-
Notifications
You must be signed in to change notification settings - Fork 2
/
saspy.py
1255 lines (1094 loc) · 46 KB
/
saspy.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
# python lib
'''
SASpy - ATSAS PLUGIN FOR PYMOL
(c) 2015-2019 A.PANJKOVICH AND H.MERTENS FOR ATSAS TEAM AT EMBL-HAMBURG.
'''
import os
import sys
import re
import time
import shutil
import string
import math
try:
import Tkinter as tkinter # python 2
import tkSimpleDialog as simpledialog
import tkMessageBox as messagebox
import tkFileDialog as filedialog
except ImportError:
print('Warning: pymol compatible tkinter library (python 2) not found.')
pass
try:
from tkinter import *
import tkinter # python 3
import tkinter.simpledialog as simpledialog
import tkinter.messagebox as messagebox
import tkinter.filedialog as filedialog
print('Message: pymol compatible tkinter library (python 3) found.')
except ImportError:
print('Warning: pymol compatible tkinter library (python 3) not found.')
sys.exit(1)
import tempfile
import threading
import subprocess
import itertools
# pymol lib
try:
from pymol import cmd
from pymol.cgo import *
except ImportError:
print('Warning: pymol library cmd not found.')
sys.exit(1)
# external lib
try:
import Pmw
except ImportError:
print('Warning: failed to import Pmw. Exit ...')
sys.exit(1)
## Check the PYTHON version used by PYMOL
pymolVersion = str(sys.version)
print('PYTHON VERSION: ', pymolVersion)
pythonVersion = 0
if pymolVersion.startswith('3'):
print(
'''
===================================================================
PYMOL version based on python3, compatible saspy plugin identified!
===================================================================
'''
)
pythonVersion = 3
else:
print(
'''
===================================================================
PYMOL version based on python2, compatible saspy plugin identified!
===================================================================
'''
)
pythonVersion = 2
## Plugin initialization
#global variables
saspyVersion = "3.1.0"
currentDat = []
modelingRuns = 0
from sys import platform
def __init__(self):
""" SASpy - ATSAS Plugin for PyMOL
"""
self.menuBar.addmenuitem('Plugin', 'command',
'SASpy', label = 'SASpy',
command = lambda s=self : SASpy(s))
class TemporaryDirectory:
"""Context Manager for working in a temporary directory"""
def __init__(self, *args, **kwargs):
self.temp_dir = tempfile.mkdtemp(*args, **kwargs)
def __enter__(self):
self.orig_dir = os.getcwd()
os.chdir(self.temp_dir)
return self
def __exit__(self, exc_type, exc_value, traceback):
os.chdir(self.orig_dir)
# If there was an error, do not delete the temporary
# directory, so that the user can examine its contents
if exc_type is None:
shutil.rmtree(self.temp_dir)
def copy_in(self, src, dst=None):
"""Copy a file into the temporary directory
Arguments:
src -- Source file name (relative to the original working directory)
dst -- Destination file name (relative to the temporary directory)
If not present, same as the source file name
"""
if dst is None:
dst = src
if os.path.isabs(dst):
raise ValueError("Destination path should not be absolute")
abs_src = os.path.join(self.orig_dir, src)
abs_dst = os.path.join(self.temp_dir, dst)
shutil.copy(abs_src, abs_dst)
return abs_dst
def move_out(self, src, dst=None):
"""Move a file out of the temporary directory
Arguments:
src -- Source file name (relative to the temporary directory)
dst -- Destination file name (relative to the original directory)
If not present, same as the source file name
"""
if os.path.isabs(src):
raise ValueError("Source path should not be absolute")
if dst is None:
dst = src
abs_src = os.path.join(self.temp_dir, src)
abs_dst = os.path.join(self.orig_dir, dst)
shutil.move(abs_src, abs_dst)
return abs_dst
def move_out_numbered(self, src, prefix, suffix):
"""Move a file out of the temporary directory, without overwriting old files
Chooses a new file name based on the given prefix and suffix and a unique number
Arguments:
src -- Source file name (relative to the temporary directory)
prefix -- prefix for the destination filename
suffix -- suffix for the destination filename
"""
if os.path.isabs(src):
raise ValueError("Source path should not be absolute")
if suffix.startswith('.'):
suffix = suffix[1:]
abs_src = os.path.join(self.temp_dir, src)
abs_prefix = os.path.join(self.orig_dir, prefix)
abs_dst = "%s.%s" % (abs_prefix, suffix)
if os.path.exists(abs_dst):
for i in itertools.count(start=1):
abs_dst = "%s_%d.%s" % (abs_prefix, i, suffix)
if not os.path.exists(abs_dst):
break
shutil.move(abs_src, abs_dst)
return abs_dst
## class for GUI
class SASpy:
def __init__(self, app):
self.parent = app.root
self.dialog = Pmw.Dialog(self.parent,
buttons = ('Quit',
#'Debug',
'Refresh model list',
'3. Execute'),
title = 'SASpy - ATSAS Plugin for PyMOL',
command = self.execute)
Pmw.setbusycursorattributes(self.dialog.component('hull'))
self.atsasThreads = []
self.maxThreads = 1
self.procedure = 'empty'
self.saxsfn = tkinter.StringVar()
self.sasrefmode = tkinter.StringVar()
self.sasrefmode.set('local')
self.crysolmode = tkinter.StringVar()
self.crysolmode.set('predict')
self.prefix = tkinter.StringVar()
self.datViewer = tkinter.StringVar()
self.cwd = tkinter.StringVar()
self.cwd.set(os.getcwd())
self.datViewer.set("primus") #on linux
if "win32" == platform:
self.datViewer.set("primusqt")
if "darwin" == platform:
self.datViewer.set("primus")
# OLD default below (cannot be used if installation is elsewhere):
#self.datViewer.set("/Applications/ATSAS/primus.app")
self.warnLabel = tkinter.Label( self.dialog.interior(),
anchor='center',
fg ="red",
text = 'No models found. Please open/load structures in PyMOL to proceed.')
description = "SASpy - ATSAS Plugin for PyMOL\n"
description += "ATSAS " + saspyVersion + "\n\n"
description += "European Molecular Biology Laboratory\n"
description += "Hamburg Outstation, ATSAS Team, 2015-2017.\n"
w = tkinter.Label(self.dialog.interior(),
text = description,
background = 'white', foreground = 'blue')
w.pack(expand = 1, fill = 'both', padx = 10, pady = 5)
self.procLabel = tkinter.Label( self.dialog.interior(),
anchor='w',
text = '1. Choose procedure:')
self.procLabel.pack(fill='both', expand=True, padx=10, pady=5)
#NOTEBOOK START
self.notebook = Pmw.NoteBook(self.dialog.interior(),raisecommand=self.tabSelection)
self.notebook.pack(fill = 'both', expand=2, padx=10, pady=10)
# crysol tab
crysolTab = self.createTab("crysol",
"Prediction of theoretical intensities and optionally fit\n"+
"to experimental SAXS data. Please select at least one model\n"+
"(and a SAXS .dat file for fit mode)."
)
self.crymodebut = Pmw.RadioSelect(crysolTab,
buttontype='radiobutton',
labelpos='w',
label_text="Mode:",
command=self.setCrysolMode,
selectmode = 'single')
self.crymodebut.grid(sticky='we', row=2, column=0, padx=5, pady=2)
self.crymodebut.add('predict')
#self.crymodebut.add('simulate')
self.crymodebut.add('fit')
self.crymodebut.setvalue('predict')
saxsfn_ent = Pmw.EntryField(crysolTab,
label_text = 'SAXS .dat file:',
labelpos='ws',
entry_textvariable=self.saxsfn)
saxsfn_but = tkinter.Button(crysolTab, text = 'Browse...',
command = self.getSAXSFile)
saxsfn_ent.grid(sticky='we', row=3, column=0, padx=5, pady=2)
saxsfn_but.grid(sticky='we', row=3, column=1, padx=5, pady=2)
#### TRYING to add explicit hydrogen flag ####
self.crycalcbut = Pmw.RadioSelect(crysolTab,
buttontype='radiobutton',
labelpos='w',
label_text="Explicit Hydrogens?",
selectmode = 'single')
self.crycalcbut.grid(sticky='we', row=4, column=0, padx=5, pady=2)
self.crycalcbut.add('no')
self.crycalcbut.add('yes')
self.crycalcbut.setvalue('no')
fn = []
fn.append('crysol')
# self.notebook.setnaturalsize(pageNames=fn)
#alpraxin tab
alpraxinTab = self.createTab("alpraxin", "Position a structure at the origin such that its principal\ninertia vectors are aligned with the coordinate axis.\nPlease select one or more models.")
self.enantiobut = Pmw.RadioSelect(alpraxinTab,
buttontype='radiobutton',
labelpos='w',
label_text="Produce enantiomorph as new model:",
selectmode = 'single')
self.enantiobut.grid(sticky='we', row=2, column=0, padx=5, pady=2)
self.enantiobut.add('no')
self.enantiobut.add('yes')
self.enantiobut.setvalue('no')
#supalm tab
supalmTab = self.createTab('supalm', 'Superimposition of models and calculation of\nnormalized spatial discrepancy (NSD).\nPlease select two models.')
#sasref tab
sasreftab = self.createTab("sasref", "Quaternary structure modeling against solution scattering data.\nPlease select multiple models (rigid bodies) and a SAXS .dat file.\nRecommendation: execute alpraxin before refinement.")
saxsfn_ent = Pmw.EntryField(sasreftab,
label_text = 'SAXS .dat file:',
labelpos='ws',
entry_textvariable=self.saxsfn)
saxsfn_but = tkinter.Button(sasreftab, text = 'Browse...',
command = self.getSAXSFile)
saxsfn_ent.grid(sticky='we', row=3, column=0, padx=5, pady=5)
saxsfn_but.grid(sticky='we', row=3, column=1, padx=5, pady=5)
self.sasrefmodebut = Pmw.RadioSelect(sasreftab,
buttontype='radiobutton',
labelpos='w',
label_text="Refinement mode:",
command=self.setSasrefMode,
selectmode = 'single')
self.sasrefmodebut.grid(sticky='we', row=2, column=0, padx=5, pady=2)
self.sasrefmodebut.add('local')
self.sasrefmodebut.add('global')
self.sasrefmodebut.setvalue('local')
# sreflex tab
sreflexTab = self.createTab("sreflex", "Model refinement based on SAXS data and normal mode analysis.\nPlease select models and a SAXS .dat file.")
saxsfn_ent = Pmw.EntryField(sreflexTab,
label_text = 'SAXS .dat file:',
labelpos='ws',
entry_textvariable=self.saxsfn)
saxsfn_but = tkinter.Button(sreflexTab, text = 'Browse...',
command = self.getSAXSFile)
saxsfn_ent.grid(sticky='we', row=3, column=0, padx=5, pady=5)
saxsfn_but.grid(sticky='we', row=3, column=1, padx=5, pady=5)
#dam display tab
self.damColor = tkinter.StringVar();
self.damColor.set('white');
self.damTrans = tkinter.StringVar();
self.damTrans.set('0.5');
damdisplayTab = self.createTab("damdisplay", "Apply a predefined representation to a dummy-atom-model (DAM).\nPlease select one model.")
damDisplayColorEntry = Pmw.EntryField(damdisplayTab,
label_text = 'Color:',
labelpos='ws',
entry_textvariable=self.damColor)
damDisplayColorEntry.grid(sticky='we', row=3, column=1, padx=5, pady=5)
damDisplayTransEntry = Pmw.EntryField(damdisplayTab,
label_text = 'Transparency:',
labelpos='ws',
entry_textvariable=self.damTrans)
damDisplayTransEntry.grid(sticky='we', row=4, column=1, padx=5, pady=5)
# config tab
configTab = self.createTab("configure", "Settings available to configure SASpy:")
# saxs viewer selection
svi_ent = Pmw.EntryField(configTab,
label_text = 'SAXS viewer:',
labelpos='ws',
entry_textvariable = self.datViewer)
svi_but = tkinter.Button(configTab, text = 'Select SAXS viewer',
command = self.getSAXSViewer)
svi_ent.grid(sticky='we', row=3, column=0, padx=5, pady=5)
svi_but.grid(sticky='we', row=3, column=1, padx=5, pady=5)
#working directory selection
wd_ent = Pmw.EntryField(configTab,
label_text = 'Current working dir:',
labelpos='ws',
entry_textvariable = self.cwd)
#wd_ent.grid(sticky='w', row=2, column=0, columnspan=3, padx=5, pady=2)
wd_ent.grid(sticky='w', row=2, column=0, padx=5, pady=2)
scd_but = tkinter.Button(configTab, text = 'Select working directory',
command = self.setWorkingDirectory)
scd_but.grid(sticky='we', row=2, column=1, padx=5, pady=2)
#Model selection
self.modsW = self.createModelSelectionWidget()
self.modsW.pack(expand=1, fill='both', padx=10, pady=5)
self.refreshModelSelectionWidget()
self.notebook.setnaturalsize()
self.ATSAS_sanityCheck()
#GUI FUNCTIONS
def errorWindow(self, title, msg):
messagebox.showerror(title,
"ERROR\n" + msg,
parent=self.parent)
return
def notificationWindow(self, title, msg):
messagebox.showinfo(title, msg,
parent=self.parent)
return
def ATSAS_sanityCheck(self):
msg = checkAtsasVersion()
if "NOBIN" == msg:
msg = "ATSAS binaries not found, please install ATSAS and/or "
msg += "update the binary PATH in your ~/pymolrc.pml file.\n"
msg += "SASpy will quit now."
message(msg)
self.errorWindow("ERROR", msg)
self.execute("Quit")
return
if "OK" != msg:
message(msg)
self.errorWindow("ERROR", msg)
return
def createModelSelectionWidget(self):
modsW = Pmw.RadioSelect(self.dialog.interior(),
buttontype='button',
labelpos='w',
label_text="2. Model selection:",
selectmode = 'multiple')
mols = self.getListOfModels()
for m in mols:
modsW.add(m)
return modsW
def countSelectedModels(self):
counter = 0
ma = self.modsW.getcurselection()
for m in ma:
counter += 1
return counter
def setCrysolMode(self, mode):
print("Setting crysol mode to "+mode)
self.crysolmode.set(mode)
self.crymodebut.setvalue(mode)
# self.crycalc.set(mode)
# self.crycalcbut.setvalue(mode)
def setSasrefMode(self, mode):
print("Setting sasref mode to "+mode)
self.sasrefmode.set(mode)
self.sasrefmodebut.setvalue(mode)
def setDatMode(self, mode):
print("Setting open mode to " + mode)
global datmode
datmode.set(mode)
self.datmodebut.setvalue(mode)
def submitJobAsThread(self, procType, models= []):
viewer = self.datViewer.get()
#check how many threads from this plugin are running
running = self.checkAtsasThreads()
if running == self.maxThreads:
self.errorWindow("Max threads exceeded",
"A process is already running, please wait for it to complete.")
return
#check if saxs file is available
saxsfn = self.saxsfn.get()
if False == os.path.isfile(saxsfn):
self.errorWindow("FILE NOT FOUND",
"SAXS file \'"+saxsfn+"\' NOT FOUND.");
return
if 'sasref' == procType:
t = threading.Thread(target = sasref, name = procType+'_thread', args = (saxsfn, models, self.sasrefmode.get(), viewer))
elif 'sreflex' == procType:
t = threading.Thread(target = sreflex, name = procType+'_thread', args = (saxsfn, models, viewer))
t.setDaemon(1)
t.start()
self.atsasThreads.append(t)
return
def checkAtsasThreads(self):
threadsAlive = 0
for t in self.atsasThreads:
a = t.is_alive()
name = t.name
if True == a:
threadsAlive += 1
else:
idx = self.atsasThreads.index(t)
t.join()
del self.atsasThreads[idx]
print("Just removed "+name+" from the list, with index "+repr(idx))
return threadsAlive
def submitSaspyJob(self, procType, models = []):
if "alpraxin" == procType:
alpraxin(models, self.enantiobut.getvalue())
return
if "crysol" == procType:
self.crysol(models, self.crycalcbut.getvalue())
# self.crysol(models)
return
if "damdisplay" == procType:
damdisplay(models[0], self.damColor.get(), self.damTrans.get())
return
if "supalm" == procType:
supalm(models[0], models[1])
return
#remaining job types (sreflex, sasref)
#should be submitted as a thread
self.submitJobAsThread(procType, models)
return
def prepareJobAndSubmit(self):
procType = self.procedure
seln = self.countSelectedModels()
if 'configure' == procType:
return
if 0 == seln:
self.errorWindow("No model selected", "Please select models")
return
#some procedures need an exact number of models selected
expect_dict = { #expected number of models
'damdisplay':1,
'supalm':2,
#other procedures need a minimum number of selected models
'alpraxin':11,
'sreflex':11, #subtract ten to obtain min expected
'crysol':11,
'sasref':12,
}
expn = expect_dict[procType]
if 10 > expn: #procedure needs an exact number of selected models
if expn != seln:
self.errorWindow("Wrong number of models selected",
"You selected "+ getPlural(seln) + ", but \'" + procType+ "\' expects "+getPlural(expn)+".\n")
return
else: #the procedure needs a minimum number of selected models
expn = expn - 10
if seln < expn:
self.errorWindow("Wrong number of models selected",
"You selected "+ getPlural(seln) + ", but \'" + procType +
"\' expects at least " + getPlural(expn) +".\n")
return
self.submitSaspyJob(procType, self.modsW.getcurselection())
return
def getListOfModels(self):
#models can not contain the underscore character '_'
#this is a Pmw limitation, but PyMOL does add such
#characters often
#dots are also removed, as they confuse crysol
initialList = cmd.get_object_list()
outputList = list();
for m in initialList:
if '_' in m:
# Python 2 and 3 string table handling:
if pythonVersion == 3:
try:
newName = m.translate(m.maketrans('', '',"_"))
pass
except ValueError:
pass
else:
try:
newName = m.translate(None,"_")
pass
except ValueError:
pass
cmd.set_name(m,newName)
message("WARNING Renaming model \'"+m+ "\' to \'"+ newName+"\'")
m = newName
if '.' in m:
# Python 2 and 3 string table handling:
if pythonVersion == 3:
try:
newName = m.translate(m.maketrans('', '',"."))
pass
except ValueError:
pass
else:
try:
newName = m.translate(None,"_")
except:
pass
cmd.set_name(m,newName)
message("WARNING Renaming model \'"+m+ "\' to \'"+ newName+"\'")
m = newName
outputList.append(m)
return outputList
def refreshModelSelectionWidget(self):
self.modsW.deleteall()
mols = self.getListOfModels()
for m in mols:
if '_' in m:
newName = m
newName.replace('_', '-')
cmd.set_name(m,newName)
m = newName
message("Renaming a model...")
self.modsW.add(m)
if 1 > len(self.getListOfModels()):
self.warnLabel.pack(fill='both', expand=True, padx=10, pady=5)
else:
self.warnLabel.pack_forget()
return
def createTab(self, name = 'empty', description = 'empty'):
page = self.notebook.add(name)
tab_struc = tkinter.LabelFrame(page, text = name)
tab_struc.pack(fill='both', expand=True, padx=10, pady=10)
desc = tkinter.Label(tab_struc, justify="left", text = description, pady=2)
desc.grid(sticky='w', row=0, column=0, columnspan=4, padx=10, pady=10)
return tab_struc
def openCurrentDatFile(self):
global currentDat
# message("About to open current dat file: " + repr(currentDat))
if 0 == len(currentDat):
messagebox.showerror('No curve yet',
'No SAXS intensities have been calculated yet',
parent=self.parent)
else:
openDatFile(self.datViewer.get(), currentDat)
return
def getSAXSViewer(self):
file_name = filedialog.askopenfilename(
title='SAXS viewer', initialdir='',
parent=self.parent)
self.datViewer.set(file_name)
return
def setWorkingDirectory(self):
newWorkDir = filedialog.askdirectory(
title='Set working directory', initialdir='',
parent=self.parent)
cmd.cd(newWorkDir)
self.cwd.set(newWorkDir)
message("Working directory changed to: " + newWorkDir);
return
def getSAXSFile(self):
if 'crysol' == self.procedure:
self.setCrysolMode('fit')
opts = {}
opts['filetypes'] = [('SAXS .dat files','.dat'),('all files','.*')]
file_name = filedialog.askopenfilename(**opts)
self.saxsfn.set(file_name)
return
def tabSelection(self, pagename):
#refresh each time a tab is selected
self.cwd.set(os.getcwd()) #I don't know how to refresh this if the
#user just calls 'cd'
self.procedure = pagename
return
def crysol(self, selection, param=""):
#wrapper for the different crysol modes
df = 'empty'
if 1 < len(selection):
message("CRYSOL will be executed for a complex")
message("made of the following models: "+repr(selection))
crymode = self.crysolmode.get()
crycalc = self.crycalcbut.getvalue()
if 'simulate' == crymode:
df = simulateScattering(selection)
if 'predict' == crymode:
df = predcrysol(crycalc,selection)
elif 'fit' == crymode:
saxsfn = self.saxsfn.get()
if False == os.path.isfile(saxsfn):
self.errorWindow("FILE NOT FOUND",
"SAXS file \'"+saxsfn+"\' NOT FOUND.");
return
df = fitcrysol(crycalc, saxsfn, selection)
if 'empty' != df:
openSingleDatFile(self.datViewer.get(), df)
updateCurrentDat(df)
return
def execute(self, cmd):
""" Run the cmd represented by the button clicked by user.
"""
if cmd == 'OK':
print('is everything OK?')
elif cmd == 'Refresh model list':
self.refreshModelSelectionWidget()
# elif cmd == 'Debug':
elif cmd == '3. Execute':
self.prepareJobAndSubmit()
elif cmd == 'Quit':
self.checkAtsasThreads()
for p in self.atsasThreads:
print("WARNING, a thread is still running: " + repr(p.name))
message('Quit')
if __name__ == '__main__':
self.parent.destroy()
else:
self.dialog.withdraw()
else:
print('Terminating SASpy Plugin...')
self.dialog.withdraw()
print('Done.')
##################
# CLI Funtions
defprefix = 'saspy_wd'
def systemCommand(command, **kwargs):
status = subprocess.call(command, **kwargs)
if(0 != status):
message("WARNING, something went wrong while executing:\n"
+ ' '.join(command))
return status
def message(text):
print("SASpy: "+text)
return
def getPlural(n):
#get plurals right
outstring = repr(n) +" model";
if 1 != n:
outstring+='s'
return outstring
def destFile(folder, basename, suffix):
#check if the destination filename already exists
full = os.path.join(folder, basename + suffix)
if(False == os.path.exists(full)):
return full
else: # generate a new filename, and check if it is available
counter = 1;
nf = os.path.join(folder, basename + "_" + repr(counter) + suffix)
while(True == os.path.exists(nf)):
counter += 1
nf = os.path.join(folder, basename + "_" + repr(counter) + suffix)
return nf
def writePdb(sel, prefix = ""):
pdbfn = prefix + sel + ".pdb"
npdbfn = pdbfn.replace(" or ", "");
npdbfn = npdbfn.replace(" and ", "");
# Python 2 and 3 string table handling:
if pythonVersion == 3:
try:
npdbfn = npdbfn.translate(npdbfn.maketrans('', '', string.whitespace))
except ImportError:
pass
else:
try:
npdbfn = npdbfn.translate(None, string.whitespace)
except ImportError:
pass
cmd.save(npdbfn, sel)
return npdbfn
#parse crysol log file
def parseCrysolLog (logFileName):
'''Parse Crysol log file, obtain Chi2, Rg and eDens'''
#will not parse crysol_summary.txt, but the .log file
#created for each individual run
chi2 = 9999;
Rg = 9999;
eDens = 9999;
position = -1
counter = 0
with open(logFileName, 'r') as rf:
for line in rf:
counter += 1
if re.match("(.*)Fitting parameters(.*)", line):
print("line number: " + repr(counter))
position = counter + 2
if counter == position:
if line[66:73] != "*******":
chi2 = float(line[66:73])
if re.match("(.*)Rg from the slope of net intensity(.*)", line):
Rg = float(line[59:65])
if re.match("(.*)Average electron density(.*)", line):
eDens = float(line[59:66])
rf.close()
return {'chi2':chi2, 'Rg':Rg, 'eDens':eDens}
def simulateScattering(crycalc, models, prefix=defprefix, param = " "):
'''Use CRYSOL and ADDERRORS to simulate scattering'''
#write all models into a single file
selection = " or ".join(models)
Rg = -9999
eDens = -9999
df = 'unknown'
with TemporaryDirectory() as tmpdir:
pdbfn = writePdb(selection)
if ('yes' == crycalc):
message("CRYSOL calculation using explicit hydrogens")
systemCommand(["crysol", "-eh", "-ns", "800"] + param.split() + [pdbfn])
if ('no' == crycalc):
systemCommand(["crysol", "-ns", "800"] + param.split() + [pdbfn])
fid = pdbfn.replace(".pdb", "")
result = parseCrysolLog(fid+"00.log")
Rg = result['Rg']
eDens = result['eDens']
tmpint = fid + "00.int"
tmpout = fid + ".dat"
systemCommand(["adderrors", tmpint, "-o", tmpout])
df = tmpdir.move_out_numbered(tmpout, fid, '.dat')
message("CRYSOL Theoretical Rg = " + repr(Rg))
message("CRYSOL Average electron density = " + repr(eDens))
message( ".dat file written to " + df)
return df
#cmd.extend("simulateScattering", simulateScattering)
#run crysol in predictive mode for a given selection
def predcrysol(crycalc ,models, prefix=defprefix, param = " "):
#write all models into a single file
#crycalc flag for use/non-use of explicit hydrogens
selection = " or ".join(models)
Rg = -9999
eDens = -9999
df = 'unknown'
with TemporaryDirectory() as tmpdir:
#cmd.save(selection, pdbfn)
pdbfn = writePdb(selection)
if ('yes' == crycalc):
message("CRYSOL calculation using explicit hydrogens")
systemCommand(["crysol", "-eh"] + param.split() + [pdbfn])
if ('no' == crycalc):
systemCommand(["crysol"] + param.split() + [pdbfn])
fid = pdbfn.replace(".pdb", "")
result = parseCrysolLog(fid+"00.log")
Rg = result['Rg']
eDens = result['eDens']
df = tmpdir.move_out_numbered(fid+"00.int", fid, '.int')
message("CRYSOL Theoretical Rg = " + repr(Rg))
message("CRYSOL Average electron density = " + repr(eDens))
message( ".int file written to " + df)
return df
cmd.extend("predcrysol", predcrysol)
def checkAtsasVersion():
'''Check if ATSAS is installed'''
CHECK_PATH = str(os.getenv('PATH'))
if 'ATSAS' in CHECK_PATH:
return "OK"
else:
return "NOBIN"
return
cmd.extend("checkAtsasVersion", checkAtsasVersion)
#run crysol in fit mode
def fitcrysol(crycalc, SaxsDataFileName, models, prefix = defprefix, param = ""):
if False == os.path.isfile(SaxsDataFileName):
message("SAXS .dat file \'"+SaxsDataFileName+"\' not found")
return
fileFullPath = os.path.abspath(SaxsDataFileName);
Rg = -9999
chi2 = -9999
eDens = -9999
#write all models into a single file
selection = " or ".join(models)
with TemporaryDirectory() as tmpdir:
#cmd.save(selection, pdbfn)
pdbfn = writePdb(selection)
if ('yes' == crycalc):
message("CRYSOL calculation using explicit hydrogens")
systemCommand(["crysol", "-eh"] + param.split() + [pdbfn, fileFullPath])
if ('no' == crycalc):
systemCommand(["crysol"] + param.split() + [pdbfn, fileFullPath])
fid = pdbfn.replace(".pdb", "")
logfile = fid+"00.log"
result = parseCrysolLog(logfile)
Rg = result['Rg']
chi2 = result['chi2']
eDens = result['eDens']
df = tmpdir.move_out_numbered(fid+"00.fit", fid, '.fit')
logfn = tmpdir.move_out_numbered(logfile, fid, '.log')
message( ".log file written to " + logfile)
message( ".fit file written to " + df)
#if there is more than one model, we are evaluating a complex
#in this case we should provide the coordinates of the complex
#to the user.
if 1 < len(models):
pdbfn=tmpdir.move_out_numbered(pdbfn, fid, '.pdb')
message( ".pdb file written to " + pdbfn)
message("CRYSOL Theoretical Rg = " + repr(Rg))
message("CRYSOL Chi-square = " + repr(chi2))
message("CRYSOL Average electron density = " + repr(eDens))
return df
cmd.extend("fitcrysol", fitcrysol)
#run sreflex
def sreflex(SaxsDataFileName, models,
viewer='primus', prefix=defprefix):
global modelingRuns
global currentDat
if False == os.path.isfile(SaxsDataFileName):
message("SAXS .dat file \'"+SaxsDataFileName+"\' not found")
return
fileFullPath = os.path.abspath(SaxsDataFileName);
cwd = os.getcwd()
pdbs = []
for m in models:
pdbfn = writePdb(m)
pdbs.append(pdbfn)
s = ','
coordsarg = s.join(pdbs)
df = destFile("", prefix+"_sreflex","")
systemCommand(["sreflex", "-p", df, fileFullPath, coordsarg])
message( "sreflex finished." )
modelingRuns += 1;
#prepare files for load
#open report and read entries there
reportfn = os.path.join(df, "report.txt")
if False == os.path.isfile(reportfn):
message("SREFLEX report file \'"+reportfn+"\' not found, something went wrong")
return
currentDat = []
with open(reportfn, 'r') as rf:
for line in rf:
sys.stdout.write(line)
modelid = line.split()[0]
if modelid.startswith('rc01') or modelid.startswith('uc01'):
currentDat.append(df + "/fits/" + modelid + ".fit")
cmd.load(df + "/models/" + modelid + ".pdb",
"sreflex" + repr(modelingRuns) + modelid)
openDatFile(viewer, currentDat)
return
cmd.extend("sreflex", sreflex)
def readNSDFromSupalmPdb(pdbfn):
"""parse NSD value from SUPALM output PDB file
useful for Windows users without console access"""
nsd = 9999;
with open(pdbfn, 'r') as rf:
for line in rf:
if re.match("(.*)Final distance(.*)", line):
nsd = float(line[38:49])
break
return nsd
def readTransformationMatrixFromPdbRemark(pdbfn):
#read transformation matrix from output pdb
#useful for alpraxin and supalm
rf = open(pdbfn, 'r')
read = 1
a=[]
c=4
while(1):
line=rf.readline()
if re.match("(.*)Transformation(.*)", line):
while(c):
a.append(line[39:51])
a.append(line[51:63])
a.append(line[63:75])
a.append(line[75:87])
line=rf.readline()
c=c-1;
break
rf.close()
pymolOrder=[1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15, 4, 8, 12, 16]
p=[]; #output in pymol's format
for i in pymolOrder:
p.append(float (a[i-1]))
return p
def alpraxin(models, enantiomode):
"""run alpraxin and apply transformation matrix"""
sel = " or ".join(models)
with TemporaryDirectory():
pdbfn = writePdb(sel, "in_")
outfn = sel + ".pdb"
outfn = outfn.replace(" ", "")
aargs = ["alpraxin", pdbfn]
if ('yes' == enantiomode):
message("ALPRAXIN will create enantiomer as new model")
aargs.append("--enantiomorph=Y")
aargs.append("-o")
aargs.append(outfn)
systemCommand(aargs)
if ('no' == enantiomode):