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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
|
from __future__ import absolute_import, division, print_function
from operator import itemgetter
import iotbx.phil
import iotbx.pdb
import iotbx.mrcfile
from cctbx import crystal
from cctbx import maptbx
from libtbx.utils import Sorry
import sys, os
from cctbx.array_family import flex
from scitbx.math import matrix
from copy import deepcopy
from libtbx.utils import null_out
import libtbx.callbacks # import dependency
from libtbx import group_args
from six.moves import range
from six.moves import zip
from cctbx.development.create_models_or_maps import get_map_from_map_coeffs
master_phil = iotbx.phil.parse("""
input_files {
seq_file = None
.type = path
.short_caption = Sequence file
.help = Sequence file (unique chains only, \
1-letter code, chains separated by \
blank line or greater-than sign.) \
Can have chains that are DNA/RNA/protein and\
all can be present in one file. \
If not supplied, must supply molecular mass or \
solvent content.
map_file = None
.type = path
.help = File with CCP4-style map
.short_caption = Map file
half_map_file = None
.type = path
.multiple = True
.short_caption = Half map
.help = Half map (two should be supplied) for FSC calculation. Must \
have grid identical to map_file
external_map_file = None
.type = path
.short_caption = External map
.style = file_type:ccp4_map bold input_file
.help = External map to be used to scale map_file (power vs resolution\
will be matched). Not used in segment_and_split_map
ncs_file = None
.type = path
.help = File with symmetry information (typically point-group NCS with \
the center specified). Typically in PDB format. \
Can also be a .ncs_spec file from phenix. \
Created automatically if symmetry is specified.
.short_caption = symmetry file
pdb_file = None
.type = path
.help = Optional PDB file matching map_file to be offset
pdb_to_restore = None
.type = path
.help = Optional PDB file to restore to position matching original \
map_file. Used in combination with info_file = xxx.pkl \
and restored_pdb = yyyy.pdb
.short_caption = PDB to restore
info_file = None
.type = path
.help = Optional pickle file with information from a previous run.\
Can be used with pdb_to_restore to restore a PDB file to \
to position matching original \
map_file.
.short_caption = Info file
target_ncs_au_file = None
.type = path
.help = Optional PDB file to partially define the ncs asymmetric \
unit of the map. The coordinates in this file will be used \
to mark part of the ncs au and all points nearby that are \
not part of another ncs au will be added.
input_weight_map_pickle_file = None
.type = path
.short_caption = Input weight map pickle file
.help = Weight map pickle file
}
output_files {
magnification_map_file = magnification_map.ccp4
.type = path
.help = Input map file with magnification applied. Only written if\
magnification is applied.
.short_caption = Magnification map file
magnification_ncs_file = magnification_ncs.ncs_spec
.type = path
.help = Input NCS with magnification applied. Only written if\
magnification is applied.
.short_caption = Magnification NCS file
shifted_map_file = shifted_map.ccp4
.type = path
.help = Input map file shifted to new origin.
.short_caption = Shifted map file
shifted_sharpened_map_file = shifted_sharpened_map.ccp4
.type = path
.help = Input map file shifted to new origin and sharpened.
.short_caption = Shifted sharpened map file
sharpened_map_file = sharpened_map.ccp4
.type = str
.short_caption = Sharpened map file
.help = Output sharpened map file, superimposed on the original map.
.input_size = 400
shifted_pdb_file = shifted_pdb.pdb
.type = path
.help = Input pdb file shifted to new origin.
.short_caption = Shifted pdb file
shifted_ncs_file = shifted_ncs.ncs_spec
.type = path
.help = NCS information shifted to new origin.
.short_caption = Output NCS info file
shifted_used_ncs_file = shifted_used_ncs.ncs_spec
.type = path
.help = NCS information (just the part that is used) shifted \
to new origin.
.short_caption = Output used NCS info file
output_directory = segmented_maps
.type = path
.help = Directory where output files are to be written \
applied.
.short_caption = Output directory
box_map_file = box_map_au.ccp4
.type = path
.help = Output map file with one NCS asymmetric unit, cut out box
.short_caption = Box NCS map file
box_mask_file = box_mask_au.ccp4
.type = path
.help = Output mask file with one NCS asymmetric unit, cut out box
.short_caption = Box NCS mask file
box_buffer = 5
.type = int
.help = Buffer (grid units) around NCS asymmetric unit in box_mask and map
.short_caption = Box buffer size
au_output_file_stem = shifted_au
.type = str
.help = File stem for output map files with one NCS asymmetric unit
.short_caption = Output au file stem
write_intermediate_maps = False
.type = bool
.help = Write out intermediate maps and masks for visualization
.short_caption = Write intermediate maps
write_output_maps = True
.type = bool
.help = Write out maps
.short_caption = Write maps
remainder_map_file = remainder_map.ccp4
.type = path
.help = output map file with remainder after initial regions identified
.short_caption = Output remainder map file
output_info_file = segment_and_split_map_info.pkl
.type = path
.help = Output pickle file with information about map and masks
.short_caption = Output pickle file
restored_pdb = None
.type = path
.help = Output name of PDB restored to position matching original \
map_file. Used in combination with info_file = xxx.pkl \
and pdb_to_restore = xxxx.pdb
.short_caption = Restored PDB file
output_weight_map_pickle_file = weight_map_pickle_file.pkl
.type = path
.short_caption = Output weight map pickle file
.help = Output weight map pickle file
}
crystal_info {
chain_type = *None PROTEIN RNA DNA
.type = choice
.short_caption = Chain type
.help = Chain type. Determined automatically from sequence file if \
not given. Mixed chain types are fine (leave blank if so).
sequence = None
.type = str
.short_caption = Sequence
.help = Sequence as string
is_crystal = None
.type = bool
.short_caption = Is a crystal
.help = Defines whether this is a crystal (or cryo-EM).\
Default is True if use_sg_symmetry = True and False otherwise.
use_sg_symmetry = False
.type = bool
.short_caption = Use space-group symmetry
.help = If you set use_sg_symmetry = True then the symmetry of the space\
group will be used. For example in P1 a point at one end of \
the \
unit cell is next to a point on the other end. Normally for \
cryo-EM data this should be set to False and for crystal data \
it should be set to True. This will normally also set the \
value of is_crystal (same value as use_sg_symmetry) and \
restrict_map_size (False if use_sg_symmetry = True).
resolution = None
.type = float
.short_caption = resolution
.help = Nominal resolution of the map. This is used later to decide on\
resolution cutoffs for Fourier inversion of the map. Note: \
the resolution is not cut at this value, it is cut at \
resolution*d_min_ratio if at all.
space_group = None
.type = space_group
.help = Space group (used for boxed maps)
.style = hidden
unit_cell = None
.type = unit_cell
.help = Unit Cell (used for boxed maps)
.style = hidden
original_unit_cell = None
.type = unit_cell
.help = Original unit cell (of input map). Used internally
.style = hidden
original_unit_cell_grid = None
.type = ints
.help = Original unit cell grid (of input map). Used internally
.style = hidden
molecular_mass = None
.type = float
.help = Molecular mass of molecule in Da. Used as alternative method \
of specifying solvent content.
.short_caption = Molecular mass in Da
solvent_content = None
.type = float
.help = Solvent fraction of the cell. Used for ID of \
solvent content in boxed maps.
.short_caption = Solvent content
solvent_content_iterations = 3
.type = int
.help = Iterations of solvent fraction estimation. Used for ID of \
solvent content in boxed maps.
.short_caption = Solvent fraction iterations
.style = hidden
wang_radius = None
.type = float
.help = Wang radius for solvent identification. \
Default is 1.5* resolution
.short_caption = Wang radius
buffer_radius = None
.type = float
.help = Buffer radius for mask smoothing. \
Default is resolution
.short_caption = Buffer radius
pseudo_likelihood = None
.type = bool
.help = Use pseudo-likelihood method for half-map sharpening. \
(In development)
.short_caption = Pseudo-likelihood
.style = hidden
}
reconstruction_symmetry {
symmetry = None
.type = str
.short_caption = Symmetry type
.help = Symmetry used in reconstruction. For example D7, C3, C2\
I (icosahedral), T (tetrahedral), or ANY (try everything and \
use the highest symmetry found). Not needed if ncs_file is supplied. \
include_helical_symmetry = True
.type = bool
.short_caption = Include helical symmetry
.help = You can include or exclude searches for helical symmetry
must_be_consistent_with_space_group_number = None
.type = int
.short_caption = Space group to match
.help = Searches for symmetry must be compatible with this space group\
number.
symmetry_center = None
.type = floats
.short_caption = symmetry center
.help = Center (in A) for symmetry operators (if symmetry is found \
automatically). \
If set to None, first guess is the center of the cell and then \
if that fails, found automatically as the center of the \
density in the map.
optimize_center = False
.type = bool
.short_caption = Optimize symmetry center
.help = Optimize position of symmetry center. Also checks for center \
at (0, 0, 0) vs center of map
helical_rot_deg = None
.type = float
.short_caption = helical rotation
.help = helical rotation about z in degrees
helical_trans_z_angstrom = None
.type = float
.short_caption = helical translation
.help = helical translation along z in Angstrom units
max_helical_optimizations = 2
.type = int
.short_caption = Max helical optimizations
.help = Number of optimizations of helical parameters\
when finding symmetry
max_helical_ops_to_check = 5
.type = int
.short_caption = Max helical ops to check
.help = Number of helical operations in each direction to check \
when finding symmetry
max_helical_rotations_to_check = None
.type = int
.short_caption = Max helical rotations
.help = Number of helical rotations to check \
when finding symmetry
two_fold_along_x = None
.type = bool
.short_caption = D two-fold along x
.help = Specifies if D or I two-fold is along x (True) or y (False). \
If None, both are tried.
smallest_object = None
.type = float
.short_caption = Smallest object to consider
.help = Dimension of smallest object to consider\
when finding symmetry. Default is 5 * resolution
score_basis = ncs_score cc *None
.type = choice
.short_caption = Symmetry score basis
.help = Symmetry score basis. Normally ncs_score (sqrt(n)* cc) is \
used except for identification of helical symmetry
scale_weight_fractional_translation = 1.05
.type = float
.short_caption = Scale on fractional translation
.help = Give slight increase in weighting in helical symmetry \
search to translations that are a fraction (1/2, 1/3) of \
the d-spacing of the peak of intensity in the fourier \
transform of the density.
random_points = 100
.type = int
.short_caption = Random points
.help = Number of random points in map to examine in finding symmetry
identify_ncs_id = True
.type = bool
.short_caption = Identify NCS ID
.help = If symmetry is not point-group symmetry, try each possible \
operator when evaluating symmetry and choose the one that \
results in the most uniform density at symmetry-related points.
min_ncs_cc = 0.75
.type = float
.short_caption = Minimum symmetry CC to keep it
.help = Minimum symmetry CC to keep operators when identifying \
automatically
n_rescore = 5
.type = int
.short_caption = symmetry operators to rescore
.help = Number of symmetry operators to rescore
op_max = 14
.type = int
.short_caption = Max operators to try
.help = If symmetry is ANY, try up to op_max-fold symmetries
tol_r = 0.02
.type = float
.help = tolerance in rotations for point group or helical symmetry
.short_caption = Rotation tolerance
abs_tol_t = 2
.type = float
.help = tolerance in translations (A) for point group or helical symmetry
.short_caption = Translation tolerance absolute
max_helical_operators = None
.type = int
.help = Maximum helical operators (if extending existing helical\
operators)
.short_caption = Maximum helical operators
rel_tol_t = .05
.type = float
.help = tolerance in translations (fractional) for point group or \
helical symmetry
.short_caption = Translation tolerance fractional
require_helical_or_point_group_symmetry = False
.type = bool
.help = normally helical or point-group symmetry (or none) is expected. \
However in some cases (helical + rotational symmetry for \
example) this is not needed and is not the case.
.short_caption = Require helical or point-group or no symmetry
}
map_modification {
magnification = None
.type = float
.short_caption = Magnification
.help = Magnification to apply to input map. Input map grid will be \
scaled by magnification factor before anything else is done.
b_iso = None
.type = float
.short_caption = Target b_iso
.help = Target B-value for map (sharpening will be applied to yield \
this value of b_iso). If sharpening method is not supplied, \
default is to use b_iso_to_d_cut sharpening.
b_sharpen = None
.type = float
.short_caption = Sharpening
.help = Sharpen with this b-value. Contrast with b_iso that yield a \
targeted value of b_iso. B_sharpen greater than zero is sharpening.\
Less than zero is blurring.
b_blur_hires = 200
.type = float
.short_caption = high_resolution blurring
.help = Blur high_resolution data (higher than d_cut) with \
this b-value. Contrast with b_sharpen applied to data up to\
d_cut. \
Note on defaults: If None and b_sharpen is positive (sharpening) \
then high-resolution data is left as is (not sharpened). \
If None and b_sharpen is negative (blurring) high-resolution data\
is also blurred.
resolution_dependent_b = None
.type = floats
.short_caption = resolution_dependent b
.help = If set, apply resolution_dependent_b (b0 b1 b2). \
Log10(amplitudes) will start at 1, change to b0 at half \
of resolution specified, changing linearly, \
change to b1/2 at resolution specified, \
and change to b1/2+b2 at d_min_ratio*resolution
normalize_amplitudes_in_resdep = False
.type = bool
.short_caption = Normalize amplitudes in resdep
.help = Normalize amplitudes in resolution-dependent sharpening
d_min_ratio = 0.833
.type = float
.short_caption = Sharpen d_min ratio
.help = Sharpening will be applied using d_min equal to \
d_min_ratio times resolution. Default is 0.833
scale_max = 100000
.type = float
.short_caption = Scale_max
.help = Scale amplitudes from inverse FFT to yield maximum of this value
input_d_cut = None
.type = float
.short_caption = d_cut
.help = High-resolution limit for sharpening
rmsd = None
.type = float
.short_caption = RMSD of model
.help = RMSD of model to true model (if supplied). Used to \
estimate expected fall-of with resolution of correct part \
of model-based map. If None, assumed to be resolution \
times rmsd_resolution_factor.
rmsd_resolution_factor = 0.25
.type = float
.short_caption = rmsd resolution factor
.help = default RMSD is resolution times resolution factor
fraction_complete = None
.type = float
.short_caption = Completeness model
.help = Completness of model (if supplied). Used to \
estimate correct part \
of model-based map. If None, estimated from max(FSC).
regions_to_keep = None
.type = int
.short_caption = Regions to keep
.help = You can specify a limit to the number of regions to keep\
when generating the asymmetric unit of density.
auto_sharpen = True
.type = bool
.short_caption = Automatically determine sharpening
.help = Automatically determine sharpening using kurtosis maximization\
or adjusted surface area
auto_sharpen_methods = no_sharpening b_iso *b_iso_to_d_cut \
resolution_dependent model_sharpening \
half_map_sharpening target_b_iso_to_d_cut None
.type = choice(multi = True)
.short_caption = Sharpening methods
.help = Methods to use in sharpening. b_iso searches for b_iso to \
maximize sharpening target (kurtosis or adjusted_sa). \
b_iso_to_d_cut applies b_iso only up to resolution specified, with \
fall-over of k_sharpen. Resolution dependent adjusts 3 parameters \
to sharpen variably over resolution range. Default is \
b_iso_to_d_cut . target_b_iso_to_d_cut uses target_b_iso_ratio \
to set b_iso.
box_in_auto_sharpen = False
.type = bool
.short_caption = Use box for auto_sharpening
.help = Use a representative box of density for initial \
auto-sharpening instead of the entire map.
density_select_in_auto_sharpen = True
.type = bool
.short_caption = density_select to choose box
.help = Choose representative box of density for initial \
auto-sharpening with density_select method \
(choose region where there is high density). \
Normally use this as well as density_select = True which \
carries out density_select at start of segmentation.
density_select_threshold_in_auto_sharpen = None
.type = float
.short_caption = density_select threshold to choose box
.help = Threshold for density select choice of box. Default is 0.05. \
If your map has low overall contrast you might need to make this\
bigger such as 0.2.
allow_box_if_b_iso_set = False
.type = bool
.short_caption = Allow box if b_iso set
.help = Allow box_in_auto_sharpen (if set to True) even if \
b_iso is set. Default is to set box_n_auto_sharpen = False \
if b_iso is set.
soft_mask = True
.type = bool
.help = Use soft mask (smooth change from inside to outside with radius\
based on resolution of map). Required if you use half-map \
sharpening without a model, otherwise optional.
.short_caption = Soft mask
use_weak_density = False
.type = bool
.short_caption = Use box with poor density
.help = When choosing box of representative density, use poor \
density (to get optimized map for weaker density)
discard_if_worse = None
.type = bool
.short_caption = Discard sharpening if worse
.help = Discard sharpening if worse
local_sharpening = None
.type = bool
.short_caption = Local sharpening
.help = Sharpen locally using overlapping regions. \
NOTE: Best to turn off local_aniso_in_local_sharpening \
if symmetry is present.\
If local_aniso_in_local_sharpening is True and symmetry is \
present this can distort the map for some symmetry copies \
because an anisotropy correction is applied\
based on local density in one copy and is transferred without \
rotation to other copies.
local_aniso_in_local_sharpening = None
.type = bool
.short_caption = Local anisotropy
.help = Use local anisotropy in local sharpening. \
Default is True unless symmetry is present.
overall_before_local = True
.type = bool
.short_caption = Overall before local
.help = Apply overall scaling before local scaling
select_sharpened_map = None
.type = int
.short_caption = Sharpened map to use
.help = Select a single sharpened map to use
read_sharpened_maps = None
.type = bool
.short_caption = Read sharpened maps
.help = Read in previously-calculated sharpened maps
write_sharpened_maps = None
.type = bool
.short_caption = Write sharpened maps
.help = Write out local sharpened maps
smoothing_radius = None
.type = float
.short_caption = Smoothing radius
.help = Sharpen locally using smoothing_radius. Default is 2/3 of \
mean distance between centers for sharpening
box_center = None
.type = floats
.short_caption = Center of box
.help = You can specify the center of the box (A units)
box_size = 40 40 40
.type = ints
.short_caption = Size of box
.help = You can specify the size of the boxes to use (grid units)
target_n_overlap = 10
.type = int
.short_caption = Target overlap of boxes
.help = You can specify the targeted overlap of boxes in local \
sharpening
restrict_map_size = None
.type = bool
.short_caption = Restrict box map size
.help = Restrict box map to be inside full map (required for cryo-EM data).\
Default is True if use_sg_symmetry = False.
restrict_z_turns_for_helical_symmetry = 1
.type = float
.short_caption = Restrict Z turns for helical symmetry
.help = Restrict Z turns for helical symmetry. Number of \
turns of helix going each direction in Z is specified.
restrict_z_distance_for_helical_symmetry = None
.type = float
.short_caption = Restrict Z distance for helical symmetry
.help = Restrict Z distance (+/- this distance from center) \
for helical symmetry.
remove_aniso = True
.type = bool
.short_caption = Remove aniso
.help = You can remove anisotropy (overall and locally) during sharpening
cc_cut = 0.2
.type = float
.short_caption = Min reliable CC in half-maps
.help = Estimate of minimum highly reliable CC in half-map FSC. Used\
to decide at what CC value to smooth the remaining CC values.
max_cc_for_rescale = 0.2
.type = float
.short_caption = Max CC for rescale
.help = Min reliable CC in half-maps. \
Used along with cc_cut and scale_using_last to correct for \
small errors in FSC estimation at high resolution. If the \
value of FSC near the high-resolution limit is above \
max_cc_for_rescale, assume these values are correct and do not \
correct them. To keep all original values use\
max_cc_for_rescale = 1
scale_using_last = 3
.type = int
.short_caption = Last N bins in FSC assumed to be about zero
.help = If set, assume that the last scale_using_last bins in the FSC \
for half-map or model sharpening are about zero (corrects for \
errors in the half-map process).
max_box_fraction = 0.5
.type = float
.short_caption = Max size of box for auto_sharpening
.help = If box is greater than this fraction of entire map, use \
entire map.
density_select_max_box_fraction = 0.95
.type = float
.short_caption = Max size of box for density_select
.help = If box is greater than this fraction of entire map, use \
entire map for density_select. Default is 0.95
mask_atoms = True
.type = bool
.short_caption = Mask atoms
.help = Mask atoms when using model sharpening
mask_atoms_atom_radius = 3
.type = float
.short_caption = Mask radius
.help = Mask for mask_atoms will have mask_atoms_atom_radius
value_outside_atoms = None
.type = str
.short_caption = Value outside atoms
.help = Value of map outside atoms (set to 'mean' to have mean \
value inside and outside mask be equal)
k_sharpen = 10
.type = float
.short_caption = sharpening transition
.help = Steepness of transition between sharpening (up to resolution \
) and not sharpening (d < resolution). Note: for blurring, \
all data are blurred (regardless of resolution), while for \
sharpening, only data with d about resolution or lower are \
sharpened. This prevents making very high-resolution data too \
strong. Note 2: if k_sharpen is zero, then no \
transition is applied and all data is sharpened or blurred. \
Note 3: only used if b_iso is set.
iterate = False
.type = bool
.short_caption = Iterate auto-sharpening
.help = You can iterate auto-sharpening. This is useful in cases where \
you do not specify the solvent content and it is not \
accurately estimated until sharpening is optimized.
optimize_b_blur_hires = False
.type = bool
.short_caption = Optimize value of b_blur_hires
.help = Optimize value of b_blur_hires. \
Only applies for auto_sharpen_methods b_iso_to_d_cut and \
b_iso. This is normally carried out and helps prevent \
over-blurring at high resolution if the same map is \
sharpened more than once.
optimize_d_cut = None
.type = bool
.short_caption = Optimize value of d_cut
.help = Optimize value of d_cut. \
Only applies for auto_sharpen_methods b_iso_to_d_cut and \
b_iso. Not normally carried out.
adjust_region_weight = True
.type = bool
.short_caption = Adjust region weight
.help = Adjust region_weight to make overall change in surface area \
equal to overall change in normalized regions over the range \
of search_b_min to search_b_max using b_iso_to_d_cut.
region_weight_method = initial_ratio *delta_ratio b_iso
.type = choice
.short_caption = Region weight method
.help = Method for choosing region_weights. Initial_ratio uses \
ratio of surface area to regions at low B value. Delta \
ratio uses change in this ratio from low to high B. B_iso \
uses resolution-dependent b_iso (not weights) with the \
formula b_iso = 5.9*d_min**2
region_weight_factor = 1.0
.type = float
.short_caption = Region weight factor
.help = Multiplies region_weight after calculation with \
region_weight_method above
region_weight_buffer = 0.1
.type = float
.short_caption = Region weight factor buffer
.help = Region_weight adjusted to be region_weight_buffer \
away from minimum or maximum values
region_weight_default = 30.
.type = float
.short_caption = Region weight default
.help = Region_weight adjusted to be region_weight_default\
if no information available
target_b_iso_ratio = 5.9
.type = float
.short_caption = Target b_iso ratio
.help = Target b_iso ratio : b_iso is estimated as \
target_b_iso_ratio * resolution**2
signal_min = 3.0
.type = float
.short_caption = Minimum signal
.help = Minimum signal in estimation of optimal b_iso. If\
not achieved, use any other method chosen.
target_b_iso_model_scale = 0.
.type = float
.short_caption = scale on target b_iso ratio for model
.help = For model sharpening, the target_biso is scaled \
(normally zero).
search_b_min = -100
.type = float
.short_caption = Low bound for b_iso search
.help = Low bound for b_iso search.
search_b_max = 300
.type = float
.short_caption = High bound for b_iso search
.help = High bound for b_iso search.
search_b_n = 21
.type = int
.short_caption = Number of b_iso values to search
.help = Number of b_iso values to search.
residual_target = 'adjusted_sa'
.type = str
.short_caption = Residual target
.help = Target for maximization steps in sharpening. \
Can be kurtosis or adjusted_sa (adjusted surface area)
sharpening_target = 'adjusted_sa'
.type = str
.short_caption = Overall sharpening target
.help = Overall target for sharpening. Can be kurtosis or adjusted_sa \
(adjusted surface area) or adjusted_path_length. \
Used to decide which sharpening approach \
is used. Note that during optimization, residual_target is used \
(they can be the same.)
region_weight = 40
.type = float
.short_caption = Region weighting
.help = Region weighting in adjusted surface area calculation.\
Score is surface area minus region_weight times number of regions.\
Default is 40. A smaller value will give more sharpening.
sa_percent = 30.
.type = float
.short_caption = Percent of target regions in adjusted_sa
.help = Percent of target regions used in calulation of adjusted \
surface area. Default is 30.
fraction_occupied = 0.20
.type = float
.short_caption = Fraction of molecular volume inside contours
.help = Fraction of molecular volume targeted to be inside contours. \
Used to set contour level. Default is 0.20
n_bins = 20
.type = int
.short_caption = Resolution bins
.help = Number of resolution bins for sharpening. Default is 20.
max_regions_to_test = 30
.type = int
.short_caption = Max regions to test
.help = Number of regions to test for surface area in adjusted_sa \
scoring of sharpening
eps = None
.type = float
.short_caption = Shift used in calculation of derivatives for \
sharpening maximization. Default is 0.01 for kurtosis and 0.5 for \
adjusted_sa.
k_sol = 0.35
.type = float
.help = k_sol value for model map calculation. IGNORED (Not applied)
.short_caption = k_sol IGNORED
.style = hidden
b_sol = 50
.type = float
.help = b_sol value for model map calculation. IGNORED (Not applied)
.short_caption = b_sol IGNORED
.style = hidden
}
segmentation {
select_au_box = None
.type = bool
.help = Select box containing at least one representative region of \
the map. Also select just symmetry operators relevant to that box. \
Default is true if number of operators is at least \
n_ops_to_use_au_box
.short_caption = select au box
n_ops_to_use_au_box = 25
.type = int
.help = If number of operators is this big or more and \
select_au_box is None, set it to True.
.short_caption = N ops to use au_box
n_au_box = 5
.type = int
.help = Number of symmetry copies to try and get inside au_box
.short_caption = N au box
lower_bounds = None
.type = ints
.help = You can select a part of your map for analysis with \
lower_bounds and upper_bounds.
.short_caption = Lower bounds
upper_bounds = None
.type = ints
.help = You can select a part of your map for analysis with \
lower_bounds and upper_bounds.
.short_caption = Upper bounds
density_select = True
.type = bool
.help = Run map_box with density_select = True to cut out the region \
in the input map that contains density. Useful if the input map \
is much larger than the structure. Done before segmentation is\
carried out.
.short_caption = Trim map to density
density_select_threshold = 0.05
.type = float
.help = Choose region where density is this fraction of maximum or greater
.short_caption = threshold for density_select
get_half_height_width = None
.type = bool
.help = Use 4 times half-width at half-height as estimate of max size
.short_caption = Half-height width estimation
box_ncs_au = True
.type = bool
.help = Box the map containing just the au of the map
.short_caption = Box NCS au
cell_cutoff_for_solvent_from_mask = 150
.type = float
.help = For cells with average edge over this cutoff, use the\
low resolution mask (backup) method for solvent estimation
.short_caption = Cell cutoff for solvent_from_mask
mask_padding_fraction = 0.025
.type = float
.help = Adjust threshold of standard deviation map in low resolution \
mask identification of solvent content to give this much more \
inside mask than would be obtained with the value of\
fraction_of_max_mask_threshold.
.short_caption = Mask padding fraction
fraction_of_max_mask_threshold = .05
.type = float
.help = threshold of standard deviation map in low resolution mask \
identification of solvent content.
.short_caption = Fraction of max mask_threshold
mask_threshold = None
.type = float
.help = threshold in identification of overall mask. If None, guess \
volume of molecule from sequence and symmetry copies.
.short_caption = Density select threshold
grid_spacing_for_au = 3
.type = int
.help = Grid spacing for asymmetric unit when constructing asymmetric unit.
.short_caption = Grid spacing for constructing asymmetric unit
radius = None
.type = float
.help = Radius for constructing asymmetric unit.
.short_caption = Radius for constructing asymmetric unit
value_outside_mask = 0.0
.type = float
.help = Value to assign to density outside masks
.short_caption = Value outside mask
density_threshold = None
.type = float
.short_caption = Density threshold
.help = Threshold density for identifying regions of density. \
Applied after normalizing the density in the region of \
the molecule to an rms of 1 and mean of zero.
starting_density_threshold = None
.type = float
.short_caption = Starting density threshold
.help = Optional guess of threshold density
iteration_fraction = 0.2
.type = float
.short_caption = Iteration fraction
.help = On iteration of finding regions, assume target volume is \
this fraction of the value on previous iteration
max_overlap_fraction = 0.05
.type = float
.short_caption = Max overlap
.help = Maximum fractional overlap allowed to density in another \
asymmetric unit. Definition of a bad region.
remove_bad_regions_percent = 1
.type = float
.short_caption = Remove worst overlapping regions
.help = Remove the worst regions that are part of more than one NCS \
asymmetric unit, up to remove_bad_regions_percent of the total
require_complete = True
.type = bool
.short_caption = Require all symmetry copies to be represented for a region
.help = Require all symmetry copies to be represented for a region
split_if_possible = True
.type = bool
.short_caption = Split regions if mixed
.help = Split regions that are split in some symmetry copies.\
If None, split if most copies are split.
write_all_regions = False
.type = bool
.short_caption = Write all regions
.help = Write all regions to ccp4 map files.
max_per_au = None
.type = int
.short_caption = Max regions in au
.help = Maximum number of regions to be kept in the NCS asymmetric unit
max_per_au_ratio = 5.
.type = int
.short_caption = Max ratio of regions to expected
.help = Maximum ratio of number of regions to be kept in the \
NCS asymmetric unit to those expected
min_ratio_of_ncs_copy_to_first = 0.5
.type = float
.short_caption = Minimum ratio of ncs copy to first
.help = Minimum ratio of the last ncs_copy region size to maximum
min_ratio = 0.1
.type = float
.short_caption = Minimum ratio to keep
.help = Minimum ratio of region size to maximum to keep it
max_ratio_to_target = 3
.type = float
.help = Maximum ratio of grid points in top region to target
.short_caption = Max ratio to target
min_ratio_to_target = 0.3
.type = float
.help = Minimum ratio of grid points in top region to target
.short_caption = Min ratio to target
min_volume = 10
.type = int
.help = Minimum region size to consider (in grid points)
.short_caption = Minimum region size
residues_per_region = 50
.type = float
.help = Target number of residues per region
.short_caption = Residues per region
seeds_to_try = 10
.type = int
.help = Number of regions to try as centers
.short_caption = Seeds to try
iterate_with_remainder = True
.type = bool
.short_caption = Iterate
.help = Iterate looking for regions based on remainder from first analysis
weight_rad_gyr = 0.1
.type = float
.short_caption = Weight on radius of gyration
.help = Weight on radius of gyration of group of regions in NCS AU \
relative to weight on closeness to neighbors. Normalized to\
largest cell dimension with weight = weight_rad_gyr*300/cell_max
expand_size = None
.type = int
.help = Grid points to expand size of regions when excluding for next \
round. If None, set to approx number of grid points to get \
expand_target below
.short_caption = Expand size
expand_target = 1.5
.type = float
.help = Target expansion of regions (A)
.short_caption = Expand target
mask_additional_expand_size = 1
.type = int
.help = Mask expansion in addition to expand_size for final map
.short_caption = Mask additional expansion
mask_expand_ratio = 1
.type = int
.help = Mask expansion relative to resolution for save_box_map_ncs_au
.short_caption = Mask expand ratio
exclude_points_in_ncs_copies = True
.type = bool
.help = Exclude points that are in symmetry copies when creating NCS au. \
Does not apply if add_neighbors = True
.short_caption = Exclude points in symmetry copies
add_neighbors = True
.type = bool
.help = Add neighboring regions around the au. Turns off \
exclude_points_in_ncs_copies also.
.short_caption = Add neighbors
add_neighbors_dist = 1.
.type = float
.help = Max increase in radius of gyration by adding region to keep it.
.short_caption = Add neighbors dist
}
control {
verbose = False
.type = bool
.help = '''Verbose output'''
.short_caption = Verbose output
shift_only = None
.type = bool
.short_caption = Shift only
.help = Shift map and half_maps and stop
sharpen_only = None
.type = bool
.short_caption = Sharpen only
.help = Sharpen map and stop
check_ncs = None
.type = bool
.short_caption = Check NCS
.help = Check the NCS symmetry by estimating NCS correlation and stop
resolve_size = None
.type = int
.help = "Size of resolve to use. "
.style = hidden
quick = True
.type = bool
.help = Run quickly if possible
.short_caption = Quick run
memory_check = True
.type = bool
.help = Map-to-model checks to make sure you have enough memory on \
your machine to run. You can disable this by setting this \
keyword to False. The estimates are approximate so it is \
possible your job could run even if the check fails. Note \
the check does not take any other uses of the memory on \
your machine into account.
.short_caption = Memory check
save_box_map_ncs_au = False
.type = bool
.help = Controls whether the map_box ncs_au is saved. Internal use only
.style = hidden
write_files = True
.type = bool
.help = Controls whether files are written
.short_caption = Write files
multiprocessing = *multiprocessing sge lsf pbs condor pbspro slurm
.type = choice
.short_caption = multiprocessing type
.help = Choices are multiprocessing (single machine) or queuing systems
queue_run_command = None
.type = str
.short_caption = Queue run command
.help = run command for queue jobs. For example qsub.
nproc = 1
.type = int
.short_caption = Number of processors
.help = Number of processors to use
.style = renderer:draw_nproc_widget bold
}
""", process_includes = True)
master_params = master_phil
class map_and_b_object:
def __init__(self,
map_data = None,
starting_b_iso = None,
final_b_iso = None):
from libtbx import adopt_init_args
adopt_init_args(self, locals())
class pdb_info_object:
def __init__(self,
file_name = None,
n_residues = None,
):
from libtbx import adopt_init_args
adopt_init_args(self, locals())
import time
self.init_asctime = time.asctime()
def show_summary(self, out = sys.stdout):
print("PDB file:%s" %(self.file_name), end = ' ', file = out)
if self.n_residues:
print(" Residues: %d" %(self.n_residues), file = out)
else:
print(file = out)
class seq_info_object:
def __init__(self,
file_name = None,
sequence = None,
n_residues = None,
):
from libtbx import adopt_init_args
adopt_init_args(self, locals())
import time
self.init_asctime = time.asctime()
def show_summary(self, out = sys.stdout):
if self.file_name:
print("Sequence file:%s" %(self.file_name), end = ' ', file = out)
if self.n_residues:
print(" Residues: %d" %(self.n_residues), file = out)
else:
print(file = out)
class ncs_info_object:
def __init__(self,
file_name = None,
number_of_operators = None,
is_helical_symmetry = None,
original_number_of_operators = None,
):
from libtbx import adopt_init_args
adopt_init_args(self, locals())
import time
self.init_asctime = time.asctime()
if original_number_of_operators is None:
self.original_number_of_operators = number_of_operators
self._has_updated_operators = False
def show_summary(self, out = sys.stdout):
print("NCS file:%s Operators: %d" %(self.file_name,
self.number_of_operators), file = out)
if self.is_helical_symmetry:
print("Helical symmetry is present", file = out)
def has_updated_operators(self):
return self._has_updated_operators
def update_number_of_operators(self, number_of_operators = None):
self.number_of_operators = number_of_operators
self._has_updated_operators = True
def update_is_helical_symmetry(self, is_helical_symmetry = None):
self.is_helical_symmetry = is_helical_symmetry
self._has_updated_operators = True
class map_info_object:
def __init__(self,
file_name = None,
origin = None,
all = None,
crystal_symmetry = None,
is_map = None,
map_id = None,
b_sharpen = None,
id = None,
):
from libtbx import adopt_init_args
adopt_init_args(self, locals())
import time
self.init_asctime = time.asctime()
def show_summary(self, out = sys.stdout):
if self.is_map:
print("Map file:%s" %(self.file_name), end = ' ', file = out)
else:
print("Mask file:%s" %(self.file_name), end = ' ', file = out)
if self.id is not None:
print("ID: %d" %(self.id), end = ' ', file = out)
if self.b_sharpen is not None:
print("B-sharpen: %7.2f" %(self.b_sharpen), end = ' ', file = out)
if self.map_id is not None:
print("Map ID: %s" %(self.map_id), file = out)
else:
print(file = out)
if self.origin and self.all:
print(" Origin: %d %d %d Extent: %d %d %d" %(
tuple(self.origin)+tuple(self.all)), file = out)
if self.crystal_symmetry:
print(" Map unit cell: %.1f %.1f %.1f %.1f %.1f %.1f " %(
self.crystal_symmetry.unit_cell().parameters()), file = out)
def lower_upper_bounds(self):
lower_bounds = self.origin
upper_bounds = []
for a, b in zip(self.origin, self.all):
upper_bounds.append(a+b-1) # 2019-11-05 upper bound is na-1
return list(self.origin), list(upper_bounds)
class info_object:
def __init__(self,
acc = None,
ncs_obj = None,
min_b = None,
max_b = None,
b_sharpen = None, # b_sharpen applied to map
ncs_group_list = None,
origin_shift = None,
crystal_symmetry = None, # after density_select
original_crystal_symmetry = None, # before density_select
full_crystal_symmetry = None, # from real_map object
full_unit_cell_grid = None, # from real_map object
edited_volume_list = None,
region_range_dict = None,
selected_regions = None,
ncs_related_regions = None,
self_and_ncs_related_regions = None,
map_files_written = None,
bad_region_list = None,
region_centroid_dict = None,
original_id_from_id = None,
remainder_id_dict = None, # dict relating regions in a remainder object to
params = None, # input params
input_pdb_info = None,
input_map_info = None,
input_ncs_info = None,
input_seq_info = None,
shifted_pdb_info = None,
shifted_map_info = None,
shifted_ncs_info = None,
shifted_used_ncs_info = None,
n_residues = None,
solvent_fraction = None,
output_ncs_au_map_info = None,
output_ncs_au_mask_info = None,
output_ncs_au_pdb_info = None,
output_box_map_info = None,
output_box_mask_info = None,
output_region_map_info_list = None,
output_region_pdb_info_list = None,
sharpening_info_obj = None,
box_map_bounds_first = None,
box_map_bounds_last = None,
final_output_sharpened_map_file = None,
box_map_ncs_au = None,
box_map_ncs_au_crystal_symmetry = None,
):
if not selected_regions: selected_regions = []
if not ncs_related_regions: ncs_related_regions = []
if not self_and_ncs_related_regions: self_and_ncs_related_regions = []
if not map_files_written: map_files_written = []
if not output_region_map_info_list: output_region_map_info_list = []
if not output_region_pdb_info_list: output_region_pdb_info_list = []
from libtbx import adopt_init_args
adopt_init_args(self, locals())
self.object_type = "segmentation_info"
import time
self.init_asctime = time.asctime()
def set_box_map_ncs_au_map_data(self,
box_map_ncs_au_map_data = None,
box_mask_ncs_au_map_data = None,
box_map_ncs_au_half_map_data_list = None,
box_map_ncs_au_crystal_symmetry = None):
self.box_map_ncs_au_map_data = box_map_ncs_au_map_data.deep_copy()
self.box_mask_ncs_au_map_data = box_mask_ncs_au_map_data.deep_copy()
self.box_map_ncs_au_half_map_data_list = []
for hm in box_map_ncs_au_half_map_data_list:
self.box_map_ncs_au_half_map_data_list.append(hm.deep_copy())
self.box_map_ncs_au_crystal_symmetry = box_map_ncs_au_crystal_symmetry
if self.origin_shift and self.origin_shift != (0, 0, 0):
self.box_map_ncs_au_map_data = self.shift_map_back(
map_data = self.box_map_ncs_au_map_data,
crystal_symmetry = self.box_map_ncs_au_crystal_symmetry,
shift_cart = self.origin_shift)
self.box_mask_ncs_au_map_data = self.shift_mask_back(
mask_data = self.box_mask_ncs_au_map_data,
crystal_symmetry = self.box_mask_ncs_au_crystal_symmetry,
shift_cart = self.origin_shift)
new_hm_list = []
for hm in self.box_map_ncs_au_half_map_data_list:
hm = self.shift_map_back(
map_data = hm,
crystal_symmetry = self.box_map_ncs_au_crystal_symmetry,
shift_cart = self.origin_shift)
new_hm_list.append(hm)
self.box_map_ncs_au_half_map_data_list = new_hm_list
def shift_map_back(self, map_data = None,
crystal_symmetry = None, shift_cart = None):
from scitbx.matrix import col
new_origin = self.origin_shift_grid_units(crystal_symmetry = crystal_symmetry,
map_data = map_data, shift_cart = shift_cart, reverse = True)
new_all = list(col(map_data.all())+col(new_origin))
shifted_map_data = map_data.deep_copy()
shifted_map_data.resize(flex.grid(new_origin, new_all))
return shifted_map_data
def origin_shift_grid_units(self, crystal_symmetry = None, map_data = None,
shift_cart = None, reverse = False):
# Get origin shift in grid units from shift_cart
from scitbx.matrix import col
cell = crystal_symmetry.unit_cell().parameters()[:3]
origin_shift_grid = []
for s, c, a in zip(shift_cart, cell, map_data.all()):
if s<0:
delta = -0.5
else:
delta = 0.5
origin_shift_grid.append( int(delta+ a*s/c))
if reverse:
return list(-col(origin_shift_grid))
else:
return origin_shift_grid
def is_segmentation_info_object(self):
return True
def set_params(self, params):
self.params = deepcopy(params)
def set_input_seq_info(self, file_name = None, sequence = None, n_residues = None):
self.input_seq_info = seq_info_object(file_name = file_name,
sequence = sequence,
n_residues = n_residues)
def set_input_pdb_info(self, file_name = None, n_residues = None):
self.input_pdb_info = pdb_info_object(file_name = file_name,
n_residues = n_residues)
def set_input_ncs_info(self, file_name = None, number_of_operators = None):
self.input_ncs_info = ncs_info_object(file_name = file_name,
number_of_operators = number_of_operators)
def update_ncs_info(self, number_of_operators = None, is_helical_symmetry = None,
shifted = False):
if shifted:
ncs_info = self.shifted_ncs_info
else:
ncs_info = self.input_ncs_info
assert ncs_info
if number_of_operators is not None:
ncs_info.update_number_of_operators(
number_of_operators = number_of_operators)
if is_helical_symmetry is not None:
ncs_info.update_is_helical_symmetry(
is_helical_symmetry = is_helical_symmetry)
def set_sharpening_info(self, sharpening_info_obj = None):
self.sharpening_info_obj = sharpening_info_obj
def set_input_map_info(self, file_name = None, crystal_symmetry = None,
origin = None, all = None):
self.input_map_info = map_info_object(file_name = file_name,
crystal_symmetry = crystal_symmetry,
origin = origin,
all = all,
is_map = True)
def set_ncs_obj(self, ncs_obj = None):
self.ncs_obj = ncs_obj
def set_origin_shift(self, origin_shift = None):
if not origin_shift: origin_shift = (0, 0, 0)
self.origin_shift = tuple(origin_shift)
def set_crystal_symmetry(self, crystal_symmetry):
self.crystal_symmetry = deepcopy(crystal_symmetry)
def set_original_crystal_symmetry(self, crystal_symmetry):
self.original_crystal_symmetry = deepcopy(crystal_symmetry)
def set_full_crystal_symmetry(self, crystal_symmetry):
self.full_crystal_symmetry = deepcopy(crystal_symmetry)
def set_full_unit_cell_grid(self, unit_cell_grid):
self.full_unit_cell_grid = deepcopy(unit_cell_grid)
def set_box_map_bounds_first_last(self, box_map_bounds_first,
box_map_bounds_last):
self.box_map_bounds_first = box_map_bounds_first
self.box_map_bounds_last = []
for l in box_map_bounds_last:
self.box_map_bounds_last.append(l+1) # it is one bigger...
def set_accessor(self, acc):
self.acc = acc
def set_shifted_map_info(self, file_name = None, crystal_symmetry = None,
origin = None, all = None, b_sharpen = None):
self.shifted_map_info = map_info_object(file_name = file_name,
crystal_symmetry = crystal_symmetry,
origin = origin,
all = all,
b_sharpen = b_sharpen,
is_map = True)
def set_shifted_pdb_info(self, file_name = None, n_residues = None):
self.shifted_pdb_info = pdb_info_object(file_name = file_name,
n_residues = n_residues)
def set_shifted_ncs_info(self, file_name = None, number_of_operators = None,
is_helical_symmetry = None):
self.shifted_ncs_info = ncs_info_object(file_name = file_name,
number_of_operators = number_of_operators,
is_helical_symmetry = is_helical_symmetry)
def set_shifted_used_ncs_info(self, file_name = None, number_of_operators = None,
is_helical_symmetry = None):
self.shifted_used_ncs_info = ncs_info_object(file_name = file_name,
number_of_operators = number_of_operators,
is_helical_symmetry = is_helical_symmetry)
def set_solvent_fraction(self, solvent_fraction):
self.solvent_fraction = solvent_fraction
def set_n_residues(self, n_residues): # may not be the same as seq file
self.n_residues = n_residues
def set_output_ncs_au_map_info(self, file_name = None, crystal_symmetry = None,
origin = None, all = None):
self.output_ncs_au_map_info = map_info_object(file_name = file_name,
crystal_symmetry = crystal_symmetry,
origin = origin,
all = all,
is_map = True)
def set_output_ncs_au_mask_info(self, file_name = None, crystal_symmetry = None,
origin = None, all = None):
self.output_ncs_au_mask_info = map_info_object(file_name = file_name,
crystal_symmetry = crystal_symmetry,
origin = origin,
all = all,
is_map = False)
def set_output_ncs_au_pdb_info(self, file_name = None, n_residues = None):
self.output_ncs_au_pdb_info = pdb_info_object(file_name = file_name,
n_residues = n_residues)
def set_output_box_map_info(self, file_name = None, crystal_symmetry = None,
origin = None, all = None):
self.output_box_map_info = map_info_object(file_name = file_name,
crystal_symmetry = crystal_symmetry,
origin = origin,
all = all,
is_map = True)
def set_output_box_mask_info(self, file_name = None, crystal_symmetry = None,
origin = None, all = None):
self.output_box_mask_info = map_info_object(file_name = file_name,
crystal_symmetry = crystal_symmetry,
origin = origin,
all = all,
is_map = False)
def add_output_region_map_info(self, file_name = None, crystal_symmetry = None,
origin = None, all = None, map_id = None):
self.output_region_map_info_list.append(map_info_object(
file_name = file_name,
crystal_symmetry = crystal_symmetry,
origin = origin,
all = all,
id = len(self.output_region_map_info_list)+1,
map_id = map_id,
is_map = True)
)
def add_output_region_pdb_info(self, file_name = None, n_residues = None):
self.output_region_pdb_info_list.append(pdb_info_object(
file_name = file_name,
n_residues = n_residues)
)
def show_summary(self, out = sys.stdout):
print("\n ========== Summary of %s: ======== \n" %(self.object_type), file = out)
print("Created: %s" %(self.init_asctime), file = out)
print("\nInput files used:\n", file = out)
if self.input_map_info:
self.input_map_info.show_summary(out = out)
if self.input_pdb_info:
self.input_pdb_info.show_summary(out = out)
if self.input_ncs_info:
self.input_ncs_info.show_summary(out = out)
if self.input_seq_info:
self.input_seq_info.show_summary(out = out)
print(file = out)
if self.crystal_symmetry:
print("Working unit cell: %.1f %.1f %.1f %.1f %.1f %.1f " %(
self.crystal_symmetry.unit_cell().parameters()), file = out)
if self.n_residues:
print("Estimated total number of residues: %d" %(self.n_residues), file = out)
if self.solvent_fraction:
print("Estimated solvent fraction: %5.3f" %(self.solvent_fraction), file = out)
if self.origin_shift and self.origin_shift != (0, 0, 0):
print("\nOrigin offset applied: %.1f %.1f %.1f" %(self.origin_shift), file = out)
else:
print("\nNo origin offset applied", file = out)
if self.shifted_map_info:
print("\nShifted/sharpened map, pdb and ncs files created "+\
"(after origin offset):\n", file = out)
if self.shifted_map_info:
self.shifted_map_info.show_summary(out = out)
if self.shifted_pdb_info:
self.shifted_pdb_info.show_summary(out = out)
if self.shifted_ncs_info:
self.shifted_ncs_info.show_summary(out = out)
if self.output_ncs_au_pdb_info:
print("\nOutput PDB file with dummy atoms representing the NCS AU:", file = out)
self.output_ncs_au_pdb_info.show_summary(out = out)
if self.output_ncs_au_mask_info or self.output_ncs_au_map_info:
print("\nOutput map files showing just the NCS AU (same size", end = ' ', file = out)
if self.origin_shift and self.origin_shift != (0, 0, 0):
print("\nand location as shifted map files:\n", file = out)
else:
print("\nand location as input map:\n", file = out)
if self.output_ncs_au_mask_info:
self.output_ncs_au_mask_info.show_summary(out = out)
if self.output_ncs_au_map_info:
self.output_ncs_au_map_info.show_summary(out = out)
if self.output_box_mask_info or self.output_box_map_info:
print("\nOutput cut-out map files trimmed to contain just "+\
"the \nNCS AU (superimposed on", end = ' ', file = out)
if self.origin_shift and self.origin_shift != (0, 0, 0):
print("shifted map files, note origin offset):\n", file = out)
else:
print("input map, note origin offset):\n", file = out)
if self.output_box_mask_info:
self.output_box_mask_info.show_summary(out = out)
if self.output_box_map_info:
self.output_box_map_info.show_summary(out = out)
if self.output_region_pdb_info_list:
print("\nOutput PDB files representing one region of connected"+\
" density.\nThese are useful for marking where to look in cut-out map"+\
" files.", file = out)
for output_region_pdb_info in self.output_region_pdb_info_list:
output_region_pdb_info.show_summary(out = out)
if self.output_region_map_info_list:
print("\nOutput cut-out map files trimmed to contain just "+\
"one region of \nconnected density (superimposed on", end = ' ', file = out)
if self.origin_shift and self.origin_shift != (0, 0, 0):
print("shifted map files, note origin offset):\n", file = out)
else:
print(" input map, note origin offset):\n", file = out)
for output_region_map_info in self.output_region_map_info_list:
output_region_map_info.show_summary(out = out)
print("\n"+50*"="+"\n", file = out)
class make_ccp4_map: # just a holder so map_to_structure_factors will run
# XXX Replace with map_manager
def __init__(self, map = None, unit_cell = None):
self.data = map
self.unit_cell_parameters = unit_cell.parameters()
self.space_group_number = 1
self.unit_cell_grid = map.all()
def unit_cell(self):
return self.crystal_symmetry().unit_cell()
def unit_cell_crystal_symmetry(self):
return self.crystal_symmetry()
def map_data(self):
return self.data
def crystal_symmetry(self):
return crystal.symmetry(self.unit_cell_parameters,
self.space_group_number)
class b_vs_region_info:
def __init__(self):
self.b_iso = 0.
self.b_vs_region_dict = {}
self.sa_sum_v_vs_region_dict = {}
self.sa_nn_vs_region_dict = {}
self.sa_ratio_b_vs_region_dict = {}
class box_sharpening_info:
def __init__(self, tracking_data = None,
crystal_symmetry = None,
solvent_fraction = None,
b_iso = None,
resolution = None,
d_min_ratio = None,
scale_max = None,
lower_bounds = None,
upper_bounds = None,
wrapping = None,
n_real = None,
n_buffer = None,
map_data = None,
smoothing_radius = None,
smoothed_box_mask_data = None,
original_box_map_data = None,
):
from libtbx import adopt_init_args
adopt_init_args(self, locals())
del self.tracking_data # do not save it
if tracking_data:
self.crystal_symmetry = tracking_data.crystal_symmetry
self.solvent_fraction = tracking_data.solvent_fraction
self.wrapping = tracking_data.params.crystal_info.use_sg_symmetry
def get_gaussian_weighting(self, out = sys.stdout):
# return a gaussian function centered on center of the map, fall-off
# based on smoothing_radius
# Calculate weight map, max near location of centers_ncs_cart
# U = rmsd**2
# (b_eff = 8*3.14159**2*U)
# rmsd is at least distance between centers, not too much bigger than
# unit cell size, typically 10-20 A,
print("\nFall-off of local weight is 1/%6.1f A\n" %(
self.smoothing_radius), file = out)
u = self.smoothing_radius**2
from cctbx import xray
xrs, scatterers = set_up_xrs(crystal_symmetry = self.crystal_symmetry)
unit_cell = self.crystal_symmetry.unit_cell()
for xyz_fract in [(0.5, 0.5, 0.5, )]:
scatterers.append( xray.scatterer(scattering_type = "H", label = "H",
site = xyz_fract, u = u, occupancy = 1.0))
xrs = xray.structure(xrs, scatterers = scatterers)
f_array, phases = get_f_phases_from_map(map_data = self.map_data,
crystal_symmetry = self.crystal_symmetry,
d_min = self.resolution,
scale_max = self.scale_max,
d_min_ratio = self.d_min_ratio,
get_remove_aniso_object = False, # don't need it
out = out)
weight_f_array = f_array.structure_factors_from_scatterers(
algorithm = 'direct',
xray_structure = xrs).f_calc()
weight_map = get_map_from_map_coeffs(map_coeffs = weight_f_array,
crystal_symmetry = self.crystal_symmetry, n_real = self.map_data.all())
min_value = weight_map.as_1d().min_max_mean().min
weight_map = weight_map-min_value # all positive or zero
max_value = weight_map.as_1d().min_max_mean().max
weight_map = weight_map/max(1.e-10, max_value) # normalize; max = 1 now
min_value = 1.e-10 # just a small value for all distances far from center
s = (weight_map <min_value ) # make extra sure every point is above this
weight_map = weight_map.set_selected(s, min_value)
return weight_map
def remove_buffer_from_bounds(self, minimum = 1):
# back off by n_buffer in each direction, leave at
# least minimum grid on either side of center
adjusted_lower_bounds, adjusted_upper_bounds = [], []
delta_lower_bounds, delta_upper_bounds = [], []
for lb, ub in zip(self.lower_bounds, self.upper_bounds):
sum = lb+ub
if sum >= 0:
mid = (1+sum)//2
else:
mid = (-1+sum)//2
alb = min(mid-minimum, lb+self.n_buffer)
aub = max(mid+minimum, ub-self.n_buffer)
adjusted_lower_bounds.append(alb)
adjusted_upper_bounds.append(aub)
delta_lower_bounds.append(alb-lb)
delta_upper_bounds.append(aub-ub)
return adjusted_lower_bounds, adjusted_upper_bounds, \
delta_lower_bounds, delta_upper_bounds
def merge_into_overall_map(self, overall_map = None):
# Smoothly fill out edges of the small map with overall_map
assert self.smoothed_box_mask_data is not None
assert self.original_box_map_data is not None
self.map_data = (self.map_data * self.smoothed_box_mask_data) + \
(self.original_box_map_data * (1-self.smoothed_box_mask_data))
def remove_buffer(self, out = sys.stdout):
# remove the buffer from this box
new_lower_bounds, new_upper_bounds, delta_lower, delta_upper = \
self.remove_buffer_from_bounds()
cut_out_lower_bounds = []
cut_out_upper_bounds = []
for o, a, dlb, dub in zip(self.map_data.origin(), self.map_data.all(),
delta_lower, delta_upper):
cut_out_lower_bounds.append(o+dlb)
cut_out_upper_bounds.append(a+dub-1)
self.map_data, self.crystal_symmetry, \
self.smoothed_box_mask_data, self.original_box_map_data = cut_out_map(
map_data = self.map_data,
crystal_symmetry = self.crystal_symmetry,
soft_mask = False,
resolution = self.resolution,
shift_origin = True,
min_point = cut_out_lower_bounds,
max_point = cut_out_upper_bounds, out = out)
self.lower_bounds = new_lower_bounds
self.upper_bounds = new_upper_bounds
class sharpening_info:
def __init__(self,
tracking_data = None,
crystal_symmetry = None,
is_crystal = None,
sharpening_method = None,
solvent_fraction = None,
n_residues = None,
ncs_copies = None,
ncs_file = None,
seq_file = None,
sequence = None,
n_real = None,
region_weight = None,
n_bins = None,
eps = None,
d_min = None,
d_min_ratio = None,
scale_max = None,
input_d_cut = None,
b_blur_hires = None,
rmsd = None,
rmsd_resolution_factor = None,
k_sol = None,
b_sol = None,
fraction_complete = None,
wrapping = None,
sharpening_target = None,
residual_target = None,
fraction_occupied = None,
nproc = None,
multiprocessing = None,
queue_run_command = None,
resolution = None, # changed from d_cut
resolution_dependent_b = None, # linear sharpening
normalize_amplitudes_in_resdep = None, # linear sharpening
b_sharpen = None,
b_iso = None, # expected B_iso after applying b_sharpen
k_sharpen = None,
optimize_b_blur_hires = None,
iterate = None,
optimize_d_cut = None,
kurtosis = None,
adjusted_sa = None,
sa_ratio = None,
normalized_regions = None,
score = None,
input_weight_map_pickle_file = None,
output_weight_map_pickle_file = None,
read_sharpened_maps = None,
write_sharpened_maps = None,
select_sharpened_map = None,
output_directory = None,
smoothing_radius = None,
local_sharpening = None,
local_aniso_in_local_sharpening = None,
overall_before_local = None,
use_local_aniso = None,
original_aniso_obj = None,
auto_sharpen = None,
box_in_auto_sharpen = None,
density_select_in_auto_sharpen = None,
density_select_threshold_in_auto_sharpen = None,
use_weak_density = None,
discard_if_worse = None,
max_box_fraction = None,
cc_cut = None,
max_cc_for_rescale = None,
scale_using_last = None,
density_select_max_box_fraction = None,
mask_atoms = None,
mask_atoms_atom_radius = None,
value_outside_atoms = None,
soft_mask = None,
allow_box_if_b_iso_set = None,
search_b_min = None,
search_b_max = None,
search_b_n = None,
adjust_region_weight = None,
region_weight_method = None,
region_weight_factor = None,
region_weight_buffer = None,
region_weight_default = None,
target_b_iso_ratio = None,
signal_min = None,
target_b_iso_model_scale = None,
box_sharpening_info_obj = None,
chain_type = None,
target_scale_factors = None,
remove_aniso = None,
d_min_list = None,
verbose = None,
resolve_size = None,
pdb_inp = None, # XXX probably do not need this
local_solvent_fraction = None,
wang_radius = None,
buffer_radius = None,
pseudo_likelihood = None,
preliminary_sharpening_done = False,
adjusted_path_length = None,
):
from libtbx import adopt_init_args
adopt_init_args(self, locals())
del self.tracking_data # don't need it as part of the object
del self.box_sharpening_info_obj# don't need it as part of the object
del self.pdb_inp # don't need it as part of the object
if tracking_data: # use tracking data information
self.update_with_tracking_data(tracking_data = tracking_data)
if box_sharpening_info_obj: # update information
self.update_with_box_sharpening_info(
box_sharpening_info_obj = box_sharpening_info_obj)
if self.resolution_dependent_b is None:
self.resolution_dependent_b = [0, 0, 0]
if self.target_scale_factors and \
self.sharpening_method!= 'model_sharpening' \
and self.sharpening_method!= 'half_map_sharpening':
assert self.sharpening_method is None # XXX may want to print out error
self.sharpening_method = 'model_sharpening'
if self.sharpening_method == 'b_iso' and self.k_sharpen is not None:
self.k_sharpen = None
if pdb_inp:
self.sharpening_method = 'model_sharpening'
self.box_in_auto_sharpen = True
self.density_select_in_auto_sharpen = False
self.sharpening_target = 'model'
def get_d_cut(self):
if self.input_d_cut is not None:
return self.input_d_cut
else:
return self.resolution
def get_target_b_iso(self):
if self.target_b_iso_ratio is None:
return None
if self.resolution is None:
return None
return self.target_b_iso_ratio*self.resolution**2
def set_resolution_dependent_b(self,
resolution_dependent_b = None,
sharpening_method = 'resolution_dependent'):
if resolution_dependent_b:
self.resolution_dependent_b = resolution_dependent_b
if sharpening_method:
self.sharpening_method = sharpening_method
def sharpening_is_defined(self):
if self.sharpening_method is None:
return False
if self.target_scale_factors:
return True
if self.sharpening_method == 'target_b_iso_to_d_cut':
return True
if self.b_iso is not None or \
self.b_sharpen is not None or \
(self.resolution_dependent_b is not None and
self.resolution_dependent_b!= [0, 0, 0]):
return True
return False
def update_with_box_sharpening_info(self, box_sharpening_info_obj = None):
if not box_sharpening_info_obj:
return self
self.crystal_symmetry = box_sharpening_info_obj.crystal_symmetry
self.solvent_fraction = box_sharpening_info_obj.solvent_fraction
self.wrapping = box_sharpening_info_obj.wrapping
self.n_real = box_sharpening_info_obj.n_real
return self
def update_with_tracking_data(self, tracking_data = None):
self.update_with_params(params = tracking_data.params,
crystal_symmetry = tracking_data.crystal_symmetry,
solvent_fraction = tracking_data.solvent_fraction,
n_residues = tracking_data.n_residues,
ncs_copies = tracking_data.input_ncs_info.number_of_operators)
return self
def update_with_params(self, params = None,
crystal_symmetry = None,
is_crystal = None,
solvent_fraction = None,
auto_sharpen = None,
sharpening_method = None,
pdb_inp = None,
half_map_data_list = None,
n_residues = None, ncs_copies = None):
self.crystal_symmetry = crystal_symmetry
self.is_crystal = is_crystal
self.solvent_fraction = solvent_fraction
self.auto_sharpen = auto_sharpen
self.n_residues = n_residues
self.ncs_copies = ncs_copies
self.seq_file = params.input_files.seq_file
self.chain_type = params.crystal_info.chain_type
self.verbose = params.control.verbose
self.resolve_size = params.control.resolve_size
self.multiprocessing = params.control.multiprocessing
self.nproc = params.control.nproc
self.queue_run_command = params.control.queue_run_command
self.wrapping = params.crystal_info.use_sg_symmetry
self.fraction_occupied = params.map_modification.fraction_occupied
self.sa_percent = params.map_modification.sa_percent
self.region_weight = params.map_modification.region_weight
self.max_regions_to_test = params.map_modification.max_regions_to_test
self.regions_to_keep = params.map_modification.regions_to_keep
self.d_min_ratio = params.map_modification.d_min_ratio
self.scale_max = params.map_modification.scale_max
self.input_d_cut = params.map_modification.input_d_cut
self.b_blur_hires = params.map_modification.b_blur_hires
self.rmsd = params.map_modification.rmsd
self.rmsd_resolution_factor = params.map_modification.rmsd_resolution_factor
self.k_sol = params.map_modification.k_sol
self.b_sol = params.map_modification.b_sol
self.fraction_complete = params.map_modification.fraction_complete
self.resolution = params.crystal_info.resolution # changed from d_cut
# NOTE:
# resolution = X-ray resolution or nominal resolution of cryoEM map
# high-res cutoff of reflections is d_min*d_min_ratio
self.buffer_radius = params.crystal_info.buffer_radius
self.wang_radius = params.crystal_info.wang_radius
self.pseudo_likelihood = params.crystal_info.pseudo_likelihood
self.max_box_fraction = params.map_modification.max_box_fraction
self.cc_cut = params.map_modification.cc_cut
self.max_cc_for_rescale = params.map_modification.max_cc_for_rescale
self.scale_using_last = params.map_modification.scale_using_last
self.density_select_max_box_fraction = params.map_modification.density_select_max_box_fraction
self.mask_atoms = params.map_modification.mask_atoms
self.mask_atoms_atom_radius = params.map_modification.mask_atoms_atom_radius
self.value_outside_atoms = params.map_modification.value_outside_atoms
self.soft_mask = params.map_modification.soft_mask
self.allow_box_if_b_iso_set = params.map_modification.allow_box_if_b_iso_set
self.k_sharpen = params.map_modification.k_sharpen
self.optimize_b_blur_hires = params.map_modification.optimize_b_blur_hires
self.iterate = params.map_modification.iterate
self.optimize_d_cut = params.map_modification.optimize_d_cut
self.sharpening_target = params.map_modification.sharpening_target
self.residual_target = params.map_modification.residual_target
self.eps = params.map_modification.eps
self.n_bins = params.map_modification.n_bins
self.input_weight_map_pickle_file = params.input_files.input_weight_map_pickle_file
self.output_weight_map_pickle_file = params.output_files.output_weight_map_pickle_file
self.read_sharpened_maps = params.map_modification.read_sharpened_maps
self.write_sharpened_maps = params.map_modification.write_sharpened_maps
self.select_sharpened_map = params.map_modification.select_sharpened_map
self.output_directory = params.output_files.output_directory
self.smoothing_radius = params.map_modification.smoothing_radius
self.local_sharpening = params.map_modification.local_sharpening
self.local_aniso_in_local_sharpening = \
params.map_modification.local_aniso_in_local_sharpening
self.overall_before_local = \
params.map_modification.overall_before_local
self.box_in_auto_sharpen = params.map_modification.box_in_auto_sharpen
self.density_select_in_auto_sharpen = params.map_modification.density_select_in_auto_sharpen
self.density_select_threshold_in_auto_sharpen = params.map_modification.density_select_threshold_in_auto_sharpen
self.use_weak_density = params.map_modification.use_weak_density
self.discard_if_worse = params.map_modification.discard_if_worse
self.box_center = params.map_modification.box_center
self.box_size = params.map_modification.box_size
self.target_n_overlap = params.map_modification.target_n_overlap
self.restrict_map_size = params.map_modification.restrict_map_size
self.remove_aniso = params.map_modification.remove_aniso
self.min_ratio_of_ncs_copy_to_first = \
params.segmentation.min_ratio_of_ncs_copy_to_first
self.max_ratio_to_target = params.segmentation.max_ratio_to_target
self.min_ratio_to_target = params.segmentation.min_ratio_to_target
self.residues_per_region = params.segmentation.residues_per_region
self.mask_padding_fraction = \
params.segmentation.mask_padding_fraction
self.fraction_of_max_mask_threshold = \
params.segmentation.fraction_of_max_mask_threshold
self.cell_cutoff_for_solvent_from_mask = \
params.segmentation.cell_cutoff_for_solvent_from_mask
self.starting_density_threshold = \
params.segmentation.starting_density_threshold
self.density_threshold = params.segmentation.density_threshold
self.min_ratio = params.segmentation.min_ratio
self.min_volume = params.segmentation.min_volume
self.search_b_min = params.map_modification.search_b_min
self.search_b_max = params.map_modification.search_b_max
self.search_b_n = params.map_modification.search_b_n
self.adjust_region_weight = params.map_modification.adjust_region_weight
self.region_weight_method = params.map_modification.region_weight_method
self.region_weight_factor = params.map_modification.region_weight_factor
self.region_weight_buffer = params.map_modification.region_weight_buffer
self.region_weight_default = params.map_modification.region_weight_default
self.target_b_iso_ratio = params.map_modification.target_b_iso_ratio
self.signal_min = params.map_modification.signal_min
self.target_b_iso_model_scale = params.map_modification.target_b_iso_model_scale
if sharpening_method is not None:
self.sharpening_method = sharpening_method
if not self.sharpening_method and \
len(params.map_modification.auto_sharpen_methods) == 1:
self.sharpening_method = params.map_modification.auto_sharpen_methods[0]
if half_map_data_list or self.sharpening_method == 'half_map_sharpening':
self.sharpening_method = 'half_map_sharpening'
self.sharpening_target = 'half_map'
elif pdb_inp or self.sharpening_method == 'model_sharpening':
self.sharpening_method = 'model_sharpening'
self.box_in_auto_sharpen = True
self.density_select_in_auto_sharpen = False
self.sharpening_target = 'model'
elif params.map_modification.b_iso is not None or \
params.map_modification.b_sharpen is not None:
if self.sharpening_method is None:
raise Sorry("b_iso is not set")
# if sharpening values are specified, set them
if params.map_modification.b_iso is not None:
self.b_iso = params.map_modification.b_iso # but we need b_sharpen
elif params.map_modification.b_sharpen is not None:
self.b_sharpen = params.map_modification.b_sharpen
elif (params.map_modification.resolution_dependent_b is not None
and params.map_modification.resolution_dependent_b!= [0, 0, 0]):
self.sharpening_method = 'resolution_dependent'
self.resolution_dependent_b = \
params.map_modification.resolution_dependent_b
if self.sharpening_method == 'b_iso' and self.k_sharpen is not None:
self.k_sharpen = None
return self
def show_summary(self, verbose = False, out = sys.stdout):
method_summary_dict = {
'b_iso':"Overall b_iso sharpening",
'b_iso_to_d_cut':"b_iso sharpening to high_resolution cutoff",
'resolution_dependent':"Resolution-dependent sharpening",
'model_sharpening':"Model sharpening",
'half_map_sharpening':"Half-map sharpening",
'no_sharpening':"No sharpening",
None:"No sharpening",
}
target_summary_dict = {
'adjusted_sa':"Adjusted surface area",
'adjusted_path_length':"Adjusted path length",
'kurtosis':"Map kurtosis",
'model':"Map-model CC",
}
print("\nSummary of sharpening:\n", file = out)
print("Sharpening method used: %s\n" %(
method_summary_dict.get(self.sharpening_method)), file = out)
if self.sharpening_method == "b_iso":
if self.b_sharpen is not None:
print("Overall b_sharpen applied: %7.2f A**2" %(
self.b_sharpen), file = out)
if self.b_iso is not None:
print("Final b_iso obtained: %7.2f A**2" %(self.b_iso), file = out)
elif self.sharpening_method == "b_iso_to_d_cut":
if self.b_sharpen is not None:
print("Overall b_sharpen applied: %7.2f A**2" %(
self.b_sharpen), file = out)
if self.b_iso is not None:
print("Final b_iso obtained: %7.2f A**2" %(self.b_iso), file = out)
if self.input_d_cut:
print("High-resolution cutoff: %7.2f A" %(self.input_d_cut), file = out)
else:
print("High-resolution cutoff: %7.2f A" %(self.resolution), file = out)
elif self.sharpening_method == "resolution_dependent":
print("Resolution-dependent b values (%7.2f, %7.2f, %7.2f)\n" %(
tuple(self.resolution_dependent_b)), file = out)
print("Effective b_iso vs resolution obtained:", file = out)
from cctbx.maptbx.refine_sharpening import get_effective_b_values
d_min_values, b_values = get_effective_b_values(
d_min_ratio = self.d_min_ratio,
resolution_dependent_b = self.resolution_dependent_b,
resolution = self.resolution)
print(" Resolution Effective B-iso", file = out)
print(" (A) (A**2)", file = out)
for dd, b in zip(d_min_values, b_values):
print(" %7.1f %7.2f " %(
dd, b), file = out)
elif self.sharpening_method == "model_sharpening":
print("Resolution-dependent model sharpening", file = out)
if self.d_min_list and self.target_scale_factors:
print("Scale vs resolution:", file = out)
for d_min, sc in zip(
self.d_min_list,
self.target_scale_factors):
print("Dmin: %7.2f Scale: %9.6f" %(d_min, sc), file = out)
elif self.sharpening_method == "half_map_sharpening":
print("Resolution-dependent half-map sharpening", file = out)
if self.d_min_list and self.target_scale_factors:
print("Scale vs resolution:", file = out)
for d_min, sc in zip(
self.d_min_list,
self.target_scale_factors):
print("Dmin: %7.2f Scale: %9.6f" %(d_min, sc), file = out)
if self.sharpening_method in ["b_iso_to_d_cut"] and \
self.k_sharpen and self.resolution:
print("Transition from sharpening"+\
" to not sharpening (k_sharpen):%7.2f " %(self.k_sharpen), file = out)
print("\nSharpening target used: %s" %(
target_summary_dict.get(self.sharpening_target)), file = out)
if self.adjusted_sa is not None:
print("Final adjusted map surface area: %7.2f" %(self.adjusted_sa), file = out)
if self.kurtosis is not None:
print("Final map kurtosis: %7.2f" %(self.kurtosis), file = out)
if hasattr(self, 'adjusted_path_length') and \
self.adjusted_path_length is not None:
print("Final adjusted path length: %7.2f A" %(
self.adjusted_path_length), file = out)
print(file = out)
if verbose:
for x in dir(self):
if x.startswith("__"): continue
if type(getattr(self, x)) in [type('a'), type(1), type(1.), type([]),
type((1, 2, ))]:
print("%s : %s" %(x, getattr(self, x)), file = out)
def get_effective_b_iso(self, map_data = None, out = sys.stdout):
map_coeffs_ra, map_coeffs, f_array, phases = effective_b_iso(
map_data = map_data,
resolution = self.resolution,
d_min_ratio = self.d_min_ratio,
scale_max = self.scale_max,
crystal_symmetry = self.crystal_symmetry,
out = out)
return map_coeffs_ra.b_iso
def sharpen_and_score_map(self, map_data = None, set_b_iso = False, out = sys.stdout):
if self.n_real is None: # need to get it
self.n_real = map_data.all()
map_and_b = sharpen_map_with_si(
sharpening_info_obj = self,
map_data = map_data,
resolution = self.resolution, out = out)
self.map_data = map_and_b.map_data
if set_b_iso:
self.b_iso = map_and_b.final_b_iso
score_map(map_data = self.map_data,
sharpening_info_obj = self,
out = null_out())
return self
def show_score(self, out = sys.stdout):
print("Adjusted surface area: %7.3f Kurtosis: %7.3f Score: %7.3f\n" %(
self.adjusted_sa, self.kurtosis, self.score), file = out)
def is_target_b_iso_to_d_cut(self):
if self.sharpening_method == 'target_b_iso_to_d_cut':
return True
else:
return False
def is_b_iso_sharpening(self):
if self.is_resolution_dependent_sharpening():
return False
if self.is_model_sharpening():
return False
if self.is_half_map_sharpening():
return False
if self.is_external_map_sharpening():
return False
return True
def is_resolution_dependent_sharpening(self):
if self.sharpening_method == 'resolution_dependent':
return True
else:
return False
def is_model_sharpening(self):
if self.sharpening_method == 'model_sharpening':
return True
else:
return False
def is_external_map_sharpening(self):
if self.sharpening_method == 'external_map_sharpening':
return True
else:
return False
def is_half_map_sharpening(self):
if self.sharpening_method == 'half_map_sharpening':
return True
else:
return False
def as_map_coeffs(self, out = sys.stdout):
map_data = getattr(self, 'map_data', None)
if map_data:
map_coeffs, dummy = get_f_phases_from_map(map_data = self.map_data,
crystal_symmetry = self.crystal_symmetry,
d_min = self.resolution,
d_min_ratio = self.d_min_ratio,
scale_max = self.scale_max,
return_as_map_coeffs = True,
out = out)
return map_coeffs
else:
return None
def as_map_data(self):
return getattr(self, 'map_data', None)
class ncs_group_object:
def __init__(self,
ncs_obj = None,
ncs_ops_used = None,
ncs_group_list = None,
edited_mask = None,
crystal_symmetry = None,
max_cell_dim = None,
origin_shift = None,
edited_volume_list = None,
region_range_dict = None,
selected_regions = None,
ncs_related_regions = None,
self_and_ncs_related_regions = None,
equiv_dict = None,
map_files_written = None,
bad_region_list = None,
region_centroid_dict = None,
region_scattered_points_dict = None,
shared_group_dict = None,
co = None,
min_b = None,
max_b = None,
original_id_from_id = None,
remainder_id_dict = None, # dict relating regions in a remainder object to
# those in the original map
):
if not selected_regions: selected_regions = []
if not ncs_related_regions: ncs_related_regions = []
if not self_and_ncs_related_regions: self_and_ncs_related_regions = []
if not map_files_written: map_files_written = []
if not max_cell_dim: max_cell_dim = 0.
from libtbx import adopt_init_args
adopt_init_args(self, locals())
if self.crystal_symmetry and not self.max_cell_dim:
self.max_cell_dim = 0.
for x in self.crystal_symmetry.unit_cell().parameters()[:3]:
self.max_cell_dim = max(max_cell_dim, x)
def as_info_object(self):
return info_object(
ncs_obj = self.ncs_obj,
max_b = self.max_b,
min_b = self.min_b,
ncs_group_list = self.ncs_group_list,
origin_shift = self.origin_shift,
edited_volume_list = self.edited_volume_list,
region_range_dict = self.region_range_dict,
selected_regions = self.selected_regions,
ncs_related_regions = self.ncs_related_regions,
self_and_ncs_related_regions = self.self_and_ncs_related_regions,
bad_region_list = self.bad_region_list,
region_centroid_dict = self.region_centroid_dict,
original_id_from_id = self.original_id_from_id,
map_files_written = self.map_files_written,
)
def set_ncs_ops_used(self, ncs_ops_used):
self.ncs_ops_used = deepcopy(ncs_ops_used)
def set_selected_regions(self, selected_regions):
self.selected_regions = deepcopy(selected_regions)
def set_ncs_related_regions(self, ncs_related_regions):
self.ncs_related_regions = deepcopy(ncs_related_regions)
def set_self_and_ncs_related_regions(self, self_and_ncs_related_regions):
self.self_and_ncs_related_regions = deepcopy(self_and_ncs_related_regions)
def set_map_files_written(self, map_files_written):
self.map_files_written = deepcopy(map_files_written)
def zero_if_none(x):
if not x:
return 0
else:
return x
def scale_map(map, scale_rms = 1.0, out = sys.stdout):
sd = map.as_double().as_1d().sample_standard_deviation()
if (sd > 1.e-10):
scale = scale_rms/sd
if 0: print("Scaling map by %7.3f to set SD = 1" %(scale), file = out)
map = map*scale
else:
print("Cannot scale map...all zeros", file = out)
return map
def scale_map_coeffs(map_coeffs, scale_max = None, out = sys.stdout):
f_array, phases = map_coeffs_as_fp_phi(map_coeffs)
max_value = f_array.data().min_max_mean().max
if scale_max:
scale = scale_max/max(1.e-10, max_value)
else:
scale = 1.0
if 0:
print("Scaling map_coeffs by %9.3f to yield maximum of %7.0f" %(
scale, scale_max), file = out)
return f_array.array(data = f_array.data()*scale
).phase_transfer(phase_source = phases, deg = True)
def get_map_object(file_name = None, must_allow_sharpening = None,
get_map_labels = None, out = sys.stdout):
# read a ccp4 map file and return sg, cell and map objects 2012-01-16
if not os.path.isfile(file_name):
raise Sorry("The map file %s is missing..." %(file_name))
map_labels = None
if file_name.endswith(".xplor"):
import iotbx.xplor.map
m = iotbx.xplor.map.reader(file_name = file_name)
m.unit_cell_grid = m.map_data().all() # just so we have something
m.space_group_number = 0 # so we have something
else:
from iotbx import mrcfile
m = mrcfile.map_reader(file_name = file_name)
print("MIN MAX MEAN RMS of map: %7.2f %7.2f %7.2f %7.2f " %(
m.header_min, m.header_max, m.header_mean, m.header_rms), file = out)
print("grid: ", m.unit_cell_grid, file = out)
print("cell: %8.3f %8.3f %8.3f %8.3f %8.3f %8.3f " %tuple(
m.unit_cell().parameters()), file = out)
print("SG: ", m.unit_cell_crystal_symmetry().space_group_number(), file = out)
if must_allow_sharpening and m.cannot_be_sharpened():
raise Sorry("Input map is already modified and should not be sharpened")
if get_map_labels:
map_labels = m.labels
print("ORIGIN: ", m.map_data().origin(), file = out)
print("EXTENT: ", m.map_data().all(), file = out)
print("IS PADDED: ", m.map_data().is_padded(), file = out)
map_data = m.data
acc = map_data.accessor()
shift_needed = not \
(map_data.focus_size_1d() > 0 and map_data.nd() == 3 and
map_data.is_0_based())
if(shift_needed):
map_data = map_data.shift_origin()
origin_shift = (
m.map_data().origin()[0]/m.map_data().all()[0],
m.map_data().origin()[1]/m.map_data().all()[1],
m.map_data().origin()[2]/m.map_data().all()[2])
origin_frac = origin_shift # NOTE: fraction of NEW cell
else:
origin_frac = (0., 0., 0.)
# determine if we need to trim off the outer part of the map duplicating inner
offsets = []
need_offset = False
for g, e in zip(m.unit_cell_grid, map_data.all() ):
offset = e-g
offsets.append(offset)
if offsets == [1, 1, 1]:
if origin_frac!= (0., 0., 0.): # this was a shifted map...we can't do this
raise Sorry("Sorry if a CCP4 map has an origin other than (0, 0, 0) "+
"the extent \nof the map must be the same as the grid or 1 "+
"\ngreater for "+
"segment_and_split_map routines."+
"The file %s has a grid of %s and extent of %s" %(
file_name, str(m.unit_cell_grid), str(map_data.all())))
map = map_data[:-1, :-1, :-1]
acc = map.accessor()
else:
map = map_data
# now get space group and cell
from cctbx import crystal
from cctbx import sgtbx
if m.unit_cell_crystal_symmetry().space_group_number() == 0:
n = 1 # fix mrc formatting
else:
n = m.unit_cell_crystal_symmetry().space_group_number()
if hasattr(m, 'crystal_symmetry'):
space_group_info = sgtbx.space_group_info(number = n)
unit_cell = m.unit_cell_crystal_symmetry().unit_cell()
original_unit_cell_grid = m.unit_cell_grid
original_crystal_symmetry = crystal.symmetry(
unit_cell = unit_cell, space_group_info = space_group_info)
if original_crystal_symmetry and map.all() == m.unit_cell_grid:
crystal_symmetry = original_crystal_symmetry
print("\nUnit cell crystal symmetry used: ", file = out)
else:
crystal_symmetry = m.crystal_symmetry()
print("\nBox crystal symmetry used: ", file = out)
crystal_symmetry.show_summary(f = out)
space_group = crystal_symmetry.space_group()
unit_cell = crystal_symmetry.unit_cell()
else:
space_group = None
unit_cell = None
crystal_symmetry = None
original_crystal_symmetry, original_unit_cell_grid = None, None
map = scale_map(map, out = out)
if get_map_labels:
return map, space_group, unit_cell, crystal_symmetry, origin_frac, acc, \
original_crystal_symmetry, original_unit_cell_grid, map_labels
else:
return map, space_group, unit_cell, crystal_symmetry, origin_frac, acc, \
original_crystal_symmetry, original_unit_cell_grid
def write_ccp4_map(crystal_symmetry, file_name, map_data,
output_unit_cell_grid = None, labels = None):
if output_unit_cell_grid is None:
output_unit_cell_grid = map_data.all()
if labels is None:
labels = flex.std_string([""])
iotbx.mrcfile.write_ccp4_map(
file_name = file_name,
unit_cell = crystal_symmetry.unit_cell(),
space_group = crystal_symmetry.space_group(),
unit_cell_grid = output_unit_cell_grid,
map_data = map_data.as_double(),
labels = labels)
def set_up_xrs(crystal_symmetry = None): # dummy xrs to write out atoms
lines = ["ATOM 92 SG CYS A 10 8.470 28.863 18.423 1.00 22.05 S"] # just a random line to set up x-ray structure
from cctbx.array_family import flex
pdb_inp = iotbx.pdb.input(source_info = "", lines = lines)
xrs = pdb_inp.xray_structure_simple(crystal_symmetry = crystal_symmetry)
scatterers = flex.xray_scatterer()
return xrs, scatterers
def write_atoms(tracking_data = None, sites = None, file_name = None,
crystal_symmetry = None,
atom_name = None, resname = None, atom_type = None, occ = None,
out = sys.stdout):
if crystal_symmetry is None:
crystal_symmetry = tracking_data.crystal_symmetry
xrs, scatterers = set_up_xrs(crystal_symmetry = crystal_symmetry)
from cctbx import xray
unit_cell = crystal_symmetry.unit_cell()
for xyz_cart in sites:
scatterers.append( xray.scatterer(scattering_type = "O",
label = "O",
site = unit_cell.fractionalize(xyz_cart), u = 0.38, occupancy = 1.0))
text = write_xrs(xrs = xrs, scatterers = scatterers, file_name = file_name, out = out)
if atom_name and resname and atom_type:
text = text.replace("O O ", " %2s %3s A" %(atom_name, resname) )
text = text.replace(" O", " %1s" %(atom_type))
if occ:
text = text.replace(" 1.00 ", " %.2f " %(occ))
return text
def write_xrs(xrs = None, scatterers = None, file_name = "atoms.pdb", out = sys.stdout):
from cctbx import xray
xrs = xray.structure(xrs, scatterers = scatterers)
text = xrs.as_pdb_file()
if file_name:
f = open(file_name, 'w')
print(text, file = f)
f.close()
print("Atoms written to %s" %file_name, file = out)
return text
def get_b_iso(miller_array, d_min = None, return_aniso_scale_and_b = False,
d_max = 100000.):
if d_min:
res_cut_array = miller_array.resolution_filter(d_max = d_max,
d_min = d_min)
else:
res_cut_array = miller_array
from mmtbx.scaling import absolute_scaling
try:
aniso_scale_and_b = absolute_scaling.ml_aniso_absolute_scaling(
miller_array = res_cut_array, n_residues = 200, n_bases = 0, ignore_errors = True)
b_cart = aniso_scale_and_b.b_cart
except Exception as e:
b_cart = [0, 0, 0]
aniso_scale_and_b = None
b_aniso_mean = 0.
if b_cart:
for k in [0, 1, 2]:
b_aniso_mean+= b_cart[k]
if return_aniso_scale_and_b:
return b_aniso_mean/3.0, aniso_scale_and_b
else: # usual
return b_aniso_mean/3.0
def map_coeffs_as_fp_phi(map_coeffs):
amplitudes = map_coeffs.amplitudes()
amplitudes.set_observation_type_xray_amplitude()
assert amplitudes.is_real_array()
phases = map_coeffs.phases(deg = True)
return amplitudes, phases
def map_coeffs_to_fp(map_coeffs):
amplitudes = map_coeffs.amplitudes()
amplitudes.set_observation_type_xray_amplitude()
assert amplitudes.is_real_array()
return amplitudes
def get_f_phases_from_model(f_array = None, pdb_inp = None, overall_b = None,
k_sol = None, b_sol = None, out = sys.stdout):
xray_structure = pdb_inp.construct_hierarchy().extract_xray_structure(
crystal_symmetry = f_array.crystal_symmetry())
print("Getting map coeffs from model with %s atoms.." %(
xray_structure.sites_frac().size()), file = out)
if overall_b is not None:
print("Setting overall b_iso to %7.1f for model " %(
overall_b), file = out)
xray_structure.set_b_iso(value = overall_b)
model_f_array = f_array.structure_factors_from_scatterers(
xray_structure = xray_structure).f_calc()
return model_f_array
def get_f_phases_from_map(
map_data = None, crystal_symmetry = None, d_min = None,
d_max = 100000.,
d_min_ratio = None,
return_as_map_coeffs = False,
remove_aniso = None,
get_remove_aniso_object = True,
scale_max = None,
origin_frac = None,
out = sys.stdout):
if d_min is not None:
d_min_use = d_min
if d_min_ratio is not None:
d_min_use = d_min*d_min_ratio
else:
d_min_use = None
if map_data.origin() != (0,0,0):
map_data = map_data.shift_origin()
from iotbx.map_manager import map_manager
mm = map_manager(map_data = map_data,
unit_cell_grid = map_data.all(),
unit_cell_crystal_symmetry = crystal_symmetry,
wrapping = False)
map_coeffs = mm.map_as_fourier_coefficients(d_min = d_min_use,
d_max = d_max if d_min_use is not None else None)
if origin_frac and tuple(origin_frac) != (0., 0., 0.): # shift origin
map_coeffs = map_coeffs.translational_shift(origin_frac, deg = False)
map_coeffs = scale_map_coeffs(map_coeffs, scale_max = scale_max, out = out)
if remove_aniso:
print("\nRemoving aniso in data before analysis\n", file = out)
get_remove_aniso_object = True
from cctbx.maptbx.refine_sharpening import analyze_aniso
map_coeffs, map_coeffs_ra = analyze_aniso(
remove_aniso = remove_aniso,
get_remove_aniso_object = get_remove_aniso_object,
map_coeffs = map_coeffs, resolution = d_min, out = out)
if return_as_map_coeffs:
return map_coeffs, map_coeffs_ra
else:
return map_coeffs_as_fp_phi(map_coeffs)
def apply_sharpening(map_coeffs = None,
sharpening_info_obj = None,
n_real = None, b_sharpen = None, crystal_symmetry = None,
target_scale_factors = None,
f_array = None, phases = None, d_min = None, k_sharpen = None,
b_blur_hires = None,
include_sharpened_map_coeffs = False,
out = sys.stdout):
if map_coeffs and f_array is None and phases is None:
f_array, phases = map_coeffs_as_fp_phi(map_coeffs)
if sharpening_info_obj is not None:
b_sharpen = sharpening_info_obj.b_sharpen
b_blur_hires = sharpening_info_obj.b_blur_hires
k_sharpen = sharpening_info_obj.k_sharpen
if sharpening_info_obj.input_d_cut:
d_min = sharpening_info_obj.input_d_cut
else:
d_min = sharpening_info_obj.resolution# changed from d_cut
n_real = sharpening_info_obj.n_real
target_scale_factors = sharpening_info_obj.target_scale_factors
n_bins = sharpening_info_obj.n_bins
remove_aniso = sharpening_info_obj.remove_aniso
resolution = sharpening_info_obj.resolution
if target_scale_factors:
assert sharpening_info_obj is not None
print("\nApplying target scale factors vs resolution", file = out)
if not map_coeffs:
map_coeffs = f_array.phase_transfer(phase_source = phases, deg = True)
f_array, phases = map_coeffs_as_fp_phi(map_coeffs)
f_array_b_iso = get_b_iso(f_array, d_min = d_min)
if not f_array.binner():
(local_d_max, local_d_min) = f_array.d_max_min(
d_max_is_highest_defined_if_infinite=True)
f_array.setup_binner(n_bins = n_bins, d_max = local_d_max,
d_min = local_d_min)
from cctbx.maptbx.refine_sharpening import apply_target_scale_factors
map_and_b = apply_target_scale_factors(f_array = f_array, phases = phases,
resolution = d_min,
target_scale_factors = target_scale_factors,
n_real = n_real,
out = out)
return map_and_b
elif b_sharpen is None or (
b_sharpen in [0, None] and k_sharpen in [0, None]):
if not map_coeffs:
map_coeffs = f_array.phase_transfer(phase_source = phases, deg = True)
map_data = get_map_from_map_coeffs(map_coeffs = map_coeffs,
crystal_symmetry = crystal_symmetry, n_real = n_real)
return map_and_b_object(map_data = map_data)
elif k_sharpen is None or d_min is None or k_sharpen<= 0 or \
( b_blur_hires is None and b_sharpen < 0):
# 2016-08-10 original method: apply b_sharpen to all data
# Use this if blurring (b_sharpen<0) or if k_sharpen is not set
from cctbx import adptbx # next lines from xtriage (basic_analysis.py)
b_cart_aniso_removed = [ b_sharpen, b_sharpen, b_sharpen, 0, 0, 0]
from mmtbx.scaling import absolute_scaling
u_star_aniso_removed = adptbx.u_cart_as_u_star(
f_array.unit_cell(), adptbx.b_as_u( b_cart_aniso_removed ) )
f_array_sharpened = absolute_scaling.anisotropic_correction(
f_array, 0.0, u_star_aniso_removed, must_be_greater_than = -0.0001)
else:
# Apply sharpening only to data from infinity to d_min, with transition
# steepness of k_sharpen.
# 2017-08-21 if b_blur_hires is set, sharpen with
# b_sharpen-b_blur_hires data beyond d_min (with same
# transition, so transition goes from b_sharpen TO b_sharpen-b_blur_hires
data_array = f_array.data()
sthol_array = f_array.sin_theta_over_lambda_sq()
d_spacings = f_array.d_spacings()
scale_array = flex.double()
import math
if b_blur_hires is not None:
b_sharpen_hires_use = b_sharpen-b_blur_hires
else:
b_sharpen_hires_use = 0.
for x, (ind, sthol), (ind1, d) in zip(data_array, sthol_array, d_spacings):
# for small value b = b_sharpen
# for large value b = -b_sharpen_hires_use
# transition is determined by k_sharpen
value = min(20., max(-20., k_sharpen*(d_min-d)))
lowres_weight = 1./(1.+math.exp(value))
hires_weight = max(0., 1-lowres_weight)
b_sharpen_use = b_sharpen*lowres_weight+b_sharpen_hires_use*hires_weight
log_scale = sthol*b_sharpen_use
scale_array.append(math.exp(log_scale))
data_array = data_array*scale_array
f_array_sharpened = f_array.customized_copy(data = data_array)
actual_b_iso = get_b_iso(f_array_sharpened, d_min = d_min)
print("B-iso after sharpening by b_sharpen = %6.1f is %7.2f\n" %(
b_sharpen, actual_b_iso), file = out)
sharpened_map_coeffs = f_array_sharpened.phase_transfer(
phase_source = phases, deg = True)
# And get new map
map_data = get_map_from_map_coeffs(map_coeffs = sharpened_map_coeffs,
crystal_symmetry = crystal_symmetry,
n_real = n_real)
mb = map_and_b_object(map_data = map_data, final_b_iso = actual_b_iso)
if include_sharpened_map_coeffs:
mb.sharpened_map_coeffs = sharpened_map_coeffs
return mb
def find_symmetry_center(map_data, crystal_symmetry = None, out = sys.stdout):
# find center if necessary:
origin = list(map_data.origin())
all = list(map_data.all())
centroid_wx = {}
centroid_w = {}
from cctbx import maptbx
for ai in [0, 1, 2]:
centroid_wx[ai] = 0.
centroid_w[ai] = 0.
for i in range(0, all[ai]):
if ai == 0:
start_tuple = tuple((i, 0, 0))
end_tuple = tuple((i, all[1]-1, all[2]-1)) #2019-11-05 not beyond na-1
elif ai == 1:
start_tuple = tuple((0, i, 0))
end_tuple = tuple((all[0]-1, i, all[2]-1))
elif ai == 2:
start_tuple = tuple((0, 0, i))
end_tuple = tuple((all[0]-1, all[1]-1, i))
new_map_data = maptbx.copy(map_data,
start_tuple, end_tuple)
mean_value = max(0., new_map_data.as_1d().as_double().min_max_mean().mean)
centroid_wx[ai]+= mean_value*(i-origin[ai])
centroid_w[ai]+= mean_value
if centroid_w[ai]>0:
centroid_wx[ai] = centroid_wx[ai]/centroid_w[ai]
print("CENTROID OF DENSITY: (%7.2f, %7.2f, %7.2f) (grid units) " %(
tuple((centroid_wx[0], centroid_wx[1], centroid_wx[2], ))), file = out)
xyz_fract = matrix.col((centroid_wx[0]/all[0], centroid_wx[1]/all[1], centroid_wx[2]/all[2], ))
xyz_cart = crystal_symmetry.unit_cell().orthogonalize(xyz_fract)
print("CENTROID (A): (%7.3f, %7.3f, %7.3f) " %(
tuple(xyz_cart)), file = out)
return xyz_cart
def get_center_of_map(map_data, crystal_symmetry,
place_on_grid_point = True):
all = list(map_data.all())
origin = list(map_data.origin())
if place_on_grid_point:
sx, sy, sz = [int(all[0]/2)+origin[0], int(all[1]/2)+origin[1],
int(all[2]/2)+origin[2]]
else:
sx, sy, sz = [all[0]/2+origin[0], all[1]/2+origin[1],
all[2]/2+origin[2]]
site_fract = matrix.col((sx/all[0], sy/all[1], sz/all[2], ))
return crystal_symmetry.unit_cell().orthogonalize(site_fract)
def select_remaining_ncs_ops( map_data = None,
crystal_symmetry = None,
random_points = None,
closest_sites = None,
ncs_object = None,
out = sys.stdout):
# identify which NCS ops still apply. Choose the ones that maximize
# scoring with score_ncs_in_map
if ncs_object.max_operators()<1:
return ncs_object
used_ncs_id_list = [ncs_object.ncs_groups()[0].identity_op_id()]
ncs_copies = ncs_object.max_operators()
# find ncs_id that maximizes score (if any)
improving = True
from copy import deepcopy
best_ops_to_keep = deepcopy(used_ncs_id_list)
working_best_ops_to_keep = None
best_score = None
while improving:
improving = False
working_best_ops_to_keep = deepcopy(best_ops_to_keep)
working_score = None
for ncs_id in range(ncs_copies):
if ncs_id in best_ops_to_keep:continue
ops_to_keep = deepcopy(best_ops_to_keep)
ops_to_keep.append(ncs_id)
ncs_used_obj = ncs_object.deep_copy(ops_to_keep = ops_to_keep)
score, ncs_cc = score_ncs_in_map(map_data = map_data, ncs_object = ncs_used_obj,
ncs_in_cell_only = True,
allow_score_with_pg = False,
sites_orth = closest_sites,
crystal_symmetry = crystal_symmetry, out = null_out())
if score is None: continue
if working_score is None or score >working_score:
working_score = score
working_best_ops_to_keep = deepcopy(ops_to_keep)
if working_score is not None and (
best_score is None or working_score>best_score):
improving = True
best_score = working_score
best_ops_to_keep = deepcopy(working_best_ops_to_keep)
ncs_used_obj = ncs_object.deep_copy(ops_to_keep = best_ops_to_keep)
return ncs_used_obj
def run_get_ncs_from_map(params = None,
map_data = None,
crystal_symmetry = None,
map_symmetry_center = None,
ncs_obj = None,
fourier_filter = False,
out = sys.stdout,
):
# Get or check NCS operators. Try various possibilities for center of NCS
# First Fourier filter map if resolution is set
if fourier_filter and params.crystal_info.resolution:
print("Fourier filtering at resolution of %.2f A" %(
params.crystal_info.resolution), file = out)
from iotbx.map_manager import map_manager
mm = map_manager(map_data= map_data,
unit_cell_crystal_symmetry = crystal_symmetry,
unit_cell_grid = map_data.all(),
wrapping=False)
mm.resolution_filter(d_min=params.crystal_info.resolution)
map_data = mm.map_data()
ncs_obj_to_check = None
if params.reconstruction_symmetry.symmetry and (
not ncs_obj or ncs_obj.max_operators()<2):
if params.reconstruction_symmetry.optimize_center:
center_try_list = [True, False]
else:
center_try_list = [True]
elif ncs_obj:
center_try_list = [True]
ncs_obj_to_check = ncs_obj
elif params.reconstruction_symmetry.optimize_center:
center_try_list = [None]
else:
return None, None, None # did not even try
# check separately for helical symmetry
if params.reconstruction_symmetry.symmetry and \
params.reconstruction_symmetry.symmetry.lower() == 'helical':
helical_list = [True]
elif params.reconstruction_symmetry.symmetry and \
params.reconstruction_symmetry.symmetry.lower() in ['all', 'any'] and\
params.reconstruction_symmetry.include_helical_symmetry:
helical_list = [False, True]
else:
helical_list = [False]
new_ncs_obj, ncs_cc, ncs_score = None, None, None
for use_center_of_map in center_try_list:
for include_helical in helical_list:
local_params = deepcopy(params)
local_params.reconstruction_symmetry.include_helical_symmetry = \
include_helical
new_ncs_obj, ncs_cc, ncs_score = get_ncs_from_map(params = local_params,
map_data = map_data,
map_symmetry_center = map_symmetry_center,
use_center_of_map_as_center = use_center_of_map,
crystal_symmetry = crystal_symmetry,
ncs_obj_to_check = ncs_obj_to_check,
out = out
)
if new_ncs_obj:
return new_ncs_obj, ncs_cc, ncs_score
return new_ncs_obj, ncs_cc, ncs_score
def get_ncs_from_map(params = None,
map_data = None,
map_symmetry_center = None,
symmetry = None,
symmetry_center = None,
helical_rot_deg = None,
helical_trans_z_angstrom = None,
two_fold_along_x = None,
op_max = None,
crystal_symmetry = None,
optimize_center = None,
sites_orth = None,
random_points = None,
n_rescore = None,
use_center_of_map_as_center = None,
min_ncs_cc = None,
identify_ncs_id = None,
ncs_obj_to_check = None,
ncs_in_cell_only = False,
out = sys.stdout):
# Purpose: check through standard point groups and helical symmetry to see
# if map has symmetry. If symmetry == ANY then take highest symmetry that fits
# Otherwise limit to the one specified with symmetry.
# Use a library of symmetry matrices. For helical symmetry generate it
# along the z axis.
# Center of symmetry is as supplied, or center of map or center of density
# If center is not supplied and use_center_of_map_as_center, try that
# and return None if it fails to achieve a map cc of min_ncs_cc
if ncs_in_cell_only is None:
ncs_in_cell_only = (not params.crystal_info.use_sg_symmetry)
if symmetry is None:
symmetry = params.reconstruction_symmetry.symmetry
if symmetry_center is None:
symmetry_center = params.reconstruction_symmetry.symmetry_center
if optimize_center is None:
optimize_center = params.reconstruction_symmetry.optimize_center
if helical_rot_deg is None:
helical_rot_deg = params.reconstruction_symmetry.helical_rot_deg
if helical_trans_z_angstrom is None:
helical_trans_z_angstrom = \
params.reconstruction_symmetry.helical_trans_z_angstrom
if n_rescore is None:
n_rescore = params.reconstruction_symmetry.n_rescore
if random_points is None:
random_points = params.reconstruction_symmetry.random_points
if op_max is None:
op_max = params.reconstruction_symmetry.op_max
if two_fold_along_x is None:
two_fold_along_x = params.reconstruction_symmetry.two_fold_along_x
if identify_ncs_id is None:
identify_ncs_id = params.reconstruction_symmetry.identify_ncs_id
if min_ncs_cc is None:
min_ncs_cc = params.reconstruction_symmetry.min_ncs_cc
# if ncs_obj_to_check is supplied...just use that ncs
if ncs_obj_to_check and ncs_obj_to_check.max_operators()>1:
symmetry = "SUPPLIED NCS"
if map_symmetry_center is None:
map_symmetry_center = get_center_of_map(map_data, crystal_symmetry)
if optimize_center is None:
if symmetry_center is None and (not use_center_of_map_as_center):
optimize_center = True
print("Setting optimize_center = True as no symmetry_center is supplied", file = out)
else:
optimize_center = False
if symmetry_center is not None:
symmetry_center = matrix.col(symmetry_center)
elif use_center_of_map_as_center:
print("Using center of map as NCS center", file = out)
symmetry_center = map_symmetry_center
else: # Find it
if not ncs_obj_to_check:
print("Finding NCS center as it is not supplied", file = out)
symmetry_center = find_symmetry_center(
map_data, crystal_symmetry = crystal_symmetry,
out = out)
print("Center of NCS (A): (%7.3f, %7.3f, %7.3f) " %(
tuple(symmetry_center)), file = out)
ncs_list = get_ncs_list(params = params,
symmetry = symmetry,
symmetry_center = symmetry_center,
helical_rot_deg = helical_rot_deg,
two_fold_along_x = two_fold_along_x,
op_max = op_max,
helical_trans_z_angstrom = helical_trans_z_angstrom,
ncs_obj_to_check = ncs_obj_to_check,
map_data = map_data,
crystal_symmetry = crystal_symmetry,
out = out,
)
print("Total of %d NCS types to examine..." %(len(ncs_list)), file = out)
if not sites_orth:
sites_orth = get_points_in_map(
map_data, n = random_points, crystal_symmetry = crystal_symmetry)
# some random points in the map
# Now make sure symmetry applied to points in points_list gives similar values
results_list = []
for ncs_obj in ncs_list:
symmetry = ncs_obj.get_ncs_name()
score, cc_avg = score_ncs_in_map(map_data = map_data, ncs_object = ncs_obj,
identify_ncs_id = identify_ncs_id,
ncs_in_cell_only = ncs_in_cell_only,
sites_orth = sites_orth, crystal_symmetry = crystal_symmetry, out = out)
if cc_avg < min_ncs_cc:
score = 0. # Do not allow low CC values to be used
if score is None:
print("symmetry:", symmetry, " no score", ncs_obj.max_operators(), file = out)
else:
results_list.append([score, cc_avg, ncs_obj, symmetry])
if not results_list:
return None, None, None
results_list.sort(key=itemgetter(0))
results_list.reverse()
# Rescore top n_rescore
if n_rescore and not ncs_obj_to_check:
print("Rescoring top %d results" %(min(n_rescore, len(results_list))), file = out)
rescore_list = results_list[n_rescore:]
new_sites_orth = get_points_in_map(
map_data, n = 10*random_points, crystal_symmetry = crystal_symmetry)
new_sites_orth.extend(sites_orth)
for orig_score, orig_cc_avg, ncs_obj, symmetry in results_list[:n_rescore]:
score, cc_avg = score_ncs_in_map(map_data = map_data, ncs_object = ncs_obj,
identify_ncs_id = identify_ncs_id,
ncs_in_cell_only = ncs_in_cell_only,
sites_orth = new_sites_orth, crystal_symmetry = crystal_symmetry, out = out)
if cc_avg < min_ncs_cc:
score = 0. # Do not allow low CC values to be used
if score is None:
print("symmetry:", symmetry, " no score", ncs_obj.max_operators(), file = out)
else:
rescore_list.append([score, cc_avg, ncs_obj, symmetry])
rescore_list.sort(key=itemgetter(0))
rescore_list.reverse()
results_list = rescore_list
if len(results_list) == 1:
# check for C1
score, cc_avg, ncs_obj, symmetry = results_list[0]
if symmetry and symmetry.strip() == 'C1':
score = 1.
cc_avg = 1.
results_list = [[score, cc_avg, ncs_obj, symmetry], ]
print("Ranking of NCS types:", file = out)
if min_ncs_cc is not None:
print("NOTE: any NCS type with CC < %.2f (min_ncs_cc) is unscored " %(
min_ncs_cc), file = out)
print("\n SCORE CC OPERATORS SYMMETRY", file = out)
for score, cc_avg, ncs_obj, symmetry in results_list:
if not symmetry: symmetry = ""
if not cc_avg: cc_avg = 0.0
print(" %6.2f %5.2f %2d %s" %(
score, cc_avg, ncs_obj.max_operators(), symmetry.strip(), ), file = out)
score, cc_avg, ncs_obj, ncs_info = results_list[0]
# Optimize center if necessary
if optimize_center:
symmetry_center, cc_avg, score, ncs_obj = optimize_center_position(
map_data, sites_orth,
crystal_symmetry,
ncs_info, symmetry_center, ncs_obj, score, cc_avg,
params = params,
helical_rot_deg = helical_rot_deg,
two_fold_along_x = two_fold_along_x,
op_max = op_max,
min_ncs_cc = min_ncs_cc,
identify_ncs_id = identify_ncs_id,
ncs_obj_to_check = ncs_obj_to_check,
ncs_in_cell_only = ncs_in_cell_only,
helical_trans_z_angstrom = helical_trans_z_angstrom, out = out)
print("New center: (%7.3f, %7.3f, %7.3f)" %(tuple(symmetry_center)), file = out)
if cc_avg < min_ncs_cc:
print("No suitable symmetry found", file = out)
return None, None, None
print("\nBest NCS type is: ", end = ' ', file = out)
print("\n SCORE CC OPERATORS SYMMETRY", file = out)
if not ncs_info: ncs_info = ""
print(" %6.2f %5.2f %2d %s Best NCS type" %(
score, cc_avg, ncs_obj.max_operators(), ncs_info.strip(), ), file = out)
return ncs_obj, cc_avg, score
def optimize_center_position(map_data, sites_orth, crystal_symmetry,
ncs_info, symmetry_center, ncs_obj, score, cc_avg,
params = None,
helical_rot_deg = None,
two_fold_along_x = None,
op_max = None,
identify_ncs_id = None,
ncs_obj_to_check = None,
ncs_in_cell_only = None,
min_ncs_cc = None,
helical_trans_z_angstrom = None, out = sys.stdout):
if ncs_info is None:
ncs_info = "None"
symmetry = ncs_info.split()[0]
print("Optimizing center position...type is %s" %(ncs_info), file = out)
if len(ncs_info.split())>1 and ncs_info.split()[1] == '(a)':
two_fold_along_x = True
elif len(ncs_info.split())>1 and ncs_info.split()[1] == '(b)':
two_fold_along_x = False
else:
two_fold_along_x = None
best_center = matrix.col(symmetry_center)
best_ncs_obj = ncs_obj
best_score = score
best_cc_avg = cc_avg
print("Starting center: (%7.3f, %7.3f, %7.3f)" %(tuple(best_center)), file = out)
from libtbx.utils import null_out
scale = 5.
for itry in range(6):
scale = scale/5.
for i in range(-4, 5):
for j in range(-4, 5):
local_center = matrix.col(symmetry_center)+matrix.col((scale*i, scale*j, 0., ))
ncs_list = get_ncs_list(params = params, symmetry = symmetry,
symmetry_center = local_center,
helical_rot_deg = helical_rot_deg,
two_fold_along_x = two_fold_along_x,
op_max = op_max,
helical_trans_z_angstrom = helical_trans_z_angstrom,
ncs_obj_to_check = ncs_obj_to_check,
map_data = map_data,
crystal_symmetry = crystal_symmetry,
out = null_out(),
)
if ncs_list:
ncs_obj = ncs_list[0]
score, cc_avg = score_ncs_in_map(map_data = map_data, ncs_object = ncs_obj,
identify_ncs_id = identify_ncs_id,
ncs_in_cell_only = ncs_in_cell_only,
sites_orth = sites_orth, crystal_symmetry = crystal_symmetry, out = out)
if cc_avg < min_ncs_cc:
score = 0. # Do not allow low CC values to be used
else:
ncs_obj = None
score, cc_avg = None, None
if best_score is None or score>best_score:
best_cc_avg = cc_avg
best_score = score
best_center = local_center
best_ncs_obj = ncs_obj
symmetry_center = best_center
cc_avg = best_cc_avg
score = best_score
ncs_obj = best_ncs_obj
return best_center, best_cc_avg, best_score, best_ncs_obj
def score_ncs_in_map_point_group_symmetry(
map_data = None, ncs_object = None, sites_orth = None,
crystal_symmetry = None, out = sys.stdout):
ncs_group = ncs_object.ncs_groups()[0]
all_value_lists = []
for c, t, r in zip(ncs_group.centers(),
ncs_group.translations_orth(),
ncs_group.rota_matrices()):
new_sites_cart = flex.vec3_double()
r_inv = r.inverse()
for site in sites_orth:
new_sites_cart.append(r_inv * (matrix.col(site) - t))
# get value at new_sites cart and make sure they are all the same...
new_sites_fract = crystal_symmetry.unit_cell().fractionalize(new_sites_cart)
values = flex.double()
for site_fract in new_sites_fract:
values.append(map_data.value_at_closest_grid_point(site_fract))
all_value_lists.append(values)
return get_cc_among_value_lists(all_value_lists)
def get_cc_among_value_lists(all_value_lists):
a = all_value_lists[0]
cc_avg = 0.
cc_low = None
cc_n = 0.
for j in range(1, len(all_value_lists)):
b = all_value_lists[j]
cc = flex.linear_correlation(a, b).coefficient()
cc_avg+= cc
cc_n+= 1.
if cc_low is None or cc<cc_low:
cc_low = cc
cc_avg = cc_avg/max(1., cc_n)
if cc_n>0:
import math
return cc_low*math.sqrt(len(all_value_lists)), cc_avg
else:
return None, None
def score_ncs_in_map(map_data = None, ncs_object = None, sites_orth = None,
identify_ncs_id = None,
ncs_in_cell_only = None,
allow_score_with_pg = True,
crystal_symmetry = None, out = sys.stdout):
if not ncs_object or ncs_object.max_operators()<2:
return None, None
ncs_group = ncs_object.ncs_groups()[0]
# don't use point-group symmetry if we have only some of the ops
if allow_score_with_pg and (
(not identify_ncs_id) or ncs_group.is_point_group_symmetry()):
return score_ncs_in_map_point_group_symmetry(
map_data = map_data, ncs_object = ncs_object,
sites_orth = sites_orth, crystal_symmetry = crystal_symmetry, out = out)
# This version does not assume point-group symmetry: find the NCS
# operator that maps each point on to all others the best, then save
# that list of values
if (not ncs_group) or not ncs_group.n_ncs_oper():
identify_ncs_id_list = [None]
else:
identify_ncs_id_list = list(range(ncs_group.n_ncs_oper()))+[None]
all_value_lists = []
if not sites_orth:
sites_orth = get_points_in_map(map_data, n = 100,
minimum_fraction_of_max = 0.05,
crystal_symmetry = crystal_symmetry)
for site in sites_orth:
best_id = 0
best_score = None
best_values = None
for site_ncs_id in identify_ncs_id_list: #last is real one
if site_ncs_id is None:
site_ncs_id = best_id
real_thing = True
else:
real_thing = False
if identify_ncs_id and site_ncs_id:
local_site = ncs_group.rota_matrices()[site_ncs_id] * matrix.col(site) + \
ncs_group.translations_orth()[site_ncs_id]
else:
local_site = site
new_sites_cart = flex.vec3_double()
for c, t, r in zip(ncs_group.centers(),
ncs_group.translations_orth(),
ncs_group.rota_matrices()):
r_inv = r.inverse()
new_sites_cart.append(r_inv * (matrix.col(local_site) - t))
new_sites_fract = crystal_symmetry.unit_cell().fractionalize(
new_sites_cart)
values = flex.double()
for site_frac in new_sites_fract:
if (not ncs_in_cell_only) or (
site_frac[0]>= 0 and site_frac[0]<= 1 and \
site_frac[1]>= 0 and site_frac[1]<= 1 and \
site_frac[2]>= 0 and site_frac[2]<= 1):
values.append(map_data.value_at_closest_grid_point(site_frac))
else:
values.append(0.)
score = values.standard_deviation_of_the_sample()
if real_thing or (best_score is None or score < best_score):
best_score = score
best_id = site_ncs_id
best_values = values
all_value_lists.append(best_values)
values_by_site_dict = {} # all_value_lists[j][i] -> values_by_site_dict[i][j]
# there are sites_orth.size() values of j
# there are len(ncs_group_centers) == len(all_value_lists[0]) values of i
for i in range(len(all_value_lists[0])):
values_by_site_dict[i] = flex.double() # value_list[0][1]
for j in range(sites_orth.size()):
values_by_site_dict[i].append(all_value_lists[j][i])
new_all_values_lists = []
for i in range(len(all_value_lists[0])):
new_all_values_lists.append(values_by_site_dict[i])
score, cc = get_cc_among_value_lists(new_all_values_lists)
return score, cc
def get_points_in_map(map_data, n = None,
minimum_fraction_of_max = 0.,
random_xyz = None,
max_tries_ratio = 100, crystal_symmetry = None):
map_1d = map_data.as_1d()
map_mean = map_1d.min_max_mean().mean
map_max = map_1d.min_max_mean().max
minimum_value = map_mean+minimum_fraction_of_max*(map_max-map_mean)
points_list = flex.vec3_double()
import random
random.seed(1)
nu, nv, nw = map_data.all()
xyz_fract = crystal_symmetry.unit_cell().fractionalize(
tuple((17.4, 27.40128571, 27.32985714, )))
for i in range(int(max_tries_ratio*n)): # max tries
ix = random.randint(0, nu-1)
iy = random.randint(0, nv-1)
iz = random.randint(0, nw-1)
xyz_fract = matrix.col((ix/nu, iy/nv, iz/nw, ))
value = map_data.value_at_closest_grid_point(xyz_fract)
if value > minimum_value and value <map_max:
if random_xyz:
offset = []
for i in range(3):
offset.append((random.random()-0.5)*2.*random_xyz)
offset = crystal_symmetry.unit_cell().fractionalize(matrix.col(offset))
new_xyz_fract = []
for x, o in zip(xyz_fract, offset):
new_xyz_fract.append(max(0, min(1, x+o)))
xyz_fract = matrix.col(new_xyz_fract)
points_list.append(xyz_fract)
if points_list.size()>= n: break
sites_orth = crystal_symmetry.unit_cell().orthogonalize(points_list)
return sites_orth
def get_ncs_list(params = None, symmetry = None,
symmetry_center = None,
helical_rot_deg = None,
helical_trans_z_angstrom = None,
op_max = None,
two_fold_along_x = None,
ncs_obj_to_check = None,
crystal_symmetry = None,
map_data = None,
include_helical_symmetry = None,
max_helical_ops_to_check = None,
require_helical_or_point_group_symmetry = None,
out = sys.stdout):
# params.reconstruction_symmetry.require_helical_or_point_group_symmetry
# params.reconstruction_symmetry.include_helical_symmetry):
# params.reconstruction_symmetry.max_helical_ops_to_check))
if ncs_obj_to_check and ncs_obj_to_check.max_operators()>1:
return [ncs_obj_to_check] # , ["SUPPLIED NCS"]
from mmtbx.ncs.ncs import generate_ncs_ops
ncs_list = generate_ncs_ops(
must_be_consistent_with_space_group_number = \
params.reconstruction_symmetry.must_be_consistent_with_space_group_number,
symmetry = symmetry,
helical_rot_deg = helical_rot_deg,
helical_trans_z_angstrom = helical_trans_z_angstrom,
op_max = op_max,
two_fold_along_x = two_fold_along_x,
include_helical_symmetry = \
params.reconstruction_symmetry.include_helical_symmetry,
max_helical_ops_to_check = \
params.reconstruction_symmetry.max_helical_ops_to_check,
require_helical_or_point_group_symmetry = \
params.reconstruction_symmetry.require_helical_or_point_group_symmetry,
out = out)
# Generate helical symmetry from map if necessary
if symmetry.lower() == 'helical' or (
symmetry.lower() in ['all', 'any'] and
params.reconstruction_symmetry.include_helical_symmetry):
if helical_rot_deg is None or helical_trans_z_angstrom is None:
# returns ncs for symmetry_center at symmetry_center
ncs_object, helical_rot_deg, helical_trans_z_angstrom = \
find_helical_symmetry(params = params,
symmetry_center = symmetry_center,
map_data = map_data,
crystal_symmetry = crystal_symmetry, out = out)
if ncs_object:
ncs_name = "Type: Helical %5.2f deg %6.2f Z-trans " %(
helical_rot_deg, helical_trans_z_angstrom)
ncs_object.set_ncs_name(ncs_name)
ncs_list.append(ncs_object)
if symmetry_center and tuple(symmetry_center) != (0, 0, 0, ):
print("Offsetting NCS center by (%.2f, %.2f, %.2f) A " %(tuple(symmetry_center)), file = out)
new_list = []
for ncs_obj in ncs_list:
new_list.append(ncs_obj.coordinate_offset(coordinate_offset = symmetry_center))
ncs_list = new_list
if (require_helical_or_point_group_symmetry):
for ncs_obj in ncs_list:
assert ncs_obj.is_helical_along_z() or ncs_obj.is_point_group_symmetry()
return ncs_list
def find_helical_symmetry(params = None,
symmetry_center = None,
map_data = None,
crystal_symmetry = None,
max_z_to_test = 2, max_peaks_to_score = 5, out = sys.stdout):
params = deepcopy(params) # so changing them does not go back
if not params.crystal_info.resolution:
from cctbx.maptbx import d_min_from_map
params.crystal_info.resolution = d_min_from_map(
map_data, crystal_symmetry.unit_cell(), resolution_factor = 1./4.)
if str(params.reconstruction_symmetry.score_basis) == 'None':
params.reconstruction_symmetry.score_basis = 'cc'
if params.reconstruction_symmetry.smallest_object is None:
params.reconstruction_symmetry.smallest_object = \
5*params.crystal_info.resolution
print("\nLooking for helical symmetry with center at (%.2f, %.2f, %.2f) A\n" %(
tuple(symmetry_center)), file = out)
print("\nFinding likely translations along z...", file = out)
map_coeffs, dummy = get_f_phases_from_map(map_data = map_data,
crystal_symmetry = crystal_symmetry,
d_min = params.crystal_info.resolution,
return_as_map_coeffs = True,
out = out)
f_array, phases = map_coeffs_as_fp_phi(map_coeffs)
from cctbx.maptbx.refine_sharpening import quasi_normalize_structure_factors
(d_max, d_min) = f_array.d_max_min()
f_array.setup_binner(d_max = d_max, d_min = d_min, n_bins = 20)
normalized = quasi_normalize_structure_factors(
f_array, set_to_minimum = 0.01)
# Now look along c* and get peaks
zero_index_a = 0 # look along c*
zero_index_b = 1
c_star_list = get_c_star_list(f_array = normalized,
zero_index_a = zero_index_a,
zero_index_b = zero_index_b)
likely_z_translations = get_helical_trans_z_angstrom(params = params,
c_star_list = c_star_list,
crystal_symmetry = crystal_symmetry,
out = out)
# Now for each z...get the rotation. Try +/- z and try rotations
abc = crystal_symmetry.unit_cell().parameters()[:3]
max_z = max(abc[0], abc[1])
if params.reconstruction_symmetry.max_helical_rotations_to_check:
min_delta_rot = 360/max(1,
params.reconstruction_symmetry.max_helical_rotations_to_check)
else:
min_delta_rot = 0.01
delta_rot = max(min_delta_rot,
(180./3.141659)*params.crystal_info.resolution/max_z)
delta_z = params.crystal_info.resolution/4.
print("\nOptimizing helical paramers:", file = out)
print("\n Rot Trans Score CC", file = out)
n_rotations = int(0.5+360/delta_rot)
rotations = []
for k in range(1, n_rotations):
helical_rot_deg = k*delta_rot
if helical_rot_deg > 180: helical_rot_deg = helical_rot_deg-360
rotations.append(helical_rot_deg)
done = False
n_try = 0
score_list = []
quick = params.control.quick
best_ncs_cc = None
best_ncs_obj = None
best_score = None
best_helical_trans_z_angstrom = None
best_helical_rot_deg = None
import math
for helical_trans_z_angstrom in likely_z_translations[:max_z_to_test]:
n_try+= 1
if done: break
for helical_rot_deg in rotations:
if done: break
if abs(helical_trans_z_angstrom)+abs(math.sin(
helical_rot_deg*(3.14159/180.))*max_z) < \
params.reconstruction_symmetry.smallest_object:
continue # this is identity
new_ncs_obj, ncs_cc, ncs_score, \
new_helical_trans_z_angstrom, new_helical_rot_deg = try_helical_params(
optimize = 0,
helical_rot_deg = helical_rot_deg,
helical_trans_z_angstrom = helical_trans_z_angstrom,
params = params,
map_data = map_data,
map_symmetry_center = symmetry_center, # should not be needed XXX
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = null_out())
if not ncs_score: continue
if ncs_cc> 0.95 or \
ncs_cc > 2*params.reconstruction_symmetry.min_ncs_cc or \
(quick and (ncs_cc> 0.90 or
ncs_cc > 1.5*params.reconstruction_symmetry.min_ncs_cc)):
print(" %.2f %.2f %.2f %.2f (ok to go on)" %(
new_helical_rot_deg, new_helical_trans_z_angstrom,
ncs_score, ncs_cc), file = out)
done = True
if params.control.verbose:
print(" %.2f %.2f %.2f %.2f" %(
new_helical_rot_deg, new_helical_trans_z_angstrom, ncs_score, ncs_cc), file = out)
score_list.append(
[ncs_score, ncs_cc, new_helical_rot_deg, new_helical_trans_z_angstrom])
score_list.sort(key=itemgetter(0))
score_list.reverse()
done = False
for ncs_score, ncs_cc, helical_rot_deg, helical_trans_z_angstrom in \
score_list[:max_peaks_to_score]:
if done: continue
# rescore and optimize:
new_ncs_obj, ncs_cc, ncs_score, \
new_helical_trans_z_angstrom, new_helical_rot_deg = try_helical_params(
params = params,
best_score = best_score,
helical_rot_deg = helical_rot_deg,
helical_trans_z_angstrom = helical_trans_z_angstrom,
delta_z = delta_z/2.,
delta_rot = delta_rot/2.,
map_data = map_data,
map_symmetry_center = symmetry_center,
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = null_out())
if not ncs_score or ncs_score <0:
continue
if best_score is None or ncs_score>best_score:
best_ncs_cc = ncs_cc
best_ncs_obj = new_ncs_obj
best_score = ncs_score
best_helical_trans_z_angstrom = new_helical_trans_z_angstrom
best_helical_rot_deg = new_helical_rot_deg
# after trying out a range quit if good enough
if best_ncs_cc> 0.90 or \
best_ncs_cc > 1.5*params.reconstruction_symmetry.min_ncs_cc or \
( (quick or n_try>1) and \
ncs_cc>= params.reconstruction_symmetry.min_ncs_cc):
print(" %.2f %.2f %.2f %.2f (high enough to go on)" %(
best_helical_rot_deg, best_helical_trans_z_angstrom,
best_score, best_ncs_cc), file = out)
done = True
# Optimize one more time trying fractional values, but only if
# that makes the delta less than the resolution
print("\nTrying fraction of rot/trans", file = out)
for iter in [0, 1]:
if not best_helical_rot_deg: continue
for ifract in range(2, 11):
if iter == 0: # try fractional
test_helical_rot_deg = best_helical_rot_deg/ifract
test_helical_trans_z_angstrom = best_helical_trans_z_angstrom/ifract
if test_helical_trans_z_angstrom > params.crystal_info.resolution*1.1:
continue # skip it...would have been a peak if ok
else: # iter >0
if ifract > 0:
continue # skip these
else: # optimize current best
test_helical_rot_deg = best_helical_rot_deg
test_helical_trans_z_angstrom = best_helical_trans_z_angstrom
new_ncs_obj, new_ncs_cc, new_ncs_score, \
new_helical_trans_z_angstrom, new_helical_rot_deg = \
try_helical_params(
params = params,
helical_rot_deg = test_helical_rot_deg,
helical_trans_z_angstrom = test_helical_trans_z_angstrom,
delta_z = delta_z/2.,
delta_rot = delta_rot/2.,
map_data = map_data,
map_symmetry_center = symmetry_center,
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = out)
if new_ncs_score is not None:
new_ncs_score = new_ncs_score*\
params.reconstruction_symmetry.scale_weight_fractional_translation
# give slight weight to smaller
if best_score is None or new_ncs_score > best_score:
best_ncs_cc = new_ncs_cc
best_ncs_obj = new_ncs_obj
best_score = new_ncs_score
best_helical_trans_z_angstrom = new_helical_trans_z_angstrom
best_helical_rot_deg = new_helical_rot_deg
print(" %.2f %.2f %.2f %.2f (improved fractions)" %(
best_helical_rot_deg, best_helical_trans_z_angstrom,
best_score, best_ncs_cc), file = out)
else:
print(" %.2f %.2f %.2f %.2f (worse with fractions)" %(
new_helical_rot_deg, new_helical_trans_z_angstrom,
new_ncs_score, new_ncs_cc), file = out)
# Optimize one more time trying multiples of values to get better param
imult = int(0.5+
0.33*max_z/params.reconstruction_symmetry.max_helical_ops_to_check)
working_ncs_cc = best_ncs_cc
working_ncs_obj = best_ncs_obj
working_score = None
if best_helical_rot_deg:
working_helical_rot_deg = best_helical_rot_deg*imult
working_helical_trans_z_angstrom = best_helical_trans_z_angstrom*imult
else:
working_helical_rot_deg = None
working_helical_trans_z_angstrom = None
imult = 0
if imult > 1:
print("\nTrying %sx multiples of rot/trans" %(imult), file = out)
improved = False
for iter in [1, 2, 3]:
if iter > 1 and not improved: break
improved = False
new_ncs_obj, new_ncs_cc, new_ncs_score, \
new_helical_trans_z_angstrom, new_helical_rot_deg = \
try_helical_params(
params = params,
helical_rot_deg = working_helical_rot_deg,
helical_trans_z_angstrom = working_helical_trans_z_angstrom,
delta_z = delta_z/(2.*iter),
delta_rot = delta_rot/(2.*iter),
map_data = map_data,
map_symmetry_center = symmetry_center,
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = out)
if new_ncs_score is not None:
if working_score is None or new_ncs_score > working_score:
working_ncs_cc = new_ncs_cc
working_ncs_obj = new_ncs_obj
working_score = new_ncs_score
working_helical_trans_z_angstrom = new_helical_trans_z_angstrom
working_helical_rot_deg = new_helical_rot_deg
print(" %.2f %.2f %.2f %.2f (Scoring for multiple)" %(
working_helical_rot_deg, working_helical_trans_z_angstrom,
working_score, working_ncs_cc), file = out)
# and rescore with this:
working_helical_rot_deg = working_helical_rot_deg/imult
working_helical_trans_z_angstrom = working_helical_trans_z_angstrom/imult
for iter in [1, 2, 3]:
new_ncs_obj, new_ncs_cc, new_ncs_score, \
new_helical_trans_z_angstrom, new_helical_rot_deg = \
try_helical_params(
params = params,
helical_rot_deg = working_helical_rot_deg,
helical_trans_z_angstrom = working_helical_trans_z_angstrom,
delta_z = delta_z/(2.*iter),
delta_rot = delta_rot/(2.*iter),
map_data = map_data,
map_symmetry_center = symmetry_center,
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = null_out())
if new_ncs_score is not None:
working_ncs_obj, working_ncs_cc, working_ncs_score, \
working_helical_trans_z_angstrom, working_helical_rot_deg = \
new_ncs_obj, new_ncs_cc, new_ncs_score, \
new_helical_trans_z_angstrom, new_helical_rot_deg
if best_score is None or working_ncs_score > best_score:
if params.control.verbose:
print("\nTaking parameters from multiples", file = out)
best_ncs_cc = working_ncs_cc
best_ncs_obj = working_ncs_obj
best_score = working_ncs_score
best_helical_trans_z_angstrom = working_helical_trans_z_angstrom
best_helical_rot_deg = working_helical_rot_deg
print(" %.2f %.2f %.2f %.2f (improved by multiples)" %(
best_helical_rot_deg, best_helical_trans_z_angstrom,
best_score, best_ncs_cc), file = out)
improved = True
working_ncs_cc = best_ncs_cc
working_ncs_obj = best_ncs_obj
working_score = None
working_helical_trans_z_angstrom = best_helical_trans_z_angstrom*imult
working_helical_rot_deg = best_helical_rot_deg*imult
if best_helical_rot_deg and best_helical_trans_z_angstrom and best_score and best_ncs_cc:
# Check to make sure there is no overlap
print(" %.2f %.2f %.2f %.2f (Final)" %(
best_helical_rot_deg, best_helical_trans_z_angstrom, \
best_score, best_ncs_cc), file = out)
from mmtbx.ncs.ncs import get_helical_symmetry
ncs_object = get_helical_symmetry(
helical_rot_deg = best_helical_rot_deg,
helical_trans_z_angstrom = best_helical_trans_z_angstrom,
max_ops = params.reconstruction_symmetry.max_helical_ops_to_check)
else:
ncs_object = None
return ncs_object, best_helical_rot_deg, best_helical_trans_z_angstrom
def try_helical_params(
optimize = None,
best_score = None,
delta_z = None,
delta_rot = None,
helical_rot_deg = None,
helical_trans_z_angstrom = None,
params = None,
map_data = None,
map_symmetry_center = None,
symmetry_center = None,
crystal_symmetry = None,
out = sys.stdout):
if delta_z is None or delta_rot is None:
assert not optimize
local_params = deepcopy(params)
local_params.reconstruction_symmetry.min_ncs_cc = -100
local_params.reconstruction_symmetry.n_rescore = 0
local_params.reconstruction_symmetry.symmetry = 'helical'
local_params.reconstruction_symmetry.helical_rot_deg = helical_rot_deg
local_params.reconstruction_symmetry.helical_trans_z_angstrom = \
helical_trans_z_angstrom
abc = crystal_symmetry.unit_cell().parameters()[:3]
max_z = max(abc[0], abc[1])
import math
if abs(helical_trans_z_angstrom)+abs(math.sin(
helical_rot_deg*(3.14159/180.))*max_z) < \
params.reconstruction_symmetry.smallest_object:
return None, None, None, \
None, None
best_helical_trans_z_angstrom, best_helical_rot_deg = \
helical_trans_z_angstrom, helical_rot_deg
best_ncs_score = best_score
best_ncs_obj = None
best_ncs_cc = None
test_ncs_obj, test_ncs_cc, test_ncs_score = get_ncs_from_map(params = local_params,
map_data = map_data,
map_symmetry_center = symmetry_center,
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = null_out())
if params.reconstruction_symmetry.score_basis == 'cc':
test_ncs_score = test_ncs_cc
if best_ncs_score is None or test_ncs_score>best_ncs_score:
best_ncs_score = test_ncs_score
best_ncs_cc = test_ncs_cc
best_ncs_obj = test_ncs_obj
if optimize is None:
optimize = params.reconstruction_symmetry.max_helical_optimizations
# save in case we need to go back
working_helical_trans_z_angstrom, working_helical_rot_deg = \
helical_trans_z_angstrom, helical_rot_deg
working_ncs_score = best_ncs_score
working_ncs_cc = best_ncs_cc
working_ncs_obj = best_ncs_obj
if optimize and (best_score is None or best_ncs_score > best_score):
# try with few to many operators..
if params.control.verbose:
print("\nOptimizing by varying number of operators", file = out)
print("Starting score: %.2f" %(working_ncs_score), file = out)
for k in range(optimize):
local_params.reconstruction_symmetry.max_helical_ops_to_check = min(k+1,
params.reconstruction_symmetry.max_helical_ops_to_check)
best_score = None # start over for each number of operators
for i in [0, -1, 1]:
for j in [0, -1, 1]:
new_ncs_obj, new_ncs_cc, new_ncs_score, \
new_helical_trans_z_angstrom, new_helical_rot_deg = try_helical_params(
optimize = False,
helical_rot_deg = max(0.1, best_helical_rot_deg+i*delta_rot),
helical_trans_z_angstrom = max(0.01, best_helical_trans_z_angstrom+j*delta_z),
delta_z = delta_z,
delta_rot = delta_rot,
params = params,
map_data = map_data,
map_symmetry_center = symmetry_center,
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = out)
if new_ncs_score and new_ncs_score>0 and (
best_score is None or new_ncs_score>best_score):
if params.control.verbose:
print("Working score for %s ops: %.2f" %(
local_params.reconstruction_symmetry.max_helical_ops_to_check,
new_ncs_score), file = out)
best_score = new_ncs_score
best_ncs_score = new_ncs_score
best_helical_trans_z_angstrom = new_helical_trans_z_angstrom
best_helical_rot_deg = new_helical_rot_deg
best_ncs_obj = new_ncs_obj
best_ncs_cc = new_ncs_cc
delta_rot = delta_rot/2
delta_z = delta_z/2
#rescore with what we now have (best values) and compare with working
local_params.reconstruction_symmetry.max_helical_ops_to_check = \
params.reconstruction_symmetry.max_helical_ops_to_check
if params.control.verbose:
print("Rescoring with original number of operators (%s)" %(
local_params.reconstruction_symmetry.max_helical_ops_to_check), file = out)
local_params.reconstruction_symmetry.helical_rot_deg = best_helical_rot_deg
local_params.reconstruction_symmetry.helical_trans_z_angstrom = \
best_helical_trans_z_angstrom
best_ncs_obj, best_ncs_cc, best_ncs_score = get_ncs_from_map(
params = local_params,
map_data = map_data,
map_symmetry_center = symmetry_center,
symmetry_center = symmetry_center,
crystal_symmetry = crystal_symmetry,
out = null_out())
if params.reconstruction_symmetry.score_basis == 'cc':
best_ncs_score = best_ncs_cc
# now take it if better
if best_ncs_cc and best_ncs_cc>working_ncs_cc:
if params.control.verbose:
print("Using optimized values (%.2f > %.2f)" %(
best_ncs_cc, working_ncs_cc), file = out)
# keep these (best)
else:
if params.control.verbose:
print("Rejecting optimized values (%.2f <= %.2f)" %(
best_ncs_cc, working_ncs_cc), file = out)
# resture working values
best_helical_trans_z_angstrom, best_helical_rot_deg = \
working_helical_trans_z_angstrom, working_helical_rot_deg
best_ncs_score = working_ncs_score
best_ncs_obj = working_ncs_obj
best_ncs_cc = working_ncs_cc
if params.reconstruction_symmetry.score_basis == 'cc':
best_ncs_score = best_ncs_cc
return best_ncs_obj, best_ncs_cc, best_ncs_score, \
best_helical_trans_z_angstrom, best_helical_rot_deg
def get_d_and_value_list(c_star_list):
d_list = []
from scitbx.array_family import flex
value_list = flex.double()
for hkl, value, d in c_star_list:
d_list.append(d)
value_list.append(value)
max_value = value_list.min_max_mean().max
if value_list.size()>3:
max_value = value_list[2]
new_d_list = []
new_value_list = []
for d, value in zip(d_list, value_list):
if value < max_value/1000: # reject those that are really zero
continue
new_d_list.append(d)
new_value_list.append(value)
return new_d_list, new_value_list
def get_helical_trans_z_angstrom(params = None,
c_star_list = None, crystal_symmetry = None,
minimum_ratio = 2.,
max_first_peak = 1, out = sys.stdout):
# Find highest-resolution peak along c*...guess it is n*z_translation
# where n is small
max_z = flex.double(crystal_symmetry.unit_cell().parameters()[:3]).min_max_mean().max
if params.control.verbose:
print("Values along c*: ", file = out)
d_list, value_list = get_d_and_value_list(c_star_list)
for d, value in zip(d_list, value_list):
if params.control.verbose:
print(" %.2f A : %.2f " %(d, value), file = out)
d_list, value_list = get_max_min_list(
d_list = d_list, value_list = value_list, minimum_ratio = 1.0)
d_list, value_list = get_max_min_list(
d_list = d_list, value_list = value_list, minimum_ratio = 2.0,
maximum_only = True)
sort_list = []
for d, value in zip(d_list, value_list):
sort_list.append([value, d])
sort_list.sort(key=itemgetter(0))
sort_list.reverse()
likely_z_translations = []
dis_min = params.crystal_info.resolution/4
for value, d in sort_list:
likely_z_translations_local = []
for i in range(1, max_first_peak+1):
z = d/i
if z > max_z: continue
if z < dis_min: continue # no way
if is_close_to_any(z = z, others = likely_z_translations,
dis_min = dis_min): continue
likely_z_translations_local.append(z)
likely_z_translations.append(z)
print("\nMaximal values along c* and likely z-translations: ", file = out)
for z in likely_z_translations:
print(" %.2f A " %(z), end = ' ', file = out)
print(file = out)
return likely_z_translations
def small_deltas(z_translations, dis_min = None):
delta_list = []
for z, z1 in zip(z_translations, z_translations[1:]):
delta = abs(z-z1)
if not is_close_to_any(z = delta, others = z_translations+delta_list,
dis_min = dis_min):
delta_list.append(abs(delta))
return delta_list
def is_close_to_any(z = None, others = None,
dis_min = None):
for x in others:
if abs(x-z)<dis_min:
return True
return False
def get_max_min_list(d_list = None, value_list = None,
minimum_ratio = None, maximum_only = False):
max_min_list = []
max_min_d_list = []
for value_prev, d_prev, \
value, d, \
value_next, d_next in zip(
value_list+[0, 0],
d_list+[0, 0],
[0]+value_list+[0],
[0]+d_list+[0],
[0, 0]+value_list,
[0, 0]+d_list):
if d and ( value >= value_prev *minimum_ratio) and (
value >= value_next*minimum_ratio): # local max
max_min_list.append(value)
max_min_d_list.append(d)
if (not maximum_only) and d and ( value <= value_prev ) and (
value <= value_next): # local min
max_min_list.append(value)
max_min_d_list.append(d)
return max_min_d_list, max_min_list
def get_c_star_list(f_array = None,
zero_index_a = 0, zero_index_b = 1, zero_index_c = 2):
c_star_list = []
for value, (indices, d) in zip(f_array.data(),
f_array.d_spacings()):
if indices[zero_index_a] == 0 and indices[zero_index_b] == 0 and \
indices[zero_index_c] >= 4:
c_star_list.append([tuple(indices), value, d])
c_star_list.sort()
return c_star_list
def get_params_from_args(args):
command_line = iotbx.phil.process_command_line_with_files(
map_file_def = "input_files.map_file",
seq_file_def = "input_files.seq_file",
pdb_file_def = "input_files.pdb_in",
ncs_file_def = "input_files.ncs_file",
args = args,
master_phil = master_phil)
return command_line.work.extract()
def get_mask_around_molecule(map_data = None,
wang_radius = None,
buffer_radius = None,
force_buffer_radius = None,
return_masked_fraction = False,
minimum_fraction_of_max = 0.01,
solvent_content = None,
solvent_content_iterations = None,
crystal_symmetry = None, out = sys.stdout):
# use iterated solvent fraction tool to identify mask around molecule
try:
from phenix.autosol.map_to_model import iterated_solvent_fraction
solvent_fraction, mask = iterated_solvent_fraction(
crystal_symmetry = crystal_symmetry,
wang_radius = wang_radius,
solvent_content = solvent_content,
solvent_content_iterations = solvent_content_iterations,
map_as_double = map_data,
out = out)
except Exception as e:
print("No mask obtained...", file = out)
return None, None
if not mask:
print("No mask obtained...", file = out)
return None, None
# Now expand the mask to increase molecular region
expand_size = estimate_expand_size(
crystal_symmetry = crystal_symmetry,
map_data = map_data,
expand_target = buffer_radius,
minimum_expand_size = 0,
out = out)
print("Target mask expand size is %d based on buffer_radius of %7.1f A" %(
expand_size, buffer_radius), file = out)
co, sorted_by_volume, min_b, max_b = get_co(map_data = mask,
threshold = 0.5, wrapping = False)
if len(sorted_by_volume)<2:
print ("\nSkipping expansion as no space is available\n", file = out)
return None, None
masked_fraction = sorted_by_volume[1][0]/mask.size()
if expand_size <= 0:
expanded_fraction = masked_fraction
else: # Try to get expanded fraction < 0.5*(masked_fraction+1)
upper_limit = 0.5*(masked_fraction+1)
bool_region_mask = co.expand_mask(id_to_expand = sorted_by_volume[1][1],
expand_size = expand_size)
s = (bool_region_mask == True)
expanded_fraction = s.count(True)/s.size()
if expanded_fraction>upper_limit:
amount_too_big = max(1.e-10, expanded_fraction-upper_limit)/max(1.e-10,
expanded_fraction-masked_fraction)**0.667
# cut back
original_expand_size = expand_size
expand_size = max(1, int(0.5+expand_size * min(1, max(0, (1-amount_too_big)))))
if expand_size != original_expand_size:
print ("\nCutting back expand size to try and get "+
"fraction < about %.2f . New expand_size: %s" %(
upper_limit, expand_size), file = out)
bool_region_mask = co.expand_mask(id_to_expand = sorted_by_volume[1][1],
expand_size = expand_size)
s = (bool_region_mask == True)
expanded_fraction = s.count(True)/s.size()
if expanded_fraction > 0.9999:
print ("\nSkipping expansion as no space is available\n", file = out)
return None, None
print("\nLargest masked region before buffering: %7.2f" %(masked_fraction),
file = out)
print("\nLargest masked region after buffering: %7.2f" %(expanded_fraction),
file = out)
if solvent_content and (not force_buffer_radius):
delta_as_is = abs(solvent_content- (1-masked_fraction))
delta_expanded = abs(solvent_content- (1-expanded_fraction))
if delta_expanded > delta_as_is:
# already there
expand_size = 0
print ("Setting expand size to zero as masked fraction already ",
"close to solvent_content", file = out)
s = None
minimum_size = sorted_by_volume[1][0] * minimum_fraction_of_max
if expand_size == 0:
result = co.result()
else:
result = None
for v1, i1 in sorted_by_volume[1:]:
if v1 < minimum_size: break
if expand_size > 0:
bool_region_mask = co.expand_mask(
id_to_expand = i1, expand_size = expand_size)
else:
bool_region_mask = (result == i1)
if s is None:
s = (bool_region_mask == True)
else:
s |= (bool_region_mask == True)
mask.set_selected(s, 1)
mask.set_selected(~s, 0)
masked_fraction = mask.count(1)/mask.size()
print("Masked fraction after buffering: %7.2f" %(masked_fraction), file = out)
if return_masked_fraction:
return mask.as_double(), 1-masked_fraction
else: # usual return solvent fraction estimate
return mask.as_double(), solvent_fraction # This is solvent fraction est.
def get_mean_in_and_out(sel = None,
map_data = None,
verbose = False,
out = sys.stdout):
mean_value_in, fraction_in = get_mean_in_or_out(sel = sel,
map_data = map_data,
out = out)
mean_value_out, fraction_out = get_mean_in_or_out(sel = ~sel,
map_data = map_data,
out = out)
if mean_value_out is None:
mean_value_out = mean_value_in
if mean_value_in is None:
mean_value_in = mean_value_out
if verbose:
print("\nMean inside mask: %7.2f Outside mask: %7.2f Fraction in: %7.2f" %(
mean_value_in, mean_value_out, fraction_in), file = out)
return mean_value_in, mean_value_out, fraction_in
def get_mean_in_or_out(sel = None,
map_data = None,
out = sys.stdout):
masked_map = map_data.deep_copy()
if sel.count(False) != 0:
masked_map.as_1d().set_selected(~sel.as_1d(), 0)
mean_after_zeroing_in_or_out = masked_map.as_1d().min_max_mean().mean
if sel.count(True) != 0:
masked_map.as_1d().set_selected(sel.as_1d(), 1)
fraction_in_or_out = masked_map.as_1d().min_max_mean().mean
if fraction_in_or_out >1.e-10:
mean_value = mean_after_zeroing_in_or_out/fraction_in_or_out
else:
mean_value = None
return mean_value, fraction_in_or_out
def apply_soft_mask(map_data = None,
mask_data = None,
rad_smooth = None,
crystal_symmetry = None,
set_outside_to_mean_inside = False,
set_mean_to_zero = False,
threshold = 0.5,
verbose = False,
out = sys.stdout):
# apply a soft mask based on mask_data to map_data.
# set value outside mask == mean value inside mask or mean value outside mask
original_mask_data = mask_data.deep_copy()
smoothed_mask_data = smooth_mask_data(mask_data = mask_data,
crystal_symmetry = crystal_symmetry,
threshold = threshold,
rad_smooth = rad_smooth)
masked_map = apply_mask_to_map(mask_data = original_mask_data,
smoothed_mask_data = smoothed_mask_data,
map_data = map_data,
set_outside_to_mean_inside = set_outside_to_mean_inside,
set_mean_to_zero = set_mean_to_zero,
threshold = threshold,
verbose = verbose,
out = out)
return masked_map, smoothed_mask_data
def smooth_mask_data(mask_data = None,
crystal_symmetry = None,
threshold = None,
rad_smooth = None):
if threshold is None:
threshold = mask_data.as_1d().min_max_mean().max * 0.5
# Smooth a mask in place. First make it a binary mask
s = mask_data > threshold # s marks inside mask
mask_data = mask_data.set_selected(~s, 0) # outside mask == 0
mask_data = mask_data.set_selected( s, 1)
if mask_data.count(1) and mask_data.count(0): # something to do
maptbx.unpad_in_place(map = mask_data)
mask_data = maptbx.smooth_map(
map = mask_data,
crystal_symmetry = crystal_symmetry,
rad_smooth = rad_smooth)
# Make sure that mask_data max value is now 1, scale if not
max_mask_data_value = mask_data.as_1d().min_max_mean().max
if max_mask_data_value > 1.e-30 and max_mask_data_value!= 1.0:
mask_data = mask_data*(1./max_mask_data_value)
else:
pass
return mask_data
def apply_mask_to_map(mask_data = None,
smoothed_mask_data = None,
set_outside_to_mean_inside = None,
set_mean_to_zero = None,
map_data = None,
threshold = 0.5,
verbose = None,
out = sys.stdout):
if smoothed_mask_data and not mask_data:
mask_data = smoothed_mask_data
elif mask_data and not smoothed_mask_data:
smoothed_mask_data = mask_data
s = mask_data > threshold # s marks inside mask
# get mean inside or outside mask
if verbose:
print("\nStarting map values inside and outside mask:", file = out)
mean_value_in, mean_value_out, fraction_in = get_mean_in_and_out(sel = s,
verbose = verbose, map_data = map_data, out = out)
if verbose:
print("\nMask inside and outside values", file = out)
mask_mean_value_in, mask_mean_value_out, mask_fraction_in = get_mean_in_and_out(
sel = s, map_data = mask_data, verbose = verbose, out = out)
if verbose:
print("\nSmoothed mask inside and outside values", file = out)
smoothed_mean_value_in, smoothed_mean_value_out, smoothed_fraction_in = \
get_mean_in_and_out(sel = s, map_data = smoothed_mask_data,
verbose = verbose, out = out)
# Now replace value outside mask with mean_value, value inside with current,
# smoothly going from one to the other based on mask_data
# set_to_mean will be a constant map with value equal to inside or outside
if (set_outside_to_mean_inside is False):
target_value_for_outside = 0
elif set_outside_to_mean_inside or mean_value_out is None:
target_value_for_outside = mean_value_in
if verbose:
print("Setting value outside mask to mean inside (%.2f)" %(
target_value_for_outside), file = out)
else:
target_value_for_outside = mean_value_out
if verbose:
print("Setting value outside mask to mean outside (%.2f)" %(
target_value_for_outside), file = out)
set_to_mean = mask_data.deep_copy()
ss = set_to_mean > -1.e+30 # select everything
set_to_mean.set_selected(ss, target_value_for_outside)
masked_map = (map_data * smoothed_mask_data ) + (set_to_mean * (1-smoothed_mask_data))
if set_mean_to_zero: # remove average
masked_map = masked_map - masked_map.as_1d().min_max_mean().mean
if verbose:
print("\nFinal mean value inside and outside mask:", file = out)
mean_value_in, mean_value_out, fraction_in = get_mean_in_and_out(sel = s,
map_data = masked_map, verbose = verbose, out = out)
return masked_map
def estimate_expand_size(
crystal_symmetry = None,
map_data = None,
expand_target = None,
minimum_expand_size = 1,
out = sys.stdout):
if not expand_target:
return minimum_expand_size
abc = crystal_symmetry.unit_cell().parameters()[:3]
N_ = map_data.all()
nn = 0.
for i in range(3):
delta = abc[i]/N_[i]
nn+= expand_target/delta
nn = max(1, int(0.5+nn/3.))
print("Expand size (grid units): %d (about %4.1f A) " %(
nn, nn*abc[0]/N_[0]), file = out)
return max(minimum_expand_size, nn)
def get_max_z_range_for_helical_symmetry(params, out = sys.stdout):
if not params.input_files.ncs_file: return
ncs_obj, dummy_tracking_data = get_ncs(params = params, out = out)
if not ncs_obj.is_helical_along_z(): return
if params.map_modification.restrict_z_distance_for_helical_symmetry: #take it
return params.map_modification.restrict_z_distance_for_helical_symmetry
if not params.map_modification.restrict_z_turns_for_helical_symmetry: return
print("Identifying maximum z-range for helical symmetry", file = out)
print("Maximum of %7.1f turns up and down in Z allowed..." %(
params.map_modification.restrict_z_turns_for_helical_symmetry), file = out)
r, t = ncs_obj.ncs_groups()[0].helix_rt_forwards()
cost = r[0]
sint = r[1]
import math
theta = abs(180.*math.atan2(sint, cost)/3.14159)
trans = abs(t)
pitch = trans*360./max(0.1, theta)
max_z = params.map_modification.restrict_z_turns_for_helical_symmetry*pitch
print("Z-values restricted to +/- %7.1f A" %(max_z), file = out)
print("\nRunning map-box once to get position of molecule, again to"+\
" apply\n Z restriction\n", file = out)
return max_z
def dist(x, y):
dd = 0.
for a, b in zip(x, y):
dd+= (a-b)**2
return dd**0.5
def get_ncs_closest_sites(
closest_sites = None,
sites_cart = None,
used_ncs_id_list = None,
box_ncs_object = None,
box_crystal_symmetry = None,
out = sys.stdout):
# try to find NCS ops mapping sites_cart close to closest_sites
best_id = None
best_rms = None
best_sites = closest_sites.deep_copy()
for ncs_id in range(box_ncs_object.max_operators()):
if ncs_id in used_ncs_id_list: continue
test_sites = closest_sites.deep_copy()
ncs_sites_cart = get_ncs_sites_cart(sites_cart = sites_cart,
ncs_obj = box_ncs_object, unit_cell = box_crystal_symmetry.unit_cell(),
ncs_id = ncs_id,
ncs_in_cell_only = False)
test_sites.extend(ncs_sites_cart)
rms = radius_of_gyration_of_vector(test_sites)
if best_rms is None or rms < best_rms:
best_rms = rms
best_ncs_id = ncs_id
best_sites = test_sites.deep_copy()
used_ncs_id_list.append(best_ncs_id)
return best_sites, used_ncs_id_list
def get_closest_sites(
high_points = None,
sites_cart = None,
box_ncs_object = None,
box_crystal_symmetry = None,
out = sys.stdout):
if not box_ncs_object.is_point_group_symmetry() and not \
box_ncs_object.is_helical_along_z():
# extract point_group symmetry if present and box_ncs_object doesn't have it
print("Trying to extract point-group symmetry from box_ncs_object "+\
"with %d ops" %( box_ncs_object.max_operators()), file = out)
ncs_object = box_ncs_object.deep_copy(extract_point_group_symmetry = True)
if ncs_object:
print("New number of operators satisfying point-group symmetry: %d" %(
ncs_object.max_operators()), file = out)
box_ncs_object = ncs_object
else:
print("No point-group symmetry found", file = out)
ncs_copies = box_ncs_object.max_operators()
closest_sites = high_points
from scitbx.matrix import col
for id in range(sites_cart.size()):
local_sites_cart = sites_cart[id:id+1]
local_sites_cart.extend(get_ncs_sites_cart(sites_cart = local_sites_cart,
ncs_obj = box_ncs_object, unit_cell = box_crystal_symmetry.unit_cell(),
ncs_in_cell_only = True))
if local_sites_cart.size() <ncs_copies: continue # some were out of range
xx = col((0., 0., 0., ))
for site in closest_sites:
xx+= col(site)
xx = xx/max(1, closest_sites.size())
target = flex.vec3_double()
target.append(xx)
dd, id1, id2 = target.min_distance_between_any_pair_with_id(
local_sites_cart)
best_points = local_sites_cart[id2:id2+1]
closest_sites.extend(best_points)
return closest_sites[1:]
def get_range(sites = None, unit_cell = None, map_data = None,
boundary_tolerance = None, out = sys.stdout):
x_values = flex.double()
y_values = flex.double()
z_values = flex.double()
for site_cart in sites:
(x, y, z) = tuple(site_cart)
x_values.append(x)
y_values.append(y)
z_values.append(z)
x_min_max_mean = x_values.min_max_mean()
x_min = x_min_max_mean.min
x_max = x_min_max_mean.max
y_min_max_mean = y_values.min_max_mean()
y_min = y_min_max_mean.min
y_max = y_min_max_mean.max
z_min_max_mean = z_values.min_max_mean()
z_min = z_min_max_mean.min
z_max = z_min_max_mean.max
print("\nRange for box:", file = out)
print(" X Y Z", file = out)
print(" LOW: %7.1f %7.1f %7.1f " %(tuple([x_min, y_min, z_min])), file = out)
print(" HIGH: %7.1f %7.1f %7.1f \n" %(tuple([x_max, y_max, z_max])), file = out)
# move to 0, 1 if near ends
if x_min<= boundary_tolerance: x_min = 0.
if y_min<= boundary_tolerance: y_min = 0.
if z_min<= boundary_tolerance: z_min = 0.
a, b, c, al, bet, gam = unit_cell.parameters()
if x_min>= a-boundary_tolerance: x_min = a
if y_min>= b-boundary_tolerance: y_min = b
if z_min>= c-boundary_tolerance: z_min = c
print("\nAdjusted range for box:", file = out)
print(" X Y Z", file = out)
print(" LOW: %7.1f %7.1f %7.1f " %(tuple([x_min, y_min, z_min])), file = out)
print(" HIGH: %7.1f %7.1f %7.1f \n" %(tuple([x_max, y_max, z_max])), file = out)
nx, ny, nz = map_data.all()
# convert to grid units
i_min = max(0, min(nx, int(0.5+nx*x_min/a)))
j_min = max(0, min(ny, int(0.5+ny*y_min/b)))
k_min = max(0, min(nz, int(0.5+nz*z_min/c)))
i_max = max(0, min(nx, int(0.5+nx*x_max/a)))
j_max = max(0, min(ny, int(0.5+ny*y_max/b)))
k_max = max(0, min(nz, int(0.5+nz*z_max/c)))
lower_bounds = [i_min, j_min, k_min]
upper_bounds = [i_max, j_max, k_max]
print("\nGrid bounds for box:", file = out)
print(" X Y Z", file = out)
print(" LOW: %7d %7d %7d " %(tuple([i_min, j_min, k_min])), file = out)
print(" HIGH: %7d %7d %7d \n" %(tuple([i_max, j_max, k_max])), file = out)
return lower_bounds, upper_bounds
def get_bounds_for_au_box(params,
box = None, out = sys.stdout):
# Try to get bounds for a box that include one au
if not box.ncs_object or box.ncs_object.max_operators()<2:
return None, None, None
box_ncs_object = box.ncs_object
box_map_data = box.map_box
box_crystal_symmetry = box.box_crystal_symmetry
random_points = 10*params.reconstruction_symmetry.random_points
sites_cart = get_points_in_map(box_map_data, n = random_points,
minimum_fraction_of_max = params.segmentation.density_select_threshold,
random_xyz = params.crystal_info.resolution*2.,
crystal_symmetry = box_crystal_symmetry)
assert sites_cart.size() >0
# apply symmetry to sites_orth and see where the molecule is
ncs_sites_cart = get_ncs_sites_cart(sites_cart = sites_cart,
ncs_obj = box_ncs_object, unit_cell = box_crystal_symmetry.unit_cell(),
ncs_in_cell_only = True)
# generate this in a lower-memory way XXX
low_res_map_data = get_low_res_map_data(sites_cart = ncs_sites_cart,
d_min = params.crystal_info.resolution*7.,
crystal_symmetry = box_crystal_symmetry,
out = out)
high_points = get_high_points_from_map( # actually returns just one.
map_data = low_res_map_data,
unit_cell = box_crystal_symmetry.unit_cell(), out = out)
from scitbx.matrix import col
high_points = high_points[0:1]
cutout_center = col(high_points[0])
print("Center of box will be near (%7.1f, %7.1f, %7.1f)" %(
tuple(cutout_center)))
# now figure out box that contains at least one copy of each ncs-related
# point.
# Find closest ncs-related points for each unique random point to this
# center. Starting box is the box that contains all of these.
closest_sites = get_closest_sites(
high_points = high_points,
sites_cart = sites_cart,
box_ncs_object = box_ncs_object,
box_crystal_symmetry = box_crystal_symmetry,
out = out)
if not closest_sites or closest_sites.size()<1:
print("\nNo sites representing au of map found...skipping au box\n", file = out)
return None, None, None
print("\nTotal of %d sites representing 1 au found" %(
closest_sites.size()), file = out)
# write out closest_sites to match original position
coordinate_offset = -1*matrix.col(box.shift_cart)
write_atoms(file_name = 'one_au.pdb',
crystal_symmetry = box_crystal_symmetry, sites = closest_sites+coordinate_offset)
unique_closest_sites = closest_sites.deep_copy()
# Now if desired, find NCS-related groups of sites
if params.segmentation.n_au_box >1:
print("\nFinding up to %d related au" %(params.segmentation.n_au_box), file = out)
print("Starting RMSD of sites: %7.1f A " %(
radius_of_gyration_of_vector(closest_sites)), file = out)
sites_orig = closest_sites.deep_copy()
used_ncs_id_list = [box_ncs_object.ncs_groups()[0].identity_op_id()]
for i in range(params.segmentation.n_au_box-1):
closest_sites, used_ncs_id_list = get_ncs_closest_sites(
used_ncs_id_list = used_ncs_id_list,
closest_sites = closest_sites,
sites_cart = sites_orig,
box_ncs_object = box_ncs_object,
box_crystal_symmetry = box_crystal_symmetry,
out = out)
print("\nNew total of %d sites representing %d au found" %(
closest_sites.size(), params.segmentation.n_au_box), file = out)
print("New rmsd: %7.1f A " %(
radius_of_gyration_of_vector(closest_sites)), file = out)
lower_bounds, upper_bounds = get_range(
sites = closest_sites, map_data = box_map_data,
boundary_tolerance = params.crystal_info.resolution,
unit_cell = box_crystal_symmetry.unit_cell(),
out = out)
return lower_bounds, upper_bounds, unique_closest_sites+coordinate_offset
def get_low_res_map_data(sites_cart = None,
crystal_symmetry = None,
d_min = None,
out = sys.stdout):
from cctbx import xray
xrs, scatterers = set_up_xrs(crystal_symmetry = crystal_symmetry)
unit_cell = crystal_symmetry.unit_cell()
sites_fract = unit_cell.fractionalize(sites_cart)
for xyz_fract in sites_fract:
scatterers.append( xray.scatterer(scattering_type = "H", label = "H",
site = xyz_fract, u = 0, occupancy = 1.0))
xrs = xray.structure(xrs, scatterers = scatterers)
# generate f_array to d_min with xrs
f_array = xrs.structure_factors(d_min = d_min, anomalous_flag = False).f_calc()
weight_f_array = f_array.structure_factors_from_scatterers(
algorithm = 'direct',
xray_structure = xrs).f_calc()
return get_map_from_map_coeffs(map_coeffs = weight_f_array,
crystal_symmetry = crystal_symmetry)
def get_bounds_for_helical_symmetry(params,
box = None, crystal_symmetry = None):
original_cell = box.map_data.all()
new_cell = box.map_box.all()
z_first = box.gridding_first[2]
z_last = box.gridding_last[2]
assert z_last>= z_first
z_middle = (z_first+z_last)//2
delta_z = crystal_symmetry.unit_cell().parameters()[5]/box.map_data.all()[2]
n_z_max = int(0.5+
params.map_modification.restrict_z_distance_for_helical_symmetry/delta_z)
new_z_first = max(z_first, z_middle-n_z_max)
new_z_last = min(z_last, z_middle+n_z_max)
lower_bounds = list(deepcopy(box.gridding_first))
upper_bounds = list(deepcopy(box.gridding_last))
lower_bounds[2] = new_z_first
upper_bounds[2] = new_z_last
return lower_bounds, upper_bounds
def check_memory(map_data, ratio_needed, maximum_fraction_to_use = 0.90,
maximum_map_size = 1,
out = sys.stdout):
map_size = map_data.size()/(1024*1024*1024)
if maximum_map_size and map_size>maximum_map_size:
raise Sorry("Maximum map size for this tool is %s GB" %(maximum_map_size))
needed_memory = ratio_needed*map_size
from libtbx.utils import guess_total_memory # returns total memory
bytes_total_memory = guess_total_memory()
if bytes_total_memory:
total_memory = bytes_total_memory/(1024*1024*1024)
else:
total_memory = None
print("\nMap size is " +\
"%.2f GB. This will require about %.1f GB of memory" %(
map_size, needed_memory) +"\nfor this stage of analysis\n", file = out)
if total_memory:
print("Total memory on this computer is about %.1f GB." %(
total_memory), file = out)
if (needed_memory>= 0.5* total_memory):
print("\n ** WARNING: It is possible that this computer may not"+\
" have **\n *** sufficient memory to complete this job. ***\n", file = out)
if (needed_memory >= maximum_fraction_to_use*total_memory):
raise Sorry("This computer does not have sufficient "+
"memory (%.0f GB needed) \nto run this job" %(needed_memory))
def get_params(args, map_data = None, crystal_symmetry = None,
half_map_data_list = None,
sharpening_target_pdb_inp = None,
ncs_object = None,
write_files = None,
auto_sharpen = None,
density_select = None,
add_neighbors = None,
save_box_map_ncs_au = None,
sequence = None,
wrapping = None,
target_ncs_au_file = None,
regions_to_keep = None,
solvent_content = None,
resolution = None,
molecular_mass = None,
symmetry = None,
chain_type = None,
keep_low_density = None,
box_buffer = None,
soft_mask_extract_unique = None,
mask_expand_ratio = None,
include_helical_symmetry = None,
min_ncs_cc = None,
symmetry_center = None,
return_params_only = None,
out = sys.stdout):
params = get_params_from_args(args)
# Set params specifically if coming in from call
if sequence is not None:
params.crystal_info.sequence = sequence
if (wrapping is not None) and (params.crystal_info.use_sg_symmetry is None):
params.crystal_info.use_sg_symmetry = wrapping
if target_ncs_au_file is not None:
params.input_files.target_ncs_au_file = target_ncs_au_file
if regions_to_keep is not None:
params.map_modification.regions_to_keep = regions_to_keep
if solvent_content is not None:
params.crystal_info.solvent_content = solvent_content
if resolution is not None:
params.crystal_info.resolution = resolution
if molecular_mass is not None:
params.crystal_info.molecular_mass = molecular_mass
if symmetry is not None:
params.reconstruction_symmetry.symmetry = symmetry
if min_ncs_cc is not None:
params.reconstruction_symmetry.min_ncs_cc = min_ncs_cc
if symmetry_center is not None:
params.reconstruction_symmetry.symmetry_center = symmetry_center
if include_helical_symmetry is not None:
params.reconstruction_symmetry.include_helical_symmetry = \
include_helical_symmetry
if chain_type is not None:
params.crystal_info.chain_type = chain_type
if regions_to_keep is not None:
params.map_modification.regions_to_keep = regions_to_keep
params.segmentation.iterate_with_remainder = False
elif keep_low_density:
params.segmentation.iterate_with_remainder = True
elif keep_low_density is False:
params.segmentation.iterate_with_remainder = False
else:
pass # just so it is clear this was considered
if box_buffer is not None:
params.output_files.box_buffer = box_buffer
if soft_mask_extract_unique is not None:
params.map_modification.soft_mask = soft_mask_extract_unique
if mask_expand_ratio is not None:
params.segmentation.mask_expand_ratio = mask_expand_ratio
if write_files is not None:
params.control.write_files = write_files
if auto_sharpen is not None:
params.map_modification.auto_sharpen = auto_sharpen
if density_select is not None:
params.segmentation.density_select = density_select
if add_neighbors is not None:
params.segmentation.add_neighbors = add_neighbors
if save_box_map_ncs_au is not None:
params.control.save_box_map_ncs_au = save_box_map_ncs_au
if return_params_only:
return params
print("\nSegment_and_split_map\n", file = out)
print("Command used: %s\n" %(
" ".join(['segment_and_split_map']+args)), file = out)
master_params.format(python_object = params).show(out = out)
# Set space-group defaults
if params.crystal_info.use_sg_symmetry:
if params.map_modification.restrict_map_size is None:
params.map_modification.restrict_map_size = False
if params.crystal_info.is_crystal is None:
params.crystal_info.is_crystal = True
else:
if params.map_modification.restrict_map_size is None:
params.map_modification.restrict_map_size = True
if params.crystal_info.is_crystal is None:
params.crystal_info.is_crystal = False
# Turn off files if desired
if params.control.write_files is False:
params.output_files.magnification_map_file = None
params.output_files.magnification_map_file = None
params.output_files.magnification_ncs_file = None
params.output_files.shifted_map_file = None
params.output_files.shifted_sharpened_map_file = None
params.output_files.sharpened_map_file = None
params.output_files.shifted_pdb_file = None
params.output_files.shifted_ncs_file = None
params.output_files.shifted_used_ncs_file = None
params.output_files.box_map_file = None
params.output_files.box_mask_file = None
params.output_files.write_output_maps = False
params.output_files.remainder_map_file = None
params.output_files.output_info_file = None
params.output_files.restored_pdb = None
params.output_files.output_weight_map_pickle_file = None
from cctbx.maptbx.auto_sharpen import set_sharpen_params
params = set_sharpen_params(params, out)
if params.input_files.seq_file and not params.crystal_info.sequence and \
not sequence:
if not params.crystal_info.sequence:
if sequence:
params.crystal_info.sequence = sequence
else:
params.crystal_info.sequence = open(params.input_files.seq_file).read()
print("Read sequence from %s" %(params.input_files.seq_file), file = out)
if not params.crystal_info.resolution and (
params.map_modification.b_iso is not None or \
params.map_modification.auto_sharpen
or params.map_modification.resolution_dependent_b or
params.map_modification.b_sharpen):
raise Sorry("Need resolution for segment_and_split_map with sharpening")
if params.map_modification.auto_sharpen and (
params.map_modification.b_iso is not None or
params.map_modification.b_sharpen is not None or
params.map_modification.resolution_dependent_b is not None):
print("Turning off auto_sharpen as it is not compatible with "+\
"b_iso, \nb_sharpen, or resolution_dependent_b", file = out)
params.map_modification.auto_sharpen = False
if params.control.write_files and \
params.output_files.output_directory and \
(not os.path.isdir(params.output_files.output_directory)):
os.mkdir(params.output_files.output_directory)
if not params.output_files.output_directory:
params.output_files.output_directory = ""
# Test to see if we can use adjusted_sa as target and use box_map with it
if (params.map_modification.residual_target == 'adjusted_sa' or
params.map_modification.sharpening_target == 'adjusted_sa') and \
(params.map_modification.box_in_auto_sharpen or
params.map_modification.density_select_in_auto_sharpen) and (
params.map_modification.auto_sharpen):
print("Checking to make sure we can use adjusted_sa as target...",
end = ' ', file = out)
try:
from phenix.autosol.map_to_model import iterated_solvent_fraction
dummy = iterated_solvent_fraction # just to import it
except Exception as e:
raise Sorry("Please either set box_in_auto_sharpen = False and "+
"\ndensity_select_in_auto_sharpen = False or \n"+\
"set residual_target = kurtosis and sharpening_target = kurtosis")
print("OK", file = out)
if not half_map_data_list: half_map_data_list = []
if params.input_files.info_file:
map_data = None
pdb_hierarchy = None
from libtbx import easy_pickle
print("Loading tracking data from %s" %(
params.input_files.info_file), file = out)
tracking_data = easy_pickle.load(params.input_files.info_file)
return params, map_data, half_map_data_list, pdb_hierarchy, tracking_data, None
else:
tracking_data = info_object()
tracking_data.set_params(params)
# PDB file
if params.input_files.pdb_file:
print("\nInput PDB file to be used to identify region to work with: %s\n" %(
params.input_files.pdb_file), file = out)
pdb_inp = iotbx.pdb.input(file_name = params.input_files.pdb_file)
pdb_hierarchy = pdb_inp.construct_hierarchy()
pdb_atoms = pdb_hierarchy.atoms()
pdb_atoms.reset_i_seq()
tracking_data.set_input_pdb_info(file_name = params.input_files.pdb_file,
n_residues = pdb_hierarchy.overall_counts().n_residues)
else:
pdb_hierarchy = None
if map_data:
pass # ok
elif params.input_files.map_file:
ccp4_map = iotbx.mrcfile.map_reader(
file_name = params.input_files.map_file)
if not crystal_symmetry:
crystal_symmetry = ccp4_map.crystal_symmetry() # 2018-07-18
tracking_data.set_full_crystal_symmetry(
ccp4_map.unit_cell_crystal_symmetry())
tracking_data.set_full_unit_cell_grid(ccp4_map.unit_cell_grid)
map_data = ccp4_map.data.as_double()
else:
raise Sorry("Need ccp4 map")
if not crystal_symmetry:
raise Sorry("Need crystal_symmetry")
if params.input_files.half_map_file:
if len(params.input_files.half_map_file) != 2:
raise Sorry("Please supply none or two half_map_file values")
half_map_data_list = []
half_map_data_list.append(iotbx.mrcfile.map_reader(
file_name = params.input_files.half_map_file[0]).data.as_double())
half_map_data_list.append(iotbx.mrcfile.map_reader(
file_name = params.input_files.half_map_file[1]).data.as_double())
# Get the NCS object
ncs_obj, dummy_tracking_data = get_ncs(params = params,
ncs_object = ncs_object, out = out)
if (not params.map_modification.auto_sharpen or
params.map_modification.b_iso is not None) and (
not params.crystal_info.molecular_mass and
not params.crystal_info.solvent_content and
not params.input_files.seq_file and not params.crystal_info.sequence and
not sequence):
params.crystal_info.solvent_content = get_iterated_solvent_fraction(
crystal_symmetry = crystal_symmetry,
verbose = params.control.verbose,
resolve_size = params.control.resolve_size,
mask_padding_fraction = \
params.segmentation.mask_padding_fraction,
fraction_of_max_mask_threshold = \
params.segmentation.fraction_of_max_mask_threshold,
cell_cutoff_for_solvent_from_mask = \
params.segmentation.cell_cutoff_for_solvent_from_mask,
mask_resolution = params.crystal_info.resolution,
map = map_data,
out = out)
if params.crystal_info.solvent_content:
print("Estimated solvent content: %.2f" %(
params.crystal_info.solvent_content), file = out)
else:
raise Sorry("Unable to estimate solvent content...please supply "+
"solvent_content \nor molecular_mass")
if params.map_modification.auto_sharpen or \
params.map_modification.b_iso is not None or \
params.map_modification.b_sharpen is not None or \
params.map_modification.resolution_dependent_b is not None:
# Sharpen the map
print("Auto-sharpening map before using it", file = out)
local_params = deepcopy(params)
if tracking_data.solvent_fraction: # XXX was previously always done but may not have been set
local_params.crystal_info.solvent_content = tracking_data.solvent_fraction
from cctbx.maptbx.auto_sharpen import run as auto_sharpen
acc = map_data.accessor()
map_data, new_map_coeffs, new_crystal_symmetry, new_si = auto_sharpen(
args = [], params = local_params,
map_data = map_data,
wrapping = wrapping,
crystal_symmetry = crystal_symmetry,
write_output_files = False,
pdb_inp = sharpening_target_pdb_inp,
ncs_obj = ncs_obj,
return_map_data_only = False,
return_unshifted_map = True,
half_map_data_list = half_map_data_list,
n_residues = tracking_data.n_residues,
ncs_copies = ncs_obj.max_operators(),
out = out)
tracking_data.b_sharpen = new_si.b_sharpen
if not tracking_data.solvent_fraction:
tracking_data.solvent_fraction = new_si.solvent_fraction
if tracking_data.params.output_files.sharpened_map_file:
sharpened_map_file = os.path.join(
tracking_data.params.output_files.output_directory,
tracking_data.params.output_files.sharpened_map_file)
sharpened_map_data = map_data.deep_copy()
if acc is not None: # offset the map to match original if possible
sharpened_map_data.reshape(acc)
print("Gridding of sharpened map:", file = out)
print("Origin: ", sharpened_map_data.origin(), file = out)
print("All: ", sharpened_map_data.all(), file = out)
print("\nWrote sharpened map in original location with "+\
"origin at %s\nto %s" %(
str(sharpened_map_data.origin()), sharpened_map_file), file = out)
# NOTE: original unit cell and grid
write_ccp4_map(tracking_data.full_crystal_symmetry,
sharpened_map_file, sharpened_map_data,
output_unit_cell_grid = tracking_data.full_unit_cell_grid, )
params.input_files.map_file = sharpened_map_file # overwrite map_file name here
# done with any sharpening
params.map_modification.auto_sharpen = False# so we don't do it again later
params.map_modification.b_iso = None
params.map_modification.b_sharpen = None
params.map_modification.resolution_dependent_b = None
if params.control.sharpen_only:
print("Stopping after sharpening", file = out)
return
# check on size right away
if params.control.memory_check:
# map_box and mask generation use about 50GB of memory for
# map with 1 billion elements
check_memory(map_data = map_data, maximum_map_size = None,
ratio_needed = 50, out = out)
if params.map_modification.magnification and \
params.map_modification.magnification!= 1.0:
print("\nAdjusting magnification by %7.3f\n" %(
params.map_modification.magnification), file = out)
if ncs_obj:
# Magnify ncs
print("NCS before applying magnification...", file = out)
ncs_obj.format_all_for_group_specification(out = out)
ncs_obj = ncs_obj.adjust_magnification(
magnification = params.map_modification.magnification)
if params.output_files.magnification_ncs_file:
file_name = os.path.join(params.output_files.output_directory,
params.output_files.magnification_ncs_file)
print("Writing NCS after magnification of %7.3f to %s" %(
params.map_modification.magnification, file_name), file = out)
ncs_obj.format_all_for_group_specification(out = out)
ncs_obj.format_all_for_group_specification(file_name = file_name)
params.input_files.ncs_file = file_name
else:
raise Sorry("Need magnification_ncs_file defined if magnification is"+
" applied \nto input NCS file")
# Magnify map
shrunk_uc = []
for i in range(3):
shrunk_uc.append(
crystal_symmetry.unit_cell().parameters()[i] *
params.map_modification.magnification )
uc_params = crystal_symmetry.unit_cell().parameters()
from cctbx import uctbx
new_unit_cell = uctbx.unit_cell(
parameters = (shrunk_uc[0], shrunk_uc[1], shrunk_uc[2],
uc_params[3], uc_params[4], uc_params[5]))
print("Original unit cell: (%7.4f, %7.4f, %7.4f, %7.4f, %7.4f, %7.4f)" %(
crystal_symmetry.unit_cell().parameters()), file = out)
crystal_symmetry = crystal.symmetry(
unit_cell = new_unit_cell,
space_group = crystal_symmetry.space_group())
print("New unit cell: (%7.4f, %7.4f, %7.4f, %7.4f, %7.4f, %7.4f)" %(
crystal_symmetry.unit_cell().parameters()), file = out)
# magnify original unit cell too..
cell = list(tracking_data.full_crystal_symmetry.unit_cell().parameters())
for i in range(3):
cell[i] = cell[i]*params.map_modification.magnification
tracking_data.set_full_crystal_symmetry(
crystal.symmetry(tuple(cell), ccp4_map.space_group_number))
print("New original (full unit cell): "+\
" (%7.4f, %7.4f, %7.4f, %7.4f, %7.4f, %7.4f)" %(
tracking_data.full_crystal_symmetry.unit_cell.parameters()), file = out)
if params.output_files.magnification_map_file:
file_name = os.path.join(params.output_files.output_directory,
params.output_files.magnification_map_file)
# write out magnified map (our working map) (before shifting it)
print("\nWriting magnification map (input map with "+\
"magnification of %7.3f \n" %(params.map_modification.magnification) +\
"applied) to %s \n" %(file_name), file = out)
#write_ccp4_map(crystal_symmetry, file_name, map_data)
# NOTE: original unit cell and grid
write_ccp4_map(tracking_data.full_crystal_symmetry,
file_name, map_data,
output_unit_cell_grid = tracking_data.original_unit_cell_grid, )
params.input_files.map_file = file_name
else:
raise Sorry("Need a file name to write out magnification_map_file")
params.map_modification.magnification = None # no longer need it.
tracking_data.set_input_map_info(file_name = params.input_files.map_file,
crystal_symmetry = crystal_symmetry,
origin = map_data.origin(),
all = map_data.all())
tracking_data.set_crystal_symmetry(crystal_symmetry = crystal_symmetry)
tracking_data.set_original_crystal_symmetry(crystal_symmetry = crystal_symmetry)
tracking_data.set_accessor(acc = map_data.accessor())
# Save center of map
map_symmetry_center = get_center_of_map(map_data, crystal_symmetry)
# Check for helical ncs...if present we may try to cut map at +/- 1 turn
params.map_modification.restrict_z_distance_for_helical_symmetry = \
get_max_z_range_for_helical_symmetry(params, out = out)
# either use map_box with density_select = True or just shift the map
if params.segmentation.density_select:
print("\nTrimming map to density...", file = out)
args = ["output_format = ccp4"]
if params.segmentation.density_select_threshold is not None:
print("Threshold for density selection will be: %6.2f \n"%(
params.segmentation.density_select_threshold), file = out)
args.append("density_select_threshold = %s" %(
params.segmentation.density_select_threshold))
if params.segmentation.get_half_height_width is not None:
args.append("get_half_height_width = %s" %(
params.segmentation.get_half_height_width))
if params.input_files.ncs_file:
args.append("symmetry_file = %s" %(params.input_files.ncs_file))
if params.input_files.pdb_file:
args.append("pdb_file = %s" %(params.input_files.pdb_file))
args.append("ccp4_map_file = %s" %(params.input_files.map_file))
file_name_prefix = os.path.join(params.output_files.output_directory,
"density_select")
args.append("output_file_name_prefix = %s" %(file_name_prefix))
from mmtbx.command_line.map_box import run as run_map_box
args.append("keep_input_unit_cell_and_grid = False") # for new defaults
assert params.crystal_info.use_sg_symmetry is not None
wrapping = params.crystal_info.use_sg_symmetry
if params.segmentation.lower_bounds and params.segmentation.upper_bounds:
bounds_supplied = True
print("\nRunning map_box with supplied bounds", file = out)
box = run_map_box(args,
map_data = map_data,
ncs_object = ncs_obj,
crystal_symmetry = crystal_symmetry,
lower_bounds = params.segmentation.lower_bounds,
upper_bounds = params.segmentation.upper_bounds,
write_output_files = params.output_files.write_output_maps,
wrapping = wrapping,
log = out)
else:
bounds_supplied = False
box = run_map_box(["density_select = True"]+args,
map_data = map_data,
crystal_symmetry = crystal_symmetry,
ncs_object = ncs_obj,
write_output_files = params.output_files.write_output_maps,
wrapping = wrapping,
log = out)
# Run again to select au box
shifted_unique_closest_sites = None
selected_au_box = None
if params.segmentation.select_au_box is None and box.ncs_object and \
box.ncs_object.max_operators() >= params.segmentation.n_ops_to_use_au_box:
params.segmentation.select_au_box = True
print("Setting select_au_box to True as there are %d operators" %(
box.ncs_object.max_operators()), file = out)
if params.segmentation.select_au_box and not bounds_supplied:
lower_bounds, upper_bounds, unique_closest_sites = get_bounds_for_au_box(
params, box = box, out = out) #unique_closest_sites relative to original map
if lower_bounds and upper_bounds:
bounds_supplied = True
selected_au_box = True
score, ncs_cc = score_ncs_in_map(map_data = box.map_box,
allow_score_with_pg = False,
sites_orth = unique_closest_sites+box.shift_cart,
ncs_object = box.ncs_object, ncs_in_cell_only = True,
crystal_symmetry = box.box_crystal_symmetry, out = null_out())
print("NCS CC before rerunning box: %7.2f SCORE: %7.1f OPS: %d " %(
ncs_cc, score, box.ncs_object.max_operators()), file = out)
print("\nRunning map-box again with boxed range ...", file = out)
del box
box = run_map_box(args, lower_bounds = lower_bounds,
map_data = map_data,
crystal_symmetry = crystal_symmetry,
ncs_object = ncs_obj,
wrapping = wrapping,
upper_bounds = upper_bounds, log = out)
box.map_box = box.map_box.as_double() # Do we need double?
shifted_unique_closest_sites = unique_closest_sites+box.shift_cart
# Or run again for helical symmetry
elif params.map_modification.restrict_z_distance_for_helical_symmetry and \
not bounds_supplied:
bounds_supplied = True
lower_bounds, upper_bounds = get_bounds_for_helical_symmetry(params,
crystal_symmetry = crystal_symmetry, box = box)
print("\nRunning map-box again with restricted Z range ...", file = out)
box = run_map_box(args,
map_data = map_data,
crystal_symmetry = crystal_symmetry,
ncs_object = ncs_obj,
lower_bounds = lower_bounds, upper_bounds = upper_bounds,
wrapping = wrapping,
write_output_files = params.output_files.write_output_maps,
log = out)
#-----------------------------
if bounds_supplied and box.ncs_object:
print("Selecting remaining NCS operators", file = out)
box.ncs_object = select_remaining_ncs_ops(
map_data = box.map_box,
crystal_symmetry = box.box_crystal_symmetry,
closest_sites = shifted_unique_closest_sites,
random_points = params.reconstruction_symmetry.random_points,
ncs_object = box.ncs_object,
out = out)
score, ncs_cc = score_ncs_in_map(map_data = box.map_box,
allow_score_with_pg = False,
ncs_object = box.ncs_object, ncs_in_cell_only = True,
sites_orth = shifted_unique_closest_sites,
crystal_symmetry = box.box_crystal_symmetry, out = null_out())
if score is not None:
print("NCS CC after selections: %7.2f SCORE: %7.1f OPS: %d" %(
ncs_cc, score, box.ncs_object.max_operators()), file = out)
#-----------------------------
origin_shift = box.shift_cart
# Note: moving cell with (0, 0, 0) in middle to (0, 0, 0) at corner means
# total_shift_cart and origin_shift both positive
map_data = box.map_box
map_data = scale_map(map_data, out = out)
crystal_symmetry = box.box_crystal_symmetry
print("New unit cell: %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f " %(
crystal_symmetry.unit_cell().parameters()), file = out)
tracking_data.set_crystal_symmetry(crystal_symmetry = crystal_symmetry)
print("Moving origin to (0, 0, 0)", file = out)
print("Adding (%8.2f, %8.2f, %8.2f) to all coordinates\n"%(
tuple(origin_shift)), file = out)
# NOTE: size and cell params are now different!
tracking_data.set_box_map_bounds_first_last(
box.gridding_first, box.gridding_last)
new_half_map_data_list = []
ii = 0
for hm in half_map_data_list:
ii+= 1
hm = hm.shift_origin() # shift if necessary
hm = box.cut_and_copy_map(map_data = hm).as_double()
hm.reshape(flex.grid(hm.all()))
new_half_map_data_list.append(hm)
cutout_half_map_file = os.path.join(params.output_files.output_directory,
"cutout_half_map_%s.ccp4" %(ii))
print("Writing cutout half_map data to %s" %(cutout_half_map_file), file = out)
write_ccp4_map(crystal_symmetry, cutout_half_map_file, new_half_map_data_list[-1])
half_map_data_list = new_half_map_data_list
if params.map_modification.soft_mask:
mask_data, map_data, half_map_data_list, \
soft_mask_solvent_fraction, smoothed_mask_data, \
original_box_map_data = \
get_and_apply_soft_mask_to_maps(
resolution = params.crystal_info.resolution,
wang_radius = params.crystal_info.wang_radius,
buffer_radius = params.crystal_info.buffer_radius,
map_data = map_data, crystal_symmetry = crystal_symmetry,
half_map_data_list = half_map_data_list,
out = out)
print("\nSolvent fraction from soft mask procedure: %7.2f (not used)\n" %(
soft_mask_solvent_fraction), file = out)
shifted_ncs_object = box.ncs_object
if not shifted_ncs_object or shifted_ncs_object.max_operators()<2:
from mmtbx.ncs.ncs import ncs
shifted_ncs_object = ncs()
shifted_ncs_object.set_unit_ncs()
else: # shift if necessary...
shift_needed = not \
(map_data.focus_size_1d() > 0 and map_data.nd() == 3 and
map_data.is_0_based())
a, b, c = crystal_symmetry.unit_cell().parameters()[:3]
N_ = map_data.all()
O_ = map_data.origin()
sx, sy, sz = O_[0]/N_[0], O_[1]/N_[1], O_[2]/N_[2]
# Note: If (0, 0, 0) is in the middle of the box, origin at sx, sy, sz
# is negative, shift of coordinates will be positive
sx_cart, sy_cart, sz_cart = crystal_symmetry.unit_cell().orthogonalize(
[sx, sy, sz])
print("Origin for input map is at (%8.2f, %8.2f, %8.2f)" % (
sx_cart, sy_cart, sz_cart), file = out)
print("Cell dimensions of this map are: (%8.2f, %8.2f, %8.2f)" % (a, b, c), file = out)
if shift_needed:
if(not crystal_symmetry.space_group().type().number() in [0, 1]):
raise RuntimeError("Not implemented")
origin_shift = [-sx_cart, -sy_cart, -sz_cart] # positive if (0, 0, 0) in middle
print("Adding (%8.2f, %8.2f, %8.2f) to all coordinates"%(
tuple(origin_shift))+" to put origin at (0, 0, 0)\n", file = out)
map_data = map_data.shift_origin()
new_half_map_data_list = []
for hm in half_map_data_list:
new_half_map_data_list.append(hm.shift_origin())
half_map_data_list = new_half_map_data_list
else:
origin_shift = (0., 0., 0.)
# Get NCS object if any
if params.input_files.ncs_file and not ncs_obj:
ncs_obj, dummy_obj = get_ncs(file_name = params.input_files.ncs_file)
if ncs_obj:
shifted_ncs_object = ncs_obj.coordinate_offset(
coordinate_offset = matrix.col(origin_shift)) # shift to match shifted map
else:
from mmtbx.ncs.ncs import ncs
shifted_ncs_object = ncs()
shifted_ncs_object.set_unit_ncs()
update_tracking_data_with_sharpening(
map_data = map_data,
tracking_data = tracking_data, out = out)
# Set origin shift now
tracking_data.set_origin_shift(origin_shift)
map_symmetry_center = matrix.col(map_symmetry_center)+matrix.col(origin_shift) # New ctr
if shifted_ncs_object and params.control.check_ncs:
ncs_obj_to_check = shifted_ncs_object
else:
ncs_obj_to_check = None
found_ncs = False
if params.reconstruction_symmetry.symmetry or ncs_obj_to_check or \
params.reconstruction_symmetry.optimize_center:
looking_for_ncs = True
new_ncs_obj, ncs_cc, ncs_score = run_get_ncs_from_map(params = params,
map_data = map_data,
map_symmetry_center = map_symmetry_center,
crystal_symmetry = crystal_symmetry,
ncs_obj = ncs_obj_to_check,
out = out,
)
if new_ncs_obj:
found_ncs = True
shifted_ncs_object = new_ncs_obj.deep_copy()
# offset this back to where it would have been before the origin offset..
new_ncs_obj = new_ncs_obj.coordinate_offset(
coordinate_offset = -1*matrix.col(origin_shift))
# XXX save it in tracking_data
if params.output_files.output_directory:
if not os.path.isdir(params.output_files.output_directory):
os.mkdir(params.output_files.output_directory)
file_name = os.path.join(params.output_files.output_directory,
'ncs_from_map.ncs_spec')
f = open(file_name, 'w')
new_ncs_obj.format_all_for_group_specification(out = f)
f.close()
print("Wrote NCS operators (for original map) to %s" %(file_name), file = out)
if not params.control.check_ncs:
params.input_files.ncs_file = file_name # set it
else:
looking_for_ncs = False
if params.control.check_ncs:
print("Done checking NCS", file = out)
return params, map_data, half_map_data_list, pdb_hierarchy, tracking_data, None
if looking_for_ncs and (not found_ncs) and \
params.reconstruction_symmetry.symmetry.upper() not in ['ANY', 'ALL']:
raise Sorry(
"Unable to identify %s symmetry automatically in this map." %(
params.reconstruction_symmetry.symmetry)+
"\nPlease supply a symmetry file with symmetry matrices.")
if params.segmentation.expand_size is None:
params.segmentation.expand_size = estimate_expand_size(
crystal_symmetry = crystal_symmetry,
map_data = map_data,
expand_target = params.segmentation.expand_target,
out = out)
if params.output_files.output_info_file and params.control.shift_only:
write_info_file(params = params, tracking_data = tracking_data, out = out)
return params, map_data, half_map_data_list, pdb_hierarchy, \
tracking_data, shifted_ncs_object
def write_info_file(params = None, tracking_data = None, out = sys.stdout):
# write out the info file
from libtbx import easy_pickle
tracking_data.show_summary(out = out)
print("\nWriting summary information to: %s" %(
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.output_info_file)), file = out)
print("\nTo restore original position of a PDB file built into these maps, use:", file = out)
print("phenix.segment_and_split_map info_file = %s" %(
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.output_info_file))+" pdb_to_restore = mypdb.pdb\n", file = out)
easy_pickle.dump(os.path.join(tracking_data.params.output_files.output_directory, params.output_files.output_info_file),
tracking_data)
def get_and_apply_soft_mask_to_maps(
resolution = None, #params.crystal_info.resolution
wang_radius = None, #params.crystal_info.wang_radius
buffer_radius = None, #params.crystal_info.buffer_radius
force_buffer_radius = None, # apply buffer radius always
map_data = None, crystal_symmetry = None,
solvent_content = None,
solvent_content_iterations = None,
return_masked_fraction = True,
rad_smooth = None,
half_map_data_list = None,
out = sys.stdout):
smoothed_mask_data = None
if not resolution:
from cctbx.maptbx import d_min_from_map
resolution = d_min_from_map(
map_data, crystal_symmetry.unit_cell(), resolution_factor = 1./4.)
if not rad_smooth:
rad_smooth = resolution
if rad_smooth:
print("\nApplying soft mask with smoothing radius of %.2f A\n" %(
rad_smooth), file = out)
if wang_radius:
wang_radius = wang_radius
else:
wang_radius = 1.5*resolution
if buffer_radius is not None:
buffer_radius = buffer_radius
else:
buffer_radius = 2.*resolution
original_map_data = map_data.deep_copy()
# Check to make sure this is possible
cell_dims = crystal_symmetry.unit_cell().parameters()[:3]
min_cell_dim = min(cell_dims)
if wang_radius > 0.25 * min_cell_dim or buffer_radius > 0.25 * min_cell_dim:
new_wang_radius = min(wang_radius, 0.25 * min_cell_dim)
new_buffer_radius = min(buffer_radius, 0.25 * min_cell_dim)
print ("Cell is too small to get solvent fraction ...resetting "+
"values of wang_radius \n"+
"(was %.3f A now %.3f A) and buffer_radius (was %.3f A now %.3f A)" %(
wang_radius, new_wang_radius, buffer_radius, new_buffer_radius), file = out)
wang_radius = new_wang_radius
buffer_radius = new_buffer_radius
mask_data, solvent_fraction = get_mask_around_molecule(map_data = map_data,
crystal_symmetry = crystal_symmetry,
wang_radius = wang_radius,
solvent_content = solvent_content,
solvent_content_iterations = solvent_content_iterations,
buffer_radius = buffer_radius,
force_buffer_radius = force_buffer_radius,
return_masked_fraction = return_masked_fraction,
out = out)
if mask_data:
map_data, smoothed_mask_data = apply_soft_mask(map_data = map_data,
mask_data = mask_data.as_double(),
rad_smooth = rad_smooth,
crystal_symmetry = crystal_symmetry,
out = out)
new_half_map_data_list = []
if not half_map_data_list: half_map_data_list = []
for half_map in half_map_data_list:
assert half_map.size() == mask_data.size()
half_map, smoothed_mask_data = apply_soft_mask(map_data = half_map,
mask_data = mask_data.as_double(),
rad_smooth = rad_smooth,
crystal_symmetry = crystal_symmetry,
out = out)
new_half_map_data_list.append(half_map)
half_map_data_list = new_half_map_data_list
else:
print("Unable to get mask...skipping", file = out)
return mask_data, map_data, half_map_data_list, \
solvent_fraction, smoothed_mask_data, original_map_data
def get_ncs(params = None, tracking_data = None, file_name = None,
ncs_object = None, out = sys.stdout):
if not file_name:
file_name = params.input_files.ncs_file
if (not ncs_object or ncs_object.max_operators()<2) and file_name: print("Reading ncs from %s" %(file_name), file = out)
is_helical_symmetry = None
if (not ncs_object or ncs_object.max_operators()<2) and not file_name: # No ncs supplied...use just 1 ncs copy..
from mmtbx.ncs.ncs import ncs
ncs_object = ncs()
ncs_object.set_unit_ncs()
#ncs_object.display_all(log = out)
elif (not ncs_object or ncs_object.max_operators()<2) and \
not os.path.isfile(file_name):
raise Sorry("The ncs file %s is missing" %(file_name))
else: # get the ncs
if not ncs_object:
from mmtbx.ncs.ncs import ncs
ncs_object = ncs()
try: # see if we can read biomtr records
pdb_inp = iotbx.pdb.input(file_name = file_name)
ncs_object.ncs_from_pdb_input_BIOMT(pdb_inp = pdb_inp, log = out)
except Exception as e: # try as regular ncs object
ncs_object.read_ncs(file_name = file_name, log = out)
#ncs_object.display_all(log = out)
ncs_object.select_first_ncs_group()
if ncs_object.max_operators()<1:
from mmtbx.ncs.ncs import ncs
ncs_object = ncs()
ncs_object.set_unit_ncs()
print("\nTotal of %d NCS operators read\n" %(
ncs_object.max_operators()), file = out)
if not tracking_data or not params:
return ncs_object, None
if ncs_object.max_operators()<2:
print("No NCS present", file = out)
elif ncs_object.is_helical_along_z(
abs_tol_t = tracking_data.params.reconstruction_symmetry.abs_tol_t,
rel_tol_t = tracking_data.params.reconstruction_symmetry.rel_tol_t,
tol_r = tracking_data.params.reconstruction_symmetry.tol_r):
print("This NCS is helical symmetry", file = out)
is_helical_symmetry = True
elif ncs_object.is_point_group_symmetry(
abs_tol_t = tracking_data.params.reconstruction_symmetry.abs_tol_t,
rel_tol_t = tracking_data.params.reconstruction_symmetry.rel_tol_t,
tol_r = tracking_data.params.reconstruction_symmetry.tol_r):
print("This NCS is point-group symmetry", file = out)
elif params.crystal_info.is_crystal:
print("This NCS is crystal symmetry", file = out)
elif not (
params.reconstruction_symmetry.require_helical_or_point_group_symmetry):
print("WARNING: NCS is not crystal symmetry nor point-group "+\
"symmetry nor helical symmetry", file = out)
else:
raise Sorry("Need point-group or helical symmetry.")
if not ncs_object or ncs_object.max_operators()<1:
raise Sorry("Need ncs information from an ncs_info file")
if tracking_data:
tracking_data.set_input_ncs_info(file_name = file_name, # XXX may be updated ops
number_of_operators = ncs_object.max_operators())
if tracking_data and is_helical_symmetry: # update shifted_ncs_info
if tracking_data.shifted_ncs_info: # XXX may not be needed
shifted = True
else:
shifted = False
print("Updating NCS info (shifted = %s)" %(shifted), file = out)
tracking_data.update_ncs_info(is_helical_symmetry = True, shifted = shifted)
if tracking_data.input_map_info and tracking_data.input_map_info.all:
z_range = tracking_data.crystal_symmetry.unit_cell(). \
parameters()[2]
print("Extending NCS operators to entire cell (z_range = %.1f)" %(
z_range), file = out)
max_operators = \
tracking_data.params.reconstruction_symmetry.max_helical_operators
if max_operators:
print("Maximum new number of NCS operators will be %s" %(
max_operators), file = out)
ncs_object.extend_helix_operators(z_range = z_range,
max_operators = max_operators)
#ncs_object.display_all()
print("New number of NCS operators is: %s " %(
ncs_object.max_operators()), file = out)
tracking_data.update_ncs_info(
number_of_operators = ncs_object.max_operators(), is_helical_symmetry = True,
shifted = shifted)
return ncs_object, tracking_data
def score_threshold(b_vs_region = None, threshold = None,
sorted_by_volume = None, n_residues = None,
ncs_copies = None,
fraction_occupied = None,
solvent_fraction = None,
map_data = None,
residues_per_region = 50,
min_volume = None,
min_ratio = None,
max_ratio_to_target = None,
min_ratio_to_target = None,
weight_score_grid_points = 1.,
weight_score_ratio = 1.0,
weight_near_one = 0.1,
min_ratio_of_ncs_copy_to_first = None,
target_in_all_regions = None,
crystal_symmetry = None,
chain_type = None,
out = sys.stdout):
# We want about 1 region per 50-100 residues for the biggest region.
# One possibility is to try to maximize the median size of the N top
# regions, where N = number of expected regions = n_residues/residues_per_region
# Also note we have an idea how big a region should be (how many
# grid points) if we make an assumption about the fractional volume that
# should be inside a region compared to the total volume of protein/nucleic
# acid in the region...this gives us target_in_top_regions points.
# So using this, make the median size as close to target_in_top_regions as
# we can.
# If we have solvent fraction but not ncs_copies or n_residues, guess the
# number of residues and ncs copies from the volume
if ncs_copies is not None and n_residues is not None:
expected_regions = max(ncs_copies,
max(1, int(0.5+n_residues/residues_per_region)))
else:
if chain_type in [None, 'None']: chain_type = "PROTEIN"
assert crystal_symmetry is not None
assert solvent_fraction is not None
volume_per_residue, nres, chain_type = get_volume_of_seq(
"A", chain_type = chain_type, out = out)
expected_regions = max(1, int(0.5+(1-solvent_fraction)*\
crystal_symmetry.unit_cell().volume()/volume_per_residue ))
# NOTE: This is expected residues. expected_regions should be this
# divided by residues_per_region
expected_regions = max(1, int(0.5+expected_regions/residues_per_region))
ncs_copies = 1
target_in_top_regions = target_in_all_regions/expected_regions
nn = len(sorted_by_volume)-1 # first one is total
ok = True
too_low = None # marker for way too low
too_high = None
if nn < ncs_copies:
ok = False #return # not enough
v1, i1 = sorted_by_volume[1]
if v1 < min_volume:
ok = False #return
if v1 > max_ratio_to_target*target_in_top_regions:
ok = False #return
too_low = True
if v1 < min_volume or v1 < 0.1*min_ratio_to_target*target_in_top_regions:
# way too high
too_high = True
# there should be about ncs_copies copies of each size region if ncs_copies>1
if ncs_copies>1:
v2, i2 = sorted_by_volume[max(1, min(ncs_copies, nn))]
score_ratio = v2/v1 # want it to be about 1
if score_ratio < min_ratio_of_ncs_copy_to_first:
ok = False #return # not allowed
else:
score_ratio = 1.0 # for ncs_copies = 1
nn2 = min(nn, max(1, (expected_regions+1)//2))
median_number, iavg = sorted_by_volume[nn2]
# number in each region should be about target_in_top_regions
if median_number > target_in_top_regions:
score_grid_points = target_in_top_regions/max(1., median_number)
else:
score_grid_points = median_number/target_in_top_regions
if v1> target_in_top_regions:
score_grid_points_b = target_in_top_regions/max(1., v1)
else:
score_grid_points_b = v1/target_in_top_regions
score_grid_points = 0.5*(score_grid_points+score_grid_points_b)
score_grid_points = score_grid_points**2 # maybe even **3
if threshold>1.:
score_near_one = 1./threshold
else:
score_near_one = threshold
# Normalize weight_score_ratio by target_in_top_regions:
sc = min(1., 0.5*median_number/max(1, target_in_top_regions))
overall_score = (
(sc*weight_score_ratio*score_ratio+
weight_score_grid_points*score_grid_points+
weight_near_one*score_near_one
) /
(weight_score_ratio+weight_score_grid_points+weight_near_one))
half_expected_regions = max(1, (1+expected_regions)//2)
ratio = sorted_by_volume[min(len(sorted_by_volume)-1, half_expected_regions)][0]/v1
if ok and v1 >= target_in_top_regions/2 and \
len(sorted_by_volume)>half_expected_regions:
last_volume = sorted_by_volume[half_expected_regions][0]
if ratio >= min_ratio and \
last_volume>= min_volume:
has_sufficient_regions = True
else:
has_sufficient_regions = False
else:
has_sufficient_regions = False
print("%7.2f %5.2f %5d %4d %5d %5d %6.3f %5s %5.3f %s %s" %(
b_vs_region.b_iso, threshold, target_in_top_regions, expected_regions,
v1, median_number, ratio, has_sufficient_regions, overall_score, ok, nn), file = out)
if not b_vs_region.b_iso in b_vs_region.b_vs_region_dict.keys():
b_vs_region.b_vs_region_dict[b_vs_region.b_iso] = {}
b_vs_region.sa_sum_v_vs_region_dict[b_vs_region.b_iso] = {}
b_vs_region.sa_nn_vs_region_dict[b_vs_region.b_iso] = {}
b_vs_region.sa_ratio_b_vs_region_dict[b_vs_region.b_iso] = {}
b_vs_region.b_vs_region_dict[b_vs_region.b_iso][threshold] = nn
b_vs_region.sa_nn_vs_region_dict[b_vs_region.b_iso][threshold] = None
b_vs_region.sa_ratio_b_vs_region_dict[b_vs_region.b_iso][threshold] = None
return overall_score, has_sufficient_regions, \
too_low, too_high, expected_regions, ok
def choose_threshold(b_vs_region = None, map_data = None,
fraction_occupied = None,
solvent_fraction = None,
n_residues = None,
ncs_copies = None,
scale = 0.95,
calculate_sa = None, # calculate surface area of top sa_percent of target
sa_percent = None, # calculate surface area of top sa_fraction of target
density_threshold = None,
starting_density_threshold = None,
wrapping = None,
residues_per_region = None,
min_volume = None,
min_ratio = None,
max_ratio_to_target = None,
min_ratio_to_target = None,
min_ratio_of_ncs_copy_to_first = None,
verbose = None,
crystal_symmetry = None,
chain_type = None,
out = sys.stdout):
best_threshold = None
best_threshold_has_sufficient_regions = None
best_score = None
best_ok = None
if not ncs_copies: ncs_copies = 1
print("\nChecking possible cutoffs for region identification", file = out)
print("Scale: %7.3f" %(scale), file = out)
used_ranges = []
# Assume any threshold that is lower than a threshold that gave a non-zero value
# and is zero is an upper bound on the best value. Same the other way around
upper_bound = 1000
lower_bound = 0.0001
best_nn = None
if density_threshold is not None: # use it
print("\nUsing input threshold of %5.2f " %(
density_threshold), file = out)
n_range_low_high_list = [[0, 0]] # use as is
else:
n_range_low_high_list = [[-16, 4], [-32, 16], [-64, 80]]
if starting_density_threshold is not None:
starting_density_threshold = starting_density_threshold
print("Starting density threshold is: %7.3f" %(
starting_density_threshold), file = out)
else:
starting_density_threshold = 1.0
if verbose:
local_out = out
else:
from libtbx.utils import null_out
local_out = null_out()
target_in_all_regions = map_data.size()*fraction_occupied*(1-solvent_fraction)
print("\nTarget number of points in all regions: %.0f" %(
target_in_all_regions), file = local_out)
local_threshold = find_threshold_in_map(target_points = int(
target_in_all_regions), map_data = map_data)
print("Cutoff will be threshold of %7.2f marking %7.1f%% of cell" %(
local_threshold, 100.*(1.-solvent_fraction)), file = out)
print("B-iso Threshold Target N Biggest Median Ratio Enough Score OK Regions", file = local_out)
unique_expected_regions = None
for n_range_low, n_range_high in n_range_low_high_list:
last_score = None
for nn in range(n_range_low, n_range_high+1):
if nn in used_ranges: continue
used_ranges.append(nn)
if density_threshold is not None:
threshold = density_threshold
else:
threshold = starting_density_threshold*(scale**nn)
if threshold < lower_bound or threshold > upper_bound:
continue
co, sorted_by_volume, min_b, max_b = get_co(
map_data = map_data.deep_copy(),
threshold = threshold, wrapping = wrapping)
if len(sorted_by_volume)<2:
score, has_sufficient_regions, too_low, too_high, expected_regions, ok = \
None, None, None, None, None, None
continue # don't go on
else:
score, has_sufficient_regions, too_low, too_high, expected_regions, ok = \
score_threshold(b_vs_region = b_vs_region,
threshold = threshold,
sorted_by_volume = sorted_by_volume,
fraction_occupied = fraction_occupied,
solvent_fraction = solvent_fraction,
residues_per_region = residues_per_region,
min_volume = min_volume,
min_ratio = min_ratio,
max_ratio_to_target = max_ratio_to_target,
min_ratio_to_target = min_ratio_to_target,
min_ratio_of_ncs_copy_to_first = min_ratio_of_ncs_copy_to_first,
ncs_copies = ncs_copies,
n_residues = n_residues,
map_data = map_data,
target_in_all_regions = target_in_all_regions,
crystal_symmetry = crystal_symmetry,
chain_type = chain_type,
out = local_out)
if expected_regions:
unique_expected_regions = max(1,
(ncs_copies-1+expected_regions)//ncs_copies)
if too_high and threshold<upper_bound:
upper_bound = threshold
if too_low and threshold>lower_bound:
lower_bound = threshold
if score is None:
if best_threshold and best_threshold_has_sufficient_regions:
if threshold >best_threshold: # new upper bound
upper_bound = threshold
elif threshold <best_threshold: # new lower bound
lower_bound = threshold
elif (ok or not best_ok) and \
(best_score is None or score > best_score):
best_threshold = threshold
best_threshold_has_sufficient_regions = has_sufficient_regions
best_score = score
best_ok = ok
if best_threshold is not None:
print("\nBest threshold: %5.2f\n" %(best_threshold), file = out)
return best_threshold, unique_expected_regions, best_score, best_ok
elif density_threshold is not None: # use it anyhow
return density_threshold, unique_expected_regions, None, None
else:
return None, unique_expected_regions, None, None
def get_co(map_data = None, threshold = None, wrapping = None):
co = maptbx.connectivity(map_data = map_data, threshold = threshold,
wrapping = wrapping)
regions = co.regions()
rr = list(range(0, co.regions().size()))
regions_0 = regions[0]
rr_0 = rr[0]
regions = regions[1:]
rr = rr[1:]
if rr:
z = zip(regions, rr)
sorted_by_volume = sorted(z, key=itemgetter(0), reverse = True)
else:
sorted_by_volume = []
sorted_by_volume = [(regions_0, rr_0)]+sorted_by_volume
min_b, max_b = co.get_blobs_boundaries_tuples() # As grid points, not A
return co, sorted_by_volume, min_b, max_b
def get_connectivity(b_vs_region = None,
map_data = None,
solvent_fraction = None,
n_residues = None,
ncs_copies = None,
fraction_occupied = None,
iterate_with_remainder = None,
min_volume = None,
min_ratio = None,
wrapping = None,
residues_per_region = None,
max_ratio_to_target = None,
min_ratio_to_target = None,
min_ratio_of_ncs_copy_to_first = None,
starting_density_threshold = None,
density_threshold = None,
crystal_symmetry = None,
chain_type = None,
verbose = None,
out = sys.stdout):
print("\nGetting connectivity", file = out)
libtbx.call_back(message = 'segment', data = None)
# Normalize map data now to SD of the part that is not solvent
map_data = renormalize_map_data(
map_data = map_data, solvent_fraction = solvent_fraction)
# Try connectivity at various thresholds
# Choose one that has about the right number of grid points in top regions
scale = 0.95
best_threshold = None
best_scale = scale
best_score = None
best_ok = None
best_unique_expected_regions = None
for ii in range(3):
threshold, unique_expected_regions, score, ok = choose_threshold(
density_threshold = density_threshold,
starting_density_threshold = starting_density_threshold,
b_vs_region = b_vs_region,
map_data = map_data,
n_residues = n_residues,
ncs_copies = ncs_copies,
fraction_occupied = fraction_occupied,
solvent_fraction = solvent_fraction,
scale = scale,
wrapping = wrapping,
residues_per_region = residues_per_region,
min_volume = min_volume,
min_ratio = min_ratio,
max_ratio_to_target = max_ratio_to_target,
min_ratio_to_target = min_ratio_to_target,
min_ratio_of_ncs_copy_to_first = min_ratio_of_ncs_copy_to_first,
crystal_symmetry = crystal_symmetry,
chain_type = chain_type,
verbose = verbose,
out = out)
# Take it if it improves (score, ok)
if threshold is not None:
if best_score is None or \
((ok or not best_ok) and (score > best_score)):
best_score = score
best_unique_expected_regions = unique_expected_regions
best_ok = ok
best_threshold = threshold
best_scale = scale
if best_ok or density_threshold is not None:
break
else:
scale = scale**0.333 # keep trying
if best_threshold is None or (
density_threshold is not None and best_score is None):
if iterate_with_remainder: # on first try failed
raise Sorry("No threshold found...try with density_threshold = xxx")
else: # on iteration...ok
print("Note: No threshold found", file = out)
return None, None, None, None, None, None, None, None
else:
starting_density_threshold = best_threshold
# try it next time
co, sorted_by_volume, min_b, max_b = get_co(
map_data = map_data, threshold = best_threshold, wrapping = wrapping)
return co, sorted_by_volume, min_b, max_b, best_unique_expected_regions, \
best_score, threshold, starting_density_threshold
def get_volume_of_seq(text, chain_type = None, out = sys.stdout):
from iotbx.bioinformatics import chain_type_and_residues
# get chain type and residues (or use given chain type and count residues)
chain_type, n_residues = chain_type_and_residues(text = text, chain_type = chain_type)
if chain_type is None and n_residues is None:
return None, None, None
if chain_type == 'PROTEIN':
mw_residue = 110.0 # from $CDOC/matthews.doc
density_factor = 1.23 # 1.66/DENSITY-OF-PROTEIN = 1.66/1.35
else:
mw_residue = 330.0 # guess for DNA/RNA
density_factor = 1.15 # 1.66/DENSITY-OF-DNA = 1.66/1.45
return len(text)*density_factor*mw_residue, len(text), chain_type
def create_rna_dna(cns_dna_rna_residue_names):
dd = {}
for key in cns_dna_rna_residue_names.keys():
dd[cns_dna_rna_residue_names[key]] = key
return dd
def get_solvent_content_from_seq_file(params,
sequence = None,
seq_file = None,
overall_chain_type = None,
ncs_copies = None,
map_volume = None,
out = sys.stdout):
if params and not overall_chain_type:
overall_chain_type = params.crystal_info.chain_type
if not sequence and not os.path.isfile(seq_file):
raise Sorry(
"The sequence file '%s' is missing." %(seq_file))
if not sequence:
print("\nReading sequence from %s " %(seq_file), file = out)
sequence = open(seq_file).read()
from iotbx.bioinformatics import get_sequences
sequences = get_sequences(text = sequence)
# get unique part of these sequences
from mmtbx.validation.chain_comparison import \
extract_unique_part_of_sequences as eups
print("Unique part of sequences:", file = out)
copies_in_unique, base_copies, unique_sequence_dict = eups(sequences,
out = out)
all_unique_sequence = []
for seq in copies_in_unique.keys():
print("Copies: %s base copies: %s Sequence: %s" %(
copies_in_unique[seq], base_copies, seq), file = out)
all_unique_sequence.append(seq)
if base_copies != ncs_copies:
print("NOTE: %s copies of unique portion but ncs_copies = %s" %(
base_copies, ncs_copies), file = out)
if ncs_copies == 1:
ncs_copies = base_copies
print("Using ncs_copies = %s instead" %(ncs_copies), file = out)
else:
print("Still using ncs_copies = %s" %(ncs_copies), file = out)
volume_of_chains = 0.
n_residues = 0
chain_types_considered = []
for seq in all_unique_sequence:
volume, nres, chain_type = get_volume_of_seq(seq,
chain_type = overall_chain_type, out = out)
if volume is None: continue
volume_of_chains+= volume
n_residues+= nres
if not chain_type in chain_types_considered:
chain_types_considered.append(chain_type)
chain_types_considered.sort()
print("\nChain types considered: %s\n" %(
" ".join(chain_types_considered)), file = out)
volume_of_molecules = volume_of_chains*ncs_copies
n_residues_times_ncs = n_residues*ncs_copies
solvent_fraction = 1.-(volume_of_molecules/map_volume)
solvent_fraction = max(0.001, min(0.999, solvent_fraction))
if solvent_fraction == 0.001 or solvent_fraction == 0.999:
print("NOTE: solvent fraction of %7.2f very unlikely..." %(
solvent_fraction) + "please check ncs_copies and sequence ", file = out)
print("Solvent content from composition: %7.2f" %(solvent_fraction), file = out)
print("Cell volume: %.1f NCS copies: %d Volume of unique chains: %.1f" %(
map_volume, ncs_copies, volume_of_chains), file = out)
print("Total residues: %d Volume of all chains: %.1f Solvent fraction: %.3f "%(
n_residues_times_ncs, volume_of_molecules, solvent_fraction), file = out)
return solvent_fraction, n_residues, n_residues_times_ncs
def get_solvent_fraction(params,
ncs_object = None, ncs_copies = None,
do_not_adjust_dalton_scale = None,
sequence = None,
seq_file = None,
molecular_mass = None,
solvent_content = None,
crystal_symmetry = None, tracking_data = None, out = sys.stdout):
if tracking_data and not crystal_symmetry:
#crystal_symmetry = tracking_data.original_crystal_symmetry not used
crystal_symmetry = tracking_data.crystal_symmetry
map_volume = crystal_symmetry.unit_cell().volume()
if tracking_data and not ncs_copies:
#ncs_copies = tracking_data.input_ncs_info.original_number_of_operators
ncs_copies = tracking_data.input_ncs_info.number_of_operators # 2018-01-29 put back
if not ncs_copies: ncs_copies = 1
if params and not solvent_content:
solvent_content = params.crystal_info.solvent_content
if params and not molecular_mass:
molecular_mass = params.crystal_info.molecular_mass
if params and not seq_file:
seq_file = params.input_files.seq_file
if params and not sequence:
sequence = params.crystal_info.sequence
if seq_file or sequence:
solvent_content, n_residues, n_residues_times_ncs = \
get_solvent_content_from_seq_file(
params,
sequence = sequence,
seq_file = seq_file,
ncs_copies = ncs_copies,
map_volume = map_volume,
out = out)
if params and not params.crystal_info.solvent_content:
params.crystal_info.solvent_content = solvent_content
print("Solvent fraction from composition: %7.2f "%(
params.crystal_info.solvent_content), file = out)
elif params:
print("Solvent content from parameters: %7.2f" %(
params.crystal_info.solvent_content), file = out)
else:
if params and params.crystal_info.solvent_content:
print("Solvent content from parameters: %7.2f" %(
params.crystal_info.solvent_content), file = out)
elif molecular_mass:
solvent_content = \
get_solvent_fraction_from_molecular_mass(
crystal_symmetry = crystal_symmetry,
do_not_adjust_dalton_scale = do_not_adjust_dalton_scale,
molecular_mass = molecular_mass,
out = out)
if params:
params.crystal_info.solvent_content = solvent_content
else:
print("Getting solvent content automatically.", file = out)
if tracking_data:
if params.input_files.seq_file or params.crystal_info.sequence:
tracking_data.set_input_seq_info(file_name = params.input_files.seq_file,
sequence = params.crystal_info.sequence,
n_residues = n_residues)
tracking_data.set_n_residues(
n_residues = n_residues_times_ncs)
if params.crystal_info.solvent_content:
tracking_data.set_solvent_fraction(params.crystal_info.solvent_content)
return tracking_data
else:
return solvent_content
def top_key(dd):
if not dd:
return None, None
elif len(dd) == 1:
return list(dd.items())[0]
else:
best_key = None
best_n = None
for key in dd.keys():
if not best_n or dd[key] > best_n:
best_n = dd[key]
best_key = key
return best_key, best_n
def choose_max_regions_to_consider(params,
sorted_by_volume = None,
ncs_copies = None):
max_per_au = params.segmentation.max_per_au
min_ratio = params.segmentation.min_ratio
min_volume = params.segmentation.min_volume
# sort and eliminate regions with few points and those at end of list
if len(sorted_by_volume)<2:
return 0
max_grid_points = sorted_by_volume[1][0]
cntr = 0
for p in sorted_by_volume[1:]:
cntr+= 1
if max_per_au and (cntr>max_per_au*ncs_copies):
cntr-= 1
break
v, i = p # v = volume in grid points, i = id
if v/max_grid_points<min_ratio or v < min_volume:
cntr-= 1
break
return cntr
def get_edited_mask(sorted_by_volume = None,
max_regions_to_consider = None,
co = None,
out = sys.stdout):
conn_obj = co.result()
origin = list(conn_obj.accessor().origin())
all = list(conn_obj.accessor().all())
conn_obj.accessor().show_summary(out)
edited_mask = conn_obj.deep_copy()
first = True
edited_volume_list = []
original_id_from_id = {}
for i in range(1, max_regions_to_consider+1):
v, id = sorted_by_volume[i]
original_id_from_id[i] = id
edited_volume_list.append(v)
s = (conn_obj == id)
if first:
edited_mask = edited_mask.set_selected(~s, 0)
first = False
edited_mask = edited_mask.set_selected(s, i) # edited mask has ID of
# regions, labeled in decreasing size from 1 to max_regions_to_consider
return edited_mask, edited_volume_list, original_id_from_id
def choose_subset(a, target_number = 1):
new_array = flex.vec3_double()
assert type(new_array) == type(a)
n = a.size()
nskip = max(1, n//target_number)
i = 0
for x in a:
if i%nskip == 0 or i == n-1:
new_array.append(x)
i+= 1
return new_array
def run_get_duplicates_and_ncs(
ncs_obj = None,
min_b = None,
max_b = None,
edited_mask = None,
original_id_from_id = None,
edited_volume_list = None,
max_regions_to_consider = None,
regions_left = None,
tracking_data = None,
out = sys.stdout,
):
duplicate_dict, equiv_dict, equiv_dict_ncs_copy_dict, region_range_dict, \
region_centroid_dict, region_scattered_points_dict = \
get_duplicates_and_ncs(
ncs_obj = ncs_obj,
min_b = min_b,
max_b = max_b,
edited_mask = edited_mask,
edited_volume_list = edited_volume_list,
original_id_from_id = original_id_from_id,
max_regions_to_consider = max_regions_to_consider,
tracking_data = tracking_data,
out = out)
# check that we have region_centroid for all values
complete = True
missing = []
for i in range(1, max_regions_to_consider+1):
if not i in region_centroid_dict.keys():
if (regions_left is None) or (i in regions_left):
complete = False
missing.append(i)
if complete:
return duplicate_dict, equiv_dict, equiv_dict_ncs_copy_dict, \
region_range_dict, region_centroid_dict, \
region_scattered_points_dict
else:
raise Sorry("Cannot find region-centroid for all regions? Missing: %s" %(
missing))
def copy_dict_info(from_dict, to_dict):
for key in from_dict.keys():
to_dict[key] = from_dict[key]
def get_centroid_from_blobs(min_b = None, max_b = None,
id = None, original_id_from_id = None):
orig_id = original_id_from_id[id]
upper = max_b[orig_id]
lower = min_b[orig_id]
avg = []
for u, l in zip(upper, lower):
avg.append(0.5*(u+l))
return avg
def get_duplicates_and_ncs(
ncs_obj = None,
min_b = None,
max_b = None,
edited_mask = None,
original_id_from_id = None,
edited_volume_list = None,
max_regions_to_consider = None,
target_points_per_region = 30,
minimum_points_per_region = 10,
maximum_points_per_region = 100,
tracking_data = None,
out = sys.stdout,
):
unit_cell = tracking_data.crystal_symmetry.unit_cell()
region_scattered_points_dict = get_region_scattered_points_dict(
edited_volume_list = edited_volume_list,
edited_mask = edited_mask,
unit_cell = unit_cell,
target_points_per_region = target_points_per_region,
minimum_points_per_region = minimum_points_per_region,
maximum_points_per_region = maximum_points_per_region)
# Now just use the scattered points to get everything else:
region_n_dict = {} # count of points used by region (differs from volume due
# to the sampling)
region_range_dict = {} # keyed by region in edited_mask; range for x, y, z
region_centroid_dict = {} # keyed by region in edited_mask; range for x, y, z
for id in region_scattered_points_dict.keys():
sites = region_scattered_points_dict[id]
region_n_dict[id] = sites.size()
if region_n_dict[id]:
region_centroid_dict[id] = list(sites.mean())
else: # No points...use bounds from object
region_centroid_dict[id] = get_centroid_from_blobs(min_b = min_b,
max_b = max_b,
id = id, original_id_from_id = original_id_from_id)
# Now get NCS relationships
ncs_group = ncs_obj.ncs_groups()[0]
duplicate_dict = {} # keyed by id, number of duplicates for that region
equiv_dict = {} # equiv_dict[id][other_id] = number_of points other_id matches
# id through an ncs relationship
equiv_dict_ncs_copy_dict = {}
for id in region_scattered_points_dict.keys():
duplicate_dict[id] = 0
equiv_dict[id] = {}
equiv_dict_ncs_copy_dict[id] = {}
# Figure out which ncs operator is the identity
identity_op = ncs_group.identity_op_id()
print("Identity operator is %s" %(identity_op), file = out)
# 2017-12-16 Score poorly if it involves a cell translation unless it
# is a crystal
if len(ncs_group.translations_orth())>1:
# Skip if no ncs...
for id in region_scattered_points_dict.keys():
for xyz_cart in region_scattered_points_dict[id]:
n = 0
for i0 in range(len(ncs_group.translations_orth())):
if i0 == identity_op: continue
r = ncs_group.rota_matrices_inv()[i0] # inverse maps pos 0 on to pos i
t = ncs_group.translations_orth_inv()[i0]
n+= 1
new_xyz_cart = r * matrix.col(xyz_cart) + t
new_xyz_frac = unit_cell.fractionalize(new_xyz_cart)
if tracking_data.params.crystal_info.use_sg_symmetry or \
(new_xyz_frac[0]>= 0 and new_xyz_frac[0]<= 1 and \
new_xyz_frac[1]>= 0 and new_xyz_frac[1]<= 1 and \
new_xyz_frac[2]>= 0 and new_xyz_frac[2]<= 1):
value = edited_mask.value_at_closest_grid_point(new_xyz_frac)
else:
value = 0 # value for nothing there 2017-12-16
if value == id:
duplicate_dict[id]+= 1
break # only count once
elif value>0: # notice which one is matched
if not value in equiv_dict[id]:
equiv_dict[id][value] = 0
equiv_dict_ncs_copy_dict[id][value] = {}
equiv_dict[id][value]+= 1
if not n in equiv_dict_ncs_copy_dict[id][value]:
equiv_dict_ncs_copy_dict[id][value][n] = 0
equiv_dict_ncs_copy_dict[id][value][n]+= 1 # how many are ncs copy n
return duplicate_dict, equiv_dict, equiv_dict_ncs_copy_dict, \
region_range_dict, region_centroid_dict, region_scattered_points_dict
def get_region_scattered_points_dict(
edited_volume_list = None,
edited_mask = None,
unit_cell = None,
sampling_rate = None,
target_points_per_region = None,
minimum_points_per_region = None,
maximum_points_per_region = None):
# Get sampled points in each region
sample_dict = {}
region_scattered_points_dict = {} # some points in each region
if not sampling_rate:
sampling_rate = edited_volume_list[0]//target_points_per_region
sampling_rate_set = False
else:
sampling_rate_set = True
volumes = flex.int()
sampling_rates = flex.int()
id_list = []
# have to set up dummy first set:
volumes.append(0)
sampling_rates.append(0)
id_list.append(0)
for i in range(len(edited_volume_list)):
id = i+1
v = edited_volume_list[i]
region_scattered_points_dict[id] = flex.vec3_double()
volumes.append(v)
if sampling_rate_set:
sample_dict[id] = sampling_rate
sampling_rates.append(sampling_rate)
else:
sample_dict[id] = max(1,
max(v//maximum_points_per_region,
min(v//minimum_points_per_region,
sampling_rate) ))
sampling_rates.append(max(1,
max(v//maximum_points_per_region,
min(v//minimum_points_per_region,
sampling_rate) )))
id_list.append(id)
sample_regs_obj = maptbx.sample_all_mask_regions(
mask = edited_mask,
volumes = volumes,
sampling_rates = sampling_rates,
unit_cell = unit_cell)
for id in id_list[1:]: # skip the dummy first set
region_scattered_points_dict[id] = sample_regs_obj.get_array(id)
return region_scattered_points_dict
def remove_bad_regions(params = None,
duplicate_dict = None,
edited_volume_list = None,
out = sys.stdout):
worst_list = []
for id in list(duplicate_dict.keys()):
fract = duplicate_dict[id]/edited_volume_list[id-1]
if duplicate_dict[id] and fract >= params.segmentation.max_overlap_fraction:
worst_list.append([fract, id])
else:
del duplicate_dict[id]
worst_list.sort()
worst_list.reverse()
bad_region_list = []
max_number_to_remove = int(0.5+
0.01*params.segmentation.remove_bad_regions_percent*len(edited_volume_list))
if worst_list:
print("\nRegions that span multiple NCS au:", file = out)
for fract, id in worst_list:
print("ID: %d Duplicate points: %d (%.1f %%)" %(
id, duplicate_dict[id], 100.*fract), end = ' ', file = out)
if len(bad_region_list)<max_number_to_remove:
bad_region_list.append(id)
print(" (removed)", file = out)
else:
print(file = out)
new_sorted_by_volume = []
region_list = []
region_volume_dict = {}
for i in range(len(edited_volume_list)):
id = i+1
v = edited_volume_list[i]
new_sorted_by_volume.append([v, id])
region_list.append(id)
region_volume_dict[id] = v
if bad_region_list:
print("Bad regions (excluded)", bad_region_list, file = out)
return region_list, region_volume_dict, new_sorted_by_volume, bad_region_list
def sort_by_ncs_overlap(matches, equiv_dict_ncs_copy_dict_id):
sort_list = []
for id1 in matches:
key, n = top_key(equiv_dict_ncs_copy_dict_id[id1]) # Take top ncs_copy
sort_list.append([n, id1])
sort_list.sort(key=itemgetter(0))
sort_list.reverse()
key_list = []
for n, id1 in sort_list:
key_list.append(id1)
return key_list
def get_ncs_equivalents(
bad_region_list = None,
region_list = None,
region_scattered_points_dict = None,
equiv_dict = None,
ncs_copies = None,
equiv_dict_ncs_copy_dict = None,
min_coverage = .10,
out = sys.stdout):
equiv_dict_ncs_copy = {}
for id in region_list:
if id in bad_region_list: continue
match_dict = equiv_dict.get(id, {}) # which are matches
matches = list(match_dict.keys())
if not matches: continue
key_list = sort_by_ncs_overlap(matches, equiv_dict_ncs_copy_dict[id])
n_found = 0
for id1 in key_list:
# id matches id1 N = match_dict[id1]
# 2017-12-16 Do not include if there is a cell translation
key, n = top_key(equiv_dict_ncs_copy_dict[id][id1]) # ncs_copy, n-overlap
if n<min_coverage*region_scattered_points_dict[id].size():
break
else:
if not id in equiv_dict_ncs_copy:equiv_dict_ncs_copy[id] = {}
equiv_dict_ncs_copy[id][id1] = key
n_found+= 1
if n_found>= ncs_copies-1:
break
return equiv_dict_ncs_copy
def get_overlap(l1, l2):
overlap_list = []
l1a = single_list(l1)
l2a = single_list(l2)
for i in l1a:
if i in l2a and not i in overlap_list: overlap_list.append(i)
return overlap_list
def group_ncs_equivalents(params,
region_list = None,
region_volume_dict = None,
equiv_dict_ncs_copy = None,
tracking_data = None,
split_if_possible = None,
out = sys.stdout):
# equiv_dict_ncs_copy[id][id1] = ncs_copy
# group together all the regions that are related to region 1...etc
# if split_if_possible then skip all groups with multiple entries
ncs_equiv_groups_as_list = []
ncs_equiv_groups_as_dict = {}
for id in region_list:
equiv_group = {} #equiv_group[ncs_copy] = [id1, id2, id3...]
equiv_group[0] = [id] # always
for id1 in equiv_dict_ncs_copy.get(id, {}).keys():
ncs_copy = equiv_dict_ncs_copy[id][id1]
if not ncs_copy in equiv_group: equiv_group[ncs_copy] = []
equiv_group[ncs_copy].append(id1) # id1 is ncs_copy of id
all_single = True
equiv_group_as_list = []
total_grid_points = 0
missing_ncs_copies = []
present_ncs_copies = []
for ncs_copy in range(tracking_data.input_ncs_info.number_of_operators):
# goes 0 to ncs_copies-1 (including extra ones if present)
local_equiv_group = equiv_group.get(ncs_copy, [])
if local_equiv_group:
equiv_group_as_list.append(local_equiv_group)
present_ncs_copies.append(ncs_copy)
if ncs_copy > 0 and \
len(local_equiv_group)>1 and len(equiv_group.get(0, [])) == 1:
all_single = False
for id in equiv_group.get(ncs_copy, []):
total_grid_points+= region_volume_dict[id]
else:
missing_ncs_copies.append(ncs_copy)
equiv_group_as_list.sort()
if tracking_data.input_ncs_info.is_helical_symmetry:
# complete if we have original_number_of_operators worth
if (not params.segmentation.require_complete) or \
len(present_ncs_copies)>= \
tracking_data.input_ncs_info.original_number_of_operators:
complete = True
else:
complete = False
else:
if len(missing_ncs_copies) == 0:
complete = True
else:
complete = False
if complete and \
(not str(equiv_group_as_list) in ncs_equiv_groups_as_dict or
total_grid_points>ncs_equiv_groups_as_dict[str(equiv_group_as_list)]) \
and (all_single or (not split_if_possible)):
ncs_equiv_groups_as_dict[str(equiv_group_as_list)] = total_grid_points
ncs_equiv_groups_as_list.append([total_grid_points, equiv_group_as_list])
ncs_equiv_groups_as_list.sort()
ncs_equiv_groups_as_list.reverse()
# Now remove any group that duplicates a previous group
# 2015-11-07 allow a member to be in multiple groups though (for example
# one that spans several groups because it contains 2 region in other ncs
# copies)
# Make sure that if there are duplicates they are all in the leading
# positions of the list (these must be very big ones as they match 2
# regions in other ncs copies)
max_duplicates = tracking_data.input_ncs_info.number_of_operators-1 # not all duplicates
ncs_group_list = []
used_list = []
print("All equiv groups:", file = out)
used_regions = []
for total_grid_points, equiv_group_as_list in ncs_equiv_groups_as_list:
duplicate = False
n_dup = 0
for equiv_group in equiv_group_as_list:
for x in equiv_group:
if x in used_list:
n_dup+= 1
if n_dup>max_duplicates or n_dup >len(equiv_group_as_list)-1:
duplicate = True
if not duplicate and n_dup>0: # check carefully to make sure that all
# are leading entries
for ncs_group in ncs_group_list:
overlaps = get_overlap(ncs_group, equiv_group_as_list)
if not overlaps: continue
overlaps.sort()
expected_match = single_list(equiv_group_as_list)[:len(overlaps)]
expected_match.sort()
if overlaps!= expected_match: # not leading entries
duplicate = True
break
if not duplicate:
#print >>out, "NCS GROUP:", equiv_group_as_list, ":", total_grid_points
ncs_group_list.append(equiv_group_as_list)
for equiv_group in equiv_group_as_list:
for x in equiv_group:
if not x in used_list: used_list.append(x)
print("Total NCS groups: %d" %len(ncs_group_list), file = out)
# Make a dict that lists all ids that are in the same group as region x
shared_group_dict = {}
for ncs_group in ncs_group_list:
for group_list in ncs_group:
for id1 in group_list:
if not id1 in shared_group_dict: shared_group_dict[id1] = []
for other_group_list in ncs_group:
if other_group_list is group_list:continue
for other_id1 in other_group_list:
if not other_id1 in shared_group_dict [id1]:
shared_group_dict[id1].append(other_id1)
return ncs_group_list, shared_group_dict
def identify_ncs_regions(params,
sorted_by_volume = None,
co = None,
min_b = None,
max_b = None,
ncs_obj = None,
tracking_data = None,
out = sys.stdout):
# 1.choose top regions to work with
# 2.remove regions that are in more than one au of the NCS
# 3.identify groups of regions that are related by NCS
# Also note the centers and bounds of each region
# Choose number of top regions to consider
max_regions_to_consider = choose_max_regions_to_consider(params,
sorted_by_volume = sorted_by_volume,
ncs_copies = tracking_data.input_ncs_info.original_number_of_operators)
print("\nIdentifying NCS-related regions.Total regions to consider: %d" %(
max_regions_to_consider), file = out)
if max_regions_to_consider<1:
print("\nUnable to identify any NCS regions", file = out)
return None, tracking_data, None
# Go through all grid points; discard if not in top regions
# Renumber regions in order of decreasing size
load_saved_files = False # set to True to load results from previous run
dump_files = False # set to True to dump results and speed up next run
if not load_saved_files:
edited_mask, edited_volume_list, original_id_from_id = get_edited_mask(
sorted_by_volume = sorted_by_volume,
co = co,
max_regions_to_consider = max_regions_to_consider, out = out)
if dump_files:
from libtbx import easy_pickle
easy_pickle.dump("edited_mask.pkl",
[edited_mask, edited_volume_list, original_id_from_id])
else:
from libtbx import easy_pickle
[edited_mask, edited_volume_list, original_id_from_id
] = easy_pickle.load("edited_mask.pkl")
print("Loading edited_mask.pkl", file = out)
# edited_mask contains re-numbered region id's
# Identify duplicate and ncs relationships between regions
# duplicate_dict[id] = number of duplicates for that region
# equiv_dict[id][other_id] = number_of points other_id matches
# id through an ncs relationship
if not load_saved_files:
duplicate_dict, equiv_dict, equiv_dict_ncs_copy_dict, \
region_range_dict, region_centroid_dict, \
region_scattered_points_dict = \
run_get_duplicates_and_ncs(
ncs_obj = ncs_obj,
min_b = min_b,
max_b = max_b,
edited_mask = edited_mask,
original_id_from_id = original_id_from_id,
edited_volume_list = edited_volume_list,
max_regions_to_consider = max_regions_to_consider,
tracking_data = tracking_data,
out = out)
# Remove any bad regions
region_list, region_volume_dict, new_sorted_by_volume, \
bad_region_list = remove_bad_regions(
params = params,
duplicate_dict = duplicate_dict,
edited_volume_list = edited_volume_list,
out = out)
# Identify groups of regions that are ncs-related
# equiv_dict_ncs_copy[id][id1] = ncs_copy of id that corresponds to id1
equiv_dict_ncs_copy = get_ncs_equivalents(
region_list = region_list,
bad_region_list = bad_region_list,
region_scattered_points_dict = region_scattered_points_dict,
equiv_dict = equiv_dict,
ncs_copies = tracking_data.input_ncs_info.number_of_operators,
equiv_dict_ncs_copy_dict = equiv_dict_ncs_copy_dict,
out = out)
if dump_files:
from libtbx import easy_pickle
easy_pickle.dump("save.pkl", [duplicate_dict, equiv_dict, region_range_dict, region_centroid_dict, region_scattered_points_dict, region_list, region_volume_dict, new_sorted_by_volume, bad_region_list, equiv_dict_ncs_copy, tracking_data])
print("Dumped save.pkl", file = out)
else:
from libtbx import easy_pickle
[duplicate_dict, equiv_dict, region_range_dict, region_centroid_dict, region_scattered_points_dict, region_list, region_volume_dict, new_sorted_by_volume, bad_region_list, equiv_dict_ncs_copy, tracking_data] = easy_pickle.load("save.pkl")
print("Loaded save.pkl", file = out)
# Group together regions that are ncs-related. Also if one ncs
# copy has 2 or more regions linked together, group the other ones.
# each entry in ncs_group_list is a list of regions for each ncs_copy:
# e.g., [[8], [9, 23], [10, 25], [11, 27], [12, 24], [13, 22], [14, 26]]
# May contain elements that are in bad_region_list (to exclude later)
if not load_saved_files:
ncs_group_list, shared_group_dict = group_ncs_equivalents(params,
split_if_possible = params.segmentation.split_if_possible,
tracking_data = tracking_data,
region_volume_dict = region_volume_dict,
region_list = region_list,
equiv_dict_ncs_copy = equiv_dict_ncs_copy,
out = out)
if dump_files:
from libtbx import easy_pickle
easy_pickle.dump("group_list.pkl", [ncs_group_list, shared_group_dict])
print("Dumped to group_list.pkl", file = out)
else:
from libtbx import easy_pickle
[ncs_group_list, shared_group_dict] = easy_pickle.load("group_list.pkl")
print("Loaded group_list.pkl", file = out)
ncs_group_obj = ncs_group_object(
ncs_group_list = ncs_group_list,
shared_group_dict = shared_group_dict,
ncs_obj = ncs_obj,
crystal_symmetry = tracking_data.crystal_symmetry,
edited_mask = edited_mask,
origin_shift = tracking_data.origin_shift,
co = co,
min_b = min_b,
max_b = max_b,
equiv_dict = equiv_dict,
bad_region_list = bad_region_list,
original_id_from_id = original_id_from_id,
edited_volume_list = edited_volume_list,
region_range_dict = region_range_dict,
region_scattered_points_dict = region_scattered_points_dict,
region_centroid_dict = region_centroid_dict)
return ncs_group_obj, tracking_data, equiv_dict_ncs_copy
def get_center_list(regions,
region_centroid_dict = None):
center_list = []
for region in regions:
center_list.append(region_centroid_dict[region])
return center_list
def get_average_center(regions,
region_centroid_dict = None):
center_list = get_center_list(regions, region_centroid_dict = region_centroid_dict)
for region in regions:
center_list.append(region_centroid_dict[region])
average_center = deepcopy(center_list[0])
if len(center_list)>1:
for r in center_list[1:]:
for i in range(3):
average_center[i]+= r[i]
for i in range(3):
average_center[i]/= len(center_list)
return average_center
def get_dist(r, s):
dd = 0.
for i in range(3):
dd+= (r[i]-s[i])**2
return dd**0.5
def has_intersection(set1, set2):
set1a = single_list(set1)
set2a = single_list(set2)
for x in set1a:
if x in set2a:
return True
return False
def get_scattered_points_list(other_regions,
region_scattered_points_dict = None):
scattered_points_list = flex.vec3_double()
for x in other_regions:
scattered_points_list.extend(region_scattered_points_dict[x])
return scattered_points_list
def get_inter_region_dist_dict(ncs_group_obj = None,
selected_regions = None, target_scattered_points = None):
dd = {}
for i in range(len(selected_regions)):
id = selected_regions[i]
if not id in dd: dd[id] = {}
test_centers = ncs_group_obj.region_scattered_points_dict[id]
for j in range(i+1, len(selected_regions)):
id1 = selected_regions[j]
test_centers1 = ncs_group_obj.region_scattered_points_dict[id1]
dist = get_closest_dist(test_centers, test_centers1)
dd[id][id1] = dist
if not id1 in dd: dd[id1] = {}
dd[id1][id] = dist
return dd
def get_dist_to_first_dict(ncs_group_obj = None,
selected_regions = None,
inter_region_dist_dict = None,
target_scattered_points = None):
# Get distance to region 0 ( or to target_scattered_points if supplied)
dist_to_first_dict = {}
if target_scattered_points:
start_region = 0
for x in selected_regions:
dist_to_first_dict[x] = get_closest_dist(
ncs_group_obj.region_scattered_points_dict[x],
target_scattered_points)
else:
start_region = 1
x0 = selected_regions[0]
dist_to_first_dict[x0] = 0
for x in selected_regions[1:]:
dist_to_first_dict[x] = inter_region_dist_dict[x0][x]
changing = True
while changing:
changing = False
for x in selected_regions[start_region:]:
for y in selected_regions[start_region:]:
if x == y: continue
if dist_to_first_dict[y]<dist_to_first_dict[x] and \
inter_region_dist_dict[x][y]<dist_to_first_dict[x]:
dist_to_first_dict[x] = max(
dist_to_first_dict[y], inter_region_dist_dict[x][y])
changing = True
return dist_to_first_dict
def radius_of_gyration_of_vector(xyz):
return (xyz-xyz.mean()).rms_length()
def get_radius_of_gyration(ncs_group_obj = None,
selected_regions = None):
# return radius of gyration of points in selected regions
centers = flex.vec3_double()
for s in selected_regions:
centers.append(ncs_group_obj.region_centroid_dict[s])
centers = centers-centers.mean()
return centers.rms_length()
def get_closest_neighbor_rms(ncs_group_obj = None, selected_regions = None,
target_scattered_points = None, verbose = False, out = sys.stdout):
# return rms closest distance of each region center to lowest_numbered region,
# allowing sequential tracking taking max of inter-region distances
# XXX can't we save some of this for next time?
inter_region_dist_dict = get_inter_region_dist_dict(ncs_group_obj = ncs_group_obj,
selected_regions = selected_regions)
if verbose:
print("Inter-region distance dict:", file = out)
keys = list(inter_region_dist_dict.keys())
keys.sort()
for key in keys:
for key2 in inter_region_dist_dict[key].keys():
print("%s %s : %.1f " %(key, key2, inter_region_dist_dict[key][key2]), file = out)
dist_to_first_dict = get_dist_to_first_dict(ncs_group_obj = ncs_group_obj,
selected_regions = selected_regions,
inter_region_dist_dict = inter_region_dist_dict,
target_scattered_points = target_scattered_points)
if verbose:
print("Distance-to-first dict:", file = out)
keys = list(dist_to_first_dict.keys())
keys.sort()
for key in keys: print("\n %s: %.1f " %(key, dist_to_first_dict[key]), file = out)
if target_scattered_points:
start_region = 0 # we are getting dist to target_scattered_points
else:
start_region = 1 # we are getting dist to region 0
rms = 0.
rms_n = 0.
for x in selected_regions[start_region:]:
dist = dist_to_first_dict[x]
rms+= dist**2
rms_n+= 1.
if rms_n>1:
rms/= rms_n
rms = rms**0.5
return rms
def get_rms(selected_regions = None,
region_centroid_dict = None):
# return rms distance of each region center from average of all others
rms = 0.
rms_n = 0.
for x in selected_regions:
other_regions = remove_one_item(selected_regions, item_to_remove = x)
current_center = get_average_center(other_regions,
region_centroid_dict = region_centroid_dict)
test_center = region_centroid_dict[x]
dist = get_dist(current_center, test_center)
rms+= dist**2
rms_n+= 1.
if rms_n>1:
rms/= rms_n
return rms**0.5
def single_list(list_of_lists):
single = []
for x in list_of_lists:
if type(x) == type([1, 2, 3]):
single+= single_list(x)
else:
single.append(x)
return single
def get_closest_dist(test_center, target_centers):
# make sure we have target_centers = vec3_double and not a list,
# and vec3_double or tuple for test_center
if type(test_center) == type([1, 2, 3]):
test_center = flex.vec3_double(test_center)
if type(target_centers) == type([1, 2, 3]):
target_centers = flex.vec3_double(target_centers)
if test_center.size()<1 or target_centers.size()<1: return None
closest_dist = test_center.min_distance_between_any_pair(target_centers)
return closest_dist
def region_lists_have_ncs_overlap(set1, set2, ncs_group_obj = None, cutoff = 0):
for id1 in set1:
for id2 in set2:
if id2 in ncs_group_obj.shared_group_dict.get(id1, []):
return True
return False
def get_effective_radius(ncs_group_obj = None,
target_scattered_points = None,
weight_rad_gyr = None,
selected_regions = None):
sr = deepcopy(selected_regions)
sr.sort()
rad_gyr = get_radius_of_gyration(ncs_group_obj = ncs_group_obj,
selected_regions = sr)
rms = get_closest_neighbor_rms(ncs_group_obj = ncs_group_obj,
target_scattered_points = target_scattered_points,
selected_regions = sr)
max_cell_dim = 0.
if ncs_group_obj.max_cell_dim and ncs_group_obj.max_cell_dim > 1.0:
wrg = weight_rad_gyr*(300/ncs_group_obj.max_cell_dim) # have a consistent scale
else:
wrg = weight_rad_gyr
effective_radius = (rms+wrg*rad_gyr)/(1.+wrg)
return effective_radius
def add_neighbors(params,
selected_regions = None,
max_length_of_group = None,
target_scattered_points = None,
tracking_data = None,
equiv_dict_ncs_copy = None,
ncs_group_obj = None, out = sys.stdout):
# Add neighboring regions on to selected_regions.
# Same rules as select_from_seed
selected_regions = single_list(deepcopy(selected_regions))
added_regions = []
start_dist = get_effective_radius(ncs_group_obj = ncs_group_obj,
target_scattered_points = target_scattered_points,
weight_rad_gyr = params.segmentation.weight_rad_gyr,
selected_regions = selected_regions)
delta_dist = params.segmentation.add_neighbors_dist
max_dist = start_dist+delta_dist
starting_selected_regions = deepcopy(selected_regions)
for x in selected_regions: # delete, add in alternatives one at a time and
# keep all the ok ones
ncs_groups_to_use = get_ncs_related_regions(
ncs_group_obj = ncs_group_obj,
selected_regions = [x],
include_self = False)
for x in ncs_groups_to_use: # try adding from each group
if x in selected_regions+added_regions:
continue
ncs_group = [[x]]
current_scattered_points_list = get_scattered_points_list(selected_regions,
region_scattered_points_dict = ncs_group_obj.region_scattered_points_dict)
for ncs_set in ncs_group: # pick the best ncs_set from this group
if has_intersection(ncs_group_obj.bad_region_list, ncs_set):
continue
dist = get_effective_radius(ncs_group_obj = ncs_group_obj,
target_scattered_points = target_scattered_points,
weight_rad_gyr = params.segmentation.weight_rad_gyr,
selected_regions = selected_regions+ncs_set)
if dist <= max_dist:
added_regions.append(x)
selected_regions = selected_regions+added_regions
dist = get_effective_radius(ncs_group_obj = ncs_group_obj,
target_scattered_points = target_scattered_points,
weight_rad_gyr = params.segmentation.weight_rad_gyr,
selected_regions = selected_regions)
# Identify all the NCS operators required to map final to starting
# equiv_dict_ncs_copy[id][id1] = ncs_copy of id that corresponds to id1
ncs_group = ncs_group_obj.ncs_obj.ncs_groups()[0]
identity_op = ncs_group.identity_op_id()
ncs_ops_used = [identity_op]
for id in selected_regions:
related_regions = get_ncs_related_regions(
ncs_group_obj = ncs_group_obj,
selected_regions = [id],
include_self = False)
for id1 in selected_regions:
if not id1 in related_regions: continue
ncs_copy1 = equiv_dict_ncs_copy.get(id, {}).get(id1, None)
ncs_copy2 = equiv_dict_ncs_copy.get(id1, {}).get(id, None)
for a in [ncs_copy1, ncs_copy2]:
if a is not None and not a in ncs_ops_used:
ncs_ops_used.append(a)
selected_regions.sort()
ncs_ops_used.sort()
for x in selected_regions:
print("GROUP ", x, ":", ncs_group_obj.shared_group_dict.get(x, []), file = out)
return selected_regions, dist, ncs_ops_used
def select_from_seed(params,
starting_regions,
target_scattered_points = None,
max_length_of_group = None,
ncs_groups_to_use = None,
tracking_data = None,
ncs_group_obj = None):
selected_regions = single_list(deepcopy(starting_regions))
# do not allow any region in ncs_group_obj.bad_region_list
# also do not allow any region that is in an ncs-related group to any region
# already used. Use ncs_group_obj.equiv_dict to identify these.
if not ncs_groups_to_use:
ncs_groups_to_use = ncs_group_obj.ncs_group_list
for ncs_group in ncs_groups_to_use: # try adding from each group
if max_length_of_group is not None and \
len(selected_regions)>= max_length_of_group:
break
best_ncs_set = None
best_dist = None
if has_intersection(ncs_group, selected_regions):
continue
current_scattered_points_list = get_scattered_points_list(selected_regions,
region_scattered_points_dict = ncs_group_obj.region_scattered_points_dict)
if target_scattered_points:
current_scattered_points_list.extend(target_scattered_points)
for ncs_set in ncs_group: # pick the best ncs_set from this group
if has_intersection(ncs_group_obj.bad_region_list, ncs_set): continue
# does any ncs copy of anything in selected_regions actually overlap
# with any member of ncs_set... might be efficient to delete the entire
# ncs_group if any ncs_set overlaps, but could lose some.
if region_lists_have_ncs_overlap(ncs_set, selected_regions,
ncs_group_obj = ncs_group_obj):
continue
dist = get_effective_radius(ncs_group_obj = ncs_group_obj,
target_scattered_points = target_scattered_points,
weight_rad_gyr = params.segmentation.weight_rad_gyr,
selected_regions = selected_regions+ncs_set)
if best_dist is None or dist<best_dist:
best_dist = dist
best_ncs_set = ncs_set
if best_ncs_set is not None:
selected_regions+= best_ncs_set
dist = get_effective_radius(ncs_group_obj = ncs_group_obj,
target_scattered_points = target_scattered_points,
weight_rad_gyr = params.segmentation.weight_rad_gyr,
selected_regions = selected_regions)
return selected_regions, dist
def remove_one_item(input_list, item_to_remove = None):
new_list = []
for item in input_list:
if item != item_to_remove:
new_list.append(item)
return new_list
def get_ncs_related_regions_specific_list(
ncs_group_obj = None,
target_regions = None,
include_self = False):
all_regions = []
for target_region in target_regions:
all_regions+= get_ncs_related_regions_specific_target(
ncs_group_obj = ncs_group_obj,
target_region = target_region,
other_regions = remove_one_item(
target_regions, item_to_remove = target_region),
include_self = include_self)
return all_regions
def get_ncs_related_regions_specific_target(
ncs_group_obj = None,
target_region = None,
other_regions = None,
include_self = False):
# similar to get_ncs_related_regions, but find just one ncs group that
# contains x but does not contain any member of other_regions
for ncs_group in ncs_group_obj.ncs_group_list: # might this be the group
ids_in_group = single_list(ncs_group)
if not target_region in ids_in_group: continue # does not contain target
contains_others = False
for other_id in other_regions:
if other_id in ids_in_group:
contains_other = True
break# contains other members
if not contains_others:
# this is the group
if include_self:
return ids_in_group
else:
return remove_one_item(ids_in_group, item_to_remove = target_region)
return []
def get_ncs_related_regions(
ncs_group_obj = None,
selected_regions = None,
include_self = False):
# returns a simple list of region ids
# if include_self then include selected regions and all ncs-related
# otherwise do not include selected regions or anything that might
# overlap with them
ncs_related_regions = []
if include_self:
for id in selected_regions:
if not id in ncs_related_regions:
ncs_related_regions.append(id)
for ncs_group in ncs_group_obj.ncs_group_list:
ids_in_group = single_list(ncs_group)
if id in ids_in_group: # this group contains this selected id
for i in ids_in_group:
if not i in ncs_related_regions:
ncs_related_regions.append(i)
else:
for id in selected_regions:
found = False
for ncs_group in ncs_group_obj.ncs_group_list:
ids_in_group = single_list(ncs_group)
if id in ids_in_group: # this group contains this selected id
found = True
for i in ids_in_group:
if (not i == id) and (not i in selected_regions) and \
(not i in ncs_related_regions):
ncs_related_regions.append(i)
break # don't look at any more ncs groups
return ncs_related_regions
def all_elements_are_length_one(list_of_elements):
for x in list_of_elements:
if type(x) == type([1, 2, 3]):
if len(x)!= 1: return False
return True
def as_list_of_lists(ll):
new_list = []
for x in ll:
new_list.append([x])
return new_list
def select_regions_in_au(params,
ncs_group_obj = None,
target_scattered_points = None,
unique_expected_regions = None,
equiv_dict_ncs_copy = None,
tracking_data = None,
out = sys.stdout):
# Choose one region or set of regions from each ncs_group
# up to about unique_expected_regions
# Optimize closeness of centers...
# If target scattered_points is supplied, include them as allowed target
if not ncs_group_obj.ncs_group_list:
return ncs_group_obj, []
max_length_of_group = max(1, unique_expected_regions*
params.segmentation.max_per_au_ratio)
print("Maximum length of group: %d" %(max_length_of_group), file = out)
if all_elements_are_length_one(ncs_group_obj.ncs_group_list):
# This is where there is no ncs. Basically skipping everything
best_selected_regions = single_list(ncs_group_obj.ncs_group_list)
best_rms = None
else:
#-------------- Find initial set of regions --------------------
# Seed with members of the first NCS group or with the target points
# and find the member of each NCS group that is closest
if target_scattered_points:
starting_regions = [None]
else:
starting_regions = ncs_group_obj.ncs_group_list[0]
best_selected_regions = None
best_rms = None
ok_seeds_examined = 0
for starting_region in starting_regions: # NOTE starting_region is a list
if not starting_region and not target_scattered_points:continue
if ok_seeds_examined >= params.segmentation.seeds_to_try:
break # don't bother to keep trying
if starting_region and starting_region in ncs_group_obj.bad_region_list:
continue # do not use
if starting_region: # NOTE: starting_region is a list itself
starting_region_list = [starting_region]
else:
starting_region_list = []
selected_regions, rms = select_from_seed(params,
starting_region_list,
target_scattered_points = target_scattered_points,
max_length_of_group = max_length_of_group,
tracking_data = tracking_data,
ncs_group_obj = ncs_group_obj)
if not selected_regions:
continue
ok_seeds_examined+= 1
if best_rms is None or rms<best_rms:
best_rms = rms
best_selected_regions = selected_regions
print("New best selected: rms: %7.1f: %s " %(
rms, str(selected_regions)), file = out)
if best_rms is not None:
print("Best selected so far: rms: %7.1f: %s " %(
best_rms, str(best_selected_regions)), file = out)
if not best_selected_regions:
print("\nNo NCS regions found ...", file = out)
return ncs_group_obj, []
# Now we have a first version of best_rms, best_selected_regions
#-------------- END Find initial set of regions --------------------
#-------------- Optimize choice of regions -------------------------
max_tries = 10
improving = True
itry = 0
while improving and itry<max_tries:
itry+= 1
improving = False
previous_selected_regions = deepcopy(best_selected_regions)
previous_selected_regions.sort()
print("\nTry %d for optimizing regions" %(itry), file = out)
# Now see if replacing any regions with alternatives would improve it
for x in previous_selected_regions:
starting_regions = remove_one_item(previous_selected_regions,
item_to_remove = x)
# identify ncs_related regions to x, but not to other members of
# selected_regions
ncs_related_regions = get_ncs_related_regions_specific_list(
ncs_group_obj = ncs_group_obj,
include_self = True,
target_regions = [x])
if not ncs_related_regions: continue
ncs_groups_to_use = [as_list_of_lists(ncs_related_regions)]
new_selected_regions, rms = select_from_seed(params, starting_regions,
target_scattered_points = target_scattered_points,
max_length_of_group = max_length_of_group,
tracking_data = tracking_data,
ncs_groups_to_use = ncs_groups_to_use,
ncs_group_obj = ncs_group_obj)
if not new_selected_regions: continue
if best_rms is None or rms<best_rms:
best_selected_regions = new_selected_regions
best_selected_regions.sort()
best_rms = rms
improving = True
print("Optimized best selected: rms: %7.1f: %s " %(
best_rms, str(best_selected_regions)), file = out)
# Done with this try
selected_regions = best_selected_regions
selected_regions.sort()
available_selected_regions = len(selected_regions)
print("\nAvailable selected regions: %s ..." %(available_selected_regions), file = out)
if tracking_data:
tracking_data.available_selected_regions = available_selected_regions
if params.map_modification.regions_to_keep is not None:
if params.map_modification.regions_to_keep <= 0:
# keep just region abs(regions_to_keep)
ii = min(len(selected_regions)-1, abs(params.map_modification.regions_to_keep))
selected_regions = selected_regions[ii:ii+1]
else: # usual
selected_regions = selected_regions[:params.map_modification.regions_to_keep]
rms = get_closest_neighbor_rms(ncs_group_obj = ncs_group_obj,
selected_regions = selected_regions, verbose = False, out = out)
if params.segmentation.add_neighbors and \
ncs_group_obj.ncs_obj.max_operators()>1:
print("\nAdding neighbor groups...", file = out)
selected_regions, rms, ncs_ops_used = add_neighbors(params,
selected_regions = selected_regions,
max_length_of_group = max_length_of_group,
target_scattered_points = target_scattered_points,
equiv_dict_ncs_copy = equiv_dict_ncs_copy,
tracking_data = tracking_data,
ncs_group_obj = ncs_group_obj, out = out)
else:
ncs_ops_used = None
print("\nFinal selected regions with rms of %6.2f: " %(rms), end = ' ', file = out)
for x in selected_regions:
print(x, end = ' ', file = out)
if ncs_ops_used:
print("\nNCS operators used: ", end = ' ', file = out)
for op in ncs_ops_used: print(op, end = ' ', file = out)
print(file = out)
# Save an ncs object containing just the ncs_ops_used
ncs_group_obj.set_ncs_ops_used(ncs_ops_used)
# Identify scattered points for all selected regions:
scattered_points = get_scattered_points_list(selected_regions,
region_scattered_points_dict = ncs_group_obj.region_scattered_points_dict)
# Identify ncs-related regions for all the selected regions
self_and_ncs_related_regions = get_ncs_related_regions(
ncs_group_obj = ncs_group_obj,
selected_regions = selected_regions,
include_self = True)
ncs_related_regions = get_ncs_related_regions(
ncs_group_obj = ncs_group_obj,
selected_regions = selected_regions,
include_self = False)
print("NCS-related regions (not used): %d " %(len(ncs_related_regions)), file = out)
ncs_group_obj.set_selected_regions(selected_regions)
ncs_group_obj.set_self_and_ncs_related_regions(self_and_ncs_related_regions)
ncs_group_obj.set_ncs_related_regions(ncs_related_regions)
return ncs_group_obj, scattered_points
def get_bool_mask_as_int(ncs_group_obj = None, mask_as_int = None, mask_as_bool = None):
if mask_as_int:
mask_as_int = mask_as_int.deep_copy()
else:
mask_as_int = ncs_group_obj.edited_mask.deep_copy()
s = (mask_as_bool == True)
mask_as_int = mask_as_int.set_selected(s, 1)
mask_as_int = mask_as_int.set_selected(~s, 0)
return mask_as_int
def get_bool_mask_of_regions(ncs_group_obj = None, region_list = None,
expand_size = None):
s = (ncs_group_obj.edited_mask == -1)
if region_list is None: region_list = []
for id in region_list:
if not expand_size:
s |= (ncs_group_obj.edited_mask == id) # just take this region
else: # expand the size of the regions...use expand_mask which operates
# on the original id numbers and uses the co
bool_region_mask = ncs_group_obj.co.expand_mask(
id_to_expand = ncs_group_obj.original_id_from_id[id],
expand_size = expand_size)
s |= (bool_region_mask == True)
bool_mask = ncs_group_obj.co.expand_mask(id_to_expand = 1, expand_size = 1) # just to get bool mask
bool_mask = bool_mask.set_selected(s, True)
bool_mask = bool_mask.set_selected(~s, False)
return bool_mask
def create_remaining_mask_and_map(params,
ncs_group_obj = None,
map_data = None,
crystal_symmetry = None,
out = sys.stdout):
if not ncs_group_obj.selected_regions:
print("No regions selected", file = out)
return map_data
# create new remaining_map containing everything except the part that
# has been interpreted (and all points in interpreted NCS-related copies)
bool_all_used = get_bool_mask_of_regions(ncs_group_obj = ncs_group_obj,
region_list = ncs_group_obj.selected_regions+
ncs_group_obj.self_and_ncs_related_regions,
expand_size = params.segmentation.expand_size)
map_data_remaining = map_data.deep_copy()
s = (bool_all_used == True)
map_data_remaining = map_data_remaining.set_selected(s,
params.segmentation.value_outside_mask)
return map_data_remaining
def get_lower(lower_bounds, lower):
new_lower = []
for i in range(3):
if lower_bounds[i] is None:
new_lower.append(lower[i])
elif lower[i] is None:
new_lower.append(lower_bounds[i])
else:
new_lower.append(min(lower_bounds[i], lower[i]))
return new_lower
def get_upper(upper_bounds, upper):
new_upper = []
for i in range(3):
if upper_bounds[i] is None:
new_upper.append(upper[i])
elif upper[i] is None:
new_upper.append(upper_bounds[i])
else:
new_upper.append(max(upper_bounds[i], upper[i]))
return new_upper
def get_bounds(ncs_group_obj = None, id = None):
orig_id = ncs_group_obj.original_id_from_id[id]
lower = ncs_group_obj.min_b[orig_id]
upper = ncs_group_obj.max_b[orig_id]
return lower, upper
def get_selected_and_related_regions(params,
ncs_group_obj = None):
# Identify all points in the targeted regions
bool_selected_regions = get_bool_mask_of_regions(ncs_group_obj = ncs_group_obj,
region_list = ncs_group_obj.selected_regions,
expand_size = params.segmentation.expand_size+\
params.segmentation.mask_additional_expand_size)
# and all points in NCS-related copies (to be excluded)
if params.segmentation.exclude_points_in_ncs_copies and (
not params.segmentation.add_neighbors):
bool_ncs_related_mask = get_bool_mask_of_regions(ncs_group_obj = ncs_group_obj,
region_list = ncs_group_obj.ncs_related_regions)
# NOTE: using ncs_related_regions here NOT self_and_ncs_related_regions
else:
bool_ncs_related_mask = None
lower_bounds = [None, None, None]
upper_bounds = [None, None, None]
if ncs_group_obj.selected_regions:
for id in ncs_group_obj.selected_regions:
lower, upper = get_bounds(
ncs_group_obj = ncs_group_obj, id = id)
lower_bounds = get_lower(lower_bounds, lower)
upper_bounds = get_upper(upper_bounds, upper)
return bool_selected_regions, bool_ncs_related_mask, lower_bounds, upper_bounds
def adjust_bounds(params,
lower_bounds, upper_bounds, map_data = None, out = sys.stdout):
# range is lower_bounds to upper_bounds
lower_bounds = list(lower_bounds)
upper_bounds = list(upper_bounds)
if params is None or params.output_files.box_buffer is None:
box_buffer = 0
else:
box_buffer = int(0.5+params.output_files.box_buffer)
for i in range(3):
if lower_bounds[i] is None: lower_bounds[i] = 0
if upper_bounds[i] is None: upper_bounds[i] = 0
lower_bounds[i]-= box_buffer
lower_bounds[i] = max(0, lower_bounds[i])
upper_bounds[i]+= box_buffer
upper_bounds[i] = min(map_data.all()[i]-1, upper_bounds[i])
"""
print >>out, "\nRange: X:(%6d, %6d) Y:(%6d, %6d) Z:(%6d, %6d)" %(
lower_bounds[0], upper_bounds[0],
lower_bounds[1], upper_bounds[1],
lower_bounds[2], upper_bounds[2])
"""
return lower_bounds, upper_bounds
def write_region_maps(params,
ncs_group_obj = None,
map_data = None,
tracking_data = None,
remainder_ncs_group_obj = None,
regions_to_skip = None,
out = sys.stdout):
remainder_regions_written = []
map_files_written = []
if not ncs_group_obj:
return map_files_written, remainder_regions_written
if not ncs_group_obj.selected_regions:
return map_files_written, remainder_regions_written
for id in ncs_group_obj.selected_regions:
if regions_to_skip and id in regions_to_skip:
print("Skipping remainder region %d (already written out)" %(id), file = out)
continue
print("Writing region %d" %(id), end = ' ', file = out)
# dummy atoms representing this region
sites = ncs_group_obj.region_scattered_points_dict[id]
bool_region_mask = ncs_group_obj.co.expand_mask(
id_to_expand = ncs_group_obj.original_id_from_id[id],
expand_size = params.segmentation.expand_size)
s = (bool_region_mask == True)
lower_bounds, upper_bounds = get_bounds(ncs_group_obj = ncs_group_obj, id = id)
if remainder_ncs_group_obj:
for remainder_id in remainder_ncs_group_obj.remainder_id_dict.keys():
if remainder_ncs_group_obj.remainder_id_dict[remainder_id] == id:
remainder_regions_written.append(remainder_id)
sites.extend(
remainder_ncs_group_obj.region_scattered_points_dict[remainder_id])
print("(including remainder region %d)" %(remainder_id), end = ' ', file = out)
remainder_bool_region_mask = remainder_ncs_group_obj.co.expand_mask(
id_to_expand = remainder_ncs_group_obj.original_id_from_id[remainder_id],
expand_size = params.segmentation.expand_size)
s|= (remainder_bool_region_mask == True)
lower, upper = get_bounds(
ncs_group_obj = remainder_ncs_group_obj, id = remainder_id)
lower_bounds = get_lower(lower_bounds, lower)
upper_bounds = get_upper(upper_bounds, upper)
region_mask = map_data.deep_copy()
region_mask = region_mask.set_selected(s, 1)
region_mask = region_mask.set_selected(~s, 0)
local_map_data = map_data.deep_copy()
local_map_data = local_map_data * region_mask.as_double()
# Now cut down the map to the size we want
lower_bounds, upper_bounds = adjust_bounds(params, lower_bounds, upper_bounds,
map_data = map_data, out = out)
box_map, box_crystal_symmetry, \
dummy_smoothed_box_mask_data, dummy_original_box_map_data = cut_out_map(
map_data = local_map_data, \
crystal_symmetry = tracking_data.crystal_symmetry,
min_point = lower_bounds, max_point = upper_bounds, out = out)
if remainder_ncs_group_obj:
text = ""
else:
text = "_r"
base_file = 'map%s_%d.ccp4' %(text, id)
base_pdb_file = 'atoms%s_%d.pdb' %(text, id)
if tracking_data.params.output_files.output_directory:
if not os.path.isdir(tracking_data.params.output_files.output_directory):
os.mkdir(tracking_data.params.output_files.output_directory)
file_name = os.path.join(tracking_data.params.output_files.output_directory, base_file)
pdb_file_name = os.path.join(
tracking_data.params.output_files.output_directory, base_pdb_file)
else:
file_name = base_file
pdb_file_name = base_pdb_file
write_ccp4_map(box_crystal_symmetry, file_name, box_map)
print("to %s" %(file_name), file = out)
map_files_written.append(file_name)
tracking_data.add_output_region_map_info(
file_name = file_name,
crystal_symmetry = box_crystal_symmetry,
origin = box_map.origin(),
all = box_map.all(),
map_id = base_file)
print("Atoms representation written to %s" %(pdb_file_name), file = out)
write_atoms(tracking_data = tracking_data, sites = sites, file_name = pdb_file_name,
out = out)
tracking_data.add_output_region_pdb_info(
file_name = pdb_file_name)
return map_files_written, remainder_regions_written
def get_bounds_from_sites(sites_cart = None, map_data = None,
unit_cell = None):
lower_bounds = [None, None, None]
upper_bounds = [None, None, None]
sites_frac = unit_cell.fractionalize(sites_cart)
nx, ny, nz = map_data.all()
for x_frac in sites_frac:
x = [
int(0.5+nx*x_frac[0]),
int(0.5+ny*x_frac[1]),
int(0.5+nz*x_frac[2])]
if lower_bounds[0] is None or x[0]<lower_bounds[0]: lower_bounds[0] = x[0]
if lower_bounds[1] is None or x[1]<lower_bounds[1]: lower_bounds[1] = x[1]
if lower_bounds[2] is None or x[2]<lower_bounds[2]: lower_bounds[2] = x[2]
if upper_bounds[0] is None or x[0]>upper_bounds[0]: upper_bounds[0] = x[0]
if upper_bounds[1] is None or x[1]>upper_bounds[1]: upper_bounds[1] = x[1]
if upper_bounds[2] is None or x[2]>upper_bounds[2]: upper_bounds[2] = x[2]
return lower_bounds, upper_bounds
def write_output_files(params,
tracking_data = None,
map_data = None,
half_map_data_list = None,
ncs_group_obj = None,
remainder_ncs_group_obj = None,
pdb_hierarchy = None,
removed_ncs = None,
out = sys.stdout):
half_map_data_list_au = []
if not half_map_data_list: half_map_data_list = []
if params.output_files.au_output_file_stem:
au_mask_output_file = os.path.join(tracking_data.params.output_files.output_directory, params.output_files.au_output_file_stem+"_mask.ccp4")
au_map_output_file = os.path.join(tracking_data.params.output_files.output_directory, params.output_files.au_output_file_stem+"_map.ccp4")
au_atom_output_file = os.path.join(tracking_data.params.output_files.output_directory, params.output_files.au_output_file_stem+"_atoms.pdb")
else:
au_mask_output_file = None
au_map_output_file = None
au_atom_output_file = None
# Write out pdb file with dummy atoms for the AU to au_atom_output_file
if au_atom_output_file and params.output_files.write_output_maps:
sites = flex.vec3_double()
for id in ncs_group_obj.selected_regions:
sites.extend(ncs_group_obj.region_scattered_points_dict[id])
if remainder_ncs_group_obj:
for id in remainder_ncs_group_obj.selected_regions:
sites.extend(remainder_ncs_group_obj.region_scattered_points_dict[id])
write_atoms(tracking_data = tracking_data, sites = sites,
file_name = au_atom_output_file, out = out)
tracking_data.set_output_ncs_au_pdb_info(file_name = au_atom_output_file)
# Write out mask and map representing one NCS copy and none of
# other NCS copies. Expand the mask to include neighboring points (but
# not those explicitly in other NCS copies
if params.map_modification.soft_mask and params.control.save_box_map_ncs_au:
mask_expand_size = estimate_expand_size(
crystal_symmetry = tracking_data.crystal_symmetry,
map_data = map_data,
expand_target = tracking_data.params.segmentation.mask_expand_ratio*\
tracking_data.params.crystal_info.resolution,
out = out)
params.segmentation.mask_additional_expand_size = max(mask_expand_size,
params.segmentation.mask_additional_expand_size, )
bool_selected_regions, bool_ncs_related_mask, lower_bounds, upper_bounds = \
get_selected_and_related_regions(
params, ncs_group_obj = ncs_group_obj)
if bool_ncs_related_mask is not None:
s_ncs_related = (bool_ncs_related_mask == True)
else:
s_ncs_related = None
# Add in remainder regions if present
if remainder_ncs_group_obj:
bool_remainder_selected_regions, bool_remainder_ncs_related_mask, \
remainder_lower_bounds, remainder_upper_bounds = \
get_selected_and_related_regions(
params, ncs_group_obj = remainder_ncs_group_obj)
lower_bounds = get_lower(lower_bounds, remainder_lower_bounds)
upper_bounds = get_upper(upper_bounds, remainder_upper_bounds)
s_remainder_au = (bool_remainder_selected_regions == True)
bool_selected_regions = bool_selected_regions.set_selected(
s_remainder_au, True)
if s_ncs_related is not None and \
bool_remainder_ncs_related_mask is not None:
s_ncs_related |= (bool_remainder_ncs_related_mask == True)
# Now create NCS mask by eliminating all points in target (expanded) in
# NCS-related copies
if s_ncs_related is not None:
bool_selected_regions = bool_selected_regions.set_selected(
s_ncs_related, False)
if tracking_data.params.map_modification.regions_to_keep is None:
# Identify full (possibly expanded) ncs au starting with what we have
au_mask = get_one_au(tracking_data = tracking_data,
starting_mask = bool_selected_regions,
removed_ncs = removed_ncs,
ncs_obj = ncs_group_obj.ncs_obj, map_data = map_data, out = out)
print("\nExpanding NCS AU if necessary...", file = out)
print("Size of AU mask: %s Current size of AU: %s" %(
au_mask.count(True), bool_selected_regions.count(True)), file = out)
bool_selected_regions = (bool_selected_regions | au_mask)
print("New size of AU mask: %s" %(bool_selected_regions.count(True)), file = out)
sites_cart = get_marked_points_cart(mask_data = bool_selected_regions,
unit_cell = ncs_group_obj.crystal_symmetry.unit_cell(),
every_nth_point = tracking_data.params.segmentation.grid_spacing_for_au,
boundary_radius = tracking_data.params.segmentation.radius)
sites_lower_bounds, sites_upper_bounds = get_bounds_from_sites(
unit_cell = ncs_group_obj.crystal_symmetry.unit_cell(),
sites_cart = sites_cart, map_data = map_data)
print("Original bounds: %5s %5s %5s to %5s %5s %5s" %(
tuple(lower_bounds+upper_bounds)), file = out)
lower_bounds = get_lower(lower_bounds, sites_lower_bounds)
upper_bounds = get_upper(upper_bounds, sites_upper_bounds)
print("Updated bounds: %5s %5s %5s to %5s %5s %5s" %(
tuple(lower_bounds+upper_bounds)), file = out)
lower_bounds, upper_bounds = adjust_bounds(params, lower_bounds, upper_bounds,
map_data = map_data, out = out)
box_ncs_au = params.segmentation.box_ncs_au
if (not box_ncs_au):
print("Using entire input map (box_ncs_au = False)", file = out)
lower_bounds = map_data.origin()
upper_bounds = tuple(matrix.col(map_data.all())+
matrix.col(map_data.origin())-matrix.col((1, 1, 1)))
print("\nMaking two types of maps for AU of NCS mask and map with "+\
"buffer of %d grid units \nin each direction around AU" %(
params.output_files.box_buffer), file = out)
if params.output_files.write_output_maps:
print("Both types of maps have the same origin and overlay on %s" %(
os.path.join(tracking_data.params.output_files.output_directory,
params.output_files.shifted_map_file)), file = out)
print("\nThe standard maps (%s, %s) have the \noriginal cell dimensions." %(
os.path.join(tracking_data.params.output_files.output_directory, au_mask_output_file),
os.path.join(tracking_data.params.output_files.output_directory, au_map_output_file))+\
"\nThese maps show only the unique (NCS AU) part of the map.", file = out)
print("\nThe cut out box_maps (%s, %s) have \nsmaller cell dimensions." %(
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_mask_file),
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_map_file), ) +\
"\nThese maps also show only the unique part of the map and have this"+\
"\nunique part cut out.\n", file = out)
# Write out NCS AU with shifted origin but initial crystal_symmetry
# Mask
mask_data_ncs_au = get_bool_mask_as_int(
ncs_group_obj = ncs_group_obj, mask_as_bool = bool_selected_regions)
if au_mask_output_file and params.output_files.write_output_maps:
# Write out the mask (as int)
write_ccp4_map(tracking_data.crystal_symmetry,
au_mask_output_file, mask_data_ncs_au)
print("Output NCS AU mask: %s" %(au_mask_output_file), file = out)
tracking_data.set_output_ncs_au_mask_info(
file_name = au_mask_output_file,
crystal_symmetry = tracking_data.crystal_symmetry,
origin = mask_data_ncs_au.origin(),
all = mask_data_ncs_au.all())
# Map
map_data_ncs_au = map_data.deep_copy()
s = (bool_selected_regions == True)
mask = map_data.deep_copy()
mask = mask.set_selected(s, 1)
mask = mask.set_selected(~s, 0)
if params.map_modification.soft_mask:
# buffer and smooth the mask
map_data_ncs_au, smoothed_mask_data = apply_soft_mask(map_data = map_data_ncs_au,
mask_data = mask.as_double(),
rad_smooth = tracking_data.params.crystal_info.resolution,
crystal_symmetry = tracking_data.crystal_symmetry,
out = out)
half_map_data_list_au = []
for hm in half_map_data_list: # apply mask to half maps
hm_data_ncs_au, hm_smoothed_mask_data = apply_soft_mask(
map_data = hm.deep_copy().as_double(),
mask_data = mask.as_double(),
rad_smooth = tracking_data.params.crystal_info.resolution,
crystal_symmetry = tracking_data.crystal_symmetry,
out = out)
half_map_data_list_au.append(hm_data_ncs_au)
elif (box_ncs_au): # usual. If box_ncs_au is False, do not mask
map_data_ncs_au = map_data_ncs_au*mask
one_d = map_data_ncs_au.as_1d()
n_zero = mask.count(0)
n_tot = mask.size()
mean_in_box = one_d.min_max_mean().mean*n_tot/(n_tot-n_zero)
map_data_ncs_au = map_data_ncs_au+(1-mask)*mean_in_box
half_map_data_list_au = []
for hm in half_map_data_list: # apply mask to half maps
one_d = hm.as_1d()
mean_in_box = one_d.min_max_mean().mean*n_tot/(n_tot-n_zero)
hm_data_ncs_au = hm+(1-mask)*mean_in_box
half_map_data_list_au.append(hm_data_ncs_au)
del one_d, mask
if au_map_output_file and params.output_files.write_output_maps:
# Write out the NCS au of density
write_ccp4_map(tracking_data.crystal_symmetry, au_map_output_file,
map_data_ncs_au)
print("Output NCS AU map: %s" %(au_map_output_file), file = out)
tracking_data.set_output_ncs_au_map_info(
file_name = au_map_output_file,
crystal_symmetry = tracking_data.crystal_symmetry,
origin = map_data_ncs_au.origin(),
all = map_data_ncs_au.all())
# Now box_map of cut out AU
box_mask_ncs_au, box_crystal_symmetry, \
dummy_smoothed_box_mask_data, dummy_original_box_map_data = cut_out_map(
map_data = mask_data_ncs_au.as_double(),
crystal_symmetry = tracking_data.crystal_symmetry,
min_point = lower_bounds, max_point = upper_bounds, out = out)
# Mask
if params.output_files.box_mask_file and params.output_files.write_output_maps:
# write out box_map NCS mask representing one AU of the NCS
write_ccp4_map(
box_crystal_symmetry,
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_mask_file),
box_mask_ncs_au)
print("Output NCS au as box (cut out) mask: %s " %(
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_mask_file)), file = out)
tracking_data.set_output_box_mask_info(
file_name = os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_mask_file),
crystal_symmetry = box_crystal_symmetry,
origin = box_mask_ncs_au.origin(),
all = box_mask_ncs_au.all())
# Map
box_map_ncs_au, box_crystal_symmetry, \
dummy_smoothed_box_mask_data, dummy_original_box_map_data = cut_out_map(
soft_mask = tracking_data.params.map_modification.soft_mask,
resolution = tracking_data.params.crystal_info.resolution,
map_data = map_data_ncs_au.as_double(),
crystal_symmetry = tracking_data.crystal_symmetry,
min_point = lower_bounds, max_point = upper_bounds, out = out)
half_map_data_list_au_box = []
for hmdlu in half_map_data_list_au:
hm_box_map_ncs_au, dummy_box_crystal_symmetry, \
dummy_smoothed_box_mask_data, dummy_original_box_map_data = cut_out_map(
soft_mask = tracking_data.params.map_modification.soft_mask,
resolution = tracking_data.params.crystal_info.resolution,
map_data = hmdlu.as_double(),
crystal_symmetry = tracking_data.crystal_symmetry,
min_point = lower_bounds, max_point = upper_bounds, out = out)
half_map_data_list_au_box.append(hm_box_map_ncs_au)
if params.control.save_box_map_ncs_au:
tracking_data.set_box_map_ncs_au_map_data(
box_map_ncs_au_crystal_symmetry = box_crystal_symmetry,
box_map_ncs_au_map_data = box_map_ncs_au,
box_mask_ncs_au_map_data = box_mask_ncs_au,
box_map_ncs_au_half_map_data_list = half_map_data_list_au_box,
)
if params.output_files.box_map_file:
# write out NCS map as box_map (cut out region of map enclosed in box_mask)
if params.output_files.write_output_maps:
write_ccp4_map(box_crystal_symmetry,
os.path.join(tracking_data.params.output_files.output_directory,
params.output_files.box_map_file), box_map_ncs_au)
print("Output NCS au as box (cut out) map: %s " %(
os.path.join(tracking_data.params.output_files.output_directory,
params.output_files.box_map_file)), file = out)
tracking_data.set_output_box_map_info(
file_name = os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_map_file),
crystal_symmetry = box_crystal_symmetry,
origin = box_map_ncs_au.origin(),
all = box_map_ncs_au.all())
# Write out all the selected regions
if params.output_files.write_output_maps:
print("\nWriting out region maps. "+\
"These superimpose on the NCS AU map \nand "+\
"mask %s, %s\n" %(
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_map_file),
os.path.join(tracking_data.params.output_files.output_directory, params.output_files.box_mask_file), ), file = out)
map_files_written, remainder_regions_written = write_region_maps(params,
map_data = map_data,
tracking_data = tracking_data,
ncs_group_obj = ncs_group_obj,
remainder_ncs_group_obj = remainder_ncs_group_obj,
out = out)
# and pick up the remainder regions not already written
remainder_map_files_written, dummy_remainder = write_region_maps(params,
map_data = map_data,
tracking_data = tracking_data,
ncs_group_obj = remainder_ncs_group_obj,
regions_to_skip = remainder_regions_written,
out = out)
map_files_written+= remainder_map_files_written
else:
map_files_written = []
return map_files_written
def write_intermediate_maps(params,
map_data = None,
map_data_remaining = None,
ncs_group_obj = None,
tracking_data = None,
out = sys.stdout):
if map_data_remaining and params.output_files.remainder_map_file:
write_ccp4_map(
tracking_data.crystal_symmetry, params.output_files.remainder_map_file,
map_data_remaining)
print("Wrote output remainder map to %s" %(
params.output_files.remainder_map_file), file = out)
if params.segmentation.write_all_regions:
for id in ncs_group_obj.selected_regions:
region_mask = ncs_group_obj.edited_mask.deep_copy()
s = (ncs_group_obj.edited_mask == -1)
s |= (ncs_group_obj.edited_mask == id)
region_mask = region_mask.set_selected(s, 1)
region_mask = region_mask.set_selected(~s, 0)
write_ccp4_map(tracking_data.crystal_symmetry,
'mask_%d.ccp4' %id, region_mask)
print("Wrote output mask for region %d to %s" %(id,
"mask_%d.ccp4" %(id)), file = out)
def iterate_search(params,
map_data_remaining = None,
map_data = None,
ncs_obj = None,
ncs_group_obj = None,
scattered_points = None,
tracking_data = None,
out = sys.stdout):
# Write out intermediate maps if desired
if params.output_files.write_intermediate_maps:
write_intermediate_maps(params,
map_data = map_data,
map_data_remaining = map_data_remaining,
ncs_group_obj = ncs_group_obj,
tracking_data = tracking_data,
out = out)
new_params = deepcopy(params)
new_params.segmentation.iterate_with_remainder = False
new_params.segmentation.density_threshold = None
new_params.output_files.write_output_maps = False
new_params.output_files.output_info_file = None
if params.output_files.write_intermediate_maps:
new_params.output_files.au_output_file_stem = \
params.output_files.au_output_file_stem+"_cycle_2"
else:
new_params.output_files.au_output_file_stem = None
fraction = params.segmentation.iteration_fraction
if tracking_data.n_residues:
new_n_residues = int(tracking_data.n_residues*fraction)
new_solvent_fraction = max(0.001, min(0.999,
1- (1-tracking_data.solvent_fraction)*fraction))
new_tracking_data = deepcopy(tracking_data)
if new_tracking_data.n_residues:
new_tracking_data.set_n_residues(new_n_residues)
new_tracking_data.set_solvent_fraction(new_solvent_fraction)
new_tracking_data.set_origin_shift() # sets it to zero
new_tracking_data.params.segmentation.starting_density_threshold = new_params.segmentation.starting_density_threshold # this is new
print("\nIterating with remainder density", file = out)
# NOTE: do not include pdb_hierarchy here unless you deep_copy it
remainder_ncs_group_obj, dummy_remainder, remainder_tracking_data = run(
None, params = new_params,
map_data = map_data_remaining,
ncs_obj = ncs_obj,
target_scattered_points = scattered_points,
tracking_data = new_tracking_data,
is_iteration = True,
out = out)
if not remainder_ncs_group_obj: # Nothing to do
return None
# Combine the results to get remainder_id_dict
# remainder_id_dict[id_remainder] = id_nearby
remainder_ncs_group_obj = combine_with_iteration(params,
map_data = map_data,
crystal_symmetry = tracking_data.crystal_symmetry,
ncs_group_obj = ncs_group_obj,
remainder_ncs_group_obj = remainder_ncs_group_obj,
out = out)
return remainder_ncs_group_obj
def bounds_overlap(lower = None, upper = None,
other_lower = None, other_upper = None, tol = 1):
for i in range(3):
if upper[i]+tol<other_lower[i]: return False
if other_upper[i]+tol<lower[i]: return False
return True
def combine_with_iteration(params,
map_data = None,
crystal_symmetry = None,
ncs_group_obj = None,
remainder_ncs_group_obj = None,
out = sys.stdout):
if not ncs_group_obj.selected_regions or not remainder_ncs_group_obj \
or not remainder_ncs_group_obj.selected_regions:
return None
# see if any regions in ncs_obj overlap with remainder_ncs_group_obj...
# If so, combine
remainder_id_dict = {}
for id_remainder in remainder_ncs_group_obj.selected_regions:
best_id = None
best_overlaps = None
remainder_centers = \
remainder_ncs_group_obj.region_scattered_points_dict[id_remainder]
# figure out typical distance between scattered_points...
touching_dist = get_touching_dist(remainder_centers)
# Notice bounds of remainder region:
r_lower, r_upper = get_bounds(
ncs_group_obj = remainder_ncs_group_obj, id = id_remainder)
for id in ncs_group_obj.selected_regions:
# Skip if not likely to be very close...
lower, upper = get_bounds(ncs_group_obj = ncs_group_obj, id = id)
if not bounds_overlap(lower = lower, upper = upper,
other_lower = r_lower, other_upper = r_upper):
continue
test_centers = ncs_group_obj.region_scattered_points_dict[id]
dist = get_closest_dist(test_centers, remainder_centers)
if touching_dist is not None and dist>touching_dist:
continue
bool_region_mask = ncs_group_obj.co.expand_mask(
id_to_expand = ncs_group_obj.original_id_from_id[id],
expand_size = params.segmentation.expand_size+1) # just touching
s = (bool_region_mask == True)
s &= (remainder_ncs_group_obj.edited_mask == id_remainder)
overlaps = s.count(True)
if best_overlaps is None or overlaps>best_overlaps:
best_overlaps = overlaps
best_id = id
if best_overlaps:
print("\nCombining remainder id %d with original id %d (overlaps = %d)" %(
id_remainder, best_id, best_overlaps), file = out)
remainder_id_dict[id_remainder] = best_id
remainder_ncs_group_obj.remainder_id_dict = remainder_id_dict
return remainder_ncs_group_obj
def get_touching_dist(centers, default = 100., min_dist = 8.):
mean_dist = 0.
mean_dist_n = 0.
nskip = max(1, len(centers)//10) # try to get 10
for i in range(0, len(centers), nskip):
if i == 0:
target = centers[1:]
elif i == len(centers)-1:
target = centers[:-1]
else:
target = centers[:i]
target.extend(centers[i+1:])
other = centers[i:i+1]
if not target or not other: continue
dist = get_closest_dist(target, other)
if dist is not None:
mean_dist+= dist
mean_dist_n+= 1.
if mean_dist_n>0:
return max(min_dist, 2.0*mean_dist/mean_dist_n)
else:
return default
def get_grid_units(map_data = None, crystal_symmetry = None, radius = None,
out = sys.stdout):
N_ = map_data.all()
sx, sy, sz = 1/N_[0], 1/N_[1], 1/N_[2]
sx_cart, sy_cart, sz_cart = crystal_symmetry.unit_cell().orthogonalize(
[sx, sy, sz])
grid_spacing = (sx_cart+sy_cart+sz_cart)/3.
grid_units = int(radius/grid_spacing)
min_cell_grid_units = min(N_[0], N_[1], N_[2])
grid_units = max(1, min(grid_units, int(min_cell_grid_units/3)))
print("Grid units representing %7.1f A will be %d" %(
radius, grid_units), file = out)
return grid_units
def cut_out_map(map_data = None, crystal_symmetry = None,
soft_mask = None, soft_mask_radius = None, resolution = None,
shift_origin = None,
min_point = None, max_point = None, out = sys.stdout):
from cctbx import uctbx
from cctbx import maptbx
na = map_data.all() # tuple with dimensions
for i in range(3):
assert min_point[i] >= 0
assert max_point[i] < na[i] # 2019-11-05 just na-1
new_map_data = maptbx.copy(map_data, tuple(min_point), tuple(max_point))
# NOTE: end point of map is max_point, so size of map (new all()) is
# (max_point-min_point+ (1, 1, 1))
# shrink unit cell, angles are the same
# NOTE 2: the origin of output map will be min_point (not 0, 0, 0).
shrunk_uc = []
for i in range(3):
shrunk_uc.append(
crystal_symmetry.unit_cell().parameters()[i]*new_map_data.all()[i]/na[i] )
uc_params = crystal_symmetry.unit_cell().parameters()
new_unit_cell_box = uctbx.unit_cell(
parameters = (shrunk_uc[0], shrunk_uc[1], shrunk_uc[2],
uc_params[3], uc_params[4], uc_params[5]))
new_crystal_symmetry = crystal.symmetry(
unit_cell = new_unit_cell_box, space_group = 'p1')
if soft_mask:
if soft_mask_radius is None:
soft_mask_radius = resolution
assert soft_mask_radius is not None
original_map_data = new_map_data.deep_copy()
new_map_data, smoothed_mask_data = set_up_and_apply_soft_mask(
map_data = new_map_data,
shift_origin = shift_origin,
crystal_symmetry = new_crystal_symmetry,
resolution = resolution,
radius = soft_mask_radius, out = out)
else:
original_map_data = None
smoothed_mask_data = None
return new_map_data, new_crystal_symmetry, \
smoothed_mask_data, original_map_data
def get_zero_boundary_map(
map_data = None,
grid_units_for_boundary = None,
crystal_symmetry = None,
radius = None):
assert grid_units_for_boundary or (crystal_symmetry and radius)
# grid_units is how many grid units are about equal to soft_mask_radius
if grid_units_for_boundary is None:
grid_units = get_grid_units(map_data = map_data,
crystal_symmetry = crystal_symmetry, radius = radius, out = null_out())
grid_units = int(0.5+0.5*grid_units)
else:
grid_units = grid_units_for_boundary
from cctbx import maptbx
zero_boundary_map = maptbx.zero_boundary_box_map(
map_data, grid_units).result()
return zero_boundary_map
def set_up_and_apply_soft_mask(map_data = None, shift_origin = None,
crystal_symmetry = None, resolution = None,
grid_units_for_boundary = None,
radius = None, out = None):
if out is None:
from libtbx.utils import null_out
out = null_out()
acc = map_data.accessor()
map_data = map_data.shift_origin()
new_acc = map_data.accessor()
# Add soft boundary to mean around outside of mask
zero_boundary_map = get_zero_boundary_map(
map_data = map_data,
grid_units_for_boundary = grid_units_for_boundary,
crystal_symmetry = crystal_symmetry,
radius = radius)
# this map is zero's around the edge and 1 in the middle
# multiply zero_boundary_map--smoothed & new_map_data and return
print("Applying soft mask to boundary of cut out map", file = out)
new_map_data, smoothed_mask_data = apply_soft_mask(map_data = map_data,
mask_data = zero_boundary_map,
rad_smooth = resolution,
crystal_symmetry = crystal_symmetry,
out = out)
if new_acc != acc:
new_map_data.reshape(acc)
smoothed_mask_data.reshape(acc)
return new_map_data, smoothed_mask_data
def apply_shift_to_pdb_hierarchy(
origin_shift = None,
crystal_symmetry = None,
pdb_hierarchy = None, out = sys.stdout):
if origin_shift is not None:
sites_cart = pdb_hierarchy.atoms().extract_xyz()
sites_cart_shifted = sites_cart+\
flex.vec3_double(sites_cart.size(), origin_shift)
pdb_hierarchy.atoms().set_xyz(sites_cart_shifted)
return pdb_hierarchy
def apply_origin_shift(origin_shift = None,
ncs_object = None,
shifted_ncs_object = None,
pdb_hierarchy = None,
target_hierarchy = None,
map_data = None,
shifted_map_file = None,
shifted_pdb_file = None,
shifted_ncs_file = None,
tracking_data = None,
sharpening_target_pdb_inp = None,
out = sys.stdout):
if shifted_map_file:
write_ccp4_map(tracking_data.crystal_symmetry,
shifted_map_file,
map_data)
print("Wrote shifted map to %s" %(
shifted_map_file), file = out)
tracking_data.set_shifted_map_info(file_name =
shifted_map_file,
crystal_symmetry = tracking_data.crystal_symmetry,
origin = map_data.origin(),
all = map_data.all())
if origin_shift: # Note origin shift does not change crystal_symmetry
if pdb_hierarchy:
pdb_hierarchy = apply_shift_to_pdb_hierarchy(
origin_shift = origin_shift,
crystal_symmetry = tracking_data.crystal_symmetry,
pdb_hierarchy = pdb_hierarchy,
out = out)
if sharpening_target_pdb_inp:
sharpening_target_pdb_inp = apply_shift_to_pdb_hierarchy(
origin_shift = origin_shift,
crystal_symmetry = tracking_data.crystal_symmetry,
pdb_hierarchy = sharpening_target_pdb_inp.construct_hierarchy(),
out = out).as_pdb_input()
if target_hierarchy:
target_hierarchy = apply_shift_to_pdb_hierarchy(
origin_shift = origin_shift,
crystal_symmetry = tracking_data.crystal_symmetry,
pdb_hierarchy = target_hierarchy,
out = out)
from scitbx.math import matrix
if ncs_object and not shifted_ncs_object:
shfted_ncs_object = ncs_object.coordinate_offset(
coordinate_offset = matrix.col(origin_shift))
if shifted_pdb_file and pdb_hierarchy:
import iotbx.pdb
f = open(shifted_pdb_file, 'w')
print(iotbx.pdb.format_cryst1_record(
crystal_symmetry = tracking_data.crystal_symmetry), file = f)
print(pdb_hierarchy.as_pdb_string(), file = f)
f.close()
print("Wrote shifted pdb file to %s" %(
shifted_pdb_file), file = out)
tracking_data.set_shifted_pdb_info(file_name = shifted_pdb_file,
n_residues = pdb_hierarchy.overall_counts().n_residues)
if shifted_ncs_file and shifted_ncs_object:
shifted_ncs_object.format_all_for_group_specification(
file_name = shifted_ncs_file)
print("Wrote %s NCS operators for shifted map to %s" %(
shifted_ncs_object.max_operators(),
shifted_ncs_file), file = out)
if tracking_data.input_ncs_info.has_updated_operators():
print("NOTE: these may include additional operators added to fill the cell"+\
" or\nhave fewer operators if not all applied.", file = out)
tracking_data.set_shifted_ncs_info(file_name = shifted_ncs_file,
number_of_operators = shifted_ncs_object.max_operators(),
is_helical_symmetry = tracking_data.input_ncs_info.is_helical_symmetry)
tracking_data.shifted_ncs_info.show_summary(out = out)
return shifted_ncs_object, pdb_hierarchy, target_hierarchy, tracking_data, \
sharpening_target_pdb_inp
def restore_pdb(params, tracking_data = None, out = sys.stdout):
if not params.output_files.restored_pdb:
params.output_files.restored_pdb = \
params.input_files.pdb_to_restore[:-4]+"_restored.pdb"
print("Shifting origin of %s and writing to %s" %(
params.input_files.pdb_to_restore,
params.output_files.restored_pdb), file = out)
os = tracking_data.origin_shift
origin_shift = (-os[0], -os[1], -os[2])
print("Origin shift will be: %.1f %.1f %.1f "%(origin_shift), file = out)
import iotbx.pdb
pdb_inp = iotbx.pdb.input(file_name = params.input_files.pdb_to_restore)
pdb_hierarchy = pdb_inp.construct_hierarchy()
pdb_hierarchy = apply_shift_to_pdb_hierarchy(
origin_shift = origin_shift,
crystal_symmetry = tracking_data.crystal_symmetry,
pdb_hierarchy = pdb_hierarchy,
out = out)
f = open(params.output_files.restored_pdb, 'w')
print(iotbx.pdb.format_cryst1_record(
crystal_symmetry = tracking_data.crystal_symmetry), file = f)
print(pdb_hierarchy.as_pdb_string(), file = f)
f.close()
print("Wrote restored pdb file to %s" %(
params.output_files.restored_pdb), file = out)
def find_threshold_in_map(target_points = None,
map_data = None,
require_at_least_target_points = None,
iter_max = 10):
map_1d = map_data.as_1d()
map_mean = map_1d.min_max_mean().mean
map_max = map_1d.min_max_mean().max
map_min = map_1d.min_max_mean().min
cutoff = map_mean
low = map_min
high = map_max
best_cutoff = None
best_score = None
for iter in range(iter_max):
s = (map_1d >cutoff)
n_cutoff = s.count(True)
if (not require_at_least_target_points) or (n_cutoff >= target_points):
score = abs(n_cutoff-target_points)
else:
score = 1.e+10 # allow it but anything above cutoff will be better
if best_score is None or score < best_score:
best_cutoff = cutoff
best_score = score
if n_cutoff == target_points:
return best_cutoff
elif n_cutoff < target_points: # lower it
high = cutoff
cutoff = 0.5*(cutoff+low)
else: # raise it
low = cutoff
cutoff = 0.5*(cutoff+high)
return best_cutoff
def remove_points(mask, remove_points = None):
keep_points = (remove_points == False)
new_mask = (mask & keep_points)
return new_mask
def get_ncs_sites_cart(sites_cart = None, ncs_id = None,
ncs_obj = None, unit_cell = None, ncs_in_cell_only = True):
ncs_sites_cart = flex.vec3_double()
if not ncs_obj or not ncs_obj.ncs_groups() or not ncs_obj.ncs_groups()[0] or \
not ncs_obj.ncs_groups()[0].translations_orth():
return ncs_sites_cart
# identify ncs-related points
ncs_group = ncs_obj.ncs_groups()[0]
identity_op = ncs_group.identity_op_id()
ncs_sites_cart = flex.vec3_double()
for xyz_cart in sites_cart:
for i0 in range(len(ncs_group.translations_orth())):
if i0 == identity_op: continue
if ncs_id is not None and i0!= ncs_id: continue
r = ncs_group.rota_matrices_inv()[i0] # inverse maps pos 0 on to pos i
t = ncs_group.translations_orth_inv()[i0]
new_xyz_cart = r * matrix.col(xyz_cart) + t
ncs_sites_cart.append(new_xyz_cart)
if ncs_in_cell_only:
new_sites_cart = flex.vec3_double()
ncs_sites_frac = unit_cell.fractionalize(ncs_sites_cart)
for site_frac, site_cart in zip(ncs_sites_frac, ncs_sites_cart):
if site_frac[0]>= 0 and site_frac[0]<= 1 and \
site_frac[1]>= 0 and site_frac[1]<= 1 and \
site_frac[2]>= 0 and site_frac[2]<= 1:
new_sites_cart.append(site_cart)
ncs_sites_cart = new_sites_cart
return ncs_sites_cart
def get_ncs_mask(map_data = None, unit_cell = None, ncs_object = None,
starting_mask = None, radius = None, expand_radius = None, overall_mask = None,
every_nth_point = None):
assert every_nth_point is not None
if not expand_radius: expand_radius = 2.*radius
working_au_mask = starting_mask.deep_copy()
working_ncs_mask = mask_from_sites_and_map( # empty ncs mask
map_data = map_data, unit_cell = unit_cell,
sites_cart = flex.vec3_double(), radius = radius, overall_mask = overall_mask)
au_points_last = working_au_mask.count(True)
ncs_points_last = working_ncs_mask.count(True)
max_tries = 10000
for ii in range(max_tries): # just a big number; should take just a few
# Find all points in au (sample every_nth_point in grid)
au_sites_cart = get_marked_points_cart(mask_data = working_au_mask,
unit_cell = unit_cell, every_nth_point = every_nth_point,
boundary_radius = radius)
# Find all points ncs-related to marked point in mask
ncs_sites_cart = get_ncs_sites_cart(sites_cart = au_sites_cart,
ncs_obj = ncs_object, unit_cell = unit_cell, ncs_in_cell_only = True)
# Expand au slightly with all points near to au_sites_cart
new_au_mask = mask_from_sites_and_map(
map_data = map_data, unit_cell = unit_cell,
sites_cart = au_sites_cart, radius = radius, overall_mask = overall_mask)
working_au_mask = (working_au_mask | new_au_mask) # add on to existing
keep_points = (working_ncs_mask == False) # cross off those in ncs
working_au_mask = (working_au_mask & keep_points)
# mark ncs au with all points not in au that are close to ncs_sites_cart
new_ncs_mask = mask_from_sites_and_map(
map_data = map_data, unit_cell = unit_cell,
sites_cart = ncs_sites_cart, radius = radius, overall_mask = overall_mask)
keep_points = (working_au_mask == False) # cross off those in au
new_ncs_mask = (new_ncs_mask & keep_points)
working_ncs_mask = (new_ncs_mask | working_ncs_mask) # add on to existing
au_points = working_au_mask.count(True)
ncs_points = working_ncs_mask.count(True)
if au_points == au_points_last and ncs_points == ncs_points_last:
break
au_points_last = au_points
ncs_points_last = ncs_points
# Now expand the au and repeat
working_au_mask = mask_from_sites_and_map(
map_data = map_data, unit_cell = unit_cell,
sites_cart = au_sites_cart, radius = expand_radius, overall_mask = overall_mask)
keep_points = (working_ncs_mask == False) # cross off those in ncs
working_au_mask = (working_au_mask & keep_points)
return working_au_mask, working_ncs_mask
def renormalize_map_data(
map_data = None, solvent_fraction = None):
sd = max(0.0001, map_data.sample_standard_deviation())
if solvent_fraction >= 10.: solvent_fraction = solvent_fraction/100.
solvent_fraction = min(0.999, max(0.001, solvent_fraction))
scaled_sd = sd/(1-solvent_fraction)**0.5
map_data = (map_data-map_data.as_1d().min_max_mean().mean)/scaled_sd
return map_data
def mask_from_sites_and_map(
map_data = None, unit_cell = None,
sites_cart = None, radius = None, overall_mask = None):
assert radius is not None
from cctbx import maptbx
sel = maptbx.grid_indices_around_sites(
unit_cell = unit_cell,
fft_n_real = map_data.focus(),
fft_m_real = map_data.all(),
sites_cart = sites_cart,
site_radii = flex.double(sites_cart.size(), radius))
map_data_1d = map_data.as_1d()
mask = (map_data_1d == 0 and map_data_1d == 1) # 1D bool array all False
mask.set_selected(sel, True) # mark points around sites
mask.reshape(map_data.accessor())
if overall_mask:
assert overall_mask.all() == mask.all()
mask = (mask & overall_mask)
return mask
def set_radius(unit_cell = None, map_data = None, every_nth_point = None):
# Set radius so that radius will capture all points on grid if sampled
# on every_nth_point
a, b, c = unit_cell.parameters()[:3]
nx, ny, nz = map_data.all()
# furthest possible minimum distance between grid points
max_diagonal_between_sampled = every_nth_point*(
(a/nx)**2+(b/ny)**2+(c/nz)**2)**0.5
radius = max_diagonal_between_sampled*0.55 # big enough to cover everything
return radius
def get_marked_points_cart(mask_data = None, unit_cell = None,
every_nth_point = 3, boundary_radius = None):
# return list of cartesian coordinates of grid points that are marked
# only sample every every_nth_point in each direction...
assert mask_data.origin() == (0, 0, 0)
nx, ny, nz = mask_data.all()
if boundary_radius:
# How far from edges shall we stay:
grid_frac = (1./nx, 1./ny, 1./nz)
grid_orth = unit_cell.orthogonalize(grid_frac)
boundary_grid_points = 0
for go in grid_orth:
bgp = int(0.99+boundary_radius/go)
boundary_grid_points = max(boundary_grid_points, bgp)
else:
boundary_grid_points = 0
marked_points = maptbx.marked_grid_points(
map_data = mask_data,
every_nth_point = every_nth_point).result()
sites_frac = flex.vec3_double()
boundary_points_skipped = 0
for grid_point in marked_points:
if boundary_grid_points:
if \
grid_point[0]<boundary_grid_points or \
grid_point[0]>nx-boundary_grid_points or \
grid_point[1]<boundary_grid_points or \
grid_point[1]>ny-boundary_grid_points or \
grid_point[2]<boundary_grid_points or \
grid_point[2]>nz-boundary_grid_points: # XXX was typo previously
boundary_points_skipped+= 1
continue
sites_frac.append(
(grid_point[0]/nx,
grid_point[1]/ny,
grid_point[2]/nz))
sites_cart = unit_cell.orthogonalize(sites_frac)
return sites_cart
def get_overall_mask(
map_data = None,
mask_threshold = None,
fraction_of_max_mask_threshold = None,
use_solvent_content_for_threshold = None, # use instead of fraction_of
mask_padding_fraction = None,
solvent_fraction = None,
crystal_symmetry = None,
radius = None,
resolution = None,
d_max = 100000.,
out = sys.stdout):
# This routine cannot use mask_data with origin != (0,0,0)
if map_data.origin() != (0,0,0):
print("Map origin must be at (0,0,0) for get_overall_mask")
assert map_data.origin() == (0,0,0) # Map origin must be at (0,0,0)
# Make a local SD map from our map-data
from cctbx.maptbx import crystal_gridding
from cctbx import sgtbx
cg = crystal_gridding(
unit_cell = crystal_symmetry.unit_cell(),
space_group_info = sgtbx.space_group_info(number = 1), # Always
pre_determined_n_real = map_data.all())
if not resolution:
from cctbx.maptbx import d_min_from_map
resolution = d_min_from_map(
map_data, crystal_symmetry.unit_cell(), resolution_factor = 1./4.)
print("\nEstimated resolution of map: %6.1f A\n" %(
resolution), file = out)
if radius:
smoothing_radius = 2.*radius
else:
smoothing_radius = 2.*resolution
from iotbx.map_manager import map_manager
mm = map_manager(map_data = map_data,
unit_cell_grid = map_data.all(),
unit_cell_crystal_symmetry = crystal_symmetry,
wrapping = False)
map_coeffs = mm.map_as_fourier_coefficients(
d_min = resolution, d_max = d_max)
if not map_coeffs:
raise Sorry("No map coeffs obtained")
complete_set = map_coeffs.complete_set()
stol = flex.sqrt(complete_set.sin_theta_over_lambda_sq().data())
import math
w = 4 * stol * math.pi * smoothing_radius
sphere_reciprocal = 3 * (flex.sin(w) - w * flex.cos(w))/flex.pow(w, 3)
try:
temp = complete_set.structure_factors_from_map(
flex.pow2(map_data-map_data.as_1d().min_max_mean().mean))
except Exception as e:
print(e, file = out)
print ("The sampling of the map appears to be too low for a "+
"\nresolution of %s. Using a larger value for resolution" %(
resolution), file = out)
from cctbx.maptbx import d_min_from_map
resolution = d_min_from_map(
map_data, crystal_symmetry.unit_cell(), resolution_factor = 1./4.)
print("\nEstimated resolution of map: %6.1f A\n" %(
resolution), file = out)
map_coeffs = map_coeffs.resolution_filter(d_min = resolution, d_max = d_max)
complete_set = map_coeffs.complete_set()
stol = flex.sqrt(complete_set.sin_theta_over_lambda_sq().data())
import math
w = 4 * stol * math.pi * smoothing_radius
sphere_reciprocal = 3 * (flex.sin(w) - w * flex.cos(w))/flex.pow(w, 3)
temp = complete_set.structure_factors_from_map(
flex.pow2(map_data-map_data.as_1d().min_max_mean().mean))
fourier_coeff = complete_set.array(data = temp.data()*sphere_reciprocal)
sd_map = fourier_coeff.fft_map(
crystal_gridding = cg,
).apply_volume_scaling().real_map_unpadded()
assert sd_map.all() == map_data.all()
# now use sd_map
# First mask out the map based on threshold
mm = sd_map.as_1d().min_max_mean()
max_in_sd_map = mm.max
mean_in_map = mm.mean
min_in_map = mm.min
print("Highest value in SD map is %7.2f. Mean is %7.2f . Lowest is %7.2f " %(
max_in_sd_map,
mean_in_map,
min_in_map), file = out)
if fraction_of_max_mask_threshold and (
(not solvent_fraction) or (not use_solvent_content_for_threshold)):
mask_threshold = fraction_of_max_mask_threshold*max_in_sd_map
print("Using fraction of max as threshold: %.3f " %(
fraction_of_max_mask_threshold), \
"which is threshold of %.3f" %(mask_threshold), file = out)
if mask_padding_fraction:
# Adjust threshold to increase by mask_padding_fraction, proportional
# to fraction available
overall_mask = (sd_map>= mask_threshold)
current_above_threshold = overall_mask.count(True)/overall_mask.size()
# current+(1-current)*pad
additional_padding = (1-current_above_threshold)*mask_padding_fraction
target_above_threshold = min(
0.99, current_above_threshold+additional_padding)
print("Target with padding of %.2f will be %.2f" %(
mask_padding_fraction, target_above_threshold), file = out)
solvent_fraction = (1-target_above_threshold)
mask_threshold = None
if mask_threshold:
print("Cutoff for mask will be input threshold", file = out)
threshold = mask_threshold
else: # guess based on solvent_fraction
if solvent_fraction is None:
print("Guessing solvent fraction of 0.9", file = out)
solvent_fraction = 0.9 # just guess
threshold = find_threshold_in_map(target_points = int(
(1.-solvent_fraction)*sd_map.size()),
map_data = sd_map)
print("Cutoff will be threshold marking about %7.1f%% of cell" %(
100.*(1.-solvent_fraction)), file = out)
overall_mask = (sd_map>= threshold)
print("Model region of map "+\
"(density above %7.3f )" %( threshold) +" includes %7.1f%% of map" %(
100.*overall_mask.count(True)/overall_mask.size()), file = out)
return overall_mask, max_in_sd_map, sd_map
def get_skew(data = None):
mean = data.min_max_mean().mean
sd = data.standard_deviation_of_the_sample()
x = data-mean
return (x**3).min_max_mean().mean/sd**3
def get_kurtosis(data = None):
mean = data.min_max_mean().mean
sd = data.standard_deviation_of_the_sample()
x = data-mean
return (x**4).min_max_mean().mean/sd**4
def score_map(map_data = None,
sharpening_info_obj = None,
solvent_fraction = None,
fraction_occupied = None,
wrapping = None,
sa_percent = None,
region_weight = None,
max_regions_to_test = None,
scale_region_weight = False,
out = sys.stdout):
if sharpening_info_obj:
solvent_fraction = sharpening_info_obj.solvent_fraction
wrapping = sharpening_info_obj.wrapping
fraction_occupied = sharpening_info_obj.fraction_occupied
sa_percent = sharpening_info_obj.sa_percent
region_weight = sharpening_info_obj.region_weight
max_regions_to_test = sharpening_info_obj.max_regions_to_test
else:
sharpening_info_obj = sharpening_info()
if solvent_fraction is None: # skip SA score
sharpening_info_obj.adjusted_sa = 0.
assert sharpening_info_obj.sharpening_target == 'kurtosis'
else: # usual
map_data = renormalize_map_data(
map_data = map_data, solvent_fraction = solvent_fraction)
target_in_all_regions = map_data.size()*fraction_occupied*(1-solvent_fraction)
print("\nTarget number of points in all regions: %.0f" %(
target_in_all_regions), file = out)
threshold = find_threshold_in_map(target_points = int(
target_in_all_regions), map_data = map_data)
print("Cutoff will be threshold of %7.2f marking %7.1f%% of cell" %(
threshold, 100.*(1.-solvent_fraction)), file = out)
co, sorted_by_volume, min_b, max_b = get_co(
map_data = map_data.deep_copy(),
threshold = threshold, wrapping = wrapping)
if len(sorted_by_volume)<2:
return sharpening_info_obj# skip it, nothing to do
target_sum = sa_percent* target_in_all_regions*0.01
print("Points for %.1f percent of target in all regions: %.1f" %(
sa_percent, target_sum), file = out)
cntr = 0
sum_v = 0.
sum_new_v = 0.
for p in sorted_by_volume[1:max_regions_to_test+2]:
cntr+= 1
v, i = p
sum_v+= v
bool_expanded = co.expand_mask(id_to_expand = i, expand_size = 1)
new_v = bool_expanded.count(True)-v
sum_new_v+= new_v
sa_ratio = new_v/v
if sum_v>= target_sum: break
sa_ratio = sum_new_v/max(1., sum_v) # ratio of SA to volume
regions = len(sorted_by_volume[1:])
normalized_regions = regions/max(1, target_in_all_regions)
skew = get_skew(map_data.as_1d())
if scale_region_weight:
solvent_fraction_std = 0.85 # typical value, ends up as scale on weight
region_weight_scale = (1.-solvent_fraction)/(1.-solvent_fraction_std)
region_weight_use = region_weight*region_weight_scale
else:
region_weight_use = region_weight
sharpening_info_obj.adjusted_sa = \
sa_ratio - region_weight_use*normalized_regions
sharpening_info_obj.sa_ratio = sa_ratio
sharpening_info_obj.normalized_regions = normalized_regions
sharpening_info_obj.kurtosis = get_kurtosis(map_data.as_1d())
if sharpening_info_obj.sharpening_target == 'adjusted_path_length':
sharpening_info_obj.adjusted_path_length = get_adjusted_path_length(
map_data = map_data,
resolution = sharpening_info_obj.resolution,
crystal_symmetry = sharpening_info_obj.crystal_symmetry,
out = out)
else:
sharpening_info_obj.adjusted_path_length = None
if sharpening_info_obj.sharpening_target == 'kurtosis':
sharpening_info_obj.score = sharpening_info_obj.kurtosis
if sharpening_info_obj.sharpening_target == 'adjusted_path_length':
sharpening_info_obj.score = sharpening_info_obj.adjusted_path_length
else:
sharpening_info_obj.score = sharpening_info_obj.adjusted_sa
return sharpening_info_obj
def get_adjusted_path_length(
map_data = None,
crystal_symmetry = None,
resolution = None,
out = sys.stdout):
try:
from phenix.autosol.trace_and_build import trace_and_build
except Exception as e: # Not available
return 0
from phenix.programs.trace_and_build import master_phil_str
import iotbx.phil
tnb_params = iotbx.phil.parse(master_phil_str).extract()
tnb_params.crystal_info.resolution = resolution
tnb_params.strategy.retry_long_branches = False
tnb_params.strategy.correct_segments = False
tnb_params.strategy.split_and_join = False
tnb_params.strategy.vary_sharpening = []
tnb_params.strategy.get_path_length_only = True
tnb_params.trace_and_build.find_helices_strands = False
tnb = trace_and_build(
params = tnb_params,
map_data = map_data,
crystal_symmetry = crystal_symmetry,
origin_cart = (0, 0, 0),
origin = (0, 0, 0),
log = out)
tnb.run()
return tnb.adjusted_path_length
def sharpen_map_with_si(sharpening_info_obj = None,
f_array_normalized = None,
f_array = None, phases = None,
map_data = None,
overall_b = None,
resolution = None,
out = sys.stdout):
si = sharpening_info_obj
if si.sharpening_method == 'no_sharpening':
return map_and_b_object(map_data = map_data)
if map_data and (not f_array or not phases):
map_coeffs, dummy = get_f_phases_from_map(map_data = map_data,
crystal_symmetry = si.crystal_symmetry,
d_min = si.resolution,
d_min_ratio = si.d_min_ratio,
return_as_map_coeffs = True,
scale_max = si.scale_max,
out = out)
f_array, phases = map_coeffs_as_fp_phi(map_coeffs)
if si.remove_aniso:
if si.use_local_aniso and \
(si.local_aniso_in_local_sharpening or
(si.local_aniso_in_local_sharpening is None and si.ncs_copies == 1)) and \
si.original_aniso_obj: # use original
aniso_obj = si.original_aniso_obj
print("\nRemoving aniso from map using saved aniso object before sharpening\n", file = out)
else:
print("\nRemoving aniso from map before sharpening\n", file = out)
aniso_obj = None
from cctbx.maptbx.refine_sharpening import analyze_aniso
f_array, f_array_ra = analyze_aniso(
aniso_obj = aniso_obj,
remove_aniso = si.remove_aniso,
f_array = f_array, resolution = si.resolution, out = out)
if si.is_model_sharpening() or si.is_half_map_sharpening():
from cctbx.maptbx.refine_sharpening import scale_amplitudes
ff = f_array.phase_transfer(phase_source = phases, deg = True)
map_and_b = scale_amplitudes(
map_coeffs = f_array.phase_transfer(phase_source = phases, deg = True),
si = si, overall_b = overall_b, out = out)
return map_and_b
elif si.is_resolution_dependent_sharpening():
if f_array_normalized is None:
from cctbx.maptbx.refine_sharpening import get_sharpened_map, \
quasi_normalize_structure_factors
(d_max, d_min) = f_array.d_max_min()
if not f_array.binner():
f_array.setup_binner(n_bins = si.n_bins, d_max = d_max, d_min = d_min)
f_array_normalized = quasi_normalize_structure_factors(
f_array, set_to_minimum = 0.01)
map_data = get_sharpened_map(ma = f_array_normalized, phases = phases,
b = si.resolution_dependent_b, resolution = si.resolution, n_real = si.n_real,
d_min_ratio = si.d_min_ratio)
return map_and_b_object(map_data = map_data)
else:
map_and_b = apply_sharpening(n_real = si.n_real,
f_array = f_array, phases = phases,
sharpening_info_obj = si,
crystal_symmetry = si.crystal_symmetry,
out = null_out())
return map_and_b
def put_bounds_in_range(
lower_bounds = None, upper_bounds = None,
box_size = None,
n_buffer = None,
n_real = None, out = sys.stdout):
# put lower and upper inside (0, n_real-1) and try to make size at least minimum
new_lb = []
new_ub = []
print("Putting bounds in range...(%s, %s, %s) to (%s, %s, %s)" %(
tuple(list(lower_bounds)+list(upper_bounds))), file = out)
if n_buffer:
print("Buffer of %s added" %(n_buffer), file = out)
for lb, ub, ms, nr in zip(lower_bounds, upper_bounds, box_size, n_real):
if ub<lb: ub = lb
if lb >ub: lb = ub
extra = (ms-(ub-lb))//2
lb = lb-extra
ub = ub+extra
if n_buffer:
lb = lb-n_buffer
ub = ub+n_buffer
if lb<0:
shift = -lb
lb+= shift
ub+= shift
boundary = int(ms-(ub-lb+1))//2
if boundary>0:
lb = lb-boundary
ub = ub+boundary
if lb<0: lb = 0
if ub>= nr: ub = nr-1 # 2019-11-05 cannot go beyond na-1
new_lb.append(lb)
new_ub.append(ub)
print("New bounds ...(%s, %s, %s) to (%s, %s, %s)" %(
tuple(list(new_lb)+list(new_ub))), file = out)
return tuple(new_lb), tuple(new_ub)
def get_iterated_solvent_fraction(map = None,
verbose = None,
resolve_size = None,
crystal_symmetry = None,
mask_padding_fraction = None,
fraction_of_max_mask_threshold = None,
solvent_content = None,
use_solvent_content_for_threshold = None, # use instead of fraction_of_..
cell_cutoff_for_solvent_from_mask = None,
mask_resolution = None,
return_mask_and_solvent_fraction = None,
out = sys.stdout):
if cell_cutoff_for_solvent_from_mask and \
crystal_symmetry.unit_cell().volume() > cell_cutoff_for_solvent_from_mask**3:
#go directly to low_res_mask
return get_solvent_fraction_from_low_res_mask(
crystal_symmetry = crystal_symmetry,
map_data = map.deep_copy(),
mask_padding_fraction = mask_padding_fraction,
fraction_of_max_mask_threshold = fraction_of_max_mask_threshold,
solvent_content = solvent_content,
use_solvent_content_for_threshold = use_solvent_content_for_threshold,
return_mask_and_solvent_fraction = return_mask_and_solvent_fraction,
mask_resolution = mask_resolution, out = out)
try:
from phenix.autosol.map_to_model import iterated_solvent_fraction
solvent_fraction, overall_mask = iterated_solvent_fraction(
crystal_symmetry = crystal_symmetry,
map_as_double = map,
verbose = verbose,
resolve_size = resolve_size,
out = out)
if solvent_fraction<= 0.989: # means that it was 0.99 which is hard limit
if return_mask_and_solvent_fraction:
return overall_mask, solvent_fraction
else:
return solvent_fraction
else: # use backup method
return get_solvent_fraction_from_low_res_mask(
crystal_symmetry = crystal_symmetry,
map_data = map.deep_copy(),
mask_padding_fraction = mask_padding_fraction,
fraction_of_max_mask_threshold = fraction_of_max_mask_threshold,
solvent_content = solvent_content,
use_solvent_content_for_threshold = use_solvent_content_for_threshold,
return_mask_and_solvent_fraction = return_mask_and_solvent_fraction,
mask_resolution = mask_resolution, out = out)
except Exception as e:
# catch case where map was not on proper grid
if str(e).find("sym equiv of a grid point must be a grid point")>-1:
print("\nSpace group:%s \n Unit cell: %s \n Gridding: %s \nError message: %s" %(
crystal_symmetry.space_group().info(),
str(crystal_symmetry.unit_cell().parameters()),
str(map.all()), str(e)), file = out)
raise Sorry(
"The input map seems to be on a grid incompatible with crystal symmetry"+
"\n(symmetry equivalents of a grid point must be on "+
"an integer grid point)")
elif str(e).find("maximum size for resolve is")>-1:
raise Sorry(str(e)+
"\nIt may be possible to go on by supplying solvent content"+
"or molecular_mass")
# Try to get solvent fraction with low_res mask
return get_solvent_fraction_from_low_res_mask(
crystal_symmetry = crystal_symmetry,
map_data = map.deep_copy(),
mask_padding_fraction = mask_padding_fraction,
fraction_of_max_mask_threshold = fraction_of_max_mask_threshold,
solvent_content = solvent_content,
use_solvent_content_for_threshold = use_solvent_content_for_threshold,
return_mask_and_solvent_fraction = return_mask_and_solvent_fraction,
mask_resolution = mask_resolution, out = out)
def get_solvent_fraction_from_low_res_mask(
crystal_symmetry = None, map_data = None,
fraction_of_max_mask_threshold = None,
solvent_content = None,
use_solvent_content_for_threshold = None, # use instead of fraction_of
mask_padding_fraction = None,
return_mask_and_solvent_fraction = None,
mask_resolution = None,
out = sys.stdout):
overall_mask, max_in_sd_map, sd_map = get_overall_mask(map_data = map_data,
fraction_of_max_mask_threshold = fraction_of_max_mask_threshold,
use_solvent_content_for_threshold = use_solvent_content_for_threshold,
mask_padding_fraction = mask_padding_fraction,
solvent_fraction = solvent_content, # note name change XXX
crystal_symmetry = crystal_symmetry,
resolution = mask_resolution,
out = out)
if overall_mask is None:
if return_mask_and_solvent_fraction:
return None, None
else:
return None
solvent_fraction = overall_mask.count(False)/overall_mask.size()
print("Solvent fraction from overall mask: %.3f " %(solvent_fraction), file = out)
if return_mask_and_solvent_fraction:
mask_data = map_data.deep_copy()
mask_data.as_1d().set_selected(overall_mask.as_1d(), 1)
mask_data.as_1d().set_selected(~overall_mask.as_1d(), 0)
return mask_data, solvent_fraction
else:
return solvent_fraction
def get_solvent_fraction_from_molecular_mass(
do_not_adjust_dalton_scale = None,
crystal_symmetry = None, molecular_mass = None, out = sys.stdout):
map_volume = crystal_symmetry.unit_cell().volume()
density_factor = 1000*1.23 # just protein density, close enough...
mm = molecular_mass
molecule_fraction = mm*density_factor/map_volume
if do_not_adjust_dalton_scale or molecule_fraction > 1 and mm > 1000:
mm = mm/1000 # was in Da
solvent_fraction = max(0.01, min(1., 1 - (
mm*density_factor/map_volume)))
print("Solvent content of %7.2f from molecular mass of %7.1f kDa" %(
solvent_fraction, mm), file = out)
return solvent_fraction
def set_up_si(var_dict = None, crystal_symmetry = None,
is_crystal = None,
ncs_copies = None, n_residues = None,
solvent_fraction = None, molecular_mass = None, pdb_inp = None, map = None,
auto_sharpen = True, half_map_data_list = None, verbose = None,
out = sys.stdout):
si = sharpening_info(n_real = map.all())
args = []
auto_sharpen_methods = var_dict.get('auto_sharpen_methods')
if auto_sharpen_methods and auto_sharpen_methods != ['None'] and \
len(auto_sharpen_methods) == 1:
sharpening_method = auto_sharpen_methods[0]
else:
sharpening_method = None
for param in [
'verbose', 'resolve_size', 'seq_file', 'sequence',
'box_size',
'target_n_overlap',
'restrict_map_size',
'box_center', 'remove_aniso',
'input_weight_map_pickle_file', 'output_weight_map_pickle_file',
'read_sharpened_maps', 'write_sharpened_maps', 'select_sharpened_map',
'output_directory',
'smoothing_radius', 'use_local_aniso',
'local_aniso_in_local_sharpening',
'overall_before_local',
'local_sharpening',
'box_in_auto_sharpen',
'density_select_in_auto_sharpen',
'density_select_threshold_in_auto_sharpen',
'use_weak_density',
'resolution',
'd_min_ratio',
'scale_max',
'input_d_cut',
'b_blur_hires',
'discard_if_worse',
'mask_atoms', 'mask_atoms_atom_radius', 'value_outside_atoms',
'soft_mask',
'tol_r', 'abs_tol_t',
'rel_tol_t',
'require_helical_or_point_group_symmetry',
'max_helical_operators',
'allow_box_if_b_iso_set',
'max_box_fraction',
'cc_cut',
'max_cc_for_rescale',
'scale_using_last',
'density_select_max_box_fraction',
'k_sharpen',
'optimize_b_blur_hires',
'iterate',
'optimize_d_cut',
'residual_target', 'sharpening_target',
'search_b_min', 'search_b_max', 'search_b_n', 'adjust_region_weight',
'region_weight_method',
'region_weight_factor',
'region_weight_buffer',
'region_weight_default',
'target_b_iso_ratio',
'signal_min',
'buffer_radius',
'wang_radius',
'pseudo_likelihood',
'target_b_iso_model_scale',
'b_iso', 'b_sharpen',
'resolution_dependent_b',
'normalize_amplitudes_in_resdep',
'region_weight',
'sa_percent',
'n_bins',
'eps',
'max_regions_to_test',
'regions_to_keep',
'fraction_occupied',
'rmsd',
'rmsd_resolution_factor',
'k_sol',
'b_sol',
'fraction_complete',
'nproc',
'multiprocessing',
'queue_run_command',
'verbose',
]:
x = var_dict.get(param)
if x is not None:
if type(x) == type([1, 2, 3]):
xx = []
for k in x:
xx.append(str(k))
args.append("%s = %s" %(param, " ".join(xx)))
else:
args.append("%s = %s" %(param, x))
local_params = get_params_from_args(args)
# Set solvent content from molecular_mass if present
if molecular_mass and not solvent_fraction:
solvent_fraction = get_solvent_fraction_from_molecular_mass(
crystal_symmetry = crystal_symmetry, molecular_mass = molecular_mass,
out = out)
# Test to see if we can use adjusted_path_length as target
if local_params.map_modification.sharpening_target == \
'adjusted_path_length':
print(
"Checking to make sure we can use 'adjusted_path_length'as target...",
end = ' ', file = out)
try:
from phenix.autosol.trace_and_build import trace_and_build
except Exception as e:
raise Sorry("Please set sharpening target to something other than "+
"adjusted_path_length (not available)")
print("OK", file = out)
if (local_params.input_files.seq_file or
local_params.crystal_info.sequence) and \
not local_params.crystal_info.solvent_content and \
not solvent_fraction: # 2017-12-19
solvent_fraction = get_solvent_fraction(local_params,
crystal_symmetry = crystal_symmetry,
ncs_copies = ncs_copies, out = out)
si.update_with_params(params = local_params,
crystal_symmetry = crystal_symmetry,
is_crystal = is_crystal,
solvent_fraction = solvent_fraction,
ncs_copies = ncs_copies,
n_residues = n_residues,
auto_sharpen = auto_sharpen,
sharpening_method = sharpening_method,
pdb_inp = pdb_inp,
half_map_data_list = half_map_data_list,
)
return si
def bounds_to_frac(b, map_data):
a = map_data.all()
return b[0]/a[0], b[1]/a[1], b[2]/a[2]
def bounds_to_cart(b, map_data, crystal_symmetry = None):
bb = bounds_to_frac(b, map_data)
a, b, c = crystal_symmetry.unit_cell().parameters()[:3]
return a*bb[0], b*bb[1], c*bb[2]
def select_inside_box(lower_bounds = None, upper_bounds = None, xrs = None,
hierarchy = None):
if not hierarchy or not xrs:
return None
selection = flex.bool(xrs.scatterers().size())
for atom_group in hierarchy.atom_groups():
for atom in atom_group.atoms():
if atom.xyz[0]>= lower_bounds[0] and \
atom.xyz[0]<= upper_bounds[0] and \
atom.xyz[1]>= lower_bounds[1] and \
atom.xyz[1]<= upper_bounds[1] and \
atom.xyz[2]>= lower_bounds[2] and \
atom.xyz[2]<= upper_bounds[2]:
selection[atom.i_seq] = True
asc1 = hierarchy.atom_selection_cache()
return hierarchy.select(selection)
def make_empty_map(template_map = None, value = 0.):
# Create empty map original_map_in_box
empty_map = flex.double(template_map.as_1d().as_double().size(), value)
empty_map.reshape(flex.grid(template_map.all()))
return empty_map
def sum_box_data(starting_map = None, box_map = None,
lower_bounds = None, upper_bounds = None):
# sum box data into starting_map
#Pull out current starting_map data
starting_box_data = maptbx.copy(starting_map, tuple(lower_bounds), tuple(upper_bounds))
assert starting_box_data.all() == box_map.all()
# Add to box_map
starting_box_data = starting_box_data.as_1d()
box_map_data = box_map.as_1d()
starting_box_data+= box_map_data
# put back into shape
starting_box_data.reshape(flex.grid(box_map.all()))
maptbx.set_box(
map_data_from = starting_box_data,
map_data_to = starting_map,
start = lower_bounds,
end = upper_bounds)
return starting_map
def copy_box_data(starting_map = None, box_map = None,
lower_bounds = None, upper_bounds = None):
# Copy box data into original_map_in_box
maptbx.set_box(
map_data_from = box_map,
map_data_to = starting_map,
start = lower_bounds,
end = upper_bounds)
return starting_map
def select_box_map_data(si = None,
map_data = None,
first_half_map_data = None,
second_half_map_data = None,
pdb_inp = None,
get_solvent_fraction = True, # XXX test not doing this...
n_min = 30, # at least 30 atoms to run model sharpening
restrict_map_size = None,
out = sys.stdout, local_out = sys.stdout):
box_solvent_fraction = None
solvent_fraction = si.solvent_fraction
crystal_symmetry = si.crystal_symmetry
box_size = si.box_size
lower_bounds = None
upper_bounds = None
smoothed_box_mask_data = None
original_box_map_data = None #
n_buffer = None
if (not pdb_inp and not si.box_in_auto_sharpen) and (
first_half_map_data and second_half_map_data):
print("Creating density-based soft mask and applying to half-map data", file = out)
if not si.soft_mask:
raise Sorry(
"Need to set soft_mask = True for half-map sharpening without model")
# NOTE: could precede this by density_select on map_data, save bounds and
# cut out half-maps with those bounds. That case could
# cover si.soft_mask = False
half_map_data_list = [first_half_map_data, second_half_map_data]
box_mask_data, box_map, half_map_data_list, \
box_solvent_fraction, smoothed_box_mask_data, original_box_map_data = \
get_and_apply_soft_mask_to_maps(
resolution = si.resolution,
wang_radius = si.wang_radius,
buffer_radius = si.buffer_radius,
map_data = map_data, crystal_symmetry = crystal_symmetry,
half_map_data_list = half_map_data_list,
out = out)
box_first_half_map, box_second_half_map = half_map_data_list
box_crystal_symmetry = crystal_symmetry
box_pdb_inp = pdb_inp
elif pdb_inp or (
si.density_select_in_auto_sharpen and not si.box_in_auto_sharpen):
# use map_box for pdb_inp (mask with model)
# also use map_box for density_select_in_auto_sharpen sharpening because
# need to use the same density select for all 3 maps.
# XXX Perhaps we canuse above method for pdb_inp
assert not si.local_sharpening
if pdb_inp:
print("Using map_box based on input model", file = out)
hierarchy = pdb_inp.construct_hierarchy()
max_box_fraction = si.max_box_fraction
si.density_select_in_auto_sharpen = False
else:
#print >>out, "Using density_select in map_box"
hierarchy = None
assert si.density_select_in_auto_sharpen
max_box_fraction = si.density_select_max_box_fraction
#----------------------trimming model-------------------------------
if si.box_center: # Have model but center at box_center and trim hierarchy
lower_bounds, upper_bounds = box_from_center(si = si,
map_data = map_data, out = out)
if si.soft_mask:
n_buffer = get_grid_units(map_data = map_data,
crystal_symmetry = crystal_symmetry,
radius = si.resolution, out = out)
n_buffer = int(0.5+n_buffer*1.5)
else:
n_buffer = 0
lower_bounds, upper_bounds = put_bounds_in_range(
lower_bounds = lower_bounds, upper_bounds = upper_bounds,
box_size = box_size, n_buffer = n_buffer,
n_real = map_data.all(), out = out)
lower_frac = bounds_to_frac(lower_bounds, map_data)
upper_frac = bounds_to_frac(upper_bounds, map_data)
lower_cart = bounds_to_cart(
lower_bounds, map_data, crystal_symmetry = crystal_symmetry)
upper_cart = bounds_to_cart(
upper_bounds, map_data, crystal_symmetry = crystal_symmetry)
if hierarchy: # trimming hierarchy to box and then using trimmed
# hierarchy in map_box to create actual box
xrs = hierarchy.extract_xray_structure(
crystal_symmetry = si.crystal_symmetry)
# find everything in box
sel_hierarchy = select_inside_box(lower_bounds = lower_cart,
upper_bounds = upper_cart, xrs = xrs, hierarchy = hierarchy)
n = sel_hierarchy.overall_counts().n_atoms
print("Selected atoms inside box: %d" %(n), file = out)
if n<n_min:
print("Skipping...using entire structure", file = out)
else:
hierarchy = sel_hierarchy
#----------------------end trimming model-------------------------------
from mmtbx.command_line.map_box import run as run_map_box
args = ["keep_input_unit_cell_and_grid = False"]
if si.density_select_in_auto_sharpen:
args.append('density_select = True')
#print >>out, "Using density_select in map_box"
if si.density_select_threshold_in_auto_sharpen is not None:
args.append('density_select_threshold = %s' %(
si.density_select_threshold_in_auto_sharpen))
elif si.box_in_auto_sharpen and not si.mask_atoms:
print("Using map_box with model", file = out)
elif si.mask_atoms:
print("Using map_box with model and mask_atoms", file = out)
args.append('mask_atoms = True')
if si.mask_atoms_atom_radius:
args.append('mask_atoms_atom_radius = %s' %(si.mask_atoms_atom_radius))
if si.value_outside_atoms:
args.append('value_outside_atoms = %s' %(si.value_outside_atoms))
if si.soft_mask:
print("Using soft mask", file = out)
args.append('soft_mask = %s' %(si.soft_mask))
args.append('soft_mask_radius = %s' %(si.resolution))
else:
raise Sorry("Unknown choice in select_box_data")
if restrict_map_size:
args.append('restrict_map_size = True')
print("Getting map as box now", file = out)
local_hierarchy = None
if hierarchy:
local_hierarchy = hierarchy.deep_copy() # run_map_box modifies its argument
assert isinstance(si.wrapping, bool) # wrapping must be defined
box = run_map_box(args,
map_data = map_data, pdb_hierarchy = local_hierarchy,
write_output_files = False,
wrapping = si.wrapping,
crystal_symmetry = crystal_symmetry, log = out)
lower_bounds = box.gridding_first
upper_bounds = box.gridding_last
box_map = box.map_box
box_map = scale_map(box_map, out = out)
box_crystal_symmetry = box.box_crystal_symmetry
if box.hierarchy:
box_pdb_inp = box.hierarchy.as_pdb_input()
else:
box_pdb_inp = None
if first_half_map_data:
print("Getting first map as box", file = out)
if hierarchy:
local_hierarchy = hierarchy.deep_copy() # required
box_first = run_map_box(args,
map_data = first_half_map_data, pdb_hierarchy = local_hierarchy,
write_output_files = False,
lower_bounds = lower_bounds,
upper_bounds = upper_bounds,
crystal_symmetry = crystal_symmetry,
wrapping = si.wrapping,
log = out)
box_first_half_map = box_first.map_box.as_double()
else:
box_first_half_map = None
if second_half_map_data:
print("Getting second map as box", file = out)
if hierarchy:
local_hierarchy = hierarchy.deep_copy() # required
box_second = run_map_box(args,
map_data = second_half_map_data, pdb_hierarchy = local_hierarchy,
write_output_files = False,
lower_bounds = lower_bounds,
upper_bounds = upper_bounds,
crystal_symmetry = crystal_symmetry,
wrapping = si.wrapping,
log = out)
box_second_half_map = box_second.map_box.as_double()
else:
box_second_half_map = None
else: # cut out box based on box_center or regions
if si.box_center: # center at box_center
print("Cutting out box based on center at (%.2f, %.2f, %.2f) " %( si.box_center), file = out)
lower_bounds, upper_bounds = box_from_center(si = si,
map_data = map_data, out = out)
elif si.use_weak_density:
print("Cutting out box based on centering on weak density", file = out)
lower_bounds, upper_bounds = box_of_smallest_region(si = si,
map_data = map_data,
out = out)
else:
print("Cutting out box based on centering on strong density", file = out)
lower_bounds, upper_bounds = box_of_biggest_region(si = si,
map_data = map_data,
out = out)
if si.soft_mask:
n_buffer = get_grid_units(map_data = map_data,
crystal_symmetry = crystal_symmetry,
radius = si.resolution, out = out)
n_buffer = int(0.5+n_buffer*1.5)
else:
n_buffer = 0
lower_bounds, upper_bounds = put_bounds_in_range(
lower_bounds = lower_bounds, upper_bounds = upper_bounds,
box_size = box_size, n_buffer = n_buffer,
n_real = map_data.all(), out = out)
# select map data inside this box
print("\nSelecting map data inside box", file = out)
box_map, box_crystal_symmetry, \
smoothed_box_mask_data, original_box_map_data = cut_out_map(
map_data = map_data.as_double(),
crystal_symmetry = crystal_symmetry,
soft_mask = si.soft_mask,
soft_mask_radius = si.resolution,
resolution = si.resolution,
shift_origin = True,
min_point = lower_bounds, max_point = upper_bounds, out = out)
box_pdb_inp = None
if first_half_map_data:
box_first_half_map, box_first_crystal_symmetry, \
dummy_smoothed_box_mask_data, dummy_original_box_map_data = cut_out_map(
map_data = first_half_map_data.as_double(),
crystal_symmetry = crystal_symmetry,
soft_mask = si.soft_mask,
soft_mask_radius = si.resolution,
resolution = si.resolution,
shift_origin = True,
min_point = lower_bounds, max_point = upper_bounds, out = local_out)
else:
box_first_half_map = None
if second_half_map_data:
box_second_half_map, box_second_crystal_symmetry, \
dummy_smoothed_box_mask_data, dummy_original_box_map_data = cut_out_map(
map_data = second_half_map_data.as_double(),
crystal_symmetry = crystal_symmetry,
soft_mask = si.soft_mask,
soft_mask_radius = si.resolution,
resolution = si.resolution,
shift_origin = True,
min_point = lower_bounds, max_point = upper_bounds, out = local_out)
else:
box_second_half_map = None
if not box_map or (
(not pdb_inp and not second_half_map_data) and \
box_map.size() > si.max_box_fraction* map_data.size()):
return None, map_data, first_half_map_data, \
second_half_map_data, crystal_symmetry, None, \
smoothed_box_mask_data, None, None # no point
# figure out solvent fraction in this box...
if get_solvent_fraction: #
if box_solvent_fraction is None:
box_solvent_fraction = get_iterated_solvent_fraction(
crystal_symmetry = box_crystal_symmetry,
map = box_map,
fraction_of_max_mask_threshold = si.fraction_of_max_mask_threshold,
mask_resolution = si.resolution,
out = out)
if box_solvent_fraction is None:
box_solvent_fraction = si.solvent_fraction
print("Using overall solvent fraction for box", file = out)
print("Local solvent fraction: %7.2f" %(box_solvent_fraction), file = out)
else:
box_solvent_fraction = None
box_sharpening_info_obj = box_sharpening_info(
lower_bounds = lower_bounds,
upper_bounds = upper_bounds,
n_real = box_map.all(),
scale_max = si.scale_max,
wrapping = False,
crystal_symmetry = box_crystal_symmetry,
solvent_fraction = box_solvent_fraction)
return box_pdb_inp, box_map, box_first_half_map, box_second_half_map, \
box_crystal_symmetry, box_sharpening_info_obj, \
smoothed_box_mask_data, original_box_map_data, n_buffer
def inside_zero_one(xyz):
from scitbx.matrix import col
offset = xyz-col((0.5, 0.5, 0.5))
lower_int = offset.iround().as_vec3_double()
return xyz-lower_int
def move_xyz_inside_cell(xyz_cart = None, crystal_symmetry = None):
xyz_local = flex.vec3_double()
if type(xyz_cart) == type(xyz_local):
xyz_local = xyz_cart
is_single = False
else:
is_single = True
xyz_local.append(xyz_cart)
xyz_frac = crystal_symmetry.unit_cell().fractionalize(xyz_local)
new_xyz_frac = inside_zero_one(xyz_frac)
new_xyz_cart = crystal_symmetry.unit_cell().orthogonalize(new_xyz_frac)
if is_single:
return new_xyz_cart[0]
else:
return new_xyz_cart
def box_from_center( si = None,
map_data = None,
out = sys.stdout):
cx, cy, cz = si.crystal_symmetry.unit_cell().fractionalize(si.box_center)
if cx<0 or cx>1 or cy<0 or cy>1 or cz<0 or cz>1:
print("Moving box center inside (0, 1)", file = out)
si.box_center = move_xyz_inside_cell(
xyz_cart = si.box_center, crystal_symmetry = si.crystal_symmetry)
cx, cy, cz = si.crystal_symmetry.unit_cell().fractionalize(si.box_center)
print("\nBox centered at (%7.2f, %7.2f, %7.2f) A" %(
tuple(si.box_center)), file = out)
ax, ay, az = map_data.all()
cgx, cgy, cgz = int(0.5+ax*cx), int(0.5+ay*cy), int(0.5+az*cz),
print("Box grid centered at (%d, %d, %d)\n" %(cgx, cgy, cgz), file = out)
return (cgx, cgy, cgz), (cgx, cgy, cgz)
def box_of_smallest_region(si = None,
map_data = None,
return_as_list = None,
out = sys.stdout):
return box_of_biggest_region(si = si,
map_data = map_data,
return_as_list = return_as_list,
use_smallest = True,
out = out)
def box_of_biggest_region(si = None,
map_data = None,
return_as_list = None,
use_smallest = False,
out = sys.stdout):
n_residues = si.n_residues
ncs_copies = si.ncs_copies
solvent_fraction = si.solvent_fraction
b_vs_region = b_vs_region_info()
co, sorted_by_volume, min_b, max_b, unique_expected_regions, best_score, \
new_threshold, starting_density_threshold = \
get_connectivity(
b_vs_region = b_vs_region,
map_data = map_data,
n_residues = n_residues,
ncs_copies = ncs_copies,
solvent_fraction = solvent_fraction,
min_volume = si.min_volume,
min_ratio = si.min_ratio,
fraction_occupied = si.fraction_occupied,
wrapping = si.wrapping,
residues_per_region = si.residues_per_region,
max_ratio_to_target = si.max_ratio_to_target,
min_ratio_to_target = si.min_ratio_to_target,
min_ratio_of_ncs_copy_to_first = si.min_ratio_of_ncs_copy_to_first,
starting_density_threshold = si.starting_density_threshold,
density_threshold = si.density_threshold,
crystal_symmetry = si.crystal_symmetry,
chain_type = si.chain_type,
verbose = si.verbose,
out = out)
if len(sorted_by_volume)<2:
return # nothing to do
if use_smallest:
small_ratio = 0.25
maximum_position_ratio = 0.75
v1, i1 = sorted_by_volume[1]
v_small = small_ratio*v1
maximum_position_small = maximum_position_ratio*(len(sorted_by_volume)-1)+1
best_pos = 1
ii = 0
for v, i in sorted_by_volume[1:]:
ii+= 1
if v < v_small: continue
if ii > maximum_position_small: continue
best_pos = ii
v, i = sorted_by_volume[best_pos]
print("\nVolume of target region %d: %d grid points: "%(best_pos, v), file = out)
else: # usual
v, i = sorted_by_volume[1]
print("\nVolume of largest region: %d grid points: "%(v), file = out)
print("Region %3d (%3d) volume:%5d X:%6d - %6d Y:%6d - %6d Z:%6d - %6d "%(
1, i, v,
min_b[i][0], max_b[i][0],
min_b[i][1], max_b[i][1],
min_b[i][2], max_b[i][2]), file = out)
if (not return_as_list):
return min_b[i], max_b[i]
else: # return a list of centers
centers_frac = flex.vec3_double()
a1, a2, a3 = map_data.all()
for v, i in sorted_by_volume[1:]:
centers_frac.append(
tuple((
(min_b[i][0]+max_b[i][0])/(2.*a1),
(min_b[i][1]+max_b[i][1])/(2.*a2),
(min_b[i][2]+max_b[i][2])/(2.*a3),
))
)
return centers_frac
def get_fft_map(n_real = None, map_coeffs = None):
from cctbx import maptbx
from cctbx.maptbx import crystal_gridding
if n_real:
cg = crystal_gridding(
unit_cell = map_coeffs.crystal_symmetry().unit_cell(),
space_group_info = map_coeffs.crystal_symmetry().space_group_info(),
pre_determined_n_real = n_real)
else:
cg = None
ccs = map_coeffs.crystal_symmetry()
fft_map = map_coeffs.fft_map( resolution_factor = 0.25,
crystal_gridding = cg,
symmetry_flags = maptbx.use_space_group_symmetry)
fft_map.apply_sigma_scaling()
return fft_map
def average_from_bounds(lower, upper, grid_all = None):
avg = []
for u, l in zip(upper, lower):
avg.append(0.5*(u+l))
if grid_all:
avg_fract = []
for a, g in zip(avg, grid_all):
avg_fract.append(a/g)
avg = avg_fract
return avg
def get_ncs_copies(site_cart, ncs_object = None,
only_inside_box = None, unit_cell = None):
ncs_group = ncs_object.ncs_groups()[0]
from scitbx.array_family import flex
from scitbx.matrix import col
sites_cart_ncs = flex.vec3_double()
for t, r in zip(ncs_group.translations_orth_inv(),
ncs_group.rota_matrices_inv()):
sites_cart_ncs.append(r * col(site_cart) + t)
if only_inside_box:
assert unit_cell is not None
sites_frac_ncs = unit_cell.fractionalize(sites_cart_ncs)
new_sites_frac = flex.vec3_double()
for x in sites_frac_ncs:
if x[0]>= 0 and x[0]<= 1 and \
x[1]>= 0 and x[1]<= 1 and \
x[2]>= 0 and x[2]<= 1:
new_sites_frac.append(x)
sites_cart_ncs = unit_cell.orthogonalize(new_sites_frac)
return sites_cart_ncs
def fit_bounds_inside_box(lower, upper, box_size = None, all = None):
# adjust bounds so upper>lower and box size is at least box_size
new_lower = []
new_upper = []
if box_size:
for u, l, s, a in zip(upper, lower, box_size, all):
ss = u-l+1
delta = int((1+s-ss)/2) # desired increase in size, to subtract from l
l = max(0, l-delta)
ss = u-l+1
delta = (s-ss) # desired increase in size, to add to u
u = min(a-1, u+delta)
l = max(0, l)
new_lower.append(l)
new_upper.append(u)
else:
for u, l, a in zip(upper, lower, all):
u = min(a-1, u)
l = max(0, l)
new_lower.append(l)
new_upper.append(u)
return new_lower, new_upper
def split_boxes(lower = None, upper = None, target_size = None, target_n_overlap = None,
fix_target_size_and_overlap = None):
# purpose: split the region from lower to upper into overlapping
# boxes of size about target_size
# NOTE: does not actually use target_n_overlap unless
# fix_target_size_and_overlap is set
all_box_list = []
for l, u, ts in zip (lower, upper, target_size):
n = u+1-l
# offset defined by: ts-offset + ts-offset+...+ts = n
# ts*n_box-offset*(n_box-1) = n approx
# n_box (ts-offset) +offset = n
# n_box = (n-offset)/(ts-offset)
assert ts>target_n_overlap
if fix_target_size_and_overlap:
n_box = (n-target_n_overlap-1)/(ts-target_n_overlap)
if n_box>int(n_box):
n_box = int(n_box)+1
else:
n_box = int(n_box)
new_target_size = ts
offset = ts-target_n_overlap
else: # original version
n_box = max(1, (n+(3*ts//4))//ts)
new_target_size = int(0.9+n/n_box)
offset = int(0.9+(n-new_target_size)/max(1, n_box-1))
box_list = []
for i in range(n_box):
start_pos = max(l, l+i*offset)
end_pos = min(u, start_pos+new_target_size)
if fix_target_size_and_overlap:
start_pos = max(0, min(start_pos, end_pos-new_target_size))
box_list.append([start_pos, end_pos])
all_box_list.append(box_list)
new_lower_upper_list = []
for xs, xe in all_box_list[0]:
for ys, ye in all_box_list[1]:
for zs, ze in all_box_list[2]:
new_lower_upper_list.append([(xs, ys, zs, ), (xe, ye, ze, )])
return new_lower_upper_list
def get_target_boxes(si = None, ncs_obj = None, map = None,
pdb_inp = None, out = sys.stdout):
print(80*"-", file = out)
print("Getting segmented map to ID locations for sharpening", file = out)
print(80*"-", file = out)
if si.input_weight_map_pickle_file:
from libtbx import easy_pickle
file_name = si.input_weight_map_pickle_file
print("Loading segmentation data from %s" %(file_name), file = out)
tracking_data = easy_pickle.load(file_name)
else:
args = [
'resolution = %s' %(si.resolution),
'seq_file = %s' %(si.seq_file),
'sequence = %s' %(si.sequence),
'solvent_content = %s' %(si.solvent_fraction),
'auto_sharpen = False', # XXX could sharpen overall
'write_output_maps = True',
'add_neighbors = False',
'density_select = False', ]
if si.is_crystal:
args.append("is_crystal = True")
ncs_group_obj, remainder_ncs_group_obj, tracking_data = run(
args,
map_data = map.deep_copy(),
ncs_obj = ncs_obj,
crystal_symmetry = si.crystal_symmetry)
if si.output_weight_map_pickle_file:
from libtbx import easy_pickle
file_name = os.path.join(si.output_directory, si.output_weight_map_pickle_file)
print("Dumping segmentation data to %s" %(file_name), file = out)
easy_pickle.dump(file_name, tracking_data)
if not ncs_obj or ncs_obj.max_operators() == 0:
from mmtbx.ncs.ncs import ncs
ncs_obj = ncs()
ncs_obj.set_unit_ncs()
print("Regions in this map:", file = out)
centers_frac = flex.vec3_double()
upper_bounds_list = []
lower_bounds_list = []
if pdb_inp and pdb_inp.atoms().extract_xyz().size()>1:
xyz_list = pdb_inp.atoms().extract_xyz()
i_end = xyz_list.size()
n_centers = min(i_end, max(1, len(tracking_data.output_region_map_info_list)))
n_steps = min(n_centers, xyz_list.size())
i_step = int(0.5+min(i_end/2, i_end/n_steps)) # about n_centers but up to n_atoms
i_start = max(1, int(0.5+i_step/2))
from scitbx.matrix import col
ma = map.all()
for i in range(i_start, i_end, i_step):
lower_cart = col(xyz_list[i])
lower_frac = si.crystal_symmetry.unit_cell().fractionalize(lower_cart)
lower = [
int(0.5+ma[0]*lower_frac[0]),
int(0.5+ma[1]*lower_frac[1]),
int(0.5+ma[2]*lower_frac[2])]
lower, upper = fit_bounds_inside_box(
lower, lower, box_size = si.box_size, all = map.all())
upper_bounds_list.append(upper)
lower_bounds_list.append(lower)
average_fract = average_from_bounds(lower, upper, grid_all = map.all())
centers_frac.append(average_fract)
else:
for map_info_obj in tracking_data.output_region_map_info_list:
lower, upper = map_info_obj.lower_upper_bounds()
lower, upper = fit_bounds_inside_box(
lower, upper,
box_size = None, # take the whole region, not just center
all = map.all())
for lower, upper in split_boxes(lower = lower, upper = upper,
target_size = si.box_size,
target_n_overlap = si.target_n_overlap):
upper_bounds_list.append(upper)
lower_bounds_list.append(lower)
average_fract = average_from_bounds(lower, upper, grid_all = map.all())
centers_frac.append(average_fract)
centers_cart = si.crystal_symmetry.unit_cell().orthogonalize(centers_frac)
# Make ncs-related centers
print("NCS ops:", ncs_obj.max_operators(), file = out)
centers_cart_ncs_list = []
for i in range(centers_cart.size()):
centers_cart_ncs_list.append(get_ncs_copies(
centers_cart[i], ncs_object = ncs_obj, only_inside_box = True,
unit_cell = si.crystal_symmetry.unit_cell()) )
all_cart = flex.vec3_double()
for center_list in centers_cart_ncs_list:
all_cart.extend(center_list)
sharpening_centers_file = os.path.join(
si.output_directory, "sharpening_centers.pdb")
write_atoms(file_name = sharpening_centers_file,
crystal_symmetry = si.crystal_symmetry, sites = centers_cart)
ncs_sharpening_centers_file = os.path.join(
si.output_directory, "ncs_sharpening_centers.pdb")
write_atoms(file_name = ncs_sharpening_centers_file,
crystal_symmetry = si.crystal_symmetry, sites = all_cart)
print("\nSharpening centers (matching shifted_map_file).\n\n "+\
"Written to: \n%s \n%s\n"%(
sharpening_centers_file, ncs_sharpening_centers_file), file = out)
for i in range(centers_cart.size()):
print("Center: %s (%7.2f, %7.2f, %7.2f) Bounds: %s :: %s " %(
i, centers_cart[i][0], centers_cart[i][1], centers_cart[i][2],
str(lower_bounds_list[i]), str(upper_bounds_list[i])), file = out)
print(80*"-", file = out)
print("Done getting segmented map to ID locations for sharpening", file = out)
print(80*"-", file = out)
return upper_bounds_list, lower_bounds_list, \
centers_cart_ncs_list, centers_cart, all_cart
def get_box_size(lower_bound = None, upper_bound = None):
box_size = []
for lb, ub in zip(lower_bound, upper_bound):
box_size.append(ub-lb+1)
return box_size
def mean_dist_to_nearest_neighbor(all_cart):
if all_cart.size()<2: # nothing to check
return None
sum_dist = 0.
sum_n = 0.
for i in range(all_cart.size()):
xyz = all_cart[i:i+1]
others = all_cart[:i]
others.extend(all_cart[i+1:])
sum_dist+= get_closest_dist(xyz, others)
sum_n+= 1.
return sum_dist/max(1., sum_n)
def run_local_sharpening(si = None,
auto_sharpen_methods = None,
map = None,
ncs_obj = None,
half_map_data_list = None,
pdb_inp = None,
out = sys.stdout):
print(80*"-", file = out)
print("Running local sharpening", file = out)
print(80*"-", file = out)
# run auto_sharpen_map_or_map_coeffs with box_in_auto_sharpen = True and
# centered at different places. Identify the places as centers of regions.
# Run on au of NCS and apply NCS to get remaining positions
if si.overall_before_local:
# first do overall sharpening of the map to get it about right
print(80*"*", file = out)
print("\nSharpening map overall before carrying out local sharpening\n", file = out)
overall_si = deepcopy(si)
overall_si.local_sharpening = False # don't local sharpen
overall_si = auto_sharpen_map_or_map_coeffs(si = overall_si,
auto_sharpen_methods = auto_sharpen_methods,
map = map,
half_map_data_list = half_map_data_list,
pdb_inp = pdb_inp,
out = out)
sharpened_map = overall_si.map_data
print("\nDone sharpening map overall before carrying out local sharpening\n", file = out)
print(80*"*", file = out)
else:
sharpened_map = map
# Accumulate sums
starting_weight = 0.01 # put starting map everywhere with low weight
sum_weight_map = make_empty_map(template_map = map, value = starting_weight)
# in case a pixel is not covered...
sum_weight_value_map = starting_weight*sharpened_map.deep_copy()
print("\nUsing overall map for any regions where "+\
"no local information is present", file = out)
id_list = []
b_iso_list = flex.double()
starting_b_iso_list = flex.double()
# use sharpened map here
upper_bounds_list, lower_bounds_list, \
centers_cart_ncs_list, centers_cart, all_cart = \
get_target_boxes(si = si, map = sharpened_map, ncs_obj = ncs_obj,
pdb_inp = pdb_inp, out = out)
dist = mean_dist_to_nearest_neighbor(all_cart)
if not dist:
dist = 10.
if not si.smoothing_radius:
print("No nearest neighbors...best to set smoothing radius", file = out)
print("\nMean distance to nearest center is %7.2f A " %(
dist), file = out)
if not si.smoothing_radius:
si.smoothing_radius = float("%.0f" %(dist*2/3)) # 10A from nearest neighbor
print("Using %s A for smoothing radius" %(si.smoothing_radius), file = out)
i = -1
for ub, lb, centers_ncs_cart, center_cart in zip(
upper_bounds_list, lower_bounds_list, centers_cart_ncs_list, centers_cart):
i+= 1
if si.select_sharpened_map is not None and i != si.select_sharpened_map:
continue
map_file_name = 'sharpened_map_%s.ccp4' %(i)
if 0 and si.read_sharpened_maps: # cannot do this as no bounds
print("\nReading sharpened map directly from %s" %(map_file_name), file = out)
result = get_map_object(file_name = map_file_name,
out = out)
local_map_data = result[0]
else:
local_si = deepcopy(si)
local_si.local_sharpening = False # don't do it again
local_si.box_size = get_box_size(lower_bound = lb, upper_bound = ub)
local_si.box_center = center_cart
local_si.box_in_auto_sharpen = True
local_si.density_select_in_auto_sharpen = False
local_si.use_local_aniso = si.local_aniso_in_local_sharpening
local_si.remove_aniso = si.local_aniso_in_local_sharpening
local_si.max_box_fraction = 999 # just bigger than 1
local_si.density_select_max_box_fraction = 999
local_si.nproc = 1
print(80*"+", file = out)
print("Getting local sharpening for box %s" %(i), file = out)
print(80*"+", file = out)
bsi = auto_sharpen_map_or_map_coeffs(si = local_si,
auto_sharpen_methods = auto_sharpen_methods,
map = sharpened_map,
half_map_data_list = half_map_data_list,
pdb_inp = pdb_inp,
return_bsi = True, # just return the bsi of sharpened data
out = out)
if not bsi.map_data:
print("\nNo result for local map %s ...skipping" %(i), file = out)
continue
# merge with background using bsi.smoothed_box_mask_data
if bsi.smoothed_box_mask_data:
print("Merging small map into overall map in soft-mask region", file = out)
bsi.merge_into_overall_map(overall_map = map) # XXX overall_map not used
# Now remove buffer region
if bsi.n_buffer: # extract just the good part
print("Removing buffer from small map", file = out)
bsi.remove_buffer(out = out)
weight_data = bsi.get_gaussian_weighting(out = out)
weighted_data = bsi.map_data*weight_data
sum_weight_value_map = sum_box_data(starting_map = sum_weight_value_map,
box_map = weighted_data,
lower_bounds = bsi.lower_bounds,
upper_bounds = bsi.upper_bounds)
sum_weight_map = sum_box_data(starting_map = sum_weight_map,
box_map = weight_data,
lower_bounds = bsi.lower_bounds,
upper_bounds = bsi.upper_bounds)
id_list.append(i)
starting_b_iso_list.append(bsi.starting_b_iso)
b_iso_list.append(bsi.b_iso)
print(80*"+", file = out)
print("End of getting local sharpening for small box %s" %(i), file = out)
print(80*"+", file = out)
print("\nOverall map created from total of %s local maps" %(i), file = out)
if si.overall_before_local:
print("Note: overall map already sharpened with global sharpening", file = out)
if starting_b_iso_list.size()<1:
print("No results for local sharpening...", file = out)
else:
print("Summary of b_iso values by local map:", file = out)
print(" ID Starting B-iso Sharpened B-iso", file = out)
for i, starting_b_iso, b_iso in zip(id_list, starting_b_iso_list, b_iso_list):
print(" %4s %7.2f %7.2f" %(i, starting_b_iso, b_iso), file = out)
print("\nMean %7.2f %7.2f" %(
starting_b_iso_list.min_max_mean().mean,
b_iso_list.min_max_mean().mean), file = out)
si.map_data = sum_weight_value_map/sum_weight_map
# Get overall b_iso...
print("\nGetting overall b_iso of composite map...", file = out)
map_coeffs_aa, map_coeffs, f_array, phases = effective_b_iso(
map_data = si.map_data,
resolution = si.resolution,
d_min_ratio = si.d_min_ratio,
scale_max = si.scale_max,
crystal_symmetry = si.crystal_symmetry,
out = out)
print(80*"+", file = out)
print("End of getting local sharpening ", file = out)
print(80*"+", file = out)
return si
def auto_sharpen_map_or_map_coeffs(
si = None,
resolution = None, # resolution is required
crystal_symmetry = None, # supply crystal_symmetry and map or
map = None, # map and n_real
wrapping = None,
half_map_data_list = None, # two half-maps matching map
is_crystal = None,
map_coeffs = None,
pdb_inp = None,
ncs_obj = None,
seq_file = None,
sequence = None,
rmsd = None,
rmsd_resolution_factor = None,
k_sol = None,
b_sol = None,
fraction_complete = None,
n_real = None,
solvent_content = None,
molecular_mass = None,
region_weight = None,
sa_percent = None,
n_bins = None,
eps = None,
max_regions_to_test = None,
regions_to_keep = None,
fraction_occupied = None,
input_weight_map_pickle_file = None,
output_weight_map_pickle_file = None,
read_sharpened_maps = None,
write_sharpened_maps = None,
select_sharpened_map = None,
output_directory = None,
smoothing_radius = None,
local_sharpening = None,
local_aniso_in_local_sharpening = None,
overall_before_local = None,
use_local_aniso = None,
auto_sharpen = None,
box_in_auto_sharpen = None, # n_residues, ncs_copies required if not False
density_select_in_auto_sharpen = None,
density_select_threshold_in_auto_sharpen = None,
allow_box_if_b_iso_set = None,
use_weak_density = None,
discard_if_worse = None,
n_residues = None,
ncs_copies = None,
box_center = None,
remove_aniso = None,
box_size = None,
target_n_overlap = None,
lower_bounds = None,
upper_bounds = None,
restrict_map_size = None,
auto_sharpen_methods = None,
residual_target = None,
sharpening_target = None,
d_min_ratio = None,
scale_max = None,
input_d_cut = None,
b_blur_hires = None,
max_box_fraction = None,
cc_cut = None,
max_cc_for_rescale = None,
scale_using_last = None,
density_select_max_box_fraction = None,
mask_atoms = None,
mask_atoms_atom_radius = None,
value_outside_atoms = None,
soft_mask = None,
tol_r = None,
abs_tol_t = None,
rel_tol_t = None,
require_helical_or_point_group_symmetry = None,
max_helical_operators = None,
k_sharpen = None,
optimize_d_cut = None,
optimize_b_blur_hires = None,
iterate = None,
search_b_min = None,
search_b_max = None,
search_b_n = None,
adjust_region_weight = None,
region_weight_method = None,
region_weight_factor = None,
region_weight_buffer = None,
region_weight_default = None,
target_b_iso_ratio = None,
signal_min = None,
buffer_radius = None,
wang_radius = None,
pseudo_likelihood = None,
target_b_iso_model_scale = None,
b_iso = None, # if set, use it
b_sharpen = None, # if set, use it
resolution_dependent_b = None, # if set, use it
normalize_amplitudes_in_resdep = None, # if set, use it
return_bsi = False,
verbose = None,
resolve_size = None,
nproc = None,
multiprocessing = None,
queue_run_command = None,
out = sys.stdout):
if si: #
resolution = si.resolution
crystal_symmetry = si.crystal_symmetry
if not auto_sharpen:
auto_sharpen = si.auto_sharpen
if verbose is None:
verbose = si.verbose
if resolve_size is None:
resolve_size = si.resolve_size
if auto_sharpen is None:
auto_sharpen = True
if map_coeffs and not resolution:
resolution = map_coeffs.d_min()
if map_coeffs and not crystal_symmetry:
crystal_symmetry = map_coeffs.crystal_symmetry()
assert resolution is not None
if map:
return_as_map = True
else: # convert from structure factors to create map if necessary
map = get_fft_map(n_real = n_real, map_coeffs = map_coeffs).real_map_unpadded()
return_as_map = False
# Set ncs_copies if possible
if ncs_copies is None and ncs_obj and ncs_obj.max_operators():
ncs_copies = ncs_obj.max_operators()
print("Set ncs copies based on ncs_obj to %s" %(ncs_copies), file = out)
# Determine if we are running model_sharpening
if half_map_data_list and len(half_map_data_list) == 2:
if auto_sharpen_methods != ['external_map_sharpening']:
auto_sharpen_methods = ['half_map_sharpening']
elif pdb_inp:
auto_sharpen_methods = ['model_sharpening']
if not si:
# Copy parameters to si (sharpening_info_object)
si = set_up_si(var_dict = locals(),
crystal_symmetry = crystal_symmetry,
is_crystal = is_crystal,
solvent_fraction = solvent_content,
molecular_mass = molecular_mass,
auto_sharpen = auto_sharpen,
map = map,
verbose = verbose,
half_map_data_list = half_map_data_list,
pdb_inp = pdb_inp,
ncs_copies = ncs_copies,
n_residues = n_residues, out = out)
if wrapping is not None:
si.wrapping = wrapping
# Figure out solvent fraction
if si.solvent_fraction is None:
si.solvent_fraction = get_iterated_solvent_fraction(
crystal_symmetry = crystal_symmetry,
verbose = si.verbose,
resolve_size = si.resolve_size,
fraction_of_max_mask_threshold = si.fraction_of_max_mask_threshold,
mask_resolution = si.resolution,
map = map,
out = out)
if si.solvent_fraction:
print("Estimated solvent content: %.2f" %(si.solvent_fraction), file = out)
else:
raise Sorry("Unable to estimate solvent content...please supply "+
"solvent_content \nor molecular_mass")
# Determine if we are running half-map or model_sharpening
if half_map_data_list and len(half_map_data_list) == 2:
first_half_map_data = half_map_data_list[0]
second_half_map_data = half_map_data_list[1]
else:
first_half_map_data = None
second_half_map_data = None
# Decide if we are running local sharpening (overlapping set of sharpening
# runs at various locations)
libtbx.call_back(message = 'sharpen', data = None)
if si.local_sharpening:
return run_local_sharpening(si = si,
auto_sharpen_methods = auto_sharpen_methods,
map = map,
ncs_obj = ncs_obj,
half_map_data_list = half_map_data_list,
pdb_inp = pdb_inp,
out = out)
# Get preliminary values of sharpening
working_map = map # use another name for map XXX
if si.iterate and not si.preliminary_sharpening_done:
si.preliminary_sharpening_done = True
si.iterate = False
# first do overall sharpening of the map to get it about right
print(80*"*", file = out)
print("\nSharpening map overall before carrying out final sharpening\n", file = out)
overall_si = deepcopy(si)
overall_si.local_sharpening = False # don't local sharpen
overall_si = auto_sharpen_map_or_map_coeffs(si = overall_si,
auto_sharpen_methods = auto_sharpen_methods,
map = map,
half_map_data_list = half_map_data_list,
pdb_inp = pdb_inp,
out = out)
working_map = overall_si.map_data
# Get solvent content again
overall_si.solvent_content = None
overall_si.solvent_fraction = get_iterated_solvent_fraction(
crystal_symmetry = crystal_symmetry,
verbose = overall_si.verbose,
resolve_size = overall_si.resolve_size,
fraction_of_max_mask_threshold = si.fraction_of_max_mask_threshold,
mask_resolution = si.resolution,
map = working_map,
out = out)
print("Resetting solvent fraction to %.2f " %(
overall_si.solvent_fraction), file = out)
si.solvent_fraction = overall_si.solvent_fraction
print("\nDone sharpening map overall before carrying out final sharpening\n", file = out)
print(80*"*", file = out)
si.b_blur_hires = 0. # from now on, don't apply extra blurring
else:
working_map = map
# Now identify optimal sharpening params
print(80*"=", file = out)
print("\nRunning auto_sharpen to get sharpening parameters\n", file = out)
print(80*"=", file = out)
result = run_auto_sharpen( # get sharpening parameters standard run
si = si,
map_data = working_map,
first_half_map_data = first_half_map_data,
second_half_map_data = second_half_map_data,
pdb_inp = pdb_inp,
auto_sharpen_methods = auto_sharpen_methods,
print_result = False,
return_bsi = return_bsi,
out = out)
if return_bsi:
return result # it is a box_sharpening_info object
else:
si = result
print(80*"=", file = out)
print("\nDone running auto_sharpen to get sharpening parameters\n", file = out)
print(80*"=", file = out)
# Apply the optimal sharpening values and save map in si.map_data
# First test without sharpening if sharpening_method is b_iso, b and
# b_iso is not set
if si.sharpening_method in [
'b_iso', 'b_iso_to_d_cut', 'resolution_dependent'] and b_iso is None:
local_si = deepcopy(si)
local_si.sharpening_method = 'no_sharpening'
local_si.sharpen_and_score_map(map_data = working_map, out = null_out())
print("\nScore for no sharpening: %7.2f " %(local_si.score), file = out)
else:
local_si = None
print(80*"=", file = out)
print("\nApplying final sharpening to entire map", file = out)
print(80*"=", file = out)
si.sharpen_and_score_map(map_data = working_map, set_b_iso = True, out = out)
if si.discard_if_worse and local_si and local_si.score > si.score:
print("Sharpening did not improve map "+\
"(%7.2f sharpened, %7.2f unsharpened). Discarding sharpened map" %(
si.score, local_si.score), file = out)
print("\nUse discard_if_worse = False to keep the sharpening", file = out)
local_si.sharpen_and_score_map(map_data = working_map, out = out)
si = local_si
if not si.is_model_sharpening() and not si.is_half_map_sharpening():
si.show_score(out = out)
si.show_summary(out = out)
return si # si.map_data is the sharpened map
def estimate_signal_to_noise(value_list = None, minimum_value_to_include = 0):
# get "noise" from rms value of value_list(n) compared with average of n-2, n-1, n+1, n+2
# assumes middle is the high part of the very smooth curve.
# Don't include values < minimum_value_to_include
mean_square_diff = 0.
mean_square_diff_n = 0.
for b2, b1, value, p1, p2 in zip(value_list,
value_list[1:],
value_list[2:],
value_list[3:],
value_list[4:]):
too_low = False
for xx in [b2, b1, value, p1, p2]:
if xx <minimum_value_to_include:
too_low = True
if not too_low:
mean_square_diff_n+= 1
mean_square_diff+= ( (b2+b1+p1+p2)*0.25 - value)**2
rmsd = (mean_square_diff/max(1, mean_square_diff_n))**0.5
if value_list.size()>0:
min_adj_sa = max(value_list[0], value_list[-1])
max_adj_sa = value_list.min_max_mean().max
signal_to_noise = (max_adj_sa-min_adj_sa)/max(1.e-10, rmsd)
else:
signal_to_noise = 0.
return signal_to_noise
def optimize_b_blur_or_d_cut_or_b_iso(
optimization_target = 'b_blur_hires',
local_best_si = None,
local_best_map_and_b = None,
si_id_list = None,
si_score_list = None,
delta_b = None,
original_b_iso = None,
f_array = None,
phases = None,
delta_b_blur_hires = 100,
delta_d_cut = 0.25,
n_cycle_optimize = 5,
min_cycles = 2,
n_range = 5,
out = sys.stdout):
assert optimization_target in ['b_blur_hires', 'd_cut', 'b_iso']
if optimization_target == 'b_blur_hires':
print("\nOptimizing b_blur_hires. ", file = out)
elif optimization_target == 'd_cut':
print("\nOptimizing d_cut. ", file = out)
local_best_si.input_d_cut = local_best_si.get_d_cut()
elif optimization_target == 'b_iso':
print("\nOptimizing b_iso. ", file = out)
local_best_si.show_summary(out = out)
print("Current best score = %7.3f b_iso = %5.1f b_blur_hires = %5.1f d_cut = %5.1f" %(
local_best_si.score, local_best_si.b_iso,
local_best_si.b_blur_hires,
local_best_si.get_d_cut()), file = out)
# existing values:
value_dict = {}
for id, score in zip(si_id_list, si_score_list):
value_dict[id] = score
best_score = local_best_si.score
delta_b_iso = delta_b
local_best_score = best_score
improving = True
working_best_si = deepcopy(local_best_si)
for cycle in range(n_cycle_optimize):
if not improving: break
print("Optimization cycle %s" %(cycle), file = out)
print("Current best score = %7.3f b_iso = %5.1f b_blur_hires = %5.1f d_cut = %5.1f" %(
working_best_si.score, working_best_si.b_iso,
working_best_si.b_blur_hires,
working_best_si.get_d_cut()), file = out)
if working_best_si.verbose:
print(" B-sharpen B-iso B-blur Adj-SA "+\
"Kurtosis SA-ratio Regions d_cut b_blur_hires", file = out)
local_best_working_si = deepcopy(working_best_si)
improving = False
for jj in range(-n_range, n_range+1):
if optimization_target == 'b_blur_hires': # try optimizing b_blur_hires
test_b_blur_hires = max(0., working_best_si.b_blur_hires+jj*delta_b_blur_hires)
test_d_cut = working_best_si.get_d_cut()
test_b_iso = working_best_si.b_iso
elif optimization_target == 'd_cut':
test_b_blur_hires = working_best_si.b_blur_hires
test_d_cut = working_best_si.get_d_cut()+jj*delta_d_cut
test_b_iso = working_best_si.b_iso
elif optimization_target == 'b_iso':
test_b_blur_hires = working_best_si.b_blur_hires
test_d_cut = working_best_si.get_d_cut()
test_b_iso = working_best_si.b_iso+jj*delta_b_iso
id = "%.3f_%.3f_%.3f" %(test_b_iso, test_b_blur_hires, test_d_cut)
if id in value_dict:
score = value_dict[id]
else:
local_si = deepcopy(local_best_si)
local_f_array = f_array
local_phases = phases
local_si.b_blur_hires = test_b_blur_hires
local_si.input_d_cut = test_d_cut
local_si.b_iso = test_b_iso
local_si.b_sharpen = original_b_iso-local_si.b_iso
local_map_and_b = apply_sharpening(
f_array = local_f_array, phases = local_phases,
sharpening_info_obj = local_si,
crystal_symmetry = local_si.crystal_symmetry,
out = null_out())
local_si = score_map(
map_data = local_map_and_b.map_data, sharpening_info_obj = local_si,
out = null_out())
value_dict[id] = local_si.score
if local_si.verbose:
print(" %6.1f %6.1f %5s %7.3f %7.3f" %(
local_si.b_sharpen, local_si.b_iso,
local_si.b_blur_hires,
local_si.adjusted_sa, local_si.kurtosis) + \
" %7.1f %7.3f %7.3f %7.3f " %(
zero_if_none(local_si.adjusted_path_length), #local_si.sa_ratio,
local_si.normalized_regions,
test_d_cut,
test_b_blur_hires
), file = out)
if local_si.score > local_best_score:
local_best_score = local_si.score
local_best_working_si = deepcopy(local_si)
if local_best_score > best_score:
best_score = local_best_score
working_best_si = deepcopy(local_best_working_si)
delta_b_iso = delta_b_iso/2
delta_b_blur_hires = delta_b_blur_hires/2
delta_d_cut = delta_d_cut/2
print("Current working best "+\
"score = %7.3f b_iso = %5.1f b_blur_hires = %5.1f d_cut = %5.1f" %(
working_best_si.score, working_best_si.b_iso,
working_best_si.b_blur_hires,
working_best_si.get_d_cut()), file = out)
improving = True
if working_best_si and working_best_si.score > local_best_si.score:
print("Using new values of b_iso and b_blur_hires and d_cut", file = out)
local_best_si = working_best_si
local_best_si.show_summary(out = out)
return local_best_si, local_best_map_and_b
def set_mean_sd_of_map(map_data = None, target_mean = None, target_sd = None):
if not map_data: return None
new_mean = map_data.as_1d().min_max_mean().mean
new_sd = max(1.e-10, map_data.sample_standard_deviation())
map_data = (map_data-new_mean)/new_sd # normalized
return map_data*target_sd + target_mean # restore original
def run_auto_sharpen(
si = None,
map_data = None,
first_half_map_data = None,
second_half_map_data = None,
pdb_inp = None,
auto_sharpen_methods = None,
print_result = True,
return_bsi = False,
out = sys.stdout):
if si.verbose:
local_out = out
else:
local_out = null_out()
# Identifies parameters for optimal map sharpening using analysis of density,
# model-correlation, or half-map correlation (first_half_map_data vs
# vs second_half_map_data).
# NOTE: We can apply this to any map_data (a part or whole of the map)
# BUT: need to update n_real if we change the part of the map!
# change with map data: crystal_symmetry, solvent_fraction, n_real, wrapping,
smoothed_box_mask_data = None
original_box_map_data = None
if si.auto_sharpen and (
si.box_in_auto_sharpen or si.density_select_in_auto_sharpen or pdb_inp):
original_box_sharpening_info_obj = deepcopy(si) # should really not be box
box_pdb_inp, box_map_data, box_first_half_map_data, \
box_second_half_map_data, \
box_crystal_symmetry, box_sharpening_info_obj, \
smoothed_box_mask_data, original_box_map_data, n_buffer = \
select_box_map_data(si = si,
map_data = map_data,
first_half_map_data = first_half_map_data,
second_half_map_data = second_half_map_data,
pdb_inp = pdb_inp,
restrict_map_size = si.restrict_map_size,
out = out, local_out = local_out)
if box_sharpening_info_obj is None: # did not do it
print("Box map is similar in size to entire map..."+\
"skipping representative box of density", file = out)
original_box_sharpening_info_obj = None
crystal_symmetry = si.crystal_symmetry
else:
print("Using small map to identify optimal sharpening", file = out)
print("Box map grid: %d %d %d" %(
box_map_data.all()), file = out)
print("Box map cell: %7.2f %7.2f %7.2f %7.2f %7.2f %7.2f "%(
box_crystal_symmetry.unit_cell().parameters()), file = out)
original_map_data = map_data
original_crystal_symmetry = si.crystal_symmetry
map_data = box_map_data
pdb_inp = box_pdb_inp
if si.density_select_in_auto_sharpen and ( # catch empty pdb_inp
not pdb_inp or not \
pdb_inp.construct_hierarchy().overall_counts().n_residues):
pdb_inp = None
crystal_symmetry = box_crystal_symmetry
if box_first_half_map_data:
first_half_map_data = box_first_half_map_data
if box_second_half_map_data:
second_half_map_data = box_second_half_map_data
# SET si for box now...
si = deepcopy(si).update_with_box_sharpening_info(
box_sharpening_info_obj = box_sharpening_info_obj)
else:
original_box_sharpening_info_obj = None
box_sharpening_info_obj = None
crystal_symmetry = si.crystal_symmetry
starting_mean = map_data.as_1d().min_max_mean().mean
starting_sd = map_data.sample_standard_deviation()
print("\nGetting original b_iso...", file = out)
map_coeffs_aa, map_coeffs, f_array, phases = effective_b_iso(
map_data = map_data,
resolution = si.resolution,
d_min_ratio = si.d_min_ratio,
scale_max = si.scale_max,
remove_aniso = si.remove_aniso,
crystal_symmetry = si.crystal_symmetry,
out = out)
original_b_iso = map_coeffs_aa.b_iso
if original_b_iso is None:
print("Could not determine original b_iso...setting to 200", file = out)
original_b_iso = 200.
si.original_aniso_obj = map_coeffs_aa # set it so we can apply it later if desired
if first_half_map_data:
first_half_map_coeffs, dummy = get_f_phases_from_map(
map_data = first_half_map_data,
crystal_symmetry = si.crystal_symmetry,
d_min = si.resolution,
d_min_ratio = si.d_min_ratio,
remove_aniso = si.remove_aniso,
scale_max = si.scale_max,
return_as_map_coeffs = True,
out = local_out)
else:
first_half_map_coeffs = None
if second_half_map_data:
second_half_map_coeffs, dummy = get_f_phases_from_map(
map_data = second_half_map_data,
crystal_symmetry = si.crystal_symmetry,
d_min = si.resolution,
d_min_ratio = si.d_min_ratio,
scale_max = si.scale_max,
remove_aniso = si.remove_aniso,
return_as_map_coeffs = True,
out = local_out)
else:
second_half_map_coeffs = None
if pdb_inp:
# Getting model information if pdb_inp present ---------------------------
from cctbx.maptbx.refine_sharpening import get_model_map_coeffs_normalized
model_map_coeffs = get_model_map_coeffs_normalized(pdb_inp = pdb_inp,
si = si,
f_array = f_array,
resolution = si.resolution,
out = out)
if not model_map_coeffs: # give up
pdb_inp = None
if si.is_model_sharpening():
raise Sorry("Cannot carry out model sharpening without a model."+
" It could be that the model was outside the map")
else:
model_map_coeffs = None
# Try various methods for sharpening. # XXX fix this up
local_si = deepcopy(si).update_with_box_sharpening_info(
box_sharpening_info_obj = box_sharpening_info_obj)
if si.adjust_region_weight and \
(not si.sharpening_is_defined()) and (not si.is_model_sharpening()) \
and (not si.is_half_map_sharpening()) and (
not si.is_target_b_iso_to_d_cut()) and (
si.sharpening_target == 'adjusted_sa'):
for iii in range(1): # just so we can break
local_si = deepcopy(si).update_with_box_sharpening_info(
box_sharpening_info_obj = box_sharpening_info_obj)
local_si.sharpening_target = 'adjusted_sa'
local_si.sharpening_method = 'b_iso_to_d_cut'
sa_ratio_list = []
normalized_regions_list = []
if 0: #si.resolution:
# 2017-07-26 reset b_low, b_mid, b_high, using 5.9*resolution**2 for b_mid
delta_search = si.search_b_max-si.search_b_min
b_mid = si.get_target_b_iso()
b_low = b_mid-150*delta_search/400
b_high = b_mid+250*delta_search/400
print("Centering search on b_iso = %7.2f" %(b_mid), file = out)
else:
b_low = min(original_b_iso, si.search_b_min)
b_high = max(original_b_iso, si.search_b_max)
b_mid = b_low+0.375*(b_high-b_low)
ok_region_weight = True
results_list = []
kw_list = []
first = True
id = 0
for b_iso in [b_low, b_high, b_mid]:
id+= 1
if first and local_si.multiprocessing == 'multiprocessing' or \
local_si.nproc == 1: # can do anything
local_log = out
else: # skip log entirely
local_log = None # will set this later and return as r.log_as_text
first = False
lsi = deepcopy(local_si)
lsi.b_sharpen = original_b_iso-b_iso
lsi.b_iso = b_iso
# ------ SET UP RUN HERE ----------
kw_list.append(
{
'f_array':f_array,
'phases':phases,
'crystal_symmetry':lsi.crystal_symmetry,
'local_si':lsi,
'id':id,
'out':local_log,
})
# We are going to call autosharpening with this
# ------ END OF SET UP FOR RUN ----------
"""
local_map_and_b = apply_sharpening(
f_array = f_array, phases = phases,
sharpening_info_obj = lsi,
crystal_symmetry = lsi.crystal_symmetry,
out = null_out())
local_si = score_map(map_data = local_map_and_b.map_data,
sharpening_info_obj = local_si,
out = null_out())
"""
# This is the actual run here =============
from libtbx.easy_mp import run_parallel
results_list = run_parallel(
method = si.multiprocessing,
qsub_command = si.queue_run_command,
nproc = si.nproc,
target_function = run_sharpen_and_score, kw_list = kw_list)
# results looks like: [result, result2]
sort_list = []
for result in results_list:
sort_list.append([result.id, result])
sort_list.sort(key=itemgetter(0))
for id, result in sort_list:
local_si = result.local_si
if local_si.sa_ratio is None or local_si.normalized_regions is None:
ok_region_weight = False
sa_ratio_list.append(local_si.sa_ratio)
normalized_regions_list.append(local_si.normalized_regions)
if not ok_region_weight:
break # skip it
# Set region weight so that either:
# (1) delta_sa_ratio == region_weight*delta_normalized_regions
# (2) sa_ratio = region_weight*normalized_regions (at low B)
# region weight from change over entire region
d_sa_ratio = sa_ratio_list[0]-sa_ratio_list[1]
d_normalized_regions = normalized_regions_list[0]-normalized_regions_list[1]
delta_region_weight = si.region_weight_factor*d_sa_ratio/max(
1.e-10, d_normalized_regions)
if d_sa_ratio < 0 or d_normalized_regions < 0:
print("Not using delta_region_weight with unusable values", file = out)
ok_region_weight = False
# region weight from initial values
init_region_weight = si.region_weight_factor* \
sa_ratio_list[0]/max(1.e-10, normalized_regions_list[0])
# Ensure that adjusted_sa at b_mid is > than either end
# adjusted_sa = sa_ratio - region_weight*normalized_regions
# sa[2] = sa_ratio_list[2]-region_weight*normalized_regions[2]
# sa[1] = sa_ratio_list[1]-region_weight*normalized_regions[1]
# sa[0] = sa_ratio_list[0]-region_weight*normalized_regions[0]
# sa[2] >= sa[1] and sa[2] >= sa[0]
# sa_ratio_list[2]-region_weight*normalized_regions[2] >=
# sa_ratio_list[1]-region_weight*normalized_regions[1]
# NOTE: sa_ratio_list and normalized_regions both decrease in order:
# low med high or [0] [2] [1]
max_region_weight = (sa_ratio_list[2]- sa_ratio_list[1])/max(0.001,
normalized_regions_list[2]-normalized_regions_list[1])
min_region_weight = (sa_ratio_list[0]- sa_ratio_list[2])/max(0.001,
normalized_regions_list[0]-normalized_regions_list[2])
min_region_weight = max(1.e-10, min_region_weight) # positive
max_region_weight = max(1.e-10, max_region_weight) # positive
delta_weight = max(0., max_region_weight-min_region_weight)
min_buffer = delta_weight*si.region_weight_buffer
min_region_weight+= min_buffer
max_region_weight-= min_buffer
min_max_region_weight = True
if min_region_weight >= max_region_weight:
print("Warning: min_region_weight >= max_region_weight...", file = out)
min_max_region_weight = False
#ok_region_weight = False
print("Region weight bounds: Min: %7.1f Max: %7.1f " %(
min_region_weight, max_region_weight), file = out)
print("Region weight estimates:", file = out)
print("From ratio of low-B surface area to regions: %7.1f" %(
init_region_weight), file = out)
print("Ratio of change in surface area to change in regions: %7.1f" %(
delta_region_weight), file = out)
# put them in bounds but note if we did it
out_of_range = False
if ok_region_weight and si.region_weight_method == 'initial_ratio':
if min_max_region_weight and (
init_region_weight > max_region_weight or \
init_region_weight<min_region_weight):
init_region_weight = max(
min_region_weight, min(max_region_weight, init_region_weight))
out_of_range = True
print("\nRegion weight adjusted to %7.1f using initial ratio" %(
init_region_weight), file = out)
si.region_weight = init_region_weight
elif ok_region_weight and si.region_weight_method == 'delta_ratio':
if min_max_region_weight and (
delta_region_weight > max_region_weight or \
delta_region_weight<min_region_weight):
delta_region_weight = max(
min_region_weight, min(max_region_weight, delta_region_weight))
out_of_range = True
si.region_weight = delta_region_weight
print("\nRegion weight set to %7.1f using overall ratio and " %(
si.region_weight) +\
"\nfactor of %5.1f" %(si.region_weight_factor), file = out)
else: # just use default target for b_iso
si.region_weight = si.region_weight_default
print("Skipping region_weight analysis as signal-to-noise is zero ("+\
"adjusted sa\nvs b_iso does not have low values at extremes and "+\
"clear maximum in the middle.)", file = out)
print("\nUnable to set region_weight ... using value of %7.2f" % (
si.region_weight), file = out)
if si.discard_if_worse:
print("Setting discard_if_worse = False as region_weight failed ", file = out)
si.discard_if_worse = False
if out_of_range and auto_sharpen_methods and \
'resolution_dependent' in auto_sharpen_methods:
new_list = []
have_something_left = False
for x in auto_sharpen_methods:
if x != 'resolution_dependent':
if str(x) != 'None':
have_something_left = True
new_list.append(x)
if have_something_left:
auto_sharpen_methods = new_list
print("Removed resolution_dependent sharpening ( "+\
"weights were out of range)", file = out)
if box_sharpening_info_obj:
si.local_solvent_fraction = box_sharpening_info_obj.solvent_fraction
else:
si.local_solvent_fraction = si.solvent_fraction
null_si = None
best_si = deepcopy(si).update_with_box_sharpening_info(
box_sharpening_info_obj = box_sharpening_info_obj)
best_map_and_b = map_and_b_object()
if si.sharpening_is_defined(): # Use this if come in with method
print("\nUsing specified sharpening", file = out)
best_si = set_up_sharpening(si = si, map_data = map_data, out = out)
best_si.sharpen_and_score_map(map_data = map_data,
out = out).show_score(out = out)
best_si.show_summary(out = out)
else:
if best_si.is_model_sharpening():
print("\nSetting up model sharpening", file = out)
elif best_si.is_half_map_sharpening():
print("\nSetting up half-map sharpening", file = out)
elif best_si.is_external_map_sharpening():
print("\nSetting up external map sharpening", file = out)
else:
print("\nTesting sharpening methods with target of %s" %(
best_si.sharpening_target), file = out)
if not auto_sharpen_methods or auto_sharpen_methods == ['None']:
auto_sharpen_methods = ['no_sharpening']
for m in auto_sharpen_methods:
# ------------------------
if m in ['no_sharpening', 'resolution_dependent', 'model_sharpening',
'half_map_sharpening', 'target_b_iso_to_d_cut',
'external_map_sharpening']:
if m == 'target_b_iso_to_d_cut':
b_min = si.get_target_b_iso()
b_max = si.get_target_b_iso()
else:
b_min = original_b_iso
b_max = original_b_iso
b_n = 1
k_sharpen = 0.
delta_b = 0
if m in ['resolution_dependent', 'model_sharpening',
'half_map_sharpening', 'external_map_sharpening']:
pass # print out later
else:
print("\nB-sharpen B-iso k_sharpen SA "+\
"Kurtosis Path len Normalized regions", file = out)
# ------------------------
# ------------------------
else: # ['b_iso', 'b_iso_to_d_cut']:
if si.search_b_n>1:
b_min = min(original_b_iso, si.search_b_min)
b_max = max(original_b_iso, si.search_b_max)
else: # for just one, take it
b_min = si.search_b_min
b_max = si.search_b_max
b_n = si.search_b_n
delta_b = (b_max-b_min)/max(1, b_n-1)
print("\nTesting %s with b_iso from %7.1f to %7.1f in %d steps of %7.1f" %(
m, b_min, b_max, b_n, delta_b), file = out)
print("(b_sharpen from %7.1f to %7.1f ) " %(
original_b_iso-b_min, original_b_iso-b_max), file = out)
if m == 'b_iso':
k_sharpen = 0.
else:
k_sharpen = si.k_sharpen
print("\nB-sharpen B-iso k_sharpen SA "+\
"Kurtosis Path len Normalized regions", file = out)
# ------------------------
local_best_map_and_b = map_and_b_object()
local_best_si = deepcopy(si).update_with_box_sharpening_info(
box_sharpening_info_obj = box_sharpening_info_obj)
si_b_iso_list = flex.double()
si_score_list = flex.double()
si_id_list = []
kw_list = []
first = True
if return_bsi: assert local_si.nproc == 1
results_list = []
for i in range(b_n):
#============================================
local_si = deepcopy(si).update_with_box_sharpening_info(
box_sharpening_info_obj = box_sharpening_info_obj)
local_si.sharpening_method = m
local_si.n_real = map_data.all()
local_si.k_sharpen = k_sharpen
if first and local_si.multiprocessing == 'multiprocessing' or \
local_si.nproc == 1: # can do anything
local_log = out
else: # skip log entirely
local_log = None # will set this later and return as r.log_as_text
first = False
if m == 'resolution_dependent':
print("\nRefining resolution-dependent sharpening based on %s" %(
local_si.residual_target), file = out)
local_si.b_sharpen = 0
local_si.b_iso = original_b_iso
from cctbx.maptbx.refine_sharpening import run as refine_sharpening
local_f_array, local_phases = refine_sharpening(
map_coeffs = map_coeffs,
sharpening_info_obj = local_si,
out = out)
elif m == 'model_sharpening':
print("\nUsing model-based sharpening", file = out)
local_si.b_sharpen = 0
local_si.b_iso = original_b_iso
from cctbx.maptbx.refine_sharpening import scale_amplitudes
scale_amplitudes(
model_map_coeffs = model_map_coeffs, map_coeffs = map_coeffs,
si = local_si, out = out)
# local_si contains target_scale_factors now
local_f_array = f_array
local_phases = phases
elif m == 'half_map_sharpening':
print("\nUsing half-map-based sharpening", file = out)
local_si.b_sharpen = 0
local_si.b_iso = original_b_iso
from cctbx.maptbx.refine_sharpening import scale_amplitudes
scale_amplitudes(
model_map_coeffs = model_map_coeffs,
map_coeffs = map_coeffs,
first_half_map_coeffs = first_half_map_coeffs,
second_half_map_coeffs = second_half_map_coeffs,
si = local_si, out = out)
# local_si contains target_scale_factors now
local_f_array = f_array
local_phases = phases
elif m == 'external_map_sharpening':
print("\nUsing external-map-based sharpening", file = out)
local_si.b_sharpen = 0
local_si.b_iso = original_b_iso
from cctbx.maptbx.refine_sharpening import scale_amplitudes
scale_amplitudes(
model_map_coeffs = model_map_coeffs,
map_coeffs = map_coeffs,
external_map_coeffs = first_half_map_coeffs,
si = local_si, out = out)
# local_si contains target_scale_factors now
local_f_array = f_array
local_phases = phases
else:
local_f_array = f_array
local_phases = phases
b_iso = b_min+i*delta_b
local_si.b_sharpen = original_b_iso-b_iso
local_si.b_iso = b_iso
# ------ SET UP RUN HERE ----------
kw_list.append(
{
'f_array':local_f_array,
'phases':local_phases,
'crystal_symmetry':local_si.crystal_symmetry,
'original_b_iso':original_b_iso,
'local_si':local_si,
'm':m,
'return_bsi':return_bsi,
'out':local_log,
'id':i+1,
})
# We are going to call autosharpening with this
# ------ END OF SET UP FOR RUN ----------
# This is the actual run here =============
from libtbx.easy_mp import run_parallel
results_list = run_parallel(
method = si.multiprocessing,
qsub_command = si.queue_run_command,
nproc = si.nproc,
target_function = run_sharpen_and_score, kw_list = kw_list)
# results looks like: [result, result2]
sort_list = []
for result in results_list:
sort_list.append([result.id, result])
sort_list.sort(key=itemgetter(0))
for id, result in sort_list:
local_si = result.local_si
local_map_and_b = result.local_map_and_b
if result.text:
print(result.text, file = out)
# Run through all result to get these
if local_si.b_sharpen is not None and local_si.b_iso is not None and\
local_si.k_sharpen is not None and local_si.kurtosis is not None \
and local_si.adjusted_sa is not None and local_si.score is not None:
si_b_iso_list.append(local_si.b_iso)
si_score_list.append(local_si.score)
if local_si.k_sharpen is not None:
si_id_list.append("%.3f_%.3f_%.3f" %(
local_si.b_iso, local_si.k_sharpen,
local_si.get_d_cut()))
if m == 'no_sharpening':
null_si = local_si
if local_best_si.score is None or local_si.score>local_best_si.score:
local_best_si = local_si
local_best_map_and_b = local_map_and_b
# ============================================
# DONE WITH ALL RUNS
if not local_best_si.is_model_sharpening() and \
not local_best_si.is_half_map_sharpening():
if local_best_si.sharpening_method == 'resolution_dependent':
print("\nBest scores for sharpening with "+\
"b[0] = %6.2f b[1] = %6.2f b[2] = %6.2f: " %(
local_best_si.resolution_dependent_b[0],
local_best_si.resolution_dependent_b[1],
local_best_si.resolution_dependent_b[2]), file = out)
else:
print("\nBest scores for sharpening with "+\
"b_iso = %6.1f b_sharpen = %6.1f k_sharpen = %s: " %(
local_best_si.b_iso, local_best_si.b_sharpen,
local_best_si.k_sharpen), file = out)
if local_best_si.score is not None:
local_best_si.show_summary(out = out)
print("Adjusted surface area: %7.3f Kurtosis: %7.3f Score: %7.3f\n" %(
local_best_si.adjusted_sa, local_best_si.kurtosis, local_best_si.score), file = out)
if si_score_list.size()>1: # test for signal
signal_to_noise = estimate_signal_to_noise(value_list = si_score_list)
print("Estimated signal-to-noise in ID of optimal sharpening: %5.1f" %(
signal_to_noise), file = out)
if signal_to_noise<local_best_si.signal_min and \
'target_b_iso_to_d_cut' in auto_sharpen_methods:
print("Skipping this analysis as signal-to-noise is less than %5.1f " %(
local_best_si.signal_min), file = out)
local_best_si.score = None
optimize_b_blur_hires = False
optimize_d_cut = False
n_cycles = 0
if local_best_si.score is not None and local_best_si.optimize_d_cut and \
local_best_si.sharpening_method in ['b_iso_to_d_cut', 'b_iso']:
optimize_d_cut = True
n_cycles+= 1
if local_best_si.score is not None and \
local_best_si.optimize_b_blur_hires and \
local_best_si.k_sharpen is not None and \
local_best_si.sharpening_method in ['b_iso_to_d_cut', 'b_iso']:
optimize_b_blur_hires = True
n_cycles+= 1
##########################################
optimize_b_iso = True
for cycle in range(n_cycles):
if optimize_b_blur_hires:
local_best_si, local_best_map_and_b = optimize_b_blur_or_d_cut_or_b_iso(
#optimization_target = 'k_sharpen',
optimization_target = 'b_blur_hires',
local_best_si = local_best_si,
local_best_map_and_b = local_best_map_and_b,
si_id_list = si_id_list,
si_score_list = si_score_list,
delta_b = delta_b,
original_b_iso = original_b_iso,
f_array = f_array,
phases = phases,
out = out)
if optimize_d_cut:
local_best_si, local_best_map_and_b = optimize_b_blur_or_d_cut_or_b_iso(
optimization_target = 'd_cut',
local_best_si = local_best_si,
local_best_map_and_b = local_best_map_and_b,
si_id_list = si_id_list,
si_score_list = si_score_list,
delta_b = delta_b,
original_b_iso = original_b_iso,
f_array = f_array,
phases = phases,
out = out)
if optimize_b_iso:
local_best_si, local_best_map_and_b = optimize_b_blur_or_d_cut_or_b_iso(
optimization_target = 'b_iso',
local_best_si = local_best_si,
local_best_map_and_b = local_best_map_and_b,
si_id_list = si_id_list,
si_score_list = si_score_list,
delta_b = delta_b,
original_b_iso = original_b_iso,
f_array = f_array,
phases = phases,
out = out)
##########################################
if (local_best_si.score is not None or
local_best_si.is_model_sharpening()) and (
best_si.score is None or local_best_si.score > best_si.score):
best_si = local_best_si
best_map_and_b = local_best_map_and_b
if not best_si.is_model_sharpening() and \
not best_si.is_half_map_sharpening():
print("This is the current best score\n", file = out)
if (best_si.score is not None ) and (
not best_si.is_model_sharpening() ) and (not best_si.is_half_map_sharpening()):
print("\nOverall best sharpening method: %s Score: %7.3f\n" %(
best_si.sharpening_method, best_si.score), file = out)
best_si.show_summary(out = out)
if (not best_si.is_model_sharpening()) and \
(not best_si.is_half_map_sharpening()) and null_si:
if best_si.score>null_si.score: # we improved them..
print("Improved score with sharpening...", file = out)
else:
print("Did not improve score with sharpening...", file = out)
if return_bsi:
map_data = best_map_and_b.map_data
map_data = set_mean_sd_of_map(map_data = map_data,
target_mean = starting_mean, target_sd = starting_sd)
box_sharpening_info_obj.map_data = map_data
box_size= map_data.all()
calculated_box_size=tuple([i-j+1 for i,j in zip(
box_sharpening_info_obj.upper_bounds,
box_sharpening_info_obj.lower_bounds)])
calculated_box_size_minus_one=tuple([i-j for i,j in zip(
box_sharpening_info_obj.upper_bounds,
box_sharpening_info_obj.lower_bounds)])
if calculated_box_size_minus_one == box_size: # one too big
box_sharpening_info_obj.upper_bounds =tuple(
[i-1 for i in box_sharpening_info_obj.upper_bounds]
) # work-around for upper bounds off by one in model sharpening
box_sharpening_info_obj.smoothed_box_mask_data = smoothed_box_mask_data
box_sharpening_info_obj.original_box_map_data = original_box_map_data
box_sharpening_info_obj.n_buffer = n_buffer
box_sharpening_info_obj.crystal_symmetry = best_si.crystal_symmetry
box_sharpening_info_obj.resolution = best_si.resolution
box_sharpening_info_obj.d_min_ratio = best_si.d_min_ratio
box_sharpening_info_obj.scale_max = best_si.scale_max
box_sharpening_info_obj.smoothing_radius = best_si.smoothing_radius
box_sharpening_info_obj.b_iso = best_map_and_b.final_b_iso
box_sharpening_info_obj.starting_b_iso = best_map_and_b.starting_b_iso
return box_sharpening_info_obj
if original_box_sharpening_info_obj:
# Put back original crystal_symmetry with original_box_sharpening_info_obj
print("\nRestoring original symmetry to best sharpening info", file = out)
best_si.update_with_box_sharpening_info(
box_sharpening_info_obj = original_box_sharpening_info_obj)
print("(%7.3f, %7.3f, %7.3f, %7.3f, %7.3f, %7.3f) "%(tuple(
best_si.crystal_symmetry.unit_cell().parameters())), file = out)
# and set tracking data with result
return best_si
def run_sharpen_and_score(f_array = None,
phases = None,
local_si = None,
crystal_symmetry = None,
original_b_iso = None,
m = None,
return_bsi = None,
id = None,
out = sys.stdout):
local_map_and_b = apply_sharpening(
f_array = f_array, phases = phases,
sharpening_info_obj = local_si,
crystal_symmetry = crystal_symmetry,
out = null_out())
local_si = score_map(map_data = local_map_and_b.map_data,
sharpening_info_obj = local_si,
out = null_out())
# Record b_iso values
if not local_map_and_b.starting_b_iso:
local_map_and_b.starting_b_iso = original_b_iso
if not local_map_and_b.final_b_iso:
local_map_and_b.final_b_iso = local_si.b_iso
# This is printout below here ===============
if m == 'resolution_dependent':
text = \
"\nb[0] b[1] b[2] SA Kurtosis sa_ratio Normalized regions"
text+= "\n"+\
"\nB-sharpen B-iso k_sharpen SA "+\
"Kurtosis Path len Normalized regions"
text+= "\n"+" %6.2f %6.2f %6.2f " %(
local_si.resolution_dependent_b[0],
local_si.resolution_dependent_b[1],
local_si.resolution_dependent_b[2]) +\
" %7.3f %7.3f " %(
local_si.adjusted_sa, local_si.kurtosis)+\
" %7.1f %7.3f" %(
zero_if_none(local_si.adjusted_path_length), #local_si.sa_ratio,
local_si.normalized_regions)
elif local_si.b_sharpen is not None and local_si.b_iso is not None and\
local_si.k_sharpen is not None and local_si.kurtosis is not None \
and local_si.adjusted_sa is not None:
text = \
" %6.1f %6.1f %5s %7.3f %7.3f" %(
local_si.b_sharpen, local_si.b_iso,
local_si.k_sharpen, local_si.adjusted_sa, local_si.kurtosis) + \
" %7.1f %7.3f" %(
zero_if_none(local_si.adjusted_path_length), #local_si.sa_ratio,
local_si.normalized_regions)
else:
text = ""
if return_bsi:
r = group_args(
local_si = local_si,
local_map_and_b = local_map_and_b,
text = text,
id = id)
else:
r = group_args(
local_si = local_si,
local_map_and_b = None,
text = text,
id = id)
return r
def effective_b_iso(map_data = None, tracking_data = None,
box_sharpening_info_obj = None,
crystal_symmetry = None,
resolution = None,
remove_aniso = None,
d_min_ratio = None,
scale_max = None,
out = sys.stdout):
if not crystal_symmetry:
if box_sharpening_info_obj:
crystal_symmetry = box_sharpening_info_obj.crystal_symmetry
else:
crystal_symmetry = tracking_data.crystal_symmetry
if resolution:
d_min = resolution
else:
d_min = tracking_data.params.crystal_info.resolution
if not d_min_ratio:
d_min_ratio = tracking_data.params.map_modification.d_min_ratio
map_coeffs, map_coeffs_ra = get_f_phases_from_map(map_data = map_data,
crystal_symmetry = crystal_symmetry,
d_min = d_min,
d_min_ratio = d_min_ratio,
scale_max = scale_max,
remove_aniso = remove_aniso,
return_as_map_coeffs = True,
out = out)
f_array, phases = map_coeffs_as_fp_phi(map_coeffs)
if map_coeffs_ra:
b_iso = map_coeffs_ra.b_iso
else:
b_iso = None
if b_iso is not None:
print("Effective B-iso = %7.2f\n" %(b_iso), file = out)
else:
print("Effective B-iso not determined\n", file = out)
return map_coeffs_ra, map_coeffs, f_array, phases
def update_tracking_data_with_sharpening(map_data = None, tracking_data = None,
si = None, out = sys.stdout):
# Set shifted_map_info if map_data is new
if tracking_data.params.output_files.shifted_sharpened_map_file:
shifted_sharpened_map_file = os.path.join(
tracking_data.params.output_files.output_directory,
tracking_data.params.output_files.shifted_sharpened_map_file)
else:
shifted_sharpened_map_file = None
from cctbx.maptbx.segment_and_split_map import write_ccp4_map
if shifted_sharpened_map_file:
write_ccp4_map(tracking_data.crystal_symmetry,
shifted_sharpened_map_file, map_data)
print("Wrote shifted, sharpened map to %s" %(
shifted_sharpened_map_file), file = out)
tracking_data.set_shifted_map_info(file_name =
shifted_sharpened_map_file,
crystal_symmetry = tracking_data.crystal_symmetry,
origin = map_data.origin(),
all = map_data.all(),
b_sharpen = None)
def get_high_points_from_map(
map_data = None,
boundary_radius = 5.,
unit_cell = None,
out = sys.stdout):
max_in_map_data = map_data.as_1d().min_max_mean().max
for cutoff in [0.99, 0.98, 0.95, 0.90, 0.50]:
high_points_mask = (map_data>= cutoff*max_in_map_data)
sda = map_data.as_1d().min_max_mean().max
for nth_point in [4, 2, 1]:
sites_cart = get_marked_points_cart(mask_data = high_points_mask,
unit_cell = unit_cell, every_nth_point = nth_point,
boundary_radius = boundary_radius)
if sites_cart.size()>0: break
if sites_cart.size()>0: break
assert sites_cart.size()>0
del high_points_mask
sites_cart = sites_cart[:1]
xyz_frac = unit_cell.fractionalize(sites_cart[0])
value = map_data.value_at_closest_grid_point(xyz_frac)
print("High point in map at (%7.2f %7.2f %7.2f) with value of %7.2f " %(
sites_cart[0][0], sites_cart[0][1], sites_cart[0][2], value), file = out)
return sites_cart
def get_one_au(tracking_data = None,
sites_cart = None,
ncs_obj = None,
map_data = None,
starting_mask = None,
radius = None,
every_nth_point = None,
removed_ncs = None,
out = sys.stdout):
unit_cell = tracking_data.crystal_symmetry.unit_cell()
if removed_ncs: # take everything left
mm = map_data.as_1d().min_max_mean()
mask_threshold = mm.min+max(0.00001, 0.0001*(mm.mean-mm.min)) # just above min
else:
mask_threshold = tracking_data.params.segmentation.mask_threshold
every_nth_point = tracking_data.params.segmentation.grid_spacing_for_au
radius = tracking_data.params.segmentation.radius
if not radius:
radius = set_radius(unit_cell = unit_cell, map_data = map_data,
every_nth_point = every_nth_point)
tracking_data.params.segmentation.radius = radius
print("\nRadius for AU identification: %7.2f A" %(radius), file = out)
overall_mask, max_in_sd_map, sd_map = get_overall_mask(map_data = map_data,
mask_threshold = mask_threshold,
crystal_symmetry = tracking_data.crystal_symmetry,
resolution = tracking_data.params.crystal_info.resolution,
solvent_fraction = tracking_data.solvent_fraction,
radius = radius,
out = out)
if starting_mask:
print("Points in starting mask:", starting_mask.count(True), file = out)
print("Points in overall mask:", overall_mask.count(True), file = out)
print("Points in both:", (starting_mask & overall_mask).count(True), file = out)
if tracking_data.params.crystal_info.is_crystal:
# take starting mask as overall...
overall_mask = starting_mask
else: # usual
# make sure overall mask is at least as big..
overall_mask = (overall_mask | starting_mask)
print("New size of overall mask: ", overall_mask.count(True), file = out)
else:
if not sites_cart: # pick top of map
sites_cart = get_high_points_from_map(
boundary_radius = radius,
map_data = sd_map,
unit_cell = unit_cell, out = out)
starting_mask = mask_from_sites_and_map( # starting au mask
map_data = sd_map, unit_cell = unit_cell,
sites_cart = sites_cart, radius = radius,
overall_mask = overall_mask)
del sd_map
au_mask, ncs_mask = get_ncs_mask(
map_data = map_data, unit_cell = unit_cell, ncs_object = ncs_obj,
starting_mask = starting_mask,
radius = radius,
overall_mask = overall_mask,
every_nth_point = every_nth_point)
print("Points in au: %d in ncs: %d (total %7.1f%%) both: %d Not marked: %d" %(
au_mask.count(True), ncs_mask.count(True),
100.*float(au_mask.count(True)+ncs_mask.count(True))/au_mask.size(),
(au_mask & ncs_mask).count(True),
au_mask.size()-au_mask.count(True)-ncs_mask.count(True), ), file = out)
return au_mask
def set_up_sharpening(si = None, map_data = None, out = sys.stdout):
print("\nCarrying out specified sharpening/blurring of map", file = out)
check_si = si # just use input information
check_si.show_summary(out = out)
if check_si.is_target_b_iso_to_d_cut():
check_si.b_iso = check_si.get_target_b_iso()
check_si.b_sharpen = None
print("Setting target b_iso of %7.1f " %(check_si.b_iso), file = out)
if check_si.b_sharpen is None and check_si.b_iso is not None:
# need to figure out b_sharpen
print("\nGetting b_iso of map", file = out)
b_iso = check_si.get_effective_b_iso(map_data = map_data, out = out)
check_si.b_sharpen = b_iso-check_si.b_iso # sharpen is what to
print("Value of b_sharpen to obtain b_iso of %s is %5.2f" %(
check_si.b_iso, check_si.b_sharpen), file = out)
elif check_si.b_sharpen is not None:
print("Sharpening b_sharpen will be %s" %(check_si.b_sharpen), file = out)
elif check_si.resolution_dependent_b:
print("Resolution-dependent b_sharpening values:" +\
"b0: %7.2f b1: %7.2f b2: %7.2f " %(
tuple(check_si.resolution_dependent_b)), file = out)
elif check_si.target_scale_factors:
print("Model sharpening scale values:", file = out)
for x in check_si.target_scale_factors: print(x, end = ' ', file = out)
print(file = out)
return check_si
def run(args,
params = None,
map_data = None,
crystal_symmetry = None,
write_files = None,
auto_sharpen = None,
density_select = None,
add_neighbors = None,
save_box_map_ncs_au = None,
resolution = None,
sequence = None,
half_map_data_list = None,
ncs_obj = None,
tracking_data = None,
target_scattered_points = None,
is_iteration = False,
pdb_hierarchy = None,
target_xyz = None,
target_hierarchy = None,
target_model = None,
sharpening_target_pdb_inp = None,
wrapping = None,
target_ncs_au_file = None,
regions_to_keep = None,
solvent_content = None,
molecular_mass = None,
symmetry = None,
chain_type = None,
keep_low_density = None,
box_buffer = None,
soft_mask_extract_unique = None,
mask_expand_ratio = None,
out = sys.stdout):
if is_iteration:
print("\nIteration tracking data:", file = out)
tracking_data.show_summary(out = out)
else:
# get the parameters and map_data (sharpened, magnified, shifted...)
params, map_data, half_map_data_list, pdb_hierarchy, tracking_data, \
shifted_ncs_object = get_params( #
args, map_data = map_data, crystal_symmetry = crystal_symmetry,
half_map_data_list = half_map_data_list,
ncs_object = ncs_obj,
write_files = write_files,
auto_sharpen = auto_sharpen,
density_select = density_select,
add_neighbors = add_neighbors,
save_box_map_ncs_au = save_box_map_ncs_au,
sequence = sequence,
wrapping = wrapping,
target_ncs_au_file = target_ncs_au_file,
regions_to_keep = regions_to_keep,
solvent_content = solvent_content,
resolution = resolution,
molecular_mass = molecular_mass,
symmetry = symmetry,
chain_type = chain_type,
keep_low_density = keep_low_density,
box_buffer = box_buffer,
soft_mask_extract_unique = soft_mask_extract_unique,
mask_expand_ratio = mask_expand_ratio,
sharpening_target_pdb_inp = sharpening_target_pdb_inp, out = out)
if params.control.shift_only:
return map_data, ncs_obj, tracking_data
elif params.control.check_ncs or \
params.control.sharpen_only:
return None, None, tracking_data
if params.input_files.pdb_to_restore:
restore_pdb(params, tracking_data = tracking_data, out = out)
return None, None, tracking_data
# read and write the ncs (Normally point-group NCS)
ncs_obj, tracking_data = get_ncs(params = params, tracking_data = tracking_data,
ncs_object = shifted_ncs_object,
out = out)
if target_model:
target_hierarchy = target_model.get_hierarchy()
elif params.input_files.target_ncs_au_file: # read in target
import iotbx.pdb
target_hierarchy = iotbx.pdb.input(
file_name = params.input_files.target_ncs_au_file).construct_hierarchy()
print("\nShifting model based on origin shift (if any)", file = out)
print("Coordinate shift is (%7.2f, %7.2f, %7.2f)" %(
tuple(tracking_data.origin_shift)), file = out)
if not map_data:
raise Sorry("Need map data for segment_and_split_map")
if params.output_files.shifted_map_file:
shifted_map_file = os.path.join(
tracking_data.params.output_files.output_directory,
params.output_files.shifted_map_file)
else:
shifted_map_file = None
if params.output_files.shifted_ncs_file:
shifted_ncs_file = os.path.join(
tracking_data.params.output_files.output_directory,
params.output_files.shifted_ncs_file)
else:
shifted_ncs_file = None
if params.output_files.shifted_ncs_file:
shifted_pdb_file = os.path.join(
tracking_data.params.output_files.output_directory,
params.output_files.shifted_pdb_file)
else:
shifted_pdb_file = None
ncs_obj, pdb_hierarchy, target_hierarchy, \
tracking_data, sharpening_target_pdb_inp = apply_origin_shift(
shifted_map_file = shifted_map_file,
shifted_pdb_file = shifted_pdb_file,
shifted_ncs_file = shifted_ncs_file,
origin_shift = tracking_data.origin_shift,
shifted_ncs_object = shifted_ncs_object,
pdb_hierarchy = pdb_hierarchy,
target_hierarchy = target_hierarchy,
map_data = map_data,
tracking_data = tracking_data,
sharpening_target_pdb_inp = sharpening_target_pdb_inp,
out = out)
if target_hierarchy:
target_xyz = target_hierarchy.atoms().extract_xyz()
del target_hierarchy
# We can use params.input_files.target_ncs_au_file here to define ncs au
if target_xyz and not target_scattered_points:
target_scattered_points = flex.vec3_double()
target_scattered_points.append(target_xyz.mean())
# get the chain types and therefore (using ncs_copies) volume fraction
tracking_data = get_solvent_fraction(params,
ncs_object = ncs_obj, tracking_data = tracking_data, out = out)
# Done with getting params and maps
# Summarize after any sharpening
tracking_data.show_summary(out = out)
original_ncs_obj = ncs_obj # in case we need it later...
original_input_ncs_info = tracking_data.input_ncs_info
removed_ncs = False
n_residues = tracking_data.n_residues
ncs_copies = tracking_data.input_ncs_info.number_of_operators
if (not tracking_data.solvent_fraction) and \
params.crystal_info.molecular_mass:
tracking_data.solvent_fraction = get_solvent_fraction_from_molecular_mass(
crystal_symmetry = tracking_data.crystal_symmetry,
molecular_mass = params.crystal_info.molecular_mass,
out = out)
if tracking_data.solvent_fraction:
solvent_fraction = tracking_data.solvent_fraction
else:
raise Sorry("Need solvent fraction or molecular mass or sequence file")
# Now usual method, using our new map...should duplicate best result above
for itry in range(2):
# get connectivity (conn = connectivity_object.result)
b_vs_region = b_vs_region_info()
si = sharpening_info(tracking_data = tracking_data)
co, sorted_by_volume, min_b, max_b, unique_expected_regions, best_score, \
new_threshold, starting_density_threshold = \
get_connectivity(
b_vs_region = b_vs_region,
map_data = map_data,
iterate_with_remainder = params.segmentation.iterate_with_remainder,
n_residues = n_residues,
ncs_copies = ncs_copies,
solvent_fraction = solvent_fraction,
fraction_occupied = si.fraction_occupied,
min_volume = si.min_volume,
min_ratio = si.min_ratio,
wrapping = si.wrapping,
residues_per_region = si.residues_per_region,
max_ratio_to_target = si.max_ratio_to_target,
min_ratio_to_target = si.min_ratio_to_target,
min_ratio_of_ncs_copy_to_first = si.min_ratio_of_ncs_copy_to_first,
starting_density_threshold = si.starting_density_threshold,
density_threshold = si.density_threshold,
crystal_symmetry = si.crystal_symmetry,
chain_type = si.chain_type,
verbose = si.verbose,
out = out)
params.segmentation.starting_density_threshold = starting_density_threshold # have to set tracking data as we are passing that above
tracking_data.params.segmentation.starting_density_threshold = starting_density_threshold # have to set tracking data as we are passing that above
if new_threshold:
print("\nNew threshold is %7.2f" %(new_threshold), file = out)
if co is None: # no luck
return None, None, tracking_data
# Check to see which regions are in more than one au of the NCS
# and set them aside. Group ncs-related regions together
ncs_group_obj, tracking_data, equiv_dict_ncs_copy = identify_ncs_regions(
params, sorted_by_volume = sorted_by_volume,
co = co,
min_b = min_b,
max_b = max_b,
ncs_obj = ncs_obj,
tracking_data = tracking_data,
out = out)
if ncs_group_obj and ncs_group_obj.ncs_group_list: # ok
break
elif ncs_obj and itry == 0 and not is_iteration:# try again
print("No NCS groups identified on first try...taking entire NCS AU.", file = out)
# Identify ncs au
au_mask = get_one_au(tracking_data = tracking_data,
ncs_obj = ncs_obj,
map_data = map_data, out = out)
s = (au_mask == False)
min_in_map = map_data.as_1d().min_max_mean().min
map_data.set_selected(s, min_in_map) # mask out all but au
from mmtbx.ncs.ncs import ncs
ncs_obj = ncs()
ncs_obj.set_unit_ncs()
tracking_data.set_ncs_obj(ncs_obj = None)
tracking_data.update_ncs_info(number_of_operators = 1)
if n_residues:
n_residues = n_residues/ncs_copies
solvent_fraction = max(0.001, min(0.999,
1-((1-solvent_fraction)/ncs_copies)))
ncs_copies = 1
params.segmentation.require_complete = False
params.segmentation.iterate_with_remainder = False # so we do not iterate
removed_ncs = True
# Run again
else: # tried twice, give up
return None, None, tracking_data
# Choose one region or group of regions from each ncs_group in the list
# Optimize the closeness of centers
# Select group of regions that are close together and represent one au
ncs_group_obj, scattered_points = \
select_regions_in_au(
params,
ncs_group_obj = ncs_group_obj,
equiv_dict_ncs_copy = equiv_dict_ncs_copy,
tracking_data = tracking_data,
target_scattered_points = target_scattered_points,
unique_expected_regions = unique_expected_regions,
out = out)
# write out mask and map for all the selected regions...
# Iterate if desired
if params.segmentation.iterate_with_remainder and \
ncs_group_obj.selected_regions:
print("\nCreating remaining mask and map", file = out)
map_data_remaining = create_remaining_mask_and_map(params,
ncs_group_obj = ncs_group_obj,
map_data = map_data,
crystal_symmetry = tracking_data.crystal_symmetry,
out = out)
remainder_ncs_group_obj = iterate_search(params,
map_data = map_data,
map_data_remaining = map_data_remaining,
ncs_obj = ncs_obj,
ncs_group_obj = ncs_group_obj,
scattered_points = scattered_points,
tracking_data = tracking_data,
out = out)
else:
remainder_ncs_group_obj = None
# collect all NCS ops that are needed to relate all the regions
# that are used
ncs_ops_used = ncs_group_obj.ncs_ops_used
if remainder_ncs_group_obj and remainder_ncs_group_obj.ncs_ops_used:
for x in remainder_ncs_group_obj.ncs_ops_used:
if not x in ncs_ops_used: ncs_ops_used.append(x)
if ncs_ops_used:
ncs_ops_used.sort()
print("Final NCS ops used: ", ncs_ops_used, file = out)
# Save the used NCS ops
ncs_used_obj = ncs_group_obj.ncs_obj.deep_copy(ops_to_keep = ncs_ops_used)
if params.output_files.shifted_used_ncs_file:
shifted_used_ncs_file = os.path.join(
tracking_data.params.output_files.output_directory,
params.output_files.shifted_used_ncs_file)
ncs_used_obj.format_all_for_group_specification(
file_name = shifted_used_ncs_file)
tracking_data.set_shifted_used_ncs_info(file_name = shifted_used_ncs_file,
number_of_operators = ncs_used_obj.max_operators(),
is_helical_symmetry = tracking_data.input_ncs_info.is_helical_symmetry)
tracking_data.shifted_used_ncs_info.show_summary(out = out)
# Write out final maps and dummy atom files
if params.output_files.write_output_maps:
print("\nWriting output maps", file = out)
else:
print("\nSetting up but not writing output maps", file = out)
map_files_written = write_output_files(params,
tracking_data = tracking_data,
map_data = map_data,
half_map_data_list = half_map_data_list,
ncs_group_obj = ncs_group_obj,
remainder_ncs_group_obj = remainder_ncs_group_obj,
pdb_hierarchy = pdb_hierarchy,
removed_ncs = removed_ncs,
out = out)
ncs_group_obj.set_map_files_written(map_files_written)
# Restore ncs info if we removed it
if removed_ncs:
print("\nRestoring original NCS info to tracking_data", file = out)
tracking_data.input_ncs_info = original_input_ncs_info
if params.output_files.output_info_file and ncs_group_obj:
write_info_file(params = params, tracking_data = tracking_data, out = out)
return ncs_group_obj, remainder_ncs_group_obj, tracking_data
if __name__ == "__main__":
run(args = sys.argv[1:])
|