-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidationLevelA.py
1660 lines (1403 loc) · 73.5 KB
/
validationLevelA.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
# **************************************************************************
# *
# * Authors: Carlos Oscar Sorzano ([email protected])
# *
# * Unidad de Bioinformatica of Centro Nacional de Biotecnologia , CSIC
# *
# * This program is free software; you can redistribute it and/or modify
# * it under the terms of the GNU General Public License as published by
# * the Free Software Foundation; either version 2 of the License, or
# * (at your option) any later version.
# *
# * This program is distributed in the hope that it will be useful,
# * but WITHOUT ANY WARRANTY; without even the implied warranty of
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# * GNU General Public License for more details.
# *
# * You should have received a copy of the GNU General Public License
# * along with this program; if not, write to the Free Software
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# * 02111-1307 USA
# *
# * All comments concerning this program package may be sent to the
# * e-mail address '[email protected]'
# *
# **************************************************************************
import collections
import glob
import json
import numpy as np
import os
import pickle
import subprocess
import re
from datetime import datetime
from random import randint
from time import sleep
import pwem.convert as emconv
from scipion.utils import getScipionHome
import pyworkflow.plugin as pwplugin
from pyworkflow.utils.path import cleanPath, copyFile
from pwem.convert.atom_struct import AtomicStructHandler
from pwem.viewers.viewer_localres import replaceOcuppancyWithAttribute, makeResidueValuesDic
import pwem.convert.atom_struct
import xmipp3
from validationReport import reportHistogram, readGuinier, reportMultiplePlots, reportPlot, isHomogeneous, safeNeg
from resourceManager import waitOutput, sendToSlurm, waitUntilFinishes, createScriptForSlurm, checkIfJobFinished
import configparser
from tools.utils import saveIntermediateData, getFilename, getScoresFromWS, getFileFromWS
from tools.emv_utils import convert_2_json
from resources.constants import *
config = configparser.ConfigParser()
config.read(os.path.join(os.path.dirname(__file__), 'config.yaml'))
useSlurm = config['QUEUE'].getboolean('USE_SLURM')
chimeraProgram = config['MAPQ'].get('CHIMERA_PROGRAM_PATH')
mapq_path = config['MAPQ'].get('MAPQ_PATH')
validation_tools_path = config['EM-VALIDATION'].get('VALIDATION_TOOLS_PATH')
EMDB_entries_path = config['EMDB'].get('ENTRIES_PATH')
N_THREADS = config['SCIPION'].get('N_THREADS')
def importMap(project, label, protImportMap, mapCoordX, mapCoordY, mapCoordZ, priority=False):
Prot = pwplugin.Domain.importFromPlugin('pwem.protocols',
'ProtImportVolumes', doRaise=True)
if mapCoordX is not None and mapCoordY is not None and mapCoordZ is not None:
prot = project.newProtocol(Prot,
objLabel=label,
filesPath=os.path.join(project.getPath(),protImportMap.outputVolume.getFileName()),
samplingRate=protImportMap.outputVolume.getSamplingRate(),
setOrigCoord=True,
x=mapCoordX,
y=mapCoordY,
z=mapCoordZ)
else:
prot = project.newProtocol(Prot,
objLabel=label,
filesPath=os.path.join(project.getPath(),protImportMap.outputVolume.getFileName()),
samplingRate=protImportMap.outputVolume.getSamplingRate(),
setOrigCoord=False)
if useSlurm:
sendToSlurm(prot, priority=True if priority else False)
project.launchProtocol(prot)
#waitOutput(project, prot, 'outputVolume')
waitUntilFinishes(project, prot)
return prot
def importModel(project, report, label, protImportMap, fnPdb, priority=False):
Prot = pwplugin.Domain.importFromPlugin('pwem.protocols',
'ProtImportPdb', doRaise=True)
protImport = project.newProtocol(Prot,
objLabel=label,
inputPdbData=1,
pdbFile=fnPdb)
protImport.inputVolume.set(protImportMap.outputVolume)
if useSlurm:
sendToSlurm(protImport, priority=True if priority else False)
project.launchProtocol(protImport)
#waitOutput(project, protImport, 'outputPdb')
waitUntilFinishes(project, protImport)
if protImport.isFailed():
raise Exception("Import atomic model did not work")
if protImport.isAborted():
raise Exception("Import atomic model was MANUALLY ABORTED")
saveIntermediateData(report.fnReportDir, 'inputData', True, 'atomic model', os.path.join(project.getPath(), fnPdb.split('/')[-1].replace('.pdb', '.cif')), 'atomic model')
return protImport
def moveOriginTo(newOrigin, handler):
centerMass = handler.centerOfMass(geometric=True)
for atom in handler.getStructure().get_atoms():
coords = atom.get_coord()
atom.coord = coords + np.asarray(newOrigin) - np.asarray(centerMass)
def phenixExecution(project, report, protImportMap, protAtom, resolution, label, priority=False):
Prot = pwplugin.Domain.importFromPlugin('phenix.protocols',
'PhenixProtRunValidationCryoEM', doRaise=True)
prot = project.newProtocol(Prot,
objLabel=label,
resolution=max(resolution,3.0))
prot.inputVolume.set(protImportMap.outputVolume)
prot.inputStructure.set(protAtom.outputPdb)
if useSlurm:
sendToSlurm(prot, priority=True if priority else False)
project.launchProtocol(prot)
waitUntilFinishes(project, prot)
fnPkl = os.path.join(project.getPath(),prot._getExtraPath("validation_cryoem.pkl"))
data = None
if os.path.isfile(fnPkl):
fnPklOut = os.path.join(report.getReportDir(),"validation_cryoem.pkl")
phenixScript=\
"""import pickle
data=pickle.load(open("%s","r"))
dataOut = {}
# CC ----------------------------------------------------------------
dataOut["cc_mask"]=data.model_vs_data.cc.cc_mask
dataOut["cc_box"]=data.model_vs_data.cc.cc_box
dataOut["cc_peaks"]=data.model_vs_data.cc.cc_peaks
dataOut["cc_volume"]=data.model_vs_data.cc.cc_volume
dataOut["cc_main_chain"]=data.model_vs_data.cc.cc_main_chain.cc
try:
dataOut["cc_side_chain"]=data.model_vs_data.cc.cc_side_chain.cc
except:
pass
# CC per chain ------------------------------------------------------
dataOut['chain_list'] = []
chain_names = []
for item in data.model_vs_data.cc.cc_per_chain:
if item.chain_id not in chain_names:
chain_names.append(item.chain_id)
dataOut['chain_list'].append((item.chain_id, item.cc))
dataOut['resseq_list'] = {}
for chain_name in chain_names:
resseq_list = []
residue_cc = []
for item in data.model_vs_data.cc.cc_per_residue:
if item.chain_id == chain_name:
resseq_list.append(item.resseq)
residue_cc.append(item.cc)
dataOut['resseq_list'][chain_name]=(resseq_list,residue_cc)
# Resolutions ------------------------------------------------------
dataOut['*d99_full_masked']=data.data.masked.d99
dataOut["overall_b_iso_masked"]=data.data.masked.b_iso_overall
dataOut['*dmodel_masked']=data.data.masked.d_model
dataOut['d_model_b0_masked']=data.data.masked.d_model_b0
dataOut['*dFSCmodel_0_masked']=data.data.masked.d_fsc_model_0
dataOut['*dFSCmodel_0.143_masked']=data.data.masked.d_fsc_model_0143
dataOut['*dFSCmodel_0.5_masked']=data.data.masked.d_fsc_model_05
dataOut['mask_smoothing_radius']=data.data.masked.radius_smooth
dataOut['*d99_full_unmasked']=data.data.unmasked.d99
dataOut["overall_b_iso_unmasked"]=data.data.unmasked.b_iso_overall
dataOut['*dmodel_unmasked']=data.data.unmasked.d_model
dataOut['d_model_b0_unmasked']=data.data.unmasked.d_model_b0
dataOut['*dFSCmodel_0_unmasked']=data.data.unmasked.d_fsc_model_0
dataOut['*dFSCmodel_0.143_unmasked']=data.data.unmasked.d_fsc_model_0143
dataOut['*dFSCmodel_0.5_unmasked']=data.data.unmasked.d_fsc_model_05
# FSCs -------------------------------------------------------------
if data.data.masked.fsc_curve_model.fsc is not None:
fsc_model_map_masked = []
d_inv_model_map_masked = []
for item in data.data.masked.fsc_curve_model.fsc:
fsc_model_map_masked.append(item)
dataOut['FSC_Model_Map_Masked'] = fsc_model_map_masked
for item in data.data.masked.fsc_curve_model.d_inv:
d_inv_model_map_masked.append(item)
dataOut['d_inv_Model_Map_Masked'] = d_inv_model_map_masked
if data.data.unmasked.fsc_curve_model.fsc is not None:
fsc_model_map_unmasked = []
d_inv_model_map_unmasked = []
for item in data.data.unmasked.fsc_curve_model.fsc:
fsc_model_map_unmasked.append(item)
dataOut['FSC_Model_Map_Unmasked'] = fsc_model_map_unmasked
for item in data.data.unmasked.fsc_curve_model.d_inv:
d_inv_model_map_unmasked.append(item)
dataOut['d_inv_Model_Map_Unmasked'] = d_inv_model_map_unmasked
fh = open("%s",'wb')
pickle.dump(dataOut,fh)
fh.close()
"""%(fnPkl, fnPklOut)
fnPhenixScript = os.path.join(report.getReportDir(),"validation_cryoem.py")
fhPhenixScript = open(fnPhenixScript,"w")
fhPhenixScript.write(phenixScript)
fhPhenixScript.close()
saveIntermediateData(report.getReportDir(), 'phenix', True, 'validation_cryoem.pkl', fnPkl, 'validation_cryoem.pkl file')
saveIntermediateData(report.getReportDir(), 'phenix', True, 'validation_cryoem.py', fnPhenixScript, 'validation_cryoem.py file to get all phenix data from pickle')
from phenix import Plugin
Plugin.runPhenixProgram('',fnPhenixScript)
data = pickle.load(open(fnPklOut, "rb"))
saveIntermediateData(report.getReportDir(), 'phenix', False, 'dataDict', data, ['', 'phenix data dictionary containing all key params'])
return prot, data
def phenixReporting(project, report, resolution, prot, data):
secLabel = "sec:phenix"
msg = \
"""
\\subsection{Level A.a Phenix validation}
\\label{%s}
\\textbf{Explanation}:\\\\
Phenix provides a number of tools to assess the agreement between the experimental map and its atomic model
(see this \\href{%s}{link} for more details). There are several cross-correlations to assess the quality of the fitting:\\\\
\\begin{itemize}
\\item CC (mask): Model map vs. experimental map correlation coefficient calculated considering map values inside
a mask calculated around the macromolecule.
\\item CC (box): Model map vs. experimental map correlation coefficient calculated considering all grid points of the
box.
\\item CC (volume) and CC (peaks) compare only map regions with the highest density values and regions below a
certain contouring threshold level are ignored. CC (volume): The map region considered is defined by
the N highest points inside the molecular mask. CC (peaks): In this case, calculations consider the union of
regions defined by the N highest peaks in the model-calculated map and the N highest peaks in the experimental map.
\\item Local real-space correlation coefficients CC (main chain) and CC (side chain) involve the main skeleton chain
and side chains, respectively.
\\end{itemize}
There are also multiple ways of measuring the resolution:
\\begin{itemize}
\\item d99: Resolution cutoff beyond which Fourier map coefficients are negligibly small. Calculated from the
full map.
\\item d\_model: Resolution cutoff at which the model map is the most similar to the target (experimental)
map. For d\_model to be meaningful, the model is expected to fit the map as well as possible. d\_model (B\ factors = 0)
tries to avoid the blurring of the map.
\\item d\_FSC\_model; Resolution cutoff up to which the model and map Fourier coefficients are similar at FSC values
of 0, 0.143, 0.5.
\\end{itemize}
In addition to these resolution measurements the overall isotropic B factor is another indirect measure of the
quality of the map.
\\\\
\\textbf{Results:}\\\\
\\\\
""" % (secLabel, PHENIX_DOI)
report.write(msg)
if prot.isFailed():
report.writeSummary("A.a Phenix", secLabel, ERROR_MESSAGE)
report.write(ERROR_MESSAGE_PROTOCOL_FAILED)
phenixStdout = open(os.path.join(project.getPath(), prot.getStdoutLog()), "r").read()
controlledErrors = ["Sorry: Input map is all zero after boxing", "Sorry: Map and model are not aligned", "Sorry: Fatal problems interpreting model file"]
for error in controlledErrors:
if error in phenixStdout:
report.write("{\\color{red} \\textbf{REASON: %s.}}\\\\ \n" % error)
report.write(STATUS_ERROR_MESSAGE)
return prot
if prot.isAborted():
print(PRINT_PROTOCOL_ABORTED + ": " + NAME_PHENIX)
report.writeSummary("A.a Phenix", secLabel, ERROR_ABORTED_MESSAGE)
report.write(ERROR_MESSAGE_ABORTED + STATUS_ERROR_ABORTED_MESSAGE)
return prot
# CC
msg =\
"""To avoid ringing in Fourier space a smooth mask with a radius of %5.1f \\AA~has been applied. \\\\
\\underline{Overall correlation coefficients}: \\\\
\\\\
\\begin{center}
\\begin{tabular}{rc}
CC (mask) = & %5.3f\\\\
CC (box) = & %5.3f\\\\
CC (volume) = & %5.3f\\\\
CC (peaks) = & %5.3f\\\\
CC (main chain) = & %5.3f\\\\
"""%(data['mask_smoothing_radius'], data['cc_mask'],data['cc_box'],data['cc_volume'],data['cc_peaks'],
data['cc_main_chain'])
if 'cc_side_chain' in data:
msg+="CC (side chain) = & %5.3f\\\\ \n"%data['cc_side_chain']
msg+="\\end{tabular}\n\\\\\n"
msg+="\\end{center}\n\n"
# CC per chain
msg+=\
"""
\\underline{Correlation coefficients per chain}:\\\\
\\begin{center}
\\begin{tabular}{cc}
\\textbf{Chain} & \\textbf{Cross-correlation} \\\\
"""
for chain_id, cc in data['chain_list']:
msg+="%s & %f\\\\ \n"%(chain_id, cc)
msg+="\\end{tabular}\n\n"
msg+="\\end{center}\n\n\n"
# CC per residues
allCCs = []
def plotCCResidue(chain_id, reportDir, allCCs):
fnPlot = os.path.join(reportDir, "ccresidue_%s.png"%chain_id)
resseq_list, residue_cc = data['resseq_list'][chain_id]
allCCs+=residue_cc
x = [x+1 for x in np.arange(0,len(residue_cc))]
reportPlot(x, residue_cc, 'Aminoacid no.', 'Cross-correlation', fnPlot, addMean=True, title="Chain %s"%chain_id)
return fnPlot
msg+="""We now show the correlation profiles of the different chain per residue.\n"""
for chain_id in sorted(data['resseq_list']):
fnPlot = plotCCResidue(chain_id, report.getReportDir(), allCCs)
saveIntermediateData(report.fnReportDir, "phenix", True, "ccresidue_%s.png"%chain_id, fnPlot, 'Plot including the correlation profiles of the chain %s'%chain_id)
msg+="""\\includegraphics[width=7cm]{%s}\n"""%fnPlot
fnCCHist = os.path.join(report.getReportDir(),"ccModelHist.png")
reportHistogram(allCCs, "Cross-correlation", fnCCHist)
badResidues = np.sum(np.array(allCCs)<0.5)/len(allCCs)*100
msg += \
"""
Fig. \\ref{fig:ccResidueHist} shows the histogram of all cross-correlations evaluated at the residues. The percentage
of residues whose correlation is below 0.5 is %4.1f \\%%.
\\begin{figure}[H]
\centering
\includegraphics[width=10cm]{%s}
\\caption{Histogram of the cross-correlation between the map and model evaluated for all residues.}
\\label{fig:ccResidueHist}
\\end{figure}
"""%(badResidues, fnCCHist)
saveIntermediateData(report.fnReportDir, "phenix", True, "ccModelHist.png", fnCCHist, 'Histogram of the cross-correlation between the map and model evaluated for all residues')
saveIntermediateData(report.fnReportDir, "phenix", False, "percentageResidues05", badResidues, ['%', 'The percentage of residues whose correlation is below 0.5'])
# Resolutions
msg+=\
"""
\\underline{Resolutions estimated from the model}:\\\\
\\begin{center}
\\begin{tabular}{rcc}
\\textbf{Resolution} (\\AA) & \\textbf{Masked} & \\textbf{Unmasked} \\\\
d99 & %4.1f & %4.1f \\\\
d\_model & %4.1f & %4.1f \\\\
d\_model (B-factor=0) & %4.1f & %4.1f \\\\
FSC\_model=0 & %4.1f & %4.1f \\\\
FSC\_model=0.143 & %4.1f & %4.1f \\\\
FSC\_model=0.5 & %4.1f & %4.1f \\\\
\\end{tabular}
\\end{center}
"""%(data['*d99_full_masked'],data['*d99_full_unmasked'],
data['*dmodel_masked'],data['*dmodel_unmasked'],
data['d_model_b0_masked'],data['d_model_b0_unmasked'],
data['*dFSCmodel_0_masked'],data['*dFSCmodel_0_unmasked'],
data['*dFSCmodel_0.143_masked'],data['*dFSCmodel_0.143_unmasked'],
data['*dFSCmodel_0.5_masked'],data['*dFSCmodel_0.5_unmasked'])
msg += \
"""
\\underline{Overall isotropic B factor}:\\\\
\\begin{center}
\\begin{tabular}{rcc}
\\textbf{B factor} & \\textbf{Masked} & \\textbf{Unmasked} \\\\
Overall B-iso & %4.1f & %4.1f \\\\
\\end{tabular}
\\end{center}
""" % (data["overall_b_iso_masked"], data["overall_b_iso_unmasked"])
if 'FSC_Model_Map_Masked' in data and 'FSC_Model_Map_Unmasked' in data:
fnFSCModel = os.path.join(report.getReportDir(),"fscModel.png")
reportMultiplePlots(data['d_inv_Model_Map_Masked'],
[data['FSC_Model_Map_Masked'], data['FSC_Model_Map_Unmasked'],
0.5*np.ones(len(data['FSC_Model_Map_Masked']))],
"Resolution (A)", "FSC", fnFSCModel,
['Masked','Unmasked','0.5 Threshold'], invertXLabels=True)
msg+=\
"""Fig. \\ref{fig:fscModel} shows the FSC between the input map and the model.
\\begin{figure}[H]
\centering
\includegraphics[width=12cm]{%s}
\\caption{FSC between the input map and model with and without a mask constructed from the model.
The X-axis is the square of the inverse of the resolution in \\AA.}
\\label{fig:fscModel}
\\end{figure}
"""%fnFSCModel
report.write(msg)
saveIntermediateData(report.fnReportDir, "phenix", True, "fscModel.png", fnFSCModel, 'Plot that shows FSC between the input map and model with and without a mask constructed from the model')
warnings = []
testWarnings = False
if badResidues > 10 or testWarnings:
warnings.append("{\\color{red} \\textbf{The percentage of residues that have a cross-correlation below 0.5 " \
"is %4.1f, that is larger than 10\\%%}}" % badResidues)
if resolution<0.8*data['*dFSCmodel_0.5_masked'] or testWarnings:
warnings.append("{\\color{red} \\textbf{The resolution reported by the user, %4.1f \\AA, is significantly " \
"smaller than the resolution estimated between map and model (FSC=0.5), %4.1f \\AA}}" %\
(resolution,data['*dFSCmodel_0.5_masked']))
report.addResolutionEstimate(data['*d99_full_masked'])
report.addResolutionEstimate(data['*dmodel_masked'])
report.addResolutionEstimate(data['d_model_b0_masked'])
report.addResolutionEstimate(data['*dFSCmodel_0_masked'])
report.addResolutionEstimate(data['*dFSCmodel_0.143_masked'])
report.addResolutionEstimate(data['*dFSCmodel_0.5_masked'])
msg = \
"""\\textbf{Automatic criteria}: The validation is OK if 1) the percentage of residues whose correlation is
smaller than 0.5 is smaller than 10\\%, and 2) the resolution reported by the user is larger than 0.8 times the
resolution estimated between the map and model at FSC=0.5.
\\\\
"""
report.write(msg)
report.writeWarningsAndSummary(warnings, "A.a Phenix validation", secLabel)
if len(warnings)>0:
report.writeAbstract("According to phenix, it seems that there might be some mismatch between the map "\
"and its model (see Sec. \\ref{%s}). "%secLabel)
def phenix(project, report, protImportMap, protAtom, resolution, priority=False):
label = "A.a Phenix"
protPhenix, dataPhenix = phenixExecution(project, report, protImportMap, protAtom, resolution, label, priority)
phenixReporting(project, report, resolution, protPhenix, dataPhenix)
def searchFittedInOriginListWithPhenix(unique_list_origins, original_cc_mask, project, report, protImportMap, FNMODEL, resolution, cc_mask_threshold, priority=False):
h = AtomicStructHandler()
h.read(FNMODEL)
new_cc_mask_dict = {}
for origin in unique_list_origins:
origin_dict = {}
originStr = '-'.join(map(str, origin))
modelName = os.path.splitext(os.path.basename(FNMODEL))[0]
modelNewName = f"{modelName}_{originStr}.cif"
newFnModel = os.path.join(report.getReportDir(), modelNewName)
moveOriginTo(origin, h)
h.writeAsCif(newFnModel)
newProtAtom = importModel(project, report, f"Import atomic - origin {originStr}", protImportMap, newFnModel, priority=priority)
protPhenix, dataPhenix = phenixExecution(project, report, protImportMap, newProtAtom, resolution, f"Phenix search fitted - origin {originStr}", priority)
if protPhenix.isFailed():
print(f"Phenix protocol failed while checking new origin {originStr}")
elif protPhenix.isAborted():
print(f"Phenix protocol was aborted while checking new origin {originStr}")
else:
importProtId = newProtAtom.getObjId()
phenixProtId = protPhenix.getObjId()
origin_dict["cc_mask"] = dataPhenix["cc_mask"]
origin_dict["import_prot_id"] = importProtId
origin_dict["phenix_prot_id"] = phenixProtId
new_cc_mask_dict[originStr] = origin_dict
# Get greatest cc_mask that is also greater than cc_mask original and beyond cc_mask_threshold (that normally is 0.5)
greatest_cc_mask = None
greatest_cc_mask_key = None
for key, sub_dict in new_cc_mask_dict.items():
new_cc_mask = sub_dict.get("cc_mask", None)
if new_cc_mask is not None and new_cc_mask > original_cc_mask and new_cc_mask > cc_mask_threshold:
if greatest_cc_mask is None or new_cc_mask > greatest_cc_mask:
greatest_cc_mask = new_cc_mask
greatest_cc_mask_key = key
if greatest_cc_mask:
newOrigin = greatest_cc_mask_key.split("-")
# Get import and phenix protocol for new origin
newImportProtId = new_cc_mask_dict[greatest_cc_mask_key]["import_prot_id"]
newImportProt = project.getProtocol(int(newImportProtId), fromRuns=True)
newPhenixProtId = new_cc_mask_dict[greatest_cc_mask_key]["phenix_prot_id"]
newPhenixProt = project.getProtocol(int(newPhenixProtId), fromRuns=True)
return newImportProt, newPhenixProt, dataPhenix, newOrigin
else:
return None, None, None, None
def checkFittedWithPhenix(project, report, EMDB_ID_NUM, section, secLabel, protImportMap, protAtom, FNMODEL, resolution, cc_mask_threshold, unique_list_origins, priority=False):
label = "A.a Phenix"
protPhenix, dataPhenix = phenixExecution(project, report, protImportMap, protAtom, resolution, label, priority)
if protPhenix.isFailed():
print("Phenix protocol failed while checking if map and model are fitted.")
return None, protPhenix, dataPhenix, protAtom
if protPhenix.isAborted():
print(PRINT_PROTOCOL_ABORTED + ": " + NAME_PHENIX)
report.writeSummary(section, secLabel, ERROR_ABORTED_MESSAGE)
report.write(ERROR_MESSAGE_ABORTED + STATUS_ERROR_ABORTED_MESSAGE)
return None, protPhenix, dataPhenix, protAtom
if dataPhenix["cc_mask"] > cc_mask_threshold:
report.write(PROPERLY_FITTED)
return True, protPhenix, dataPhenix, protAtom
elif dataPhenix["cc_mask"] <= cc_mask_threshold:
protAtom, protPhenix, dataPhenix, newOrigin = searchFittedInOriginListWithPhenix(unique_list_origins, dataPhenix["cc_mask"], project, report, protImportMap, FNMODEL, resolution, cc_mask_threshold, priority=priority)
if protAtom is None and protPhenix is None:
report.write(NOT_FOUND_NEW_FITTED)
######TODO: this part is for debugging. Remove when finishing debugging.######
os.makedirs(EMDB_entries_path, exist_ok=True)
with open(os.path.join(EMDB_entries_path, 'EMDB_fail_fitted.txt'), 'a') as output:
if EMDB_ID_NUM:
output.writelines(f'EMD-{EMDB_ID_NUM}\n')
else:
output.writelines('Unkown\n')
##############################################################################
return False, protPhenix, dataPhenix, protAtom
else:
report.write(FITTED_NEW_ORIGIN % ', '.join(newOrigin))
######TODO: this part is for debugging. Remove when finishing debugging.######
os.makedirs(EMDB_entries_path, exist_ok=True)
with open(os.path.join(EMDB_entries_path, 'EMDB_new_fitted.txt'), 'a') as output:
if EMDB_ID_NUM:
output.writelines(f'EMD-{EMDB_ID_NUM}\n')
else:
output.writelines('Unkown\n')
##############################################################################
return True, protPhenix, dataPhenix, protAtom
def checkFittedManually():
pass
def getListOfNewOrigins(protImportMap, mapCoordX, mapCoordY, mapCoordZ, fnMap):
sampling = protImportMap.outputVolume.getSamplingRate()
## Origin in center of the box
x, y, z = protImportMap.outputVolume.getDimensions()
xA = x * sampling / 2
yA = y * sampling / 2
zA = z * sampling / 2
## Origin from header
ccp4header = emconv.Ccp4Header(protImportMap.outputVolume.getFileName(), readHeader=True)
origin_header = np.array(ccp4header.getOrigin())
x_header = origin_header[0]
y_header = origin_header[1]
z_header = origin_header[2]
list_origins = [[x_header, y_header, z_header], [safeNeg(x_header), safeNeg(y_header), safeNeg(z_header)], [0,0,0], [xA, yA, zA], [safeNeg(xA), safeNeg(yA), safeNeg(zA)], [mapCoordX, mapCoordY, mapCoordZ], [safeNeg(mapCoordX), safeNeg(mapCoordY), safeNeg(mapCoordZ)]]
# Filter sublists and avoid those that include None values
filtered_list_origins = [lst for lst in list_origins if all(elem is not None for elem in lst)]
# Create list of unique aublists
unique_list_origins = [list(x) for x in set(tuple(x) for x in filtered_list_origins)]
return unique_list_origins
def convertPDB(project, report, protImportMap, protAtom, priority=False):
Prot = pwplugin.Domain.importFromPlugin('xmipp3.protocols',
'XmippProtConvertPdb', doRaise=True)
protConvert = project.newProtocol(Prot,
objLabel="Convert Pdb to map",
inputPdbData=1,
sampling=protImportMap.outputVolume.getSamplingRate(),
vol=True,
centerPdb=False)
protConvert.pdbObj.set(protAtom.outputPdb)
protConvert.volObj.set(protImportMap.outputVolume)
if useSlurm:
sendToSlurm(protConvert, priority=True if priority else False)
project.launchProtocol(protConvert)
#waitOutput(project, protConvert, 'outputVolume')
waitUntilFinishes(project, protConvert)
secLabel = "sec:convertPdb2Map"
msg = \
"""
\\subsection{Level A.b Conversion PDB to map}
\\label{%s}
\\textbf{Explanation}:\\\\
Convert a PDB file into a volume.\\\\
\\\\
\\textbf{Results:}\\\\
\\\\
""" % secLabel
if protConvert.isFailed(): #TODO: check texts for ConverToPdb when fails
report.writeSummary("A. Conversion PDB to map", secLabel, ERROR_CONVERT_MESSAGE)
report.write(msg)
report.write(ERROR_MESSAGE_PROTOCOL_FAILED + STATUS_ERROR_CONVERT_MESSAGE)
return None
if protConvert.isAborted():
print(PRINT_PROTOCOL_ABORTED + ": " + NAME_CONVERSION_PDB_MAP)
report.writeSummary("A. Conversion PDB to map", secLabel, ERROR_ABORTED_MESSAGE)
report.write(ERROR_MESSAGE_ABORTED + STATUS_ERROR_ABORTED_MESSAGE)
return protConvert
# Check if volume is not empty
volumeData = xmipp3.Image(protConvert.outputVolume.getFileName()).getData()
if not np.sum(volumeData) > 0:
report.writeSummary("A. Conversion PDB to map", secLabel, ERROR_CONVERT_MESSAGE)
report.write(msg)
report.write(ERROR_MESSAGE_EMPTY_VOL + STATUS_ERROR_MESSAGE)
return None
return protConvert
def fscq(project, report, protImportMap, protAtom, protConvert, protCreateSoftMask, fnMaskedMap, priority=False):
if not protImportMap.outputVolume.hasHalfMaps():
return
secLabel = "sec:fscq"
msg = \
"""
\\subsection{Level A.b FSC-Q}
\\label{%s}
\\textbf{Explanation}:\\\\
FSC-Q (see this \\href{%s}{link} for more details) compares the local FSC between the map and the atomic model to the local FSC of the two
half maps. FSC-Qr is the normalized version of FSC-Q to facilitate comparisons. Typically, FSC-Qr should
take values between -1.5 and 1.5, being 0 an indicator of good matching between map and model.\\\\
\\\\
\\textbf{Results:}\\\\
\\\\
""" % (secLabel, FSCQ_DOI)
report.write(msg)
Prot = pwplugin.Domain.importFromPlugin('xmipp3.protocols',
'XmippProtValFit', doRaise=True)
prot = project.newProtocol(Prot,
objLabel="A.b FSC-Q",
inputPDBObj=protAtom.outputPdb,
numberOfThreads=N_THREADS)
prot.inputVolume.set(protImportMap.outputVolume)
prot.pdbMap.set(protConvert.outputVolume)
prot.inputMask.set(protCreateSoftMask.outputMask)
if useSlurm:
sendToSlurm(prot, priority=True if priority else False)
project.launchProtocol(prot)
#waitOutput(project, prot, 'outputAtomStruct')
waitUntilFinishes(project, prot)
if prot.isFailed():
report.writeSummary("A.b FSC-Q", secLabel, ERROR_MESSAGE)
report.write(ERROR_MESSAGE_PROTOCOL_FAILED + STATUS_ERROR_MESSAGE)
return
if prot.isAborted():
print(PRINT_PROTOCOL_ABORTED + ": " + NAME_FSCQ)
report.writeSummary("A.b FSC-Q", secLabel, ERROR_ABORTED_MESSAGE)
report.write(ERROR_MESSAGE_ABORTED + STATUS_ERROR_ABORTED_MESSAGE)
return prot
V = xmipp3.Image(prot._getExtraPath("pdb_volume.map"))
FSCQr = xmipp3.Image(prot._getExtraPath("diferencia_norm.map"))
fscqr = FSCQr.getData()[V.getData()>0.97]
avgFSCQr = np.mean(fscqr)
ci = np.percentile(fscqr, [2.5, 97.5])
f15=float(np.sum(abs(fscqr)>1.5))/fscqr.size*100
fnHist = os.path.join(report.getReportDir(),"fscqrHist.png")
reportHistogram(np.clip(fscqr, -1.5, 1.5), "FSC-Qr", fnHist)
Bpercentiles = np.percentile(np.clip(fscqr, -1.5, 1.5), np.array([0.025, 0.25, 0.5, 0.75, 0.975])*100)
msg =\
"""Fig. \\ref{fig:fscqHist} shows the histogram of FSC-Qr and Fig.
\\ref{fig:fscq} the colored isosurface of the atomic model converted to map. The
average FSC-Qr is %5.2f, its 95\\%% confidence interval is [%5.2f,%5.2f]. The percentage of values
whose FSC-Qr absolute value is beyond 1.5 is %5.1f \\%%.
\\begin{figure}[H]
\\centering
\\includegraphics[width=8cm]{%s}
\\caption{Histogram of the FSC-Qr limited to -1.5 and 1.5.}
\\label{fig:fscqHist}
\\end{figure}
"""%(avgFSCQr, ci[0], ci[1], f15, fnHist)
report.colorIsoSurfaces(msg, "Isosurface of the atomic model colored by FSC-Qr between -1.5 and 1.5",
"fig:fscq", project, "fscq", fnMaskedMap,
protImportMap.outputVolume.getSamplingRate(),
prot._getExtraPath("diferencia_norm.map"), -3.0, 3.0)
saveIntermediateData(report.getReportDir(), 'FSCQ', False, 'averageFSQr', float(avgFSCQr), ['', 'average FSC-Qr'])
saveIntermediateData(report.getReportDir(), 'FSCQ', False, 'llcinterval', float(ci[0]), ['', 'Lower limit 95% confidence interval'])
saveIntermediateData(report.getReportDir(), 'FSCQ', False, 'ulcinterval', float(ci[1]), ['', 'Upper limit 95% confidence interval'])
saveIntermediateData(report.getReportDir(), 'FSCQ', False, 'percentage15', f15, ['%', 'The percentage of values whose FSC-Qr absolute value is beyond 1.5'])
saveIntermediateData(report.getReportDir(), 'FSCQ', False, 'fscqrList', np.clip(fscqr, -1.5, 1.5).tolist(), ['', 'List of FSCalues to create the histogram'])
saveIntermediateData(report.getReportDir(), 'FSCQ', True, 'fscq_struct', os.path.join(project.getPath(), prot._getPath('fscq_struct.cif')), 'fscq_struct cif file')
saveIntermediateData(report.getReportDir(), 'FSCQ', True, 'fscqHist', fnHist, 'FSCQ Histogram')
saveIntermediateData(report.getReportDir(), 'FSCQ', True, 'fscqViewer',
[os.path.join(report.getReportDir(), 'fscq1.jpg'),
os.path.join(report.getReportDir(), 'fscq2.jpg'),
os.path.join(report.getReportDir(), 'fscq3.jpg')], 'FSCQ views')
warnings = []
testWarnings = False
BperHomogeneous = isHomogeneous(Bpercentiles[0], Bpercentiles[-1], eps=0.1)
if BperHomogeneous:
warnings.append("{\\color{red} \\textbf{Program output seems to be too homogeneous. There might " \
"be some program issues analyzing the data.}}")
if f15>10 or testWarnings:
warnings.append("{\\color{red} \\textbf{The percentage of voxels that have a FSC-Qr larger than 1.5 in "\
"absolute value is %5.1f, that is larger than 10\\%%}}"%f15)
msg = \
"""\\textbf{Automatic criteria}: The validation is OK if the percentage of residues whose FSC-Q is larger than 1.5
in absolute value is smaller than 10\\%.
\\\\
"""
report.write(msg)
report.writeWarningsAndSummary(warnings, "A.b FSC-Q", secLabel)
if len(warnings)>0:
report.writeAbstract("According to FSC-Q, it seems that there is a mismatch between the map and its model "\
"(see Sec. \\ref{%s}). "%secLabel)
def multimodel(project, report, protImportMap, protAtom, resolution, priority=False):
secLabel = "sec:multimodel"
msg = \
"""
\\subsection{Level A.c Multimodel stability}
\\label{%s}
\\textbf{Explanation}:\\\\
This method (see this \\href{%s}{link} for more details) estimates the ambiguity of the atomic model in each region of the CryoEM map due to
the different local resolutions or local heterogeneity.\\\\
\\\\
\\textbf{Results:}\\\\
\\\\
""" % (secLabel, MULTIMODEL_DOI)
report.write(msg)
Prot = pwplugin.Domain.importFromPlugin('rosetta.protocols',
'ProtRosettaGenerateStructures', doRaise=True)
prot1 = project.newProtocol(Prot,
objLabel="A.c Multimodel ambiguity",
inputStructure=protAtom.outputPdb,
inputVolume=protImportMap.outputVolume,
resolution=resolution,
numMods=2)
if useSlurm:
sendToSlurm(prot1, GPU=True, priority=True if priority else False)
project.launchProtocol(prot1)
#waitOutput(project, prot1, 'outputAtomStructs')
waitUntilFinishes(project, prot1)
if prot1.isFailed() or not hasattr(prot1,"outputAtomStructs"):
report.writeSummary("A.c Multimodel", secLabel, ERROR_MESSAGE)
report.write(ERROR_MESSAGE_PROTOCOL_FAILED + STATUS_ERROR_MESSAGE)
return
if prot1.isAborted():
print(PRINT_PROTOCOL_ABORTED + ": " + NAME_MULTIMODEL)
report.writeSummary("A.c Multimodel", secLabel, ERROR_ABORTED_MESSAGE)
report.write(ERROR_MESSAGE_ABORTED + STATUS_ERROR_ABORTED_MESSAGE)
return prot1
Prot = pwplugin.Domain.importFromPlugin('atomstructutils.protocols',
'ProtRMSDAtomStructs', doRaise=True)
prot2 = project.newProtocol(Prot,
objLabel="A.c RMSD",
inputStructureSet=prot1.outputAtomStructs)
if useSlurm:
sendToSlurm(prot2, priority=True if priority else False)
project.launchProtocol(prot2)
#waitOutput(project, prot2, 'outputAtomStructs')
waitUntilFinishes(project, prot2)
if prot2.isFailed():
report.writeSummary("A.c Multimodel", secLabel, ERROR_MESSAGE)
report.write(ERROR_MESSAGE_PROTOCOL_FAILED + STATUS_ERROR_MESSAGE)
return
if prot2.isAborted():
print(PRINT_PROTOCOL_ABORTED + ": " + NAME_MULTIMODEL)
report.writeSummary("A.c Multimodel", secLabel, ERROR_ABORTED_MESSAGE)
report.write(ERROR_MESSAGE_ABORTED + STATUS_ERROR_ABORTED_MESSAGE)
return prot2
fnCifs = glob.glob(prot2._getPath('*.cif'))
if len(fnCifs)==0:
report.writeSummary("A.c Multimodel", secLabel, ERROR_MESSAGE)
report.write(ERROR_MESSAGE_PROTOCOL_FAILED + STATUS_ERROR_MESSAGE)
return
fnCif = fnCifs[0]
fnCifRMSD = os.path.join(report.getReportDir(),"atomicModelRMSD.cif")
replaceOcuppancyWithAttribute(fnCif, "perResidueRMSD", fnCifRMSD)
cifDic = AtomicStructHandler().readLowLevel(fnCifRMSD)
rmsd = []
for name, value in zip(cifDic['_scipion_attributes.name'],cifDic['_scipion_attributes.value']):
if name=='perResidueRMSD':
rmsd.append(float(value))
fnRMSDHist = os.path.join(report.getReportDir(),"rmsdHist.png")
reportHistogram(rmsd, "RMSD", fnRMSDHist)
avgRMSD = np.mean(rmsd)
msg =\
"""Fig. \\ref{fig:rmsdHist} shows the histogram of the RMSD of the different models. The average RMSD between models
is %4.2f \\AA. Fig. \\ref{fig:modelRMSD} shows the atomic model colored by RMSD.
\\begin{figure}[H]
\\centering
\\includegraphics[width=8cm]{%s}
\\caption{Histogram of RMSD of the different atoms of the multiple models.}
\\label{fig:rmsdHist}
\\end{figure}
"""%(avgRMSD, fnRMSDHist)
report.atomicModel("modelRMSD", msg, "Atomic model colored by RMSD", fnCifRMSD, "fig:modelRMSD", occupancy=True)
warnings=[]
testWarnings = False
if avgRMSD>2 or testWarnings:
warnings.append("{\\color{red} \\textbf{The average RMSD is too high, "\
"%4.1f\\%%}}"%avgRMSD)
msg = \
"""\\textbf{Automatic criteria}: The validation is OK if the average RMSD is smaller than 2\\AA.
\\\\
"""
report.write(msg)
report.writeWarningsAndSummary(warnings, "A.c Multimodel", secLabel)
if len(warnings)>0:
report.writeAbstract("It seems that the model is too ambiguous (see Sec. \\ref{%s}). "%\
secLabel)
def guinierModel(project, report, protImportMap, protConvert, resolution, priority=False):
map = protImportMap.outputVolume
Ts = map.getSamplingRate()
fnAtom = protConvert.outputVolume.getFileName()
fnOut = os.path.join(report.getReportDir(), "sharpenedModel.mrc")
args = "-i %s -o %s --sampling %f --maxres %s --auto"%(fnAtom, fnOut, Ts, resolution)
scipionHome = getScipionHome()
scipion3 = os.path.join(scipionHome, 'scipion3')
cmd = '%s run xmipp_volume_correct_bfactor %s' % (scipion3, args)
if not useSlurm:
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)
p.wait()
sleep(120)
else:
randomInt = int(datetime.now().timestamp()) + randint(0, 1000000)
slurmScriptPath = createScriptForSlurm('xmipp_volume_correct_bfactor_levelA_' + str(randomInt), report.getReportDir(), cmd, priority=priority)
# send job to queue
subprocess.Popen('sbatch %s' % slurmScriptPath, shell=True)
# check if job has finished
while True:
if checkIfJobFinished('xmipp_volume_correct_bfactor_levelA_' + str(randomInt)):
break
sleep(120)
dinv2, lnFMap, _ = readGuinier(os.path.join(report.getReportDir() if not useSlurm else os.path.dirname(slurmScriptPath), 'sharpenedMap.mrc') + '.guinier')
_, lnFAtom, _ = readGuinier(fnOut + ".guinier")
lnFMapp = lnFMap+(np.mean(lnFAtom)-np.mean(lnFMap))
R = np.corrcoef(lnFMapp, lnFAtom)
R=R[0,1]
fnPlot = os.path.join(report.getReportDir(), 'BfactorAtom.png')
reportMultiplePlots(dinv2, [lnFAtom, lnFMapp], '1/Resolution^2 (1/A^2)', 'log Structure factor', fnPlot,
['Atomic model', 'Experimental map'])
secLabel = "sec:bfactorModel"
msg = \
"""\\subsection{Level A.d Map-Model Guinier analysis}
\\label{%s}
\\textbf{Explanation:}\\\\
We compared the Guinier plot (see this \\href{%s}{link} for more details) of the atomic model and the experimental map. We made the mean
of both profiles to be equal (and equal to the mean of the atomic model) to make sure that they had comparable scales.
\\\\
\\\\
\\textbf{Results:}\\\\
Fig. \\ref{fig:BfactorModel} shows the logarithm (in natural units) of the structure factor (the module squared of the
Fourier transform) of the atom model and the experimental map. The correlation between the two profiles was %5.3f.
\\begin{figure}[H]
\centering
\includegraphics[width=10cm]{%s}
\\caption{Guinier plot of the atom model and experimental map.
The X-axis is the square of the inverse of the resolution in \\AA.}
\\label{fig:BfactorModel}
\\end{figure}
""" % (secLabel, BFACTOR_GUINIER_DOI, R, fnPlot)
report.write(msg)
warnings = []
testWarnings = False
if R<0.5 or testWarnings:
warnings.append("{\\color{red} \\textbf{The correlation is smaller than 0.5, it is %5.3f.}}"%R)
msg = \
"""\\textbf{Automatic criteria}: The validation is OK if the correlation between the two Guinier profiles is larger
than 0.5.
\\\\
"""
report.write(msg)
report.writeWarningsAndSummary(warnings, "A.d Map-Model Guinier", secLabel)
if len(warnings)>0:
report.writeAbstract("It seems that the Guinier plot of the map and its model do not match "\
"(see Sec. \\ref{%s}). "%secLabel)
saveIntermediateData(report.getReportDir(), 'guinierModel', False, 'correlation', R, ['', 'The correlation between the structure factor of the atom model and the experimental map'])
saveIntermediateData(report.getReportDir(), 'guinierModel', True, 'sharpenedModel.mrc.guinier', os.path.join(report.getReportDir(), 'sharpenedModel.mrc.guinier'), 'sharpenedModel.mrc.guinier file which contain the data to create the guinier plot')
saveIntermediateData(report.getReportDir(), 'guinierModel', True, 'guinierPlot', fnPlot, 'guinier plot for Map-Model Guinier Analysis')
def mapq(project, report, protImportMap, protAtom, resolution, priority=False):
secLabel = "sec:mapq"
msg = \
"""
\\subsection{Level A.e MapQ}
\\label{%s}
\\textbf{Explanation}:\\\\
MapQ (see this \\href{%s}{link} for more details) computes the local correlation between the map and each one of its atoms assumed to
have a Gaussian shape.\\\\
\\\\
\\textbf{Results:}\\\\
\\\\
""" % (secLabel, MAPQ_DOI)
report.write(msg)
# check if we have the precomputed data
# https://3dbionotes.cnb.csic.es/bws/api/emv/7xzz/mapq/
emdb_Id = getFilename(str(protImportMap.filesPath), withExt=False)
pdbdb_Id = getFilename(str(protAtom.outputPdb._filename), withExt=False)
print("Get MapQ scores from 3DBionotes-WS for %s" % pdbdb_Id)
has_precalculated_data = False
cif_data = getFileFromWS(pdbdb_Id, 'mapq')
if cif_data:
# save to report
results_msg = \
"""
\\Precalculated MapQ scores obtained from DB source via 3DBionotes-WS:
\\\\
\\url{https://3dbionotes.cnb.csic.es/bws/api/emv/%s/mapq/}
\\\\
""" % emdb_Id.lower().replace('_','-')
report.write(results_msg)
has_precalculated_data = True
else:
# if there is not precalculated data or failed to retrieve it
print('- Could not get data for', pdbdb_Id)
print('-- Proceed to calculate it localy')
if resolution>5:
report.writeSummary("A.e MapQ", secLabel, NOT_APPLY_MESSAGE)
report.write(NOT_APPLY_WORSE_RESOLUTION % 5 + STATUS_NOT_APPLY)
return None
Prot = pwplugin.Domain.importFromPlugin('mapq.protocols',
'ProtMapQ', doRaise=True)
prot = project.newProtocol(Prot,
objLabel="A.e MapQ",
inputVol=protImportMap.outputVolume,
pdbs=[protAtom.outputPdb],
mapRes=resolution)