-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPyShiftsPlugin.py
2515 lines (2283 loc) · 111 KB
/
PyShiftsPlugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright Notice
# ================
#
# The PyMOL Plugin source code in this file is copyrighted, but you can
# freely use and copy it as long as you don't change or remove any of
# the copyright notices.
#
# ----------------------------------------------------------------------
# This PyMOL Plugin is Copyright (C) 2016 by
# Aaron T. Frank <afrankz at umich dot edu>
#
# All Rights Reserved
#
# Permission to use, copy, modify, distribute, and distribute modified
# versions of this software and its documentation for any purpose and
# without fee is hereby granted, provided that the above copyright
# notice appear in all copies and that both the copyright notice and
# this permission notice appear in supporting documentation, and that
# the name(s) of the author(s) not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# THE AUTHOR(S) DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
# INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
# NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY SPECIAL, INDIRECT OR
# CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
# USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
# OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
# PERFORMANCE OF THIS SOFTWARE.
#----------------------------------------------------------------------
# python lib
import os
import sys
import platform
import pandas as pd
if sys.version_info >= (2,4):
import subprocess # subprocess is introduced in python 2.4
import math
import random
import numpy as np
import tempfile
from scipy import stats
from math import log
from Meter import Meter
from math import sqrt
import tkinter
from tkinter import *
#import tkSimpleDialog
#import tkMessageBox
#import tkFileDialog
#import tkColorChooser
import tkinter.simpledialog as tkSimpleDialog
import tkinter.filedialog as tkFileDialog
import tkinter.messagebox as tkMessageBox
import tkinter.colorchooser as tkColorChooser
from tkinter.filedialog import asksaveasfilename
# pymol lib
try:
from pymol import cmd
from pymol.cgo import *
from pymol import stored
from pymol import cmd
except ImportError:
print('ERROR: pymol library cmd not found.')
sys.exit(1)
# external libraries
try:
import Pmw
except ImportError:
print('ERROR: failed to import Pmw. Exit ...')
sys.exit(1)
try:
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import KMeans
SKLEARN = True
except:
SKLEARN = False
print("Warning: Couldn't find sklearn")
# try loading optionally libraries
try:
import psico.fullinit
PSICO = True
except:
PSICO = False
print("Warning: Couldn't find psico")
try:
import bme_reweight as bme
BME = True
except:
BME = False
print("Warning: Couldn't find BME")
VERBOSE = False
#################
## here we go
#################
def __init__(self):
""" PyShifts plugin for PyMol """
self.menuBar.addmenuitem('Plugin', 'command','PyShifts', label = 'PyShifts', command = lambda s=self : PyShiftsPlugin(s))
#################
## GUI related
#################
class PyShiftsPlugin:
def __init__(self, app):
""" Set up user interface and initialize parameters """
# parameters used by LARMORD
self.parent = app.root
self.pymol_sel = tkinter.StringVar(self.parent)
self.larmord_bin = tkinter.StringVar(self.parent)
self.larmorca_bin = tkinter.StringVar(self.parent)
self.larmord_para = tkinter.StringVar(self.parent)
self.larmord_ref = tkinter.StringVar(self.parent)
self.larmord_acc = tkinter.StringVar(self.parent)
self.cs = tkinter.StringVar(self.parent)
self.cs2 = tkinter.StringVar(self.parent)
self.larmord_rlt_dict = {}
self.larmord_error_all = {}
self.larmord_error_carbon = {}
self.larmord_error_proton = {}
self.larmord_error_nitrogen = {}
self.larmord_error_color = tkinter.StringVar(self.parent)
self.larmord_error_scale = tkinter.DoubleVar(self.parent)
self.larmord_error_height = tkinter.DoubleVar(self.parent)
self.larmord_error_lsize = tkinter.IntVar(self.parent)
self.larmord_ndisplayed = tkinter.IntVar(self.parent)
self.min_size = tkinter.IntVar(self.parent)
self.larmord_ndisplayed = tkinter.IntVar(self.parent)
self.mae = {}
self.measuredCS = {}
self.predictedCS = []
self.total_error = {}
self.proton_error = {}
self.nitrogen_error = {}
self.carbon_error = {}
self.larmord_erros = {}
self.best_model_indices = []
self.worst_model_indices = []
self.larmord_proton_offset = tkinter.DoubleVar(self.parent)
self.larmord_carbon_offset = tkinter.DoubleVar(self.parent)
self.larmord_nitrogen_offset = tkinter.DoubleVar(self.parent)
self.larmord_outlier_threshold = tkinter.DoubleVar(self.parent)
self.get_shifts_from_larmord = True
self.get_shifts_from_larmorca = False
self.get_shifts_from_file = False
self.weighted_errors = False
self.larmord_error_sel = 'all'
self.BME = BME
self.PSICO = PSICO
self.SKLEARN = SKLEARN
# Initialize some variables
# Define different types of nucleus of interest
self.proton_list = ["H1","H3","H1'", "H2'", "H3'", "H4'", "H5'", "H5''", "H2", "H5", "H6", "H8", "H" "HN", "HA"]
self.carbon_list = ["C1'", "C2'", "C3'", "C4'", "C5'", "C2", "C5", "C6", "C8", "CA", "C", "CB"]
self.nitrogen_list = ["N1", "N3", "N"]
self.total_list = self.proton_list + self.carbon_list + self.nitrogen_list
self.ndisplayed = 10
if self.ndisplayed > cmd.count_states(self.pymol_sel.get()):
self.ndisplayed = cmd.count_states(self.pymol_sel.get())
self.min_size.set(2)
if self.min_size.get() > cmd.count_states(self.pymol_sel.get()):
self.min_size.set(cmd.count_states(self.pymol_sel.get()))
self.sel_obj_list = []
# there may be more than one seletion or object defined by self.pymol_sel
# treat each selection and object separately
# System environment check
if 'LARMORD_BIN' not in os.environ and 'PYMOL_GIT_MOD' in os.environ:
if sys.platform.startswith('linux') and platform.machine() == 'x86_32':
initialdir_stride = os.path.join(os.environ['PYMOL_GIT_MOD'],"Larmord","i86Linux2","larmord")
os.environ['LARMORD_BIN'] = initialdir_stride
elif sys.platform.startswith('linux') and platform.machine() == 'x86_64':
initialdir_stride = os.path.join(os.environ['PYMOL_GIT_MOD'],"Larmord","ia64Linux2","larmord")
os.environ['LARMORD_BIN'] = initialdir_stride
else:
pass
# Set default file path
if 'LARMORD_BIN' in os.environ:
if VERBOSE: print('Found LARMORD_BIN in environmental variables', os.environ['LARMORD_BIN'])
self.larmord_bin.set(os.environ['LARMORD_BIN'])
#self.cs.set("/Users/afrankz/Documents/GitHub/PyShifts/test/protein_cs.dat")#for test use only
#self.cs2.set("/Users/afrankz/Documents/GitHub/RNATransientStates/FluorideRibo/data/shifts.txt") #for test use only
#self.pymol_sel.set("my_protein")#for test use only
self.larmord_para.set(os.environ['LARMORD_BIN']+"/../data/larmorD_alphas_betas_rna.dat")
self.larmord_ref.set(os.environ['LARMORD_BIN']+"/../data/larmorD_reference_shifts_rna.dat")
else:
if VERBOSE: print('LARMORD_BIN not found in environmental variables.')
self.larmord_bin.set('')
if 'PYSHIFTS_PATH' in os.environ:
self.larmord_acc.set(os.environ['PYSHIFTS_PATH']+"/test/testAccuracy.dat")
else:
print("ERROR: Pyshifts Not Set Up! Please run $. setup.sh first.")
sys.exit(1)
if 'LARMORCA_BIN' not in os.environ and 'PYMOL_GIT_MOD' in os.environ:
if sys.platform.startswith('linux') and platform.machine() == 'x86_32':
initialdir_stride = os.path.join(os.environ['PYMOL_GIT_MOD'],"Larmorca","i86Linux2","larmorca")
os.environ['LARMORCA_BIN'] = initialdir_stride
elif sys.platform.startswith('linux') and platform.machine() == 'x86_64':
initialdir_stride = os.path.join(os.environ['PYMOL_GIT_MOD'],"Larmorca","ia64Linux2","larmorca")
os.environ['LARMORCA_BIN'] = initialdir_stride
else:
pass
# Set default file path
if 'LARMORCA_BIN' in os.environ:
if VERBOSE: print('Found LARMORCA_BIN in environmental variables', os.environ['LARMORCA_BIN'])
self.larmorca_bin.set(os.environ['LARMORCA_BIN'])
else:
if VERBOSE: print('LARMORCA_BIN not found in environmental variables.')
self.larmorca_bin.set('')
# tooltips
self.balloon = Pmw.Balloon(self.parent)
self.dialog = Pmw.Dialog(self.parent,
buttons = ('Exit',),
title = 'PyShifts Plugin for PyMOL',
command = self.execute)
self.dialog.component('buttonbox').button(0).pack(fill='both',expand = 1, padx=10)
Pmw.setbusycursorattributes(self.dialog.component('hull'))
w = tkinter.Label(self.dialog.interior(),text = 'PyShifts Plugin for PyMOL\nby Jingru Xie, Kexin Zhang, and Aaron T. Frank, 2016\n',background = 'black', foreground = 'yellow')
w.pack(expand = 1, fill = 'both', padx = 8, pady = 5)
# add progress meter
self.m = Meter(self.dialog.interior(), relief='ridge', bd=5)
self.m.pack(expand = 1, padx = 10, pady = 5, fill='x')
# make a few tabs within the dialog
self.notebook = Pmw.NoteBook(self.dialog.interior())
pady=10
self.notebook.pack(fill = 'both', expand=1, padx=10, pady=pady)
######################
## Tab : Options Tab
######################
page = self.notebook.add('Compute or Load Shifts')
self.notebook.tab('Compute or Load Shifts').focus_set()
group_struc = tkinter.LabelFrame(page, text = 'Setup')
group_struc.pack(fill='both', expand=True, padx=25, pady=25)
self.analyzeButton = Pmw.ButtonBox(page,
orient = 'horizontal',
labelpos = 'w',
frame_borderwidth = 2,
frame_relief = 'groove',
)
self.analyzeButton.add('Run', command = self.runAnalysis)
#self.analyzeButton.pack(fill='both', expand=True, padx=25, pady=25)
self.analyzeButton.button(0).grid(sticky=N, row=0)
group_struc.grid(row = 0, column = 0)
self.analyzeButton.grid(sticky=N, row=1)
self.pymol_sel_ent = Pmw.EntryField(group_struc,
label_text='PyMOL selection/object:',
labelpos='wn',
entry_textvariable=self.pymol_sel
)
self.balloon.bind(self.pymol_sel_ent, 'Enter the Pymol object for the structure(s) that should be used in this analysis')
# Larmord_cs2 entry serves as the path to predicted chemical shifts file when in 'Analyze shifts' mode
# Disabled when in 'Compute and Analyze shifts' mode
self.cs2_ent = Pmw.EntryField(group_struc,
label_text='Predicted Chemical Shift File:', labelpos='wn',
entry_textvariable=self.cs2,
entry_width=10)
self.balloon.bind(self.cs2_ent, "Path to predicted chemical shifts data (only applicable in 'Other' mode) \n[Format:model_index, residue_number, residue_name, nucleus_name, CS_value_1, CS_values_2] \nmodel_index - should match the state in the Pymol object to ensure accurate mapping of difference is subsequent analysis \nresidue_number - same as above \nresidue_name - same as above \nnucleus_name - same as above \nCS_values_1 - comparison chemical shifts that, for a given nucleus, may change with model_index \nCS_values_2 - can be any value since it is ignored in this part ")
self.cs2_but = tkinter.Button(group_struc, text = 'Browse...', command = self.getLarmordCS2)
self.cs2_but.configure(state = "disabled")
self.cs2_ent.component('entry').configure(state='disabled')
# Mode selection: Larmord/ larmorca/ External
self.mode_radio = Pmw.RadioSelect(group_struc,
buttontype = 'radiobutton',
orient = 'horizontal',
labelpos = 'we',
command = self.modeCallBack,
label_text = 'Mode',
hull_borderwidth = 2,
hull_relief = 'ridge',
)
self.balloon.bind(self.mode_radio, 'LARMORD mode: chemical shifts will be computed using LARMORD.\nLARMORCA mode: chemical shifts will be computed using larmorca.\nOther mode: chemical shifts to be compared will be read from the user supplied chemical shift file.')
# Add some buttons to the radiobuttons RadioSelect.
for text in ('LARMORD', 'LARMORCA', 'Other'):
self.mode_radio.add(text)
self.mode_radio.setvalue('LARMORD')
# Arrange widgets using grid
pady = 10
padx = 5
self.pymol_sel_ent.grid(sticky='we', row=0, column=0, columnspan=5, pady=pady, padx=padx)
self.mode_radio.grid(sticky='we', row=1, column=2, columnspan=3, pady=pady, padx=padx)
self.cs2_ent.grid(sticky='we', row=2, column=0, columnspan=4, pady=pady, padx=padx)
self.cs2_but.grid(sticky='we', row=2, column=4, pady=pady, padx=padx)
page.columnconfigure(0, weight=1)
page.rowconfigure(0, weight = 1)
page.rowconfigure(1, weight = 0)
######################
## Tab : Table Tab
######################
page = self.notebook.add('Error Analysis')
"""
Create an error Table
"""
group_table = tkinter.LabelFrame(page)
group_table.grid(sticky=W+E, row=0)
self.tableButton = Pmw.ButtonBox(page,
orient = 'horizontal',
labelpos = 'w',
)
self.tableButton.add('Compare Chemcial Shifts', command = self.runCompare)
self.tableButton.add('Sort', command = self.runSort)
self.tableButton.grid(sticky='we', row=1, columnspan=2)
# disable all other buttons in the current tab before computing predicted chemical shifts
self.tableButton.button(1).config(state = 'disabled')
self.tableButton.button(0).config(state = 'disabled')
self.topheader = tkinter.Label(group_table, text = '')
fixedFont = Pmw.logicalfont('Fixed')
# Begin Error Table definition
self.error_table = Listbox(group_table,
font = fixedFont,
selectmode = BROWSE,
width = 60,
height = 10,
bd = 6,
relief='ridge',
)
self.error_table.pack(fill = BOTH, expand = 1)
self.error_table.bind("<Double-Button-1>", self.sele_from_table)
# Create the table header
self.error_table.insert(1, 'Error Table'.center(50))
self.table_header = 'state MAE R RMSE BME clusters'
self.table_header = str.split(self.table_header)
# Create row headers
headerLine = ' '
for column in range(len(self.table_header)):
headerLine = headerLine + ('%-8s ' % (self.table_header[column],))
self.error_table.insert('end', headerLine)
"""
Create a chemical shift table with a scroll bar
"""
group_CStable=Frame(group_table)
cs_scrollbar = Scrollbar(group_CStable,
orient=VERTICAL,
bd = 1,
width = 16,
)
self.CS_table = Listbox(group_CStable,
font = fixedFont,
selectmode = BROWSE,
width = 60,
height = 10,
bd = 6,
relief='ridge',
)
#cs_scrollbar.config(command=self.CS_table.yview)
#cs_scrollbar.pack(side=RIGHT, fill=Y, )
self.CS_table.pack(side=LEFT, fill = BOTH, expand = 1)
self.CS_table.bind("<Double-Button-1>", self.seleRes)
# Create the table header
self.CS_table.insert(1, 'Chemical Shift Table'.center(55))
self.CStable_header = 'resname resid nuclei expCS predCS weighted_error'
self.CStable_header = str.split(self.CStable_header)
# Create row headers
headerLine = ' '
for column in range(len(self.CStable_header)):
headerLine = headerLine + ('%-6s ' % (self.CStable_header[column],))
self.CS_table.insert('end', headerLine)
# Chemical shift table sort - button box
self.sort_CStable = Pmw.ButtonBox(group_table,
labelpos = 'w',
label_text = 'Sort CS table by:',
frame_borderwidth = 2,
frame_relief = 'groove',
)
self.balloon.bind(self.sort_CStable, 'Sort by residue id or scaled absolute error (in ascending order)')
self.sort_CStable.add('resid', command = self.showCStable)
self.sort_CStable.add('error', command = self.sort_CStable_error)
# initialize buttons as disabled
for button in range(self.sort_CStable.numbuttons()):
self.sort_CStable.button(button).config(state = 'disabled')
# Chemical shift table - save button
self.save_CStable = Pmw.ButtonBox(group_table,
# orient = 'vertical',
labelpos = 'w',
label_text = 'Save to file:',
frame_borderwidth = 2,
frame_relief = 'groove',
)
self.balloon.bind(self.save_CStable, 'Save predicted chemical shift file')
self.save_CStable.add('Error table', command = self.saveErrortable)
self.save_CStable.add('CS table', command = self.saveCStable)
self.save_CStable.add('Save single state', command = self.saveCStableOnestate)
# button to save session
self.save_CStable.add('Save session', command = self.saveSession)
# initialize buttons as disabled
for button in range(self.save_CStable.numbuttons()):
self.save_CStable.button(button).config(state = 'disabled')
# Reference chemical shift file
self.cs_ent = Pmw.EntryField(group_table,
label_text='Chemical Shift File:', labelpos='wn',
entry_textvariable=self.cs,
entry_width=10)
self.balloon.bind(self.cs_ent, 'This file should contain the reference chemical shifts that will be \ncompared to the chemical shifts computed from the structure(s) using LARMORD or larmorca or reference chemical shifts supplied by the user. \n[Format:residue_name, residue_number, nucleus_name, CS_value_1, CS_values_2] \nresidue_number - residue number for a given chemical shift (should match the number in the load structure file) \nresidue_name - residue name for a given chemical shift (should match the name in the load structure file) \nnucleus_name - nucleus name for a given chemical shift (should match the name in the load structure file) \nCS_values_1 - reference (measured) chemical shifts \nCS_values_2 - can be any value since it is ignored in this part')
self.cs_but = tkinter.Button(group_table, text = 'Browse...', command = self.getLarmordCS)
"""
Radio button for nuclei selection --
sort error table based on different nuclei types: 'carbon', 'proton', 'nitrogen' or 'all'
"""
self.sortby_nucleus = Pmw.RadioSelect(group_table,
buttontype = 'radiobutton',
orient = 'horizontal',
labelpos = 'w',
command = self.sortByNucleusCallBack,
label_text = 'Comparison Nuclei:',
hull_borderwidth = 2,
hull_relief = 'ridge',
)
self.balloon.bind(self.sortby_nucleus, 'Sort using either proton, carbon, nitrogen or all chemical shifts')
for text in ['proton', 'carbon', 'nitrogen', 'all']:
self.sortby_nucleus.add(text)
self.sortby_nucleus.setvalue('all')
self.larmord_error_sel = 'all'
"""
Radio button for metric selection --
sort based on different attributes of selected nuclei error, e.g. MAE of carbon, Pearson correlation coefficients of proton, etc.
"""
self.sortby_metric = Pmw.RadioSelect(group_table,
buttontype = 'radiobutton',
orient = 'horizontal',
labelpos = 'w',
command = self.sortByMetricCallBack,
label_text = 'Sorting Metric:',
hull_borderwidth = 2,
hull_relief = 'ridge',
)
self.balloon.bind(self.sortby_metric, 'Error metric to use when sorting states (state = reset)')
for text in ['MAE', 'pearson', 'RMSE', 'state', 'weight', 'clusters']:
self.sortby_metric.add(text)
self.sortby_metric.setvalue('MAE')
self.larmord_error_metric = 'MAE'
# Arrange widgets using grid
padx=1
pady=1
#self.topheader.grid(row=0)
#self.error_table.grid(sticky=W, row=1, column=0, rowspan = 15, columnspan = 30, padx=padx, pady=pady)
#group_CStable.grid(sticky=W, row=1, column=40, rowspan = 15, columnspan = 50, padx=padx, pady=pady)
#self.save_CStable.grid(sticky=W, row=16, column=0, rowspan = 1, columnspan = 60, padx=padx, pady=pady)
#self.sort_CStable.grid(sticky=W, row=16, column=60, rowspan = 1, columnspan = 30, padx=padx, pady=pady)
#self.cs_ent.grid(sticky='we', row=17, column=0, columnspan=4, pady=pady, padx=padx)
#self.cs_but.grid(sticky='we', row=17, column=4, pady=pady, padx=padx)
#self.sortby_nucleus.grid(sticky='we', row=18, column=0, columnspan = 50, pady=pady)
#self.sortby_metric.grid(sticky='we', row=18, column=50, columnspan = 30, pady=pady)
self.error_table.grid(sticky=W, row=1, column=0, rowspan = 5, columnspan = 30, padx=padx, pady=pady)
group_CStable.grid(sticky=W, row=6, column=0, rowspan = 5, columnspan = 50, padx=padx, pady=pady)
self.save_CStable.grid(sticky=W, row=11, column=0, rowspan = 1, columnspan = 60, padx=padx, pady=pady)
self.sort_CStable.grid(sticky=W, row=12, column=0, rowspan = 1, columnspan = 30, padx=padx, pady=pady)
self.cs_ent.grid(sticky='we', row=13, column=0, columnspan=4, pady=pady, padx=padx)
self.cs_but.grid(sticky='we', row=13, column=4, pady=pady, padx=padx)
self.sortby_nucleus.grid(sticky='we', row=14, column=0, columnspan = 50, pady=pady)
self.sortby_metric.grid(sticky='we', row=15, column=0, columnspan = 30, pady=pady)
group_table.columnconfigure(0, weight=1)
group_table.columnconfigure(50, weight=1)
group_table.columnconfigure(90, weight=1)
page.columnconfigure(0, weight=1)
###########################
## Tab : Advanced Options Tab
###########################
page = self.notebook.add('Advanced Options')
"""
Larmord file path
"""
Larmord_file = False
if Larmord_file:
group_larmord = tkinter.LabelFrame(page, text = 'LARMORD')
group_larmord.pack(fill='both', expand=True, padx=5, pady=5)
enwidth=20
self.larmord_bin_ent = Pmw.EntryField(group_larmord,
label_text='LARMORD binary:', labelpos='wn',
entry_textvariable=self.larmord_bin,
entry_width=enwidth)
self.balloon.bind(self.larmord_bin_ent, 'Path to LARMORD binary (only needed if Compute and Analyze mode )')
self.larmord_bin_but = tkinter.Button(group_larmord, text = 'Browse...', command = self.getLarmordBin)
self.larmord_para_ent = Pmw.EntryField(group_larmord,
label_text='LARMORD Parameter:', labelpos='wn',
entry_textvariable=self.larmord_para,
entry_width=enwidth)
self.balloon.bind(self.larmord_para_ent, 'Path to LARMORD parameter file (only needed if Compute and Analyze mode )')
self.larmord_para_but = tkinter.Button(group_larmord, text = 'Browse...', command = self.getLarmordPara)
self.larmord_ref_ent = Pmw.EntryField(group_larmord,
label_text='LARMORD Reference Shifts:', labelpos='wn',
entry_textvariable=self.larmord_ref,
entry_width=enwidth)
self.balloon.bind(self.larmord_ref_ent, 'Path to LARMORD reference chemical shifts file (only needed if Compute and Analyze mode )')
self.larmord_ref_but = tkinter.Button(group_larmord, text = 'Browse...', command = self.getLarmordRef)
# arrange widgets using grid
pady=5
self.larmord_bin_ent.grid(sticky='we', row=0, column=0, columnspan=3, pady=pady)
self.larmord_bin_but.grid(sticky='we', row=0, column=3, pady=pady)
self.larmord_para_ent.grid(sticky='we', row=1, column=0, columnspan=3, pady=pady)
self.larmord_para_but.grid(sticky='we', row=1, column=3, pady=pady)
self.larmord_ref_ent.grid(sticky='we', row=2, column=0, columnspan=3, pady=pady)
self.larmord_ref_but.grid(sticky='we', row=2, column=3, pady=pady)
group_advanc = tkinter.LabelFrame(page, text = 'Advanced Options')
group_advanc.pack(fill='both', expand=True, padx=5, pady=5)
"""
Scale options: scale or not/ offset for proton, carbon and nitrogen/ customize larmord or larmorca accuracy file
"""
group_scale = group_advanc
# Scale selection: scale/ not scale
self.wterror_radio = Pmw.RadioSelect(group_scale,
buttontype = 'radiobutton',
orient = 'horizontal',
labelpos = 'w',
command = self.scaleCallBack,
label_text = 'Scale \nDifferences',
hull_borderwidth = 2,
hull_relief = 'ridge',
)
self.balloon.bind(self.wterror_radio, 'Should chemical differences should be scaled by the expected accuracy of your predictor')
for text in ('Yes', 'No'):
self.wterror_radio.add(text)
self.wterror_radio.setvalue('Yes')
self.weighted_errors = True
# 1H and 13C and 15N offset
self.larmord_proton_offset_ent = Pmw.EntryField(group_scale, value = 0.0,
label_text='1H offset (ppm):',
labelpos='wn',
entry_textvariable=self.larmord_proton_offset,
)
self.balloon.bind(self.larmord_proton_offset_ent, 'offset to add to the reference 1H chemical shifts -- useful if reference shifts are known to be systematically mis-referenced')
self.larmord_carbon_offset_ent = Pmw.EntryField(group_scale, value = 0.0,
label_text='13C offset (ppm):',
labelpos='wn',
entry_textvariable=self.larmord_carbon_offset,
)
self.balloon.bind(self.larmord_carbon_offset_ent, 'offset to add to the reference 13C chemical shifts -- useful if reference shifts are known to be systematically mis-referenced')
self.larmord_nitrogen_offset_ent = Pmw.EntryField(group_scale, value = 0.0,
label_text='15N offset (ppm):',
labelpos='wn',
entry_textvariable=self.larmord_nitrogen_offset,
)
self.balloon.bind(self.larmord_nitrogen_offset_ent, 'offset to add to the reference 15N chemical shifts -- useful if reference shifts are known to be systematically mis-referenced')
# outlier threshold
self.larmord_outlier_threshold_ent = Pmw.EntryField(group_scale, value=9999.0,
label_text='Outlier Threshold:',
labelpos='wn',
entry_textvariable=self.larmord_outlier_threshold,
)
self.balloon.bind(self.larmord_outlier_threshold_ent,
'outlier_threshold -- predictions that exhibit errors that outlier_threshold x the expected error will be ignored was determining the overall error of a given structural model')
# Specify accuracy file
# load MAE from file if given
# MAE: estimated mean absolute error between measured and larmord predicted chemical shifts for a certain nucleus type
self.larmord_acc_ent = Pmw.EntryField(group_scale,
label_text='Accuracy File:', labelpos='wn',
entry_textvariable=self.larmord_acc,
entry_width=10)
self.balloon.bind(self.larmord_acc_ent, 'Path to customized LARMORD MAE data file\nMAE: estimated mean absolute error between measured and larmord predicted chemical shifts for a certain nucleus type')
self.larmord_acc_but = tkinter.Button(group_scale, text = 'Browse...', command = self.getLarmordAcc, width=4)
"""
Rendering options
-- specify colors, sphere size of residuals and No. of models to display in Pymol
"""
group_error = group_advanc
self.error_color_ent = Pmw.EntryField(group_error,
label_text="Colors:",
labelpos='wn', value = "blue_white_red",
entry_textvariable=self.larmord_error_color
)
self.balloon.bind(self.error_color_ent, "see 'help spectrum' for list of color spectra")
self.error_scale_ent = Pmw.EntryField(group_error,
label_text='Sphere size:',
labelpos='wn', value = 0.4,
entry_textvariable=self.larmord_error_scale
)
self.balloon.bind(self.error_scale_ent, "scale for spheres used to render the chemical shift differences")
self.error_ndisplay_ent = Pmw.EntryField(group_error,
labelpos = 'w',
label_text='No. models to display:',
value = '%s'%(self.ndisplayed),
entry_width = 3,
entry_textvariable=self.larmord_ndisplayed
)
self.balloon.bind(self.error_ndisplay_ent, "Number of models with lowest error (or highest correlation coefficiencts) to display")
self.min_size_ent = Pmw.EntryField(group_error,
labelpos = 'w',
label_text='Number of clusters:',
value = 2,
entry_width = 3,
entry_textvariable=self.min_size
)
self.balloon.bind(self.min_size_ent, "Number of clusters K-means should return")
# Arrange widgets using grid
padx = 5
pady = 5
self.wterror_radio.grid(sticky='we', row=0, column=0, pady=pady, padx=padx)
self.larmord_proton_offset_ent.grid(sticky='we', row=1, column=0, columnspan=2, pady=pady, padx=padx)
self.larmord_carbon_offset_ent.grid(sticky='we', row=2, column=0, columnspan=2, pady=pady, padx=padx)
self.larmord_nitrogen_offset_ent.grid(sticky='we', row=3, column=0, columnspan=2, pady=pady, padx=padx)
self.larmord_outlier_threshold_ent.grid(sticky='we', row=4, column=0, columnspan=2, pady=pady, padx=padx)
self.larmord_acc_ent.grid(sticky='we', row=5, column=0, columnspan=1, pady=pady, padx=padx)
self.larmord_acc_but.grid(sticky='we', row=5, column=1, columnspan=1, pady=pady, padx=padx)
self.error_color_ent.grid(sticky='we', row=6, column=0, columnspan=2, pady=pady, padx=padx)
self.error_scale_ent.grid(sticky='we', row=7, column=0, columnspan=2, pady=pady, padx=padx)
self.error_ndisplay_ent.grid(sticky='we', row=8, column=0, columnspan=2, pady=pady, padx=padx)
self.min_size_ent.grid(sticky='we', row=9, column=0, columnspan=2, pady=pady, padx=padx)
group_advanc.grid(row=0, column=0)
page.columnconfigure(0, weight=1)
page.rowconfigure(0, weight = 1)
######################
## Tab : About Tab
######################
page = self.notebook.add('About')
group_about = tkinter.LabelFrame(page, text = 'PyShifts Plugin for PyMOL')
group_about.grid(sticky='we', row=0,column=0,padx=5,pady=3)
about_plugin = """ Tool For Comparing and Visualizing Chemical Shift Differences.
Jingru Xie <jingrux .at. umich.edu>
Kexin Zhang <kexin .at. umich.edu>
Aaron T. Frank <afrankz .at. umich.edu>
Please cite this plugin if you use it in a publication.
"""
label_about = tkinter.Label(group_about,text=about_plugin)
label_about.grid(sticky='we', row=0, column=0, pady=pady)
self.notebook.setnaturalsize()
return
## Functions related to file and parameter initialization
def disableAll(self):
"""
Disable all buttons in the dialog(except for 'Exit')
Will be called when the user click on 'Predict or Load Chemical Shifts' or 'Compare shifts'
Purpose: avoid unnecassary repeted running caused by double click
"""
for button in range(self.tableButton.numbuttons()):
self.tableButton.button(button).config(state = 'disabled')
self.analyzeButton.button(0).config(state='disabled')
### A set of functions for getting Larmord parameters
def getLarmordBin(self):
larmord_bin_fname = tkFileDialog.askopenfilename(title='Larmord Binary', initialdir='',filetypes=[('all','*')], parent=self.parent)
if larmord_bin_fname: # if nonempty
self.larmord_bin.set(larmord_bin_fname)
return
def getLarmordPara(self):
larmord_para_fname = tkFileDialog.askopenfilename(title='Larmord Parameter', initialdir='', filetypes=[('all','*')], parent=self.parent)
if larmord_para_fname: # if nonempty
self.larmord_para.set(larmord_para_fname)
return
def getLarmordRef(self):
larmord_ref_fname = tkFileDialog.askopenfilename(title='Larmord Reference', initialdir='', filetypes=[('all','*')], parent=self.parent)
if larmord_ref_fname: # if nonempty
self.larmord_ref.set(larmord_ref_fname)
return
def getLarmordAcc(self):
larmord_acc_fname = tkFileDialog.askopenfilename(title='Accuracy File', initialdir='', filetypes=[('all','*')], parent=self.parent)
if larmord_acc_fname: # if nonempty
self.larmord_acc.set(larmord_acc_fname)
return
def getLarmordCS(self):
larmord_cs_fname = tkFileDialog.askopenfilename(title='Chemical Shift File', initialdir='', filetypes=[('all','*')], parent=self.parent)
if larmord_cs_fname: # if nonempty
self.cs.set(larmord_cs_fname)
return
def getLarmordCS2(self):
larmord_cs2_fname = tkFileDialog.askopenfilename(title='Predicted Chemical Shift File', initialdir='', filetypes=[('all','*')], parent=self.parent)
if larmord_cs2_fname: # if nonempty
self.cs2.set(larmord_cs2_fname)
return
def disableNuclei(self):
# Disable the selection of nuclei in 'table' tab
# Will be called when metric selection is in 'state'
self.sortby_nucleus.component('label').configure(state='disabled')
for child in range(self.sortby_nucleus.numbuttons()):
self.sortby_nucleus.button(child).configure(state='disabled')
return True
def enableNuclei(self):
# Enable the selection of nuclei in 'table' tab
# Will be called when metric selection is not in 'state'
self.sortby_nucleus.component('label').configure(state='normal')
for child in range(self.sortby_nucleus.numbuttons()):
self.sortby_nucleus.button(child).configure(state='normal')
return True
def sortByMetricCallBack(self, tag):
if tag in ['pearson']:
self.enableNuclei()
self.larmord_error_metric = 'pearson'
if tag in ['kendall']:
self.enableNuclei()
self.larmord_error_metric = 'kendall'
if tag in ['spearman']:
self.enableNuclei()
self.larmord_error_metric = 'spearman'
if tag in ['MAE']:
self.enableNuclei()
self.larmord_error_metric = 'MAE'
if tag in ['RMSE']:
self.enableNuclei()
self.larmord_error_metric = 'RMSE'
if tag in ['PYM']:
self.enableNuclei()
self.larmord_error_metric = 'PYM'
if tag in ['state']:
self.larmord_error_metric = 'state'
self.disableNuclei()
if tag in ['weight']:
self.larmord_error_metric = 'weight'
self.disableNuclei()
if tag in ['clusters']:
self.larmord_error_metric = 'clusters'
self.disableNuclei()
def sortByNucleusCallBack(self, tag):
self.larmord_error_sel = 'all'
#self.tableButton.button(1).config(state = 'disabled')
if tag in ['proton']:
self.larmord_error_sel = 'proton'
if tag in ['carbon']:
self.larmord_error_sel = 'carbon'
if tag in ['nitrogen']:
self.larmord_error_sel = 'nitrogen'
def modeCallBack(self, tag):
# This is called whenever the user clicks on a button
# during the selection of modes.
Larmord_file = False
if tag in ['Other']:
self.get_shifts_from_larmord = False
self.get_shifts_from_larmorca = False
self.get_shifts_from_file = True
self.cs2_but.configure(state = "normal")
self.cs2_ent.component('entry').configure(state='normal')
self.wterror_radio.component('label').configure(state='disabled')
for child in range(self.wterror_radio.numbuttons()):
self.wterror_radio.button(child).configure(state='disabled')
elif tag in ['LARMORCA']:
self.get_shifts_from_larmord = False
self.get_shifts_from_larmorca = True
self.get_shifts_from_file = False
self.wterror_radio.component('label').configure(state='normal')
self.larmord_acc_but.configure(state = "normal")
self.larmord_acc_ent.component('entry').configure(state='normal')
self.cs2_but.configure(state = "disabled")
self.cs2_ent.component('entry').configure(state='disabled')
for child in range(self.wterror_radio.numbuttons()):
self.wterror_radio.button(child).configure(state='normal')
elif tag in ['LARMORD']:
self.get_shifts_from_larmord = True
self.get_shifts_from_larmorca = False
self.get_shifts_from_file = False
if Larmord_file:
# activate LARMORD relevant buttons and entry fields
self.larmord_bin_but.configure(state = "normal")
self.larmord_para_but.configure(state = "normal")
self.larmord_ref_but.configure(state = "normal")
self.larmord_bin_ent.component('entry').configure(state='normal')
self.larmord_para_ent.component('entry').configure(state='normal')
self.larmord_ref_ent.component('entry').configure(state='normal')
self.wterror_radio.component('label').configure(state='normal')
self.larmord_acc_but.configure(state = "normal")
self.larmord_acc_ent.component('entry').configure(state='normal')
self.cs2_but.configure(state = "disabled")
self.cs2_ent.component('entry').configure(state='disabled')
for child in range(self.wterror_radio.numbuttons()):
self.wterror_radio.button(child).configure(state='normal')
else:
self.get_shifts_from_larmord = True
self.get_shifts_from_larmorca = True
self.get_shifts_from_file = False
self.wterror_radio.component('label').configure(state='normal')
self.larmord_acc_but.configure(state = "normal")
self.larmord_acc_ent.component('entry').configure(state='normal')
self.cs2_but.configure(state = "disabled")
self.cs2_ent.component('entry').configure(state='disabled')
for child in range(self.wterror_radio.numbuttons()):
self.wterror_radio.button(child).configure(state='normal')
def scaleCallBack(self, tag):
# This is called whenever the user clicks on a button in the single selection of 'scale error' or 'not scale error' and pass the selction to
# a global var self.weighted_errors.
# If the user chooses to scale the error, self.weighted_errors = True; and vice versa.
if tag in ['Yes']:
self.weighted_errors = True
else:
self.weighted_errors = False
def reset_predictedCS(self):
# reset predicted chemical shift
self.predictedCS = []
def get_shifts_from_traj(self):
"""
Run larmord in trajectory mode
"""
def reset_MAE(self):
self.mae = {}
def load_MAE(self):
# Load larmord accuracy(expected MAE for each residuals in larmord) from file.
# If MAE file is not provided by the user, then load MAE from default list also given in this function.
self.reset_MAE()
if len(self.larmord_acc.get())>0:
if self.check_file(self.larmord_acc.get()):
mae_type = {'names': ('resname', 'nucleus','MAE'),'formats': ('S5','S5','float')}
#data = np.loadtxt(self.larmord_acc.get(), dtype=mae_type)
data = pd.read_csv(self.larmord_acc.get(), sep = '\s+', names = ['resname', 'nucleus','MAE'])
self.larmord_acc_ext = data
larmord_resname = data['resname'].values
larmord_nucleus = data['nucleus'].values
larmord_mae = data['MAE'].values
print(data)
for res in range(len(larmord_resname)):
keyMAE = str(larmord_resname[res]+":"+larmord_nucleus[res])
self.mae[keyMAE] = larmord_mae[res]
else:
#self.print_file_error(self.larmord_acc.get())
return False
# default MAE list
else:
print("loading default MAE...")
# MAE for Larmord
if (self.get_shifts_from_larmord) and not (self.get_shifts_from_larmord):
self.mae["ADE:C1'"] = 0.700
self.mae["ADE:C2"] = 0.764
self.mae["ADE:C2'"] = 0.471
self.mae["ADE:C3'"] = 1.017
self.mae["ADE:C4'"] = 0.709
self.mae["ADE:C5'"] = 0.914
self.mae["ADE:C8"] = 0.684
self.mae["ADE:H1'"] = 0.114
self.mae["ADE:H2"] = 0.205
self.mae["ADE:H2'"] = 0.107
self.mae["ADE:H3'"] = 0.113
self.mae["ADE:H4'"] = 0.074
self.mae["ADE:H5'"] = 0.314
self.mae["ADE:H5''"] = 0.132
self.mae["ADE:H8"] = 0.161
self.mae["GUA:C1'"] = 0.681
self.mae["GUA:C2'"] = 0.546
self.mae["GUA:C3'"] = 0.861
self.mae["GUA:C4'"] = 0.817
self.mae["GUA:C5'"] = 0.893
self.mae["GUA:C8"] = 0.715
self.mae["GUA:H1'"] = 0.168
self.mae["GUA:H2'"] = 0.142
self.mae["GUA:H3'"] = 0.124
self.mae["GUA:H4'"] = 0.075
self.mae["GUA:H5'"] = 0.271
self.mae["GUA:H5''"] = 0.123
self.mae["GUA:H8"] = 0.202
self.mae["URA:C1'"] = 0.681
self.mae["URA:C2'"] = 0.598
self.mae["URA:C3'"] = 0.981
self.mae["URA:C4'"] = 1.106
self.mae["URA:C5"] = 0.562
self.mae["URA:C5'"] = 0.735
self.mae["URA:C6"] = 0.705
self.mae["URA:H1'"] = 0.105
self.mae["URA:H2'"] = 0.129
self.mae["URA:H3'"] = 0.088
self.mae["URA:H4'"] = 0.071
self.mae["URA:H5"] = 0.120
self.mae["URA:H5'"] = 0.303
self.mae["URA:H5''"] = 0.121
self.mae["URA:H6"] = 0.099
self.mae["CYT:C1'"] = 0.642
self.mae["CYT:C2'"] = 0.980
self.mae["CYT:C3'"] = 1.147
self.mae["CYT:C4'"] = 0.617
self.mae["CYT:C5"] = 1.945
self.mae["CYT:C5'"] = 0.938
self.mae["CYT:C6"] = 0.584
self.mae["CYT:H1'"] = 0.111
self.mae["CYT:H2'"] = 0.101
self.mae["CYT:H3'"] = 0.113
self.mae["CYT:H4'"] = 0.094
self.mae["CYT:H5"] = 0.114
self.mae["CYT:H5'"] = 0.312
self.mae["CYT:H5''"] = 0.194
self.mae["CYT:H6"] = 0.117
self.mae["URA:N3"] = 2.609
self.mae["GUA:N1"] = 1.259
# MAE for larmorca
if not (self.get_shifts_from_larmord) and (self.get_shifts_from_larmorca):
self.mae["ALA:HA"] = 0.39
self.mae["ARG:HA"] = 0.39
self.mae["ASN:HA"] = 0.39
self.mae["ASP:HA"] = 0.39
self.mae["CYS:HA"] = 0.39
self.mae["GLN:HA"] = 0.39
self.mae["GLU:HA"] = 0.39
self.mae["GLY:HA"] = 0.39
self.mae["HIS:HA"] = 0.39
self.mae["ILE:HA"] = 0.39
self.mae["LEU:HA"] = 0.39
self.mae["LYS:HA"] = 0.39
self.mae["MET:HA"] = 0.39
self.mae["PHE:HA"] = 0.39
self.mae["PRO:HA"] = 0.39
self.mae["SER:HA"] = 0.39
self.mae["THR:HA"] = 0.39
self.mae["TRP:HA"] = 0.39
self.mae["TYR:HA"] = 0.39
self.mae["VAL:HA"] = 0.39
self.mae["ALA:HN"] = 0.25
self.mae["ARG:HN"] = 0.25
self.mae["ASN:HN"] = 0.25
self.mae["ASP:HN"] = 0.25
self.mae["CYS:HN"] = 0.25
self.mae["GLN:HN"] = 0.25
self.mae["GLU:HN"] = 0.25
self.mae["GLY:HN"] = 0.25
self.mae["HIS:HN"] = 0.25
self.mae["ILE:HN"] = 0.25
self.mae["LEU:HN"] = 0.25
self.mae["LYS:HN"] = 0.25
self.mae["MET:HN"] = 0.25
self.mae["PHE:HN"] = 0.25
self.mae["PRO:HN"] = 0.25
self.mae["SER:HN"] = 0.25
self.mae["THR:HN"] = 0.25
self.mae["TRP:HN"] = 0.25
self.mae["TYR:HN"] = 0.25
self.mae["VAL:HN"] = 0.25
self.mae["ALA:CA"] = 0.9