/
__init__.py
3073 lines (2939 loc) · 123 KB
/
__init__.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
"""
Library of convenience functions for working with models and reflection data.
This contains a number of routines used in phenix.refine and related programs,
mainly concerned with the repetitive process of loading model and data files
and initializing the appropriate objects. Note that if you are writing a
program that uses similar inputs, it may be significantly easier to use the
unified input handling encapsulated in :py:mod:`mmtbx.command_line`, which
wraps much of the functionality in :py:mod:`mmtbx.utils` while hiding the
messy details.
"""
from __future__ import division
from mmtbx.scaling import twin_analyses
from cctbx import miller
from cctbx import crystal
from cctbx import sgtbx
import cctbx.xray.structure_factors
from cctbx.array_family import flex
from libtbx.utils import \
Sorry, date_and_time, host_and_user, multi_out, null_out
import iotbx.phil
from iotbx import reflection_file_utils
from iotbx.pdb import xray_structure
from iotbx import pdb
from cStringIO import StringIO
from cctbx import adptbx
from mmtbx import monomer_library
import mmtbx.monomer_library.server
import mmtbx.monomer_library.pdb_interpretation
from iotbx.pdb import combine_unique_pdb_files
from iotbx import mtz
from iotbx import cif
from libtbx import str_utils
from libtbx.str_utils import show_string
from libtbx import adopt_init_args
import random, sys, os
from libtbx.test_utils import approx_equal
from mmtbx.refinement import print_statistics
from mmtbx.twinning import twin_f_model
import mmtbx.bulk_solvent.bulk_solvent_and_scaling as bss
import mmtbx.f_model
import mmtbx.restraints
import mmtbx.tls.tools
from mmtbx.scaling import outlier_rejection
import mmtbx.command_line.fmodel
from cctbx import french_wilson
import libtbx.callbacks # import dependency
from libtbx.math_utils import ifloor, iceil
from cctbx import maptbx
from cctbx import uctbx
from cctbx import xray
from iotbx.cns.miller_array import crystal_symmetry_as_cns_comments
from iotbx.file_reader import any_file
from mmtbx.rotamer.rotamer_eval import RotamerEval
import boost.python
utils_ext = boost.python.import_ext("mmtbx_utils_ext")
from mmtbx_utils_ext import *
import boost.python
from mmtbx import bulk_solvent
ext = boost.python.import_ext("mmtbx_f_model_ext")
import mmtbx.rotamer
def miller_array_symmetry_safety_check(miller_array,
data_description,
working_point_group,
symmetry_safety_check,
log):
msg = miller_array.crystal_symmetry_is_compatible_with_symmetry_from_file(
working_point_group = working_point_group).format_error_message(
data_description = data_description)
if(msg is not None):
if(symmetry_safety_check == "warning"):
print >> log, "*" * 79
print >> log, "WARNING:", msg
print >> log, "*" * 79
else:
raise Sorry(msg + """
The program inspects all inputs to determine the working crystal
symmetry (unit cell & space group).
Please check the working crystal symmetry shown above. If it is
not correct, use the --unit_cell, --space_group, or --symmetry
option to specify the correct unit cell parameters and space group
symbol.
If the working crystal symmetry is in fact correct, disable this
error by adding
refinement.input.symmetry_safety_check=warning
to the command line arguments.
""")
def explain_how_to_generate_array_of_r_free_flags(log, flags_parameter_scope):
part1 = """\
If previously used R-free flags are available run this command again
with the name of the file containing the original flags as an
additional input. If the structure was never refined before, or if the
original R-free flags are unrecoverable, run this command again with
the additional definition:
"""
part3 = """
If the structure was refined previously using different R-free flags,
the values for R-free will become meaningful only after many cycles of
refinement.
"""
print >> log, part1 + flags_parameter_scope+""".generate=True""" + part3
data_and_flags_str_part1 = """\
file_name = None
.type=path
.short_caption=Reflections file
.style = bold input_file file_type:hkl noauto process_hkl \
child:fobs:labels child:d_min:high_resolution \
child:d_max:low_resolution child:rfree_file:r_free_flags.file_name
.expert_level = 0
labels = None
.type=strings
.input_size = 160
.short_caption = Data labels
.style = bold renderer:draw_fobs_label_widget noauto \
OnChange:auto_update_label_choice child:d_min:high_resolution \
child:d_max:low_resolution parent:file_name:file_name
.expert_level = 0
high_resolution = None
.type=float
.input_size = 80
.style = bold renderer:draw_resolution_widget noauto
.expert_level = 0
low_resolution = None
.type=float
.input_size = 80
.style = bold renderer:draw_resolution_widget noauto
.expert_level = 0
outliers_rejection = True
.type=bool
.short_caption = Reject outliers
.help = Remove "basic wilson outliers", "extreme wilson outliers", and \
"beamstop shadow outliers"
.expert_level = 0
french_wilson_scale = True
.type=bool
.short_caption = use French-Wilson method to handle negative intensities
french_wilson
{
include scope cctbx.french_wilson.master_phil
}
sigma_fobs_rejection_criterion = None
.type=float
.short_caption = Sigma(Fobs) rejection criterion
.expert_level = 0
sigma_iobs_rejection_criterion = None
.type=float
.short_caption = Sigma(Iobs) rejection criterion
.expert_level = 0
"""
data_and_flags_str_part2 = """\
file_name = None
.type=path
.short_caption=File with R(free) flags
.help = This is normally the same as the file containing Fobs and is \
usually selected automatically.
.input_size = 200
.style = noauto input_file file_type:hkl process_hkl child:rfree:label
.expert_level = 0
label = None
.type=str
.short_caption = R-free label
.input_size = 160
.style = bold renderer:draw_rfree_label_widget noauto \
OnChange:update_rfree_flag_value
.expert_level = 0
test_flag_value = None
.type=int
.help = This value is usually selected automatically - do not change \
unless you really know what you're doing!
.style = noauto
.expert_level = 0
ignore_r_free_flags = False
.type=bool
.short_caption = Ignore R-free flags
.help = Use all reflections in refinement (work and test)
.expert_level=0
"""
data_and_flags_str = """\
%s
ignore_all_zeros = True
.type=bool
.short_caption = Ignore all-zero arrays
.expert_level = 1
force_anomalous_flag_to_be_equal_to = None
.type=bool
.short_caption = Use anomalous data
.style = tribool
.expert_level = 1
convert_to_non_anomalous_if_ratio_pairs_lone_less_than_threshold=0.5
.type = float
.expert_level = 2
r_free_flags
.expert_level=0
.style = box auto_align
.caption = This information will be extracted automatically if possible. \
If no test set is present in the reflections file, one can be generated \
automatically, or you can use the reflection file editor to combine an \
existing set with your X-ray or neutron data.
{
%s
disable_suitability_test = False
.type=bool
.expert_level = 2
ignore_pdb_hexdigest = False
.type=bool
.short_caption = Ignore PDB hexdigest sanity check
.help=If True, disables safety check based on MD5 hexdigests stored in \
PDB files produced by previous runs.
.expert_level=2
generate = False
.type=bool
.short_caption = Generate new R-free flags
.help = Generate R-free flags (if not available in input files)
%s
}
""" % (data_and_flags_str_part1,
data_and_flags_str_part2,
miller.generate_r_free_params_str)
xray_data_str = """\
xray_data
.help=Scope of X-ray data and free-R flags
.style = scrolled auto_align
{
%s
}
"""%data_and_flags_str
neutron_data_str = """\
neutron_data
.help=Scope of neutron data and neutron free-R flags
.style = scrolled auto_align
{
ignore_xn_free_r_mismatch = False
.type = bool
.expert_level=2
.short_caption = Ignore Xray/neutron R-free flags set mismatch
%s
}
"""%data_and_flags_str
def data_and_flags_master_params(master_scope_name=None):
if(master_scope_name is not None):
p = """\
%s
{
%s
}
"""
return iotbx.phil.parse(p%(master_scope_name, data_and_flags_str), process_includes=True)
else:
return iotbx.phil.parse(data_and_flags_str, process_includes=True)
class determine_data_and_flags(object):
"""
Encapsulates logic for extracting experimental amplitudes and R-free flags
from the given input file(s). This expects that the standard parameter block
is being used. Determination of appropriate data labels will be as automatic
as possible, or will give clear feedback when ambiguity exists. If not
found in the inputs, the R-free flags can be created if desired.
"""
def __init__(self, reflection_file_server,
parameters = None,
data_parameter_scope = "",
flags_parameter_scope = "",
data_description = None,
working_point_group = None,
symmetry_safety_check = None,
remark_r_free_flags_md5_hexdigest = None,
extract_r_free_flags = True,
keep_going = False,
log = None,
prefer_anomalous = None,
force_non_anomalous = False):
adopt_init_args(self, locals())
if(self.parameters is None):
self.parameters = data_and_flags_master_params().extract()
self.intensity_flag = False
self.f_obs = None
self.r_free_flags = None
self.test_flag_value = None
self.r_free_flags_md5_hexdigest = None
if(data_description is not None):
print_statistics.make_header(data_description, out = log)
self.raw_data = self.extract_data()
data_info = self.raw_data.info()
self.f_obs = self.data_as_f_obs(f_obs = self.raw_data)
self.f_obs.set_info(data_info)
if(extract_r_free_flags):
self.raw_flags = self.extract_flags(data = self.raw_data)
if(self.raw_flags is not None):
flags_info = self.raw_flags.info()
if(extract_r_free_flags and self.raw_flags is not None):
self.get_r_free_flags()
self.r_free_flags.set_info(flags_info)
def get_r_free_flags(self):
self.r_free_flags,self.test_flag_value,self.r_free_flags_md5_hexdigest =\
self.flags_as_r_free_flags(f_obs = self.f_obs, r_free_flags =
self.raw_flags)
self.r_free_flags.set_info(self.raw_flags.info())
def extract_data(self):
data = self.reflection_file_server.get_xray_data(
file_name = self.parameters.file_name,
labels = self.parameters.labels,
ignore_all_zeros = self.parameters.ignore_all_zeros,
parameter_scope = self.data_parameter_scope,
prefer_anomalous = self.prefer_anomalous)
self.parameters.file_name = data.info().source
self.parameters.labels = [data.info().label_string()]
if(data.is_xray_intensity_array()):
print >> self.log, "I-obs:"
self.intensity_flag = True
else:
print >> self.log, "F-obs:"
print >> self.log, " ", data.info()
if([self.data_description, self.working_point_group,
self.symmetry_safety_check].count(None) == 0):
miller_array_symmetry_safety_check(
miller_array = data,
data_description = self.data_description,
working_point_group = self.working_point_group,
symmetry_safety_check = self.symmetry_safety_check,
log = self.log)
print >> self.log
info = data.info()
processed = data.eliminate_sys_absent(log = self.log)
if(processed is not data):
info = info.customized_copy(systematic_absences_eliminated = True)
if(not processed.is_unique_set_under_symmetry()):
if(data.is_xray_intensity_array()):
print >> self.log, "Merging symmetry-equivalent intensities:"
else:
print >> self.log, "Merging symmetry-equivalent amplitudes:"
merged = processed.merge_equivalents()
merged.show_summary(out = self.log, prefix=" ")
print >> self.log
processed = merged.array()
info = info.customized_copy(merged=True)
if (self.force_non_anomalous) :
processed = processed.average_bijvoet_mates()
return processed.set_info(info)
def extract_flags(self, data, data_description = "R-free flags"):
r_free_flags, test_flag_value = None, None
params = self.parameters.r_free_flags
if(not self.parameters.r_free_flags.generate):
try:
r_free_flags, test_flag_value = \
self.reflection_file_server.get_r_free_flags(
file_name = params.file_name,
label = params.label,
test_flag_value = params.test_flag_value,
disable_suitability_test = params.disable_suitability_test,
parameter_scope = self.flags_parameter_scope)
except reflection_file_utils.Sorry_No_array_of_the_required_type, e:
if(self.parameters.r_free_flags.generate is not None):
explain_how_to_generate_array_of_r_free_flags(log = self.log,
flags_parameter_scope = self.flags_parameter_scope)
if(self.keep_going): return None
raise Sorry("Please try again.")
r_free_flags, test_flag_value = None, None
else:
params.file_name = r_free_flags.info().source
params.label = r_free_flags.info().label_string()
params.test_flag_value = test_flag_value
print >> self.log, data_description+":"
print >> self.log, " ", r_free_flags.info()
if([self.working_point_group,
self.symmetry_safety_check].count(None) == 0):
miller_array_symmetry_safety_check(
miller_array = r_free_flags,
data_description = data_description,
working_point_group = self.working_point_group,
symmetry_safety_check = self.symmetry_safety_check,
log = self.log)
print >> self.log
info = r_free_flags.info()
processed = r_free_flags.eliminate_sys_absent(log = self.log)
if(processed is not r_free_flags):
info = info.customized_copy(systematic_absences_eliminated = True)
if(not processed.is_unique_set_under_symmetry()):
print >> self.log, \
"Checking symmetry-equivalent R-free flags for consistency:",
try:
merged = processed.merge_equivalents()
except RuntimeError, e:
print >> self.log
error_message = str(e)
expected_error_message = "cctbx Error: merge_equivalents_exact: "
assert error_message.startswith(expected_error_message)
raise Sorry("Incompatible symmetry-equivalent R-free flags: %s" %
error_message[len(expected_error_message):])
else:
print >> self.log, "OK"
print >> self.log
processed = merged.array()
info = info.customized_copy(merged=True)
del merged
if (self.force_non_anomalous) :
processed = processed.average_bijvoet_mates()
r_free_flags = processed.set_info(info)
if(r_free_flags is None):
if ((params.fraction is None) or
(params.lattice_symmetry_max_delta is None) or
(params.use_lattice_symmetry is None)) :
raise Sorry("No R-free flags are available, but one or more "+
"parameters required to generate new flags is undefined.")
print >> self.log, "Generating a new array of R-free flags."
print >> self.log
libtbx.call_back(message="warn",
data="PHENIX will generate a new array of R-free flags. Please "+
"check to make sure that the input data do not already contain "+
"an R-free set; if one is present, you should cancel this job and "+
"disable generation of new flags. If the program you are running "+
"outputs an MTZ file, you should be sure to use that file in all "+
"future refinements.")
r_free_flags = data.generate_r_free_flags(
fraction = params.fraction,
max_free = params.max_free,
lattice_symmetry_max_delta = params.lattice_symmetry_max_delta,
use_lattice_symmetry = params.use_lattice_symmetry,
use_dataman_shells = params.use_dataman_shells,
n_shells = params.n_shells
).set_info(miller.array_info(labels = ["R-free-flags"]))
params.label = r_free_flags.info().label_string()
params.test_flag_value = 1
# check if anomalous pairs are sound
if(r_free_flags is not None):
r_free_flags.deep_copy().as_non_anomalous_array()
return r_free_flags
def data_as_f_obs(self, f_obs):
"""
Convert input data array to amplitudes, adjusting the data type and
applying additional filters if necessary.
:param f_obs: selected input data
:returns: :py:class:`cctbx.miller.array` of real numbers with observation
type set to amplitudes
"""
if(not f_obs.sigmas_are_sensible()):
f_obs = f_obs.customized_copy(
indices=f_obs.indices(),
data=f_obs.data(),
sigmas=None).set_observation_type(f_obs)
# Delete F(0,0,0) if present
sel = f_obs.indices()==(0,0,0)
if(sel.count(True)>0):
print >> self.log, "F(0,0,0) will be removed."
f_obs = f_obs.select(~sel)
#
d_min = f_obs.d_min()
if(d_min < 0.25): # XXX what is the equivalent for neutrons ???
raise Sorry("Resolution of data is too high: %-6.4f A"%d_min)
f_obs.show_comprehensive_summary(f = self.log)
f_obs_data_size = f_obs.data().size()
print >> self.log
if(f_obs.is_complex_array()): f_obs = abs(f_obs)
f_obs_fw = None
if(f_obs.is_xray_intensity_array()):
if(self.parameters.french_wilson_scale) :
f_obs_fw = french_wilson.french_wilson_scale(
miller_array=f_obs,
params=self.parameters.french_wilson,
sigma_iobs_rejection_criterion=\
self.parameters.sigma_iobs_rejection_criterion,
log=self.log)
if f_obs_fw is not None:
f_obs = f_obs_fw
if (not self.parameters.french_wilson_scale or f_obs_fw is None) :
selection_by_isigma = self._apply_sigma_cutoff(
f_obs = f_obs,
n = self.parameters.sigma_iobs_rejection_criterion,
message = "Number of reflections with |Iobs|/sigma(Iobs) < %5.2f: %d")
if(selection_by_isigma is not None):
f_obs = f_obs.select(selection_by_isigma)
f_obs = f_obs.f_sq_as_f()
print >> self.log, \
"Intensities converted to amplitudes for use in refinement."
print >> self.log
#
sigmas = f_obs.sigmas()
if(sigmas is not None):
selection = sigmas > 0
selection &= f_obs.data()>=0
n_both_zero = selection.count(False)
if(n_both_zero>0):
print >> self.log, \
"Number of pairs (Fobs,sigma)=(0,0) is %s. They will be removed"%\
n_both_zero
f_obs = f_obs.select(selection)
#
f_obs.set_observation_type_xray_amplitude()
f_obs = f_obs.map_to_asu()
selection = f_obs.all_selection()
if(self.parameters.low_resolution is not None):
selection &= f_obs.d_spacings().data() <= self.parameters.low_resolution
if(self.parameters.high_resolution is not None):
selection &= f_obs.d_spacings().data() >= self.parameters.high_resolution
selection_positive = f_obs.data() >= 0
print >> self.log, \
"Number of F-obs in resolution range: ", \
selection.count(True)
print >> self.log, \
"Number of F-obs<0 (these reflections will be rejected):", \
selection_positive.count(False)
selection_zero = f_obs.data() == 0
print >> self.log, \
"Number of F-obs=0 (these reflections will be used in refinement):", \
selection_zero.count(True)
selection &= selection_positive
selection_by_fsigma = self._apply_sigma_cutoff(
f_obs = f_obs,
n = self.parameters.sigma_fobs_rejection_criterion,
message = "Number of reflections with |Fobs|/sigma(Fobs) < %5.2f: %d")
if(selection_by_fsigma is not None): selection &= selection_by_fsigma
selection &= f_obs.d_star_sq().data() > 0
f_obs = f_obs.select(selection)
rr = f_obs.resolution_range()
print >> self.log, "Refinement resolution range: d_max = %8.4f" % rr[0]
print >> self.log, " d_min = %8.4f" % rr[1]
print >> self.log
if(f_obs.indices().size() == 0):
raise Sorry(
"No data left after applying resolution limits and sigma cutoff.")
if(self.parameters.force_anomalous_flag_to_be_equal_to is not None):
if(not self.parameters.force_anomalous_flag_to_be_equal_to):
print >> self.log, "force_anomalous_flag_to_be_equal_to=False"
if(f_obs.anomalous_flag()):
print >> self.log, "Reducing data to non-anomalous array."
merged = f_obs.as_non_anomalous_array().merge_equivalents()
merged.show_summary(out = self.log, prefix=" ")
f_obs = merged.array().set_observation_type( f_obs )
del merged
print >> self.log
elif(not f_obs.anomalous_flag()):
print >> self.log, "force_anomalous_flag_to_be_equal_to=True"
print >> self.log, "Generating Bijvoet mates of X-ray data."
observation_type = f_obs.observation_type()
f_obs = f_obs.generate_bijvoet_mates()
f_obs.set_observation_type(observation_type)
print >> self.log
else:
f_obs = f_obs.convert_to_non_anomalous_if_ratio_pairs_lone_less_than(
threshold=self.parameters.
convert_to_non_anomalous_if_ratio_pairs_lone_less_than_threshold)
if(f_obs_data_size != f_obs.data().size()):
print >> self.log, "\nFobs statistics after all cutoffs applied:\n"
f_obs.show_comprehensive_summary(f = self.log)
return f_obs
def _apply_sigma_cutoff(self, f_obs, n, message):
selection = None
if(f_obs.sigmas() is not None):
sigma_cutoff = n
if(sigma_cutoff is not None and sigma_cutoff > 0):
selection_by_sigma = f_obs.data() > f_obs.sigmas()*sigma_cutoff
print >> self.log, message % (sigma_cutoff,
selection_by_sigma.count(False))
selection = selection_by_sigma
return selection
def flags_as_r_free_flags(self,
f_obs,
r_free_flags,
missing_show_max_lines=10):
test_flag_value = self.parameters.r_free_flags.test_flag_value
if (test_flag_value is None) :
raise Sorry(("PHENIX could not determine an appropriate test flag "+
"for the data with label(s) '%s'. This may happen if they are all "+
"a single value; please check the file to make sure the flags are "+
"suitable for use.") % self.parameters.r_free_flags.label)
r_free_flags.show_comprehensive_summary(f = self.log)
print >> self.log
print >> self.log, "Test (R-free flags) flag value:", test_flag_value
print >> self.log
if (isinstance(r_free_flags.data(), flex.bool)):
r_free_flags = r_free_flags.array(
data = r_free_flags.data() == bool(test_flag_value))
else:
r_free_flags = r_free_flags.array(
data = r_free_flags.data() == test_flag_value)
r_free_flags_md5_hexdigest = \
r_free_flags.map_to_asu().sort(by_value="packed_indices").data() \
.md5().hexdigest()
if(self.remark_r_free_flags_md5_hexdigest is not None):
self.verify_r_free_flags_md5_hexdigest(
ignore_pdb_hexdigest = self.parameters.r_free_flags.ignore_pdb_hexdigest,
current = r_free_flags_md5_hexdigest,
records = self.remark_r_free_flags_md5_hexdigest)
if(not f_obs.anomalous_flag()):
if(r_free_flags.anomalous_flag()):
print >> self.log, "Reducing R-free flags to non-anomalous array."
r_free_flags = r_free_flags.average_bijvoet_mates()
print >> self.log
elif(not r_free_flags.anomalous_flag()):
print >> self.log, "Generating Bijvoet mates of R-free flags."
r_free_flags = r_free_flags.generate_bijvoet_mates()
print >> self.log
r_free_flags = r_free_flags.map_to_asu().common_set(f_obs)
n_missing_r_free_flags = f_obs.indices().size() \
- r_free_flags.indices().size()
if(n_missing_r_free_flags != 0):
msg = [
"R-free flags not compatible with F-obs array:"
" missing flag for %d F-obs selected for refinement"
% n_missing_r_free_flags]
if (missing_show_max_lines is not None and missing_show_max_lines <= 0):
msg[0] += "."
else:
msg[0] += ":"
lone = f_obs.lone_set(other=r_free_flags)
if (missing_show_max_lines is None):
n_not_shown = 0
else:
n_not_shown = lone.indices().size() - missing_show_max_lines
if (n_not_shown > missing_show_max_lines * 0.5):
lone = lone[:missing_show_max_lines]
else:
n_not_shown = 0
if (lone.sigmas() is None):
msg.append(" h k l data")
for hkl,f in zip(lone.indices(), lone.data()):
msg.append(" %3d %3d %3d" % hkl + " %.6g" % f)
else:
msg.append(" h k l data sigmas")
for hkl,f,s in zip(lone.indices(), lone.data(), lone.sigmas()):
msg.append(" %3d %3d %3d" % hkl + " %.6g %.6g" % (f,s))
if (n_not_shown != 0):
msg.append(" ... (remaining %d not shown)" % n_not_shown)
raise Sorry("\n".join(msg))
r_free_flags.show_r_free_flags_info(out = self.log, prefix="")
return r_free_flags, test_flag_value, r_free_flags_md5_hexdigest
def verify_r_free_flags_md5_hexdigest(self,
ignore_pdb_hexdigest,
current,
records):
from_file = set()
for record in records:
flds = record.split()
if (len(flds) == 3):
from_file.add(flds[2])
if (len(from_file) > 1):
raise Sorry(
"Multiple conflicting REMARK r_free_flags.md5.hexdigest records"
" found in the input PDB file.")
if (len(from_file) == 1 and current not in from_file):
log = self.log
for i in xrange(2): print >> log, "*"*79
if (ignore_pdb_hexdigest):
print >> log
print >> log, " ".join(["WARNING"]*9)
print >> log, """
The MD5 checksum for the R-free flags array summarized above is:
%s
The corresponding MD5 checksum in the PDB file summarized above is:
%s
These checksums should be identical but are in fact different. This is
because the R-free flags used at previous stages of refinement are
different from the R-free flags summarized above. As a consequence,
the values for R-free could be biased and misleading.
However, there is no problem if the R-free flags were just extended to
a higher resolution, or if some reflections with no data or that are
not part of the R-free set have been added or removed.""" % (
current, sorted(from_file)[0]),
if (not ignore_pdb_hexdigest):
print >> log, """\
In this case,
simply remove the
REMARK r_free_flags.md5.hexdigest %s
record from the input PDB file to proceed with the refinement.""" % (
sorted(from_file)[0]),
print >> log, """
Otherwise it is best to recover the previously used R-free flags
and use them consistently throughout the refinement of the model.
Run this command again with the name of the file containing the
original flags as an additional input.
"""
if (not ignore_pdb_hexdigest):
print >> log, """\
If the original R-free flags are unrecoverable, remove the REMARK
record as indicated above. In this case the values for R-free will
become meaningful only after many cycles of refinement.
"""
else:
print >> log, """\
If the original R-free flags are unrecoverable, the values for R-free
will become meaningful only after many cycles of refinement.
"""
for i in xrange(2): print >> log, "*"*79
print >> log
if (not ignore_pdb_hexdigest):
if ("PHENIX_GUI_ENVIRONMENT" in os.environ) :
log.flush()
raise Sorry("This model appears to have previously been refined "+
"against a different set of R-free flags. Please resolve the "+
"mismatch; additional information and instructions are available "+
"at the end of the log output.")
else :
raise Sorry("Please resolve the R-free flags mismatch.")
map_coefficents_params_str = """\
file_name=None
.type=path
.short_caption=Map coefficients file
labels=None
.type=strings
"""
experimental_phases_params_str = """\
file_name=None
.type=path
.short_caption=Experimental phase file
.style = bold input_file file_type:hkl process_hkl child:hl_coeffs:labels
labels=None
.type=strings
.input_size = 160
.short_caption = Phase labels
.style = renderer:draw_hl_label_widget bold
"""
experimental_phases_params = iotbx.phil.parse(
input_string=experimental_phases_params_str)
def determine_experimental_phases(reflection_file_server,
parameters,
log,
parameter_scope,
working_point_group,
symmetry_safety_check,
ignore_all_zeros = True):
"""
Extract experimental phases from the given inputs if possible. Returns None
if not found.
"""
try:
experimental_phases = \
reflection_file_server.get_experimental_phases(
file_name = parameters.file_name,
labels = parameters.labels,
ignore_all_zeros = ignore_all_zeros,
parameter_scope = parameter_scope)
except reflection_file_utils.Sorry_No_array_of_the_required_type:
experimental_phases = None
else:
parameters.file_name = experimental_phases.info().source
parameters.labels = [experimental_phases.info().label_string()]
print >> log, "Experimental phases:"
print >> log, " ", experimental_phases.info()
miller_array_symmetry_safety_check(
miller_array = experimental_phases,
data_description = "Experimental phases",
working_point_group = working_point_group,
symmetry_safety_check = symmetry_safety_check,
log = log)
print >> log
info = experimental_phases.info()
processed = experimental_phases.eliminate_sys_absent(log = log)
if(processed is not experimental_phases):
info = info.customized_copy(systematic_absences_eliminated = True)
if(not processed.is_unique_set_under_symmetry()):
print >> log, \
"Merging symmetry-equivalent Hendrickson-Lattman coefficients:"
merged = processed.merge_equivalents()
merged.show_summary(out = log, prefix=" ")
print >> log
processed = merged.array()
info = info.customized_copy(merged = True)
return processed.set_info(info)
pdb_params = iotbx.phil.parse("""\
file_name=None
.optional=True
.type=path
.help=Model file(s) name (PDB)
.short_caption=Input model
.multiple=True
.input_size=400
.style = bold input_file file_type:pdb OnChange:extract_pdb_params \
file_type_default
""")
def find_overlapping_selections (selections, selection_strings) :
"""
Given a list of atom selections (:py:class:`scitbx.array_family.flex.bool`
arrays) and corresponding selection strings, inspect the selections to
determine whether any two arrays overlap. Returns a tuple of the first pair
of selection strings found to overlap, or None if all selections are unique.
"""
assert (len(selections) == len(selection_strings))
for i_sel in range(len(selections) - 1) :
selection1 = selections[i_sel]
for j_sel in range(i_sel + 1, len(selections)) :
selection2 = selections[j_sel]
if (isinstance(selection1, flex.bool)) :
joint_sel = selection1 & selection2
if (joint_sel.count(True) > 0) :
return (selection_strings[i_sel], selection_strings[j_sel])
else :
intersection = selection1.intersection(selection2)
if (len(intersection) > 0) :
return (selection_strings[i_sel], selection_strings[j_sel])
return None
def get_atom_selections(
model = None,
selection_strings = None,
iselection = True,
one_group_per_residue = False,
allow_empty_selection = False,
hydrogens_only = False,
one_selection_array = False,
parameter_name = None):
if(selection_strings is None or isinstance(selection_strings, str)):
selection_strings = [selection_strings]
elif (len(selection_strings) == 0):
selection_strings = [None]
n_none = selection_strings.count(None)
ss_size = len(selection_strings)
if((one_group_per_residue and n_none==0) or (ss_size > 1 and n_none > 0)):
raise Sorry('Ambiguous selection.') # XXX NEED MORE INFORMATIVE MESSAGE
selections = []
if(ss_size == 1 and n_none == 1 and not one_group_per_residue):
selections.append(flex.bool(model.get_number_of_atoms(), True))
elif(one_group_per_residue and ss_size == 1 and n_none == 1):
assert iselection
residues = []
hd_selection = None
if (hydrogens_only):
scat_types = model.get_xray_structure().scatterers().extract_scattering_types()
if not model.has_hd:
raise Sorry('No hydrogens to select.')
for m in model.get_hierarchy().models():
for chain in m.chains():
for rg in chain.residue_groups():
rg_i_seqs = []
for ag in rg.atom_groups():
for atom in ag.atoms():
i_seq = atom.i_seq
if ( not hydrogens_only
or scat_types[i_seq] in ["H", "D"]):
rg_i_seqs.append(atom.i_seq)
if (len(rg_i_seqs) != 0):
selections.append(flex.size_t(rg_i_seqs))
elif(ss_size != 1 or n_none == 0 and not one_group_per_residue):
for selection_string in selection_strings:
selections.append(atom_selection(model = model,
string = selection_string,
allow_empty_selection = allow_empty_selection))
else:
raise Sorry('Ambiguous selection.')
if(len(selections)>1):
if(not isinstance(selections[0], flex.bool)):
tmp = flex.bool(model.get_number_of_atoms(), selections[0]).as_int()
else:
tmp = selections[0].deep_copy().as_int()
for k_, tmp_s in enumerate(selections[1:]):
k = k_ + 1 # XXX Python 2.5 workaround
if(not isinstance(tmp_s, flex.bool)):
tmp = tmp + flex.bool(model.get_number_of_atoms(),tmp_s).as_int()
else:
tmp = tmp + tmp_s.as_int()
if(flex.max(tmp)>1):
sel1, sel2 = find_overlapping_selections(selections, selection_strings)
if (parameter_name is not None) :
raise Sorry("One or more overlapping selections for %s:\n%s\n%s" %
(parameter_name, sel1, sel2))
else :
raise Sorry("One or more overlapping selections:\n%s\n%s" %(sel1,sel2))
#
if(iselection):
for i_seq, selection in enumerate(selections):
if(hasattr(selection, "iselection")):
selections[i_seq] = selections[i_seq].iselection()
if(one_selection_array):
s0 = selections[0]
for s in selections[1:]:
if(not iselection):
s0 = s0 | s
else:
s0.extend(s)
selections = s0
if (iselection) :
selections = selections.select(flex.sort_permutation(selections))
return selections
def atom_selection(model, string, allow_empty_selection = False):
result = model.selection(
selstr=string,
optional=(allow_empty_selection is not None))
if (result is None):
return None
if (allow_empty_selection is not None):
if (not allow_empty_selection and result.all_eq(False)):
raise Sorry(
"Selection string results in empty selection (selects no atoms): %s"
% show_string(string))
return result
def print_programs_start_header(log, text):
print >> log
host_and_user().show(out= log)
print >> log, date_and_time()
print >> log
print >> log, "-"*79
print >> log, text
print >> log, "-"*79
print >> log
def set_log(args, out=sys.stdout, replace_stderr=True):
log = multi_out()
if(not "--quiet" in args):
log.register(label="stdout", file_object=out)
string_buffer = StringIO()
string_buffer_plots = StringIO()
log.register(label="log_buffer", file_object=string_buffer)
if (replace_stderr) :
sys.stderr = log
return log
def print_header(line, out=None):
str_utils.make_header(line, out=out)
def get_atom_selection(pdb_file_name, selection_string, iselection = False):
import mmtbx.model
model = mmtbx.model.manager(
model_input = iotbx.pdb.input(file_name=pdb_file_name),
process_input = True)
result = get_atom_selections(
model = model,
selection_strings = [selection_string],
iselection = iselection)
assert len(result) == 1
return result[0]
cif_params = iotbx.phil.parse("""\
file_name=None
.optional=True
.type=path
.help=Monomer file(s) name (CIF)
.multiple=True
.short_caption=Restraints (CIF)
.input_size = 400
.style = bold input_file file_type:cif
""")
class process_pdb_file_srv(object):
def __init__(self, crystal_symmetry = None,
pdb_parameters = None,
pdb_interpretation_params = None,
stop_for_unknowns = None,
log = None,
cif_objects = None,
cif_parameters = None,
mon_lib_srv = None,
ener_lib = None,
use_neutron_distances = False):
self.raw_records = None
self.crystal_symmetry = crystal_symmetry
self.pdb_parameters = pdb_parameters
self.pdb_interpretation_params = pdb_interpretation_params
if self.pdb_interpretation_params is None:
ppdb_interpretation_params = iotbx.phil.parse(
input_string=mmtbx.monomer_library.pdb_interpretation.grand_master_phil_str,
process_includes=True).extract()
self.pdb_interpretation_params = ppdb_interpretation_params.pdb_interpretation
self.stop_for_unknowns = stop_for_unknowns
self.cif_objects = cif_objects
self.cif_parameters = cif_parameters
self.log = log
self.use_neutron_distances = use_neutron_distances
if(mon_lib_srv is None): self.mon_lib_srv = monomer_library.server.server()
else: self.mon_lib_srv = mon_lib_srv
if(ener_lib is None):
self.ener_lib = monomer_library.server.ener_lib(
use_neutron_distances=use_neutron_distances,
)
else: self.ener_lib = ener_lib
if(self.log is None): self.log = sys.stdout