-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython.snippets
1140 lines (964 loc) · 40.8 KB
/
python.snippets
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
snippet millerMtzImports "Read a mtz file into a miller array." b
from iotbx.reflection_file_reader import any_reflection_file
hkl_file = any_reflection_file("${1:3hz7.mtz}")
miller_arrays = hkl_file.as_miller_arrays(merge_equivalents=False)
$0
endsnippet
snippet millerArrayLabels "Print column labels in a Miller array." b
[print("Miller Array %s: %s" % (i, miller_array.info().labels)) for i, miller_array in list(enumerate(miller_arrays))[:2]]
$0
endsnippet
snippet millerArrayWavelengths "Print wavelengths of each miller array." b
[print("Miller Array %s: %s" % (i, miller_array.info().wavelength)) for i, miller_array in list(enumerate(miller_arrays))]
$0
endsnippet
snippet millerArraySources "Print the source of each miller array." b
print("Miller Array %s: %s" % (i, miller_array.info().source)) for i, miller_array in list(enumerate(miller_arrays))]
$0
endsnippet
snippet millerArrayLengths "Print length of miller arrays (i.e., the number of datasets in a mtz file)." b
len(miller_arrays)
$0
endsnippet
snippet millerArraySymmetry "Print the crystal symmetry of each miller array." b
[print("Miller Array %s: %s" % (i, miller_array.info().crystal_symmetry_from_file)) for i, miller_array in list(enumerate(miller_arrays))]
$0
endsnippet
snippet millerArrayHKLs "Print all of the miller indices for a given Miller array." b
[print(hkl) for hkl in miller_arrays[${1:0}].indices()]
$0
endsnippet
snippet millerArrayMethods "Print the available methods for the Miller class." b
dir(miller_arrays[${1:0}])
$0
endsnippet
snippet millerArraydstar "Return the resolution range in d* in a specified Miller array." b
miller_arrays[${1:0}].min_max_d_star_sq()
$0
endsnippet
snippet millerArrayDminDmax "Return the resolution range in Angstroms for a Miller array." b
miller_arrays[${1:0}].d_max_min()
$0
endsnippet
snippet millerArrayIsigma
"Return the I/sig overall for a given Miller array." b
miller_arrays[${1:0}].i_over_sig_i()
$0
endsnippet
snippet millerArrayCC "Return CC one-half sigma tau for a given Miller array." b
miller_arrays[${1:0}].cc_one_half_sigma_tau()
$0
endsnippet
snippet millerArrayCConeHalf "Return CC one-half for a given Miller array. " b
miller_arrays[${1:0}].cc_one_half()
$0
endsnippet
snippet millerArrayBijvoetRatios "Print the Bijvoet ratios in a specified Miller array. May have to average by bin first." b
[print(i) for i in miller_arrays[${1:0}].bijvoet_ratios()]
$0
endsnippet
snippet millerArrayMeasurability "Return the `measurability` of the anomalous signal in a specified Miller array." b
miller_arrays[${1:0}].measurability()
$0
endsnippet
snippet millerArrayAnomalousSignal "Return the anomalous signal in a specified Miller array." b
miller_arrays[${1:0}].anomalous_signal()
$0
endsnippet
snippet millerArrayComprehensiveSummary "Show comprehensive summary for a specified Miller array. " b
miller_arrays[${1:0}].show_comprehensive_summary()
$0
endsnippet
snippet millerArrayCountBijvoetPairs "Show number of bijvoet pairs for a specified Miller array." b
miller_arrays[${1:0}].n_bijvoet_pairs()
$0
endsnippet
snippet millerArrayWilsonRatio "Show wilson ratio of miller array for a specified Miller array. " b
miller_arrays[${1:0}].wilson_ratio()
$0
endsnippet
snippet millerArrayUnpackIpIn "Unpack into I(+) and I(-) for a specified Miller array. " b
Iobs = miller_arrays[${1:0}]
i_plus, i_minus = Iobs.hemispheres_acentrics()
ipd = i_plus.data()
ip=list(ipd)
imd = i_minus.data()
im = list(imd)
len(im)
Iobs.show_summary()
print(Iobs.info())
print(Iobs.observation_type())
$0
endsnippet
snippet millerArrayPrintSelectRows "Print five rows of the Iobs for a specified Miller array. " b
list(Iobs[${1:100:105}])
$0
endsnippet
snippet millerArrayExtractIntensities "Extract just the intensities for a give Miller array and print ten rows of them." b
Iobs = miller_arrays[${1:0}]
iobsdata = Iobs.data()
list(iobsdata[${1:100:110}])
$0
endsnippet
snippet millerArrayPrintntensities "Print all of the intensities for a given Miller array." b
[print(hkl) for hkl in miller_arrays[1].data()]
$0
endsnippet
snippet millerArrayconvert2mtz "Convert the miller array into a mtz_dataset and write out as a mtz file." b
# Convert the miller array into a mtz_dataset and write out as a mtz file.
mtz_dataset = Iobs.as_mtz_dataset(column_root_label="${1:I}")
mtz_dataset.mtz_object().write("${2:3hz7intensities}.mtz")
$0
endsnippet
snippet millerArrayReadMtz "Read in the mtz file and print its column labels as a sanity check." b
mtz_filename2 = "${1:3hz7intensities}.mtz"
mtz_file2 = mtz.object(mtz_filename2)
mtz_file2.column_labels()
$0
endsnippet
snippet millerArray2Dictionary "Set up the arrays as dictionaries" b
from iotbx import mtz
mtz_obj = mtz.object(file_name="${1:3nd4}.mtz")
# Only works with mtz.object.
# Does not work if mtz is read in with iotbx.file_reader.
miller_arrays_dict = mtz_obj.as_miller_arrays_dict()
$0
endsnippet
snippet millerArrayDictionaryKeys "Print the miller keys() of a miller dictionary." b
miller_arrays_dict.keys()
$0
endsnippet
snippet millerArrayDictPrintColumns "Print the column labels of Miller dictionary." b
from iotbx import mtz
mtz_obj = mtz.object(file_name="${1:/Users/blaine/3nd4.mtz}")
# Only works with mtz.object. Does not work if mtz is read in with iotbx.file_reader.
miller_arrays_dict = mtz_obj.as_miller_arrays_dict()
[print(f"Column label: {key[2]}") for key in miller_arrays_dict.keys()]
$0
endsnippet
snippet millerArrayBuildFromUnitCell "Peter Zwart's code for generating the indices for unit cell of given symmetry and dimensions. " b
from cctbx import miller
import cctbx
from cctbx import crystal
ms = miller.build_set(
crystal_symmetry=crystal.symmetry(
space_group_symbol="${1:Fd-3m}",
unit_cell=(${2:5.4307,5.4307,5.4307,90.00,90.0,90.00})),
anomalous_flag=${3:True},
d_min=${4:0.4})
[print(hkl) for hkl in ms.indices()]
$0
endsnippet
snippet millerArrayMapToASU "Map generated reflections to the asu and print." b
from cctbx import miller
import cctbx
from cctbx import crystal
ms = miller.build_set(
crystal_symmetry=crystal.symmetry(
space_group_symbol="${1:Fd-3m}",
unit_cell=(${2:5.4307,5.4307,5.4307,90.00,90.0,90.00})),
anomalous_flag=${3:True},
d_min=${4:0.4})
msu = ms.map_to_asu()
[print(hkl2) for hkl2 in msu.indices()]
$0
endsnippet
snippet millerArrayPrintSummary "Read mtz file into a miller array and print summary." b
from iotbx.reflection_file_reader import any_reflection_file
hkl_in = any_reflection_file(file_name="${1:3nd4}.mtz")
miller_arrays = hkl_in.as_miller_arrays()
f_obs = miller_arrays[0]
f_obs.show_summary()
$0
endsnippet
snippet mtzObjectSummary "Read mtz file into a mtz object and print summary." b
from iotbx import mtz
mtz_obj = mtz.object(file_name="/Users/blaine/${1:3nd4}.mtz")
mtz_obj.show_summary()
$0
endsnippet
snippet millerArrayFromMtz "Read mtz file into a Miller array." b
from iotbx import mtz
mtz_obj = mtz.object(file_name="${1:3nd4}.mtz")
miller_arrays = mtz_obj.as_miller_arrays()
$0
endsnippet
snippet millerArrayTruncate "Read mtz file into a Miller array, truncate, and print summary." b
from iotbx import mtz
mtz_obj = mtz.object(file_name="${1:3nd4}.mtz")
miller_arrays = mtz_obj.as_miller_arrays()
miller_array_truncated = miller_arrays[0].resolution_filter(d_min=${2:2}, d_max=${3:5})
print(miller_array_truncated)
miller_array_truncated.show_summary()
$0
endsnippet
snippet millerArrayDictColumnLabels "Print column labels of a Miller array dictionary." b
[print(f"Column label: {key[2]}") for key in miller_arrays_dict.keys()]
$0
endsnippet
snippet condaInstall "The conda commands to install cctbx with the jupyter notebook, pandas, and xarray." b
conda create --name ${1:cctbx37} python=${2:3.7}
conda activate ${1:cctbx37}
conda install -c conda-forge cctbx-base jupyter pandas xarray
$0
endsnippet
snippet condaRemove "The conda commands to remove cctbx37 env." b
conda remove --name ${1:cctbx37}
endsnippet
snippet fetchPDB "Fetch pdb file from RCSB in PDB format." b
from iotbx.pdb.fetch import get_pdb
import sys
get_pdb(id="${1:3nd4}",data_type="pdb", mirror="rcsb", format="pdb", log=sys.stdout)
$0
endsnippet
snippet updateCLT "Update the command line tools for Xcode on Mac OS X. " b
sudo touch /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
softwareupdate -l
# Update command line tools via software update.
sudo rm /tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress
endsnippet
snippet extractCrystalSymmetry "Extract crystal symmetry from mtz file." b
from __future__ import absolute_import, division, print_function
from iotbx import mtz
from cctbx import crystal
def extract_from(file_name):
mtz_object = mtz.object(file_name=file_name)
assert mtz_object.n_symmetry_matrices() > 0
return mtz_object.crystals()[0].crystal_symmetry()
extract_from(file_name="${1:3nd4}.mtz")
$0
endsnippet
snippet plotDstarsLogMeans "Generate the list of dstars and logMeans as lists for plotting by matplotlib." b
'''Generate the list of dstars and logMeans as lists
for plotting by matplotlib.'''
used = list(binner.range_used())
selections = [binner.selection(i) for i in used]
# make means of the intensities by bin
means = [Iobs.select(sel).mean() for sel in selections]
from math import log
lnmeans = [log(y) for y in means]
# meansBR = [Iobs.bijvoet_ratios().select(sel).mean() for sel in selections]
# make d_centers
d_star_power = 1.618034
centers = binner.bin_centers(d_star_power)
d_centers = list(centers**(-1 / d_star_power))
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams["savefig.dpi"] = 600
mpl.rcParams["figure.dpi"] = 600
fig, ax = plt.subplots(figsize=[3.25, 2.])
ax.scatter(d_centers,lnmeans,c="k",alpha=0.3,s=5.5)
ax.set_xlim(${1:8, 1.5}) # decreasing time
ax.set_xlabel(r"$d^*$ in $\AA$",fontsize=12)
ax.set_ylabel("ln(I)",fontsize=12)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
ax.grid(False)
plt.savefig("${2:3hz7}iobsvsdstar.pdf",bbox_inches="tight")
plt.show()
$0
endsnippet
snippet plotDstarsMeasurability "Generate the list of dstars and measurability as lists for plotting by matplotlib." b
from iotbx.reflection_file_reader import any_reflection_file
hkl_file = any_reflection_file("${1:3hz7}.mtz")
miller_arrays = hkl_file.as_miller_arrays(merge_equivalents=False)
Iobs = miller_arrays[1]
# Set up the bins
n_bins = 50
binner = Iobs.setup_binner(n_bins=n_bins)
# binner.show_summary()
used = list(binner.range_used())
selections = [binner.selection(i) for i in used]
# make d_centers for the x-axis
d_star_power = 1.618034
centers = binner.bin_centers(d_star_power)
d_centers = list(centers**(-1 / d_star_power))
# make list of the measurabilities by resolution bin
meas = [Iobs.select(sel).measurability() for sel in selections]
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams["savefig.dpi"] = 600
mpl.rcParams["figure.dpi"] = 600
fig, ax = plt.subplots(figsize=[3.25, 2.])
ax.scatter(d_centers,lnmeans,c="k",alpha=0.3,s=5.5)
ax.set_xlim(8, 1.5) # decreasing time
ax.set_xlabel(r"$d^*$ in $\AA$",fontsize=12)
ax.set_ylabel("ln(I)",fontsize=12)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
ax.grid(False)
plt.savefig("${1:3hz7}measureability.pdf",bbox_inches="tight")
plt.show()
$0
endsnippet
snippet computeAllMillerIndices "Compute all possible Miller indices." b
from cctbx import miller
def generate_reflection_indices(uc, dmin):
maxh, maxk, maxl = uc.max_miller_indices(dmin)
indices = []
for h in range(-maxh, maxh + 1):
for k in range(-maxk, maxk + 1):
for l in range(-maxl, maxl + 1):
if h == 0 and k == 0 and l == 0:
continue
if uc.d((h, k, l)) < dmin:
continue
indices.append((h, k, l))
return indices
uc=(${1:5.4307,5.4307,5.4307,90.00,90.0,90.00})
dmin=${2:1.0}
$0
endsnippet
snippet computeAllMillerIndicesASU "Compute all possible Miller indices in the ASU." b
from cctbx import miller
import cctbx
from cctbx import crystal
ms = miller.build_set(
crystal_symmetry=crystal.symmetry(
space_group_symbol="${1:Fd-3m}",
unit_cell=("${2:5.4307,5.4307,5.4307,90.00,90.0,90.00}") ),
anomalous_flag=${3:False},
d_min=${4:0.4})
for hkl in ms.indices():
print(hkl)
# map the reflections to the asu and print
msu = ms.map_to_asu()
[print(hkl2) for hkl2 in msu.indices()]
$0
endsnippet
snippet computeAllMillerIndicesUnitCell "Build miller indices given unit cell and resolution limit." b
from cctbx import crystal
from cctbx import miller
ms = miller.build_set(
crystal_symmetry=crystal.symmetry(
space_group_symbol="${1:P4}",
unit_cell=(${2:150.8,150.8,250.4,90.0,90.0,90.0})),
anomalous_flag=${3:False},
d_min=${4:1.4})
msu = ms.map_to_asu()
[print(hkl) for hkl in msu.indices()]
print(msu.show_comprehensive_summary())
$0
endsnippet
snippet extractReflectionMtzFile "Extract the reflections from a mtz file." b
from iotbx import mtz
mtz_obj = mtz.object(file_name="${1:Users/blaine/manuscripts/RETkinaseLoxo/ret_blu.mtz}")
mtz_obj.show_summary()
$0
endsnippet
snippet extractReflectionInShell "Extract the reflections in a shell." b
from iotbx import mtz
mtz_obj = mtz.object(file_name="${1:2V89}.mtz")
miller_arrays = mtz_obj.as_miller_arrays()
for miller_array in miller_arrays:
miller_array_truncated = miller_array.resolution_filter(d_min=${2:2}, d_max=${3:5})
print(miller_array_truncated)
$0
endsnippet
snippet plotRfactorResolutionBin "Read in a phenix.refine mtz file. It plots the work and free R-factors by resolution bin." b
#!/usr/bin/env python
# coding: utf-8
'''
This script reads in a phenix.refine mtz file.
It plots the R-factor by resolution bin.
The plots are made with matplotlib using miller arrays.
It also plots the correlation coefficients.
The plots were made with matplotlib.
This script was adapted from an example script in iotbx:
Source: https://github.com/cctbx/cctbx_project/blob/master/
iotbx/examples/recalculate_phenix_refine_r_factors.py
'''
# get_ipython().run_line_magic("matplotlib", "inline")
from __future__ import absolute_import, division, print_function
from iotbx.reflection_file_utils import get_r_free_flags_scores
from iotbx.file_reader import any_file
import matplotlib
import matplotlib.pyplot as plt
def compute_r_factors(fobs, fmodel, flags):
fmodel, fobs = fmodel.common_sets(other=fobs)
fmodel, flags = fmodel.common_sets(other=flags)
fc_work = fmodel.select(~(flags.data()))
fo_work = fobs.select(~(flags.data()))
fc_test = fmodel.select(flags.data())
fo_test = fobs.select(flags.data())
r_work = fo_work.r1_factor(fc_work)
r_free = fo_test.r1_factor(fc_test)
print("r_work = %.4f" % r_work)
print("r_free = %.4f" % r_free)
print("")
binner = flags.setup_binner(n_bins=20)
d_star_power = 1.618034
centers = binner.bin_centers(d_star_power)
d_centers = list(centers**(-1 / d_star_power))
# for i in d_centers:
# print(i)
fo_work.use_binning_of(flags)
fc_work.use_binner_of(fo_work)
fo_test.use_binning_of(fo_work)
fc_test.use_binning_of(fo_work)
r_work_list = []
r_free_list = []
cc_work_list = []
cc_free_list = []
for i_bin in fo_work.binner().range_all():
sel_work = fo_work.binner().selection(i_bin)
sel_test = fo_test.binner().selection(i_bin)
fo_work_bin = fo_work.select(sel_work)
fc_work_bin = fc_work.select(sel_work)
fo_test_bin = fo_test.select(sel_test)
fc_test_bin = fc_test.select(sel_test)
if fc_test_bin.size() == 0 : continue
r_work_bin = fo_work_bin.r1_factor(other=fc_work_bin,
assume_index_matching=True)
r_work_list.append(r_work_bin)
r_free_bin = fo_test_bin.r1_factor(other=fc_test_bin,
assume_index_matching=True)
r_free_list.append(r_free_bin)
cc_work_bin = fo_work_bin.correlation(fc_work_bin).coefficient()
cc_work_list.append(cc_work_bin)
cc_free_bin = fo_test_bin.correlation(fc_test_bin).coefficient()
cc_free_list.append(cc_free_bin)
legend = flags.binner().bin_legend(i_bin, show_counts=False)
print("%s %8d %8d %.4f %.4f %.3f %.3f" % (legend, fo_work_bin.size(),
fo_test_bin.size(), r_work_bin, r_free_bin, cc_work_bin, cc_free_bin))
return d_centers, r_work_list, r_free_list, cc_work_list, cc_free_list
def plot_r_factors(d_centers, r_work_list, r_free_list):
plt.scatter(d_centers, r_work_list, label=r"$\mathit{R_{work}}$")
plt.scatter(d_centers, r_free_list, label=r"$\mathit{R_{free}}$")
plt.xlabel(r"Resolution ($\mathrm{\AA}$)")
plt.ylabel(r"R-factor (%)")
plt.legend(loc="upper right")
plt.savefig("Rs.pdf")
plt.close()
def plot_cc(d_centers, cc_work_list, cc_free_list):
plt.scatter(d_centers, cc_work_list, label=r"$\mathit{CC_{work}}$")
plt.scatter(d_centers, cc_free_list, label=r"$\mathit{CC_{free}}$")
plt.xlabel(r"Resolution ($\mathrm{\AA}$)")
plt.ylabel(r"Correlation Coefficeint Fo vs Fc (%)")
plt.legend(loc="lower right")
plt.savefig("CCs.pdf")
def run(input_mtz):
mtz_in = any_file(input_mtz)
ma = mtz_in.file_server.miller_arrays
flags = fmodel = fobs = None
# select the output arrays from phenix.refine. This could easily be modified
# to handle MTZ files from other programs.
for array in ma :
labels = array.info().label_string()
if labels.startswith("R-free-flags"):
flags = array
elif labels.startswith("F-model"):
fmodel = abs(array)
elif labels.startswith("F-obs-filtered"):
fobs = array
if (None in [flags, fobs, fmodel]):
raise RuntimeError("Not a valid phenix.refine output file")
scores = get_r_free_flags_scores([flags], None)
test_flag_value = scores.test_flag_values[0]
flags = flags.customized_copy(data=flags.data()==test_flag_value)
(d_centers,
r_work_list,
r_free_list,
cc_work_list,
cc_free_list) = compute_r_factors(fobs, fmodel, flags)
plot_r_factors(d_centers, r_work_list, r_free_list)
plot_cc(d_centers, cc_work_list, cc_free_list)
if (__name__ == "__main__"):
run(input_mtz="${1:28molrepEdited_5_refine_001}.mtz")
$0
endsnippet
snippet plotFcalcsrResolutionBin "Example of computing Fcalcs and then plotting them by resolution bin. This script uses miller arrays and binner." b
'''
This script reads in a phenix.refine mtz file.
It plots the R-factor by resolution bin.
The plots are made with matplotlib using miller arrays.
It also plots the correlation coefficients.
The plots were made with matplotlib.
This script was adapted from an example script in iotbx:
Source: https://github.com/cctbx/cctbx_project/blob/master/
iotbx/examples/recalculate_phenix_refine_r_factors.py
'''
# get_ipython().run_line_magic("matplotlib", "inline")
from __future__ import absolute_import, division, print_function
from iotbx.reflection_file_utils import get_r_free_flags_scores
from iotbx.file_reader import any_file
import matplotlib
import matplotlib.pyplot as plt
def compute_r_factors(fobs, fmodel, flags):
fmodel, fobs = fmodel.common_sets(other=fobs)
fmodel, flags = fmodel.common_sets(other=flags)
fc_work = fmodel.select(~(flags.data()))
fo_work = fobs.select(~(flags.data()))
fc_test = fmodel.select(flags.data())
fo_test = fobs.select(flags.data())
r_work = fo_work.r1_factor(fc_work)
r_free = fo_test.r1_factor(fc_test)
print("r_work = %.4f" % r_work)
print("r_free = %.4f" % r_free)
print("")
binner = flags.setup_binner(n_bins=20)
d_star_power = 1.618034
centers = binner.bin_centers(d_star_power)
d_centers = list(centers**(-1 / d_star_power))
# for i in d_centers:
# print(i)
fo_work.use_binning_of(flags)
fc_work.use_binner_of(fo_work)
fo_test.use_binning_of(fo_work)
fc_test.use_binning_of(fo_work)
r_work_list = []
r_free_list = []
cc_work_list = []
cc_free_list = []
for i_bin in fo_work.binner().range_all():
sel_work = fo_work.binner().selection(i_bin)
sel_test = fo_test.binner().selection(i_bin)
fo_work_bin = fo_work.select(sel_work)
fc_work_bin = fc_work.select(sel_work)
fo_test_bin = fo_test.select(sel_test)
fc_test_bin = fc_test.select(sel_test)
if fc_test_bin.size() == 0 : continue
r_work_bin = fo_work_bin.r1_factor(other=fc_work_bin,
assume_index_matching=True)
r_work_list.append(r_work_bin)
r_free_bin = fo_test_bin.r1_factor(other=fc_test_bin,
assume_index_matching=True)
r_free_list.append(r_free_bin)
cc_work_bin = fo_work_bin.correlation(fc_work_bin).coefficient()
cc_work_list.append(cc_work_bin)
cc_free_bin = fo_test_bin.correlation(fc_test_bin).coefficient()
cc_free_list.append(cc_free_bin)
legend = flags.binner().bin_legend(i_bin, show_counts=False)
print("%s %8d %8d %.4f %.4f %.3f %.3f" % (legend, fo_work_bin.size(),
fo_test_bin.size(), r_work_bin, r_free_bin, cc_work_bin, cc_free_bin))
return d_centers, r_work_list, r_free_list, cc_work_list, cc_free_list
def plot_r_factors(d_centers, r_work_list, r_free_list):
plt.scatter(d_centers, r_work_list, label=r"$\mathit{R_{work}}$")
plt.scatter(d_centers, r_free_list, label=r"$\mathit{R_{free}}$")
plt.xlabel(r"Resolution ($\mathrm{\AA}$)")
plt.ylabel(r"R-factor (%)")
plt.legend(loc="upper right")
plt.savefig("Rs.pdf")
plt.close()
def plot_cc(d_centers, cc_work_list, cc_free_list):
plt.scatter(d_centers, cc_work_list, label=r"$\mathit{CC_{work}}$")
plt.scatter(d_centers, cc_free_list, label=r"$\mathit{CC_{free}}$")
plt.xlabel(r"Resolution ($\mathrm{\AA}$)")
plt.ylabel(r"Correlation Coefficeint Fo vs Fc (%)")
plt.legend(loc="lower right")
plt.savefig("CCs.pdf")
def run(input_mtz):
mtz_in = any_file(input_mtz)
ma = mtz_in.file_server.miller_arrays
flags = fmodel = fobs = None
# select the output arrays from phenix.refine. This could easily be modified
# to handle MTZ files from other programs.
for array in ma :
labels = array.info().label_string()
if labels.startswith("R-free-flags"):
flags = array
elif labels.startswith("F-model"):
fmodel = abs(array)
elif labels.startswith("F-obs-filtered"):
fobs = array
if (None in [flags, fobs, fmodel]):
raise RuntimeError("Not a valid phenix.refine output file")
scores = get_r_free_flags_scores([flags], None)
test_flag_value = scores.test_flag_values[0]
flags = flags.customized_copy(data=flags.data()==test_flag_value)
(d_centers,
r_work_list,
r_free_list,
cc_work_list,
cc_free_list) = compute_r_factors(fobs, fmodel, flags)
plot_r_factors(d_centers, r_work_list, r_free_list)
plot_cc(d_centers, cc_work_list, cc_free_list)
if (__name__ == "__main__"):
run(input_mtz="${1:28molrepEdited_5_refine_001}.mtz")
endsnippet
snippet plotIntensityResolutionBin "Miller arrays to plot of bin mean intensity over dstar" b
from iotbx.file_reader import any_file
import matplotlib.pyplot as plt
f = any_file("${1:/Users/blaine/manuscripts/RETkinaseLoxo/ret_blu.mtz}")
print(f.file_type)
f.show_summary()
miller_arrays = f.file_server.miller_arrays
iobs = miller_arrays[3]
flags = miller_arrays[0]
iobs, flags = iobs.common_sets(other=flags)
iobsData = iobs.data()
list(iobsData[100:110])
iobs.show_comprehensive_summary()
# iobs.binner()
n_bins = ${2:20}
binner = iobs.setup_binner(n_bins=n_bins)
binner.show_summary()
used = list(binner.range_used())
selections = [binner.selection(i) for i in used]
means = [iobs.select(sel).mean() for sel in selections]
from math import log
lnmeans = [log(y) for y in means]
d_star_power = 1.618034
centers = binner.bin_centers(d_star_power)
d_centers = list(centers**(-1 / d_star_power))
d_centers
# plt.ylabel("Natural log of the amplitudes squared")
# plt.xlabel(r"$\textrm{d^*}$ in $\textrm{\AA}$")
# ax.set_xlim(35, 1.5)
# plt.scatter(d_centers,lnmeanss)
fig, ax = plt.subplots()
ax.scatter(d_centers,lnmeans)
ax.set_xlim(${3:8}, ${4:1.5}) # decreasing
ax.set_xlabel(r"$d^*$ in $\AA$")
ax.set_ylabel("Natural log of the intensities")
ax.grid(False)
plt.savefig("${5:iobsvsdstar}.pdf")
$0
endsnippet
snippet cns2mtz "Miller arrays to convert CNS reflection file into an mtz file" b
from iotbx import reflection_file_reader
import os
reflection_file = reflection_file_reader.any_reflection_file(file_name=os.path.expandvars("${1:\$CNS_SOLVE/doc/html/tutorial/data/pen/scale.hkl}"))
from cctbx import crystal
crystal_symmetry = crystal.symmetry( unit_cell=(${2:97.37, 46.64, 65.47, 90, 115.4, 90}), space_group_symbol="${3:C2}")
miller_arrays = reflection_file.as_miller_arrays( crystal_symmetry=crystal_symmetry)
mtz_dataset = None
for miller_array in miller_arrays:
if (mtz_dataset is None):
mtz_dataset = miller_array.as_mtz_dataset(
column_root_label=miller_array.info().labels[0])
else:
mtz_dataset.add_miller_array(
miller_array=miller_array,
column_root_label=miller_array.info().labels[0])
mtz_object = mtz_dataset.mtz_object()
mtz_object.show_summary()
$0
endsnippet
snippet FsigmaFbyabsLindex "L-plot" b
import pandas as pd
'''
Use pandas to read in a hkl file with whitespace separators into a dataframe.
Append to the dataframe a column with F/sigmaF values.
Append to the dataframe a column with the absolute value of the L indices.
Average F/sigmaF by absL index.
Write to absL and F/sigmaF to csv file.
'''
mtzdata = pd.read_csv("${1:1524start}.hkl", names=["H","K","L",${2:"F","SIGF"}], sep="\s+")
mtzdata["FovSigF"] = mtzdata.apply(lambda row: row["F"] / row["SIGF"], axis=1)
mtzdata["absL"] = mtzdata.apply(lambda row: abs(row["L"]), axis=1)
FovSigFabsL = mtzdata.groupby([mtzdata.absL]).FovSigF.mean()
FovSigFabsL.to_csv("${3:test2}.csv")
$0
endsnippet
snippet changeMtzColumns "Read in mtz file and write out with fewer columns." b
from iotbx.reflection_file_reader import any_reflection_file
hkl_in = any_reflection_file("${1:/Users/blaine/manuscripts/RETkinaseLoxo/ret_blu.mtz}")
miller_arrays = hkl_in.as_miller_arrays()
i_obs = miller_arrays[3]
r_free_flags = miller_arrays[0]
f_obs = i_obs.f_sq_as_f()
mtz_dataset = i_obs.as_mtz_dataset(column_root_label="I")
mtz_dataset.add_miller_array(f_obs, column_root_label="F")
mtz_dataset.add_miller_array(r_free_flags,column_root_label="${2:FreeR_flag}")
mtz_dataset.mtz_object().write("${3:loxodata.mtz}")
$0
endsnippet
snippet normalizedStructureFactors "Calculate quasi-normalized structure factor." b
all_e_values = miller_array.quasi_normalize_structure_factors().sort(by_value="data")
$0
endsnippet
snippet readMtzFile "Read in a mtz file into a Miller array with iotbx.file_reader." b
from iotbx.file_reader import any_file
mtz_in = any_file("${1:data}.mtz", force_type="mtz")
miller_arrays = mtz_in.file_server.miller_arrays
$0
endsnippet
snippet pattersonContourMap "Read in a mtz file with iotbx.file_reader." b
import numpy
from matplotlib import pyplot
import gemmi
# https://gemmi.readthedocs.io/en/latest/grid.html
ccp4 = gemmi.read_ccp4_map("${1:/Users/blaine/4bqrPatterson.ccp4}")
ccp4.setup()
arr = numpy.array(ccp4.grid, copy=False)
x = numpy.linspace(0, ccp4.grid.unit_cell.a, num=arr.shape[0], endpoint=False)
y = numpy.linspace(0, ccp4.grid.unit_cell.b, num=arr.shape[1], endpoint=False)
X, Y = numpy.meshgrid(x, y, indexing="ij")
pyplot.rcParams["figure.figsize"] = (8.0, 8.0)
pyplot.contour(X, Y, arr[:,:,0],500, zorder=1,linestyles="solid")
pyplot.gca().set_aspect("equal", adjustable="box")
pyplot.show()
arr2 = numpy.array(ccp4.grid, copy=False)
x = numpy.linspace(0, ccp4.grid.unit_cell.a, num=arr2.shape[0], endpoint=False)
z = numpy.linspace(0, ccp4.grid.unit_cell.c, num=arr2.shape[1], endpoint=False)
X, Z = numpy.meshgrid(x, z, indexing="ij")
pyplot.rcParams["figure.figsize"] = (4.0, 20.5)
pyplot.contour(X, Z, arr[:,:,0],500, zorder=1, linestyles="solid")
pyplot.gca().set_aspect("equal", adjustable="box")
pyplot.savefig("patterson.png", dpi=600)
pyplot.show()
$0
endsnippet
snippet condaInstall2 "The conda commands to remove old env and create a new one for cctbx. These commands need to be run on the command line." b
conda remove --name cctbx${1:37}
conda create -n ${2:cctbx38} -c conda-forge cctbx-base python=${4:3.8}
conda activate ${2:cctbx38}
conda install -c conda-forge cctbx-base
conda install -c anaconda ipykernel
python -m ipykernel install --user --name ${2:cctbx38} --display-name "${2:cctbx38}"
$0
endsnippet
snippet eigenvalues "The commands to find the eigenvalues and eigenvectors on a tensor. The code is from a post to cctbxbb on 10 December 2020 by Richard Gildea in a reply to Robert Oeffner about code in cctbx for finding eigenvalues and eigenvectors. Robert was requesting the analog in cctbx to scipy.linalg.eig." b
from scitbx.array_family import flex;
from scitbx.linalg import eigensystem;
m = flex.double(($1:-2, -4, 2, -2, 1, 2, 4, 2, 5}));
m.reshape(flex.grid(3,3));
es = eigensystem.real_symmetric(m);
list(es.values());
list(es.vectors());
$0
endsnippet
snippet IpIm "Scatter plot of I(+) and (I(-). The presence of an anomalous signal is indicated by deviations from x=y." b
%matplotlib inline
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.ticker as ticker
from matplotlib.ticker import MultipleLocator #, FormatStrFormatter
from matplotlib.ticker import FuncFormatter
from iotbx.reflection_file_reader import any_reflection_file
# >>> change the mtz file name
hkl_file = any_reflection_file("${1:3hz7}.mtz")
miller_arrays = hkl_file.as_miller_arrays(merge_equivalents=False)
Iobs = miller_arrays[1]
i_plus, i_minus = Iobs.hemispheres_acentrics()
ipd = i_plus.data()
ip=list(ipd)
imd = i_minus.data()
im = list(imd)
len(im)
comma_fmt = FuncFormatter(lambda x, p: format(int(x), ","))
mpl.rcParams["savefig.dpi"] = 600
mpl.rcParams["figure.dpi"] = 600
# Set to width of a one column on a two-column page.
# May want to adjust settings for a slide.
fig, ax = plt.subplots(figsize=[3.25, 3.25])
ax.scatter(ip,im,c="k",alpha=0.3,s=5.5)
ax.set_xlabel(r"I(+)",fontsize=12)
ax.set_ylabel(r"I(-)",fontsize=12)
ax.xaxis.set_major_locator(MultipleLocator(50000.))
ax.yaxis.set_major_locator(MultipleLocator(50000.))
ax.get_xaxis().set_major_formatter(comma_fmt)
ax.get_yaxis().set_major_formatter(comma_fmt)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
ax.grid(False)
# >>> change name of the figure file
plt.savefig("${1:3hz7}IpIm.pdf",bbox_inches="tight")
$0
endsnippet
snippet fetchFASTA "Fetch fasta file from RCSB." b
from iotbx.pdb.fetch import get_pdb
import sys
get_pdb(id="3nd4",data_type="pdb", mirror="rcsb", format="pdb", log=sys.stdout)
$0
endsnippet
snippet fetchXrayCif "Fetch X-ray data from RCSB in mmCIF format." b
from iotbx.pdb.fetch import get_pdb
import sys
get_pdb(id="${1:3nd4}",data_type="xray", mirror="rcsb", format="cif", log=sys.stdout)
$0
endsnippet
snippet fetchAtomicCif "Fetch atomic coordinates from RCSB in mmCIF format." b
from iotbx.pdb.fetch import get_pdb
import sys
get_pdb(id="${1:3nd4}",data_type="xray", mirror="rcsb", format="cif", log=sys.stdout)
$0
endsnippet
snippet symmetryFromPDB "Print the symmetry from a PDB file." b
import iotbx
iotbx.pdb.crystal_symmetry_from_pdb.extract_from("${1:3nd4}.pdb")
$0
endsnippet
snippet makeMaps "Read in mtz and pdb file and write map coefficients to a separate mtz file." b
from mmtbx.maps.utils import create_map_from_pdb_and_mtz
'''The phenix.maps commandline tool is the recommended approach.'''
id="${1:3nd4}"
create_map_from_pdb_and_mtz(
pdb_file="%s.pdb" % id,
mtz_file="%s.mtz" % id,
output_file="%s_maps.mtz" % id,
fill=False,
out=None,
llg_map=False,
remove_unknown_scatterering_type=True,
assume_pdb_data=False)
$0
endsnippet
snippet testCCTBX "Enter this snippet on the command line in an empty directory." b
libtbx.run_tests_parallel module=libtbx module=cctbx nproc=${1:6}
$0
endsnippet
snippet condaInstall4Ununtu "Enter this snippet on the command line in an empty directory." b
apt install nodejs git
wget https://repo.anaconda.com/archive/${1:Anaconda3-2020.02-Linux-x86_64.sh}
bash ${1:Anaconda3-2020.02-Linux-x86_64.sh}
conda create -n ${2:pc37} python=3.7 schrodinger::pymol-bundle=2.4.1 conda-forge::cctbx-base conda-forge::jupyter
conda activate ${2:pc37}
conda install conda-forge::jupyterlab=2.2.0
# The following may be needed
# jupyter serverextension enable --py jupyterlab --user
pip install jupyterlab-snippets-multimenus
jupyter lab build
# Might be needed
# jupyter lab clean
jupyter --path # select the top option under Data for storing the libraries
cd ~/.local/share/jupyter # change as per output from prior line
mkdir multimenus_snippets
cd multimenus_snippets
git clone https://github.com/MooersLab/juptyerlabpymolcctbx.git cctbx
git clone https://github.com/MooersLab/juptyerlabpymolcctbxplus.git cctbx+
git clone https://github.com/MooersLab/juptyerlabpymolpysnips.git pymol
git clone https://github.com/MooersLab/juptyerlabpymolpysnipsplus.git pymol+
jupyter lab # or libtbx.python -m jupyter-lab
$0
endsnippet
snippet condaListEnvs "List the currently available envs. The bang (!) enables running this command in a Juptyer Notebook. Delete the bang to run the command in the terminal." b
!conda env list
endsnippet
snippet condaRemoveEnv "Remove a specified env. The bang (!) enables running this command in a Juptyer Notebook. Delete the bang to run the command in the terminal." b
!conda env remove --name cctbx37
endsnippet