File: chain_mapping.py

package info (click to toggle)
openstructure 2.11.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 206,240 kB
  • sloc: cpp: 188,571; python: 36,686; ansic: 34,298; fortran: 3,275; sh: 312; xml: 146; makefile: 29
file content (3728 lines) | stat: -rw-r--r-- 166,577 bytes parent folder | download
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
"""
Chain mapping aims to identify a one-to-one relationship between chains in a
reference structure and a model.
"""

import itertools
import copy

import numpy as np

from scipy.special import factorial
from scipy.special import binom # as of Python 3.8, the math module implements
                                # comb, i.e. n choose k

import ost
from ost import seq
from ost import mol
from ost import geom

from ost.mol.alg import lddt
from ost.mol.alg import bb_lddt
from ost.mol.alg import qsscore

def _CSel(ent, cnames):
    """ Returns view with specified chains

    Ensures that quotation marks are around chain names to not confuse
    OST query language with weird special characters.
    """
    query = "cname=" + ','.join([mol.QueryQuoteName(cname) for cname in cnames])
    return ent.Select(query)

class MappingResult:
    """ Result object for the chain mapping functions in :class:`ChainMapper`

    Constructor is directly called within the functions, no need to construct
    such objects yourself.
    """
    def __init__(self, target, model, chem_groups, chem_mapping,
                 mdl_chains_without_chem_mapping, mapping, alns, opt_score=None):
        self._target = target
        self._model = model
        self._chem_groups = chem_groups
        self._chem_mapping = chem_mapping
        self._mdl_chains_without_chem_mapping = mdl_chains_without_chem_mapping
        self._mapping = mapping
        self._alns = alns
        self._opt_score = opt_score

    @property
    def target(self):
        """ Target/reference structure, i.e. :attr:`ChainMapper.target`

        :type: :class:`ost.mol.EntityView`
        """
        return self._target

    @property
    def model(self):
        """ Model structure that gets mapped onto :attr:`~target`

        Underwent same processing as :attr:`ChainMapper.target`, i.e.
        only contains peptide/nucleotide chains of sufficient size.

        :type: :class:`ost.mol.EntityView`
        """
        return self._model

    @property
    def chem_groups(self):
        """ Groups of chemically equivalent chains in :attr:`~target`

        Same as :attr:`ChainMapper.chem_group`

        :class:`list` of :class:`list` of :class:`str` (chain names)
        """
        return self._chem_groups

    @property
    def chem_mapping(self):
        """ Assigns chains in :attr:`~model` to :attr:`~chem_groups`.

        :class:`list` of :class:`list` of :class:`str` (chain names)
        """
        return self._chem_mapping

    @property
    def mdl_chains_without_chem_mapping(self):
        """ Model chains that cannot be mapped to :attr:`chem_groups`

        Depends on parameterization of :class:`ChainMapper`

        :class:`list` of class:`str` (chain names)
        """
        return self._mdl_chains_without_chem_mapping

    @property
    def mapping(self):
        """ Mapping of :attr:`~model` chains onto :attr:`~target`

        Exact same shape as :attr:`~chem_groups` but containing the names of the
        mapped chains in :attr:`~model`. May contain None for :attr:`~target`
        chains that are not covered. No guarantee that all chains in
        :attr:`~model` are mapped.

        :class:`list` of :class:`list` of :class:`str` (chain names)
        """
        return self._mapping

    @property
    def alns(self):
        """ Alignments of mapped chains in :attr:`~target` and :attr:`~model`

        Each alignment is accessible with ``alns[(t_chain,m_chain)]``. First
        sequence is the sequence of :attr:`target` chain, second sequence the
        one from :attr:`~model`.

        :type: :class:`dict` with key: :class:`tuple` of :class:`str`, value:
               :class:`ost.seq.AlignmentHandle`
        """
        return self._alns

    @property
    def opt_score(self):
        """ Placeholder property without any guarantee of being set

        Different scores get optimized in the various chain mapping algorithms.
        Some of them may set their final optimal score in that property.
        Consult the documentation of the respective chain mapping algorithm
        for more information. Won't be in the return dict of
        :func:`JSONSummary`.
        """
        return self._opt_score

    def GetFlatMapping(self, mdl_as_key=False):
        """ Returns flat mapping as :class:`dict` for all mapable chains

        :param mdl_as_key: Default is target chain name as key and model chain
                           name as value. This can be reversed with this flag.
        :returns: :class:`dict` with :class:`str` as key/value that describe
                  one-to-one mapping
        """
        flat_mapping = dict()
        for trg_chem_group, mdl_chem_group in zip(self.chem_groups,
                                                  self.mapping):
            for a,b in zip(trg_chem_group, mdl_chem_group):
                if a is not None and b is not None:
                    if mdl_as_key:
                        flat_mapping[b] = a
                    else:
                        flat_mapping[a] = b
        return flat_mapping

    def JSONSummary(self):
        """ Returns JSON serializable summary of results
        """
        json_dict = dict()
        json_dict["chem_groups"] = self.chem_groups
        json_dict["mapping"] = self.mapping
        json_dict["flat_mapping"] = self.GetFlatMapping()
        json_dict["alns"] = list()
        for aln in self.alns.values():
            trg_seq = aln.GetSequence(0)
            mdl_seq = aln.GetSequence(1)
            aln_dict = {"trg_ch": trg_seq.GetName(), "trg_seq": str(trg_seq),
                        "mdl_ch": mdl_seq.GetName(), "mdl_seq": str(mdl_seq)}
            json_dict["alns"].append(aln_dict)
        return json_dict


class ReprResult:

    """ Result object for :func:`ChainMapper.GetRepr`

    Constructor is directly called within the function, no need to construct
    such objects yourself.

    :param lDDT: lDDT for this mapping. Depends on how you call
                 :func:`ChainMapper.GetRepr` whether this is backbone only or
                 full atom lDDT.
    :type lDDT: :class:`float`
    :param substructure: The full substructure for which we searched for a
                         representation
    :type substructure: :class:`ost.mol.EntityView`
    :param ref_view: View pointing to the same underlying entity as
                     *substructure* but only contains the stuff that is mapped
    :type ref_view: :class:`mol.EntityView`
    :param mdl_view: The matching counterpart in model
    :type mdl_view: :class:`mol.EntityView`
    """
    def __init__(self, lDDT, substructure, ref_view, mdl_view):
        self._lDDT = lDDT
        self._substructure = substructure
        assert(len(ref_view.residues) == len(mdl_view.residues))
        self._ref_view = ref_view
        self._mdl_view = mdl_view

        # lazily evaluated attributes
        self._ref_bb_pos = None
        self._mdl_bb_pos = None
        self._ref_full_bb_pos = None
        self._mdl_full_bb_pos = None
        self._superposition = None
        self._superposed_mdl_bb_pos = None
        self._ost_query = None
        self._flat_mapping = None
        self._inconsistent_residues = None

    @property
    def lDDT(self):
        """ lDDT of representation result

        Depends on how you call :func:`ChainMapper.GetRepr` whether this is
        backbone only or full atom lDDT.

        :type: :class:`float`
        """
        return self._lDDT

    @property
    def substructure(self):
        """ The full substructure for which we searched for a
        representation

        :type: :class:`ost.mol.EntityView`
        """
        return self._substructure

    @property
    def ref_view(self):
        """ View which contains the mapped subset of :attr:`substructure`

        :type: :class:`ost.mol.EntityView`
        """
        return self._ref_view

    @property
    def mdl_view(self):
        """ The :attr:`ref_view` representation in the model

        :type: :class:`ost.mol.EntityView`
        """
        return self._mdl_view
    
    @property
    def ref_residues(self):
        """ The reference residues

        :type: class:`mol.ResidueViewList`
        """
        return self.ref_view.residues
    
    @property
    def mdl_residues(self):
        """ The model residues

        :type: :class:`mol.ResidueViewList`
        """
        return self.mdl_view.residues

    @property
    def inconsistent_residues(self):
        """ A list of mapped residue whose names do not match (eg. ALA in the
        reference and LEU in the model).

        The mismatches are reported as a tuple of :class:`~ost.mol.ResidueView`
        (reference, model), or as an empty list if all the residue names match.

        :type: :class:`list`
        """
        if self._inconsistent_residues is None:
            self._inconsistent_residues = self._GetInconsistentResidues(
                self.ref_residues, self.mdl_residues)
        return self._inconsistent_residues

    @property
    def ref_bb_pos(self):
        """ Representative backbone positions for reference residues.

        Thats CA positions for peptides and C3' positions for Nucleotides.

        :type: :class:`geom.Vec3List`
        """
        if self._ref_bb_pos is None:
            self._ref_bb_pos = self._GetBBPos(self.ref_residues)
        return self._ref_bb_pos

    @property
    def mdl_bb_pos(self):
        """ Representative backbone positions for model residues.

        Thats CA positions for peptides and C3' positions for Nucleotides.

        :type: :class:`geom.Vec3List`
        """
        if self._mdl_bb_pos is None:
            self._mdl_bb_pos = self._GetBBPos(self.mdl_residues)
        return self._mdl_bb_pos

    @property
    def ref_full_bb_pos(self):
        """ Representative backbone positions for reference residues.

        Thats N, CA and C positions for peptides and O5', C5', C4', C3', O3'
        positions for Nucleotides.

        :type: :class:`geom.Vec3List`
        """
        if self._ref_full_bb_pos is None:
            self._ref_full_bb_pos = self._GetFullBBPos(self.ref_residues)
        return self._ref_full_bb_pos

    @property
    def mdl_full_bb_pos(self):
        """ Representative backbone positions for reference residues.

        Thats N, CA and C positions for peptides and O5', C5', C4', C3', O3'
        positions for Nucleotides.

        :type: :class:`geom.Vec3List`
        """
        if self._mdl_full_bb_pos is None:
            self._mdl_full_bb_pos = self._GetFullBBPos(self.mdl_residues)
        return self._mdl_full_bb_pos


    @property
    def superposition(self):
        """ Superposition of mdl residues onto ref residues

        Superposition computed as minimal RMSD superposition on
        :attr:`ref_bb_pos` and :attr:`mdl_bb_pos`. If number of positions is
        smaller 3, the full_bb_pos equivalents are used instead.

        :type: :class:`ost.mol.alg.SuperpositionResult`
        """
        if self._superposition is None:
            if len(self.mdl_bb_pos) < 3:
                self._superposition = _GetSuperposition(self.mdl_full_bb_pos,
                                                self.ref_full_bb_pos, False)
            else:
                self._superposition = _GetSuperposition(self.mdl_bb_pos,
                                                self.ref_bb_pos, False)
        return self._superposition

    @property
    def transform(self):
        """ Transformation to superpose mdl residues onto ref residues

        :type: :class:`ost.geom.Mat4`
        """
        return self.superposition.transformation

    @property
    def superposed_mdl_bb_pos(self):
        """ :attr:`mdl_bb_pos` with :attr:`transform applied`

        :type: :class:`geom.Vec3List`
        """
        if self._superposed_mdl_bb_pos is None:
            self._superposed_mdl_bb_pos = geom.Vec3List(self.mdl_bb_pos)
            self._superposed_mdl_bb_pos.ApplyTransform(self.transform)
        return self._superposed_mdl_bb_pos

    @property
    def bb_rmsd(self):
        """ RMSD of the binding site backbone atoms after :attr:`superposition`

        :type: :class:`float`
        """
        return self.superposition.rmsd


    @property
    def ost_query(self):
        """ query for mdl residues in OpenStructure query language

        Repr can be selected as ``full_mdl.Select(ost_query)``

        Returns invalid query if residue numbers have insertion codes.

        :type: :class:`str`
        """
        if self._ost_query is None:
            chain_rnums = dict()
            for r in self.mdl_residues:
                chname = r.GetChain().GetName()
                rnum = r.GetNumber().GetNum()
                if chname not in chain_rnums:
                    chain_rnums[chname] = list()
                chain_rnums[chname].append(str(rnum))
            chain_queries = list()
            for k,v in chain_rnums.items():
                q = f"(cname={mol.QueryQuoteName(k)} and "
                q += f"rnum={','.join(v)})"
                chain_queries.append(q)
            self._ost_query = " or ".join(chain_queries)
        return self._ost_query

    def JSONSummary(self):
        """ Returns JSON serializable summary of results
        """
        json_dict = dict()
        json_dict["lDDT"] = self.lDDT
        json_dict["ref_residues"] = [r.GetQualifiedName() for r in \
                                     self.ref_residues]
        json_dict["mdl_residues"] = [r.GetQualifiedName() for r in \
                                     self.mdl_residues]
        json_dict["transform"] = list(self.transform.data)
        json_dict["bb_rmsd"] = self.bb_rmsd
        json_dict["ost_query"] = self.ost_query
        json_dict["flat_mapping"] = self.GetFlatChainMapping()
        return json_dict

    def GetFlatChainMapping(self, mdl_as_key=False):
        """ Returns flat mapping of all chains in the representation

        :param mdl_as_key: Default is target chain name as key and model chain
                           name as value. This can be reversed with this flag.
        :returns: :class:`dict` with :class:`str` as key/value that describe
                  one-to-one mapping
        """
        flat_mapping = dict()
        for trg_res, mdl_res in zip(self.ref_residues, self.mdl_residues):
            if mdl_as_key:
                flat_mapping[mdl_res.chain.name] = trg_res.chain.name
            else:
                flat_mapping[trg_res.chain.name] = mdl_res.chain.name
        return flat_mapping

    def _GetFullBBPos(self, residues):
        """ Helper to extract full backbone positions
        """
        exp_pep_atoms = ["N", "CA", "C"]
        exp_nuc_atoms = ["O5'", "C5'", "C4'", "C3'", "O3'"]
        bb_pos = geom.Vec3List()
        for r in residues:
            if r.GetChemType() == mol.ChemType.NUCLEOTIDES:
                exp_atoms = exp_nuc_atoms
            elif r.GetChemType() == mol.ChemType.AMINOACIDS:
                exp_atoms = exp_pep_atoms
            else:
                raise RuntimeError(f"Residue {r.qualified_name} has unexpected"
                                   f" chem type {r.GetChemType()}")
            for aname in exp_atoms:
                a = r.FindAtom(aname)
                if not a.IsValid():
                    raise RuntimeError(f"Expected atom {aname} missing from "
                                      f"{r.qualified_name}")
                bb_pos.append(a.GetPos())
        return bb_pos

    def _GetBBPos(self, residues):
        """ Helper to extract single representative position for each residue
        """
        bb_pos = geom.Vec3List()
        for r in residues:
            at = r.FindAtom("CA")
            if not at.IsValid():
                at = r.FindAtom("C3'")
            if not at.IsValid():
                raise RuntimeError(f"Residue {r.qualified_name} missing "
                                   f"expected CA/C3' atom")
            bb_pos.append(at.GetPos())
        return bb_pos

    def _GetInconsistentResidues(self, ref_residues, mdl_residues):
        """ Helper to extract a list of inconsistent residues.
        """
        if len(ref_residues) != len(mdl_residues):
            raise ValueError("Something terrible happened... Reference and "
                             "model lengths differ... RUN...")
        inconsistent_residues = list()
        for ref_residue, mdl_residue in zip(ref_residues, mdl_residues):
            if ref_residue.name != mdl_residue.name:
                inconsistent_residues.append((ref_residue, mdl_residue))
        return inconsistent_residues


class ChainMapper:
    """ Class to compute chain mappings

    All algorithms are performed on processed structures which fulfill
    criteria as given in constructor arguments (*min_pep_length*,
    "min_nuc_length") and only contain residues which have all required backbone
    atoms. for peptide residues thats N, CA, C and CB (no CB for GLY), for
    nucleotide residues thats O5', C5', C4', C3' and O3'.

    Chain mapping is a three step process:

    * Group chemically identical chains in *target* into so called chem
      groups. There are two options to achieve this:
      1) using pairwise alignments that are either computed with
      Needleman-Wunsch (NW) or simply derived from residue numbers
      (*resnum_alignments* flag). In case of NW, *pep_subst_mat*, *pep_gap_open*
      and *pep_gap_ext* and their nucleotide equivalents are relevant. Two
      chains are considered identical if they fulfill the *pep_seqid_thr* and
      have at least *min_pep_length* aligned residues. Same logic is applied
      for nucleotides with respective thresholds.
      2) specify seqres sequences and provide the mapping manually. This can
      be useful if you're loading data from an mmCIF file where you have mmCIF
      entity information. Alignments are performed based on residue numbers
      in this case and don't consider the *resnum_alignments* flag. Any
      mismatch of one letter code in the structure and the respective SEQRES
      raises an error.

    * Map chains in an input model to these groups. Parameters for generating
      alignments are the same as above. Model chains are mapped to the chem
      group with highest sequence identity. Optionally, you can set a minimum
      sequence identity threshold with *mdl_map_pep_seqid_thr*/
      *mdl_map_nuc_seqid_thr* to avoid nonsensical mappings. You can either
      get the group mapping with :func:`GetChemMapping` or directly call
      one of the full fletched one-to-one chain mapping functions which
      execute that step internally.

    * Obtain one-to-one mapping for chains in an input model and
      *target* with one of the available mapping functions. Just to get an
      idea of complexity. If *target* and *model* are octamers, there are
      ``8! = 40320`` possible chain mappings.

    :param target: Target structure onto which models are mapped.
                   Computations happen on a selection only containing
                   polypeptides and polynucleotides.
    :type target: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
    :param resnum_alignments: Use residue numbers instead of
                              Needleman-Wunsch to compute pairwise
                              alignments. Relevant for :attr:`~chem_groups` 
                              if *seqres* is not specified explicitely.
    :type resnum_alignments: :class:`bool`
    :param pep_seqid_thr: Sequence identity threshold (in percent of aligned
                          columns) used to decide when two chains are
                          identical. 95 percent tolerates the few mutations
                          crystallographers like to do. Range: [0-100].
    :type pep_seqid_thr:  :class:`float`
    :param nuc_seqid_thr: Nucleotide equivalent for *pep_seqid_thr*
    :type nuc_seqid_thr:  :class:`float`
    :param pep_subst_mat: Substitution matrix to align peptide sequences,
                          irrelevant if *resnum_alignments* is True,
                          defaults to seq.alg.BLOSUM62
    :type pep_subst_mat: :class:`ost.seq.alg.SubstWeightMatrix`
    :param pep_gap_open: Gap open penalty to align peptide sequences,
                         irrelevant if *resnum_alignments* is True
    :type pep_gap_open: :class:`int`
    :param pep_gap_ext: Gap extension penalty to align peptide sequences,
                        irrelevant if *resnum_alignments* is True
    :type pep_gap_ext: :class:`int`
    :param nuc_subst_mat: Nucleotide equivalent for *pep_subst_mat*,
                          defaults to seq.alg.NUC44
    :type nuc_subst_mat: :class:`ost.seq.alg.SubstWeightMatrix`
    :param nuc_gap_open: Nucleotide equivalent for *pep_gap_open*
    :type nuc_gap_open: :class:`int`
    :param nuc_gap_ext: Nucleotide equivalent for *pep_gap_ext*
    :type nuc_gap_ext: :class:`int`
    :param min_pep_length: Minimal number of residues for a peptide chain to be
                           considered in target and in models.
    :type min_pep_length: :class:`int`
    :param min_nuc_length: Minimal number of residues for a nucleotide chain to be
                           considered in target and in models.
    :type min_nuc_length: :class:`int` 
    :param n_max_naive: Max possible chain mappings that are enumerated in
                        :func:`~GetNaivelDDTMapping` /
                        :func:`~GetDecomposerlDDTMapping`. A
                        :class:`RuntimeError` is raised in case of bigger
                        complexity.
    :type n_max_naive: :class:`int`
    :param mdl_map_pep_seqid_thr: Sequence identity threshold (in percent of
                                  aligned columns) to avoid non-sensical
                                  mapping of model chains to reference chem
                                  groups. If a value larger than 0.0 is
                                  provided, minimal criteria for assignment
                                  becomes a sequence identity of
                                  *mdl_map_pep_seqid_thr* and at least
                                  *min_pep_length* aligned residues. If set to
                                  zero, it simply assigns a model chain to the
                                  chem group with highest sequence identity.
                                  Range: [0-100].
    :type mdl_map_pep_seqid_thr: :class:`float`
    :param mdl_map_nuc_seqid_thr: Nucleotide equivalent of
                                  *mdl_map_pep_seqid_thr*
    :type mdl_map_nuc_seqid_thr: :class:`float`
    :param seqres: SEQRES sequences. All polymer chains in *target* will be
                   aligned to these sequences using a residue number based
                   alignment, effectively ignoring *resnum_alignments* in
                   the chem grouping step. Additionally, you need to
                   manually specify a mapping of the polymer chains using
                   *trg_seqres_mapping* and an error is raised otherwise.
                   The one letter codes in
                   the structure must exactly match the respective characters
                   in seqres and an error is raised if not. These seqres
                   sequences are set as :attr:`~chem_group_ref_seqs` and will
                   thus influence the mapping of model chains.
    :type seqres: :class:`ost.seq.SequenceList`
    :param trg_seqres_mapping: Maps each polymer chain in *target* to a sequence
                               in *seqres*. It's a :class:`dict` with chain name
                               as key and seqres sequence name as value.
    :type trg_seqres_mapping: :class:`dict`
    """
    def __init__(self, target, resnum_alignments=False,
                 pep_seqid_thr = 95., nuc_seqid_thr = 95., 
                 pep_subst_mat = seq.alg.BLOSUM62, pep_gap_open = -11,
                 pep_gap_ext = -1, nuc_subst_mat = seq.alg.NUC44,
                 nuc_gap_open = -4, nuc_gap_ext = -4,
                 min_pep_length = 6, min_nuc_length = 4,
                 n_max_naive = 1e8,
                 mdl_map_pep_seqid_thr = 0.,
                 mdl_map_nuc_seqid_thr = 0.,
                 seqres = None,
                 trg_seqres_mapping = None):

        # input parameter check
        seqres_params_set = sum([seqres is not None,
                                 trg_seqres_mapping is not None])
        if seqres_params_set not in [0, 2]:
            raise RuntimeError("Must either give both, seqres and "
                               "trg_seqres_mapping, or none of them.")
        # attributes
        self.resnum_alignments = resnum_alignments
        self.pep_seqid_thr = pep_seqid_thr
        self.nuc_seqid_thr = nuc_seqid_thr
        self.min_pep_length = min_pep_length
        self.min_nuc_length = min_nuc_length
        self.n_max_naive = n_max_naive
        self.mdl_map_pep_seqid_thr = mdl_map_pep_seqid_thr
        self.mdl_map_nuc_seqid_thr = mdl_map_nuc_seqid_thr
        self.pep_subst_mat = pep_subst_mat
        self.pep_gap_open = pep_gap_open
        self.pep_gap_ext = pep_gap_ext
        self.nuc_subst_mat = nuc_subst_mat
        self.nuc_gap_open = nuc_gap_open
        self.nuc_gap_ext = nuc_gap_ext
        self.seqres = seqres
        self.trg_seqres_mapping = trg_seqres_mapping
        self.seqres_set = seqres_params_set == 2

        # lazy computed attributes
        self._chem_groups = None
        self._chem_group_alignments = None
        self._chem_group_ref_seqs = None
        self._chem_group_types = None

        # target structure preprocessing
        self._target, self._polypep_seqs, self._polynuc_seqs = \
        self.ProcessStructure(target)

        # input parameter check
        if self.seqres_set:
            # check if seqres names, i.e. entity ids, are unique
            entity_ids = set()
            for s in self.seqres:
                sname = s.GetName()
                if sname in entity_ids:
                    raise RuntimeError(f"Sequence names in seqres param must "
                                       f"be unique and refer to entity ids. "
                                       f"Duplicate sequence name: \"{sname}\"")
                entity_ids.add(sname)
            # check if entity ids in trg_seqres_mapping are all covered
            # in seqres
            for cname, entity_id in self.trg_seqres_mapping.items():
                if entity_id not in entity_ids:
                    raise RuntimeError(f"trg_seqres_mapping contains entity id "
                                       f"for which no seqres is given: "
                                       f"cname: \"{cname}\", entity id: "
                                       f"\"{entity_id}\"")
            # check if all sequences in self.polypep_seqs and self.polynuc_seqs
            # have a mapping in trg_seqres_mapping
            for s in self.polypep_seqs:
                if s.GetName() not in self.trg_seqres_mapping:
                    raise RuntimeError(f"If seqres information is provided, "
                                       f"all polymer chains must be covered "
                                       f"by trg_seqres_mapping. Missing "
                                       f"mapping for chain \"{s.GetName()}\"")
            for s in self.polynuc_seqs:
                if s.GetName() not in self.trg_seqres_mapping:
                    raise RuntimeError(f"If seqres information is provided, "
                                       f"all polymer chains must be covered "
                                       f"by trg_seqres_mapping. Missing "
                                       f"mapping for chain \"{s.GetName()}\"")


    @property
    def target(self):
        """Target structure that only contains peptides/nucleotides

        Contains only residues that have the backbone representatives
        (CA for peptide and C3' for nucleotides) to avoid ATOMSEQ alignment
        inconsistencies when switching between all atom and backbone only
        representations.

        :type: :class:`ost.mol.EntityView`
        """
        return self._target

    @property
    def polypep_seqs(self):
        """Sequences of peptide chains in :attr:`~target`

        :type: :class:`ost.seq.SequenceList`
        """
        return self._polypep_seqs

    @property
    def polynuc_seqs(self):
        """Sequences of nucleotide chains in :attr:`~target`

        :type: :class:`ost.seq.SequenceList`
        """
        return self._polynuc_seqs
    
    @property
    def chem_groups(self):
        """Groups of chemically equivalent chains in :attr:`~target`

        First chain in group is the one with longest sequence.
      
        :getter: Computed on first use (cached)
        :type: :class:`list` of :class:`list` of :class:`str` (chain names)
        """
        if self._chem_groups is None:
            self._ComputeChemGroups()
        return self._chem_groups
    
    @property
    def chem_group_alignments(self):
        """MSA for each group in :attr:`~chem_groups`

        The first sequence is the reference sequence.
        The subsequent sequences represent the ATOMSEQ sequences in
        :attr:`~target` in same order as in :attr:`~chem_groups`.

        :getter: Computed on first use (cached)
        :type: :class:`ost.seq.AlignmentList`
        """
        if self._chem_group_alignments is None:
            self._ComputeChemGroups()
        return self._chem_group_alignments

    @property
    def chem_group_ref_seqs(self):
        """Reference sequence for each group in :attr:`~chem_groups`

        :getter: Computed on first use (cached)
        :type: :class:`ost.seq.SequenceList`
        """
        if self._chem_group_ref_seqs is None:
            self._ComputeChemGroups()
        return self._chem_group_ref_seqs

    @property
    def chem_group_types(self):
        """ChemType of each group in :attr:`~chem_groups`

        Specifying if groups are poly-peptides/nucleotides, i.e. 
        :class:`ost.mol.ChemType.AMINOACIDS` or
        :class:`ost.mol.ChemType.NUCLEOTIDES`
        
        :getter: Computed on first use (cached)
        :type: :class:`list` of :class:`ost.mol.ChemType`
        """
        if self._chem_group_types is None:
            self._ComputeChemGroups()
        return self._chem_group_types
        
    def GetChemMapping(self, model):
        """Maps sequences in *model* to chem_groups of target

        :param model: Model from which to extract sequences, a
                      selection that only includes peptides and nucleotides
                      is performed and returned along other results.
        :type model: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :returns: Tuple with two lists of length `len(self.chem_groups)`, a list
                  and an :class:`ost.mol.EntityView` representing *model*:
                  1) Each element is a :class:`list` with mdl chain names that
                  map to the chem group at that position.
                  2) Each element is a :class:`ost.seq.AlignmentList` aligning
                  these mdl chain sequences to the chem group ref sequences.
                  3) The model chains that could not be mapped to the reference
                  4) A selection of *model* that only contains polypeptides and
                  polynucleotides whose ATOMSEQ exactly matches the sequence
                  info in the returned alignments.
        """
        mdl, mdl_pep_seqs, mdl_nuc_seqs = self.ProcessStructure(model)
        mapping = [list() for x in self.chem_groups]
        mdl_chains_without_chem_mapping = list()
        alns = [seq.AlignmentList() for x in self.chem_groups]

        for s in mdl_pep_seqs:
            idx, aln = self._MapSequence(self.chem_group_ref_seqs, 
                                         self.chem_group_types,
                                         s, mol.ChemType.AMINOACIDS, mdl,
                                         seq_id_thr = self.mdl_map_pep_seqid_thr,
                                         min_aln_length = self.min_pep_length)
            if idx is None:
                ost.LogWarning("Could not map model chain %s to any chem group"
                               " in the target" % s.name)
                mdl_chains_without_chem_mapping.append(s.GetName())
            else:
                mapping[idx].append(s.GetName())
                alns[idx].append(aln)

        for s in mdl_nuc_seqs:
            idx, aln = self._MapSequence(self.chem_group_ref_seqs, 
                                         self.chem_group_types,
                                         s, mol.ChemType.NUCLEOTIDES, mdl,
                                         seq_id_thr = self.mdl_map_nuc_seqid_thr,
                                         min_aln_length = self.min_nuc_length)
            if idx is None:
                ost.LogWarning("Could not map model chain %s to any chem group"
                               " in the target" % s.name)
                mdl_chains_without_chem_mapping.append(s.GetName())
            else:
                mapping[idx].append(s.GetName())
                alns[idx].append(aln)

        return (mapping, alns, mdl_chains_without_chem_mapping, mdl)


    def GetlDDTMapping(self, model, inclusion_radius=15.0,
                       thresholds=[0.5, 1.0, 2.0, 4.0], strategy="heuristic",
                       steep_opt_rate = None, block_seed_size = 5,
                       block_blocks_per_chem_group = 5,
                       chem_mapping_result = None,
                       heuristic_n_max_naive = 40320):
        """ Identify chain mapping by optimizing lDDT score

        Maps *model* chain sequences to :attr:`~chem_groups` and find mapping
        based on backbone only lDDT score (CA for amino acids C3' for
        Nucleotides).

        Either performs a naive search, i.e. enumerate all possible mappings or
        executes a greedy strategy that tries to identify a (close to) optimal
        mapping in an iterative way by starting from a start mapping (seed). In
        each iteration, the one-to-one mapping that leads to highest increase
        in number of conserved contacts is added with the additional requirement
        that this added mapping must have non-zero interface counts towards the
        already mapped chains. So basically we're "growing" the mapped structure
        by only adding connected stuff.

        The available strategies:

        * **naive**: Enumerates all possible mappings and returns best        

        * **greedy_full**: try multiple seeds for greedy extension, i.e. try
          all ref/mdl chain combinations within the respective chem groups and
          retain the mapping leading to the best lDDT.

        * **greedy_block**: try multiple seeds for greedy extension, i.e. try
          all ref/mdl chain combinations within the respective chem groups and
          extend them to *block_seed_size*. *block_blocks_per_chem_group*
          for each chem group are selected for exhaustive extension.

        * **heuristic**: Uses *naive* strategy if number of possible mappings
          is within *heuristic_n_max_naive*. The default of 40320 corresponds
          to an octamer (8!=40320). A structure with stoichiometry A6B2 would be
          6!*2!=1440 etc. If the number of possible mappings is larger,
          *greedy_full* is used.

        Sets :attr:`MappingResult.opt_score` in case of no trivial one-to-one
        mapping. 

        :param model: Model to map
        :type model: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :param inclusion_radius: Inclusion radius for lDDT
        :type inclusion_radius: :class:`float`
        :param thresholds: Thresholds for lDDT
        :type thresholds: :class:`list` of :class:`float`
        :param strategy: Strategy to find mapping. Must be in ["naive",
                         "greedy_full", "greedy_block"]
        :type strategy: :class:`str`
        :param steep_opt_rate: Only relevant for greedy strategies.
                               If set, every *steep_opt_rate* mappings, a simple
                               optimization is executed with the goal of
                               avoiding local minima. The optimization
                               iteratively checks all possible swaps of mappings
                               within their respective chem groups and accepts
                               swaps that improve lDDT score. Iteration stops as
                               soon as no improvement can be achieved anymore.
        :type steep_opt_rate: :class:`int`
        :param block_seed_size: Param for *greedy_block* strategy - Initial seeds
                                are extended by that number of chains.
        :type block_seed_size: :class:`int`
        :param block_blocks_per_chem_group: Param for *greedy_block* strategy -
                                            Number of blocks per chem group that
                                            are extended in an initial search
                                            for high scoring local solutions.
        :type block_blocks_per_chem_group: :class:`int`
        :param chem_mapping_result: Pro param. The result of
                                    :func:`~GetChemMapping` where you provided
                                    *model*. If set, *model* parameter is not
                                    used.
        :type chem_mapping_result: :class:`tuple`
        :returns: A :class:`MappingResult`
        """

        strategies = ["naive", "greedy_full", "greedy_block", "heuristic"]
        if strategy not in strategies:
            raise RuntimeError(f"Strategy must be in {strategies}")

        if chem_mapping_result is None:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            self.GetChemMapping(model)
        else:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            chem_mapping_result

        ref_mdl_alns =  _GetRefMdlAlns(self.chem_groups,
                                       self.chem_group_alignments,
                                       chem_mapping,
                                       chem_group_alns)

        # check for the simplest case
        one_to_one = _CheckOneToOneMapping(self.chem_groups, chem_mapping)
        if one_to_one is not None:
            alns = dict()
            for ref_group, mdl_group in zip(self.chem_groups, one_to_one):
                for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                    if ref_ch is not None and mdl_ch is not None:
                        aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                        alns[(ref_ch, mdl_ch)] = aln
            return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                                 mdl_chains_without_chem_mapping, one_to_one, alns)

        if strategy == "heuristic":
            if _NMappingsWithin(self.chem_groups, chem_mapping,
                                heuristic_n_max_naive):
                strategy = "naive"
            else:
                strategy = "greedy_full"

        mapping = None
        opt_lddt = None

        if strategy == "naive":
            mapping, opt_lddt = _lDDTNaive(self.target, mdl, inclusion_radius,
                                           thresholds, self.chem_groups,
                                           chem_mapping, ref_mdl_alns,
                                           self.n_max_naive)
        else:
            # its one of the greedy strategies - setup greedy searcher
            the_greed = _lDDTGreedySearcher(self.target, mdl, self.chem_groups,
                                            chem_mapping, ref_mdl_alns,
                                            inclusion_radius=inclusion_radius,
                                            thresholds=thresholds,
                                            steep_opt_rate=steep_opt_rate)
            if strategy == "greedy_full":
                mapping = _lDDTGreedyFull(the_greed)
            elif strategy == "greedy_block":
                mapping = _lDDTGreedyBlock(the_greed, block_seed_size,
                                           block_blocks_per_chem_group)
            # cached => lDDT computation is fast here
            opt_lddt = the_greed.Score(mapping)

        alns = dict()
        for ref_group, mdl_group in zip(self.chem_groups, mapping):
            for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                if ref_ch is not None and mdl_ch is not None:
                    aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                    alns[(ref_ch, mdl_ch)] = aln

        return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                             mdl_chains_without_chem_mapping, mapping, alns,
                             opt_score = opt_lddt)


    def GetQSScoreMapping(self, model, contact_d = 12.0, strategy = "heuristic",
                          block_seed_size = 5, block_blocks_per_chem_group = 5,
                          heuristic_n_max_naive = 40320, steep_opt_rate = None,
                          chem_mapping_result = None,
                          greedy_prune_contact_map = True):
        """ Identify chain mapping based on QSScore

        Scoring is based on CA/C3' positions which are present in all chains of
        a :attr:`chem_groups` as well as the *model* chains which are mapped to
        that respective chem group.

        The following strategies are available:

        * **naive**: Naively iterate all possible mappings and return best based
                     on QS score.

        * **greedy_full**: try multiple seeds for greedy extension, i.e. try
          all ref/mdl chain combinations within the respective chem groups and
          retain the mapping leading to the best QS-score. 

        * **greedy_block**: try multiple seeds for greedy extension, i.e. try
          all ref/mdl chain combinations within the respective chem groups and
          extend them to *block_seed_size*. *block_blocks_per_chem_group*
          for each chem group are selected for exhaustive extension.

        * **heuristic**: Uses *naive* strategy if number of possible mappings
          is within *heuristic_n_max_naive*. The default of 40320 corresponds
          to an octamer (8!=40320). A structure with stoichiometry A6B2 would be
          6!*2!=1440 etc. If the number of possible mappings is larger,
          *greedy_full* is used.

        Sets :attr:`MappingResult.opt_score` in case of no trivial one-to-one
        mapping.

        :param model: Model to map
        :type model: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :param contact_d: Max distance between two residues to be considered as 
                          contact in qs scoring
        :type contact_d: :class:`float` 
        :param strategy: Strategy for sampling, must be in ["naive",
                         greedy_full", "greedy_block"]
        :type strategy: :class:`str`
        :param chem_mapping_result: Pro param. The result of
                                    :func:`~GetChemMapping` where you provided
                                    *model*. If set, *model* parameter is not
                                    used.
        :type chem_mapping_result: :class:`tuple`
        :param greedy_prune_contact_map: Relevant for all strategies that use
                                         greedy extensions. If True, only chains
                                         with at least 3 contacts (8A CB
                                         distance) towards already mapped chains
                                         in trg/mdl are considered for
                                         extension. All chains that give a
                                         potential non-zero QS-score increase
                                         are used otherwise (at least one
                                         contact within 12A). The consequence
                                         is reduced runtime and usually no
                                         real reduction in accuracy.
        :returns: A :class:`MappingResult`
        """

        strategies = ["naive", "greedy_full", "greedy_block", "heuristic"]
        if strategy not in strategies:
            raise RuntimeError(f"strategy must be {strategies}")

        if chem_mapping_result is None:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            self.GetChemMapping(model)
        else:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            chem_mapping_result
        ref_mdl_alns =  _GetRefMdlAlns(self.chem_groups,
                                       self.chem_group_alignments,
                                       chem_mapping,
                                       chem_group_alns)
        # check for the simplest case
        one_to_one = _CheckOneToOneMapping(self.chem_groups, chem_mapping)
        if one_to_one is not None:
            alns = dict()
            for ref_group, mdl_group in zip(self.chem_groups, one_to_one):
                for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                    if ref_ch is not None and mdl_ch is not None:
                        aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                        alns[(ref_ch, mdl_ch)] = aln
            return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                                 mdl_chains_without_chem_mapping, one_to_one, alns)

        if strategy == "heuristic":
            if _NMappingsWithin(self.chem_groups, chem_mapping,
                                heuristic_n_max_naive):
                strategy = "naive"
            else:
                strategy = "greedy_full"

        mapping = None
        opt_qsscore = None

        if strategy == "naive":
            mapping, opt_qsscore = _QSScoreNaive(self.target, mdl,
                                                 self.chem_groups,
                                                 chem_mapping, ref_mdl_alns,
                                                 contact_d, self.n_max_naive)
        else:
            # its one of the greedy strategies - setup greedy searcher
            the_greed = _QSScoreGreedySearcher(self.target, mdl,
                                               self.chem_groups,
                                               chem_mapping, ref_mdl_alns,
                                               contact_d = contact_d,
                                               steep_opt_rate=steep_opt_rate,
                                               greedy_prune_contact_map = greedy_prune_contact_map)
            if strategy == "greedy_full":
                mapping = _QSScoreGreedyFull(the_greed)
            elif strategy == "greedy_block":
                mapping = _QSScoreGreedyBlock(the_greed, block_seed_size,
                                              block_blocks_per_chem_group)
            # cached => QSScore computation is fast here
            opt_qsscore = the_greed.Score(mapping, check=False).QS_global
              
        alns = dict()
        for ref_group, mdl_group in zip(self.chem_groups, mapping):
            for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                if ref_ch is not None and mdl_ch is not None:
                    aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                    alns[(ref_ch, mdl_ch)] = aln

        return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                             mdl_chains_without_chem_mapping, mapping, alns,
                             opt_score = opt_qsscore)

    def GetRMSDMapping(self, model, strategy = "heuristic", subsampling=50,
                       chem_mapping_result = None, heuristic_n_max_naive = 120):
        """Identify chain mapping based on minimal RMSD superposition

        Superposition and scoring is based on CA/C3' positions which are present
        in all chains of a :attr:`chem_groups` as well as the *model*
        chains which are mapped to that respective chem group.

        The following strategies are available:

        * **naive**: Naively iterate all possible mappings and return the one
          with lowes RMSD.

        * **greedy_single**: perform all vs. all single chain superpositions
          within the respective ref/mdl chem groups to use as starting points.
          For each starting point, iteratively add the model/target chain pair
          with lowest RMSD until a full mapping is achieved. The mapping with
          lowest RMSD is returned.

        * **greedy_single_centroid**: Same as *greedy_single* but iteratively
          adds model/target chain pairs with lowest centroid distance. The
          mapping with the lowest centroid RMSD is returned. This is mainly for
          evaluation purposes. One known failure mode is that intertwined
          structures may have multiple centroids sitting on top of each other.
          RMSD and thus *greedy_single* are better able to disentangle this
          situation.

        * **greedy_iterative**: Same as greedy_single_rmsd exept that the
          transformation gets updated with each added chain pair.

        * **heuristic**: Uses *naive* strategy if number of possible mappings
          is within *heuristic_n_max_naive*. The default of 120 corresponds
          to a homo-pentamer (5!=120). If the number of possible mappings is
          larger, *greedy_iterative* is used.

        :param model: Model to map
        :type model: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :param strategy: Strategy for sampling. Must be in ["naive",
                         "greedy_single", "greedy_iterative"]
        :type strategy: :class:`str`
        :param subsampling: If given, only an equally distributed subset
                            of CA/C3' positions in each chain are used for
                            superposition/scoring.
        :type subsampling: :class:`int`
        :param chem_mapping_result: Pro param. The result of
                                    :func:`~GetChemMapping` where you provided
                                    *model*. If set, *model* parameter is not
                                    used.
        :type chem_mapping_result: :class:`tuple`
        :returns: A :class:`MappingResult`
        """

        strategies = ["naive", "greedy_single", "greedy_single_centroid",
                      "greedy_iterative", "heuristic"]

        if strategy not in strategies:
            raise RuntimeError(f"strategy must be {strategies}")

        if chem_mapping_result is None:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            self.GetChemMapping(model)
        else:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            chem_mapping_result
        ref_mdl_alns =  _GetRefMdlAlns(self.chem_groups,
                                       self.chem_group_alignments,
                                       chem_mapping,
                                       chem_group_alns)

        # check for the simplest case
        one_to_one = _CheckOneToOneMapping(self.chem_groups, chem_mapping)
        if one_to_one is not None:
            alns = dict()
            for ref_group, mdl_group in zip(self.chem_groups, one_to_one):
                for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                    if ref_ch is not None and mdl_ch is not None:
                        aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                        alns[(ref_ch, mdl_ch)] = aln
            return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                                 mdl_chains_without_chem_mapping, one_to_one, alns)

        trg_group_pos, mdl_group_pos = _GetRefPos(self.target, mdl,
                                                  self.chem_group_alignments,
                                                  chem_group_alns,
                                                  max_pos = subsampling)

        if strategy == "heuristic":
            if _NMappingsWithin(self.chem_groups, chem_mapping,
                                heuristic_n_max_naive):
                strategy = "naive"
            else:
                strategy = "greedy_iterative"

        mapping = None

        if strategy.startswith("greedy"):
            # get transforms of any mdl chain onto any trg chain in same chem
            # group that fulfills gdtts threshold
            initial_transforms = list()
            initial_mappings = list()
            for trg_pos, trg_chains, mdl_pos, mdl_chains in zip(trg_group_pos,
                                                                self.chem_groups,
                                                                mdl_group_pos,
                                                                chem_mapping):
                for t_pos, t in zip(trg_pos, trg_chains):
                    for m_pos, m in zip(mdl_pos, mdl_chains):
                        if len(t_pos) >= 3 and len(m_pos) >= 3:
                            transform = _GetSuperposition(m_pos, t_pos,
                                                          False).transformation
                            initial_transforms.append(transform)
                            initial_mappings.append((t,m))

            if strategy == "greedy_single":
                mapping = _SingleRigidRMSD(initial_transforms,
                                           initial_mappings,
                                           self.chem_groups,
                                           chem_mapping,
                                           trg_group_pos,
                                           mdl_group_pos)

            elif strategy == "greedy_single_centroid":
                mapping = _SingleRigidCentroid(initial_transforms,
                                               initial_mappings,
                                               self.chem_groups,
                                               chem_mapping,
                                               trg_group_pos,
                                               mdl_group_pos)

            elif strategy == "greedy_iterative":
                mapping = _IterativeRigidRMSD(initial_transforms,
                                              initial_mappings,
                                              self.chem_groups, chem_mapping,
                                              trg_group_pos, mdl_group_pos)
        elif strategy == "naive":
            mapping = _NaiveRMSD(self.chem_groups, chem_mapping,
                                 trg_group_pos, mdl_group_pos,
                                 self.n_max_naive)

        # translate mapping format and return
        final_mapping = list()
        for ref_chains in self.chem_groups:
            mapped_mdl_chains = list()
            for ref_ch in ref_chains:
                if ref_ch in mapping:
                    mapped_mdl_chains.append(mapping[ref_ch])
                else:
                    mapped_mdl_chains.append(None)
            final_mapping.append(mapped_mdl_chains)

        alns = dict()
        for ref_group, mdl_group in zip(self.chem_groups, final_mapping):
            for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                if ref_ch is not None and mdl_ch is not None:
                    aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                    alns[(ref_ch, mdl_ch)] = aln

        return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                             mdl_chains_without_chem_mapping, final_mapping, alns)


    def GetAFMMapping(self, model, chem_mapping_result = None):
        """Identify chain mapping as in AlphaFold-Multimer (AFM)

        Described in section 7.3 of

        Richard Evans, Michael O’Neill, Alexander Pritzel, Natasha Antropova,
        Andrew Senior, Tim Green, Augustin Žídek, Russ Bates, Sam Blackwell,
        Jason Yim, et al. Protein complex prediction with AlphaFold-Multimer.
        bioRxiv preprint bioRxiv:10.1101/2021.10.04.463034, 2021.

        To summarize (largely follows the description in the AF-Multimer paper):
        One anchor chain in the ground truth (reference) is selected. If the
        reference has stoichiometry A3B2, an arbitary chain in B is selected
        as it has smaller ambiguity. In a tie, for example A2B2, the longest
        chain in A, B is selected.

        Given a model chain with same sequence as the reference anchor chain,
        a CA-RMSD (C3' for nucleotides) based superposition is performed. Chains
        are then greedily assigned by minimum distance of their geometric
        centers. This procedure is repeated for every model chain with same
        sequence and the assignment with minimal RMSD of the geometric centers
        is returned.

        A modification of this algorithm allows to deal with different
        stoichiometries in reference and model. In the anchor selection, this
        function ensures that there is at least one model chain that can be
        mapped to this anchor. If the logic above does not identify a mappable
        chain pair for the smallest group, it continues with the second smallest
        group etc.

        :param model: Model to map
        :type model: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :param chem_mapping_result: Pro param. The result of
                                    :func:`~GetChemMapping` where you provided
                                    *model*. If set, *model* parameter is not
                                    used.
        :type chem_mapping_result: :class:`tuple`
        :returns: A :class:`MappingResult`
        """
        if chem_mapping_result is None:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            self.GetChemMapping(model)
        else:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            chem_mapping_result
        ref_mdl_alns =  _GetRefMdlAlns(self.chem_groups,
                                       self.chem_group_alignments,
                                       chem_mapping,
                                       chem_group_alns)

        # check for the simplest case
        one_to_one = _CheckOneToOneMapping(self.chem_groups, chem_mapping)
        if one_to_one is not None:
            alns = dict()
            for ref_group, mdl_group in zip(self.chem_groups, one_to_one):
                for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                    if ref_ch is not None and mdl_ch is not None:
                        aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                        alns[(ref_ch, mdl_ch)] = aln
            return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                                 mdl_chains_without_chem_mapping, one_to_one, alns)

        # Select anchor chain in reference
        ref_group_idx = None
        ref_ch = None

        chem_group_sizes = list(set([len(g) for g in self.chem_groups]))
        chem_group_sizes.sort()

        for min_size in chem_group_sizes:
            min_chem_groups = list()
            for chem_group_idx, chem_group in enumerate(self.chem_groups):
                if len(chem_group) == min_size:
                    min_chem_groups.append(chem_group_idx)
            if len(min_chem_groups) == 1:
                if len(chem_mapping[min_chem_groups[0]]) > 0:
                    # Unique smallest chem group that has at least one
                    # model chain for mapping
                    # => select arbitrary chain
                    ref_group_idx = min_chem_groups[0]
                    ref_ch = self.chem_groups[min_chem_groups[0]][0]
            else:
                # No unique smallest chem group
                # => select the largest chain from any of these chem groups
                #    that has at least one model chain for mapping
                n_max = 0
                for chem_group_idx in min_chem_groups:
                    if len(chem_mapping[chem_group_idx]) > 0:
                        for ch in self.chem_groups[chem_group_idx]:
                            n = self.target.FindChain(ch).GetResidueCount()
                            if n > n_max:
                                n_max = n
                                ref_group_idx = chem_group_idx
                                ref_ch = ch
            if ref_group_idx is not None and ref_ch is not None:
                break

        # One transformation for each model chain that can be mapped to this one
        # anchor in the reference
        ref_bb_pos = _GetBBPos(self.target)
        mdl_bb_pos = _GetBBPos(mdl)
        transformations = list()
        for mdl_ch in chem_mapping[ref_group_idx]:
            aln = ref_mdl_alns[(ref_ch, mdl_ch)]
            # assertion can be removed after some testing
            l1 = len(ref_bb_pos[ref_ch])
            l2 = len(aln.GetSequence(0).GetGaplessString())
            assert(l1 == l2)
            l1 = len(mdl_bb_pos[mdl_ch])
            l2 = len(aln.GetSequence(1).GetGaplessString())
            assert(l1 == l2)
            # extract aligned positions
            ref_idx = 0
            mdl_idx = 0
            ref_pos = geom.Vec3List()
            mdl_pos = geom.Vec3List()
            for col in aln:
                if col[0] != '-' and col[1] != '-':
                    ref_pos.append(ref_bb_pos[ref_ch][ref_idx])
                    mdl_pos.append(mdl_bb_pos[mdl_ch][mdl_idx])
                if col[0] != '-':
                    ref_idx += 1
                if col[1] != '-':
                    mdl_idx += 1
            t = _GetSuperposition(mdl_pos, ref_pos, False).transformation
            transformations.append(t)

        ref_centers = {k: v.center for k,v in ref_bb_pos.items()}
        mdl_chains = list()
        mdl_centers = list()
        for k,v in mdl_bb_pos.items():
            mdl_chains.append(k)
            mdl_centers.append(v.center)
        mdl_centers = geom.Vec3List(mdl_centers)

        best_rmsd = float("inf") 
        best_mapping = None # k: ref_ch, v: mdl_ch

        for t in transformations:
            tmp = geom.Vec3List(mdl_centers)
            tmp.ApplyTransform(t)
            # somehow the Vec3List did not really work in a dict comprehension
            t_mdl_centers = dict()
            for i in range(len(tmp)):
                t_mdl_centers[mdl_chains[i]] = tmp[i]

            # one entry for each possible assignment
            # (<squared_distance>, <ref_ch>, <mdl_ch>)
            tmp = list()
            for a, b in zip(self.chem_groups, chem_mapping):
                for ref_ch in a:
                    for mdl_ch in b:
                        d = geom.Length2(ref_centers[ref_ch]-t_mdl_centers[mdl_ch])
                        tmp.append((d, ref_ch, mdl_ch))
            tmp.sort()

            mapping = dict()
            mapped_mdl_chains = set()
            for item in tmp:
                if item[1] not in mapping and item[2] not in mapped_mdl_chains:
                    mapping[item[1]] = item[2]
                    mapped_mdl_chains.add(item[2])
       
            if len(mapping) == 0:
                raise RuntimeError("Empty mapping in GetAFMMapping")
            elif len(mapping) == 1:
                # by definition zero
                rmsd = 0.0
            elif len(mapping) == 2:
                # no superposition possible with two positions
                # derive rmsd from the distance difference between
                # the centroid pairs in reference and model
                ref_p = [ref_centers[k] for k in mapping.keys()]
                mdl_p = [t_mdl_centers[v] for v in mapping.values()]
                ref_d = geom.Distance(ref_p[0], ref_p[1])
                mdl_d = geom.Distance(mdl_p[0], mdl_p[1])
                # compute RMSD when placing pair of coordinates with smaller
                # distance in the middle of pair of cooridnates with larger
                # distance
                dd = abs(ref_d-mdl_d) # distance difference
                # rmsd = sqrt(1/2 * ((dd/2)**2 + (dd/2)**2))
                # => rmsd = dd/2
                rmsd = dd/2
            else:
                # go for classic Kabsch superposition
                mapped_ref_centers = geom.Vec3List()
                mapped_mdl_centers = geom.Vec3List()
                for ref_ch, mdl_ch in mapping.items():
                    mapped_ref_centers.append(ref_centers[ref_ch])
                    mapped_mdl_centers.append(t_mdl_centers[mdl_ch])
                rmsd = _GetSuperposition(mapped_ref_centers,
                                         mapped_mdl_centers, False).rmsd
            if rmsd < best_rmsd:
                best_rmsd = rmsd
                best_mapping = mapping

        # translate mapping format and return
        final_mapping = list()
        for ref_chains in self.chem_groups:
            mapped_mdl_chains = list()
            for ref_ch in ref_chains:
                if ref_ch in best_mapping:
                    mapped_mdl_chains.append(best_mapping[ref_ch])
                else:
                    mapped_mdl_chains.append(None)
            final_mapping.append(mapped_mdl_chains)

        alns = dict()
        for ref_group, mdl_group in zip(self.chem_groups, final_mapping):
            for ref_ch, mdl_ch in zip(ref_group, mdl_group):
                if ref_ch is not None and mdl_ch is not None:
                    aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                    alns[(ref_ch, mdl_ch)] = aln

        return MappingResult(self.target, mdl, self.chem_groups, chem_mapping,
                             mdl_chains_without_chem_mapping, final_mapping, alns)


    def GetMapping(self, model, n_max_naive = 40320):
        """ Convenience function to get mapping with currently preferred method

        If number of possible chain mappings is <= *n_max_naive*, a naive
        QS-score mapping is performed and optimal QS-score is guaranteed.
        For anything else, a QS-score mapping with the greedy_full strategy is
        performed (greedy_prune_contact_map = True). The default for
        *n_max_naive* of 40320 corresponds to an octamer (8!=40320). A
        structure with stoichiometry A6B2 would be 6!*2!=1440 etc.

        If :attr:`~target` has nucleotide sequences, the QS-score target
        function is replaced with a backbone only lDDT score that has
        an inclusion radius of 30A. 
        """
        if len(self.polynuc_seqs) > 0:
            return self.GetlDDTMapping(model, strategy = "heuristic",
                                       inclusion_radius = 30.0,
                                       heuristic_n_max_naive = n_max_naive)
        else:
            return self.GetQSScoreMapping(model, strategy="heuristic",
                                          greedy_prune_contact_map=True,
                                          heuristic_n_max_naive = n_max_naive)

    def GetRepr(self, substructure, model, topn=1, inclusion_radius=15.0,
                thresholds=[0.5, 1.0, 2.0, 4.0], bb_only=False,
                only_interchain=False, chem_mapping_result = None,
                global_mapping = None):
        """ Identify *topn* representations of *substructure* in *model*

        *substructure* defines a subset of :attr:`~target` for which one
        wants the *topn* representations in *model*. Representations are scored
        and sorted by lDDT.

        :param substructure: A :class:`ost.mol.EntityView` which is a subset of
                             :attr:`~target`. Should be selected with the
                             OpenStructure query language. Example: if you're
                             interested in residues with number 42,43 and 85 in
                             chain A:
                             ``substructure=mapper.target.Select("cname=A and rnum=42,43,85")``
                             A :class:`RuntimeError` is raised if *substructure*
                             does not refer to the same underlying
                             :class:`ost.mol.EntityHandle` as :attr:`~target`.
        :type substructure: :class:`ost.mol.EntityView`
        :param model: Structure in which one wants to find representations for
                      *substructure*
        :type model: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :param topn: Max number of representations that are returned
        :type topn: :class:`int`
        :param inclusion_radius: Inclusion radius for lDDT
        :type inclusion_radius: :class:`float`
        :param thresholds: Thresholds for lDDT
        :type thresholds: :class:`list` of :class:`float`
        :param bb_only: Only consider backbone atoms in lDDT computation
        :type bb_only: :class:`bool`
        :param only_interchain: Only score interchain contacts in lDDT. Useful
                                if you want to identify interface patches.
        :type only_interchain: :class:`bool`
        :param chem_mapping_result: Pro param. The result of
                                    :func:`~GetChemMapping` where you provided
                                    *model*. If set, *model* parameter is not
                                    used.
        :type chem_mapping_result: :class:`tuple`
        :param global_mapping: Pro param. Specify a global mapping result. This
                               fully defines the desired representation in the
                               model but extracts it and enriches it with all
                               the nice attributes of :class:`ReprResult`.
                               The target attribute in *global_mapping* must be
                               of the same entity as self.target and the model
                               attribute of *global_mapping* must be of the same
                               entity as *model*.
        :type global_mapping: :class:`MappingResult`
        :returns: :class:`list` of :class:`ReprResult`
        """

        if topn < 1:
            raise RuntimeError("topn must be >= 1")

        if global_mapping is not None:
            # ensure that this mapping is derived from the same structures
            if global_mapping.target.handle.GetHashCode() != \
               self.target.handle.GetHashCode():
               raise RuntimeError("global_mapping.target must be the same "
                                  "entity as self.target")
            if global_mapping.model.handle.GetHashCode() != \
               model.handle.GetHashCode():
               raise RuntimeError("global_mapping.model must be the same "
                                  "entity as model param")

        # check whether substructure really is a subset of self.target
        for r in substructure.residues:
            ch_name = r.GetChain().GetName()
            rnum = r.GetNumber()
            target_r = self.target.FindResidue(ch_name, rnum)
            if not target_r.IsValid():
                raise RuntimeError(f"substructure has residue "
                                   f"{r.GetQualifiedName()} which is not in "
                                   f"self.target")
            if target_r.handle.GetHashCode() != r.handle.GetHashCode():
                raise RuntimeError(f"substructure has residue "
                                   f"{r.GetQualifiedName()} which has an "
                                   f"equivalent in self.target but it does "
                                   f"not refer to the same underlying "
                                   f"EntityHandle")
            for a in r.atoms:
                target_a = target_r.FindAtom(a.GetName())
                if not target_a.IsValid():
                    raise RuntimeError(f"substructure has atom "
                                       f"{a.GetQualifiedName()} which is not "
                                       f"in self.target")
                if a.handle.GetHashCode() != target_a.handle.GetHashCode():
                    raise RuntimeError(f"substructure has atom "
                                       f"{a.GetQualifiedName()} which has an "
                                       f"equivalent in self.target but it does "
                                       f"not refer to the same underlying "
                                       f"EntityHandle")

            # check whether it contains either CA or C3'
            ca = r.FindAtom("CA")
            c3 = r.FindAtom("C3'") # FindAtom with prime in string is tested
                                   # and works
            if not ca.IsValid() and not c3.IsValid():
                raise RuntimeError("All residues in substructure must contain "
                                   "a backbone atom named CA or C3\'")

        # perform mapping and alignments on full structures
        if chem_mapping_result is None:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            self.GetChemMapping(model)
        else:
            chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
            chem_mapping_result
        ref_mdl_alns =  _GetRefMdlAlns(self.chem_groups,
                                       self.chem_group_alignments,
                                       chem_mapping,
                                       chem_group_alns)

        # Get residue indices relative to full target chain 
        substructure_res_indices = dict()
        for ch in substructure.chains:
            full_ch = self.target.FindChain(ch.GetName())
            idx = [full_ch.GetResidueIndex(r.GetNumber()) for r in ch.residues]
            substructure_res_indices[ch.GetName()] = idx

        # strip down variables to make them specific to substructure
        # keep only chem_groups which are present in substructure
        substructure_chem_groups = list()
        substructure_chem_mapping = list()
        
        chnames = set([ch.GetName() for ch in substructure.chains])
        for chem_group, mapping in zip(self.chem_groups, chem_mapping):
            substructure_chem_group = [ch for ch in chem_group if ch in chnames]
            if len(substructure_chem_group) > 0:
                substructure_chem_groups.append(substructure_chem_group)
                substructure_chem_mapping.append(mapping)

        # early stopping if no mdl chain can be mapped to substructure
        n_mapped_mdl_chains = sum([len(m) for m in substructure_chem_mapping])
        if n_mapped_mdl_chains == 0:
            return list()

        # strip the reference sequence in alignments to only contain
        # sequence from substructure
        substructure_ref_mdl_alns = dict()
        mdl_views = dict()
        for ch in mdl.chains:
            mdl_views[ch.GetName()] = _CSel(mdl, [ch.GetName()])
        for chem_group, mapping in zip(substructure_chem_groups,
                                       substructure_chem_mapping):
            for ref_ch in chem_group:
                for mdl_ch in mapping:
                    full_aln = ref_mdl_alns[(ref_ch, mdl_ch)]
                    ref_seq = full_aln.GetSequence(0)
                    # the ref sequence is tricky... we start with a gap only
                    # sequence and only add olcs as defined by the residue
                    # indices that we extracted before...
                    tmp = ['-'] * len(full_aln)
                    for idx in substructure_res_indices[ref_ch]:
                        idx_in_seq = ref_seq.GetPos(idx)
                        tmp[idx_in_seq] = ref_seq[idx_in_seq]
                    ref_seq = seq.CreateSequence(ref_ch, ''.join(tmp))
                    ref_seq.AttachView(_CSel(substructure, [ref_ch]))
                    mdl_seq = full_aln.GetSequence(1)
                    mdl_seq = seq.CreateSequence(mdl_seq.GetName(),
                                                 mdl_seq.GetString())
                    mdl_seq.AttachView(mdl_views[mdl_ch])
                    aln = seq.CreateAlignment()
                    aln.AddSequence(ref_seq)
                    aln.AddSequence(mdl_seq)
                    substructure_ref_mdl_alns[(ref_ch, mdl_ch)] = aln

        lddt_scorer = lddt.lDDTScorer(substructure,
                                      inclusion_radius = inclusion_radius,
                                      bb_only = bb_only)
        scored_mappings = list()

        if global_mapping:
            # construct mapping of substructure from global mapping
            flat_mapping = global_mapping.GetFlatMapping()
            mapping = list()
            for chem_group, chem_mapping in zip(substructure_chem_groups,
                                                substructure_chem_mapping):
                chem_group_mapping = list()
                for ch in chem_group:
                    if ch in flat_mapping:
                        mdl_ch = flat_mapping[ch]
                        if mdl_ch in chem_mapping:
                            chem_group_mapping.append(mdl_ch)
                        else:
                            chem_group_mapping.append(None)
                    else:
                        chem_group_mapping.append(None)
                mapping.append(chem_group_mapping)
            mappings = [mapping]
        else:
            mappings = list(_ChainMappings(substructure_chem_groups,
                                           substructure_chem_mapping,
                                           self.n_max_naive))

        # This step can be slow so give some hints in logs
        msg = "Computing initial ranking of %d chain mappings" % len(mappings)
        (ost.LogWarning if len(mappings) > 10000 else ost.LogInfo)(msg)

        for mapping in mappings:
            # chain_mapping and alns as input for lDDT computation
            lddt_chain_mapping = dict()
            lddt_alns = dict()
            n_res_aln = 0
            for ref_chem_group, mdl_chem_group in zip(substructure_chem_groups,
                                                      mapping):
                for ref_ch, mdl_ch in zip(ref_chem_group, mdl_chem_group):
                    # some mdl chains can be None
                    if mdl_ch is not None:
                        lddt_chain_mapping[mdl_ch] = ref_ch
                        aln = substructure_ref_mdl_alns[(ref_ch, mdl_ch)]
                        lddt_alns[mdl_ch] = aln
                        tmp = [int(c[0] != '-' and c[1] != '-') for c in aln]
                        n_res_aln += sum(tmp)
            # don't compute lDDT if no single residue in mdl and ref is aligned
            if n_res_aln == 0:
                continue

            lDDT, _ = lddt_scorer.lDDT(mdl, thresholds=thresholds,
                                       chain_mapping=lddt_chain_mapping,
                                       residue_mapping = lddt_alns,
                                       check_resnames = False,
                                       no_intrachain = only_interchain)

            if lDDT is None:
                ost.LogVerbose("No valid contacts in the reference")
                lDDT = 0.0 # that means, that we have not a single valid contact
                           # in lDDT. For the code below to work, we just set it
                           # to a terrible score => 0.0

            if len(scored_mappings) == 0:
                scored_mappings.append((lDDT, mapping))
            elif len(scored_mappings) < topn:
                scored_mappings.append((lDDT, mapping))
                scored_mappings.sort(reverse=True, key=lambda x: x[0])
            elif lDDT > scored_mappings[-1][0]:
                scored_mappings.append((lDDT, mapping))
                scored_mappings.sort(reverse=True, key=lambda x: x[0])
                scored_mappings = scored_mappings[:topn]

        # finalize and return
        results = list()
        for scored_mapping in scored_mappings:
            ref_view = substructure.handle.CreateEmptyView()
            mdl_view = mdl.handle.CreateEmptyView()
            for ref_ch_group, mdl_ch_group in zip(substructure_chem_groups,
                                                  scored_mapping[1]):
                for ref_ch, mdl_ch in zip(ref_ch_group, mdl_ch_group):
                    if ref_ch is not None and mdl_ch is not None:
                        aln = substructure_ref_mdl_alns[(ref_ch, mdl_ch)]
                        for col in aln:
                            if col[0] != '-' and col[1] != '-':
                                ref_view.AddResidue(col.GetResidue(0),
                                                    mol.ViewAddFlag.INCLUDE_ALL)
                                mdl_view.AddResidue(col.GetResidue(1),
                                                    mol.ViewAddFlag.INCLUDE_ALL)
            results.append(ReprResult(scored_mapping[0], substructure,
                                      ref_view, mdl_view))
        return results

    def GetNMappings(self, model):
        """ Returns number of possible mappings

        :param model: Model with chains that are mapped onto
                      :attr:`chem_groups`
        :type model: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        """
        chem_mapping, chem_group_alns, mdl_chains_without_chem_mapping, mdl = \
        self.GetChemMapping(model)
        return _NMappings(self.chem_groups, chem_mapping)

    def ProcessStructure(self, ent):
        """ Entity processing for chain mapping

        * Selects view containing peptide and nucleotide residues which have 
          required backbone atoms present - for peptide residues thats
          N, CA, C and CB (no CB for GLY), for nucleotide residues thats
          O5', C5', C4', C3' and O3'.
        * filters view by chain lengths, see *min_pep_length* and
          *min_nuc_length* in constructor
        * Extracts atom sequences for each chain in that view
        * If residue number alignments are used, strictly increasing residue
          numbers without insertion codes are ensured in each chain

        :param ent: Entity to process
        :type ent: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :returns: Tuple with 3 elements: 1) :class:`ost.mol.EntityView`
                  containing peptide and nucleotide residues 2)
                  :class:`ost.seq.SequenceList` containing ATOMSEQ sequences
                  for each polypeptide chain in returned view
                  3) same for polynucleotide chains
        """
        view = ent.CreateEmptyView()
        exp_pep_atoms = ["N", "CA", "C", "CB"]
        exp_nuc_atoms = ["\"O5'\"", "\"C5'\"", "\"C4'\"", "\"C3'\"", "\"O3'\""]
        pep_query = "peptide=true and aname=" + ','.join(exp_pep_atoms)
        nuc_query = "nucleotide=true and aname=" + ','.join(exp_nuc_atoms)

        pep_sel = ent.Select(pep_query)
        for r in pep_sel.residues:
            if len(r.atoms) == 4:
                view.AddResidue(r.handle, mol.INCLUDE_ALL)
            elif r.name == "GLY" and len(r.atoms) == 3:
                atom_names = [a.GetName() for a in r.atoms]
                if sorted(atom_names) == ["C", "CA", "N"]:
                    view.AddResidue(r.handle, mol.INCLUDE_ALL)

        nuc_sel = ent.Select(nuc_query)
        for r in nuc_sel.residues:
            if len(r.atoms) == 5:
                view.AddResidue(r.handle, mol.INCLUDE_ALL)

        polypep_seqs = seq.CreateSequenceList()
        polynuc_seqs = seq.CreateSequenceList()

        if len(view.residues) == 0:
            # no residues survived => return
            return (view, polypep_seqs, polynuc_seqs)

        for ch in view.chains:
            n_res = len(ch.residues)
            n_pep = sum([r.IsPeptideLinking() for r in ch.residues])
            n_nuc = sum([r.IsNucleotideLinking() for r in ch.residues])

            # guarantee that we have either pep or nuc (no mix of the two)
            if n_pep > 0 and n_nuc > 0:
                raise RuntimeError(f"Must not mix peptide and nucleotide linking "
                                   f"residues in same chain ({ch.GetName()})")

            if (n_pep + n_nuc) != n_res:
                raise RuntimeError("All residues must either be peptide_linking "
                                   "or nucleotide_linking")

            # filter out short chains
            if n_pep > 0 and n_pep < self.min_pep_length:
                ost.LogWarning("Skipping short peptide chain: %s" % ch.name)
                continue

            if n_nuc > 0 and n_nuc < self.min_nuc_length:
                ost.LogWarning("Skipping short nucleotide chain: %s" % ch.name)
                continue

            # the superfast residue number based alignment adds some 
            # restrictions on the numbers themselves:
            # 1) no insertion codes 2) strictly increasing
            if self.resnum_alignments:
                # check if no insertion codes are present in residue numbers
                ins_codes = [r.GetNumber().GetInsCode() for r in ch.residues]
                if len(set(ins_codes)) != 1 or ins_codes[0] != '\0':
                    raise RuntimeError("Residue numbers in input structures must not "
                                       "contain insertion codes")

                # check if residue numbers are strictly increasing
                nums = [r.GetNumber().GetNum() for r in ch.residues]
                if not all(i < j for i, j in zip(nums, nums[1:])):
                    raise RuntimeError("Residue numbers in input structures must be "
                                       "strictly increasing for each chain")

            s = ''.join([r.one_letter_code for r in ch.residues])
            s = seq.CreateSequence(ch.GetName(), s)
            if n_pep == n_res:
                polypep_seqs.AddSequence(s)
            elif n_nuc == n_res:
                polynuc_seqs.AddSequence(s)
            else:
                raise RuntimeError("This shouldnt happen")

        if len(polypep_seqs) == 0 and len(polynuc_seqs) == 0:
            raise RuntimeError(f"No chain fulfilled minimum length requirement "
                               f"to be considered in chain mapping "
                               f"({self.min_pep_length} for peptide chains, "
                               f"{self.min_nuc_length} for nucleotide chains) "
                               f"- mapping failed")

        # select for chains for which we actually extracted the sequence
        chain_names = [s.name for s in polypep_seqs]
        chain_names += [s.name for s in polynuc_seqs]
        view = _CSel(view, chain_names)

        return (view, polypep_seqs, polynuc_seqs)

    def NWAlign(self, s1, s2, stype):
        """ Access to internal sequence alignment functionality

        Performs Needleman-Wunsch alignment with parameterization
        setup at ChainMapper construction

        :param s1: First sequence to align
        :type s1: :class:`ost.seq.SequenceHandle`
        :param s2: Second sequence to align
        :type s2: :class:`ost.seq.SequenceHandle`
        :param stype: Type of sequences to align, must be in
                      [:class:`ost.mol.ChemType.AMINOACIDS`,
                      :class:`ost.mol.ChemType.NUCLEOTIDES`]
        :returns: Pairwise alignment of s1 and s2
        """
        if stype == mol.ChemType.AMINOACIDS:
            return seq.alg.SemiGlobalAlign(s1, s2, self.pep_subst_mat,
                                           gap_open=self.pep_gap_open,
                                           gap_ext=self.pep_gap_ext)[0]
        elif stype == mol.ChemType.NUCLEOTIDES:
            return seq.alg.SemiGlobalAlign(s1, s2, self.nuc_subst_mat,
                                           gap_open=self.nuc_gap_open,
                                           gap_ext=self.nuc_gap_ext)[0]
        else:
            raise RuntimeError("Invalid ChemType")
        return aln

    def SEQRESAlign(self, seqres, s, s_ent):
        """ Access to internal sequence alignment functionality

        Performs alignment on SEQRES. Residue numbers for *s* are
        extracted from *s_ent*. Residue numbers start from 1, i.e.
        1 aligns to the first element in *seqres*.

        :param seqres: SEQRES sequence
        :type seqres: :class:`ost.seq.SequenceHandle`
        :param s: Sequence to align
        :type s: :class:`ost.seq.SequenceHandle`
        :param s_ent: Structure which must contain a chain of same name as *s*.
                      This chain must have the exact same number of residues
                      as characters in *s*.
        :type s_ent: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        """

        ch = s_ent.FindChain(s.name)

        if not ch.IsValid():
            raise RuntimeError("s_ent lacks required chain in SEQRESAlign")

        if len(s) != ch.GetResidueCount():
            raise RuntimeError("Sequence/structure mismatch in SEQRESAlign")

        rnums = [r.GetNumber().GetNum() for r in ch.residues]
        max_rnum = max(len(seqres), max(rnums))

        # potentially add some trailing gaps
        seqres_s = seqres.GetGaplessString() + '-'*(max_rnum-len(seqres))

        olcs = ['-'] * max_rnum
        for olc, num in zip(s, rnums):
            olcs[num-1] = olc

        aln = seq.CreateAlignment()
        aln.AddSequence(seq.CreateSequence(seqres.GetName(), seqres_s))
        aln.AddSequence(seq.CreateSequence(s.GetName(), ''.join(olcs)))
        return aln

    def ResNumAlign(self, s1, s2, s1_ent, s2_ent):
        """ Access to internal sequence alignment functionality

        Performs residue number based alignment. Residue numbers are extracted
        from *s1_ent*/*s2_ent*.

        :param s1: First sequence to align
        :type s1: :class:`ost.seq.SequenceHandle`
        :param s2: Second sequence to align
        :type s2: :class:`ost.seq.SequenceHandle`
        :param s1_ent: Structure as source for residue numbers in *s1*. Must
                       contain a chain named after sequence name in *s1*. This
                       chain must have the exact same number of residues as
                       characters in s1.
        :type s1_ent: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`
        :param s2_ent: Same for *s2*.
        :type s2_ent: :class:`ost.mol.EntityView`/:class:`ost.mol.EntityHandle`

        :returns: Pairwise alignment of s1 and s2
        """
        ch1 = s1_ent.FindChain(s1.name)
        ch2 = s2_ent.FindChain(s2.name)

        if not ch1.IsValid():
            raise RuntimeError("s1_ent lacks requested chain in ResNumAlign")

        if not ch2.IsValid():
            raise RuntimeError("s2_ent lacks requested chain in ResNumAlign")

        if len(s1) != ch1.GetResidueCount():
            raise RuntimeError("Sequence/structure mismatch in ResNumAlign")

        if len(s2) != ch2.GetResidueCount():
            raise RuntimeError("Sequence/structure mismatch in ResNumAlign")

        rnums1 = [r.GetNumber().GetNum() for r in ch1.residues]
        rnums2 = [r.GetNumber().GetNum() for r in ch2.residues]

        min_num = min(rnums1[0], rnums2[0])
        max_num = max(rnums1[-1], rnums2[-1])
        aln_length = max_num - min_num + 1

        aln_s1 = ['-'] * aln_length
        for olc, rnum in zip(s1, rnums1):
            aln_s1[rnum-min_num] = olc

        aln_s2 = ['-'] * aln_length
        for olc, rnum in zip(s2, rnums2):
            aln_s2[rnum-min_num] = olc

        aln = seq.CreateAlignment()
        aln.AddSequence(seq.CreateSequence(s1.GetName(), ''.join(aln_s1)))
        aln.AddSequence(seq.CreateSequence(s2.GetName(), ''.join(aln_s2)))
        return aln


    def _ComputeChemGroups(self):
        """ Sets properties :attr:`~chem_groups`,
        :attr:`~chem_group_alignments`, :attr:`~chem_group_ref_seqs`,
        :attr:`~chem_group_types`
        """

        if self.seqres_set:
            self._chem_group_alignments, self._chem_group_types =\
            self._ChemGroupAlignmentsFromSEQRES()
        else:
            self._chem_group_alignments, self._chem_group_types =\
            self._ChemGroupAlignmentsFromATOMSEQ()

        self._chem_group_ref_seqs = seq.CreateSequenceList()
        for a in self.chem_group_alignments:
            s = seq.CreateSequence(a.GetSequence(0).GetName(),
                                   a.GetSequence(0).GetGaplessString())
            self._chem_group_ref_seqs.AddSequence(s)

        self._chem_groups = list()
        for a in self.chem_group_alignments:
            group = list()
            for s_idx in range(1, a.GetCount()):
                s = a.GetSequence(s_idx)
                group.append(s.GetName())
            self._chem_groups.append(group)


    def _ChemGroupAlignmentsFromSEQRES(self):
        """ Groups target sequences based on SEQRES

        returns tuple that can be set as self._chem_group_alignments and
        self._chem_group_types
        """
        pep_groups = self._GroupSequencesSEQRES(self.polypep_seqs)
        nuc_groups = self._GroupSequencesSEQRES(self.polynuc_seqs)
        group_types = [mol.ChemType.AMINOACIDS] * len(pep_groups)
        group_types += [mol.ChemType.NUCLEOTIDES] * len(nuc_groups)
        groups = pep_groups
        groups.extend(nuc_groups)

        return (groups, group_types)


    def _GroupSequencesSEQRES(self, poly_seqs):

        alns = dict()

        for poly_seq in poly_seqs:
            sname = poly_seq.GetName()
            seqres_name = self.trg_seqres_mapping[sname]
            if seqres_name not in alns:
                aln = seq.CreateAlignment()
                seqres = None
                for s in self.seqres:
                    if s.GetName() == seqres_name:
                        seqres = s
                        break
                if seqres is None:
                    # each element in self.trg_seqres_mapping is guaranteed
                    # to have a SEQRES counterpart as checked in ChainMapper
                    # constructor. So we should never end up here.
                    raise RuntimeError("You should never get here - contact "
                                       "OST developer")
                aln.AddSequence(seqres)
                alns[seqres_name] = aln
            seqres = alns[seqres_name].GetSequence(0)
            aln_length = seqres.GetLength()
            atomseq = ['-'] * aln_length
            trg_chain = self.target.FindChain(sname)
            assert(trg_chain.IsValid())
            assert(trg_chain.GetResidueCount() == len(poly_seq))
            for olc, r in zip(poly_seq, trg_chain.residues):
                num = r.GetNumber().GetNum()
                if num < 1 or num > aln_length:
                    raise RuntimeError(f"Observed residue with invalid number: "
                                       f"\"{r}\" which cannot be aligned to "
                                       f"seqres with id \"{seqres_name}\"")
                if olc != seqres[num-1]:
                    raise RuntimeError(f"Sequence mismatch of residue \"{r}\" "
                                       f"with olc \"{olc}\" and residue number "
                                       f"\"{num}\". Character at that location "
                                       f"in seqres: \"{seqres[num-1]}\"."
                                       f"Seqres name: \"{seqres_name}\"")
                atomseq[num-1] = olc
            atomseq = ''.join(atomseq)
            alns[seqres_name].AddSequence(seq.CreateSequence(sname, atomseq))

        return [aln for aln in alns.values()]


    def _ChemGroupAlignmentsFromATOMSEQ(self):
        """ Groups target sequences based on ATOMSEQ

        returns tuple that can be set as self._chem_group_alignments and
        self._chem_group_types
        """
        pep_groups = self._GroupSequences(self.polypep_seqs, self.pep_seqid_thr,
                                          self.min_pep_length,
                                          mol.ChemType.AMINOACIDS)
        nuc_groups = self._GroupSequences(self.polynuc_seqs, self.nuc_seqid_thr,
                                          self.min_nuc_length,
                                          mol.ChemType.NUCLEOTIDES)

        # pep_groups and nuc_groups give us alignments based on ATOMSEQ.
        # For example: If you have polymer chains A,B and C in the same
        # group and A is the longest one, you get an alignment that looks
        # like:
        # A: ASDFE
        # B: ASDF-
        # C: -SDFE
        #
        # however, the first sequence in chem group alignments must not be
        # bound to any ATOMSEQ and represent the reference sequence. In the
        # case of this function, this is simply a copy of sequence A:
        # REF: ASDFE
        # A:   ASDFE
        # B:   ASDF-
        # C:   -SDFE

        # do pep_groups
        tmp = list()
        for a in pep_groups:
            new_a = seq.CreateAlignment()
            new_a.AddSequence(a.GetSequence(0))
            for s_idx in range(a.GetCount()):
                new_a.AddSequence(a.GetSequence(s_idx))
            tmp.append(new_a)
        pep_groups = tmp

        # do nuc groups        
        tmp = list()
        for a in nuc_groups:
            new_a = seq.CreateAlignment()
            new_a.AddSequence(a.GetSequence(0))
            for s_idx in range(a.GetCount()):
                new_a.AddSequence(a.GetSequence(s_idx))
            tmp.append(new_a)
        nuc_groups = tmp

        group_types = [mol.ChemType.AMINOACIDS] * len(pep_groups)
        group_types += [mol.ChemType.NUCLEOTIDES] * len(nuc_groups)
        groups = pep_groups
        groups.extend(nuc_groups)

        return (groups, group_types)

    def _GroupSequences(self, seqs, seqid_thr, min_length, chem_type):
        """Get list of alignments representing groups of equivalent sequences
    
        :param seqid_thr: Threshold used to decide when two chains are identical.
        :type seqid_thr:  :class:`float`
        :param gap_thr: Additional threshold to avoid gappy alignments with high
                        seqid. Number of aligned columns must be at least this
                        number.
        :type gap_thr: :class:`int`
        :param aligner: Helper class to generate pairwise alignments
        :type aligner: :class:`_Aligner`
        :param chem_type: ChemType of seqs, must be in
                          [:class:`ost.mol.ChemType.AMINOACIDS`,
                          :class:`ost.mol.ChemType.NUCLEOTIDES`]
        :type chem_type: :class:`ost.mol.ChemType` 
        :returns: A list of alignments, one alignment for each group
                  with longest sequence (reference) as first sequence.
        :rtype: :class:`ost.seq.AlignmentList`
        """
        groups = list()
        for s_idx in range(len(seqs)):
            matching_group = None
            for g_idx in range(len(groups)):
                for g_s_idx in range(len(groups[g_idx])):
                    if self.resnum_alignments:
                        aln = self.ResNumAlign(seqs[s_idx],
                                               seqs[groups[g_idx][g_s_idx]],
                                               self.target, self.target)
                    else:
                        aln = self.NWAlign(seqs[s_idx],
                                           seqs[groups[g_idx][g_s_idx]],
                                           chem_type)
                    sid, n_aligned = _GetAlnPropsOne(aln)
                    if sid >= seqid_thr and n_aligned >= min_length:
                        matching_group = g_idx
                        break
                if matching_group is not None:
                    break
    
            if matching_group is None:
                groups.append([s_idx])
            else:
                groups[matching_group].append(s_idx)
    
        # sort based on sequence length
        sorted_groups = list()
        for g in groups:
            if len(g) > 1:
                tmp = sorted([[len(seqs[i]), i] for i in g], reverse=True)
                sorted_groups.append([x[1] for x in tmp])
            else:
                sorted_groups.append(g)
    
        # translate from indices back to sequences and directly generate alignments
        # of the groups with the longest (first) sequence as reference
        aln_list = seq.AlignmentList()
        for g in sorted_groups:
            if len(g) == 1:
                # aln with one single sequence
                aln_list.append(seq.CreateAlignment(seqs[g[0]]))
            else:
                # obtain pairwise aln of first sequence (reference) to all others
                alns = seq.AlignmentList()
                i = g[0]
                for j in g[1:]:
                    if self.resnum_alignments:
                        aln = self.ResNumAlign(seqs[i], seqs[j],
                                               self.target, self.target)
                    else:
                        aln = self.NWAlign(seqs[i], seqs[j], chem_type)
                    alns.append(aln)
                # and merge
                aln_list.append(seq.alg.MergePairwiseAlignments(alns, seqs[i]))
    
        return aln_list

    def _MapSequence(self, ref_seqs, ref_types, s, s_type, s_ent,
                     seq_id_thr=0.0, min_aln_length=0):
        """Tries top map *s* onto any of the sequences in *ref_seqs*
    
        Computes alignments of *s* to each of the reference sequences of equal type
        and sorts them by seqid*fraction_covered (seqid: sequence identity of
        aligned columns in alignment, fraction_covered: Fraction of non-gap
        characters in reference sequence that are covered by non-gap characters in
        *s*). Best scoring mapping is returned. Optionally, *seq_id*/
        *min_aln_length* thresholds can be enabled to avoid non-sensical mappings.
        However, *min_aln_length* only has an effect if *seq_id_thr* > 0!!!
    
        :param ref_seqs: Reference sequences 
        :type ref_seqs: :class:`ost.seq.SequenceList`
        :param ref_types: Types of reference sequences, e.g.
                          ost.mol.ChemType.AminoAcids
        :type ref_types: :class:`list` of :class:`ost.mol.ChemType`
        :param s: Sequence to map
        :type s: :class:`ost.seq.SequenceHandle`
        :param s_type: Type of *s*, only try mapping to sequences in *ref_seqs*
                       with equal type as defined in *ref_types*
        :param s_ent: Entity which represents *s*. Only relevant in case of
                      residue number alignments.
        :type s_ent: :class:`ost.mol.EntityHandle`/:class:`ost.mol.EntityView`
        :param seq_id_thr: Minimum sequence identity to be considered as match
        :type seq_id_thr: :class:`float`
        :param min_aln_length: Minimum number of aligned columns to be considered
                               as match. Only has an effect if *seq_id_thr* > 0!
        :type min_aln_length: :class:`int`    
        :returns: Tuple with two elements. 1) index of sequence in *ref_seqs* to
                  which *s* can be mapped 2) Pairwise sequence alignment with 
                  sequence from *ref_seqs* as first sequence. Both elements are
                  None if no mapping can be found or if thresholds are not 
                  fulfilled for any alignment.
        :raises: :class:`RuntimeError` if mapping is ambiguous, i.e. *s*
                 successfully maps to more than one sequence in *ref_seqs* 
        """
        scored_alns = list()
        for ref_idx, ref_seq in enumerate(ref_seqs):
            if ref_types[ref_idx] == s_type:
                if self.seqres_set and self.resnum_alignments:
                    aln = self.SEQRESAlign(ref_seq, s, s_ent)
                elif self.resnum_alignments:
                    aln = self.ResNumAlign(ref_seq, s, self.target, s_ent)
                else:
                    aln = self.NWAlign(ref_seq, s, s_type)
                seqid, n_tot, n_aligned = _GetAlnPropsTwo(aln)
                if seq_id_thr > 0:
                    if seqid >= seq_id_thr and n_aligned >= min_aln_length:
                        fraction_covered = float(n_aligned)/n_tot
                        score = seqid * fraction_covered
                        scored_alns.append((score, ref_idx, aln))
                else:
                    fraction_covered = float(n_aligned)/n_tot
                    score = seqid * fraction_covered
                    scored_alns.append((score, ref_idx, aln))
    
        if len(scored_alns) == 0:
            return (None, None) # no mapping possible...
    
        scored_alns = sorted(scored_alns, key=lambda x: x[0], reverse=True)
        return (scored_alns[0][1], scored_alns[0][2])

def _GetAlnPropsTwo(aln):
    """Returns basic properties of *aln* version two...

    :param aln: Alignment to compute properties
    :type aln: :class:`seq.AlignmentHandle`
    :returns: Tuple with 3 elements. 1) sequence identity in range [0, 100] 
              considering aligned columns 2) Number of non gap characters in
              first sequence 3) Number of aligned characters.
    """
    assert(aln.GetCount() == 2)
    n_tot = sum([1 for col in aln if col[0] != '-'])
    n_aligned = sum([1 for col in aln if (col[0] != '-' and col[1] != '-')])
    return (seq.alg.SequenceIdentity(aln), n_tot, n_aligned) 

def _GetAlnPropsOne(aln):
    
    """Returns basic properties of *aln* version one...

    :param aln: Alignment to compute properties
    :type aln: :class:`seq.AlignmentHandle`
    :returns: Tuple with 2 elements. 1) sequence identify in range [0, 100] 
              considering aligned columns 2) Number of aligned columns.
    """
    assert(aln.GetCount() == 2)
    seqid = seq.alg.SequenceIdentity(aln)
    n_aligned = sum([1 for col in aln if (col[0] != '-' and col[1] != '-')])
    return (seqid, n_aligned) 

def _GetRefMdlAlns(ref_chem_groups, ref_chem_group_msas, mdl_chem_groups,
                   mdl_chem_group_alns, pairs=None):
    """ Get all possible ref/mdl chain alignments given chem group mapping

    :param ref_chem_groups: :attr:`ChainMapper.chem_groups`
    :type ref_chem_groups: :class:`list` of :class:`list` of :class:`str`
    :param ref_chem_group_msas: :attr:`ChainMapper.chem_group_alignments`
    :type ref_chem_group_msas: :class:`ost.seq.AlignmentList`
    :param mdl_chem_groups: Groups of model chains that are mapped to
                            *ref_chem_groups*. Return value of
                            :func:`ChainMapper.GetChemMapping`.
    :type mdl_chem_groups: :class:`list` of :class:`list` of :class:`str`
    :param mdl_chem_group_alns: A pairwise sequence alignment for every chain
                                in *mdl_chem_groups* that aligns these sequences
                                to the respective reference sequence.
                                Return values of
                                :func:`ChainMapper.GetChemMapping`.
    :type mdl_chem_group_alns: :class:`list` of :class:`ost.seq.AlignmentList`
    :param pairs: Pro param - restrict return dict to specified pairs. A set of
                  tuples in form (<trg_ch>, <mdl_ch>)
    :type pairs: :class:`set`
    :returns: A dictionary holding all possible ref/mdl chain alignments. Keys
              in that dictionary are tuples of the form (ref_ch, mdl_ch) and
              values are the respective pairwise alignments with first sequence
              being from ref, the second from mdl.
    """
    # alignment of each model chain to chem_group reference sequence
    mdl_alns = dict()
    for alns in mdl_chem_group_alns:
        for aln in alns:
            mdl_chain_name = aln.GetSequence(1).GetName()
            mdl_alns[mdl_chain_name] = aln

    # generate all alignments between ref/mdl chain atomseqs that we will
    # ever observe
    ref_mdl_alns = dict()
    for ref_chains, mdl_chains, ref_aln in zip(ref_chem_groups, mdl_chem_groups,
                                               ref_chem_group_msas):
        for ref_ch in ref_chains:
            for mdl_ch in mdl_chains:
                if pairs is not None and (ref_ch, mdl_ch) not in pairs:
                    continue
                # obtain alignments of mdl and ref chains towards chem
                # group ref sequence and merge them
                aln_list = seq.AlignmentList()
                
                # do ref aln
                ############
                # reference sequence
                s1 = ref_aln.GetSequence(0)
                # ATOMSEQ of ref_ch
                s2 = ref_aln.GetSequence(1+ref_chains.index(ref_ch))
                aln_list.append(seq.CreateAlignment(s1, s2))

                # do mdl aln
                ############
                aln_list.append(mdl_alns[mdl_ch])

                # merge
                #######
                ref_seq = seq.CreateSequence(s1.GetName(),
                                             s1.GetGaplessString())
                merged_aln = seq.alg.MergePairwiseAlignments(aln_list,
                                                             ref_seq)
                # merged_aln:
                # seq1: ref seq of chem group
                # seq2: seq of ref chain
                # seq3: seq of mdl chain
                # => we need the alignment between seq2 and seq3
                s2 = merged_aln.GetSequence(1)
                s3 = merged_aln.GetSequence(2)
                # cut leading and trailing gap columns
                a = 0 # number of leading gap columns
                for idx in range(len(s2)):
                    if s2[idx] != '-' or s3[idx] != '-':
                        break
                    a += 1
                b = 0 # number of trailing gap columns
                for idx in reversed(range(len(s2))):
                    if s2[idx] != '-' or s3[idx] != '-':
                        break
                    b += 1
                s2 = seq.CreateSequence(s2.GetName(), s2[a: len(s2)-b])
                s3 = seq.CreateSequence(s3.GetName(), s3[a: len(s3)-b])
                ref_mdl_alns[(ref_ch, mdl_ch)] = seq.CreateAlignment(s2, s3)

    return ref_mdl_alns

def _CheckOneToOneMapping(ref_chains, mdl_chains):
    """ Checks whether we already have a perfect one to one mapping

    That means each list in *ref_chains* has either exactly one element
    and the respective list in *mdl_chains* has also one element or
    it has several elements and the respective list in *mdl_chains* is
    empty (ref chain(s) has no mapped mdl chain). Returns None if no such
    mapping can be found.

    :param ref_chains: corresponds to :attr:`ChainMapper.chem_groups`
    :type ref_chains: :class:`list` of :class:`list` of :class:`str`
    :param mdl_chains: mdl chains mapped to chem groups in *ref_chains*, i.e.
                       the return value of :func:`ChainMapper.GetChemMapping`
    :type mdl_chains: class:`list` of :class:`list` of :class:`str`
    :returns: A :class:`list` of :class:`list` if a one to one mapping is found,
              None otherwise
    """
    only_one_to_one = True
    one_to_one = list()
    for ref, mdl in zip(ref_chains, mdl_chains):
        if len(ref) == 1 and len(mdl) == 1:
            one_to_one.append(mdl)
        elif len(ref) >= 1 and len(mdl) == 0:
            one_to_one.append(len(ref)*[None])
        else:
            only_one_to_one = False
            break
    if only_one_to_one:
        return one_to_one
    else:
        return None

class _lDDTGreedySearcher(bb_lddt.BBlDDTScorer):
    def __init__(self, ref, mdl, ref_chem_groups, mdl_chem_groups,
                 ref_mdl_alns, inclusion_radius = 15.0,
                 thresholds = [0.5, 1.0, 2.0, 4.0],
                 steep_opt_rate = None):

        """ Greedy extension of already existing but incomplete chain mappings
        """
        super().__init__(ref, ref_chem_groups, mdl, ref_mdl_alns,
                         dist_thresh=inclusion_radius,
                         dist_diff_thresholds=thresholds)

        self.mdl_chem_groups = mdl_chem_groups
        self.steep_opt_rate = steep_opt_rate

        self.neighbors = {k: set() for k in self.trg.chain_names}
        for interface in self.trg.interacting_chains:
            self.neighbors[interface[0]].add(interface[1])
            self.neighbors[interface[1]].add(interface[0])

        assert(len(ref_chem_groups) == len(mdl_chem_groups))
        self.ref_chem_groups = ref_chem_groups
        self.mdl_chem_groups = mdl_chem_groups
        self.ref_ch_group_mapper = dict()
        self.mdl_ch_group_mapper = dict()
        for g_idx, (ref_g, mdl_g) in enumerate(zip(ref_chem_groups,
                                                   mdl_chem_groups)):
            for ch in ref_g:
                self.ref_ch_group_mapper[ch] = g_idx
            for ch in mdl_g:
                self.mdl_ch_group_mapper[ch] = g_idx

        # keep track of mdl chains that potentially give lDDT contributions,
        # i.e. they have locations within inclusion_radius + max(thresholds)
        self.mdl_neighbors = {k: set() for k in self.mdl.chain_names}
        for interface in self.mdl.potentially_contributing_chains:
            self.mdl_neighbors[interface[0]].add(interface[1])
            self.mdl_neighbors[interface[1]].add(interface[0])

    def ExtendMapping(self, mapping, max_ext = None):

        if len(mapping) == 0:
            raise RuntimError("Mapping must contain a starting point")

        # Ref chains onto which we can map. The algorithm starts with a mapping
        # on ref_ch. From there we can start to expand to connected neighbors.
        # All neighbors that we can reach from the already mapped chains are
        # stored in this set which will be updated during runtime
        map_targets = set()
        for ref_ch in mapping.keys():
            map_targets.update(self.neighbors[ref_ch])

        # remove the already mapped chains
        for ref_ch in mapping.keys():
            map_targets.discard(ref_ch)

        if len(map_targets) == 0:
            return mapping # nothing to extend

        # keep track of what model chains are not yet mapped for each chem group
        free_mdl_chains = list()
        for chem_group in self.mdl_chem_groups:
            tmp = [x for x in chem_group if x not in mapping.values()]
            free_mdl_chains.append(set(tmp))

        # keep track of what ref chains got a mapping
        newly_mapped_ref_chains = list()

        something_happened = True
        while something_happened:
            something_happened=False

            if self.steep_opt_rate is not None:
                n_chains = len(newly_mapped_ref_chains)
                if n_chains > 0 and n_chains % self.steep_opt_rate == 0:
                    mapping = self._SteepOpt(mapping, newly_mapped_ref_chains)

            if max_ext is not None and len(newly_mapped_ref_chains) >= max_ext:
                break

            max_n = 0
            max_mapping = None
            for ref_ch in map_targets:
                chem_group_idx = self.ref_ch_group_mapper[ref_ch]
                for mdl_ch in free_mdl_chains[chem_group_idx]:
                    # single chain score
                    n_single = self._NSCConserved(ref_ch, mdl_ch).sum()
                    # scores towards neighbors that are already mapped
                    n_inter = 0
                    for neighbor in self.neighbors[ref_ch]:
                        if neighbor in mapping and mapping[neighbor] in \
                        self.mdl_neighbors[mdl_ch]:
                            n_inter += self._NPairConserved((ref_ch, neighbor),
                                                            (mdl_ch, mapping[neighbor])).sum()
                    n = n_single + n_inter

                    if n_inter > 0 and n > max_n:
                        # Only accept a new solution if its actually connected
                        # i.e. n_inter > 0. Otherwise we could just map a big
                        # fat mdl chain sitting somewhere in Nirvana
                        max_n = n
                        max_mapping = (ref_ch, mdl_ch)
     
            if max_n > 0:
                something_happened = True
                # assign new found mapping
                mapping[max_mapping[0]] = max_mapping[1]

                # add all neighboring chains to map targets as they are now
                # reachable
                for neighbor in self.neighbors[max_mapping[0]]:
                    if neighbor not in mapping:
                        map_targets.add(neighbor)

                # remove the ref chain from map targets
                map_targets.remove(max_mapping[0])

                # remove the mdl chain from free_mdl_chains - its taken...
                chem_group_idx = self.ref_ch_group_mapper[max_mapping[0]]
                free_mdl_chains[chem_group_idx].remove(max_mapping[1])

                # keep track of what ref chains got a mapping
                newly_mapped_ref_chains.append(max_mapping[0])

        return mapping

    def _SteepOpt(self, mapping, chains_to_optimize=None):

        # just optimize ALL ref chains if nothing specified
        if chains_to_optimize is None:
            chains_to_optimize = mapping.keys()

        # make sure that we only have ref chains which are actually mapped
        ref_chains = [x for x in chains_to_optimize if mapping[x] is not None]

        # group ref chains to be optimized into chem groups
        tmp = dict()
        for ch in ref_chains:
            chem_group_idx = self.ref_ch_group_mapper[ch] 
            if chem_group_idx in tmp:
                tmp[chem_group_idx].append(ch)
            else:
                tmp[chem_group_idx] = [ch]
        chem_groups = list(tmp.values())

        # try all possible mapping swaps. Swaps that improve the score are
        # immediately accepted and we start all over again
        current_lddt = self.FromFlatMapping(mapping)
        something_happened = True
        while something_happened:
            something_happened = False
            for chem_group in chem_groups:
                if something_happened:
                    break
                for ch1, ch2 in itertools.combinations(chem_group, 2):
                    swapped_mapping = dict(mapping)
                    swapped_mapping[ch1] = mapping[ch2]
                    swapped_mapping[ch2] = mapping[ch1]
                    score = self.FromFlatMapping(swapped_mapping)
                    if score > current_lddt:
                        something_happened = True
                        mapping = swapped_mapping
                        current_lddt = score
                        break        
        return mapping


def _lDDTNaive(trg, mdl, inclusion_radius, thresholds, chem_groups,
               chem_mapping, ref_mdl_alns, n_max_naive):
    """ Naively iterates all possible chain mappings and returns the best
    """
    best_mapping = None
    best_lddt = -1.0

    # Setup scoring
    lddt_scorer = bb_lddt.BBlDDTScorer(trg, chem_groups, mdl, ref_mdl_alns,
                                       dist_thresh=inclusion_radius,
                                       dist_diff_thresholds=thresholds)
    for mapping in _ChainMappings(chem_groups, chem_mapping, n_max_naive):
        lDDT = lddt_scorer.Score(mapping, check=False)
        if lDDT > best_lddt:
            best_mapping = mapping
            best_lddt = lDDT

    return (best_mapping, best_lddt)


def _GetSeeds(ref_chem_groups, mdl_chem_groups, mapped_ref_chains = set(),
              mapped_mdl_chains = set()):
    seeds = list()
    for ref_chains, mdl_chains in zip(ref_chem_groups,
                                      mdl_chem_groups):
        for ref_ch in ref_chains:
            if ref_ch not in mapped_ref_chains:
                for mdl_ch in mdl_chains:
                    if mdl_ch not in mapped_mdl_chains:
                        seeds.append((ref_ch, mdl_ch))
    return seeds

def _lDDTGreedyFull(the_greed):
    """ Uses each reference chain as starting point for expansion
    """

    seeds = _GetSeeds(the_greed.ref_chem_groups, the_greed.mdl_chem_groups)
    best_overall_score = -1.0
    best_overall_mapping = dict()

    for seed in seeds:

        # do initial extension
        mapping = the_greed.ExtendMapping({seed[0]: seed[1]})

        # repeat the process until we have a full mapping
        something_happened = True
        while something_happened:
            something_happened = False
            remnant_seeds = _GetSeeds(the_greed.ref_chem_groups,
                                      the_greed.mdl_chem_groups,
                                      mapped_ref_chains = set(mapping.keys()),
                                      mapped_mdl_chains = set(mapping.values()))
            if len(remnant_seeds) > 0:
                # still more mapping to be done
                best_score = -1.0
                best_mapping = None
                for remnant_seed in remnant_seeds:
                    tmp_mapping = dict(mapping)
                    tmp_mapping[remnant_seed[0]] = remnant_seed[1]
                    tmp_mapping = the_greed.ExtendMapping(tmp_mapping)
                    score = the_greed.FromFlatMapping(tmp_mapping)
                    if score > best_score:
                        best_score = score
                        best_mapping = tmp_mapping
                if best_mapping is not None:
                    something_happened = True
                    mapping = best_mapping

        score = the_greed.FromFlatMapping(mapping)
        if score > best_overall_score:
            best_overall_score = score
            best_overall_mapping = mapping

    mapping = best_overall_mapping

    # translate mapping format and return
    final_mapping = list()
    for ref_chains in the_greed.ref_chem_groups:
        mapped_mdl_chains = list()
        for ref_ch in ref_chains:
            if ref_ch in mapping:
                mapped_mdl_chains.append(mapping[ref_ch])
            else:
                mapped_mdl_chains.append(None)
        final_mapping.append(mapped_mdl_chains)

    return final_mapping


def _lDDTGreedyBlock(the_greed, seed_size, blocks_per_chem_group):
    """ try multiple seeds, i.e. try all ref/mdl chain combinations within the
    respective chem groups and compute single chain lDDTs. The
    *blocks_per_chem_group* best scoring ones are extend by *seed_size* chains
    and the best scoring one is exhaustively extended.
    """

    if seed_size is None or seed_size < 1:
        raise RuntimeError(f"seed_size must be an int >= 1 (got {seed_size})")

    if blocks_per_chem_group is None or blocks_per_chem_group < 1:
        raise RuntimeError(f"blocks_per_chem_group must be an int >= 1 "
                           f"(got {blocks_per_chem_group})")

    max_ext = seed_size - 1 #  -1 => start seed already has size 1

    ref_chem_groups = copy.deepcopy(the_greed.ref_chem_groups)
    mdl_chem_groups = copy.deepcopy(the_greed.mdl_chem_groups)

    mapping = dict()
    something_happened = True
    while something_happened:
        something_happened = False
        starting_blocks = list()
        for ref_chains, mdl_chains in zip(ref_chem_groups, mdl_chem_groups):
            if len(mdl_chains) == 0:
                continue # nothing to map
            ref_chains_copy = list(ref_chains)
            for i in range(blocks_per_chem_group):
                if len(ref_chains_copy) == 0:
                    break
                seeds = list()
                for ref_ch in ref_chains_copy:
                    seeds += [(ref_ch, mdl_ch) for mdl_ch in mdl_chains]
                # extend starting seeds to *seed_size* and retain best scoring
                # block for further extension
                best_score = -1.0
                best_mapping = None
                best_seed = None
                for s in seeds:
                    seed = dict(mapping)
                    seed.update({s[0]: s[1]})  
                    seed = the_greed.ExtendMapping(seed, max_ext = max_ext)
                    seed_lddt = the_greed.FromFlatMapping(seed)
                    if seed_lddt > best_score:
                        best_score = seed_lddt
                        best_mapping = seed
                        best_seed = s
                if best_mapping != None:
                    starting_blocks.append(best_mapping)
                    if best_seed[0] in ref_chains_copy:
                        # remove that ref chain to enforce diversity
                        ref_chains_copy.remove(best_seed[0])

        # fully expand initial starting blocks
        best_lddt = 0.0
        best_mapping = None
        for seed in starting_blocks:
            seed = the_greed.ExtendMapping(seed)
            seed_lddt = the_greed.FromFlatMapping(seed)
            if seed_lddt > best_lddt:
                best_lddt = seed_lddt
                best_mapping = seed

        if best_lddt == 0.0:
            break # no proper mapping found anymore

        something_happened = True
        mapping.update(best_mapping)
        for ref_ch, mdl_ch in best_mapping.items():
            for group_idx in range(len(ref_chem_groups)):
                if ref_ch in ref_chem_groups[group_idx]:
                    ref_chem_groups[group_idx].remove(ref_ch)
                if mdl_ch in mdl_chem_groups[group_idx]:
                    mdl_chem_groups[group_idx].remove(mdl_ch)

    # translate mapping format and return
    final_mapping = list()
    for ref_chains in the_greed.ref_chem_groups:
        mapped_mdl_chains = list()
        for ref_ch in ref_chains:
            if ref_ch in mapping:
                mapped_mdl_chains.append(mapping[ref_ch])
            else:
                mapped_mdl_chains.append(None)
        final_mapping.append(mapped_mdl_chains)

    return final_mapping


class _QSScoreGreedySearcher(qsscore.QSScorer):
    def __init__(self, ref, mdl, ref_chem_groups, mdl_chem_groups,
                 ref_mdl_alns, contact_d = 12.0,
                 steep_opt_rate = None, greedy_prune_contact_map=False):
        """ Greedy extension of already existing but incomplete chain mappings
        """
        super().__init__(ref, ref_chem_groups, mdl, ref_mdl_alns,
                         contact_d = contact_d)
        self.ref = ref
        self.mdl = mdl
        self.ref_mdl_alns = ref_mdl_alns
        self.steep_opt_rate = steep_opt_rate

        if greedy_prune_contact_map:
            self.neighbors = {k: set() for k in self.qsent1.chain_names}
            for p in self.qsent1.interacting_chains:
                if np.count_nonzero(self.qsent1.PairDist(p[0], p[1])<=8) >= 3:
                    self.neighbors[p[0]].add(p[1])
                    self.neighbors[p[1]].add(p[0])

            self.mdl_neighbors = {k: set() for k in self.qsent2.chain_names}
            for p in self.qsent2.interacting_chains:
                if np.count_nonzero(self.qsent2.PairDist(p[0], p[1])<=8) >= 3:
                    self.mdl_neighbors[p[0]].add(p[1])
                    self.mdl_neighbors[p[1]].add(p[0])


        else:
            self.neighbors = {k: set() for k in self.qsent1.chain_names}
            for p in self.qsent1.interacting_chains:
                self.neighbors[p[0]].add(p[1])
                self.neighbors[p[1]].add(p[0])

            self.mdl_neighbors = {k: set() for k in self.qsent2.chain_names}
            for p in self.qsent2.interacting_chains:
                self.mdl_neighbors[p[0]].add(p[1])
                self.mdl_neighbors[p[1]].add(p[0])

        assert(len(ref_chem_groups) == len(mdl_chem_groups))
        self.ref_chem_groups = ref_chem_groups
        self.mdl_chem_groups = mdl_chem_groups
        self.ref_ch_group_mapper = dict()
        self.mdl_ch_group_mapper = dict()
        for g_idx, (ref_g, mdl_g) in enumerate(zip(ref_chem_groups,
                                                   mdl_chem_groups)):
            for ch in ref_g:
                self.ref_ch_group_mapper[ch] = g_idx
            for ch in mdl_g:
                self.mdl_ch_group_mapper[ch] = g_idx

        # cache for lDDT based single chain conserved contacts
        # used to identify starting points for further extension by QS score
        # key: tuple (ref_ch, mdl_ch) value: number of conserved contacts
        self.single_chain_scorer = dict()
        self.single_chain_cache = dict()
        for ch in self.ref.chains:
            single_chain_ref = _CSel(self.ref, [ch.GetName()])
            self.single_chain_scorer[ch.GetName()] = \
            lddt.lDDTScorer(single_chain_ref, bb_only = True)

    def SCCounts(self, ref_ch, mdl_ch):
        if not (ref_ch, mdl_ch) in self.single_chain_cache:
            alns = dict()
            alns[mdl_ch] = self.ref_mdl_alns[(ref_ch, mdl_ch)]
            mdl_sel = _CSel(self.mdl, [mdl_ch])
            s = self.single_chain_scorer[ref_ch]
            _,_,_,conserved,_,_,_ = s.lDDT(mdl_sel,
                                           residue_mapping=alns,
                                           return_dist_test=True,
                                           no_interchain=True,
                                           chain_mapping={mdl_ch: ref_ch},
                                           check_resnames=False)
            self.single_chain_cache[(ref_ch, mdl_ch)] = conserved
        return self.single_chain_cache[(ref_ch, mdl_ch)]

    def ExtendMapping(self, mapping, max_ext = None):

        if len(mapping) == 0:
            raise RuntimError("Mapping must contain a starting point")

        # Ref chains onto which we can map. The algorithm starts with a mapping
        # on ref_ch. From there we can start to expand to connected neighbors.
        # All neighbors that we can reach from the already mapped chains are
        # stored in this set which will be updated during runtime
        map_targets = set()
        for ref_ch in mapping.keys():
            map_targets.update(self.neighbors[ref_ch])

        # remove the already mapped chains
        for ref_ch in mapping.keys():
            map_targets.discard(ref_ch)

        if len(map_targets) == 0:
            return mapping # nothing to extend

        # keep track of what model chains are not yet mapped for each chem group
        free_mdl_chains = list()
        for chem_group in self.mdl_chem_groups:
            tmp = [x for x in chem_group if x not in mapping.values()]
            free_mdl_chains.append(set(tmp))

        # keep track of what ref chains got a mapping
        newly_mapped_ref_chains = list()

        something_happened = True
        while something_happened:
            something_happened=False

            if self.steep_opt_rate is not None:
                n_chains = len(newly_mapped_ref_chains)
                if n_chains > 0 and n_chains % self.steep_opt_rate == 0:
                    mapping = self._SteepOpt(mapping, newly_mapped_ref_chains)

            if max_ext is not None and len(newly_mapped_ref_chains) >= max_ext:
                break

            score_result = self.FromFlatMapping(mapping)
            old_score = score_result.QS_global
            nominator = score_result.weighted_scores
            denominator = score_result.weight_sum + score_result.weight_extra_all

            max_diff = 0.0
            max_mapping = None
            for ref_ch in map_targets:
                chem_group_idx = self.ref_ch_group_mapper[ref_ch]
                for mdl_ch in free_mdl_chains[chem_group_idx]:
                    # we're not computing full QS-score here, we directly hack
                    # into the QS-score formula to compute a diff
                    nominator_diff = 0.0
                    denominator_diff = 0.0
                    for neighbor in self.neighbors[ref_ch]:
                        if neighbor in mapping and mapping[neighbor] in \
                        self.mdl_neighbors[mdl_ch]:
                            # it's a newly added interface if (ref_ch, mdl_ch)
                            # are added to mapping
                            int1 = (ref_ch, neighbor)
                            int2 = (mdl_ch, mapping[neighbor])
                            a, b, c, d = self._MappedInterfaceScores(int1, int2)
                            nominator_diff += a # weighted_scores
                            denominator_diff += b # weight_sum
                            denominator_diff += d # weight_extra_all
                            # the respective interface penalties are subtracted
                            # from denominator
                            denominator_diff -= self._InterfacePenalty1(int1)
                            denominator_diff -= self._InterfacePenalty2(int2)

                    if nominator_diff > 0:
                        # Only accept a new solution if its actually connected
                        # i.e. nominator_diff > 0.
                        new_nominator = nominator + nominator_diff
                        new_denominator = denominator + denominator_diff
                        new_score = 0.0
                        if new_denominator != 0.0:
                            new_score = new_nominator/new_denominator
                        diff = new_score - old_score
                        if diff > max_diff:
                            max_diff = diff
                            max_mapping = (ref_ch, mdl_ch)
     
            if max_mapping is not None:
                something_happened = True
                # assign new found mapping
                mapping[max_mapping[0]] = max_mapping[1]

                # add all neighboring chains to map targets as they are now
                # reachable
                for neighbor in self.neighbors[max_mapping[0]]:
                    if neighbor not in mapping:
                        map_targets.add(neighbor)

                # remove the ref chain from map targets
                map_targets.remove(max_mapping[0])

                # remove the mdl chain from free_mdl_chains - its taken...
                chem_group_idx = self.ref_ch_group_mapper[max_mapping[0]]
                free_mdl_chains[chem_group_idx].remove(max_mapping[1])

                # keep track of what ref chains got a mapping
                newly_mapped_ref_chains.append(max_mapping[0])

        return mapping

    def _SteepOpt(self, mapping, chains_to_optimize=None):

        # just optimize ALL ref chains if nothing specified
        if chains_to_optimize is None:
            chains_to_optimize = mapping.keys()

        # make sure that we only have ref chains which are actually mapped
        ref_chains = [x for x in chains_to_optimize if mapping[x] is not None]

        # group ref chains to be optimized into chem groups
        tmp = dict()
        for ch in ref_chains:
            chem_group_idx = self.ref_ch_group_mapper[ch] 
            if chem_group_idx in tmp:
                tmp[chem_group_idx].append(ch)
            else:
                tmp[chem_group_idx] = [ch]
        chem_groups = list(tmp.values())

        # try all possible mapping swaps. Swaps that improve the score are
        # immediately accepted and we start all over again
        score_result = self.FromFlatMapping(mapping)
        current_score = score_result.QS_global
        something_happened = True
        while something_happened:
            something_happened = False
            for chem_group in chem_groups:
                if something_happened:
                    break
                for ch1, ch2 in itertools.combinations(chem_group, 2):
                    swapped_mapping = dict(mapping)
                    swapped_mapping[ch1] = mapping[ch2]
                    swapped_mapping[ch2] = mapping[ch1]
                    score_result = self.FromFlatMapping(swapped_mapping)
                    if score_result.QS_global > current_score:
                        something_happened = True
                        mapping = swapped_mapping
                        current_score = score_result.QS_global
                        break        
        return mapping


def _QSScoreNaive(trg, mdl, chem_groups, chem_mapping, ref_mdl_alns, contact_d,
                  n_max_naive):
    best_mapping = None
    best_score = -1.0
    # qs_scorer implements caching, score calculation is thus as fast as it gets
    # you'll just hit a wall when the number of possible mappings becomes large
    qs_scorer = qsscore.QSScorer(trg, chem_groups, mdl, ref_mdl_alns)
    for mapping in _ChainMappings(chem_groups, chem_mapping, n_max_naive):
        score_result = qs_scorer.Score(mapping, check=False)
        if score_result.QS_global > best_score:
            best_mapping = mapping
            best_score = score_result.QS_global
    return (best_mapping, best_score)

def _QSScoreGreedyFull(the_greed):
    """ Uses each reference chain as starting point for expansion
    """

    seeds = _GetSeeds(the_greed.ref_chem_groups, the_greed.mdl_chem_groups)
    best_overall_score = -1.0
    best_overall_mapping = dict()

    for seed in seeds:

        # do initial extension
        mapping = the_greed.ExtendMapping({seed[0]: seed[1]})

        # repeat the process until we have a full mapping
        something_happened = True
        while something_happened:
            something_happened = False
            remnant_seeds = _GetSeeds(the_greed.ref_chem_groups,
                                      the_greed.mdl_chem_groups,
                                      mapped_ref_chains = set(mapping.keys()),
                                      mapped_mdl_chains = set(mapping.values()))
            if len(remnant_seeds) > 0:
                # still more mapping to be done
                best_score = -1.0
                best_mapping = None
                for remnant_seed in remnant_seeds:
                    tmp_mapping = dict(mapping)
                    tmp_mapping[remnant_seed[0]] = remnant_seed[1]
                    tmp_mapping = the_greed.ExtendMapping(tmp_mapping)
                    score_result = the_greed.FromFlatMapping(tmp_mapping)
                    if score_result.QS_global > best_score:
                        best_score = score_result.QS_global
                        best_mapping = tmp_mapping
                if best_mapping is not None:
                    something_happened = True
                    mapping = best_mapping

        score_result = the_greed.FromFlatMapping(mapping)
        if score_result.QS_global > best_overall_score:
            best_overall_score = score_result.QS_global
            best_overall_mapping = mapping

    mapping = best_overall_mapping

    # translate mapping format and return
    final_mapping = list()
    for ref_chains in the_greed.ref_chem_groups:
        mapped_mdl_chains = list()
        for ref_ch in ref_chains:
            if ref_ch in mapping:
                mapped_mdl_chains.append(mapping[ref_ch])
            else:
                mapped_mdl_chains.append(None)
        final_mapping.append(mapped_mdl_chains)

    return final_mapping


def _QSScoreGreedyBlock(the_greed, seed_size, blocks_per_chem_group):
    """ try multiple seeds, i.e. try all ref/mdl chain combinations within the
    respective chem groups and compute single chain lDDTs. The
    *blocks_per_chem_group* best scoring ones are extend by *seed_size* chains
    and the best scoring one with respect to QS score is exhaustively extended.
    """

    if seed_size is None or seed_size < 1:
        raise RuntimeError(f"seed_size must be an int >= 1 (got {seed_size})")

    if blocks_per_chem_group is None or blocks_per_chem_group < 1:
        raise RuntimeError(f"blocks_per_chem_group must be an int >= 1 "
                           f"(got {blocks_per_chem_group})")

    max_ext = seed_size - 1 #  -1 => start seed already has size 1

    ref_chem_groups = copy.deepcopy(the_greed.ref_chem_groups)
    mdl_chem_groups = copy.deepcopy(the_greed.mdl_chem_groups)

    mapping = dict()

    something_happened = True
    while something_happened:
        something_happened = False
        starting_blocks = list()
        for ref_chains, mdl_chains in zip(ref_chem_groups, mdl_chem_groups):
            if len(mdl_chains) == 0:
                continue # nothing to map
            ref_chains_copy = list(ref_chains)
            for i in range(blocks_per_chem_group):
                if len(ref_chains_copy) == 0:
                    break
                seeds = list()
                for ref_ch in ref_chains_copy:
                    seeds += [(ref_ch, mdl_ch) for mdl_ch in mdl_chains]
                # extend starting seeds to *seed_size* and retain best scoring block
                # for further extension
                best_score = -1.0
                best_mapping = None
                best_seed = None
                for s in seeds:
                    seed = dict(mapping)
                    seed.update({s[0]: s[1]})  
                    seed = the_greed.ExtendMapping(seed, max_ext = max_ext)
                    score_result = the_greed.FromFlatMapping(seed)
                    if score_result.QS_global > best_score:
                        best_score = score_result.QS_global
                        best_mapping = seed
                        best_seed = s
                if best_mapping != None:
                    starting_blocks.append(best_mapping)
                    if best_seed[0] in ref_chains_copy:
                        # remove selected ref chain to enforce diversity
                        ref_chains_copy.remove(best_seed[0])

        # fully expand initial starting blocks
        best_score = -1.0
        best_mapping = None
        for seed in starting_blocks:
            seed = the_greed.ExtendMapping(seed)
            score_result = the_greed.FromFlatMapping(seed)
            if score_result.QS_global > best_score:
                best_score = score_result.QS_global
                best_mapping = seed

        if best_mapping is not None and len(best_mapping) > len(mapping):
            # this even accepts extensions that lead to no increase in QS-score
            # at least they make sense from an lDDT perspective
            something_happened = True
            mapping.update(best_mapping)
            for ref_ch, mdl_ch in best_mapping.items():
                for group_idx in range(len(ref_chem_groups)):
                    if ref_ch in ref_chem_groups[group_idx]:
                        ref_chem_groups[group_idx].remove(ref_ch)
                    if mdl_ch in mdl_chem_groups[group_idx]:
                        mdl_chem_groups[group_idx].remove(mdl_ch)

    # translate mapping format and return
    final_mapping = list()
    for ref_chains in the_greed.ref_chem_groups:
        mapped_mdl_chains = list()
        for ref_ch in ref_chains:
            if ref_ch in mapping:
                mapped_mdl_chains.append(mapping[ref_ch])
            else:
                mapped_mdl_chains.append(None)
        final_mapping.append(mapped_mdl_chains)

    return final_mapping

def _SingleRigidRMSD(initial_transforms, initial_mappings, chem_groups,
                     chem_mapping, trg_group_pos, mdl_group_pos):
    """
    Takes initial transforms and sequentially adds chain pairs with lowest RMSD.
    The mapping from the transform that leads to lowest overall RMSD is
    returned.
    """
    best_mapping = dict()
    best_ssd = float("inf") # we're actually going for summed squared distances
                            # Since all positions have same lengths and we do a
                            # full mapping, lowest SSD has a guarantee of also
                            # being lowest RMSD
    for transform in initial_transforms:
        mapping = dict()
        mapped_mdl_chains = set()
        ssd = 0.0
        for trg_chains, mdl_chains, trg_pos, mdl_pos, in zip(chem_groups,
                                                             chem_mapping,
                                                             trg_group_pos,
                                                             mdl_group_pos):
            if len(trg_pos) == 0 or len(mdl_pos) == 0:
                continue # cannot compute valid rmsd
            ssds = list()
            t_mdl_pos = list()
            for m_pos in mdl_pos:
                t_m_pos = geom.Vec3List(m_pos)
                t_m_pos.ApplyTransform(transform)
                t_mdl_pos.append(t_m_pos)
            for t_pos, t in zip(trg_pos, trg_chains):
                for t_m_pos, m in zip(t_mdl_pos, mdl_chains):
                    ssd = t_pos.GetSummedSquaredDistances(t_m_pos)
                    ssds.append((ssd, (t,m)))
            ssds.sort()
            for item in ssds:
                p = item[1]
                if p[0] not in mapping and p[1] not in mapped_mdl_chains:
                    mapping[p[0]] = p[1]
                    mapped_mdl_chains.add(p[1])
                    ssd += item[0]

        if ssd < best_ssd:
            best_ssd = ssd
            best_mapping = mapping

    return best_mapping


def _SingleRigidCentroid(initial_transforms, initial_mappings, chem_groups,
                         chem_mapping, trg_group_pos, mdl_group_pos):
    """
    Takes initial transforms and sequentially adds chain pairs with lowest
    centroid distance.
    The mapping from the transform that leads to lowest overall RMSD of
    the centroids is returned.
    """
    best_mapping = dict()
    best_rmsd = float("inf")

    trg_group_centroids = list()
    mdl_group_centroids = list()

    for trg_pos, mdl_pos, in zip(trg_group_pos, mdl_group_pos):
        trg_group_centroids.append(geom.Vec3List([p.center for p in trg_pos]))
        mdl_group_centroids.append(geom.Vec3List([p.center for p in mdl_pos]))

    for transform in initial_transforms:
        mapping = dict()
        mapped_mdl_chains = set()
        mapped_trg_centroids = list()
        mapped_mdl_centroids = list()
        for trg_chains, mdl_chains, trg_centroids, mdl_centroids, in zip(chem_groups,
                                                                         chem_mapping,
                                                                         trg_group_centroids,
                                                                         mdl_group_centroids):
            if len(trg_centroids) == 0 or len(mdl_centroids) == 0:
                continue # cannot compute valid rmsd
            distances = list()
            t_mdl_centroids = geom.Vec3List(mdl_centroids)
            t_mdl_centroids.ApplyTransform(transform)

            for trg_idx in range(len(trg_chains)):
                for mdl_idx in range(len(mdl_chains)):
                    distances.append((geom.Length2(trg_centroids[trg_idx]-t_mdl_centroids[mdl_idx]),
                                     (trg_chains[trg_idx], mdl_chains[mdl_idx]),
                                     (trg_centroids[trg_idx], t_mdl_centroids[mdl_idx])))

            distances.sort()
            for item in distances:
                p = item[1]
                if p[0] not in mapping and p[1] not in mapped_mdl_chains:
                    mapping[p[0]] = p[1]
                    mapped_mdl_chains.add(p[1])
                    mapped_trg_centroids.append(item[2][0])
                    mapped_mdl_centroids.append(item[2][1])


        if len(mapping) == 0:
            raise RuntimeError("Empty mapping in _SingleRigidCentroid")
        elif len(mapping) == 1:
            # by definition zero
            rmsd = 0.0
        elif len(mapping) == 2:
            # no superposition possible with two positions
            # derive rmsd from the distance difference between
            # the centroid pairs in reference and model
            ref_d = geom.Distance(mapped_trg_centroids[0],
                                  mapped_trg_centroids[1])
            mdl_d = geom.Distance(mapped_mdl_centroids[0],
                                  mapped_mdl_centroids[1])
            # compute RMSD when placing pair of coordinates with smaller
            # distance in the middle of pair of cooridnates with larger
            # distance
            dd = abs(ref_d-mdl_d) # distance difference
            # rmsd = sqrt(1/2 * ((dd/2)**2 + (dd/2)**2))
            # => rmsd = dd/2
            rmsd = dd/2
        else:
            # go for classic Kabsch superposition
            mapped_trg_centroids = geom.Vec3List(mapped_trg_centroids)
            mapped_mdl_centroids = geom.Vec3List(mapped_mdl_centroids)
            rmsd = _GetSuperposition(mapped_trg_centroids,
                                     mapped_mdl_centroids, False).rmsd

        if rmsd < best_rmsd:
            best_rmsd = rmsd
            best_mapping = mapping

    return best_mapping


def _IterativeRigidRMSD(initial_transforms, initial_mappings, chem_groups,
                        chem_mapping, trg_group_pos, mdl_group_pos):
    """ Takes initial transforms and sequentially adds chain pairs with
    lowest RMSD. With each added chain pair, the transform gets updated.
    Thus the naming iterative. The mapping from the initial transform that
    leads to best overall RMSD score is returned.
    """

    # to directly retrieve positions using chain names
    trg_pos_dict = dict()
    for trg_pos, trg_chains in zip(trg_group_pos, chem_groups):
        for t_pos, t in zip(trg_pos, trg_chains):
            trg_pos_dict[t] = t_pos
    mdl_pos_dict = dict()
    for mdl_pos, mdl_chains in zip(mdl_group_pos, chem_mapping):
        for m_pos, m in zip(mdl_pos, mdl_chains):
            mdl_pos_dict[m] = m_pos
        
    best_mapping = dict()
    best_rmsd = float("inf")
    for initial_transform, initial_mapping in zip(initial_transforms,
                                                  initial_mappings):
        mapping = {initial_mapping[0]: initial_mapping[1]}
        transform = geom.Mat4(initial_transform)
        mapped_trg_pos = geom.Vec3List(trg_pos_dict[initial_mapping[0]])
        mapped_mdl_pos = geom.Vec3List(mdl_pos_dict[initial_mapping[1]])

        # the following variables contain the chains which are
        # available for mapping
        trg_chain_groups = [set(group) for group in chem_groups]
        mdl_chain_groups = [set(group) for group in chem_mapping]

        # search and kick out inital mapping
        for group in trg_chain_groups:
            if initial_mapping[0] in group:
                group.remove(initial_mapping[0])
                break
        for group in mdl_chain_groups:
            if initial_mapping[1] in group:
                group.remove(initial_mapping[1])
                break

        something_happened = True
        while something_happened:
            # search for best mapping given current transform
            something_happened=False
            best_sc_mapping = None
            best_sc_group_idx = None
            best_sc_rmsd = float("inf")
            group_idx = 0
            for trg_chains, mdl_chains in zip(trg_chain_groups, mdl_chain_groups):
                for t in trg_chains:
                    t_pos = trg_pos_dict[t]
                    for m in mdl_chains:
                        m_pos = mdl_pos_dict[m]
                        t_m_pos = geom.Vec3List(m_pos)
                        t_m_pos.ApplyTransform(transform)
                        rmsd = t_pos.GetRMSD(t_m_pos)
                        if rmsd < best_sc_rmsd:
                            best_sc_rmsd = rmsd
                            best_sc_mapping = (t,m)
                            best_sc_group_idx = group_idx
                group_idx += 1

            if best_sc_mapping is not None:
                something_happened = True
                mapping[best_sc_mapping[0]] = best_sc_mapping[1]
                mapped_trg_pos.extend(trg_pos_dict[best_sc_mapping[0]])
                mapped_mdl_pos.extend(mdl_pos_dict[best_sc_mapping[1]])
                trg_chain_groups[best_sc_group_idx].remove(best_sc_mapping[0])
                mdl_chain_groups[best_sc_group_idx].remove(best_sc_mapping[1])

                transform = _GetSuperposition(mapped_mdl_pos, mapped_trg_pos,
                                              False).transformation

        # compute overall RMSD for current transform
        mapped_mdl_pos.ApplyTransform(transform)
        rmsd = mapped_trg_pos.GetRMSD(mapped_mdl_pos)

        if rmsd < best_rmsd:
            best_rmsd = rmsd
            best_mapping = mapping

    return best_mapping

def _NaiveRMSD(chem_groups, chem_mapping, trg_group_pos, mdl_group_pos,
               n_max_naive):

    # to directly retrieve positions using chain names
    trg_pos_dict = dict()
    for trg_pos, trg_chains in zip(trg_group_pos, chem_groups):
        for t_pos, t in zip(trg_pos, trg_chains):
            trg_pos_dict[t] = t_pos
    mdl_pos_dict = dict()
    for mdl_pos, mdl_chains in zip(mdl_group_pos, chem_mapping):
        for m_pos, m in zip(mdl_pos, mdl_chains):
            mdl_pos_dict[m] = m_pos
        
    best_mapping = [[None]*len(x) for x in chem_groups]
    best_rmsd = float("inf")

    for mapping in _ChainMappings(chem_groups, chem_mapping, n_max_naive):
        trg_pos = geom.Vec3List()
        mdl_pos = geom.Vec3List()
        for trg_group, mdl_group in zip(chem_groups, mapping):
            for trg_ch, mdl_ch in zip(trg_group, mdl_group):
                if trg_ch is not None and mdl_ch is not None:
                    trg_pos.extend(trg_pos_dict[trg_ch])
                    mdl_pos.extend(mdl_pos_dict[mdl_ch])
        if len(mdl_pos) >= 3:
            superpose_res = mol.alg.SuperposeSVD(mdl_pos, trg_pos)
            if superpose_res.rmsd < best_rmsd:
                best_rmsd = superpose_res.rmsd
                best_mapping = mapping

    # this is stupid...
    tmp = dict()
    for chem_group, mapping in zip(chem_groups, best_mapping):
        for trg_ch, mdl_ch in zip(chem_group, mapping):
            tmp[trg_ch] = mdl_ch

    return tmp


def _GetRefPos(trg, mdl, trg_msas, mdl_alns, max_pos = None):
    """ Extracts reference positions which are present in trg and mdl
    """

    # mdl_alns are pairwise, let's construct MSAs
    mdl_msas = list()
    for aln_list in mdl_alns:
        if len(aln_list) > 0:
            tmp = aln_list[0].GetSequence(0)
            ref_seq = seq.CreateSequence(tmp.GetName(), tmp.GetGaplessString())
            mdl_msas.append(seq.alg.MergePairwiseAlignments(aln_list, ref_seq))
        else:
            mdl_msas.append(seq.CreateAlignment())

    # fetch positions of all backbone atoms
    bb_trg = _GetBBPos(trg)
    bb_mdl = _GetBBPos(mdl)

    # there are the actual return values
    trg_pos = list()
    mdl_pos = list()

    for trg_msa, mdl_msa in zip(trg_msas, mdl_msas):

        if mdl_msa.GetCount() > 0:
            # make sure they have the same ref sequence (should be a given...)
            assert(trg_msa.GetSequence(0).GetGaplessString() == \
                   mdl_msa.GetSequence(0).GetGaplessString())
        else:
            # if mdl_msa is empty, i.e. no model chain maps to the chem group
            # represented by trg_msa, we just continue. The result will be
            # empty position lists added to trg_pos and mdl_pos.
            pass 

        # check which columns in MSAs are fully covered (indices relative to
        # first sequence)
        trg_indices = _GetFullyCoveredIndices(trg_msa)
        mdl_indices = _GetFullyCoveredIndices(mdl_msa)

        # get indices where both, mdl and trg, are fully covered
        indices = sorted(list(trg_indices.intersection(mdl_indices)))

        # subsample if necessary
        if max_pos is not None and len(indices) > max_pos:
            step = int(len(indices)/max_pos)
            indices = [indices[i] for i in range(0, len(indices), step)]

        # translate to column indices in the respective MSAs
        trg_indices = _RefIndicesToColumnIndices(trg_msa, indices)
        mdl_indices = _RefIndicesToColumnIndices(mdl_msa, indices)

        # extract positions
        trg_pos.append(list())
        mdl_pos.append(list())
        # first seq in trg_msa is ref sequence and does not refer to any
        # ATOMSEQ
        for s_idx in range(1, trg_msa.GetCount()):
            trg_pos[-1].append(_ExtractMSAPos(trg_msa, s_idx, trg_indices,
                                              bb_trg))
        # first seq in mdl_msa is ref sequence in trg and does not belong to mdl
        for s_idx in range(1, mdl_msa.GetCount()):
            mdl_pos[-1].append(_ExtractMSAPos(mdl_msa, s_idx, mdl_indices,
                                              bb_mdl))

    return (trg_pos, mdl_pos)

def _GetBBPos(ent):
    """ Helper for _GetRefPos

    Returns a dict with key: chain name and value: a geom.Vec3List of backbone
    atom positions. Assumes that either CA or C3' is always there.
    """
    bb = dict()
    for ch in ent.chains:
        l = geom.Vec3List()
        for r in ch.residues:
            a = r.FindAtom("CA")
            if not a.IsValid():
                a = r.FindAtom("C3'")
            l.append(a.GetPos())
        bb[ch.name] = l
    return bb

def _GetFullyCoveredIndices(msa):
    """ Helper for _GetRefPos

    Returns a set containing the indices relative to first sequence in msa which
    are fully covered in all other sequences

    --AA-A-A
    -BBBB-BB
    CCCC-C-C

    => (0,1,3)
    """
    indices = set()
    ref_idx = 0
    for col in msa:
        if sum([1 for olc in col if olc != '-']) == col.GetRowCount():
            indices.add(ref_idx)
        if col[0] != '-':
            ref_idx += 1
    return indices

def _RefIndicesToColumnIndices(msa, indices):
    """ Helper for _GetRefPos

    Returns a list of mapped indices. indices refer to non-gap one letter
    codes in the first msa sequence. The returnes mapped indices are translated
    to the according msa column indices
    """
    ref_idx = 0
    mapping = dict()
    for col_idx, col in enumerate(msa):
        if col[0] != '-':
            mapping[ref_idx] = col_idx
            ref_idx += 1
    return [mapping[i] for i in indices]

def _ExtractMSAPos(msa, s_idx, indices, bb):
    """ Helper for _GetRefPos

    Returns a geom.Vec3List containing positions refering to given msa sequence.
    => Chain with corresponding name is mapped onto sequence and the position of
    the first atom of each residue specified in indices is extracted.
    Indices refers to column indices in msa!
    """
    s = msa.GetSequence(s_idx)
    ch_bb = bb[s.GetName()]

    # sanity check
    assert(len(s.GetGaplessString()) == len(ch_bb))

    residue_idx = [s.GetResidueIndex(i) for i in indices]
    return geom.Vec3List([ch_bb[i] for i in residue_idx])


def _NChemGroupMappings(ref_chains, mdl_chains):
    """ Number of mappings within one chem group

    :param ref_chains: Reference chains
    :type ref_chains: :class:`list` of :class:`str`
    :param mdl_chains: Model chains that are mapped onto *ref_chains*
    :type mdl_chains: :class:`list` of :class:`str`
    :returns: Number of possible mappings of *mdl_chains* onto *ref_chains*
    """
    n_ref = len(ref_chains)
    n_mdl = len(mdl_chains)
    if n_ref == n_mdl:
        return factorial(n_ref)
    elif n_ref > n_mdl:
        n_choose_k = binom(n_ref, n_mdl)
        return n_choose_k * factorial(n_mdl)
    else:
        n_choose_k = binom(n_mdl, n_ref)
        return n_choose_k * factorial(n_ref)

def _NMappings(ref_chains, mdl_chains):
    """ Number of mappings for a full chem mapping

    :param ref_chains: Chem groups of reference
    :type ref_chains: :class:`list` of :class:`list` of :class:`str`
    :param mdl_chains: Model chains that map onto those chem groups
    :type mdl_chains: :class:`list` of :class:`list` of :class:`str`
    :returns: Number of possible mappings of *mdl_chains* onto *ref_chains*
    """
    assert(len(ref_chains) == len(mdl_chains))
    n = 1
    for a,b in zip(ref_chains, mdl_chains):
        n *= _NChemGroupMappings(a,b)
    return n

def _NMappingsWithin(ref_chains, mdl_chains, max_mappings):
    """ Check whether total number of mappings is smaller than given maximum

    In principle the same as :func:`_NMappings` but it stops as soon as the
    maximum is hit.

    :param ref_chains: Chem groups of reference
    :type ref_chains: :class:`list` of :class:`list` of :class:`str`
    :param mdl_chains: Model chains that map onto those chem groups
    :type mdl_chains: :class:`list` of :class:`list` of :class:`str`
    :param max_mappings: Number of max allowed mappings
    :returns: Whether number of possible mappings of *mdl_chains* onto
              *ref_chains* is below or equal *max_mappings*.
    """
    assert(len(ref_chains) == len(mdl_chains))
    n = 1
    for a,b in zip(ref_chains, mdl_chains):
        n *= _NChemGroupMappings(a,b)
        if n > max_mappings:
            return False
    return True

def _RefSmallerGenerator(ref_chains, mdl_chains):
    """ Returns all possible ways to map mdl_chains onto ref_chains

    Specific for the case where len(ref_chains) < len(mdl_chains)
    """
    for c in itertools.combinations(mdl_chains, len(ref_chains)):
        for p in itertools.permutations(c):
            yield list(p)

def _RefLargerGenerator(ref_chains, mdl_chains):
    """ Returns all possible ways to map mdl_chains onto ref_chains

    Specific for the case where len(ref_chains) > len(mdl_chains)
    Ref chains without mapped mdl chain are assigned None
    """
    n_ref = len(ref_chains)
    n_mdl = len(mdl_chains)
    for c in itertools.combinations(range(n_ref), n_mdl):
        for p in itertools.permutations(mdl_chains):
            ret_list = [None] * n_ref
            for idx, ch in zip(c, p):
                ret_list[idx] = ch
            yield ret_list

def _RefEqualGenerator(ref_chains, mdl_chains):
    """ Returns all possible ways to map mdl_chains onto ref_chains

    Specific for the case where len(ref_chains) == len(mdl_chains)
    """
    for p in itertools.permutations(mdl_chains):
        yield list(p)

def _RefEmptyGenerator(ref_chains, mdl_chains):
    yield list()

def _ConcatIterators(iterators):
    for item in itertools.product(*iterators):
        yield list(item)

def _ChainMappings(ref_chains, mdl_chains, n_max=None):
    """Returns all possible ways to map *mdl_chains* onto fixed *ref_chains*

    :param ref_chains: List of list of chemically equivalent chains in reference
    :type ref_chains: :class:`list` of :class:`list`
    :param mdl_chains: Equally long list of list of chemically equivalent chains
                       in model that map on those ref chains.
    :type mdl_chains: :class:`list` of :class:`list`
    :param n_max: Aborts and raises :class:`RuntimeError` if max number of
                  mappings is above this threshold.
    :type n_max: :class:`int`
    :returns: Iterator over all possible mappings of *mdl_chains* onto fixed
              *ref_chains*. Potentially contains None as padding when number of
              model chains for a certain mapping is smaller than the according
              reference chains.
              Example: _ChainMappings([['A', 'B', 'C'], ['D', 'E']],
                                      [['x', 'y'], ['i', 'j']])
              gives an iterator over: [[['x', 'y', None], ['i', 'j']],
                                       [['x', 'y', None], ['j', 'i']],
                                       [['y', 'x', None], ['i', 'j']],
                                       [['y', 'x', None], ['j', 'i']],
                                       [['x', None, 'y'], ['i', 'j']],
                                       [['x', None, 'y'], ['j', 'i']],
                                       [['y', None, 'x'], ['i', 'j']],
                                       [['y', None, 'x'], ['j', 'i']],
                                       [[None, 'x', 'y'], ['i', 'j']],
                                       [[None, 'x', 'y'], ['j', 'i']],
                                       [[None, 'y', 'x'], ['i', 'j']],
                                       [[None, 'y', 'x'], ['j', 'i']]]
    """
    assert(len(ref_chains) == len(mdl_chains))

    if n_max is not None:
        if not _NMappingsWithin(ref_chains, mdl_chains, n_max):
            raise RuntimeError(f"Too many mappings. Max allowed: {n_max}")

    # one iterator per mapping representing all mdl combinations relative to
    # reference
    iterators = list()
    for ref, mdl in zip(ref_chains, mdl_chains):
        if len(ref) == 0:
            iterators.append(_RefEmptyGenerator(ref, mdl))
        elif len(ref) == len(mdl):
            iterators.append(_RefEqualGenerator(ref, mdl))
        elif len(ref) < len(mdl):
            iterators.append(_RefSmallerGenerator(ref, mdl))
        else:
            iterators.append(_RefLargerGenerator(ref, mdl))

    return _ConcatIterators(iterators)


def _GetSuperposition(pos_one, pos_two, iterative):
    """ Computes minimal RMSD superposition for pos_one onto pos_two

    :param pos_one: Positions that should be superposed onto *pos_two*
    :type pos_one: :class:`geom.Vec3List`
    :param pos_two: Reference positions
    :type pos_two: :class:`geom.Vec3List`
    :iterative: Whether iterative superposition should be used. Iterative
                potentially raises, uses standard superposition as fallback.
    :type iterative: :class:`bool`
    :returns: Transformation matrix to superpose *pos_one* onto *pos_two*
    :rtype: :class:`ost.mol.alg.SuperpositionResult`
    """
    res = None
    if iterative:
        try:
            res = mol.alg.IterativeSuperposeSVD(pos_one, pos_two)
        except:
            pass # triggers fallback below
    if res is None:
        res = mol.alg.SuperposeSVD(pos_one, pos_two)
    return res

# specify public interface
__all__ = ('ChainMapper', 'ReprResult', 'MappingResult')