Skip to content

API

MCDE2409_parallel

(3,1)-MCDE code.

@author: Stefano Paggi

MCDE

Attributes:

Name Type Description
zero_tol

float Threshold below which matrix elements in the effective Hamiltonian are treated as zero.

zero_tol_evals

float Threshold below which eigenvalues are treated as zero.

lanczos_tol

float Convergence tolerance for the Lanczos algorithm.

remove_single_values

bool If True, isolated diagonal elements are removed from the effective Hamiltonian.

lanczos

bool If True, use the Lanczos algorithm for diagonalization.

exactDiag

bool If True, perform exact diagonalization.

spinOptimized

bool If True, perform a spin-optimized calculation.

fullCalculation

bool If True, construct the full double-basis Hamiltonian.

secondBorn

bool If True, perform a Second-Born calculation.

mcde

bool If True, perform an MCDE calculation.

do_sparse

bool If True, force the use of sparse matrix methods.

do_auto_sparse

bool If True, automatically switch to the sparse implementation when the basis size exceeds do_auto_sparse_basis_threshold.

do_auto_sparse_basis_threshold

int Basis-size threshold above which the sparse implementation is automatically selected when do_auto_sparse is enabled.

data_type_sparse

numpy.dtype Numerical precision used for sparse matrix calculations.

reduce_evecs_to_1body

bool If True, discard the three-particle component of the eigenvectors after diagonalization, retaining only the one-particle contribution.

sparse_tol

float Threshold below which matrix elements are omitted during sparse effective Hamiltonian construction.

shift_virtual_energy

float Energy shift applied to virtual orbitals in the three-particle block of the effective Hamiltonian.

kernel_run

bool Indicates whether the kernel calculation has been executed.

Source code in src/MCDE2409_parallel.py
  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
class MCDE():
    """
        Attributes:
            zero_tol : float
                Threshold below which matrix elements in the effective Hamiltonian
                are treated as zero.

            zero_tol_evals : float
                Threshold below which eigenvalues are treated as zero.

            lanczos_tol : float
                Convergence tolerance for the Lanczos algorithm.

            remove_single_values : bool
                If ``True``, isolated diagonal elements are removed from the
                effective Hamiltonian.

            lanczos : bool
                If ``True``, use the Lanczos algorithm for diagonalization.

            exactDiag : bool
                If ``True``, perform exact diagonalization.

            spinOptimized : bool
                If ``True``, perform a spin-optimized calculation.

            fullCalculation : bool
                If ``True``, construct the full double-basis Hamiltonian.

            secondBorn : bool
                If ``True``, perform a Second-Born calculation.

            mcde : bool
                If ``True``, perform an MCDE calculation.

            do_sparse : bool
                If ``True``, force the use of sparse matrix methods.

            do_auto_sparse : bool
                If ``True``, automatically switch to the sparse implementation
                when the basis size exceeds ``do_auto_sparse_basis_threshold``.

            do_auto_sparse_basis_threshold : int
                Basis-size threshold above which the sparse implementation is
                automatically selected when ``do_auto_sparse`` is enabled.

            data_type_sparse : numpy.dtype
                Numerical precision used for sparse matrix calculations.

            reduce_evecs_to_1body : bool
                If ``True``, discard the three-particle component of the
                eigenvectors after diagonalization, retaining only the
                one-particle contribution.

            sparse_tol : float
                Threshold below which matrix elements are omitted during sparse
                effective Hamiltonian construction.

            shift_virtual_energy : float
                Energy shift applied to virtual orbitals in the three-particle
                block of the effective Hamiltonian.

            kernel_run : bool
                Indicates whether the kernel calculation has been executed.

    """
    # object saving the three and one body part of matrix
    class Nspace():

        def __init__(self,d1,d3):
            self.d1=d1
            self.d3=d3

        def v(self,n):
            if n>=len(self.d1):
                return self.d3[n-len(self.d1)]
            return self.d1[n]

        def stats(self):
            print("1-particle length: "+str(len(self.d1)))
            print("3-particle length: "+str(len(self.d3)))
            print("total length: "+str(len(self.d1)+len(self.d3)))

        def translateToAOLabels(self,n,ao_labels):
            vec=self.v(n)
            if isinstance(vec,np.ndarray):
                a=ao_labels[vec[0]]
                b=ao_labels[vec[1]]
                c=ao_labels[vec[2]]

                return "{"+a+", "+b+", "+c+"}"
            return ao_labels[vec]

        def returnNumLabels(self,n):
            vec=self.v(n)
            if isinstance(vec,np.ndarray):
                a=str(vec[0])
                b=str(vec[1])
                c=str(vec[2])

                return "{"+a+", "+b+", "+c+"}"
            return str(vec)




    class AuxillaryFunctions():

        #def __init__(self):

        @staticmethod
        def eig(matrix):
            return np.linalg.eigh(matrix)

        @staticmethod
        def remove_isolated_diagonals(A,spaceObj,remove_single_values):
            if not remove_single_values:
                return A,spaceObj
            A = np.array(A)
            keep = []
            for i in range(A.shape[0]):
                if A[i, i] == 0:
                    keep.append(i)
                else:
                    row = np.copy(A[i, :])
                    col = np.copy(A[:, i])
                    row[i] = 0
                    col[i] = 0
                    if np.any(row) or np.any(col):
                        keep.append(i)
            # Keep only rows and columns that are not isolated diagonals
            A_new = A[np.ix_(keep, keep)]


            d1=[]
            d3=[]
            #spaceObj.stats()
            for x in keep:
                if x>=len(spaceObj.d1):
                    d3.append(spaceObj.v(x))
                else:
                    d1.append(spaceObj.v(x))
            return A_new, MCDE.Nspace(np.array(d1), np.array(d3))

        @staticmethod
        def remove_isolated_diagonals_sparse(A,spaceObj,remove_single_values):
            if not remove_single_values:
                return A,spaceObj
            # Step 1: Count nonzeros per row and per column
            row_nnz = np.diff(A.indptr)           # CSR: number of nonzeros per row
            col_nnz = np.diff(A.tocsc().indptr)  # CSC: number of nonzeros per column

            # Step 2: Identify diagonal indices
            diag_idx = np.arange(A.shape[0])

            # Step 3: Mask for diagonals that are isolated
            isolated_diag_mask = (row_nnz == 1) & (col_nnz == 1)

            # Step 4: Zero out isolated diagonals
            A[diag_idx[isolated_diag_mask], diag_idx[isolated_diag_mask]] = 0

            # Step 5: Remove stored zeros
            A.eliminate_zeros()

            # print("bing")
            d1=[]
            d3=[]
            #spaceObj.stats()
            for x,v in enumerate(isolated_diag_mask):
                if v:
                    continue
                if x>=len(spaceObj.d1):
                    d3.append(spaceObj.v(x))
                else:
                    d1.append(spaceObj.v(x))

            # print(len(isolated_diag_mask))
            return A,MCDE.Nspace(np.array(d1), np.array(d3))

    def __init__(self,nBas,nO,moEn,erimo,verbose=0):


        self.starttime=time.perf_counter()
        self.intermediatetime=self.starttime

        self.verbose=verbose

        self.verbose1("_________________________")
        self.verbose1(" _      ____  ____  _____")
        self.verbose1("/ \\__/|/   _\\/  _ \\/  __/")
        self.verbose1("| |\\/|||  /  | | \\||  \\  ")
        self.verbose1("| |  |||  \\__| |_/||  /_ ")
        self.verbose1("\\_/  \\|\\____/\\____/\\____\\")
        self.verbose1("      v2409                 ")
        self.verbose1("_________________________")


        self.zero_tol=1e-10 #when values should be set to zero in the effective Hamiltonian
        self.zero_tol_evals=1e-16 #when values should be set to zero in the eigenvalues
        self.lanczos_tol=1e-12 #tolerance of Lanczos convergence
        self.remove_single_values=True #removes isolated diagonals from effective Hamiltonian
        self.lanczos=False # do lanczos algorithm
        self.exactDiag=True # do exact diagonalization
        self.spinOptimized=True # do a spinoptimized calculation
        self.fullCalculation=False # do the full double basis hamiltonian
        self.secondBorn=False # compute SB calculation
        self.mcde=True # compute MCDE calculation
        self.do_sparse=False
        self.do_auto_sparse=True # does sparse spinoptimized if the basis size is bigger than a threshold
        self.do_auto_sparse_basis_threshold=3000 # if the spin optimized basis is larger than 3000, the sparse method will be used if do_auto_sparse is set to true
        self.data_type_sparse=np.float64 # precision for the sparse matrix approach
        self.reduce_evecs_to_1body=False # discards the 3particle part of the eigenvectors, as they are not needed for the calculation of the spectrum
        self.sparse_tol=1e-8 #put values to zero in eff hamiltonian sparse algorithm when smaller than that

        self.shift_virtual_energy = 0 #energy shift in virtual energies in the body

        self.kernel_run=False # did you run the kernel?

        #self.mo_coeff = mocoeff
        self.mo_en = moEn
        self.eri_mo = erimo
        self.eri_mo_gabi =self.eri_mo.transpose((0,2,3,1))
        self.eri_mo_W = None
        self.eri_mo_gabi_W=None
        if self.eri_mo_W is not None:
            self.eri_mo_gabi_W=self.eri_mo_W.transpose((0,2,3,1))
        self.nO = nO
        self.nBas = nBas
        self.nV= nBas-nO

        estimate=int(2*int(self.nV*self.nO*(self.nO+1)/2+self.nO*self.nV*(self.nV+1)/2)-2*self.nO*self.nV+self.nBas)

        self.estimate_spin_opt_ham = estimate

        self.verbose2("Estimated size of spin Opt Hamiltonian basis: " + str(estimate))

        self.verbose4("nBas: "+str(nBas))
        self.verbose4("nO: "+str(self.nO))
        self.verbose4("nV: "+str(self.nV))

        self.iterations=max(int(estimate*.75),100) #lanczos iterations

        self.compare=[]
        self.compareshoulder=[]


    # cut corners everywhere
    def sparkurs(self):
        self.exactDiag=False
        self.data_type_sparse=np.float32
        self.do_sparse=True

    def kernel(self):

        self.verbose2("kernel start")
        self.verbose2(f"MCDE? {self.mcde}") # compute MCDE calculation
        self.verbose2(f"Second Born? {self.secondBorn}") # compute SB calculation
        self.verbose3(f"Spin Adapted Ham? {self.spinOptimized}") # do a spinoptimized calculation
        self.verbose3(f"Remove isolated diagonals from spin adapted Ham? {self.remove_single_values}") #removes isolated diagonals from effective Hamiltonian
        self.verbose3(f"Full eff Ham? {self.fullCalculation}") # do the full double basis hamiltonian
        self.verbose3(f"Effective Hamiltonian tolerance: {self.zero_tol}") #when values should be set to zero in the effective Hamiltonian

        if self.shift_virtual_energy != 0:
            self.verbose3(f"Shift of 3p virtual QP: {self.shift_virtual_energy}")

        if self.lanczos:
            self.verbose3(f"Lanczos algorithm? {self.lanczos}") # do lanczos algorithm
            self.verbose3(f"Lanczos convergence: {self.lanczos_tol}")#tolerance of Lanczos convergence

        if self.exactDiag:
            self.verbose3(f"Exact diagonalization? {self.exactDiag}") # do exact diagonalization
            self.verbose3(f"Eigenvalue tolerance: {self.zero_tol_evals}") #when values should be set to zero in the eigenvalues
            self.verbose3(f"Reduce eigenvectors to 1body part: {self.reduce_evecs_to_1body}") #only one body part needed for plotting

        if self.do_auto_sparse:
            if self.do_auto_sparse_basis_threshold<self.estimate_spin_opt_ham:
                self.do_sparse=True
                self.verbose3(f"Sparse method activated since basis size {self.estimate_spin_opt_ham} is larger than threshold {self.do_auto_sparse_basis_threshold}")
            else:
                self.verbose3(f"Sparse method: {self.do_sparse}")
        if self.do_sparse:
            self.verbose3(f"Sparse tolerance: {self.sparse_tol}")
            self.verbose3(f"sparse matrix datatype: {self.data_type_sparse}")

        if not self.do_sparse:    
            self.vout=self.vbar()
        self.nspace = self.g03spaceSelection()
        secondBorn=self.secondBorn
        calcMCDE=self.mcde
        full = self.fullCalculation
        exactdiag=self.exactDiag
        lanczos=self.lanczos
        spinOptimized=self.spinOptimized

        if full:
            self.sigma3s=self.sigma3shoulder()
            self.HeffSBmat=self.createSecondBornEffectiveHam()
            if calcMCDE:
                self.sigma3=self.g3sigma()
                # sets self.HeffMCDEmat
                self.HeffMCDE()
                if exactdiag:
                    self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs=self.exactDiagonalization(self.HeffMCDEmat)
                if lanczos:
                    self.HeffMCDEAcoeff,self.HeffMCDEBcoeff=self.LanczosAlgorithm(self.HeffMCDEmat,self.nBas*2)
            if secondBorn:
                self.HeffSecondBorn()
                if exactdiag:
                    self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs=self.exactDiagonalization(self.HeffSBmat)
                if lanczos:
                    self.HeffSBAcoeff,self.HeffSBBcoeff=self.LanczosAlgorithm(self.HeffSBmat,self.nBas*2)

        #spin free variant
        if spinOptimized:
            if not self.do_sparse:
                if secondBorn:
                    self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat=self.spinAdaptedMCDE(secondBorn)
                    if exactdiag:
                        self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs=self.exactDiagonalization(self.HeffMCDESpinAdaptmat)
                        self.HeffSBSpinAdaptExactDiagEvals,self.HeffSBSpinAdaptExactDiagEvecs=self.exactDiagonalization(self.HeffSBSpinAdaptmat)
                    if lanczos:
                        self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff=self.LanczosAlgorithm(self.HeffMCDESpinAdaptmat,self.nBas)
                        self.HeffSBSpinAdaptAcoeff,self.HeffSBSpinAdaptBcoeff=self.LanczosAlgorithm(self.HeffSBSpinAdaptmat,self.nBas)
                else:
                    self.HeffMCDESpinAdaptmat=self.spinAdaptedMCDE(secondBorn)
                    if exactdiag:
                        self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs=self.exactDiagonalization(self.HeffMCDESpinAdaptmat)
                    if lanczos:
                        self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff=self.LanczosAlgorithm(self.HeffMCDESpinAdaptmat,self.nBas)
            else:
                if secondBorn and calcMCDE:
                    self.HeffMCDESpinAdaptSparsemat,self.HeffSBSpinAdaptSparsemat=self.spinAdaptedMCDESparse(secondBorn)
                    if exactdiag:
                        self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffMCDESpinAdaptSparsemat)
                        self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffSBSpinAdaptSparsemat)
                elif secondBorn and not calcMCDE:
                    self.HeffSBSpinAdaptSparsemat=self.spinAdaptedMCDESparse(secondBorn)
                    if exactdiag:                    
                        self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffSBSpinAdaptSparsemat)
                elif calcMCDE and not secondBorn:
                    self.HeffMCDESpinAdaptSparsemat=self.spinAdaptedMCDESparse(secondBorn)
                    if exactdiag:
                        self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffMCDESpinAdaptSparsemat)
        self.kernel_run=True
        self.timed("kernel end", 2)
        self.verbose1("_________________________")
        self.verbose1("_________________________")





        # self.heff_evals,self.heff_evecs,self.heff_sigma3Shoulder,self.heff_sigma3Body=self.Heff()

        # if secondBorn:
        #     self.heff,self.heffSB=self.spinTransformedMCDE(secondBorn=True)
        #     if self.lanczos:
        #         self.a_coeff_SB,self.b_coeff_SB=self.LanczosAlgorithm(self.heffSB)
        #     else:
        #         self.heff_evals_SB,self.heff_evecs_SB=self.AuxillaryFunctions.eig(self.heffSB)
        #         self.heff_evals_SB=np.where(np.abs(self.heff_evals_SB) < self.zero_tol_evals, 0.0, self.heff_evals_SB)
        #         self.sigma3s=self.sigma3shoulder()
        #         self.heffFull_evals_SB,self.heffFull_evecs_SB=self.HeffSB()




    # return eigenvectors and Hamiltonians based on parameters
    def result(self):
        if not self.kernel_run:
            raise ValueError("kernel() not run")
        secondBorn=self.secondBorn
        calcMCDE=self.mcde
        full = self.fullCalculation
        exactdiag=self.exactDiag
        lanczos=self.lanczos
        spinOptimized=self.spinOptimized

        if full:
            if calcMCDE and secondBorn:
                if exactdiag and lanczos:
                    return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffMCDEmat,self.HeffSBmat
                if exactdiag:
                    return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffMCDEmat,self.HeffSBmat
                if lanczos:
                    return self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffMCDEmat,self.HeffSBmat
                return self.HeffMCDEmat,self.HeffSBmat
            if calcMCDE:
                if exactdiag and lanczos:
                    return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffMCDEmat
                if exactdiag:
                    return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffMCDEmat
                if lanczos:
                    return self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffMCDEmat
                return self.HeffMCDEmat
            if secondBorn:
                if exactdiag and lanczos:
                    return self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffSBmat
                if exactdiag:
                    return self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffSBmat
                if lanczos:
                    return self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffSBmat
                return self.HeffSBmat

        #spin free variant
        if spinOptimized:
            if not self.do_sparse:
                if secondBorn:
                    if exactdiag:
                        return self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs,self.HeffSBSpinAdaptExactDiagEvals,self.HeffSBSpinAdaptExactDiagEvecs,self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat
                    if lanczos:
                        return self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff,self.HeffSBSpinAdaptAcoeff,self.HeffSBSpinAdaptBcoeff,self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat
                    return self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat
                if calcMCDE:
                    if exactdiag:
                        return self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs,self.HeffMCDESpinAdaptmat
                    if lanczos:
                        return self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff,self.HeffMCDESpinAdaptmat
                    return self.HeffMCDESpinAdaptmat
            else:
                if secondBorn and calcMCDE:
                    if exactdiag:
                        return self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs,self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs,self.HeffMCDESpinAdaptSparsemat,self.HeffSBSpinAdaptSparsemat
                    return self.HeffMCDESpinAdaptSparsemat,self.HeffSBSpinAdaptSparsemat
                if calcMCDE and not secondBorn:
                    if exactdiag:
                        return self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs,self.HeffMCDESpinAdaptSparsemat
                    return self.HeffMCDESpinAdaptSparsemat
                if secondBorn and not calcMCDE:
                    if exactdiag:
                        return self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs,self.HeffSBSpinAdaptSparsemat
                    return self.HeffSBSpinAdaptSparsemat

    def saveMCDE(self,filename=None):

        if filename is None:
            filename=str(time.time())
        np.savez(filename+".npz",mcde=self)
        self.verbose2("MCDE object saved to " + filename+".npz")

    @staticmethod        
    def loadMCDE(filename):
        data = np.load(filename+".npz", allow_pickle=True)
        print("MCDE object loaded from " + filename+".npz")
        return data['mcde'].item()                


    def c2g(self,ind):
        return [ind[0],ind[2],ind[3],ind[1]]        
    def g2c(self,ind):
        return [ind[0],ind[3],ind[1],ind[2]]     

    def verbose1(self,txt):
        if self.verbose >= 1:
            print(txt)

    def verbose2(self,txt):
        if self.verbose >= 2:
            print(txt)

    def verbose3(self,txt):
        if self.verbose >= 3:
            print(txt)

    def verbose4(self,txt):
        if self.verbose >= 4:
            print(txt)

    def timed(self,txt,verbosity):
        laps=time.perf_counter()
        elapsed=laps-self.intermediatetime
        self.intermediatetime=laps
        if self.verbose >= verbosity:
            print("\n")
            print(txt + f" took {elapsed:.2f} seconds")
            print("\n")

    def sigma_mo_gabi(self,i,k,o,m):
        # return self.eri_mo_gabi[i,k,o,m]-self.eri_mo_gabi[i,k,m,o]
        return self.eri_mo_gabi[i,k,o,m]

    def sigma_mo_gabi_W(self,i,k,o,m):
        # return self.eri_mo_gabi[i,k,o,m]-self.eri_mo_gabi[i,k,m,o]
        return self.eri_mo_gabi_W[i,k,o,m]

    # for sparse use single basis
    def virtualShift(self,index):
        if index<self.nO:
            return 0
        return self.shift_virtual_energy

    def sqrt(self,x):
        return np.sqrt(x).astype(self.data_type_sparse)
#%% ordering the BSE kernels and creating the G03 space    

    def vbar(self):
        vout=np.zeros((self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2))
        self.verbose4("Vout calculation")
        for spinmu in range(2):
            for spinnu in range(2):
                for spinla in range(2):
                    for spinsi in range(2):
                        for mu in range(self.nBas):
                            for nu in range(self.nBas):
                                for la in range(self.nBas):
                                    for si in range(self.nBas):
                                        mu2 = (mu) * 2 
                                        nu2 = (nu) * 2 
                                        la2 = (la) * 2 
                                        si2 = (si) * 2 

                                        mu2 += 1 if (spinmu == 1) else 0
                                        nu2 += 1 if (spinnu == 1) else 0
                                        la2 += 1 if (spinla == 1) else 0
                                        si2 += 1 if (spinsi == 1) else 0

                                        spinmatch1 = 0.0
                                        spinmatch2 = 0.0
                                        spintotalmatch = 0.0

                                        if ((spinmu==spinnu) or (spinla == spinsi)):
                                            spinmatch1 = 1.0
                                        if ((spinmu==spinsi) or (spinla == spinnu)):
                                            spinmatch2 = 1.0

                                        spinsum = spinmu + spinnu + spinla + spinsi
                                        if (spinsum % 2 == 0):
                                            spintotalmatch = 1.0

                                        #chemists: 1234 -> physi 1324 -> gabi 1342
                                        vout[mu2,la2,si2,nu2]=spintotalmatch * (self.eri_mo_gabi[mu,la,si,nu]*spinmatch1 - self.eri_mo_gabi[mu,la,nu,si]*spinmatch2)

                                        if (abs(vout[mu2,la2,si2,nu2])>1e-5 and self.verbose>=4):
                                            self.verbose4('%4d %4d %4d %4d      %.5f'%(mu2,la2,si2,nu2,vout[mu2,la2,si2,nu2]))
        return vout


    def vbarOnTheSpot(self,mu2,la2,si2,nu2):
        mu=mu2//2
        la=la2//2
        nu=nu2//2
        si=si2//2


        spinmu=mu2%2
        spinla=la2%2
        spinnu=nu2%2
        spinsi=si2%2

        spinmatch1 = 0.0
        spinmatch2 = 0.0
        spintotalmatch = 0.0

        if ((spinmu==spinnu) or (spinla == spinsi)):
            spinmatch1 = 1.0
        if ((spinmu==spinsi) or (spinla == spinnu)):
            spinmatch2 = 1.0

        spinsum = spinmu + spinnu + spinla + spinsi
        if (spinsum % 2 == 0):
            spintotalmatch = 1.0

        return spintotalmatch * (self.eri_mo_gabi[mu,la,si,nu]*spinmatch1 - self.eri_mo_gabi[mu,la,nu,si]*spinmatch2)

    def g03spaceSelection(self):
        self.verbose4("G03 space selection")
        long_ab=np.arange(0,self.nBas*2)
        # rule ijl; i>j and l is occupied MO (electron that needs to be removed)
        space=[]
        for i in long_ab:
            fi=1 if i < self.nO*2 else 0
            for j in long_ab:
                fj=1 if j < self.nO*2 else 0
                if i>j:
                    for l in long_ab: 
                        fl=1 if l < self.nO*2 else 0
                        if (fi-fl)*(fj-fl) != 0:
                            space.append([i,j,l])
                            self.verbose4('%4d %4d %4d'%(i,j,l))
        return space              

#%% For the full effective Hamiltonian, creating the self energy shoulder and the self energy body

    def g3sigma(self):
        self.verbose4("The Sigma3 body")
        sigma3matrix=np.zeros((self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2))
        nspace=self.nspace
        for idx in range(len(nspace)):
            [i,j,l] = nspace[idx]

            fi = 0 if (i >= self.nO*2) else 1
            fj = 0 if (j >= self.nO*2) else 1
            fl = 0 if (l >= self.nO*2) else 1

            for jdx in range(len(nspace)):
                [m,o,k]=nspace[jdx]

                dlk = 1 if (l==k) else 0
                dmj = 1 if (m==j) else 0
                dio = 1 if (i==o) else 0
                doj = 1 if (o==j) else 0
                dim = 1 if (i==m) else 0

                if ((fi-fl)*(fj-fl)==0):
                    continue

                prefac=((1-fi)*(1-fj)*fl-fi*fj*(1-fl))
                lkterm=dlk*self.vout[i,j,o,m]
                mjterm=dmj*self.vout[i,k,l,o]
                ioterm=dio*self.vout[j,k,l,m]
                ojterm=doj*self.vout[i,k,l,m]
                imterm=dim*self.vout[j,k,l,o]

                sigma3matrix[i, j, l, m, o, k]=prefac*(lkterm+mjterm+ioterm-ojterm-imterm)
                if (abs(sigma3matrix[i, j, l, m, o, k])>1e-15):
                    self.compare.append([str(i),str(j),str(l),str(m),str(o),str(k),f"{sigma3matrix[i, j, l, m, o, k]:.4f}"])
                    self.verbose4('%4d %4d %4d %4d %4d %4d      %.5f'%(i,j,l,m,o,k,sigma3matrix[i, j, l, m, o, k]))

        return sigma3matrix

    def sigma3shoulder(self):
        self.verbose4("The Sigma3 shoulder")
        sigma3s=np.zeros((self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2))
        nspace=self.nspace
        for i in range(self.nBas*2):
            for idx in range(len(nspace)):
                [m,o,k] = nspace[idx]
                sigma3s[i, m, o, k]=self.vout[i,k,o,m]
                self.verbose4('%4d %4d %4d %4d      %.5f'%(i,m,o,k,sigma3s[i, m, o, k]))
                if (abs(sigma3s[i, m, o, k])>1e-15):
                    self.compareshoulder.append([str(i),str(m),str(o),str(k),f"{sigma3s[i, m, o, k]:.4f}"])
                    self.verbose4('%4d %4d %4d %4d      %.5f'%(i,m,o,k,sigma3s[i, m, o, k]))
        return sigma3s

#%% creating the full effective Hamiltonians

    def createSecondBornEffectiveHam(self):
        self.verbose4("H effective")
        e01energies=np.zeros((self.nBas*2))
        self.verbose4("writing the double basis hf energies")
        for idx in range(self.nBas*2):
            jdx=int((idx)/2)
            e01energies[idx]=self.mo_en[jdx]
            self.verbose4('%4d   %.5f'%(jdx,self.mo_en[jdx]))

        self.verbose4("writing the triple particle hf energies")
        e03energies=[]
        sigmaShoulder=np.zeros((self.nBas*2,len(self.nspace)))
        sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
        for index,element in enumerate(self.nspace):
            a=element[0]
            b=element[1]
            c=element[2]

            e03energies.append(e01energies[a]+e01energies[b]-e01energies[c])
            self.verbose4('%4d %4d %4d   %.5f'%(a,b,c,e03energies[index]))


            for jdx in range(self.nBas*2):
                sigmaShoulder[jdx,index]=self.sigma3s[jdx,a,b,c]

        h03=np.diag(np.concatenate((e01energies,e03energies)))



        selfie=np.block([
            [np.zeros((self.nBas*2,self.nBas*2)),sigmaShoulder],
            [sigmaShoulder.T,sigmaBody]
            ])

        self.heffZ=np.add(h03,selfie)
        self.verbose4("Nonzero values of effective Hamiltionian")
        if self.verbose>=4:
            for ii in range(len(self.heffZ)):
                for jj in range(len(self.heffZ)):
                    if (abs(self.heffZ[ii,jj])>1e-15):
                        self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffZ[ii,jj]))

        self.e03energies=e03energies
        self.e01energies=e01energies

        return np.add(h03,selfie)


    def HeffMCDE(self):
        if self.HeffSBmat is None:
            raise ValueError("The second Born effective Hamiltonian has not been initialised with createSecondBornEffectiveHam")
        if self.sigma3 is None:
            raise ValueError("3-particle self energy not initialized with sigma3s")

        index=self.nBas*2
        self.HeffMCDEmat=self.HeffSBmat.copy()
        sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
        for index,element in enumerate(self.nspace):
            a=element[0]
            b=element[1]
            c=element[2]
            for index2,element2 in enumerate(self.nspace):
                x=element2[0]
                y=element2[1]
                z=element2[2]
                sigmaBody[index,index2]=self.sigma3[a,b,c,x,y,z]
        # print("Target shape:", self.HeffMCDEmat[index:index+sigmaBody.shape[0],
        #                                 index:index+sigmaBody.shape[1]].shape)
        # print("sigmaBody shape:", sigmaBody.shape)
        index=self.nBas*2
        self.HeffMCDEmat[index:index+sigmaBody.shape[0], index:index+sigmaBody.shape[1]]+=sigmaBody

        self.verbose4("Nonzero values of effective Hamiltionian")
        if self.verbose>=4:
            for ii in range(len(self.HeffMCDEmat)):
                for jj in range(len(self.HeffMCDEmat)):
                    if (abs(self.HeffMCDEmat[ii,jj])>1e-15):
                        self.verbose4('%4d %4d      %.5f'%(ii,jj,self.HeffMCDEmat[ii,jj]))


    def HeffSecondBorn(self):
        if self.HeffSBmat is None:
            raise ValueError("The second Born effective Hamiltonian has not been initialised with createSecondBornEffectiveHam")




        self.verbose4("Nonzero values of effective Hamiltionian")
        if self.verbose>=4:
            for ii in range(len(self.heffSBmat)):
                for jj in range(len(self.heffSBmat)):
                    if (abs(self.heffSBmat[ii,jj])>1e-15):
                        self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffSBmat[ii,jj]))

    def OldHeffSB(self):
        self.verbose4("H effective")
        e01energies=np.zeros((self.nBas*2))
        self.verbose4("writing the double basis hf energies")
        for idx in range(self.nBas*2):
            jdx=int((idx)/2)
            e01energies[idx]=self.mo_en[jdx]
            self.verbose4('%4d   %.5f'%(jdx,self.mo_en[jdx]))

        self.verbose4("writing the triple particle hf energies")
        e03energies=[]
        sigmaShoulder=np.zeros((self.nBas*2,len(self.nspace)))
        sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
        for index,element in enumerate(self.nspace):
            a=element[0]
            b=element[1]
            c=element[2]

            e03energies.append(e01energies[a]+e01energies[b]-e01energies[c])
            self.verbose4('%4d %4d %4d   %.5f'%(a,b,c,e03energies[index]))


            for jdx in range(self.nBas*2):
                sigmaShoulder[jdx,index]=self.sigma3s[jdx,a,b,c]




        h03=np.diag(np.concatenate((e01energies,e03energies)))



        selfie=np.block([
            [np.zeros((self.nBas*2,self.nBas*2)),sigmaShoulder],
            [sigmaShoulder.T,sigmaBody]
            ])

        self.heffZ=np.add(h03,selfie)
        self.verbose4("Nonzero values of effective Hamiltionian")
        if self.verbose>=4:
            for ii in range(len(self.heffZ)):
                for jj in range(len(self.heffZ)):
                    if (abs(self.heffZ[ii,jj])>1e-15):
                        self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffZ[ii,jj]))

        self.HeffSBmat=np.add(h03,selfie)
        evals,evecs=self.AuxillaryFunctions.eig(np.add(h03,selfie))


        self.verbose4("Eigenvalues for H effective")
        if self.verbose>=4:
            idx = np.argsort(evals)  # use -eigvals for descending
            eigvals_sorted = evals[idx]
            eigvecs_sorted = evecs[:, idx]
            for ii in range(len(evals)):
                self.verbose4('%4d      %.5f'%(ii,eigvals_sorted[ii]))

        return evals,evecs

    def OldHeff(self):
        self.verbose4("H effective")
        e01energies=np.zeros((self.nBas*2))
        self.verbose4("writing the double basis hf energies")
        for idx in range(self.nBas*2):
            jdx=int((idx)/2)
            e01energies[idx]=self.mo_en[jdx]
            self.verbose4('%4d   %.5f'%(jdx,self.mo_en[jdx]))

        self.verbose4("writing the triple particle hf energies")
        e03energies=[]
        sigmaShoulder=np.zeros((self.nBas*2,len(self.nspace)))
        sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
        for index,element in enumerate(self.nspace):
            a=element[0]
            b=element[1]
            c=element[2]

            e03energies.append(e01energies[a]+e01energies[b]-e01energies[c])
            self.verbose4('%4d %4d %4d   %.5f'%(a,b,c,e03energies[index]))


            for jdx in range(self.nBas*2):
                sigmaShoulder[jdx,index]=self.sigma3s[jdx,a,b,c]

            for index2,element2 in enumerate(self.nspace):
                x=element2[0]
                y=element2[1]
                z=element2[2]
                sigmaBody[index,index2]=self.sigma3[a,b,c,x,y,z]


        h03=np.diag(np.concatenate((e01energies,e03energies)))



        selfie=np.block([
            [np.zeros((self.nBas*2,self.nBas*2)),sigmaShoulder],
            [sigmaShoulder.T,sigmaBody]
            ])

        self.heffZ=np.add(h03,selfie)
        self.verbose4("Nonzero values of effective Hamiltionian")
        if self.verbose>=4:
            for ii in range(len(self.heffZ)):
                for jj in range(len(self.heffZ)):
                    if (abs(self.heffZ[ii,jj])>1e-15):
                        self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffZ[ii,jj]))

        evals,evecs=self.AuxillaryFunctions.eig(np.add(h03,selfie))
        idx = np.argsort(evals)  # use -eigvals for descending
       # eigvals_sorted = evals[idx]
       # eigvecs_sorted = evecs[:, idx]

        self.verbose4("Eigenvalues for H effective")
        if self.verbose>=4:
            for ii in range(len(evals)):
                self.verbose4('%4d      %.5f'%(ii,evals[ii]))

        return evals,evecs,sigmaShoulder,sigmaBody

#%% spin adapted effective Hamiltonian

    # def createSecondBornEffectiveSpinAdaptedHam(self):

    #     self.verbose3("create Second Born Effective Spin Adapted Hamiltonian")


    #     def d(a,b):
    #         return 1 if a==b else 0


    #     #transform spinorbitals to spatial orbitals
    #     nspace_spatials0=[]
    #     for entry in self.nspace:
    #         nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
    #     #remove duplicates
    #     seen = set()
    #     nspace_spatials = []
    #     for item in nspace_spatials0:
    #         t = tuple(item)
    #         if t not in seen:
    #             seen.add(t)
    #             nspace_spatials.append(item)

    #     self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
    #     self.verbose4(nspace_spatials)
    #     ray=[]
    #     for i in range(self.nBas):
    #         ray.append(self.mo_en[i])
    #     head=np.diag(ray)

    #     #create wing

    #     wing=np.zeros((len(nspace_spatials)*2,len(ray)))

    #     for leftindex,left in enumerate(nspace_spatials):
    #         [i,j,l]=left
    #         for rightindex,m in enumerate(np.arange(self.nBas)):
    #             C3=np.sqrt(.5)**(d(i,j))*np.sqrt(.5)*(self.sigma_mo_gabi(i,j,l,m)+self.sigma_mo_gabi(i,j,m,l))
    #             C4=np.sqrt(3/2)*(self.sigma_mo_gabi(i,j,l,m)-self.sigma_mo_gabi(i,j,m,l))

    #             wing[2*leftindex,rightindex]=C3
    #             wing[2*leftindex+1,rightindex]=C4

    #     #create body matrix

    #     body=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
    #     # bodyHF=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
    #     for leftindex,left in enumerate(nspace_spatials):
    #         [i,j,l]=left

    #         for rightindex,right in enumerate(nspace_spatials):
    #             [m,o,k]=right


    #             A1=np.sqrt(.5)**(d(m,o))*np.sqrt(.5)**(d(i,j))*(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)+self.sigma_mo_gabi(i,j,m,o))
    #                                                           +d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-.5*self.sigma_mo_gabi(i,k,o,l))
    #                                                           +d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-.5*self.sigma_mo_gabi(j,k,m,l))
    #                                                           +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-.5*self.sigma_mo_gabi(i,k,m,l))
    #                                                           +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-.5*self.sigma_mo_gabi(j,k,o,l)))
    #             A2=(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)-self.sigma_mo_gabi(i,j,m,o))
    #                                                           -d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-1.5*self.sigma_mo_gabi(i,k,o,l))
    #                                                           -d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-1.5*self.sigma_mo_gabi(j,k,m,l))
    #                                                           +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-1.5*self.sigma_mo_gabi(i,k,m,l))
    #                                                           +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-1.5*self.sigma_mo_gabi(j,k,o,l)))
    #             F1=np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(-d(m,j)*self.sigma_mo_gabi(i,k,o,l)+d(i,o)*self.sigma_mo_gabi(j,k,m,l)
    #                                                   +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
    #                                                   -d(i,m)*self.sigma_mo_gabi(j,k,o,l))
    #             F2=np.sqrt(.5)**(d(m,o))*(np.sqrt(3)/2)*(d(m,j)*self.sigma_mo_gabi(i,k,o,l)-d(i,o)*self.sigma_mo_gabi(j,k,m,l)
    #                                                   +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
    #                                                   -d(i,m)*self.sigma_mo_gabi(j,k,o,l))


    #             fi = 0 if (i >= self.nO) else 1
    #             fj = 0 if (j >= self.nO) else 1
    #             fl = 0 if (l >= self.nO) else 1
    #             prefac=-((1-fi)*(1-fj)*fl-fi*fj*(1-fl))

    #             ei=self.mo_en[i]
    #             ej=self.mo_en[j]
    #             el=self.mo_en[l]
    #             de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


    #             body[2*leftindex,2*rightindex]=de+prefac*A1
    #             body[2*leftindex,2*rightindex+1]=prefac*F1
    #             body[2*leftindex+1,2*rightindex]=prefac*F2
    #             body[2*leftindex+1,2*rightindex+1]=de+prefac*A2

    #     H3upd=np.block([[head,np.transpose(wing)],[wing,body]])

    #     return H3upd

    # def HeffSBSpinAdapt(self):
    #     if self.HeffSBSpinAdaptMat is None:
    #         raise ValueError("the effective Hamiltonian spin adapted matrix is not initialized with createSecondBornEffectiveSpinAdaptedHam")
    #     self.HeffSBSpinAdaptMat=np.where(np.abs(self.HeffSBSpinAdaptMat) < self.zero_tol, 0.0, self.HeffSBSpinAdaptMat)
    #     self.HeffSBSpinAdaptMat=self.AuxillaryFunctions.remove_isolated_diagonals(self.HeffSBSpinAdaptMat)

    # def HeffMCDESpinAdapt(self):
    #     if self.HeffSBSpinAdaptMat is None:
    #         raise ValueError("the effective Hamiltonian spin adapted matrix is not initialized with createSecondBornEffectiveSpinAdaptedHam")
    #     self.HeffMCDESpinAdapt=self.HeffSBSpinAdapt.copy()



    #     self.HeffMCDESpinAdaptMat=np.where(np.abs(self.HeffMCDESpinAdaptMat) < self.zero_tol, 0.0, self.HeffMCDESpinAdaptMat)
    #     self.HeffMCDESpinAdaptMat=self.AuxillaryFunctions.remove_isolated_diagonals(self.HeffMCDESpinAdaptMat)



    def spinAdaptedMCDE(self,secondBorn=False):

        self.verbose3("Spin transformed MCDE")
        self.verbose3("Second Born? "+str(secondBorn))

        def d(a,b):
            return 1 if a==b else 0


        #transform spinorbitals to spatial orbitals
        nspace_spatials0=[]
        for entry in self.nspace:
            nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
        #remove duplicates
        seen = set()
        nspace_spatials = []
        for item in nspace_spatials0:
            t = tuple(item)
            if t not in seen:
                seen.add(t)
                nspace_spatials.append(item)

        #initialize 1part+3part nspace index
        spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

        self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
        self.verbose4(nspace_spatials)
        ray=[]
        for i in range(self.nBas):
            ray.append(self.mo_en[i])
        head=np.diag(ray)

        #create wing

        wing=np.zeros((len(nspace_spatials)*2,len(ray)))

        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left
            for rightindex,m in enumerate(np.arange(self.nBas)):
                C3=np.sqrt(.5)**(d(i,j))*np.sqrt(.5)*(self.sigma_mo_gabi(i,j,l,m)+self.sigma_mo_gabi(i,j,m,l))
                C4=np.sqrt(3/2)*(self.sigma_mo_gabi(i,j,l,m)-self.sigma_mo_gabi(i,j,m,l))

                wing[2*leftindex,rightindex]=C3
                wing[2*leftindex+1,rightindex]=C4

        #create body matrix

        body=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        # bodyHF=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left

            for rightindex,right in enumerate(nspace_spatials):
                [m,o,k]=right


                A1=np.sqrt(.5)**(d(m,o))*np.sqrt(.5)**(d(i,j))*(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)+self.sigma_mo_gabi(i,j,m,o))
                                                              +d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-.5*self.sigma_mo_gabi(i,k,o,l))
                                                              +d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-.5*self.sigma_mo_gabi(j,k,m,l))
                                                              +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-.5*self.sigma_mo_gabi(i,k,m,l))
                                                              +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-.5*self.sigma_mo_gabi(j,k,o,l)))
                A2=(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)-self.sigma_mo_gabi(i,j,m,o))
                                                              -d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-1.5*self.sigma_mo_gabi(i,k,o,l))
                                                              -d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-1.5*self.sigma_mo_gabi(j,k,m,l))
                                                              +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-1.5*self.sigma_mo_gabi(i,k,m,l))
                                                              +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-1.5*self.sigma_mo_gabi(j,k,o,l)))
                F1=np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(-d(m,j)*self.sigma_mo_gabi(i,k,o,l)+d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                      +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                      -d(i,m)*self.sigma_mo_gabi(j,k,o,l))
                F2=np.sqrt(.5)**(d(m,o))*(np.sqrt(3)/2)*(d(m,j)*self.sigma_mo_gabi(i,k,o,l)-d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                      +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                      -d(i,m)*self.sigma_mo_gabi(j,k,o,l))


                fi = 0 if (i >= self.nO) else 1
                fj = 0 if (j >= self.nO) else 1
                fl = 0 if (l >= self.nO) else 1
                prefac=-((1-fi)*(1-fj)*fl-fi*fj*(1-fl))

                ei=self.mo_en[i]
                ej=self.mo_en[j]
                el=self.mo_en[l]
                de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


                body[2*leftindex,2*rightindex]=de+prefac*A1
                body[2*leftindex,2*rightindex+1]=prefac*F1
                body[2*leftindex+1,2*rightindex]=prefac*F2
                body[2*leftindex+1,2*rightindex+1]=de+prefac*A2

                # bodyHF[2*leftindex,2*rightindex]=de
                # bodyHF[2*leftindex+1,2*rightindex+1]=de

        if secondBorn:
            bodySB=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))

            for leftindex,left in enumerate(nspace_spatials):
                [i,j,l]=left

                for rightindex,right in enumerate(nspace_spatials):
                    [m,o,k]=right


                    ei=self.mo_en[i]
                    ej=self.mo_en[j]
                    el=self.mo_en[l]
                    de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


                    bodySB[2*leftindex,2*rightindex]=de
                    bodySB[2*leftindex,2*rightindex+1]=0
                    bodySB[2*leftindex+1,2*rightindex]=0
                    bodySB[2*leftindex+1,2*rightindex+1]=de

        H3upd=np.block([[head,np.transpose(wing)],[wing,body]])



        H3upd=np.where(np.abs(H3upd) < self.zero_tol, 0.0, H3upd)

        if secondBorn:
            H3SB=np.block([[head,np.transpose(wing)],[wing,bodySB]])
            H3SB=np.where(np.abs(H3SB) < self.zero_tol, 0.0, H3SB)
            H3SB,self.nspace_spatials_SB=self.AuxillaryFunctions.remove_isolated_diagonals(H3SB,spaceObj,self.remove_single_values)


        H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals(H3upd,spaceObj,self.remove_single_values)



        self.timed("Creating spin Opt eff. Hamiltonian",2)

        if secondBorn:
            return H3upd,H3SB
        return H3upd

    def spinAdaptedMCDEFullChunks(self,secondBorn=False):
        self.verbose3("Full MCDE Chunks")
        self.verbose3("Second Born? "+str(secondBorn))

        datatype=self.data_type_sparse
        NBAS=2*self.nBas
        NO=2*self.nO
        #  small number
        def sqrt(x):
            return np.sqrt(x).astype(datatype)

        def check32(arr):
            prod=np.prod(arr.shape)
            res=(prod*4==arr.nbytes)
            if res:
                print("Is 32")
            else:
                print("Is not 32, its ",type(arr))
                print("Size: ",arr.nbytes)
                print("Theory: ", prod*4)
                sys.exit()

        def check16(arr):
            return None
            prod=np.prod(arr.shape)
            res=(prod*2==arr.nbytes)
            if res:
                print("Is 16")
            else:
                print("Is not 16, its ",type(arr))
                print("Size: ",arr.nbytes)
                print("Theory: ", prod*2)
                sys.exit()



        nspace3particle = np.array(self.nspace)   # shape (N,3)
        spaceObj=MCDE.Nspace(np.arange(NBAS),self.nspace)

        # head
        ray=[]
        for i in range(NBAS):
            ray.append(self.mo_en[i//2])
        head=np.diag(ray).astype(datatype)

        # check32(head)

        nBasspace=np.arange(NBAS)
        mwing = nBasspace[:,None]

        N = len(nspace3particle)

        chunk_size = max(N//100,2)
        chunk_size = 5000 if chunk_size > 5000 else chunk_size
        chunk_size = 1
        nchunks = [
            (i, i + len(nspace3particle[i:i+chunk_size]), nspace3particle[i:i+chunk_size])
            for i in range(0, len(nspace3particle), chunk_size)
        ]



        def speedUpCore(nspaceL,nspaceR):

            body_out = None

            i = nspaceL[:, 0]
            j = nspaceL[:, 1]
            l = nspaceL[:, 2]

            m = nspaceR[:, 0]
            o = nspaceR[:, 1]
            k = nspaceR[:, 2]

            iL = i[:, None]
            jL = j[:, None]
            lL = l[:, None]

            mR = m[None, :]
            oR = o[None, :]
            kR = k[None, :]

            dim = (iL == mR).astype(datatype)
            djo = (jL == oR).astype(datatype)
            dlk = (lL == kR).astype(datatype)

            dmj = (mR == jL).astype(datatype)
            dio = (iL == oR).astype(datatype)
            doj = (oR == jL).astype(datatype)

            ei = self.mo_en[i//2].astype(datatype)
            ej = self.mo_en[j//2].astype(datatype)
            el = self.mo_en[l//2].astype(datatype)

            eiL = ei[:, None]
            ejL = ej[:, None]
            elL = el[:, None]

            # check16(dlk)

            de = ((eiL - (elL - ejL)) * dim * djo * dlk).astype(datatype)

            # check32(de)
            #memory expensive!

            sigma=self.eri_mo_gabi.astype(datatype)


            # S_ijom = (iL%2 == mR%2 or jL%2 == oR%2)*sigma[iL, jL, oR, mR].astype(datatype)
            # S_ijmo = (iL%2 == oR%2 or jL%2 == mR%2)*sigma[iL, jL, mR, oR].astype(datatype)
            # S_iklo = (iL%2 == oR%2 or lL%2 == kR%2)*sigma[iL, kR, lL, oR].astype(datatype)
            # S_ikol = (iL%2 == lL%2 or oR%2 == kR%2)*sigma[iL, kR, oR, lL].astype(datatype)
            # S_jklm = (jL%2 == mR%2 or lL%2 == kR%2)*sigma[jL, kR, lL, mR].astype(datatype)
            # S_jkml = (jL%2 == lL%2 or mR%2 == kR%2)*sigma[jL, kR, mR, lL].astype(datatype)
            # S_iklm = (iL%2 == mR%2 or lL%2 == kR%2)*sigma[iL, kR, lL, mR].astype(datatype)
            # S_ikml = (iL%2 == lL%2 or mR%2 == kR%2)*sigma[iL, kR, mR, lL].astype(datatype)
            # S_jklo = (jL%2 == oR%2 or kR%2 == lL%2)*sigma[jL, kR, lL, oR].astype(datatype)
            # S_jkol = (jL%2 == lL%2 or kR%2 == oR%2)*sigma[jL, kR, oR, lL].astype(datatype)

            dividefactor=2
            S_1 = (((iL%2 + mR%2 + jL%2 + oR%2)%2==0)     
                   *(((iL % 2 == mR % 2) | (jL % 2 == oR % 2))
                                                   *sigma[iL//dividefactor, jL//dividefactor, oR//dividefactor, mR//dividefactor]-
                                                   ((iL % 2 == oR % 2) | (jL % 2 == mR % 2))*sigma[iL//dividefactor, jL//dividefactor, mR//dividefactor, oR//dividefactor])).astype(datatype)
            S_2 = (((iL%2 + kR%2 + lL%2 + oR%2)%2==0)
                   *(((iL % 2 == oR % 2) | (lL % 2 == kR % 2))*sigma[iL//dividefactor, kR//dividefactor, lL//dividefactor, oR//dividefactor]-
                                                   ((iL % 2 == kR % 2) | (lL % 2 == oR % 2))*sigma[iL//2, kR//dividefactor, oR//dividefactor, lL//dividefactor])).astype(datatype)
            S_3 = (((jL%2 + kR%2 + lL%2 + mR%2)%2==0)
                   *(((jL % 2 == mR % 2) | (lL % 2 == kR % 2))*sigma[jL//dividefactor, kR//dividefactor, lL//dividefactor, mR//dividefactor]-
                                                   ((jL % 2 == lL % 2) | (mR % 2 == kR % 2))*sigma[jL//dividefactor, kR//dividefactor, mR//dividefactor, lL//dividefactor])).astype(datatype)
            S_4 = (((iL%2 + kR%2 + lL%2 + mR%2)%2==0)
                   *(((iL % 2 == mR % 2) | (lL % 2 == kR % 2))*sigma[iL//dividefactor, kR//dividefactor, lL//dividefactor, mR//dividefactor]-
                                                   ((iL % 2 == lL % 2) | (mR % 2 == kR % 2))*sigma[iL//dividefactor, kR//dividefactor, mR//dividefactor, lL//dividefactor])).astype(datatype)
            S_5 = (((jL%2 + kR%2 + lL%2 + oR%2)%2==0)
                   *(((jL % 2 == oR % 2) | (lL % 2 == kR % 2))*sigma[jL//dividefactor, kR//dividefactor, lL//dividefactor, oR//dividefactor]-
                                                   ((jL % 2 == lL % 2) | (kR % 2 == oR % 2))*sigma[jL//dividefactor, kR//dividefactor, oR//dividefactor, lL//dividefactor])).astype(datatype)

            # spinmatch_ijom = (iL%2 == mR%2 or jL%2 == oR%2).astype(datatype)
            # spinmatch_ijmo = (iL%2 == oR%2 or jL%2 == mR%2).astype(datatype)
            # spinmatch_iklo = (iL%2 == oR%2 or lL%2 == kR%2).astype(datatype)
            # spinmatch_ikol = (iL%2 == lL%2 or oR%2 == kR%2).astype(datatype)
            # spinmatch_jklm = (jL%2 == mR%2 or lL%2 == kR%2).astype(datatype)
            # spinmatch_jkml = (jL%2 == lL%2 or mR%2 == kR%2).astype(datatype)
            # spinmatch_iklm = (iL%2 == mR%2 or lL%2 == kR%2).astype(datatype)
            # spinmatch_ikml = (iL%2 == lL%2 or mR%2 == kR%2).astype(datatype)
            # spinmatch_jklo = (jL%2 == oR%2 or kR%2 == lL%2).astype(datatype)
            # spinmatch_jkol = (jL%2 == lL%2 or kR%2 == oR%2).astype(datatype)

            # spintotalmatch_ijom=((iL%2 + mR%2 + jL%2 + oR%2)%2==0).astype(datatype)
            # spintotalmatch_iklo=((iL%2 + kR%2 + lL%2 + oR%2)%2==0).astype(datatype)
            # spintotalmatch_jklm=((jL%2 + kR%2 + lL%2 + mR%2)%2==0).astype(datatype)
            # spintotalmatch_iklm=((iL%2 + kR%2 + lL%2 + mR%2)%2==0).astype(datatype)
            # spintotalmatch_jklo=((jL%2 + kR%2 + lL%2 + oR%2)%2==0).astype(datatype)

            djo = (jL == oR).astype(datatype)
            dlk = (lL == kR).astype(datatype)

            dmj = (mR == jL).astype(datatype)
            dio = (iL == oR).astype(datatype)
            doj = (oR == jL).astype(datatype)

            fi = (i < NO).astype(np.int32)
            fj = (j < NO).astype(np.int32)
            fl = (l < NO).astype(np.int32)

            fiL = fi[:, None]
            fjL = fj[:, None]
            flL = fl[:, None]

            prefac = (((1-fiL)*(1-fjL)*flL - fiL*fjL*(1-flL))).astype(datatype)
            # print(de)
            # print(prefac)
            # interaction = (de+prefac*(dlk*S_1+dmj*S_2+dio*S_3-doj*S_4-dim*S_5)).astype(datatype)
            body_out = (de+prefac*(dlk*S_1+dmj*S_2+dio*S_3-doj*S_4-dim*S_5)).astype(datatype)

            # print("the body")
            # print(body_out)


            # print("the interaction")
            # print(interaction)
            # print(interaction - interaction.T)

            # terms = {
            #     "dlk*S1": dlk*S_1,
            #     "dmj*S2": dmj*S_2,
            #     "dio*S3": dio*S_3,
            #     "doj*S4": doj*S_4,
            #     "dim*S5": dim*S_5,
            # }

            # for name, term in terms.items():
            #     print(name)
            #     print(term)
            #     print(term - term.T)

            # sys.exit()
            # body = de
            return body_out

        def speedUpShoulder(nspaceR):

            m = nspaceR[:, 0]
            o = nspaceR[:, 1]
            k = nspaceR[:, 2]

            mR = m[None, :]
            oR = o[None, :]
            kR = k[None, :]

            sigma=self.eri_mo_gabi.astype(datatype)

            dividefactor=2

            cond1 = ((mwing % 2 + mR % 2 + kR % 2 + oR % 2) % 2 == 0).astype(datatype)

            term1 = ((mwing % 2 == mR % 2) | (kR % 2 == oR % 2)).astype(datatype)

            term2 = ((mwing % 2 == oR % 2) | (kR % 2 == mR % 2)).astype(datatype)

            s_1 = (
                cond1 *
                (
                    term1 * sigma[mwing // dividefactor,
                                  kR // dividefactor,
                                  oR // dividefactor,
                                  mR // dividefactor]
                    -
                    term2 * sigma[mwing // dividefactor,
                                  kR // dividefactor,
                                  mR // dividefactor,
                                  oR // dividefactor]
                )
            ).astype(datatype)

            return s_1

        body = np.zeros((N, N),dtype=datatype)

        wing = np.zeros((NBAS,len(nspace3particle)),dtype=datatype)
        # print(wing.shape)
        for tchunkR in nchunks:
            (indexR0, indexR1, chunkR) = tchunkR
            shoulderchunk=speedUpShoulder(chunkR)
            c0 = indexR0
            c1 = indexR1
            # print(c0)
            # print(c1)
            # print(shoulderchunk.shape)
            # print(wing[:NBAS,c0:c1].shape)
            # print(wing[:NBAS,c0:c1].shape)
            wing[:NBAS,c0:c1] = shoulderchunk
            for tchunkL in nchunks:

                (indexL0, indexL1, chunkL) = tchunkL


                # indexL0=indexL
                # indexL1=indexL+chunk_size
                # indexR0=indexR
                # indexR1=indexR+chunk_size

                bodychunk=speedUpCore(chunkL,chunkR)
                bodychunkB=speedUpCore(chunkR,chunkL).conj().T
                if not np.allclose(bodychunk,bodychunkB):
                    print(bodychunk)
                    print(bodychunkB)
                    print(chunkL)
                    print(chunkR)
                    print(indexL0)
                    print(indexR0)
                    sys.exit()

                r0 = indexL0
                r1 = indexL1


                # even-even (A)
                body[r0:r1, c0:c1] = bodychunk

        body[np.abs(body) < self.sparse_tol] = 0.0
        head[np.abs(head) < self.sparse_tol] = 0.0
        wing[np.abs(wing) < self.sparse_tol] = 0.0
        # body_sparse = csr_matrix(body)
        # print(wing.shape)
        # print(body.shape)
        # print(head.shape)


        H3upd=scipy.sparse.bmat([[head,wing],[np.transpose(wing),body]], format='csr', dtype=datatype)

        # check16(H3upd)

        H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

        self.timed("Creating spin Opt eff. Hamiltonian sparse",2)



        return H3upd

#%% Sparse

    @staticmethod
    def compute_body_block(args):
        (chunk, nspace_spatials, mo_en, nO, sparse_tol, zero_tol, sigma_func, datatype, sqrt) = args

        def check32(arr):
            prod=np.prod(arr.shape)
            res=(prod*4==arr.nbytes)
            if res:
                print("Is 32")
            else:
                print("Is not 32, its ",type(arr))
                print("Size: ",arr.nbytes)
                print("Theory: ", prod*4)
                sys.exit()

        d = lambda a,b: 1 if a==b else 0


        results = []




        prefacA1=datatype(0.5)
        prefacA2=datatype(1.5)
        sqrt2=sqrt(.5)
        sqrt3 = (sqrt(3.0) / 2.0).astype(datatype)


        for leftindex in chunk:
            i, j, l = nspace_spatials[leftindex]
            ei = mo_en[i]
            ej = mo_en[j]
            el = mo_en[l]

            fi = datatype(0) if (i >= nO) else datatype(1)
            fj = datatype(0) if (j >= nO) else datatype(1)
            fl = datatype(0) if (l >= nO) else datatype(1)
            prefac_base = datatype(-((1-fi)*(1-fj)*fl - fi*fj*(1-fl)))
            for rightindex, right in enumerate(nspace_spatials):
                m,o,k = right

                de = (ei - (el - ej)) * d(i,m)*d(j,o)*d(l,k)

                # A1

                s_ij=sqrt2**d(i,j)
                s_mo = sqrt2**d(m,o)

                A1 = s_mo * s_ij * (
                    -d(l,k) * (sigma_func[i,j,o,m] + sigma_func[i,j,m,o])
                    + d(m,j) * (sigma_func[i,k,l,o] - prefacA1 * sigma_func[i,k,o,l])
                    + d(i,o) * (sigma_func[j,k,l,m] - prefacA1 * sigma_func[j,k,m,l])
                    + d(o,j) * (sigma_func[i,k,l,m] - prefacA1 * sigma_func[i,k,m,l])
                    + d(i,m) * (sigma_func[j,k,l,o] - prefacA1 * sigma_func[j,k,o,l])
                )

                # A2
                A2 = (
                    -d(l,k)*(sigma_func[i,j,o,m]-sigma_func[i,j,m,o])
                    -d(m,j)*(sigma_func[i,k,l,o]-prefacA2*sigma_func[i,k,o,l])
                    -d(i,o)*(sigma_func[j,k,l,m]-prefacA2*sigma_func[j,k,m,l])
                    +d(o,j)*(sigma_func[i,k,l,m]-prefacA2*sigma_func[i,k,m,l])
                    +d(i,m)*(sigma_func[j,k,l,o]-prefacA2*sigma_func[i,k,o,l])
                )

                A2 = (
                    -d(l,k) * (sigma_func[i,j,o,m] - sigma_func[i,j,m,o])
                    - d(m,j) * (sigma_func[i,k,l,o] - prefacA2 * sigma_func[i,k,o,l])
                    - d(i,o) * (sigma_func[j,k,l,m] - prefacA2 * sigma_func[j,k,m,l])
                    + d(o,j) * (sigma_func[i,k,l,m] - prefacA2 * sigma_func[i,k,m,l])
                    + d(i,m) * (sigma_func[j,k,l,o] - prefacA2 * sigma_func[j,k,o,l])
                )

                F1 = np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(
                    -d(m,j)*sigma_func[i,k,o,l]
                    +d(i,o)*sigma_func[j,k,m,l]
                    +d(o,j)*sigma_func[i,k,m,l]
                    -d(i,m)*sigma_func[j,k,o,l]
                )

                F1 = s_ij * sqrt3 * (
                    -d(m,j) * sigma_func[i,k,o,l]
                    + d(i,o) * sigma_func[j,k,m,l]
                    + d(o,j) * sigma_func[i,k,m,l]
                    - d(i,m) * sigma_func[j,k,o,l]
                )

                F2 = s_mo * sqrt3 * (
                    d(m,j) * sigma_func[i,k,o,l]
                    - d(i,o) * sigma_func[j,k,m,l]
                    + d(o,j) * sigma_func[i,k,m,l]
                    - d(i,m) * sigma_func[j,k,o,l]
                )



                A = de + prefac_base*A1
                B = prefac_base*F1
                C = prefac_base*F2
                D = de + prefac_base*A2

                if abs(A) > sparse_tol:
                    results.append((2*leftindex, 2*rightindex, A))
                if abs(B) > sparse_tol:
                    results.append((2*leftindex, 2*rightindex+1, B))
                if abs(C) > sparse_tol:
                    results.append((2*leftindex+1, 2*rightindex, C))
                if abs(D) > sparse_tol:
                    results.append((2*leftindex+1, 2*rightindex+1, D))

        return results

    @staticmethod
    def compute_wing_block(args):
        (chunk, nspace_spatials, nBas, mo_en, nO, sparse_tol, zero_tol, sigma_func, datatype, sqrt) = args

        d = lambda a,b: 1 if a==b else 0


        results = []

        sqrt2=sqrt(.5)
        pref4=sqrt(3/2)
        for leftindex in chunk:
            i, j, l = nspace_spatials[leftindex]
            for rightindex,m in enumerate(np.arange(nBas)):

                pref=((sqrt2**d(i,j))*sqrt2).astype(datatype)

                S1 = sigma_func[i, j, l, m]
                S2 = sigma_func[i, j, m, l]


                C3 = pref * (S1 + S2)
                C4 = pref4 * (S1 - S2)

                if abs(C3) > sparse_tol:
                    results.append((2*leftindex,rightindex,C3))
                if abs(C4) > sparse_tol:
                    results.append((2*leftindex+1,rightindex,C4))

        return results

    def spinAdaptedMCDESparseParallel(self,secondBorn=False):

        self.verbose3("Spin transformed MCDE sparse")
        self.verbose3("Second Born? "+str(secondBorn))

        datatype=self.data_type_sparse

        def sqrt(x):
            return np.sqrt(x).astype(datatype)

        #transform spinorbitals to spatial orbitals
        nspace_spatials0=[]
        for entry in self.nspace:
            nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
        #remove duplicates
        seen = set()
        nspace_spatials = []
        for item in nspace_spatials0:
            t = tuple(item)
            if t not in seen:
                seen.add(t)
                nspace_spatials.append(item)



        nspace = np.array(nspace_spatials)   # shape (N,3)

        spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

        self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
        self.verbose4(nspace_spatials)

        sigma=self.eri_mo_gabi.astype(datatype)

        ray=[]
        for i in range(self.nBas):
            ray.append(self.mo_en[i])
        head=lil_matrix(np.diag(ray))

        # create chunks
        n_workers = os.cpu_count()
        n = len(nspace_spatials)
        chunk_size = (n + n_workers - 1) // n_workers  # ceil division

        chunks = [
            list(range(i, min(i + chunk_size, n)))
            for i in range(0, n, chunk_size)
        ]

        tasks = [
            (chunk, nspace_spatials, self.mo_en.astype(datatype), self.nO,
             self.sparse_tol, self.zero_tol, sigma, datatype, self.sqrt)
            for chunk in chunks
        ]

        all_results = []


        with ProcessPoolExecutor() as executor:
            futures = [executor.submit(MCDE.compute_body_block, t) for t in tasks]

            for f in as_completed(futures):
                all_results.extend(f.result())

        body = lil_matrix((len(nspace_spatials)*2, 2*len(nspace_spatials)), dtype=datatype)

        for r, c, v in all_results:
            body[r, c] = v

        tasks = [
            (chunk, nspace_spatials, self.nBas, self.mo_en, self.nO,
             self.sparse_tol, self.zero_tol, sigma, datatype, self.sqrt)
            for chunk in chunks
        ]

        all_results = []

        with ProcessPoolExecutor() as executor:
            futures = [executor.submit(MCDE.compute_wing_block, t) for t in tasks]

            for f in as_completed(futures):
                all_results.extend(f.result())

        wing = lil_matrix((len(nspace_spatials)*2,len(ray)),dtype=datatype)

        for r, c, v in all_results:
            wing[r, c] = v

        H3upd = scipy.sparse.bmat([[head, wing.T],
              [wing, body]], format='csr',dtype=datatype)

        self.timed("Creating spin Opt eff. Hamiltonian sparse",2)

        H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

        return H3upd

    def spinAdaptedMCDESparse(self,secondBorn=False):
        self.verbose3("Spin transformed MCDE sparse")
        self.verbose3("Second Born? "+str(secondBorn))

        datatype=self.data_type_sparse

        #  small number
        def sqrt(x):
            return np.sqrt(x).astype(datatype)

        def check32(arr):
            prod=np.prod(arr.shape)
            res=(prod*4==arr.nbytes)
            if res:
                print("Is 32")
            else:
                print("Is not 32, its ",type(arr))
                print("Size: ",arr.nbytes)
                print("Theory: ", prod*4)
                sys.exit()

        def check16(arr):
            return None
            prod=np.prod(arr.shape)
            res=(prod*2==arr.nbytes)
            if res:
                print("Is 16")
            else:
                print("Is not 16, its ",type(arr))
                print("Size: ",arr.nbytes)
                print("Theory: ", prod*2)
                sys.exit()

        #transform spinorbitals to spatial orbitals
        nspace_spatials0=[]
        for entry in self.nspace:
            nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
        #remove duplicates
        seen = set()
        nspace_spatials = []
        for item in nspace_spatials0:
            t = tuple(item)
            if t not in seen:
                seen.add(t)
                nspace_spatials.append(item)

        nspace = np.array(nspace_spatials)   # shape (N,3)
        spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

        # head
        ray=[]
        for i in range(self.nBas):
            ray.append(self.mo_en[i])
        head=np.diag(ray).astype(datatype)

        # check32(head)

        nBasspace=np.arange(self.nBas)
        mwing = nBasspace[None, :]

        i = nspace[:, 0]
        j = nspace[:, 1]
        l = nspace[:, 2]

        m = nspace[:, 0]
        o = nspace[:, 1]
        k = nspace[:, 2]

        iL = i[:, None]
        jL = j[:, None]
        lL = l[:, None]

        mR = m[None, :]
        oR = o[None, :]
        kR = k[None, :]

        dim = (iL == mR).astype(datatype)
        djo = (jL == oR).astype(datatype)
        dlk = (lL == kR).astype(datatype)

        dmj = (mR == jL).astype(datatype)
        dio = (iL == oR).astype(datatype)
        doj = (oR == jL).astype(datatype)

        ei = self.mo_en[i].astype(datatype)
        ej = self.mo_en[j].astype(datatype)
        el = self.mo_en[l].astype(datatype)

        eiL = ei[:, None]
        ejL = ej[:, None]
        elL = el[:, None]

        check16(dlk)

        de = ((eiL - (elL - ejL)) * dim * djo * dlk).astype(datatype)

        # check32(de)
        #memory expensive!
        N=self.nBas

        sigma=self.eri_mo_gabi.astype(datatype)



        S_ijom = sigma[iL, jL, oR, mR]
        S_ijmo = sigma[iL, jL, mR, oR]
        S_iklo = sigma[iL, kR, lL, oR]
        S_ikol = sigma[iL, kR, oR, lL]
        S_jklm = sigma[jL, kR, lL, mR]
        S_jkml = sigma[jL, kR, mR, lL]
        S_iklm = sigma[iL, kR, lL, mR]
        S_ikml = sigma[iL, kR, mR, lL]
        S_jklo = sigma[jL, kR, lL, oR]
        S_jkol = sigma[jL, kR, oR, lL]



        sqrt2 = sqrt(0.5)
        sqrt3 = (sqrt(3.0) / 2.0).astype(datatype)



        s_mo = np.where(mR != oR, 1.0, sqrt2).astype(datatype)
        s_ij = np.where(iL != jL, 1.0, sqrt2).astype(datatype)

        # check32(s_mo)

        prefacA1=datatype(0.5)
        prefacA2=datatype(1.5)

        A1 = s_mo * s_ij * (
            -dlk * (S_ijom + S_ijmo)
            + dmj * (S_iklo - prefacA1 * S_ikol)
            + dio * (S_jklm - prefacA1 * S_jkml)
            + doj * (S_iklm - prefacA1 * S_ikml)
            + dim * (S_jklo - prefacA1 * S_jkol)
        )
        check16(dmj * (S_iklo - prefacA1 * S_ikol))
        check16(A1)

        A2 = (
            -dlk * (S_ijom - S_ijmo)
            - dmj * (S_iklo - prefacA2 * S_ikol)
            - dio * (S_jklm - prefacA2 * S_jkml)
            + doj * (S_iklm - prefacA2 * S_ikml)
            + dim * (S_jklo - prefacA2 * S_jkol)
        )

        check16(A2)

        F1 = s_ij * sqrt3 * (
            -dmj * S_ikol
            + dio * S_jkml
            + doj * S_ikml
            - dim * S_jkol
        )
        #
        check16(F1)

        F2 = s_mo * sqrt3 * (
            dmj * S_ikol
            - dio * S_jkml
            + doj * S_ikml
            - dim * S_jkol
        )



        fi = (i < self.nO).astype(np.int32)
        fj = (j < self.nO).astype(np.int32)
        fl = (l < self.nO).astype(np.int32)

        fiL = fi[:, None]
        fjL = fj[:, None]
        flL = fl[:, None]

        prefac = (-((1-fiL)*(1-fjL)*flL - fiL*fjL*(1-flL))).astype(datatype)



        A = de + prefac * A1
        B = prefac * F1
        C = prefac * F2
        D = de + prefac * A2


        N = len(nspace)

        body = np.zeros((2*N, 2*N),dtype=datatype)

        body[0::2, 0::2] = A
        body[0::2, 1::2] = B
        body[1::2, 0::2] = C
        body[1::2, 1::2] = D

        #wing
        pref4=sqrt(3/2)
        pref=(np.where(iL==jL,sqrt2,1.0)*sqrt2).astype(datatype)

        S1 = sigma[iL, jL, lL, mwing]
        S2 = sigma[iL, jL, mwing, lL]


        C3 = pref * (S1 + S2)
        C4 = pref4 * (S1 - S2)




        wing = np.zeros((2*len(nspace), self.nBas),dtype=datatype)

        wing[0::2, :] = C3
        wing[1::2, :] = C4


        body[np.abs(body) < self.sparse_tol] = 0.0
        head[np.abs(head) < self.sparse_tol] = 0.0
        wing[np.abs(wing) < self.sparse_tol] = 0.0
        # body_sparse = csr_matrix(body)
        # print(wing.shape)
        # print(body.shape)
        # print(head.shape)


        H3upd=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,body]], format='csr', dtype=datatype)

        # check16(H3upd)

        H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

        self.timed("Creating spin Opt eff. Hamiltonian sparse",2)



        return H3upd



    def spinAdaptedMCDESparseChunks(self,secondBorn=False):
        self.verbose3("Spin transformed MCDE sparse")
        self.verbose3("Second Born? "+str(secondBorn))

        datatype=self.data_type_sparse

        #  small number
        def sqrt(x):
            return np.sqrt(x).astype(datatype)

        def check32(arr):
            prod=np.prod(arr.shape)
            res=(prod*4==arr.nbytes)
            if res:
                print("Is 32")
            else:
                print("Is not 32, its ",type(arr))
                print("Size: ",arr.nbytes)
                print("Theory: ", prod*4)
                sys.exit()

        def check16(arr):
            return None
            prod=np.prod(arr.shape)
            res=(prod*2==arr.nbytes)
            if res:
                print("Is 16")
            else:
                print("Is not 16, its ",type(arr))
                print("Size: ",arr.nbytes)
                print("Theory: ", prod*2)
                sys.exit()

        #transform spinorbitals to spatial orbitals
        nspace_spatials0=[]
        for entry in self.nspace:
            nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
        #remove duplicates
        seen = set()
        nspace_spatials = []
        for item in nspace_spatials0:
            t = tuple(item)
            if t not in seen:
                seen.add(t)
                nspace_spatials.append(item)

        nspaceFull = np.array(nspace_spatials)   # shape (N,3)
        spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

        # head
        ray=[]
        for i in range(self.nBas):
            ray.append(self.mo_en[i])
        head=np.diag(ray).astype(datatype)

        # check32(head)

        nBasspace=np.arange(self.nBas)
        mwing = nBasspace[None, :]

        N = len(nspaceFull)
        chunk_size = max(N//100,2)
        chunk_size = 5000 if chunk_size > 5000 else chunk_size

        nchunks = [
            (i, i + len(nspaceFull[i:i+chunk_size]), nspaceFull[i:i+chunk_size])
            for i in range(0, len(nspaceFull), chunk_size)
        ]

        body = np.zeros((2*N, 2*N),dtype=datatype)

        wing = np.zeros((2*len(nspaceFull), self.nBas),dtype=datatype)

        def speedUpCore(nspaceL,nspaceR):

            i = nspaceL[:, 0]
            j = nspaceL[:, 1]
            l = nspaceL[:, 2]

            m = nspaceR[:, 0]
            o = nspaceR[:, 1]
            k = nspaceR[:, 2]

            iL = i[:, None]
            jL = j[:, None]
            lL = l[:, None]

            mR = m[None, :]
            oR = o[None, :]
            kR = k[None, :]

            dim = (iL == mR).astype(datatype)
            djo = (jL == oR).astype(datatype)
            dlk = (lL == kR).astype(datatype)

            dmj = (mR == jL).astype(datatype)
            dio = (iL == oR).astype(datatype)
            doj = (oR == jL).astype(datatype)

            ei = self.mo_en[i].astype(datatype)
            ej = self.mo_en[j].astype(datatype)
            el = self.mo_en[l].astype(datatype)

            eiL = ei[:, None]
            ejL = ej[:, None]
            elL = el[:, None]

            # check16(dlk)

            de = ((eiL - (elL - ejL)) * dim * djo * dlk).astype(datatype)

            # check32(de)
            #memory expensive!

            sigma=self.eri_mo_gabi.astype(datatype)


            S_ijom = sigma[iL, jL, oR, mR]
            S_ijmo = sigma[iL, jL, mR, oR]
            S_iklo = sigma[iL, kR, lL, oR]
            S_ikol = sigma[iL, kR, oR, lL]
            S_jklm = sigma[jL, kR, lL, mR]
            S_jkml = sigma[jL, kR, mR, lL]
            S_iklm = sigma[iL, kR, lL, mR]
            S_ikml = sigma[iL, kR, mR, lL]
            S_jklo = sigma[jL, kR, lL, oR]
            S_jkol = sigma[jL, kR, oR, lL]



            sqrt2 = sqrt(0.5)
            sqrt3 = (sqrt(3.0) / 2.0).astype(datatype)



            s_mo = np.where(mR != oR, 1.0, sqrt2).astype(datatype)
            s_ij = np.where(iL != jL, 1.0, sqrt2).astype(datatype)

            # check32(s_mo)

            prefacA1=datatype(0.5)
            prefacA2=datatype(1.5)

            A1 = s_mo * s_ij * (
                -dlk * (S_ijom + S_ijmo)
                + dmj * (S_iklo - prefacA1 * S_ikol)
                + dio * (S_jklm - prefacA1 * S_jkml)
                + doj * (S_iklm - prefacA1 * S_ikml)
                + dim * (S_jklo - prefacA1 * S_jkol)
            )
            # check16(dmj * (S_iklo - prefacA1 * S_ikol))
            # check16(A1)

            A2 = (
                -dlk * (S_ijom - S_ijmo)
                - dmj * (S_iklo - prefacA2 * S_ikol)
                - dio * (S_jklm - prefacA2 * S_jkml)
                + doj * (S_iklm - prefacA2 * S_ikml)
                + dim * (S_jklo - prefacA2 * S_jkol)
            )

            # check16(A2)

            F1 = s_ij * sqrt3 * (
                -dmj * S_ikol
                + dio * S_jkml
                + doj * S_ikml
                - dim * S_jkol
            )
            #
            # check16(F1)

            F2 = s_mo * sqrt3 * (
                dmj * S_ikol
                - dio * S_jkml
                + doj * S_ikml
                - dim * S_jkol
            )

            fi = (i < self.nO).astype(np.int32)
            fj = (j < self.nO).astype(np.int32)
            fl = (l < self.nO).astype(np.int32)

            fiL = fi[:, None]
            fjL = fj[:, None]
            flL = fl[:, None]

            prefac = (-((1-fiL)*(1-fjL)*flL - fiL*fjL*(1-flL))).astype(datatype)

            A = de + prefac * A1
            B = prefac * F1
            C = prefac * F2
            D = de + prefac * A2

            pref4=sqrt(3/2)
            pref=(np.where(iL==jL,sqrt2,1.0)*sqrt2).astype(datatype)

            S1 = sigma[iL, jL, lL, mwing]
            S2 = sigma[iL, jL, mwing, lL]


            C3 = pref * (S1 + S2)
            C4 = pref4 * (S1 - S2)



            return A,B,C,D,C3,C4



        for tchunkL in nchunks:
            for tchunkR in nchunks:

                (indexL0, indexL1, chunkL) = tchunkL
                (indexR0, indexR1, chunkR) = tchunkR

                # indexL0=indexL
                # indexL1=indexL+chunk_size
                # indexR0=indexR
                # indexR1=indexR+chunk_size

                A,B,C,D,C3,C4=speedUpCore(chunkL,chunkR)

                r0 = 2 * indexL0
                r1 = 2 * indexL1
                c0 = 2 * indexR0
                c1 = 2 * indexR1

                # even-even (A)
                body[r0:r1:2, c0:c1:2] = A

                # even-odd (B)
                body[r0:r1:2, c0+1:c1:2] = B

                # odd-even (C)
                body[r0+1:r1:2, c0:c1:2] = C

                # odd-odd (D)
                body[r0+1:r1:2, c0+1:c1:2] = D

                wing[r0:r1:2, :] = C3
                wing[r0+1:r1:2, :] = C4     

        body[np.abs(body) < self.sparse_tol] = 0.0
        head[np.abs(head) < self.sparse_tol] = 0.0
        wing[np.abs(wing) < self.sparse_tol] = 0.0
        # body_sparse = csr_matrix(body)
        # print(wing.shape)
        # print(body.shape)
        # print(head.shape)


        H3upd=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,body]], format='csr', dtype=datatype)

        # check16(H3upd)

        H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

        self.timed("Creating spin Opt eff. Hamiltonian sparse",2)



        return H3upd



    def spinAdaptedMCDESparseOrig(self,secondBorn=False):
        """
        Construct the spin-adapted sparse MCDE effective Hamiltonian.

        This method transforms the spin-orbital three-particle basis into a
        spin-adapted spatial-orbital basis and constructs the corresponding
        MCDE effective Hamiltonian in sparse matrix format. The resulting matrix
        contains the one-particle sector, the spin-adapted three-particle sector,
        and the coupling between them.

        The spin-adapted basis is generated by collapsing spin-orbital indices
        onto spatial-orbital indices and removing duplicate configurations.
        For each spatial configuration, singlet-coupled and triplet-coupled
        three-particle states are constructed, yielding two spin-adapted states
        per spatial basis function.

        The effective Hamiltonian is assembled in block form,

        \[
        H_{\mathrm{MCDE}}
        =
        \\begin{pmatrix}
        H_{1p} & V^\dagger \\\\
        V & H_{3p}
        \\end{pmatrix}
        \]

        where $H_{1p}$ is the one-particle block, $H_{3p}$ is the
        spin-adapted three-particle block, and $V$ contains the coupling
        between the one- and three-particle sectors.

        Matrix elements smaller than `self.sparse_tol` are omitted during
        construction. After assembly, elements below `self.zero_tol` are
        removed and isolated diagonal states may optionally be eliminated using
        `self.AuxillaryFunctions.remove_isolated_diagonals_sparse`.

        Parameters:
            secondBorn : 
                Flag indicating whether the Second-Born approximation is used.
                This parameter is currently only employed for logging and consistency
                with other MCDE construction routines. Default is `False`. (bool, optional)

        Returns:
            matrix:
                Spin-adapted MCDE effective Hamiltonian in sparse CSR format. (scipy.sparse.csr_matrix)

        Notes:
            The size of the resulting Hamiltonian is

            $$
            N_{\mathrm{eff}}
            =
            N_{\mathrm{1p}}
            + 2 N_{\mathrm{3p}},
            $$

            where $N_{\mathrm{1p}}$ is the number of one-particle basis
            functions and $N_{\mathrm{3p}}$ is the number of unique spatial
            three-particle configurations.

            The factor of two arises from the two spin-adapted coupling channels
            associated with each spatial three-particle configuration.

            The method updates the internal attribute
            `self.nspace_spatials_MCDE` to reflect the reduced spin-adapted basis
            after any pruning operations.

        See Also:
            -spinAdaptedMCDE :
            Dense spin-adapted MCDE Hamiltonian construction.

            -spinAdaptedMCDESparse :
            Very fast, but memory expensive dense spin-adapted MCDE implementation.

            -spinAdaptedMCDESparseChunks :
            A speed and memory balanced implementation of the dense spin-adapted MCDE implementation.

            -spinAdaptedMCDESparseParallel :
            Parallelized verson of dense spin-adapted MCDE implementation.

            -spinAdaptedMCDEwithWSparse :
            like spinAdaptedMCDESparseOrig, but with the exchange V switched with W.
        """


        self.verbose3("Spin transformed MCDE sparse")
        self.verbose3("Second Born? "+str(secondBorn))

        datatype=self.data_type_sparse

        def d(a,b):
            return 1 if a==b else 0


        #transform spinorbitals to spatial orbitals
        nspace_spatials0=[]
        for entry in self.nspace:
            nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
        #remove duplicates
        seen = set()
        nspace_spatials = []
        for item in nspace_spatials0:
            t = tuple(item)
            if t not in seen:
                seen.add(t)
                nspace_spatials.append(item)

        spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

        self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
        self.verbose4(nspace_spatials)
        ray=[]
        for i in range(self.nBas):
            ray.append(self.mo_en[i])
        head=np.diag(ray)

        #create wing

        # wing=np.zeros((len(nspace_spatials)*2,len(ray)))
        wing=lil_matrix((len(nspace_spatials)*2,len(ray)),dtype=datatype)

        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left
            for rightindex,m in enumerate(np.arange(self.nBas)):
                C3=np.sqrt(.5)**(d(i,j))*np.sqrt(.5)*(self.sigma_mo_gabi(i,j,l,m)+self.sigma_mo_gabi(i,j,m,l))
                C4=np.sqrt(3/2)*(self.sigma_mo_gabi(i,j,l,m)-self.sigma_mo_gabi(i,j,m,l))

                wing[2*leftindex,rightindex]=C3
                wing[2*leftindex+1,rightindex]=C4

        #create body matrix

        if self.mcde:
            # body=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
            body=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
            # bodyHF=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
            for leftindex,left in enumerate(nspace_spatials):
                [i,j,l]=left

                for rightindex,right in enumerate(nspace_spatials):
                    [m,o,k]=right


                    A1=np.sqrt(.5)**(d(m,o))*np.sqrt(.5)**(d(i,j))*(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)+self.sigma_mo_gabi(i,j,m,o))
                                                                  +d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-.5*self.sigma_mo_gabi(i,k,o,l))
                                                                  +d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-.5*self.sigma_mo_gabi(j,k,m,l))
                                                                  +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-.5*self.sigma_mo_gabi(i,k,m,l))
                                                                  +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-.5*self.sigma_mo_gabi(j,k,o,l)))
                    A2=(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)-self.sigma_mo_gabi(i,j,m,o))
                                                                  -d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-1.5*self.sigma_mo_gabi(i,k,o,l))
                                                                  -d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-1.5*self.sigma_mo_gabi(j,k,m,l))
                                                                  +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-1.5*self.sigma_mo_gabi(i,k,m,l))
                                                                  +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-1.5*self.sigma_mo_gabi(j,k,o,l)))
                    F1=np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(-d(m,j)*self.sigma_mo_gabi(i,k,o,l)+d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                          +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                          -d(i,m)*self.sigma_mo_gabi(j,k,o,l))
                    F2=np.sqrt(.5)**(d(m,o))*(np.sqrt(3)/2)*(d(m,j)*self.sigma_mo_gabi(i,k,o,l)-d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                          +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                          -d(i,m)*self.sigma_mo_gabi(j,k,o,l))


                    fi = 0 if (i >= self.nO) else 1
                    fj = 0 if (j >= self.nO) else 1
                    fl = 0 if (l >= self.nO) else 1
                    prefac=-((1-fi)*(1-fj)*fl-fi*fj*(1-fl))

                    ei=self.mo_en[i]+self.virtualShift(i)
                    ej=self.mo_en[j]+self.virtualShift(j)
                    el=self.mo_en[l]+self.virtualShift(l)
                    de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)

                    A=de+prefac*A1
                    B=prefac*F1
                    C=prefac*F2
                    D=de+prefac*A2

                    if abs(A)>self.sparse_tol:
                        body[2*leftindex,2*rightindex]=A
                    if abs(B)>self.sparse_tol:
                        body[2*leftindex,2*rightindex+1]=B
                    if abs(C)>self.sparse_tol:
                        body[2*leftindex+1,2*rightindex]=C
                    if abs(D)>self.sparse_tol:
                        body[2*leftindex+1,2*rightindex+1]=D

                    # body[2*leftindex,2*rightindex]=de+prefac*A1
                    # body[2*leftindex,2*rightindex+1]=prefac*F1
                    # body[2*leftindex+1,2*rightindex]=prefac*F2
                    # body[2*leftindex+1,2*rightindex+1]=de+prefac*A2

                    # bodyHF[2*leftindex,2*rightindex]=de
                    # bodyHF[2*leftindex+1,2*rightindex+1]=de
                    # H3upd=np.block([[head,np.transpose(wing)],[wing,body]])
            H3upd = scipy.sparse.bmat([[head, wing.T],
                  [wing, body]], format='csr',dtype=datatype)
            # H3upd[H3upd.abs() < self.zero_tol] = 0
            # H3upd.eliminate_zeros()
            mask = np.abs(H3upd.data) < self.zero_tol
            H3upd.data[mask] = 0
            # H3upd=np.where(np.abs(H3upd) < self.zero_tol, 0.0, H3upd)
            H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

        if secondBorn:
            # bodySB=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
            bodySB=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
            for leftindex,left in enumerate(nspace_spatials):
                [i,j,l]=left

                for rightindex,right in enumerate(nspace_spatials):
                    [m,o,k]=right


                    ei=self.mo_en[i]+self.virtualShift(i)
                    ej=self.mo_en[j]+self.virtualShift(j)
                    el=self.mo_en[l]+self.virtualShift(l)
                    de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


                    bodySB[2*leftindex,2*rightindex]=de
                    bodySB[2*leftindex,2*rightindex+1]=0
                    bodySB[2*leftindex+1,2*rightindex]=0
                    bodySB[2*leftindex+1,2*rightindex+1]=de
            # H3SB=np.block([[head,np.transpose(wing)],[wing,bodySB]])
            H3SB=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,bodySB]], format='csr', dtype=datatype)
            mask = np.abs(H3SB.data) < self.zero_tol
            H3SB.data[mask] = 0
            # H3SB=np.where(np.abs(H3SB) < self.zero_tol, 0.0, H3SB)
            # H3SB=H3SB.tocsr()
            H3SB,self.nspace_spatials_SB=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3SB,spaceObj,self.remove_single_values)







        self.timed("Creating spin Opt eff. Hamiltonian sparse",2)

        if secondBorn and self.mcde:
            return H3upd,H3SB
        if secondBorn:
            return H3SB
        if self.mcde:
            return H3upd

#%% spin adapted effective Hamiltonian with W replacing V_exchange
    def spinAdaptedMCDEwithWSparse(self,secondBorn=False):
        """
        Construct the spin-adapted sparse MCDE effective Hamiltonian with the 
        direct-$eh$ and direct- and exchange-$pp$ two electron integrals $V$ replaced
        by $W$ defined in `self.eri_mo_gabi_W`.

        The method works analogously to `self.spinAdaptedMCDESparseOrig`.

        Parameters:
            secondBorn : 
                Flag indicating whether the Second-Born approximation is used.
                This parameter is currently only employed for logging and consistency
                with other MCDE construction routines. Default is `False`. (bool, optional)

        Returns:
            matrix:
                Spin-adapted MCDE effective Hamiltonian in sparse CSR format. (scipy.sparse.csr_matrix)



        See Also:
            -spinAdaptedMCDE :
            Dense spin-adapted MCDE Hamiltonian construction.

            -spinAdaptedMCDESparse :
            Very fast, but memory expensive dense spin-adapted MCDE implementation.

            -spinAdaptedMCDESparseChunks :
            A speed and memory balanced implementation of the dense spin-adapted MCDE implementation.

            -spinAdaptedMCDESparseOrig :
            Slow sparse spin-adapted MCDE Hamiltonian construction.

            -spinAdaptedMCDESparseParallel :
            Parallelized verson of dense spin-adapted MCDE implementation.
        """
        # is W defined?
        if self.eri_mo_gabi_W is None:
            self.verbose1("No W defined, proceed with unscreened V.")
            return self.spinAdaptedMCDESparse(secondBorn)

        self.verbose3("Spin transformed MCDE sparse")
        self.verbose3("Second Born? "+str(secondBorn))

        datatype=self.data_type_sparse

        def d(a,b):
            return 1 if a==b else 0


        #transform spinorbitals to spatial orbitals
        nspace_spatials0=[]
        for entry in self.nspace:
            nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
        #remove duplicates
        seen = set()
        nspace_spatials = []
        for item in nspace_spatials0:
            t = tuple(item)
            if t not in seen:
                seen.add(t)
                nspace_spatials.append(item)

        spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

        self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
        self.verbose4(nspace_spatials)
        ray=[]
        for i in range(self.nBas):
            ray.append(self.mo_en[i])
        head=np.diag(ray)

        #create wing

        # wing=np.zeros((len(nspace_spatials)*2,len(ray)))
        wing=lil_matrix((len(nspace_spatials)*2,len(ray)),dtype=datatype)

        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left
            for rightindex,m in enumerate(np.arange(self.nBas)):
                C3=np.sqrt(.5)**(d(i,j))*np.sqrt(.5)*(self.sigma_mo_gabi(i,j,l,m)+self.sigma_mo_gabi_W(i,j,m,l))
                C4=np.sqrt(3/2)*(self.sigma_mo_gabi(i,j,l,m)-self.sigma_mo_gabi_W(i,j,m,l))

                wing[2*leftindex,rightindex]=C3
                wing[2*leftindex+1,rightindex]=C4

        #create body matrix

        if self.mcde:
            # body=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
            body=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
            # bodyHF=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
            for leftindex,left in enumerate(nspace_spatials):
                [i,j,l]=left

                for rightindex,right in enumerate(nspace_spatials):
                    [m,o,k]=right


                    A1=np.sqrt(.5)**(d(m,o))*np.sqrt(.5)**(d(i,j))*(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)+self.sigma_mo_gabi_W(i,j,m,o))
                                                                  +d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-.5*self.sigma_mo_gabi_W(i,k,o,l))
                                                                  +d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-.5*self.sigma_mo_gabi_W(j,k,m,l))
                                                                  +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-.5*self.sigma_mo_gabi_W(i,k,m,l))
                                                                  +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-.5*self.sigma_mo_gabi_W(j,k,o,l)))
                    A2=(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)-self.sigma_mo_gabi_W(i,j,m,o))
                                                                  -d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-1.5*self.sigma_mo_gabi_W(i,k,o,l))
                                                                  -d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-1.5*self.sigma_mo_gabi_W(j,k,m,l))
                                                                  +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-1.5*self.sigma_mo_gabi_W(i,k,m,l))
                                                                  +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-1.5*self.sigma_mo_gabi_W(j,k,o,l)))
                    F1=np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(-d(m,j)*self.sigma_mo_gabi_W(i,k,o,l)+d(i,o)*self.sigma_mo_gabi_W(j,k,m,l)
                                                          +d(o,j)*self.sigma_mo_gabi_W(i,k,m,l)
                                                          -d(i,m)*self.sigma_mo_gabi_W(j,k,o,l))
                    F2=np.sqrt(.5)**(d(m,o))*(np.sqrt(3)/2)*(d(m,j)*self.sigma_mo_gabi_W(i,k,o,l)-d(i,o)*self.sigma_mo_gabi_W(j,k,m,l)
                                                          +d(o,j)*self.sigma_mo_gabi_W(i,k,m,l)
                                                          -d(i,m)*self.sigma_mo_gabi_W(j,k,o,l))


                    fi = 0 if (i >= self.nO) else 1
                    fj = 0 if (j >= self.nO) else 1
                    fl = 0 if (l >= self.nO) else 1
                    prefac=-((1-fi)*(1-fj)*fl-fi*fj*(1-fl))

                    ei=self.mo_en[i]+self.virtualShift(i)
                    ej=self.mo_en[j]+self.virtualShift(j)
                    el=self.mo_en[l]+self.virtualShift(l)
                    de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)

                    A=de+prefac*A1
                    B=prefac*F1
                    C=prefac*F2
                    D=de+prefac*A2

                    if abs(A)>self.sparse_tol:
                        body[2*leftindex,2*rightindex]=A
                    if abs(B)>self.sparse_tol:
                        body[2*leftindex,2*rightindex+1]=B
                    if abs(C)>self.sparse_tol:
                        body[2*leftindex+1,2*rightindex]=C
                    if abs(D)>self.sparse_tol:
                        body[2*leftindex+1,2*rightindex+1]=D

                    # body[2*leftindex,2*rightindex]=de+prefac*A1
                    # body[2*leftindex,2*rightindex+1]=prefac*F1
                    # body[2*leftindex+1,2*rightindex]=prefac*F2
                    # body[2*leftindex+1,2*rightindex+1]=de+prefac*A2

                    # bodyHF[2*leftindex,2*rightindex]=de
                    # bodyHF[2*leftindex+1,2*rightindex+1]=de
                    # H3upd=np.block([[head,np.transpose(wing)],[wing,body]])
            H3upd = scipy.sparse.bmat([[head, wing.T],
                  [wing, body]], format='csr',dtype=datatype)
            # H3upd[H3upd.abs() < self.zero_tol] = 0
            # H3upd.eliminate_zeros()
            mask = np.abs(H3upd.data) < self.zero_tol
            H3upd.data[mask] = 0
            # H3upd=np.where(np.abs(H3upd) < self.zero_tol, 0.0, H3upd)
            H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

        if secondBorn:
            # bodySB=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
            bodySB=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
            for leftindex,left in enumerate(nspace_spatials):
                [i,j,l]=left

                for rightindex,right in enumerate(nspace_spatials):
                    [m,o,k]=right


                    ei=self.mo_en[i]+self.virtualShift(i)
                    ej=self.mo_en[j]+self.virtualShift(j)
                    el=self.mo_en[l]+self.virtualShift(l)
                    de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


                    bodySB[2*leftindex,2*rightindex]=de
                    bodySB[2*leftindex,2*rightindex+1]=0
                    bodySB[2*leftindex+1,2*rightindex]=0
                    bodySB[2*leftindex+1,2*rightindex+1]=de
            # H3SB=np.block([[head,np.transpose(wing)],[wing,bodySB]])
            H3SB=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,bodySB]], format='csr', dtype=datatype)
            mask = np.abs(H3SB.data) < self.zero_tol
            H3SB.data[mask] = 0
            # H3SB=np.where(np.abs(H3SB) < self.zero_tol, 0.0, H3SB)
            # H3SB=H3SB.tocsr()
            H3SB,self.nspace_spatials_SB=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3SB,spaceObj,self.remove_single_values)







        self.timed("Creating spin Opt eff. Hamiltonian sparse",2)

        if secondBorn and self.mcde:
            return H3upd,H3SB
        if secondBorn:
            return H3SB
        if self.mcde:
            return H3upd

#%% How to diagonalize the effective Hamiltonian

    def exactDiagonalization(self,matrix):
        """
        Compute the exact diagonalization of a `numpy.array` effective Hamiltonian `matrix`.
        Returns eigenvalues and eigenvectors.

        Parameters:
            matrix : effective Hamiltonian as a numpy.array (shape: ($\lambda$,$\lambda$))


        Returns:
            evals       : sorted eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$))
            evecs       : sorted column-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
        """
        evals,evecs=self.AuxillaryFunctions.eig(matrix)

        self.verbose4("Eigenvalues for H effective")
        if self.verbose>=4:
            idx = np.argsort(evals)  # use -eigvals for descending
            eigvals_sorted = evals[idx]
            # eigvecs_sorted = evecs[:, idx]
            for ii in range(len(evals)):
                self.verbose4('%4d      %.5f'%(ii,eigvals_sorted[ii]))

        return evals,evecs

    def exactDiagonalizationSparse(self,matrix):
        """
        Compute the exact diagonalization of a `scipy.sparse` effective Hamiltonian `matrix`.
        Returns eigenvalues and eigenvectors.
        If `self.reduce_evecs_to_1body`, the three-particle part of the eigenvectors is discarded. It only impacts the memory usage.

        Parameters:
            matrix : effective Hamiltonian as a scipy.sparse csr object (shape: ($\lambda$,$\lambda$))


        Returns:
            evals       : sorted eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$))
            evecs       : sorted column-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
        """
        vecstocalc=min(self.do_auto_sparse_basis_threshold,self.estimate_spin_opt_ham)
        self.verbose3(f"Calculating {vecstocalc} eigenvectors")
        if vecstocalc>=self.estimate_spin_opt_ham:
            evals,evecs=self.AuxillaryFunctions.eig(matrix.toarray())
        else:
            evals,evecs=scipy.sparse.linalg.eigsh(matrix,k=vecstocalc, which='LM')

        if self.reduce_evecs_to_1body:
            evecs=evecs[:self.nBas]
        self.verbose4("Eigenvalues for H effective")
        if self.verbose>=4:
            idx = np.argsort(evals)  # use -eigvals for descending
            eigvals_sorted = evals[idx]
            # eigvecs_sorted = evecs[:, idx]
            for ii in range(len(evals)):
                self.verbose4('%4d      %.5f'%(ii,eigvals_sorted[ii]))
        self.timed("Calculation of eigenvectors", 3)
        return evals,evecs

    def LanczosAlgorithm(self,matrix,nbas):
        """
        Compute the Haydock-Lanczos algorithm for an effective Hamiltonian `matrix` up to `self.iterations`.
        The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
        0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
        From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
        with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
        than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.
        For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors $\psi_0,...,\psi_{i+1}$ is performed

        Parameters:
            matrix : effective Hamiltonian as a numpy array (shape: (M,M))
            nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
            Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

        Returns:
            a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
            b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
        """
        self.verbose1("Starting Lanczos Algorithm")

        acoeff = np.zeros(self.iterations)
        bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
        lanczosBasis = np.zeros((self.iterations, len(matrix)))

        # Start vector
        s0 = np.zeros(len(matrix))
        s0[:nbas] = 1
        s0 /= np.linalg.norm(s0)
        lanczosBasis[0] = s0

        # First step
        w = matrix @ s0
        acoeff[0] = np.dot(s0, w)
        w -= acoeff[0] * s0
        bcoeff[1] = np.linalg.norm(w)
        lanczosBasis[1] = w / bcoeff[1]

        # Main loop
        for i in range(1, self.iterations - 1):
            v_prev = lanczosBasis[i - 1]
            v_curr = lanczosBasis[i]
            w = matrix @ v_curr
            acoeff[i] = np.dot(v_curr, w)
            w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

            # Optional: reorthogonalize w to all previous basis vectors
            # for j in range(i):
            #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

            # FULL REORTHOGONALIZATION
            for j in range(i + 1):
                w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

            bcoeff[i + 1] = np.linalg.norm(w)
            if bcoeff[i + 1] < self.lanczos_tol:
                self.verbose2("Breakdown at step "+ str(i))
                break
            lanczosBasis[i + 1] = w / bcoeff[i + 1]

        acoeff[self.iterations - 1] = lanczosBasis[self.iterations - 1] @ matrix @ lanczosBasis[self.iterations - 1].T

        self.timed("Lanczos Algorithm", 2)

        return acoeff,bcoeff

    def LanczosAlgorithmSparse0(self,matrix,nbas):
        """
        Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian `matrix` up to `self.iterations`.
        The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
        0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
        From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
        with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
        than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.
        For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors $\psi_0,...,\psi_{i+1}$ is performed

        Parameters:
            matrix : effective Hamiltonian as a `scipy.sparse` csr matrix (shape: (M,M))
            nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
            Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

        Returns:
            a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
            b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
        """
        self.verbose1("Starting Lanczos Algorithm")

        matrix_length=matrix.shape[0]

        acoeff = np.zeros(self.iterations)
        bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
        lanczosBasis = np.zeros((self.iterations, matrix_length))

        # Start vector
        s0 = np.zeros(matrix_length)
        s0[:nbas] = 1
        s0 /= np.linalg.norm(s0)
        lanczosBasis[0] = s0

        # First step
        w = matrix @ s0
        acoeff[0] = np.dot(s0, w)
        w -= acoeff[0] * s0
        bcoeff[1] = np.linalg.norm(w)
        lanczosBasis[1] = w / bcoeff[1]

        # Main loop
        for i in range(1, self.iterations - 1):
            v_prev = lanczosBasis[i - 1]
            v_curr = lanczosBasis[i]
            w = matrix @ v_curr
            acoeff[i] = np.dot(v_curr, w)
            w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

            # Optional: reorthogonalize w to all previous basis vectors
            # for j in range(i):
            #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

            # FULL REORTHOGONALIZATION
            for j in range(i + 1):
                w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

            bcoeff[i + 1] = np.linalg.norm(w)
            if bcoeff[i + 1] < self.lanczos_tol:
                self.verbose2("Breakdown at step "+ str(i))
                break
            lanczosBasis[i + 1] = w / bcoeff[i + 1]

        self.w=lanczosBasis

        acoeff[self.iterations - 1] = lanczosBasis[self.iterations - 1] @ matrix @ lanczosBasis[self.iterations - 1].T

        self.timed("Lanczos Algorithm", 2)

        return acoeff,bcoeff



    def LanczosAlgorithmSparse(self,matrix,nbas,returnLanczosVectors=False):
        """
        Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian `matrix` up to `self.iterations`.
        The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
        0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
        From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
        with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
        than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.
        For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors $\psi_0,...,\psi_{i+1}$ is performed

        Parameters:
            matrix : effective Hamiltonian as a `scipy.sparse` csr matrix (shape: (M,M))
            nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
            Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)
            returnLanczosVectors : True if you want to return the Lanczos vectors of the Krylov Basis. (Bool)

        Returns:
            a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
            b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
            lv (optional) : if returnLanczosVectors is True, returns an array of row Lanczos vectors (length (n,M))
        """
        self.verbose1("Starting Lanczos Algorithm")

        matrix_length=matrix.shape[0]

        acoeff = np.zeros(self.iterations)
        bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
        lanczosBasis = np.zeros((self.iterations, matrix_length))

        # Start vector
        s0 = np.zeros(matrix_length)
        s0[:nbas] = 1
        s0 /= np.linalg.norm(s0)
        lanczosBasis[0] = s0

        # First step
        w = matrix @ s0
        acoeff[0] = np.dot(s0, w)
        w -= acoeff[0] * s0
        bcoeff[1] = np.linalg.norm(w)
        lanczosBasis[1] = w / bcoeff[1]

        # Main loop
        final_index = self.iterations - 1
        for i in range(1, self.iterations - 1):
            v_prev = lanczosBasis[i - 1]
            v_curr = lanczosBasis[i]
            w = matrix @ v_curr
            acoeff[i] = np.dot(v_curr, w)
            w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

            # Optional: reorthogonalize w to all previous basis vectors
            # for j in range(i):
            #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

            # FULL REORTHOGONALIZATION
            for j in range(i + 1):
                w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

            b = np.linalg.norm(w)
            # bcoeff[i + 1] = np.linalg.norm(w)
            if b < self.lanczos_tol:
                self.verbose2("Breakdown at step "+ str(i))
                final_index=i
                break
            lanczosBasis[i + 1] = w / b
            bcoeff[i+1]=b
            final_index = i+1
        self.w=lanczosBasis

        acoeff[final_index] = lanczosBasis[final_index] @ matrix @ lanczosBasis[final_index].T


        self.timed("Lanczos Algorithm", 2)

        if returnLanczosVectors:
            return acoeff[:final_index+1], bcoeff[:final_index+1], lanczosBasis 
        return acoeff[:final_index+1], bcoeff[:final_index+1]

    def LanczosAlgorithmSparseNoOrth(self,matrix,nbas,returnLanczosVectors=False):
        """
        Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian up to `self.iterations`.
        No Gram-Schmidt reorthogonalization is applied.
        The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
        0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
        From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
        with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
        than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.

        Parameters:
            matrix : effective Hamiltonian as a `scipy.sparse` csr matrix (shape: (M,M))
            nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
            Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)
            returnLanczosVectors : True if you want to return the Lanczos vectors of the Krylov Basis. (Bool)

        Returns:
            a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
            b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
            lv (optional) : if returnLanczosVectors is True, returns an array of row Lanczos vectors (length (n,M))

        Notes:
            No orthogonalization is performed.
        """
        self.verbose1("Starting Lanczos Algorithm")

        matrix_length=matrix.shape[0]

        acoeff = np.zeros(self.iterations)
        bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
        lanczosBasis = np.zeros((self.iterations, matrix_length))

        # Start vector
        s0 = np.zeros(matrix_length)
        s0[:nbas] = 1
        s0 /= np.linalg.norm(s0)
        lanczosBasis[0] = s0

        # First step
        w = matrix @ s0
        acoeff[0] = np.dot(s0, w)
        w -= acoeff[0] * s0
        bcoeff[1] = np.linalg.norm(w)
        lanczosBasis[1] = w / bcoeff[1]

        # Main loop
        final_index = self.iterations - 1
        for i in range(1, self.iterations - 1):
            v_prev = lanczosBasis[i - 1]
            v_curr = lanczosBasis[i]
            w = matrix @ v_curr
            acoeff[i] = np.dot(v_curr, w)
            w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

            # Optional: reorthogonalize w to all previous basis vectors
            # for j in range(i):
            #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]



            b = np.linalg.norm(w)
            # bcoeff[i + 1] = np.linalg.norm(w)
            if b < self.lanczos_tol:
                self.verbose2("Breakdown at step "+ str(i))
                final_index=i
                break
            lanczosBasis[i + 1] = w / b
            bcoeff[i+1]=b
            final_index = i+1
        self.w=lanczosBasis

        acoeff[final_index] = lanczosBasis[final_index] @ matrix @ lanczosBasis[final_index].T


        self.timed("Lanczos Algorithm", 2)

        if returnLanczosVectors:
            return acoeff[:final_index+1], bcoeff[:final_index+1], lanczosBasis 
        return acoeff[:final_index+1], bcoeff[:final_index+1]
#%% plotting
    @staticmethod
    def AA_vectorized(omega_array, eta, eig31, evec31, nBas):
        """
        Generates the spectrum $A(\omega)$ for the one-particle space.
        The spectrum is evaluated over the three-particle space according to
        $$
        A^{\text{1p}}(\omega)=\frac{1}{\pi}\sum_{i} |\im G^{\text{1p}}_{3,(i;i)}(\omega)|,
        $$
        with 

        $$
        G^{\text{1p}}_{3,(i;m)}(\omega)& =  \sum_{\lambda}\frac{A^{i}_{\lambda}A^{*m}_{\lambda}}{\omega-E_{\lambda}}.
        $$
        The $A^{i}_{\lambda},A^{*m}_{\lambda}$ are the one-particle part of the effective Hamiltonian's $\lambda$th eigenvectors. $\omega_{\lambda}$
        is the $\lambda$th eigenenergy.

        Parameters:
            omega_array : array of float energies over which the spectrum is calculated (shape: (M,))
            eta : Lorentzian broadening (float)
            eig31       : eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$))
            evec31       : row-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
            nBas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
            Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

        Returns:
            A(omega_array) : array of real values representing the one-particle spectrum over the energy range omega_array  (shape: (M,))
        """
        print("Calculating the spectrum")
        start_time=time.time()
        evec_squared = evec31[:nBas, :] * evec31[:nBas, :].conj()  # shape (nBas, nEig)

        denom = eig31[:, np.newaxis].real  # shape (nEig, 1)

        omega_eta = omega_array[np.newaxis, :] - denom + 1j*eta # shape (nEig, N_omega)

        weights = np.sum(evec_squared, axis=0)  # shape (nEig,)


        response = np.sum(weights[:, np.newaxis] / omega_eta, axis=0)  # shape (N_omega,)

        amplitudes=-1 / np.pi * np.imag(response)
        result = np.column_stack((omega_array.flatten(), amplitudes))
        end_time=time.time()
        elapsed=end_time-start_time
        print(f"Calculating spectrum took {elapsed:.2f} seconds")
        return result

    @staticmethod
    def AA_Lanczos(omega_array,eta, a, b):
        """
        Generates the spectrum $A(\omega)$ for the one-particle space for Lanczos parameters.
        Evaluation of the continued fraction of the Lanczos tridiagonal matrix elements over an energy range omega_array.
        Returns a spectrum $A(z)$ as an array.
        $z$ represents $\omega +i\eta$, with $\eta$ the Lorentzian broadening, and $\omega$ the energies.
        The spectrum formula used is:
        $$
        A(z) = -\pi \, \mathrm{Im}[ z - a_0 - \cfrac{b_1^2}{z - a_1 - \cfrac{b_2^2}{z - a_2 - \cdots}} ]^{-1}
        $$

        Parameters:
            omega_array : array of float energies over which the spectrum is calculated (shape: (M,))
            eta : Lorentzian broadening (float)
            a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
            b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. The first term b1 
            is automatically discarded (length n)

        Returns:
            A(omega_array) : array of real values representing the spectrum over the energy range omega_array  (shape: (M,))
        """
        b=b[1:]
        z_array=omega_array + 1j*eta
        z_array = np.asarray(z_array)
        result = z_array - a[-1]

        for i in reversed(range(len(b))):
            result = z_array - a[i] - b[i]**2 / result
        result = np.column_stack((z_array.real, -np.pi*(1/result).imag))
        return result

    @staticmethod
    def AA_vectorized_3p(omega_array, eta, eig31, evec31, nBas):
        """
        Generates the spectrum $A(\omega)$ for the three-particle space.
        The spectrum is evaluated over the three-particle space according to
        $$
        A^{\text{3p}}(\omega)=\frac{1}{\pi}\sum_{ijk} |\im G^{\text{3p}}_{3,(ijk;ijk)}(\omega)|,
        $$
        with 

        $$
        G^{\text{3p}}_{3,(ijl;mok)}(\omega)& =  \sum_{\lambda}\frac{A^{ijl}_{\lambda}A^{*mok}_{\lambda}}{\omega-E_{\lambda}}.
        $$
        The $A^{ijl}_{\lambda},A^{*mok}_{\lambda}$ are the three-particle part of the effective Hamiltonian's $\lambda$th eigenvectors. $\omega_{\lambda}$
        is the $\lambda$th eigenenergy.

        Parameters:
            omega_array : array of float energies over which the spectrum is calculated (shape: (M,))
            eta : Lorentzian broadening (float)
            eig31       : eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$))
            evec31       : row-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
            the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
            nBas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
            Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

        Returns:
            A(omega_array) : array of real values representing the three-particle spectrum over the energy range omega_array  (shape: (M,))
        """
        print("Calculating the spectrum - only 3p")
        start_time=time.time()
        evec_squared = evec31[nBas:, :] * evec31[nBas:, :].conj()  # shape (nBas, nEig)

        denom = eig31[:, np.newaxis].real  # shape (nEig, 1)

        # omega_eta = omega_array[np.newaxis, :] - denom + eta_arr[:, np.newaxis] # shape (nEig, N_omega)

        omega_eta = omega_array[np.newaxis, :] - denom + 1j*eta # shape (nEig, N_omega)

        weights = np.sum(evec_squared, axis=0)  # shape (nEig,)

        # # for i, (E, w) in enumerate(zip(eig31*Hartree, weights)):
        # #     print(f"Excitation {i}: E = {E:.3f}, weight = {w:.6f}")
        # for i, (E, w) in enumerate(zip(eig31-eta_arr, weights)):
        #     contrib = -1/np.pi * np.imag(w / (omega_array - E))
        #     plt.plot(omega_array, contrib, label=f"Exc {i}, w={w:.3e}")
        #     # plt.savefig("bse_vs_dyson/supp_"+mol_name+"_"+basis+"_"+nnn+".png", format='png', dpi=300)
        response = np.sum(weights[:, np.newaxis] / omega_eta, axis=0)  # shape (N_omega,)

        amplitudes=-1 / np.pi * np.imag(response)
        result = np.column_stack((omega_array.flatten(), amplitudes))
        end_time=time.time()
        elapsed=end_time-start_time
        print(f"Calculating spectrum took {elapsed:.2f} seconds")
        return result

#%% contribution analysis

    def getTopContributionsInEvec(self, eigen, evecs0, ao_labels=None, secondBorn=None,topN=3, MINVEC=-1, MAXVEC=-1,roundingLevel=5):
        """
        Determine the dominant basis-state contributions to effective Hamiltonian eigenvectors.

        For each eigenvector, the squared amplitudes :math:`|c_i|^2` of the basis-state
        coefficients are computed and the ``topN`` largest contributions are retained.
        Eigenvectors with degenerate (or nearly degenerate) eigenenergies are grouped
        according to their energy rounded to ``roundingLevel`` decimal places. The
        contributions of all eigenvectors within a group are summed and normalized.

        The resulting assignments can be returned either in terms of basis-state
        indices or translated to atomic-orbital labels if ``ao_labels`` is provided.

        Parameters
        ----------
        eigen : numpy.ndarray
            Eigenenergies of the effective Hamiltonian with shape ``(N,)``.

        evecs0 : numpy.ndarray
            Matrix of eigenvectors of the effective Hamiltonian. The expected shape is
            ``(N, N)`` with eigenvectors stored as columns. Internally, the matrix is
            transposed such that individual eigenvectors are processed row-wise.

        ao_labels : list[str] | None, optional
            Atomic-orbital labels used to translate basis-state indices into a
            human-readable representation. If ``None``, numerical labels are returned.
            Default is ``None``.

        secondBorn : bool | None, optional
            Whether the Second-Born basis-space mapping should be used when
            translating basis-state indices. If ``None``, the value of
            ``self.secondBorn`` is used. Default is ``None``.

        topN : int, optional
            Number of largest basis-state contributions retained for each eigenvector.
            Default is ``3``.

        MINVEC : int, optional
            Index of the first eigenvector to analyze. If negative, analysis starts
            from the first eigenvector. Default is ``-1``.

        MAXVEC : int, optional
            Index one past the last eigenvector to analyze. If negative, all
            eigenvectors are included. Default is ``-1``.

        roundingLevel : int, optional
            Number of decimal places used when grouping nearly degenerate
            eigenenergies. Default is ``5``.

        Returns
        -------
        dict[float, dict]
            Dictionary mapping rounded eigenenergies to normalized contribution
            dictionaries.

            The outer dictionary has the form

            .. code-block:: python

                {
                    energy_1: {label_1: weight_1, label_2: weight_2, ...},
                    energy_2: {label_1: weight_1, label_2: weight_2, ...},
                    ...
                }

            where the weights correspond to normalized summed contributions
            :math:`|c_i|^2` of the dominant basis states.

        Notes
        -----
        Only the ``topN`` largest contributions of each eigenvector are retained
        before grouping and normalization. Consequently, the returned weights
        represent the relative importance of the dominant basis states rather than
        the complete decomposition of the eigenvector.

        Degeneracies are identified by rounding eigenenergies to
        ``roundingLevel`` decimal places.
        """

        if secondBorn==None:
            secondBorn=self.secondBorn

        evecs0 = evecs0.T
        if ao_labels is not None:
            ao_labels = [lbl.rstrip() for lbl in ao_labels]

        if MINVEC < 0:
            MINVEC = 0
        if MAXVEC < 0:
            MAXVEC = len(evecs0)

        # Dictionary: rounded_energy → list of contribution dicts
        # Each dict: { index : magnitude }
        grouped = defaultdict(list)

        for i in range(MINVEC, MAXVEC):

            eigval = eigen[i]
            evec = evecs0[i]

            # 1. Take probabilities |c|² for the eigenvector
            probs = np.abs(evec) ** 2

            # 2. Put (prob, index) pairs and take the top N
            pairs = list(zip(probs, range(len(probs))))
            pairs.sort(reverse=True, key=lambda x: x[0])
            top = pairs[:topN]

            # 3. Build structure: [eigval, (prob1, idx1), ...]
            rounded_energy = round(float(eigval), roundingLevel)  # rounding level adjustable

            # 4. Store this eigenvector's contributions
            contrib_dict = {idx: prob for prob, idx in top}
            grouped[rounded_energy].append(contrib_dict)

        # 5. Sum + normalize contributions for each degenerate energy
        result = {}

        for energy, contrib_list in grouped.items():
            combined = defaultdict(float)

            # Sum contributions of all eigenvectors belonging to this energy
            for contrib in contrib_list:
                for idx, mag in contrib.items():
                    combined[idx] += mag

            # Normalize
            norm = sum(combined.values())
            if norm > 0:
                for k in combined:
                    combined[k] /= norm

            result[energy] = dict(combined)

        if ao_labels is not None:
            if not secondBorn:
                for energy in result:
                    result[energy] = {self.nspace_spatials_MCDE.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
            else:
                for energy in result:
                    result[energy] = {self.nspace_spatials_SB.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
        else:
            for energy in result:
                result[energy] = {self.nspace_spatials_MCDE.returnNumLabels(idx): val for idx, val in result[energy].items()}
        return result

    def getTopContributionsIn1Evec(self, eigen, evecs0, topN=10, ao_labels=None, secondBorn=None, roundingLevel=5):
        """
        Determine the dominant one-particle contributions to effective Hamiltonian eigenvectors.

        For each eigenvector, the squared amplitudes :math:`|c_i|^2` of the basis-state
        coefficients are computed and sorted in descending order. The `topN` largest
        contributions are retained for each eigenvector. Eigenvectors with degenerate
        (or nearly degenerate) eigenenergies are grouped according to their energy
        rounded to `roundingLevel` decimal places, and contributions from all
        eigenvectors in the group are summed.

        Unlike :meth:`getTopContributionsInEvec`, the summed contributions are not
        normalized. The results are returned as sorted lists of basis-state labels and
        their associated weights.

        Parameters
        -----
        eigen : numpy.ndarray
            Eigenenergies of the effective Hamiltonian with shape `(N,)`.

        evecs0 : numpy.ndarray
            Matrix of eigenvectors of the effective Hamiltonian. The expected shape is
            `(N, N)` with eigenvectors stored as columns. Internally, the matrix is
            transposed such that individual eigenvectors are processed row-wise.

        topN : int, optional
            Number of largest basis-state contributions retained for each eigenvector.
            If `topN <= 0`, all contributions are retained. Default is `10`.

        ao_labels : list[str] | None, optional
            Atomic-orbital labels. Currently unused by this method but retained for
            interface compatibility. Default is `None`.

        secondBorn : bool | None, optional
            If `None`, the value of `self.secondBorn` is used. Currently unused in
            the returned result but retained for interface compatibility.
            Default is `None`.

        roundingLevel : int, optional
            Number of decimal places used when grouping nearly degenerate
            eigenenergies. Default is `5`.

        Returns
        -----
        dict[float, list[tuple[str, float]]]
            Dictionary mapping rounded eigenenergies to sorted lists of
            `(label, weight)` pairs.

        ```
        The outer dictionary has the form

        .. code-block:: python

            {
                energy_1: [
                    ("label_1", weight_1),
                    ("label_2", weight_2),
                    ...
                ],
                energy_2: [
                    ("label_1", weight_1),
                    ("label_2", weight_2),
                    ...
                ],
                ...
            }

        where the labels correspond to basis-state occupations returned by
        ``self.nspace_spatials_MCDE.returnNumLabels`` and the weights are summed
        contributions :math:`|c_i|^2`.
        ```

        Notes
        -----
        Eigenvectors are grouped according to energies rounded to
        `roundingLevel` decimal places.

        The returned weights are not normalized. Consequently, the total weight
        associated with a given energy depends on both the number of grouped
        eigenvectors and the retained contributions.

        If `topN <= 0`, all basis-state contributions are retained before
        grouping.
        """

        if secondBorn==None:
            secondBorn=self.secondBorn

        evecs0 = evecs0.T
        if ao_labels is not None:
            ao_labels = [lbl.rstrip() for lbl in ao_labels]



        MINVEC = 0
        MAXVEC = len(evecs0)

        # Dictionary: rounded_energy → list of contribution dicts
        # Each dict: { index : magnitude }
        grouped = defaultdict(list)

        for i in range(MINVEC, MAXVEC):
             eigval = eigen[i]
             evec = evecs0[i]

             # 1. Take probabilities |c|² for the eigenvector
             probs = np.abs(evec) ** 2

             # 2. Put (prob, index) pairs and take the top N
             pairs = list(zip(probs, range(len(probs))))
             pairs.sort(reverse=True, key=lambda x: x[0])
             top=pairs[:topN] if topN>0 else pairs[:]

             # 3. Build structure: [eigval, (prob1, idx1), ...]
             rounded_energy = round(float(eigval), roundingLevel)  # rounding level adjustable
             # rounded_energy = eigval  # rounding level adjustable

             # 4. Store this eigenvector's contributions
             contrib_dict = {idx: prob for prob, idx in top}
             grouped[rounded_energy].append(contrib_dict)


        # 5. Sum + normalize contributions for each degenerate energy
        result = {}

        for energy, contrib_list in grouped.items():
            combined = defaultdict(float)

            # Sum contributions of all eigenvectors belonging to this energy
            for contrib in contrib_list:
                for idx, mag in contrib.items():
                    combined[idx] += mag

            # Normalize
            # norm = sum(combined.values())
            # if norm > 0:
            #     for k in combined:
            #         combined[k] /= norm
            sorted_items = sorted(
                combined.items(),
                key=lambda x: x[1],
                reverse=True
            )

            result[energy] = [
                (self.nspace_spatials_MCDE.returnNumLabels(idx), val)
                for idx, val in sorted_items
            ]
            # result[energy] = dict(
            #     sorted(
            #         (
            #             (self.nspace_spatials_MCDE.returnNumLabels(idx), val)
            #             for idx, val in combined.items()
            #         ),
            #         key=lambda x: x[1],
            #         reverse=True
            #     )
            # )

        # if ao_labels is not None:
        #     if not secondBorn:
        #         for energy in result:
        #             result[energy] = {self.nspace_spatials_MCDE.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
        #     else:
        #         for energy in result:
        #             result[energy] = {self.nspace_spatials_SB.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
        # else:
        #     for energy in result:
        #         result[energy] = {self.nspace_spatials_MCDE.returnNumLabels(idx): val for idx, val in result[energy].items()}
        return result

compare = [] instance-attribute

compareshoulder = [] instance-attribute

data_type_sparse = np.float64 instance-attribute

do_auto_sparse = True instance-attribute

do_auto_sparse_basis_threshold = 3000 instance-attribute

do_sparse = False instance-attribute

eri_mo = erimo instance-attribute

eri_mo_W = None instance-attribute

eri_mo_gabi = self.eri_mo.transpose((0, 2, 3, 1)) instance-attribute

eri_mo_gabi_W = None instance-attribute

estimate_spin_opt_ham = estimate instance-attribute

exactDiag = True instance-attribute

fullCalculation = False instance-attribute

intermediatetime = self.starttime instance-attribute

iterations = max(int(estimate * 0.75), 100) instance-attribute

kernel_run = False instance-attribute

lanczos = False instance-attribute

lanczos_tol = 1e-12 instance-attribute

mcde = True instance-attribute

mo_en = moEn instance-attribute

nBas = nBas instance-attribute

nO = nO instance-attribute

nV = nBas - nO instance-attribute

reduce_evecs_to_1body = False instance-attribute

remove_single_values = True instance-attribute

secondBorn = False instance-attribute

shift_virtual_energy = 0 instance-attribute

sparse_tol = 1e-08 instance-attribute

spinOptimized = True instance-attribute

starttime = time.perf_counter() instance-attribute

verbose = verbose instance-attribute

zero_tol = 1e-10 instance-attribute

zero_tol_evals = 1e-16 instance-attribute

AuxillaryFunctions

Source code in src/MCDE2409_parallel.py
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
class AuxillaryFunctions():

    #def __init__(self):

    @staticmethod
    def eig(matrix):
        return np.linalg.eigh(matrix)

    @staticmethod
    def remove_isolated_diagonals(A,spaceObj,remove_single_values):
        if not remove_single_values:
            return A,spaceObj
        A = np.array(A)
        keep = []
        for i in range(A.shape[0]):
            if A[i, i] == 0:
                keep.append(i)
            else:
                row = np.copy(A[i, :])
                col = np.copy(A[:, i])
                row[i] = 0
                col[i] = 0
                if np.any(row) or np.any(col):
                    keep.append(i)
        # Keep only rows and columns that are not isolated diagonals
        A_new = A[np.ix_(keep, keep)]


        d1=[]
        d3=[]
        #spaceObj.stats()
        for x in keep:
            if x>=len(spaceObj.d1):
                d3.append(spaceObj.v(x))
            else:
                d1.append(spaceObj.v(x))
        return A_new, MCDE.Nspace(np.array(d1), np.array(d3))

    @staticmethod
    def remove_isolated_diagonals_sparse(A,spaceObj,remove_single_values):
        if not remove_single_values:
            return A,spaceObj
        # Step 1: Count nonzeros per row and per column
        row_nnz = np.diff(A.indptr)           # CSR: number of nonzeros per row
        col_nnz = np.diff(A.tocsc().indptr)  # CSC: number of nonzeros per column

        # Step 2: Identify diagonal indices
        diag_idx = np.arange(A.shape[0])

        # Step 3: Mask for diagonals that are isolated
        isolated_diag_mask = (row_nnz == 1) & (col_nnz == 1)

        # Step 4: Zero out isolated diagonals
        A[diag_idx[isolated_diag_mask], diag_idx[isolated_diag_mask]] = 0

        # Step 5: Remove stored zeros
        A.eliminate_zeros()

        # print("bing")
        d1=[]
        d3=[]
        #spaceObj.stats()
        for x,v in enumerate(isolated_diag_mask):
            if v:
                continue
            if x>=len(spaceObj.d1):
                d3.append(spaceObj.v(x))
            else:
                d1.append(spaceObj.v(x))

        # print(len(isolated_diag_mask))
        return A,MCDE.Nspace(np.array(d1), np.array(d3))
eig(matrix) staticmethod
Source code in src/MCDE2409_parallel.py
140
141
142
@staticmethod
def eig(matrix):
    return np.linalg.eigh(matrix)
remove_isolated_diagonals(A, spaceObj, remove_single_values) staticmethod
Source code in src/MCDE2409_parallel.py
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
@staticmethod
def remove_isolated_diagonals(A,spaceObj,remove_single_values):
    if not remove_single_values:
        return A,spaceObj
    A = np.array(A)
    keep = []
    for i in range(A.shape[0]):
        if A[i, i] == 0:
            keep.append(i)
        else:
            row = np.copy(A[i, :])
            col = np.copy(A[:, i])
            row[i] = 0
            col[i] = 0
            if np.any(row) or np.any(col):
                keep.append(i)
    # Keep only rows and columns that are not isolated diagonals
    A_new = A[np.ix_(keep, keep)]


    d1=[]
    d3=[]
    #spaceObj.stats()
    for x in keep:
        if x>=len(spaceObj.d1):
            d3.append(spaceObj.v(x))
        else:
            d1.append(spaceObj.v(x))
    return A_new, MCDE.Nspace(np.array(d1), np.array(d3))
remove_isolated_diagonals_sparse(A, spaceObj, remove_single_values) staticmethod
Source code in src/MCDE2409_parallel.py
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
@staticmethod
def remove_isolated_diagonals_sparse(A,spaceObj,remove_single_values):
    if not remove_single_values:
        return A,spaceObj
    # Step 1: Count nonzeros per row and per column
    row_nnz = np.diff(A.indptr)           # CSR: number of nonzeros per row
    col_nnz = np.diff(A.tocsc().indptr)  # CSC: number of nonzeros per column

    # Step 2: Identify diagonal indices
    diag_idx = np.arange(A.shape[0])

    # Step 3: Mask for diagonals that are isolated
    isolated_diag_mask = (row_nnz == 1) & (col_nnz == 1)

    # Step 4: Zero out isolated diagonals
    A[diag_idx[isolated_diag_mask], diag_idx[isolated_diag_mask]] = 0

    # Step 5: Remove stored zeros
    A.eliminate_zeros()

    # print("bing")
    d1=[]
    d3=[]
    #spaceObj.stats()
    for x,v in enumerate(isolated_diag_mask):
        if v:
            continue
        if x>=len(spaceObj.d1):
            d3.append(spaceObj.v(x))
        else:
            d1.append(spaceObj.v(x))

    # print(len(isolated_diag_mask))
    return A,MCDE.Nspace(np.array(d1), np.array(d3))

Nspace

Source code in src/MCDE2409_parallel.py
 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
class Nspace():

    def __init__(self,d1,d3):
        self.d1=d1
        self.d3=d3

    def v(self,n):
        if n>=len(self.d1):
            return self.d3[n-len(self.d1)]
        return self.d1[n]

    def stats(self):
        print("1-particle length: "+str(len(self.d1)))
        print("3-particle length: "+str(len(self.d3)))
        print("total length: "+str(len(self.d1)+len(self.d3)))

    def translateToAOLabels(self,n,ao_labels):
        vec=self.v(n)
        if isinstance(vec,np.ndarray):
            a=ao_labels[vec[0]]
            b=ao_labels[vec[1]]
            c=ao_labels[vec[2]]

            return "{"+a+", "+b+", "+c+"}"
        return ao_labels[vec]

    def returnNumLabels(self,n):
        vec=self.v(n)
        if isinstance(vec,np.ndarray):
            a=str(vec[0])
            b=str(vec[1])
            c=str(vec[2])

            return "{"+a+", "+b+", "+c+"}"
        return str(vec)
d1 = d1 instance-attribute
d3 = d3 instance-attribute
returnNumLabels(n)
Source code in src/MCDE2409_parallel.py
123
124
125
126
127
128
129
130
131
def returnNumLabels(self,n):
    vec=self.v(n)
    if isinstance(vec,np.ndarray):
        a=str(vec[0])
        b=str(vec[1])
        c=str(vec[2])

        return "{"+a+", "+b+", "+c+"}"
    return str(vec)
stats()
Source code in src/MCDE2409_parallel.py
108
109
110
111
def stats(self):
    print("1-particle length: "+str(len(self.d1)))
    print("3-particle length: "+str(len(self.d3)))
    print("total length: "+str(len(self.d1)+len(self.d3)))
translateToAOLabels(n, ao_labels)
Source code in src/MCDE2409_parallel.py
113
114
115
116
117
118
119
120
121
def translateToAOLabels(self,n,ao_labels):
    vec=self.v(n)
    if isinstance(vec,np.ndarray):
        a=ao_labels[vec[0]]
        b=ao_labels[vec[1]]
        c=ao_labels[vec[2]]

        return "{"+a+", "+b+", "+c+"}"
    return ao_labels[vec]
v(n)
Source code in src/MCDE2409_parallel.py
103
104
105
106
def v(self,n):
    if n>=len(self.d1):
        return self.d3[n-len(self.d1)]
    return self.d1[n]

AA_Lanczos(omega_array, eta, a, b) staticmethod

Generates the spectrum \(A(\omega)\) for the one-particle space for Lanczos parameters. Evaluation of the continued fraction of the Lanczos tridiagonal matrix elements over an energy range omega_array. Returns a spectrum \(A(z)\) as an array. \(z\) represents \(\omega +i\eta\), with \(\eta\) the Lorentzian broadening, and \(\omega\) the energies. The spectrum formula used is: $$ A(z) = -\pi \, \mathrm{Im}[ z - a_0 - \cfrac{b_1^2}{z - a_1 - \cfrac{b_2^2}{z - a_2 - \cdots}} ]^{-1} $$

Parameters:

Name Type Description Default
omega_array

array of float energies over which the spectrum is calculated (shape: (M,))

required
eta

Lorentzian broadening (float)

required
a

array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)

required
b

array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. The first term b1

required

Returns:

Type Description

A(omega_array) : array of real values representing the spectrum over the energy range omega_array (shape: (M,))

Source code in src/MCDE2409_parallel.py
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
@staticmethod
def AA_Lanczos(omega_array,eta, a, b):
    """
    Generates the spectrum $A(\omega)$ for the one-particle space for Lanczos parameters.
    Evaluation of the continued fraction of the Lanczos tridiagonal matrix elements over an energy range omega_array.
    Returns a spectrum $A(z)$ as an array.
    $z$ represents $\omega +i\eta$, with $\eta$ the Lorentzian broadening, and $\omega$ the energies.
    The spectrum formula used is:
    $$
    A(z) = -\pi \, \mathrm{Im}[ z - a_0 - \cfrac{b_1^2}{z - a_1 - \cfrac{b_2^2}{z - a_2 - \cdots}} ]^{-1}
    $$

    Parameters:
        omega_array : array of float energies over which the spectrum is calculated (shape: (M,))
        eta : Lorentzian broadening (float)
        a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
        b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. The first term b1 
        is automatically discarded (length n)

    Returns:
        A(omega_array) : array of real values representing the spectrum over the energy range omega_array  (shape: (M,))
    """
    b=b[1:]
    z_array=omega_array + 1j*eta
    z_array = np.asarray(z_array)
    result = z_array - a[-1]

    for i in reversed(range(len(b))):
        result = z_array - a[i] - b[i]**2 / result
    result = np.column_stack((z_array.real, -np.pi*(1/result).imag))
    return result

AA_vectorized(omega_array, eta, eig31, evec31, nBas) staticmethod

Generates the spectrum \(A(\omega)\) for the one-particle space. The spectrum is evaluated over the three-particle space according to $$ A^{ ext{1p}}(\omega)= rac{1}{\pi}\sum_{i} |\im G^{ ext{1p}}_{3,(i;i)}(\omega)|, $$ with

$$ G^{ ext{1p}}{3,(i;m)}(\omega)& = \sum{\lambda} rac{A^{i}{\lambda}A^{*m}{\lambda}}{\omega-E_{\lambda}}. $$ The \(A^{i}_{\lambda},A^{*m}_{\lambda}\) are the one-particle part of the effective Hamiltonian's \(\lambda\)th eigenvectors. \(\omega_{\lambda}\) is the \(\lambda\)th eigenenergy.

Parameters:

Name Type Description Default
omega_array

array of float energies over which the spectrum is calculated (shape: (M,))

required
eta

Lorentzian broadening (float)

required
eig31

eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

required
evec31

row-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

required
nBas

number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted

required

Returns:

Type Description

A(omega_array) : array of real values representing the one-particle spectrum over the energy range omega_array (shape: (M,))

Source code in src/MCDE2409_parallel.py
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
@staticmethod
def AA_vectorized(omega_array, eta, eig31, evec31, nBas):
    """
    Generates the spectrum $A(\omega)$ for the one-particle space.
    The spectrum is evaluated over the three-particle space according to
    $$
    A^{\text{1p}}(\omega)=\frac{1}{\pi}\sum_{i} |\im G^{\text{1p}}_{3,(i;i)}(\omega)|,
    $$
    with 

    $$
    G^{\text{1p}}_{3,(i;m)}(\omega)& =  \sum_{\lambda}\frac{A^{i}_{\lambda}A^{*m}_{\lambda}}{\omega-E_{\lambda}}.
    $$
    The $A^{i}_{\lambda},A^{*m}_{\lambda}$ are the one-particle part of the effective Hamiltonian's $\lambda$th eigenvectors. $\omega_{\lambda}$
    is the $\lambda$th eigenenergy.

    Parameters:
        omega_array : array of float energies over which the spectrum is calculated (shape: (M,))
        eta : Lorentzian broadening (float)
        eig31       : eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$))
        evec31       : row-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
        nBas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
        Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

    Returns:
        A(omega_array) : array of real values representing the one-particle spectrum over the energy range omega_array  (shape: (M,))
    """
    print("Calculating the spectrum")
    start_time=time.time()
    evec_squared = evec31[:nBas, :] * evec31[:nBas, :].conj()  # shape (nBas, nEig)

    denom = eig31[:, np.newaxis].real  # shape (nEig, 1)

    omega_eta = omega_array[np.newaxis, :] - denom + 1j*eta # shape (nEig, N_omega)

    weights = np.sum(evec_squared, axis=0)  # shape (nEig,)


    response = np.sum(weights[:, np.newaxis] / omega_eta, axis=0)  # shape (N_omega,)

    amplitudes=-1 / np.pi * np.imag(response)
    result = np.column_stack((omega_array.flatten(), amplitudes))
    end_time=time.time()
    elapsed=end_time-start_time
    print(f"Calculating spectrum took {elapsed:.2f} seconds")
    return result

AA_vectorized_3p(omega_array, eta, eig31, evec31, nBas) staticmethod

Generates the spectrum \(A(\omega)\) for the three-particle space. The spectrum is evaluated over the three-particle space according to $$ A^{ ext{3p}}(\omega)= rac{1}{\pi}\sum_{ijk} |\im G^{ ext{3p}}_{3,(ijk;ijk)}(\omega)|, $$ with

$$ G^{ ext{3p}}{3,(ijl;mok)}(\omega)& = \sum{\lambda} rac{A^{ijl}{\lambda}A^{*mok}{\lambda}}{\omega-E_{\lambda}}. $$ The \(A^{ijl}_{\lambda},A^{*mok}_{\lambda}\) are the three-particle part of the effective Hamiltonian's \(\lambda\)th eigenvectors. \(\omega_{\lambda}\) is the \(\lambda\)th eigenenergy.

Parameters:

Name Type Description Default
omega_array

array of float energies over which the spectrum is calculated (shape: (M,))

required
eta

Lorentzian broadening (float)

required
eig31

eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

required
evec31

row-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

required
nBas

number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted

required

Returns:

Type Description

A(omega_array) : array of real values representing the three-particle spectrum over the energy range omega_array (shape: (M,))

Source code in src/MCDE2409_parallel.py
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
@staticmethod
def AA_vectorized_3p(omega_array, eta, eig31, evec31, nBas):
    """
    Generates the spectrum $A(\omega)$ for the three-particle space.
    The spectrum is evaluated over the three-particle space according to
    $$
    A^{\text{3p}}(\omega)=\frac{1}{\pi}\sum_{ijk} |\im G^{\text{3p}}_{3,(ijk;ijk)}(\omega)|,
    $$
    with 

    $$
    G^{\text{3p}}_{3,(ijl;mok)}(\omega)& =  \sum_{\lambda}\frac{A^{ijl}_{\lambda}A^{*mok}_{\lambda}}{\omega-E_{\lambda}}.
    $$
    The $A^{ijl}_{\lambda},A^{*mok}_{\lambda}$ are the three-particle part of the effective Hamiltonian's $\lambda$th eigenvectors. $\omega_{\lambda}$
    is the $\lambda$th eigenenergy.

    Parameters:
        omega_array : array of float energies over which the spectrum is calculated (shape: (M,))
        eta : Lorentzian broadening (float)
        eig31       : eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$))
        evec31       : row-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
        nBas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
        Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

    Returns:
        A(omega_array) : array of real values representing the three-particle spectrum over the energy range omega_array  (shape: (M,))
    """
    print("Calculating the spectrum - only 3p")
    start_time=time.time()
    evec_squared = evec31[nBas:, :] * evec31[nBas:, :].conj()  # shape (nBas, nEig)

    denom = eig31[:, np.newaxis].real  # shape (nEig, 1)

    # omega_eta = omega_array[np.newaxis, :] - denom + eta_arr[:, np.newaxis] # shape (nEig, N_omega)

    omega_eta = omega_array[np.newaxis, :] - denom + 1j*eta # shape (nEig, N_omega)

    weights = np.sum(evec_squared, axis=0)  # shape (nEig,)

    # # for i, (E, w) in enumerate(zip(eig31*Hartree, weights)):
    # #     print(f"Excitation {i}: E = {E:.3f}, weight = {w:.6f}")
    # for i, (E, w) in enumerate(zip(eig31-eta_arr, weights)):
    #     contrib = -1/np.pi * np.imag(w / (omega_array - E))
    #     plt.plot(omega_array, contrib, label=f"Exc {i}, w={w:.3e}")
    #     # plt.savefig("bse_vs_dyson/supp_"+mol_name+"_"+basis+"_"+nnn+".png", format='png', dpi=300)
    response = np.sum(weights[:, np.newaxis] / omega_eta, axis=0)  # shape (N_omega,)

    amplitudes=-1 / np.pi * np.imag(response)
    result = np.column_stack((omega_array.flatten(), amplitudes))
    end_time=time.time()
    elapsed=end_time-start_time
    print(f"Calculating spectrum took {elapsed:.2f} seconds")
    return result

HeffMCDE()

Source code in src/MCDE2409_parallel.py
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
def HeffMCDE(self):
    if self.HeffSBmat is None:
        raise ValueError("The second Born effective Hamiltonian has not been initialised with createSecondBornEffectiveHam")
    if self.sigma3 is None:
        raise ValueError("3-particle self energy not initialized with sigma3s")

    index=self.nBas*2
    self.HeffMCDEmat=self.HeffSBmat.copy()
    sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
    for index,element in enumerate(self.nspace):
        a=element[0]
        b=element[1]
        c=element[2]
        for index2,element2 in enumerate(self.nspace):
            x=element2[0]
            y=element2[1]
            z=element2[2]
            sigmaBody[index,index2]=self.sigma3[a,b,c,x,y,z]
    # print("Target shape:", self.HeffMCDEmat[index:index+sigmaBody.shape[0],
    #                                 index:index+sigmaBody.shape[1]].shape)
    # print("sigmaBody shape:", sigmaBody.shape)
    index=self.nBas*2
    self.HeffMCDEmat[index:index+sigmaBody.shape[0], index:index+sigmaBody.shape[1]]+=sigmaBody

    self.verbose4("Nonzero values of effective Hamiltionian")
    if self.verbose>=4:
        for ii in range(len(self.HeffMCDEmat)):
            for jj in range(len(self.HeffMCDEmat)):
                if (abs(self.HeffMCDEmat[ii,jj])>1e-15):
                    self.verbose4('%4d %4d      %.5f'%(ii,jj,self.HeffMCDEmat[ii,jj]))

HeffSecondBorn()

Source code in src/MCDE2409_parallel.py
746
747
748
749
750
751
752
753
754
755
756
757
758
def HeffSecondBorn(self):
    if self.HeffSBmat is None:
        raise ValueError("The second Born effective Hamiltonian has not been initialised with createSecondBornEffectiveHam")




    self.verbose4("Nonzero values of effective Hamiltionian")
    if self.verbose>=4:
        for ii in range(len(self.heffSBmat)):
            for jj in range(len(self.heffSBmat)):
                if (abs(self.heffSBmat[ii,jj])>1e-15):
                    self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffSBmat[ii,jj]))

LanczosAlgorithm(matrix, nbas)

Compute the Haydock-Lanczos algorithm for an effective Hamiltonian matrix up to self.iterations. The Lanczos algorithm starts from an initial three-particle guess vector \(\psi_0\), which has 1 for the one-particle coefficients (up to nbas), and 0 for the three-particle coefficients. \(\psi_0\) is multiplied with the effective Hamiltonian \(H\) (matrix) to generate an approximate vector \(\psi_1\). From \(\psi_0\) and \(\psi_1\) Lanczos coefficients \(a,b\) are won. Then, the algorithm is repeated iteratively, with \(\psi_{i+1}=H\psi_{i}\), until either self.iterations iterations are done, or the norm of \(\psi_{i+1}\) is smaller than self.lanczos_tol, in which case an invariant subspace of \(H\) has been probed. For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors \(\psi_0,...,\psi_{i+1}\) is performed

Parameters:

Name Type Description Default
matrix

effective Hamiltonian as a numpy array (shape: (M,M))

required
nbas

number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted

required

Returns:

Name Type Description
a

array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)

b

array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)

Source code in src/MCDE2409_parallel.py
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
def LanczosAlgorithm(self,matrix,nbas):
    """
    Compute the Haydock-Lanczos algorithm for an effective Hamiltonian `matrix` up to `self.iterations`.
    The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
    0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
    From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
    with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
    than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.
    For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors $\psi_0,...,\psi_{i+1}$ is performed

    Parameters:
        matrix : effective Hamiltonian as a numpy array (shape: (M,M))
        nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
        Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

    Returns:
        a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
        b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
    """
    self.verbose1("Starting Lanczos Algorithm")

    acoeff = np.zeros(self.iterations)
    bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
    lanczosBasis = np.zeros((self.iterations, len(matrix)))

    # Start vector
    s0 = np.zeros(len(matrix))
    s0[:nbas] = 1
    s0 /= np.linalg.norm(s0)
    lanczosBasis[0] = s0

    # First step
    w = matrix @ s0
    acoeff[0] = np.dot(s0, w)
    w -= acoeff[0] * s0
    bcoeff[1] = np.linalg.norm(w)
    lanczosBasis[1] = w / bcoeff[1]

    # Main loop
    for i in range(1, self.iterations - 1):
        v_prev = lanczosBasis[i - 1]
        v_curr = lanczosBasis[i]
        w = matrix @ v_curr
        acoeff[i] = np.dot(v_curr, w)
        w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

        # Optional: reorthogonalize w to all previous basis vectors
        # for j in range(i):
        #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

        # FULL REORTHOGONALIZATION
        for j in range(i + 1):
            w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

        bcoeff[i + 1] = np.linalg.norm(w)
        if bcoeff[i + 1] < self.lanczos_tol:
            self.verbose2("Breakdown at step "+ str(i))
            break
        lanczosBasis[i + 1] = w / bcoeff[i + 1]

    acoeff[self.iterations - 1] = lanczosBasis[self.iterations - 1] @ matrix @ lanczosBasis[self.iterations - 1].T

    self.timed("Lanczos Algorithm", 2)

    return acoeff,bcoeff

LanczosAlgorithmSparse(matrix, nbas, returnLanczosVectors=False)

Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian matrix up to self.iterations. The Lanczos algorithm starts from an initial three-particle guess vector \(\psi_0\), which has 1 for the one-particle coefficients (up to nbas), and 0 for the three-particle coefficients. \(\psi_0\) is multiplied with the effective Hamiltonian \(H\) (matrix) to generate an approximate vector \(\psi_1\). From \(\psi_0\) and \(\psi_1\) Lanczos coefficients \(a,b\) are won. Then, the algorithm is repeated iteratively, with \(\psi_{i+1}=H\psi_{i}\), until either self.iterations iterations are done, or the norm of \(\psi_{i+1}\) is smaller than self.lanczos_tol, in which case an invariant subspace of \(H\) has been probed. For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors \(\psi_0,...,\psi_{i+1}\) is performed

Parameters:

Name Type Description Default
matrix

effective Hamiltonian as a scipy.sparse csr matrix (shape: (M,M))

required
nbas

number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted

required
returnLanczosVectors

True if you want to return the Lanczos vectors of the Krylov Basis. (Bool)

required

Returns:

Name Type Description
a

array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)

b

array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)

lv (optional) : if returnLanczosVectors is True, returns an array of row Lanczos vectors (length (n,M))

Source code in src/MCDE2409_parallel.py
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
def LanczosAlgorithmSparse(self,matrix,nbas,returnLanczosVectors=False):
    """
    Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian `matrix` up to `self.iterations`.
    The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
    0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
    From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
    with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
    than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.
    For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors $\psi_0,...,\psi_{i+1}$ is performed

    Parameters:
        matrix : effective Hamiltonian as a `scipy.sparse` csr matrix (shape: (M,M))
        nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
        Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)
        returnLanczosVectors : True if you want to return the Lanczos vectors of the Krylov Basis. (Bool)

    Returns:
        a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
        b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
        lv (optional) : if returnLanczosVectors is True, returns an array of row Lanczos vectors (length (n,M))
    """
    self.verbose1("Starting Lanczos Algorithm")

    matrix_length=matrix.shape[0]

    acoeff = np.zeros(self.iterations)
    bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
    lanczosBasis = np.zeros((self.iterations, matrix_length))

    # Start vector
    s0 = np.zeros(matrix_length)
    s0[:nbas] = 1
    s0 /= np.linalg.norm(s0)
    lanczosBasis[0] = s0

    # First step
    w = matrix @ s0
    acoeff[0] = np.dot(s0, w)
    w -= acoeff[0] * s0
    bcoeff[1] = np.linalg.norm(w)
    lanczosBasis[1] = w / bcoeff[1]

    # Main loop
    final_index = self.iterations - 1
    for i in range(1, self.iterations - 1):
        v_prev = lanczosBasis[i - 1]
        v_curr = lanczosBasis[i]
        w = matrix @ v_curr
        acoeff[i] = np.dot(v_curr, w)
        w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

        # Optional: reorthogonalize w to all previous basis vectors
        # for j in range(i):
        #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

        # FULL REORTHOGONALIZATION
        for j in range(i + 1):
            w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

        b = np.linalg.norm(w)
        # bcoeff[i + 1] = np.linalg.norm(w)
        if b < self.lanczos_tol:
            self.verbose2("Breakdown at step "+ str(i))
            final_index=i
            break
        lanczosBasis[i + 1] = w / b
        bcoeff[i+1]=b
        final_index = i+1
    self.w=lanczosBasis

    acoeff[final_index] = lanczosBasis[final_index] @ matrix @ lanczosBasis[final_index].T


    self.timed("Lanczos Algorithm", 2)

    if returnLanczosVectors:
        return acoeff[:final_index+1], bcoeff[:final_index+1], lanczosBasis 
    return acoeff[:final_index+1], bcoeff[:final_index+1]

LanczosAlgorithmSparse0(matrix, nbas)

Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian matrix up to self.iterations. The Lanczos algorithm starts from an initial three-particle guess vector \(\psi_0\), which has 1 for the one-particle coefficients (up to nbas), and 0 for the three-particle coefficients. \(\psi_0\) is multiplied with the effective Hamiltonian \(H\) (matrix) to generate an approximate vector \(\psi_1\). From \(\psi_0\) and \(\psi_1\) Lanczos coefficients \(a,b\) are won. Then, the algorithm is repeated iteratively, with \(\psi_{i+1}=H\psi_{i}\), until either self.iterations iterations are done, or the norm of \(\psi_{i+1}\) is smaller than self.lanczos_tol, in which case an invariant subspace of \(H\) has been probed. For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors \(\psi_0,...,\psi_{i+1}\) is performed

Parameters:

Name Type Description Default
matrix

effective Hamiltonian as a scipy.sparse csr matrix (shape: (M,M))

required
nbas

number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted

required

Returns:

Name Type Description
a

array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)

b

array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)

Source code in src/MCDE2409_parallel.py
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
def LanczosAlgorithmSparse0(self,matrix,nbas):
    """
    Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian `matrix` up to `self.iterations`.
    The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
    0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
    From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
    with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
    than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.
    For each iteration step, a full Gram-Schmidt reorthogonalization of the Lanczos vectors $\psi_0,...,\psi_{i+1}$ is performed

    Parameters:
        matrix : effective Hamiltonian as a `scipy.sparse` csr matrix (shape: (M,M))
        nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
        Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)

    Returns:
        a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
        b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
    """
    self.verbose1("Starting Lanczos Algorithm")

    matrix_length=matrix.shape[0]

    acoeff = np.zeros(self.iterations)
    bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
    lanczosBasis = np.zeros((self.iterations, matrix_length))

    # Start vector
    s0 = np.zeros(matrix_length)
    s0[:nbas] = 1
    s0 /= np.linalg.norm(s0)
    lanczosBasis[0] = s0

    # First step
    w = matrix @ s0
    acoeff[0] = np.dot(s0, w)
    w -= acoeff[0] * s0
    bcoeff[1] = np.linalg.norm(w)
    lanczosBasis[1] = w / bcoeff[1]

    # Main loop
    for i in range(1, self.iterations - 1):
        v_prev = lanczosBasis[i - 1]
        v_curr = lanczosBasis[i]
        w = matrix @ v_curr
        acoeff[i] = np.dot(v_curr, w)
        w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

        # Optional: reorthogonalize w to all previous basis vectors
        # for j in range(i):
        #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

        # FULL REORTHOGONALIZATION
        for j in range(i + 1):
            w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]

        bcoeff[i + 1] = np.linalg.norm(w)
        if bcoeff[i + 1] < self.lanczos_tol:
            self.verbose2("Breakdown at step "+ str(i))
            break
        lanczosBasis[i + 1] = w / bcoeff[i + 1]

    self.w=lanczosBasis

    acoeff[self.iterations - 1] = lanczosBasis[self.iterations - 1] @ matrix @ lanczosBasis[self.iterations - 1].T

    self.timed("Lanczos Algorithm", 2)

    return acoeff,bcoeff

LanczosAlgorithmSparseNoOrth(matrix, nbas, returnLanczosVectors=False)

Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian up to self.iterations. No Gram-Schmidt reorthogonalization is applied. The Lanczos algorithm starts from an initial three-particle guess vector \(\psi_0\), which has 1 for the one-particle coefficients (up to nbas), and 0 for the three-particle coefficients. \(\psi_0\) is multiplied with the effective Hamiltonian \(H\) (matrix) to generate an approximate vector \(\psi_1\). From \(\psi_0\) and \(\psi_1\) Lanczos coefficients \(a,b\) are won. Then, the algorithm is repeated iteratively, with \(\psi_{i+1}=H\psi_{i}\), until either self.iterations iterations are done, or the norm of \(\psi_{i+1}\) is smaller than self.lanczos_tol, in which case an invariant subspace of \(H\) has been probed.

Parameters:

Name Type Description Default
matrix

effective Hamiltonian as a scipy.sparse csr matrix (shape: (M,M))

required
nbas

number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted

required
returnLanczosVectors

True if you want to return the Lanczos vectors of the Krylov Basis. (Bool)

required

Returns:

Name Type Description
a

array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)

b

array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)

lv (optional) : if returnLanczosVectors is True, returns an array of row Lanczos vectors (length (n,M))

Notes

No orthogonalization is performed.

Source code in src/MCDE2409_parallel.py
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
def LanczosAlgorithmSparseNoOrth(self,matrix,nbas,returnLanczosVectors=False):
    """
    Compute the Haydock-Lanczos algorithm for a sparse effective Hamiltonian up to `self.iterations`.
    No Gram-Schmidt reorthogonalization is applied.
    The Lanczos algorithm starts from an initial three-particle guess vector $\psi_0$, which has 1 for the one-particle coefficients (up to `nbas`), and 
    0 for the three-particle coefficients. $\psi_0$ is multiplied with the effective Hamiltonian $H$ (`matrix`) to generate an approximate vector $\psi_1$.
    From $\psi_0$ and $\psi_1$ Lanczos coefficients $a,b$ are won. Then, the algorithm is repeated iteratively,
    with $\psi_{i+1}=H\psi_{i}$, until either `self.iterations` iterations are done, or the norm of $\psi_{i+1}$ is smaller
    than `self.lanczos_tol`, in which case an invariant subspace of $H$ has been probed.

    Parameters:
        matrix : effective Hamiltonian as a `scipy.sparse` csr matrix (shape: (M,M))
        nbas       : number of one-particle basis states. For the full effective Hamiltonian it is twice the number of restricted Hartree-Fock spatial orbitals. For the spin-adapted
        Hamiltonian it is the number of restricted Hartree-Fock spatial orbitals. (int)
        returnLanczosVectors : True if you want to return the Lanczos vectors of the Krylov Basis. (Bool)

    Returns:
        a       : array of diagonal terms [a1, a2, ..., an] of the Lanczos tridiagonal matrix (length n)
        b       : array of off-diagonal terms [b1, b2, ..., bn] of the Lanczos tridiagonal matrix. (length n)
        lv (optional) : if returnLanczosVectors is True, returns an array of row Lanczos vectors (length (n,M))

    Notes:
        No orthogonalization is performed.
    """
    self.verbose1("Starting Lanczos Algorithm")

    matrix_length=matrix.shape[0]

    acoeff = np.zeros(self.iterations)
    bcoeff = np.zeros(self.iterations)  # will ignore bcoeff[0]
    lanczosBasis = np.zeros((self.iterations, matrix_length))

    # Start vector
    s0 = np.zeros(matrix_length)
    s0[:nbas] = 1
    s0 /= np.linalg.norm(s0)
    lanczosBasis[0] = s0

    # First step
    w = matrix @ s0
    acoeff[0] = np.dot(s0, w)
    w -= acoeff[0] * s0
    bcoeff[1] = np.linalg.norm(w)
    lanczosBasis[1] = w / bcoeff[1]

    # Main loop
    final_index = self.iterations - 1
    for i in range(1, self.iterations - 1):
        v_prev = lanczosBasis[i - 1]
        v_curr = lanczosBasis[i]
        w = matrix @ v_curr
        acoeff[i] = np.dot(v_curr, w)
        w -= acoeff[i] * v_curr + bcoeff[i] * v_prev

        # Optional: reorthogonalize w to all previous basis vectors
        # for j in range(i):
        #     w -= np.dot(lanczosBasis[j], w) * lanczosBasis[j]



        b = np.linalg.norm(w)
        # bcoeff[i + 1] = np.linalg.norm(w)
        if b < self.lanczos_tol:
            self.verbose2("Breakdown at step "+ str(i))
            final_index=i
            break
        lanczosBasis[i + 1] = w / b
        bcoeff[i+1]=b
        final_index = i+1
    self.w=lanczosBasis

    acoeff[final_index] = lanczosBasis[final_index] @ matrix @ lanczosBasis[final_index].T


    self.timed("Lanczos Algorithm", 2)

    if returnLanczosVectors:
        return acoeff[:final_index+1], bcoeff[:final_index+1], lanczosBasis 
    return acoeff[:final_index+1], bcoeff[:final_index+1]

OldHeff()

Source code in src/MCDE2409_parallel.py
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
def OldHeff(self):
    self.verbose4("H effective")
    e01energies=np.zeros((self.nBas*2))
    self.verbose4("writing the double basis hf energies")
    for idx in range(self.nBas*2):
        jdx=int((idx)/2)
        e01energies[idx]=self.mo_en[jdx]
        self.verbose4('%4d   %.5f'%(jdx,self.mo_en[jdx]))

    self.verbose4("writing the triple particle hf energies")
    e03energies=[]
    sigmaShoulder=np.zeros((self.nBas*2,len(self.nspace)))
    sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
    for index,element in enumerate(self.nspace):
        a=element[0]
        b=element[1]
        c=element[2]

        e03energies.append(e01energies[a]+e01energies[b]-e01energies[c])
        self.verbose4('%4d %4d %4d   %.5f'%(a,b,c,e03energies[index]))


        for jdx in range(self.nBas*2):
            sigmaShoulder[jdx,index]=self.sigma3s[jdx,a,b,c]

        for index2,element2 in enumerate(self.nspace):
            x=element2[0]
            y=element2[1]
            z=element2[2]
            sigmaBody[index,index2]=self.sigma3[a,b,c,x,y,z]


    h03=np.diag(np.concatenate((e01energies,e03energies)))



    selfie=np.block([
        [np.zeros((self.nBas*2,self.nBas*2)),sigmaShoulder],
        [sigmaShoulder.T,sigmaBody]
        ])

    self.heffZ=np.add(h03,selfie)
    self.verbose4("Nonzero values of effective Hamiltionian")
    if self.verbose>=4:
        for ii in range(len(self.heffZ)):
            for jj in range(len(self.heffZ)):
                if (abs(self.heffZ[ii,jj])>1e-15):
                    self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffZ[ii,jj]))

    evals,evecs=self.AuxillaryFunctions.eig(np.add(h03,selfie))
    idx = np.argsort(evals)  # use -eigvals for descending
   # eigvals_sorted = evals[idx]
   # eigvecs_sorted = evecs[:, idx]

    self.verbose4("Eigenvalues for H effective")
    if self.verbose>=4:
        for ii in range(len(evals)):
            self.verbose4('%4d      %.5f'%(ii,evals[ii]))

    return evals,evecs,sigmaShoulder,sigmaBody

OldHeffSB()

Source code in src/MCDE2409_parallel.py
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
def OldHeffSB(self):
    self.verbose4("H effective")
    e01energies=np.zeros((self.nBas*2))
    self.verbose4("writing the double basis hf energies")
    for idx in range(self.nBas*2):
        jdx=int((idx)/2)
        e01energies[idx]=self.mo_en[jdx]
        self.verbose4('%4d   %.5f'%(jdx,self.mo_en[jdx]))

    self.verbose4("writing the triple particle hf energies")
    e03energies=[]
    sigmaShoulder=np.zeros((self.nBas*2,len(self.nspace)))
    sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
    for index,element in enumerate(self.nspace):
        a=element[0]
        b=element[1]
        c=element[2]

        e03energies.append(e01energies[a]+e01energies[b]-e01energies[c])
        self.verbose4('%4d %4d %4d   %.5f'%(a,b,c,e03energies[index]))


        for jdx in range(self.nBas*2):
            sigmaShoulder[jdx,index]=self.sigma3s[jdx,a,b,c]




    h03=np.diag(np.concatenate((e01energies,e03energies)))



    selfie=np.block([
        [np.zeros((self.nBas*2,self.nBas*2)),sigmaShoulder],
        [sigmaShoulder.T,sigmaBody]
        ])

    self.heffZ=np.add(h03,selfie)
    self.verbose4("Nonzero values of effective Hamiltionian")
    if self.verbose>=4:
        for ii in range(len(self.heffZ)):
            for jj in range(len(self.heffZ)):
                if (abs(self.heffZ[ii,jj])>1e-15):
                    self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffZ[ii,jj]))

    self.HeffSBmat=np.add(h03,selfie)
    evals,evecs=self.AuxillaryFunctions.eig(np.add(h03,selfie))


    self.verbose4("Eigenvalues for H effective")
    if self.verbose>=4:
        idx = np.argsort(evals)  # use -eigvals for descending
        eigvals_sorted = evals[idx]
        eigvecs_sorted = evecs[:, idx]
        for ii in range(len(evals)):
            self.verbose4('%4d      %.5f'%(ii,eigvals_sorted[ii]))

    return evals,evecs

c2g(ind)

Source code in src/MCDE2409_parallel.py
477
478
def c2g(self,ind):
    return [ind[0],ind[2],ind[3],ind[1]]        

compute_body_block(args) staticmethod

Source code in src/MCDE2409_parallel.py
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
@staticmethod
def compute_body_block(args):
    (chunk, nspace_spatials, mo_en, nO, sparse_tol, zero_tol, sigma_func, datatype, sqrt) = args

    def check32(arr):
        prod=np.prod(arr.shape)
        res=(prod*4==arr.nbytes)
        if res:
            print("Is 32")
        else:
            print("Is not 32, its ",type(arr))
            print("Size: ",arr.nbytes)
            print("Theory: ", prod*4)
            sys.exit()

    d = lambda a,b: 1 if a==b else 0


    results = []




    prefacA1=datatype(0.5)
    prefacA2=datatype(1.5)
    sqrt2=sqrt(.5)
    sqrt3 = (sqrt(3.0) / 2.0).astype(datatype)


    for leftindex in chunk:
        i, j, l = nspace_spatials[leftindex]
        ei = mo_en[i]
        ej = mo_en[j]
        el = mo_en[l]

        fi = datatype(0) if (i >= nO) else datatype(1)
        fj = datatype(0) if (j >= nO) else datatype(1)
        fl = datatype(0) if (l >= nO) else datatype(1)
        prefac_base = datatype(-((1-fi)*(1-fj)*fl - fi*fj*(1-fl)))
        for rightindex, right in enumerate(nspace_spatials):
            m,o,k = right

            de = (ei - (el - ej)) * d(i,m)*d(j,o)*d(l,k)

            # A1

            s_ij=sqrt2**d(i,j)
            s_mo = sqrt2**d(m,o)

            A1 = s_mo * s_ij * (
                -d(l,k) * (sigma_func[i,j,o,m] + sigma_func[i,j,m,o])
                + d(m,j) * (sigma_func[i,k,l,o] - prefacA1 * sigma_func[i,k,o,l])
                + d(i,o) * (sigma_func[j,k,l,m] - prefacA1 * sigma_func[j,k,m,l])
                + d(o,j) * (sigma_func[i,k,l,m] - prefacA1 * sigma_func[i,k,m,l])
                + d(i,m) * (sigma_func[j,k,l,o] - prefacA1 * sigma_func[j,k,o,l])
            )

            # A2
            A2 = (
                -d(l,k)*(sigma_func[i,j,o,m]-sigma_func[i,j,m,o])
                -d(m,j)*(sigma_func[i,k,l,o]-prefacA2*sigma_func[i,k,o,l])
                -d(i,o)*(sigma_func[j,k,l,m]-prefacA2*sigma_func[j,k,m,l])
                +d(o,j)*(sigma_func[i,k,l,m]-prefacA2*sigma_func[i,k,m,l])
                +d(i,m)*(sigma_func[j,k,l,o]-prefacA2*sigma_func[i,k,o,l])
            )

            A2 = (
                -d(l,k) * (sigma_func[i,j,o,m] - sigma_func[i,j,m,o])
                - d(m,j) * (sigma_func[i,k,l,o] - prefacA2 * sigma_func[i,k,o,l])
                - d(i,o) * (sigma_func[j,k,l,m] - prefacA2 * sigma_func[j,k,m,l])
                + d(o,j) * (sigma_func[i,k,l,m] - prefacA2 * sigma_func[i,k,m,l])
                + d(i,m) * (sigma_func[j,k,l,o] - prefacA2 * sigma_func[j,k,o,l])
            )

            F1 = np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(
                -d(m,j)*sigma_func[i,k,o,l]
                +d(i,o)*sigma_func[j,k,m,l]
                +d(o,j)*sigma_func[i,k,m,l]
                -d(i,m)*sigma_func[j,k,o,l]
            )

            F1 = s_ij * sqrt3 * (
                -d(m,j) * sigma_func[i,k,o,l]
                + d(i,o) * sigma_func[j,k,m,l]
                + d(o,j) * sigma_func[i,k,m,l]
                - d(i,m) * sigma_func[j,k,o,l]
            )

            F2 = s_mo * sqrt3 * (
                d(m,j) * sigma_func[i,k,o,l]
                - d(i,o) * sigma_func[j,k,m,l]
                + d(o,j) * sigma_func[i,k,m,l]
                - d(i,m) * sigma_func[j,k,o,l]
            )



            A = de + prefac_base*A1
            B = prefac_base*F1
            C = prefac_base*F2
            D = de + prefac_base*A2

            if abs(A) > sparse_tol:
                results.append((2*leftindex, 2*rightindex, A))
            if abs(B) > sparse_tol:
                results.append((2*leftindex, 2*rightindex+1, B))
            if abs(C) > sparse_tol:
                results.append((2*leftindex+1, 2*rightindex, C))
            if abs(D) > sparse_tol:
                results.append((2*leftindex+1, 2*rightindex+1, D))

    return results

compute_wing_block(args) staticmethod

Source code in src/MCDE2409_parallel.py
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
@staticmethod
def compute_wing_block(args):
    (chunk, nspace_spatials, nBas, mo_en, nO, sparse_tol, zero_tol, sigma_func, datatype, sqrt) = args

    d = lambda a,b: 1 if a==b else 0


    results = []

    sqrt2=sqrt(.5)
    pref4=sqrt(3/2)
    for leftindex in chunk:
        i, j, l = nspace_spatials[leftindex]
        for rightindex,m in enumerate(np.arange(nBas)):

            pref=((sqrt2**d(i,j))*sqrt2).astype(datatype)

            S1 = sigma_func[i, j, l, m]
            S2 = sigma_func[i, j, m, l]


            C3 = pref * (S1 + S2)
            C4 = pref4 * (S1 - S2)

            if abs(C3) > sparse_tol:
                results.append((2*leftindex,rightindex,C3))
            if abs(C4) > sparse_tol:
                results.append((2*leftindex+1,rightindex,C4))

    return results

createSecondBornEffectiveHam()

Source code in src/MCDE2409_parallel.py
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
def createSecondBornEffectiveHam(self):
    self.verbose4("H effective")
    e01energies=np.zeros((self.nBas*2))
    self.verbose4("writing the double basis hf energies")
    for idx in range(self.nBas*2):
        jdx=int((idx)/2)
        e01energies[idx]=self.mo_en[jdx]
        self.verbose4('%4d   %.5f'%(jdx,self.mo_en[jdx]))

    self.verbose4("writing the triple particle hf energies")
    e03energies=[]
    sigmaShoulder=np.zeros((self.nBas*2,len(self.nspace)))
    sigmaBody=np.zeros((len(self.nspace),len(self.nspace)))
    for index,element in enumerate(self.nspace):
        a=element[0]
        b=element[1]
        c=element[2]

        e03energies.append(e01energies[a]+e01energies[b]-e01energies[c])
        self.verbose4('%4d %4d %4d   %.5f'%(a,b,c,e03energies[index]))


        for jdx in range(self.nBas*2):
            sigmaShoulder[jdx,index]=self.sigma3s[jdx,a,b,c]

    h03=np.diag(np.concatenate((e01energies,e03energies)))



    selfie=np.block([
        [np.zeros((self.nBas*2,self.nBas*2)),sigmaShoulder],
        [sigmaShoulder.T,sigmaBody]
        ])

    self.heffZ=np.add(h03,selfie)
    self.verbose4("Nonzero values of effective Hamiltionian")
    if self.verbose>=4:
        for ii in range(len(self.heffZ)):
            for jj in range(len(self.heffZ)):
                if (abs(self.heffZ[ii,jj])>1e-15):
                    self.verbose4('%4d %4d      %.5f'%(ii,jj,self.heffZ[ii,jj]))

    self.e03energies=e03energies
    self.e01energies=e01energies

    return np.add(h03,selfie)

exactDiagonalization(matrix)

Compute the exact diagonalization of a numpy.array effective Hamiltonian matrix. Returns eigenvalues and eigenvectors.

Parameters:

Name Type Description Default
matrix

effective Hamiltonian as a numpy.array (shape: (\(\lambda\),\(\lambda\)))

required

Returns:

Name Type Description
evals

sorted eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

the first nBas entries pertain to the one-particle space (shape (\(\lambda\)))

evecs

sorted column-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

the first nBas entries pertain to the one-particle space (shape (\(\lambda\),\(\lambda\)))

Source code in src/MCDE2409_parallel.py
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
def exactDiagonalization(self,matrix):
    """
    Compute the exact diagonalization of a `numpy.array` effective Hamiltonian `matrix`.
    Returns eigenvalues and eigenvectors.

    Parameters:
        matrix : effective Hamiltonian as a numpy.array (shape: ($\lambda$,$\lambda$))


    Returns:
        evals       : sorted eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$))
        evecs       : sorted column-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
    """
    evals,evecs=self.AuxillaryFunctions.eig(matrix)

    self.verbose4("Eigenvalues for H effective")
    if self.verbose>=4:
        idx = np.argsort(evals)  # use -eigvals for descending
        eigvals_sorted = evals[idx]
        # eigvecs_sorted = evecs[:, idx]
        for ii in range(len(evals)):
            self.verbose4('%4d      %.5f'%(ii,eigvals_sorted[ii]))

    return evals,evecs

exactDiagonalizationSparse(matrix)

Compute the exact diagonalization of a scipy.sparse effective Hamiltonian matrix. Returns eigenvalues and eigenvectors. If self.reduce_evecs_to_1body, the three-particle part of the eigenvectors is discarded. It only impacts the memory usage.

Parameters:

Name Type Description Default
matrix

effective Hamiltonian as a scipy.sparse csr object (shape: (\(\lambda\),\(\lambda\)))

required

Returns:

Name Type Description
evals

sorted eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

the first nBas entries pertain to the one-particle space (shape (\(\lambda\)))

evecs

sorted column-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that

the first nBas entries pertain to the one-particle space (shape (\(\lambda\),\(\lambda\)))

Source code in src/MCDE2409_parallel.py
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
def exactDiagonalizationSparse(self,matrix):
    """
    Compute the exact diagonalization of a `scipy.sparse` effective Hamiltonian `matrix`.
    Returns eigenvalues and eigenvectors.
    If `self.reduce_evecs_to_1body`, the three-particle part of the eigenvectors is discarded. It only impacts the memory usage.

    Parameters:
        matrix : effective Hamiltonian as a scipy.sparse csr object (shape: ($\lambda$,$\lambda$))


    Returns:
        evals       : sorted eigenenergies of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$))
        evecs       : sorted column-eigenvectors of effective Hamiltonian. Their size depends on the effective Hamiltonian calculated, but they all have in common that 
        the first nBas entries pertain to the one-particle space (shape ($\lambda$,$\lambda$))
    """
    vecstocalc=min(self.do_auto_sparse_basis_threshold,self.estimate_spin_opt_ham)
    self.verbose3(f"Calculating {vecstocalc} eigenvectors")
    if vecstocalc>=self.estimate_spin_opt_ham:
        evals,evecs=self.AuxillaryFunctions.eig(matrix.toarray())
    else:
        evals,evecs=scipy.sparse.linalg.eigsh(matrix,k=vecstocalc, which='LM')

    if self.reduce_evecs_to_1body:
        evecs=evecs[:self.nBas]
    self.verbose4("Eigenvalues for H effective")
    if self.verbose>=4:
        idx = np.argsort(evals)  # use -eigvals for descending
        eigvals_sorted = evals[idx]
        # eigvecs_sorted = evecs[:, idx]
        for ii in range(len(evals)):
            self.verbose4('%4d      %.5f'%(ii,eigvals_sorted[ii]))
    self.timed("Calculation of eigenvectors", 3)
    return evals,evecs

g03spaceSelection()

Source code in src/MCDE2409_parallel.py
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
def g03spaceSelection(self):
    self.verbose4("G03 space selection")
    long_ab=np.arange(0,self.nBas*2)
    # rule ijl; i>j and l is occupied MO (electron that needs to be removed)
    space=[]
    for i in long_ab:
        fi=1 if i < self.nO*2 else 0
        for j in long_ab:
            fj=1 if j < self.nO*2 else 0
            if i>j:
                for l in long_ab: 
                    fl=1 if l < self.nO*2 else 0
                    if (fi-fl)*(fj-fl) != 0:
                        space.append([i,j,l])
                        self.verbose4('%4d %4d %4d'%(i,j,l))
    return space              

g2c(ind)

Source code in src/MCDE2409_parallel.py
479
480
def g2c(self,ind):
    return [ind[0],ind[3],ind[1],ind[2]]     

g3sigma()

Source code in src/MCDE2409_parallel.py
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
def g3sigma(self):
    self.verbose4("The Sigma3 body")
    sigma3matrix=np.zeros((self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2))
    nspace=self.nspace
    for idx in range(len(nspace)):
        [i,j,l] = nspace[idx]

        fi = 0 if (i >= self.nO*2) else 1
        fj = 0 if (j >= self.nO*2) else 1
        fl = 0 if (l >= self.nO*2) else 1

        for jdx in range(len(nspace)):
            [m,o,k]=nspace[jdx]

            dlk = 1 if (l==k) else 0
            dmj = 1 if (m==j) else 0
            dio = 1 if (i==o) else 0
            doj = 1 if (o==j) else 0
            dim = 1 if (i==m) else 0

            if ((fi-fl)*(fj-fl)==0):
                continue

            prefac=((1-fi)*(1-fj)*fl-fi*fj*(1-fl))
            lkterm=dlk*self.vout[i,j,o,m]
            mjterm=dmj*self.vout[i,k,l,o]
            ioterm=dio*self.vout[j,k,l,m]
            ojterm=doj*self.vout[i,k,l,m]
            imterm=dim*self.vout[j,k,l,o]

            sigma3matrix[i, j, l, m, o, k]=prefac*(lkterm+mjterm+ioterm-ojterm-imterm)
            if (abs(sigma3matrix[i, j, l, m, o, k])>1e-15):
                self.compare.append([str(i),str(j),str(l),str(m),str(o),str(k),f"{sigma3matrix[i, j, l, m, o, k]:.4f}"])
                self.verbose4('%4d %4d %4d %4d %4d %4d      %.5f'%(i,j,l,m,o,k,sigma3matrix[i, j, l, m, o, k]))

    return sigma3matrix

getTopContributionsIn1Evec(eigen, evecs0, topN=10, ao_labels=None, secondBorn=None, roundingLevel=5)

Determine the dominant one-particle contributions to effective Hamiltonian eigenvectors.

For each eigenvector, the squared amplitudes :math:|c_i|^2 of the basis-state coefficients are computed and sorted in descending order. The topN largest contributions are retained for each eigenvector. Eigenvectors with degenerate (or nearly degenerate) eigenenergies are grouped according to their energy rounded to roundingLevel decimal places, and contributions from all eigenvectors in the group are summed.

Unlike :meth:getTopContributionsInEvec, the summed contributions are not normalized. The results are returned as sorted lists of basis-state labels and their associated weights.

Parameters

eigen : numpy.ndarray Eigenenergies of the effective Hamiltonian with shape (N,).

numpy.ndarray

Matrix of eigenvectors of the effective Hamiltonian. The expected shape is (N, N) with eigenvectors stored as columns. Internally, the matrix is transposed such that individual eigenvectors are processed row-wise.

int, optional

Number of largest basis-state contributions retained for each eigenvector. If topN <= 0, all contributions are retained. Default is 10.

list[str] | None, optional

Atomic-orbital labels. Currently unused by this method but retained for interface compatibility. Default is None.

bool | None, optional

If None, the value of self.secondBorn is used. Currently unused in the returned result but retained for interface compatibility. Default is None.

int, optional

Number of decimal places used when grouping nearly degenerate eigenenergies. Default is 5.

Returns

dict[float, list[tuple[str, float]]] Dictionary mapping rounded eigenenergies to sorted lists of (label, weight) pairs.

The outer dictionary has the form

.. code-block:: python

    {
        energy_1: [
            ("label_1", weight_1),
            ("label_2", weight_2),
            ...
        ],
        energy_2: [
            ("label_1", weight_1),
            ("label_2", weight_2),
            ...
        ],
        ...
    }

where the labels correspond to basis-state occupations returned by
``self.nspace_spatials_MCDE.returnNumLabels`` and the weights are summed
contributions :math:`|c_i|^2`.
Notes

Eigenvectors are grouped according to energies rounded to roundingLevel decimal places.

The returned weights are not normalized. Consequently, the total weight associated with a given energy depends on both the number of grouped eigenvectors and the retained contributions.

If topN <= 0, all basis-state contributions are retained before grouping.

Source code in src/MCDE2409_parallel.py
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
def getTopContributionsIn1Evec(self, eigen, evecs0, topN=10, ao_labels=None, secondBorn=None, roundingLevel=5):
    """
    Determine the dominant one-particle contributions to effective Hamiltonian eigenvectors.

    For each eigenvector, the squared amplitudes :math:`|c_i|^2` of the basis-state
    coefficients are computed and sorted in descending order. The `topN` largest
    contributions are retained for each eigenvector. Eigenvectors with degenerate
    (or nearly degenerate) eigenenergies are grouped according to their energy
    rounded to `roundingLevel` decimal places, and contributions from all
    eigenvectors in the group are summed.

    Unlike :meth:`getTopContributionsInEvec`, the summed contributions are not
    normalized. The results are returned as sorted lists of basis-state labels and
    their associated weights.

    Parameters
    -----
    eigen : numpy.ndarray
        Eigenenergies of the effective Hamiltonian with shape `(N,)`.

    evecs0 : numpy.ndarray
        Matrix of eigenvectors of the effective Hamiltonian. The expected shape is
        `(N, N)` with eigenvectors stored as columns. Internally, the matrix is
        transposed such that individual eigenvectors are processed row-wise.

    topN : int, optional
        Number of largest basis-state contributions retained for each eigenvector.
        If `topN <= 0`, all contributions are retained. Default is `10`.

    ao_labels : list[str] | None, optional
        Atomic-orbital labels. Currently unused by this method but retained for
        interface compatibility. Default is `None`.

    secondBorn : bool | None, optional
        If `None`, the value of `self.secondBorn` is used. Currently unused in
        the returned result but retained for interface compatibility.
        Default is `None`.

    roundingLevel : int, optional
        Number of decimal places used when grouping nearly degenerate
        eigenenergies. Default is `5`.

    Returns
    -----
    dict[float, list[tuple[str, float]]]
        Dictionary mapping rounded eigenenergies to sorted lists of
        `(label, weight)` pairs.

    ```
    The outer dictionary has the form

    .. code-block:: python

        {
            energy_1: [
                ("label_1", weight_1),
                ("label_2", weight_2),
                ...
            ],
            energy_2: [
                ("label_1", weight_1),
                ("label_2", weight_2),
                ...
            ],
            ...
        }

    where the labels correspond to basis-state occupations returned by
    ``self.nspace_spatials_MCDE.returnNumLabels`` and the weights are summed
    contributions :math:`|c_i|^2`.
    ```

    Notes
    -----
    Eigenvectors are grouped according to energies rounded to
    `roundingLevel` decimal places.

    The returned weights are not normalized. Consequently, the total weight
    associated with a given energy depends on both the number of grouped
    eigenvectors and the retained contributions.

    If `topN <= 0`, all basis-state contributions are retained before
    grouping.
    """

    if secondBorn==None:
        secondBorn=self.secondBorn

    evecs0 = evecs0.T
    if ao_labels is not None:
        ao_labels = [lbl.rstrip() for lbl in ao_labels]



    MINVEC = 0
    MAXVEC = len(evecs0)

    # Dictionary: rounded_energy → list of contribution dicts
    # Each dict: { index : magnitude }
    grouped = defaultdict(list)

    for i in range(MINVEC, MAXVEC):
         eigval = eigen[i]
         evec = evecs0[i]

         # 1. Take probabilities |c|² for the eigenvector
         probs = np.abs(evec) ** 2

         # 2. Put (prob, index) pairs and take the top N
         pairs = list(zip(probs, range(len(probs))))
         pairs.sort(reverse=True, key=lambda x: x[0])
         top=pairs[:topN] if topN>0 else pairs[:]

         # 3. Build structure: [eigval, (prob1, idx1), ...]
         rounded_energy = round(float(eigval), roundingLevel)  # rounding level adjustable
         # rounded_energy = eigval  # rounding level adjustable

         # 4. Store this eigenvector's contributions
         contrib_dict = {idx: prob for prob, idx in top}
         grouped[rounded_energy].append(contrib_dict)


    # 5. Sum + normalize contributions for each degenerate energy
    result = {}

    for energy, contrib_list in grouped.items():
        combined = defaultdict(float)

        # Sum contributions of all eigenvectors belonging to this energy
        for contrib in contrib_list:
            for idx, mag in contrib.items():
                combined[idx] += mag

        # Normalize
        # norm = sum(combined.values())
        # if norm > 0:
        #     for k in combined:
        #         combined[k] /= norm
        sorted_items = sorted(
            combined.items(),
            key=lambda x: x[1],
            reverse=True
        )

        result[energy] = [
            (self.nspace_spatials_MCDE.returnNumLabels(idx), val)
            for idx, val in sorted_items
        ]
        # result[energy] = dict(
        #     sorted(
        #         (
        #             (self.nspace_spatials_MCDE.returnNumLabels(idx), val)
        #             for idx, val in combined.items()
        #         ),
        #         key=lambda x: x[1],
        #         reverse=True
        #     )
        # )

    # if ao_labels is not None:
    #     if not secondBorn:
    #         for energy in result:
    #             result[energy] = {self.nspace_spatials_MCDE.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
    #     else:
    #         for energy in result:
    #             result[energy] = {self.nspace_spatials_SB.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
    # else:
    #     for energy in result:
    #         result[energy] = {self.nspace_spatials_MCDE.returnNumLabels(idx): val for idx, val in result[energy].items()}
    return result

getTopContributionsInEvec(eigen, evecs0, ao_labels=None, secondBorn=None, topN=3, MINVEC=-1, MAXVEC=-1, roundingLevel=5)

Determine the dominant basis-state contributions to effective Hamiltonian eigenvectors.

For each eigenvector, the squared amplitudes :math:|c_i|^2 of the basis-state coefficients are computed and the topN largest contributions are retained. Eigenvectors with degenerate (or nearly degenerate) eigenenergies are grouped according to their energy rounded to roundingLevel decimal places. The contributions of all eigenvectors within a group are summed and normalized.

The resulting assignments can be returned either in terms of basis-state indices or translated to atomic-orbital labels if ao_labels is provided.

Parameters

eigen : numpy.ndarray Eigenenergies of the effective Hamiltonian with shape (N,).

numpy.ndarray

Matrix of eigenvectors of the effective Hamiltonian. The expected shape is (N, N) with eigenvectors stored as columns. Internally, the matrix is transposed such that individual eigenvectors are processed row-wise.

list[str] | None, optional

Atomic-orbital labels used to translate basis-state indices into a human-readable representation. If None, numerical labels are returned. Default is None.

bool | None, optional

Whether the Second-Born basis-space mapping should be used when translating basis-state indices. If None, the value of self.secondBorn is used. Default is None.

int, optional

Number of largest basis-state contributions retained for each eigenvector. Default is 3.

int, optional

Index of the first eigenvector to analyze. If negative, analysis starts from the first eigenvector. Default is -1.

int, optional

Index one past the last eigenvector to analyze. If negative, all eigenvectors are included. Default is -1.

int, optional

Number of decimal places used when grouping nearly degenerate eigenenergies. Default is 5.

Returns

dict[float, dict] Dictionary mapping rounded eigenenergies to normalized contribution dictionaries.

The outer dictionary has the form

.. code-block:: python

    {
        energy_1: {label_1: weight_1, label_2: weight_2, ...},
        energy_2: {label_1: weight_1, label_2: weight_2, ...},
        ...
    }

where the weights correspond to normalized summed contributions
:math:`|c_i|^2` of the dominant basis states.
Notes

Only the topN largest contributions of each eigenvector are retained before grouping and normalization. Consequently, the returned weights represent the relative importance of the dominant basis states rather than the complete decomposition of the eigenvector.

Degeneracies are identified by rounding eigenenergies to roundingLevel decimal places.

Source code in src/MCDE2409_parallel.py
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
def getTopContributionsInEvec(self, eigen, evecs0, ao_labels=None, secondBorn=None,topN=3, MINVEC=-1, MAXVEC=-1,roundingLevel=5):
    """
    Determine the dominant basis-state contributions to effective Hamiltonian eigenvectors.

    For each eigenvector, the squared amplitudes :math:`|c_i|^2` of the basis-state
    coefficients are computed and the ``topN`` largest contributions are retained.
    Eigenvectors with degenerate (or nearly degenerate) eigenenergies are grouped
    according to their energy rounded to ``roundingLevel`` decimal places. The
    contributions of all eigenvectors within a group are summed and normalized.

    The resulting assignments can be returned either in terms of basis-state
    indices or translated to atomic-orbital labels if ``ao_labels`` is provided.

    Parameters
    ----------
    eigen : numpy.ndarray
        Eigenenergies of the effective Hamiltonian with shape ``(N,)``.

    evecs0 : numpy.ndarray
        Matrix of eigenvectors of the effective Hamiltonian. The expected shape is
        ``(N, N)`` with eigenvectors stored as columns. Internally, the matrix is
        transposed such that individual eigenvectors are processed row-wise.

    ao_labels : list[str] | None, optional
        Atomic-orbital labels used to translate basis-state indices into a
        human-readable representation. If ``None``, numerical labels are returned.
        Default is ``None``.

    secondBorn : bool | None, optional
        Whether the Second-Born basis-space mapping should be used when
        translating basis-state indices. If ``None``, the value of
        ``self.secondBorn`` is used. Default is ``None``.

    topN : int, optional
        Number of largest basis-state contributions retained for each eigenvector.
        Default is ``3``.

    MINVEC : int, optional
        Index of the first eigenvector to analyze. If negative, analysis starts
        from the first eigenvector. Default is ``-1``.

    MAXVEC : int, optional
        Index one past the last eigenvector to analyze. If negative, all
        eigenvectors are included. Default is ``-1``.

    roundingLevel : int, optional
        Number of decimal places used when grouping nearly degenerate
        eigenenergies. Default is ``5``.

    Returns
    -------
    dict[float, dict]
        Dictionary mapping rounded eigenenergies to normalized contribution
        dictionaries.

        The outer dictionary has the form

        .. code-block:: python

            {
                energy_1: {label_1: weight_1, label_2: weight_2, ...},
                energy_2: {label_1: weight_1, label_2: weight_2, ...},
                ...
            }

        where the weights correspond to normalized summed contributions
        :math:`|c_i|^2` of the dominant basis states.

    Notes
    -----
    Only the ``topN`` largest contributions of each eigenvector are retained
    before grouping and normalization. Consequently, the returned weights
    represent the relative importance of the dominant basis states rather than
    the complete decomposition of the eigenvector.

    Degeneracies are identified by rounding eigenenergies to
    ``roundingLevel`` decimal places.
    """

    if secondBorn==None:
        secondBorn=self.secondBorn

    evecs0 = evecs0.T
    if ao_labels is not None:
        ao_labels = [lbl.rstrip() for lbl in ao_labels]

    if MINVEC < 0:
        MINVEC = 0
    if MAXVEC < 0:
        MAXVEC = len(evecs0)

    # Dictionary: rounded_energy → list of contribution dicts
    # Each dict: { index : magnitude }
    grouped = defaultdict(list)

    for i in range(MINVEC, MAXVEC):

        eigval = eigen[i]
        evec = evecs0[i]

        # 1. Take probabilities |c|² for the eigenvector
        probs = np.abs(evec) ** 2

        # 2. Put (prob, index) pairs and take the top N
        pairs = list(zip(probs, range(len(probs))))
        pairs.sort(reverse=True, key=lambda x: x[0])
        top = pairs[:topN]

        # 3. Build structure: [eigval, (prob1, idx1), ...]
        rounded_energy = round(float(eigval), roundingLevel)  # rounding level adjustable

        # 4. Store this eigenvector's contributions
        contrib_dict = {idx: prob for prob, idx in top}
        grouped[rounded_energy].append(contrib_dict)

    # 5. Sum + normalize contributions for each degenerate energy
    result = {}

    for energy, contrib_list in grouped.items():
        combined = defaultdict(float)

        # Sum contributions of all eigenvectors belonging to this energy
        for contrib in contrib_list:
            for idx, mag in contrib.items():
                combined[idx] += mag

        # Normalize
        norm = sum(combined.values())
        if norm > 0:
            for k in combined:
                combined[k] /= norm

        result[energy] = dict(combined)

    if ao_labels is not None:
        if not secondBorn:
            for energy in result:
                result[energy] = {self.nspace_spatials_MCDE.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
        else:
            for energy in result:
                result[energy] = {self.nspace_spatials_SB.translateToAOLabels(idx,ao_labels): val for idx, val in result[energy].items()}
    else:
        for energy in result:
            result[energy] = {self.nspace_spatials_MCDE.returnNumLabels(idx): val for idx, val in result[energy].items()}
    return result

kernel()

Source code in src/MCDE2409_parallel.py
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
def kernel(self):

    self.verbose2("kernel start")
    self.verbose2(f"MCDE? {self.mcde}") # compute MCDE calculation
    self.verbose2(f"Second Born? {self.secondBorn}") # compute SB calculation
    self.verbose3(f"Spin Adapted Ham? {self.spinOptimized}") # do a spinoptimized calculation
    self.verbose3(f"Remove isolated diagonals from spin adapted Ham? {self.remove_single_values}") #removes isolated diagonals from effective Hamiltonian
    self.verbose3(f"Full eff Ham? {self.fullCalculation}") # do the full double basis hamiltonian
    self.verbose3(f"Effective Hamiltonian tolerance: {self.zero_tol}") #when values should be set to zero in the effective Hamiltonian

    if self.shift_virtual_energy != 0:
        self.verbose3(f"Shift of 3p virtual QP: {self.shift_virtual_energy}")

    if self.lanczos:
        self.verbose3(f"Lanczos algorithm? {self.lanczos}") # do lanczos algorithm
        self.verbose3(f"Lanczos convergence: {self.lanczos_tol}")#tolerance of Lanczos convergence

    if self.exactDiag:
        self.verbose3(f"Exact diagonalization? {self.exactDiag}") # do exact diagonalization
        self.verbose3(f"Eigenvalue tolerance: {self.zero_tol_evals}") #when values should be set to zero in the eigenvalues
        self.verbose3(f"Reduce eigenvectors to 1body part: {self.reduce_evecs_to_1body}") #only one body part needed for plotting

    if self.do_auto_sparse:
        if self.do_auto_sparse_basis_threshold<self.estimate_spin_opt_ham:
            self.do_sparse=True
            self.verbose3(f"Sparse method activated since basis size {self.estimate_spin_opt_ham} is larger than threshold {self.do_auto_sparse_basis_threshold}")
        else:
            self.verbose3(f"Sparse method: {self.do_sparse}")
    if self.do_sparse:
        self.verbose3(f"Sparse tolerance: {self.sparse_tol}")
        self.verbose3(f"sparse matrix datatype: {self.data_type_sparse}")

    if not self.do_sparse:    
        self.vout=self.vbar()
    self.nspace = self.g03spaceSelection()
    secondBorn=self.secondBorn
    calcMCDE=self.mcde
    full = self.fullCalculation
    exactdiag=self.exactDiag
    lanczos=self.lanczos
    spinOptimized=self.spinOptimized

    if full:
        self.sigma3s=self.sigma3shoulder()
        self.HeffSBmat=self.createSecondBornEffectiveHam()
        if calcMCDE:
            self.sigma3=self.g3sigma()
            # sets self.HeffMCDEmat
            self.HeffMCDE()
            if exactdiag:
                self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs=self.exactDiagonalization(self.HeffMCDEmat)
            if lanczos:
                self.HeffMCDEAcoeff,self.HeffMCDEBcoeff=self.LanczosAlgorithm(self.HeffMCDEmat,self.nBas*2)
        if secondBorn:
            self.HeffSecondBorn()
            if exactdiag:
                self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs=self.exactDiagonalization(self.HeffSBmat)
            if lanczos:
                self.HeffSBAcoeff,self.HeffSBBcoeff=self.LanczosAlgorithm(self.HeffSBmat,self.nBas*2)

    #spin free variant
    if spinOptimized:
        if not self.do_sparse:
            if secondBorn:
                self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat=self.spinAdaptedMCDE(secondBorn)
                if exactdiag:
                    self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs=self.exactDiagonalization(self.HeffMCDESpinAdaptmat)
                    self.HeffSBSpinAdaptExactDiagEvals,self.HeffSBSpinAdaptExactDiagEvecs=self.exactDiagonalization(self.HeffSBSpinAdaptmat)
                if lanczos:
                    self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff=self.LanczosAlgorithm(self.HeffMCDESpinAdaptmat,self.nBas)
                    self.HeffSBSpinAdaptAcoeff,self.HeffSBSpinAdaptBcoeff=self.LanczosAlgorithm(self.HeffSBSpinAdaptmat,self.nBas)
            else:
                self.HeffMCDESpinAdaptmat=self.spinAdaptedMCDE(secondBorn)
                if exactdiag:
                    self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs=self.exactDiagonalization(self.HeffMCDESpinAdaptmat)
                if lanczos:
                    self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff=self.LanczosAlgorithm(self.HeffMCDESpinAdaptmat,self.nBas)
        else:
            if secondBorn and calcMCDE:
                self.HeffMCDESpinAdaptSparsemat,self.HeffSBSpinAdaptSparsemat=self.spinAdaptedMCDESparse(secondBorn)
                if exactdiag:
                    self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffMCDESpinAdaptSparsemat)
                    self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffSBSpinAdaptSparsemat)
            elif secondBorn and not calcMCDE:
                self.HeffSBSpinAdaptSparsemat=self.spinAdaptedMCDESparse(secondBorn)
                if exactdiag:                    
                    self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffSBSpinAdaptSparsemat)
            elif calcMCDE and not secondBorn:
                self.HeffMCDESpinAdaptSparsemat=self.spinAdaptedMCDESparse(secondBorn)
                if exactdiag:
                    self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs=self.exactDiagonalizationSparse(self.HeffMCDESpinAdaptSparsemat)
    self.kernel_run=True
    self.timed("kernel end", 2)
    self.verbose1("_________________________")
    self.verbose1("_________________________")

loadMCDE(filename) staticmethod

Source code in src/MCDE2409_parallel.py
470
471
472
473
474
@staticmethod        
def loadMCDE(filename):
    data = np.load(filename+".npz", allow_pickle=True)
    print("MCDE object loaded from " + filename+".npz")
    return data['mcde'].item()                

result()

Source code in src/MCDE2409_parallel.py
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
def result(self):
    if not self.kernel_run:
        raise ValueError("kernel() not run")
    secondBorn=self.secondBorn
    calcMCDE=self.mcde
    full = self.fullCalculation
    exactdiag=self.exactDiag
    lanczos=self.lanczos
    spinOptimized=self.spinOptimized

    if full:
        if calcMCDE and secondBorn:
            if exactdiag and lanczos:
                return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffMCDEmat,self.HeffSBmat
            if exactdiag:
                return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffMCDEmat,self.HeffSBmat
            if lanczos:
                return self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffMCDEmat,self.HeffSBmat
            return self.HeffMCDEmat,self.HeffSBmat
        if calcMCDE:
            if exactdiag and lanczos:
                return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffMCDEmat
            if exactdiag:
                return self.HeffMCDEExactDiagEvals,self.HeffMCDEExactDiagEvecs,self.HeffMCDEmat
            if lanczos:
                return self.HeffMCDEAcoeff,self.HeffMCDEBcoeff,self.HeffMCDEmat
            return self.HeffMCDEmat
        if secondBorn:
            if exactdiag and lanczos:
                return self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffSBmat
            if exactdiag:
                return self.HeffSBxactDiagEvals,self.HeffSBxactDiagEvecs,self.HeffSBmat
            if lanczos:
                return self.HeffSBAcoeff,self.HeffSBBcoeff,self.HeffSBmat
            return self.HeffSBmat

    #spin free variant
    if spinOptimized:
        if not self.do_sparse:
            if secondBorn:
                if exactdiag:
                    return self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs,self.HeffSBSpinAdaptExactDiagEvals,self.HeffSBSpinAdaptExactDiagEvecs,self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat
                if lanczos:
                    return self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff,self.HeffSBSpinAdaptAcoeff,self.HeffSBSpinAdaptBcoeff,self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat
                return self.HeffMCDESpinAdaptmat,self.HeffSBSpinAdaptmat
            if calcMCDE:
                if exactdiag:
                    return self.HeffMCDESpinAdaptExactDiagEvals,self.HeffMCDESpinAdaptExactDiagEvecs,self.HeffMCDESpinAdaptmat
                if lanczos:
                    return self.HeffMCDESpinAdaptAcoeff,self.HeffMCDESpinAdaptBcoeff,self.HeffMCDESpinAdaptmat
                return self.HeffMCDESpinAdaptmat
        else:
            if secondBorn and calcMCDE:
                if exactdiag:
                    return self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs,self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs,self.HeffMCDESpinAdaptSparsemat,self.HeffSBSpinAdaptSparsemat
                return self.HeffMCDESpinAdaptSparsemat,self.HeffSBSpinAdaptSparsemat
            if calcMCDE and not secondBorn:
                if exactdiag:
                    return self.HeffMCDESpinAdaptSparseEvals,self.HeffMCDESpinAdaptSparseEvecs,self.HeffMCDESpinAdaptSparsemat
                return self.HeffMCDESpinAdaptSparsemat
            if secondBorn and not calcMCDE:
                if exactdiag:
                    return self.HeffSBSpinAdaptSparseEvals,self.HeffSBSpinAdaptSparseEvecs,self.HeffSBSpinAdaptSparsemat
                return self.HeffSBSpinAdaptSparsemat

saveMCDE(filename=None)

Source code in src/MCDE2409_parallel.py
463
464
465
466
467
468
def saveMCDE(self,filename=None):

    if filename is None:
        filename=str(time.time())
    np.savez(filename+".npz",mcde=self)
    self.verbose2("MCDE object saved to " + filename+".npz")

sigma3shoulder()

Source code in src/MCDE2409_parallel.py
650
651
652
653
654
655
656
657
658
659
660
661
662
def sigma3shoulder(self):
    self.verbose4("The Sigma3 shoulder")
    sigma3s=np.zeros((self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2))
    nspace=self.nspace
    for i in range(self.nBas*2):
        for idx in range(len(nspace)):
            [m,o,k] = nspace[idx]
            sigma3s[i, m, o, k]=self.vout[i,k,o,m]
            self.verbose4('%4d %4d %4d %4d      %.5f'%(i,m,o,k,sigma3s[i, m, o, k]))
            if (abs(sigma3s[i, m, o, k])>1e-15):
                self.compareshoulder.append([str(i),str(m),str(o),str(k),f"{sigma3s[i, m, o, k]:.4f}"])
                self.verbose4('%4d %4d %4d %4d      %.5f'%(i,m,o,k,sigma3s[i, m, o, k]))
    return sigma3s

sigma_mo_gabi(i, k, o, m)

Source code in src/MCDE2409_parallel.py
507
508
509
def sigma_mo_gabi(self,i,k,o,m):
    # return self.eri_mo_gabi[i,k,o,m]-self.eri_mo_gabi[i,k,m,o]
    return self.eri_mo_gabi[i,k,o,m]

sigma_mo_gabi_W(i, k, o, m)

Source code in src/MCDE2409_parallel.py
511
512
513
def sigma_mo_gabi_W(self,i,k,o,m):
    # return self.eri_mo_gabi[i,k,o,m]-self.eri_mo_gabi[i,k,m,o]
    return self.eri_mo_gabi_W[i,k,o,m]

sparkurs()

Source code in src/MCDE2409_parallel.py
277
278
279
280
def sparkurs(self):
    self.exactDiag=False
    self.data_type_sparse=np.float32
    self.do_sparse=True

spinAdaptedMCDE(secondBorn=False)

Source code in src/MCDE2409_parallel.py
 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
def spinAdaptedMCDE(self,secondBorn=False):

    self.verbose3("Spin transformed MCDE")
    self.verbose3("Second Born? "+str(secondBorn))

    def d(a,b):
        return 1 if a==b else 0


    #transform spinorbitals to spatial orbitals
    nspace_spatials0=[]
    for entry in self.nspace:
        nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
    #remove duplicates
    seen = set()
    nspace_spatials = []
    for item in nspace_spatials0:
        t = tuple(item)
        if t not in seen:
            seen.add(t)
            nspace_spatials.append(item)

    #initialize 1part+3part nspace index
    spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

    self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
    self.verbose4(nspace_spatials)
    ray=[]
    for i in range(self.nBas):
        ray.append(self.mo_en[i])
    head=np.diag(ray)

    #create wing

    wing=np.zeros((len(nspace_spatials)*2,len(ray)))

    for leftindex,left in enumerate(nspace_spatials):
        [i,j,l]=left
        for rightindex,m in enumerate(np.arange(self.nBas)):
            C3=np.sqrt(.5)**(d(i,j))*np.sqrt(.5)*(self.sigma_mo_gabi(i,j,l,m)+self.sigma_mo_gabi(i,j,m,l))
            C4=np.sqrt(3/2)*(self.sigma_mo_gabi(i,j,l,m)-self.sigma_mo_gabi(i,j,m,l))

            wing[2*leftindex,rightindex]=C3
            wing[2*leftindex+1,rightindex]=C4

    #create body matrix

    body=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
    # bodyHF=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
    for leftindex,left in enumerate(nspace_spatials):
        [i,j,l]=left

        for rightindex,right in enumerate(nspace_spatials):
            [m,o,k]=right


            A1=np.sqrt(.5)**(d(m,o))*np.sqrt(.5)**(d(i,j))*(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)+self.sigma_mo_gabi(i,j,m,o))
                                                          +d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-.5*self.sigma_mo_gabi(i,k,o,l))
                                                          +d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-.5*self.sigma_mo_gabi(j,k,m,l))
                                                          +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-.5*self.sigma_mo_gabi(i,k,m,l))
                                                          +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-.5*self.sigma_mo_gabi(j,k,o,l)))
            A2=(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)-self.sigma_mo_gabi(i,j,m,o))
                                                          -d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-1.5*self.sigma_mo_gabi(i,k,o,l))
                                                          -d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-1.5*self.sigma_mo_gabi(j,k,m,l))
                                                          +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-1.5*self.sigma_mo_gabi(i,k,m,l))
                                                          +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-1.5*self.sigma_mo_gabi(j,k,o,l)))
            F1=np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(-d(m,j)*self.sigma_mo_gabi(i,k,o,l)+d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                  +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                  -d(i,m)*self.sigma_mo_gabi(j,k,o,l))
            F2=np.sqrt(.5)**(d(m,o))*(np.sqrt(3)/2)*(d(m,j)*self.sigma_mo_gabi(i,k,o,l)-d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                  +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                  -d(i,m)*self.sigma_mo_gabi(j,k,o,l))


            fi = 0 if (i >= self.nO) else 1
            fj = 0 if (j >= self.nO) else 1
            fl = 0 if (l >= self.nO) else 1
            prefac=-((1-fi)*(1-fj)*fl-fi*fj*(1-fl))

            ei=self.mo_en[i]
            ej=self.mo_en[j]
            el=self.mo_en[l]
            de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


            body[2*leftindex,2*rightindex]=de+prefac*A1
            body[2*leftindex,2*rightindex+1]=prefac*F1
            body[2*leftindex+1,2*rightindex]=prefac*F2
            body[2*leftindex+1,2*rightindex+1]=de+prefac*A2

            # bodyHF[2*leftindex,2*rightindex]=de
            # bodyHF[2*leftindex+1,2*rightindex+1]=de

    if secondBorn:
        bodySB=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))

        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left

            for rightindex,right in enumerate(nspace_spatials):
                [m,o,k]=right


                ei=self.mo_en[i]
                ej=self.mo_en[j]
                el=self.mo_en[l]
                de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


                bodySB[2*leftindex,2*rightindex]=de
                bodySB[2*leftindex,2*rightindex+1]=0
                bodySB[2*leftindex+1,2*rightindex]=0
                bodySB[2*leftindex+1,2*rightindex+1]=de

    H3upd=np.block([[head,np.transpose(wing)],[wing,body]])



    H3upd=np.where(np.abs(H3upd) < self.zero_tol, 0.0, H3upd)

    if secondBorn:
        H3SB=np.block([[head,np.transpose(wing)],[wing,bodySB]])
        H3SB=np.where(np.abs(H3SB) < self.zero_tol, 0.0, H3SB)
        H3SB,self.nspace_spatials_SB=self.AuxillaryFunctions.remove_isolated_diagonals(H3SB,spaceObj,self.remove_single_values)


    H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals(H3upd,spaceObj,self.remove_single_values)



    self.timed("Creating spin Opt eff. Hamiltonian",2)

    if secondBorn:
        return H3upd,H3SB
    return H3upd

spinAdaptedMCDEFullChunks(secondBorn=False)

Source code in src/MCDE2409_parallel.py
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
def spinAdaptedMCDEFullChunks(self,secondBorn=False):
    self.verbose3("Full MCDE Chunks")
    self.verbose3("Second Born? "+str(secondBorn))

    datatype=self.data_type_sparse
    NBAS=2*self.nBas
    NO=2*self.nO
    #  small number
    def sqrt(x):
        return np.sqrt(x).astype(datatype)

    def check32(arr):
        prod=np.prod(arr.shape)
        res=(prod*4==arr.nbytes)
        if res:
            print("Is 32")
        else:
            print("Is not 32, its ",type(arr))
            print("Size: ",arr.nbytes)
            print("Theory: ", prod*4)
            sys.exit()

    def check16(arr):
        return None
        prod=np.prod(arr.shape)
        res=(prod*2==arr.nbytes)
        if res:
            print("Is 16")
        else:
            print("Is not 16, its ",type(arr))
            print("Size: ",arr.nbytes)
            print("Theory: ", prod*2)
            sys.exit()



    nspace3particle = np.array(self.nspace)   # shape (N,3)
    spaceObj=MCDE.Nspace(np.arange(NBAS),self.nspace)

    # head
    ray=[]
    for i in range(NBAS):
        ray.append(self.mo_en[i//2])
    head=np.diag(ray).astype(datatype)

    # check32(head)

    nBasspace=np.arange(NBAS)
    mwing = nBasspace[:,None]

    N = len(nspace3particle)

    chunk_size = max(N//100,2)
    chunk_size = 5000 if chunk_size > 5000 else chunk_size
    chunk_size = 1
    nchunks = [
        (i, i + len(nspace3particle[i:i+chunk_size]), nspace3particle[i:i+chunk_size])
        for i in range(0, len(nspace3particle), chunk_size)
    ]



    def speedUpCore(nspaceL,nspaceR):

        body_out = None

        i = nspaceL[:, 0]
        j = nspaceL[:, 1]
        l = nspaceL[:, 2]

        m = nspaceR[:, 0]
        o = nspaceR[:, 1]
        k = nspaceR[:, 2]

        iL = i[:, None]
        jL = j[:, None]
        lL = l[:, None]

        mR = m[None, :]
        oR = o[None, :]
        kR = k[None, :]

        dim = (iL == mR).astype(datatype)
        djo = (jL == oR).astype(datatype)
        dlk = (lL == kR).astype(datatype)

        dmj = (mR == jL).astype(datatype)
        dio = (iL == oR).astype(datatype)
        doj = (oR == jL).astype(datatype)

        ei = self.mo_en[i//2].astype(datatype)
        ej = self.mo_en[j//2].astype(datatype)
        el = self.mo_en[l//2].astype(datatype)

        eiL = ei[:, None]
        ejL = ej[:, None]
        elL = el[:, None]

        # check16(dlk)

        de = ((eiL - (elL - ejL)) * dim * djo * dlk).astype(datatype)

        # check32(de)
        #memory expensive!

        sigma=self.eri_mo_gabi.astype(datatype)


        # S_ijom = (iL%2 == mR%2 or jL%2 == oR%2)*sigma[iL, jL, oR, mR].astype(datatype)
        # S_ijmo = (iL%2 == oR%2 or jL%2 == mR%2)*sigma[iL, jL, mR, oR].astype(datatype)
        # S_iklo = (iL%2 == oR%2 or lL%2 == kR%2)*sigma[iL, kR, lL, oR].astype(datatype)
        # S_ikol = (iL%2 == lL%2 or oR%2 == kR%2)*sigma[iL, kR, oR, lL].astype(datatype)
        # S_jklm = (jL%2 == mR%2 or lL%2 == kR%2)*sigma[jL, kR, lL, mR].astype(datatype)
        # S_jkml = (jL%2 == lL%2 or mR%2 == kR%2)*sigma[jL, kR, mR, lL].astype(datatype)
        # S_iklm = (iL%2 == mR%2 or lL%2 == kR%2)*sigma[iL, kR, lL, mR].astype(datatype)
        # S_ikml = (iL%2 == lL%2 or mR%2 == kR%2)*sigma[iL, kR, mR, lL].astype(datatype)
        # S_jklo = (jL%2 == oR%2 or kR%2 == lL%2)*sigma[jL, kR, lL, oR].astype(datatype)
        # S_jkol = (jL%2 == lL%2 or kR%2 == oR%2)*sigma[jL, kR, oR, lL].astype(datatype)

        dividefactor=2
        S_1 = (((iL%2 + mR%2 + jL%2 + oR%2)%2==0)     
               *(((iL % 2 == mR % 2) | (jL % 2 == oR % 2))
                                               *sigma[iL//dividefactor, jL//dividefactor, oR//dividefactor, mR//dividefactor]-
                                               ((iL % 2 == oR % 2) | (jL % 2 == mR % 2))*sigma[iL//dividefactor, jL//dividefactor, mR//dividefactor, oR//dividefactor])).astype(datatype)
        S_2 = (((iL%2 + kR%2 + lL%2 + oR%2)%2==0)
               *(((iL % 2 == oR % 2) | (lL % 2 == kR % 2))*sigma[iL//dividefactor, kR//dividefactor, lL//dividefactor, oR//dividefactor]-
                                               ((iL % 2 == kR % 2) | (lL % 2 == oR % 2))*sigma[iL//2, kR//dividefactor, oR//dividefactor, lL//dividefactor])).astype(datatype)
        S_3 = (((jL%2 + kR%2 + lL%2 + mR%2)%2==0)
               *(((jL % 2 == mR % 2) | (lL % 2 == kR % 2))*sigma[jL//dividefactor, kR//dividefactor, lL//dividefactor, mR//dividefactor]-
                                               ((jL % 2 == lL % 2) | (mR % 2 == kR % 2))*sigma[jL//dividefactor, kR//dividefactor, mR//dividefactor, lL//dividefactor])).astype(datatype)
        S_4 = (((iL%2 + kR%2 + lL%2 + mR%2)%2==0)
               *(((iL % 2 == mR % 2) | (lL % 2 == kR % 2))*sigma[iL//dividefactor, kR//dividefactor, lL//dividefactor, mR//dividefactor]-
                                               ((iL % 2 == lL % 2) | (mR % 2 == kR % 2))*sigma[iL//dividefactor, kR//dividefactor, mR//dividefactor, lL//dividefactor])).astype(datatype)
        S_5 = (((jL%2 + kR%2 + lL%2 + oR%2)%2==0)
               *(((jL % 2 == oR % 2) | (lL % 2 == kR % 2))*sigma[jL//dividefactor, kR//dividefactor, lL//dividefactor, oR//dividefactor]-
                                               ((jL % 2 == lL % 2) | (kR % 2 == oR % 2))*sigma[jL//dividefactor, kR//dividefactor, oR//dividefactor, lL//dividefactor])).astype(datatype)

        # spinmatch_ijom = (iL%2 == mR%2 or jL%2 == oR%2).astype(datatype)
        # spinmatch_ijmo = (iL%2 == oR%2 or jL%2 == mR%2).astype(datatype)
        # spinmatch_iklo = (iL%2 == oR%2 or lL%2 == kR%2).astype(datatype)
        # spinmatch_ikol = (iL%2 == lL%2 or oR%2 == kR%2).astype(datatype)
        # spinmatch_jklm = (jL%2 == mR%2 or lL%2 == kR%2).astype(datatype)
        # spinmatch_jkml = (jL%2 == lL%2 or mR%2 == kR%2).astype(datatype)
        # spinmatch_iklm = (iL%2 == mR%2 or lL%2 == kR%2).astype(datatype)
        # spinmatch_ikml = (iL%2 == lL%2 or mR%2 == kR%2).astype(datatype)
        # spinmatch_jklo = (jL%2 == oR%2 or kR%2 == lL%2).astype(datatype)
        # spinmatch_jkol = (jL%2 == lL%2 or kR%2 == oR%2).astype(datatype)

        # spintotalmatch_ijom=((iL%2 + mR%2 + jL%2 + oR%2)%2==0).astype(datatype)
        # spintotalmatch_iklo=((iL%2 + kR%2 + lL%2 + oR%2)%2==0).astype(datatype)
        # spintotalmatch_jklm=((jL%2 + kR%2 + lL%2 + mR%2)%2==0).astype(datatype)
        # spintotalmatch_iklm=((iL%2 + kR%2 + lL%2 + mR%2)%2==0).astype(datatype)
        # spintotalmatch_jklo=((jL%2 + kR%2 + lL%2 + oR%2)%2==0).astype(datatype)

        djo = (jL == oR).astype(datatype)
        dlk = (lL == kR).astype(datatype)

        dmj = (mR == jL).astype(datatype)
        dio = (iL == oR).astype(datatype)
        doj = (oR == jL).astype(datatype)

        fi = (i < NO).astype(np.int32)
        fj = (j < NO).astype(np.int32)
        fl = (l < NO).astype(np.int32)

        fiL = fi[:, None]
        fjL = fj[:, None]
        flL = fl[:, None]

        prefac = (((1-fiL)*(1-fjL)*flL - fiL*fjL*(1-flL))).astype(datatype)
        # print(de)
        # print(prefac)
        # interaction = (de+prefac*(dlk*S_1+dmj*S_2+dio*S_3-doj*S_4-dim*S_5)).astype(datatype)
        body_out = (de+prefac*(dlk*S_1+dmj*S_2+dio*S_3-doj*S_4-dim*S_5)).astype(datatype)

        # print("the body")
        # print(body_out)


        # print("the interaction")
        # print(interaction)
        # print(interaction - interaction.T)

        # terms = {
        #     "dlk*S1": dlk*S_1,
        #     "dmj*S2": dmj*S_2,
        #     "dio*S3": dio*S_3,
        #     "doj*S4": doj*S_4,
        #     "dim*S5": dim*S_5,
        # }

        # for name, term in terms.items():
        #     print(name)
        #     print(term)
        #     print(term - term.T)

        # sys.exit()
        # body = de
        return body_out

    def speedUpShoulder(nspaceR):

        m = nspaceR[:, 0]
        o = nspaceR[:, 1]
        k = nspaceR[:, 2]

        mR = m[None, :]
        oR = o[None, :]
        kR = k[None, :]

        sigma=self.eri_mo_gabi.astype(datatype)

        dividefactor=2

        cond1 = ((mwing % 2 + mR % 2 + kR % 2 + oR % 2) % 2 == 0).astype(datatype)

        term1 = ((mwing % 2 == mR % 2) | (kR % 2 == oR % 2)).astype(datatype)

        term2 = ((mwing % 2 == oR % 2) | (kR % 2 == mR % 2)).astype(datatype)

        s_1 = (
            cond1 *
            (
                term1 * sigma[mwing // dividefactor,
                              kR // dividefactor,
                              oR // dividefactor,
                              mR // dividefactor]
                -
                term2 * sigma[mwing // dividefactor,
                              kR // dividefactor,
                              mR // dividefactor,
                              oR // dividefactor]
            )
        ).astype(datatype)

        return s_1

    body = np.zeros((N, N),dtype=datatype)

    wing = np.zeros((NBAS,len(nspace3particle)),dtype=datatype)
    # print(wing.shape)
    for tchunkR in nchunks:
        (indexR0, indexR1, chunkR) = tchunkR
        shoulderchunk=speedUpShoulder(chunkR)
        c0 = indexR0
        c1 = indexR1
        # print(c0)
        # print(c1)
        # print(shoulderchunk.shape)
        # print(wing[:NBAS,c0:c1].shape)
        # print(wing[:NBAS,c0:c1].shape)
        wing[:NBAS,c0:c1] = shoulderchunk
        for tchunkL in nchunks:

            (indexL0, indexL1, chunkL) = tchunkL


            # indexL0=indexL
            # indexL1=indexL+chunk_size
            # indexR0=indexR
            # indexR1=indexR+chunk_size

            bodychunk=speedUpCore(chunkL,chunkR)
            bodychunkB=speedUpCore(chunkR,chunkL).conj().T
            if not np.allclose(bodychunk,bodychunkB):
                print(bodychunk)
                print(bodychunkB)
                print(chunkL)
                print(chunkR)
                print(indexL0)
                print(indexR0)
                sys.exit()

            r0 = indexL0
            r1 = indexL1


            # even-even (A)
            body[r0:r1, c0:c1] = bodychunk

    body[np.abs(body) < self.sparse_tol] = 0.0
    head[np.abs(head) < self.sparse_tol] = 0.0
    wing[np.abs(wing) < self.sparse_tol] = 0.0
    # body_sparse = csr_matrix(body)
    # print(wing.shape)
    # print(body.shape)
    # print(head.shape)


    H3upd=scipy.sparse.bmat([[head,wing],[np.transpose(wing),body]], format='csr', dtype=datatype)

    # check16(H3upd)

    H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

    self.timed("Creating spin Opt eff. Hamiltonian sparse",2)



    return H3upd

spinAdaptedMCDESparse(secondBorn=False)

Source code in src/MCDE2409_parallel.py
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
def spinAdaptedMCDESparse(self,secondBorn=False):
    self.verbose3("Spin transformed MCDE sparse")
    self.verbose3("Second Born? "+str(secondBorn))

    datatype=self.data_type_sparse

    #  small number
    def sqrt(x):
        return np.sqrt(x).astype(datatype)

    def check32(arr):
        prod=np.prod(arr.shape)
        res=(prod*4==arr.nbytes)
        if res:
            print("Is 32")
        else:
            print("Is not 32, its ",type(arr))
            print("Size: ",arr.nbytes)
            print("Theory: ", prod*4)
            sys.exit()

    def check16(arr):
        return None
        prod=np.prod(arr.shape)
        res=(prod*2==arr.nbytes)
        if res:
            print("Is 16")
        else:
            print("Is not 16, its ",type(arr))
            print("Size: ",arr.nbytes)
            print("Theory: ", prod*2)
            sys.exit()

    #transform spinorbitals to spatial orbitals
    nspace_spatials0=[]
    for entry in self.nspace:
        nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
    #remove duplicates
    seen = set()
    nspace_spatials = []
    for item in nspace_spatials0:
        t = tuple(item)
        if t not in seen:
            seen.add(t)
            nspace_spatials.append(item)

    nspace = np.array(nspace_spatials)   # shape (N,3)
    spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

    # head
    ray=[]
    for i in range(self.nBas):
        ray.append(self.mo_en[i])
    head=np.diag(ray).astype(datatype)

    # check32(head)

    nBasspace=np.arange(self.nBas)
    mwing = nBasspace[None, :]

    i = nspace[:, 0]
    j = nspace[:, 1]
    l = nspace[:, 2]

    m = nspace[:, 0]
    o = nspace[:, 1]
    k = nspace[:, 2]

    iL = i[:, None]
    jL = j[:, None]
    lL = l[:, None]

    mR = m[None, :]
    oR = o[None, :]
    kR = k[None, :]

    dim = (iL == mR).astype(datatype)
    djo = (jL == oR).astype(datatype)
    dlk = (lL == kR).astype(datatype)

    dmj = (mR == jL).astype(datatype)
    dio = (iL == oR).astype(datatype)
    doj = (oR == jL).astype(datatype)

    ei = self.mo_en[i].astype(datatype)
    ej = self.mo_en[j].astype(datatype)
    el = self.mo_en[l].astype(datatype)

    eiL = ei[:, None]
    ejL = ej[:, None]
    elL = el[:, None]

    check16(dlk)

    de = ((eiL - (elL - ejL)) * dim * djo * dlk).astype(datatype)

    # check32(de)
    #memory expensive!
    N=self.nBas

    sigma=self.eri_mo_gabi.astype(datatype)



    S_ijom = sigma[iL, jL, oR, mR]
    S_ijmo = sigma[iL, jL, mR, oR]
    S_iklo = sigma[iL, kR, lL, oR]
    S_ikol = sigma[iL, kR, oR, lL]
    S_jklm = sigma[jL, kR, lL, mR]
    S_jkml = sigma[jL, kR, mR, lL]
    S_iklm = sigma[iL, kR, lL, mR]
    S_ikml = sigma[iL, kR, mR, lL]
    S_jklo = sigma[jL, kR, lL, oR]
    S_jkol = sigma[jL, kR, oR, lL]



    sqrt2 = sqrt(0.5)
    sqrt3 = (sqrt(3.0) / 2.0).astype(datatype)



    s_mo = np.where(mR != oR, 1.0, sqrt2).astype(datatype)
    s_ij = np.where(iL != jL, 1.0, sqrt2).astype(datatype)

    # check32(s_mo)

    prefacA1=datatype(0.5)
    prefacA2=datatype(1.5)

    A1 = s_mo * s_ij * (
        -dlk * (S_ijom + S_ijmo)
        + dmj * (S_iklo - prefacA1 * S_ikol)
        + dio * (S_jklm - prefacA1 * S_jkml)
        + doj * (S_iklm - prefacA1 * S_ikml)
        + dim * (S_jklo - prefacA1 * S_jkol)
    )
    check16(dmj * (S_iklo - prefacA1 * S_ikol))
    check16(A1)

    A2 = (
        -dlk * (S_ijom - S_ijmo)
        - dmj * (S_iklo - prefacA2 * S_ikol)
        - dio * (S_jklm - prefacA2 * S_jkml)
        + doj * (S_iklm - prefacA2 * S_ikml)
        + dim * (S_jklo - prefacA2 * S_jkol)
    )

    check16(A2)

    F1 = s_ij * sqrt3 * (
        -dmj * S_ikol
        + dio * S_jkml
        + doj * S_ikml
        - dim * S_jkol
    )
    #
    check16(F1)

    F2 = s_mo * sqrt3 * (
        dmj * S_ikol
        - dio * S_jkml
        + doj * S_ikml
        - dim * S_jkol
    )



    fi = (i < self.nO).astype(np.int32)
    fj = (j < self.nO).astype(np.int32)
    fl = (l < self.nO).astype(np.int32)

    fiL = fi[:, None]
    fjL = fj[:, None]
    flL = fl[:, None]

    prefac = (-((1-fiL)*(1-fjL)*flL - fiL*fjL*(1-flL))).astype(datatype)



    A = de + prefac * A1
    B = prefac * F1
    C = prefac * F2
    D = de + prefac * A2


    N = len(nspace)

    body = np.zeros((2*N, 2*N),dtype=datatype)

    body[0::2, 0::2] = A
    body[0::2, 1::2] = B
    body[1::2, 0::2] = C
    body[1::2, 1::2] = D

    #wing
    pref4=sqrt(3/2)
    pref=(np.where(iL==jL,sqrt2,1.0)*sqrt2).astype(datatype)

    S1 = sigma[iL, jL, lL, mwing]
    S2 = sigma[iL, jL, mwing, lL]


    C3 = pref * (S1 + S2)
    C4 = pref4 * (S1 - S2)




    wing = np.zeros((2*len(nspace), self.nBas),dtype=datatype)

    wing[0::2, :] = C3
    wing[1::2, :] = C4


    body[np.abs(body) < self.sparse_tol] = 0.0
    head[np.abs(head) < self.sparse_tol] = 0.0
    wing[np.abs(wing) < self.sparse_tol] = 0.0
    # body_sparse = csr_matrix(body)
    # print(wing.shape)
    # print(body.shape)
    # print(head.shape)


    H3upd=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,body]], format='csr', dtype=datatype)

    # check16(H3upd)

    H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

    self.timed("Creating spin Opt eff. Hamiltonian sparse",2)



    return H3upd

spinAdaptedMCDESparseChunks(secondBorn=False)

Source code in src/MCDE2409_parallel.py
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
def spinAdaptedMCDESparseChunks(self,secondBorn=False):
    self.verbose3("Spin transformed MCDE sparse")
    self.verbose3("Second Born? "+str(secondBorn))

    datatype=self.data_type_sparse

    #  small number
    def sqrt(x):
        return np.sqrt(x).astype(datatype)

    def check32(arr):
        prod=np.prod(arr.shape)
        res=(prod*4==arr.nbytes)
        if res:
            print("Is 32")
        else:
            print("Is not 32, its ",type(arr))
            print("Size: ",arr.nbytes)
            print("Theory: ", prod*4)
            sys.exit()

    def check16(arr):
        return None
        prod=np.prod(arr.shape)
        res=(prod*2==arr.nbytes)
        if res:
            print("Is 16")
        else:
            print("Is not 16, its ",type(arr))
            print("Size: ",arr.nbytes)
            print("Theory: ", prod*2)
            sys.exit()

    #transform spinorbitals to spatial orbitals
    nspace_spatials0=[]
    for entry in self.nspace:
        nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
    #remove duplicates
    seen = set()
    nspace_spatials = []
    for item in nspace_spatials0:
        t = tuple(item)
        if t not in seen:
            seen.add(t)
            nspace_spatials.append(item)

    nspaceFull = np.array(nspace_spatials)   # shape (N,3)
    spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

    # head
    ray=[]
    for i in range(self.nBas):
        ray.append(self.mo_en[i])
    head=np.diag(ray).astype(datatype)

    # check32(head)

    nBasspace=np.arange(self.nBas)
    mwing = nBasspace[None, :]

    N = len(nspaceFull)
    chunk_size = max(N//100,2)
    chunk_size = 5000 if chunk_size > 5000 else chunk_size

    nchunks = [
        (i, i + len(nspaceFull[i:i+chunk_size]), nspaceFull[i:i+chunk_size])
        for i in range(0, len(nspaceFull), chunk_size)
    ]

    body = np.zeros((2*N, 2*N),dtype=datatype)

    wing = np.zeros((2*len(nspaceFull), self.nBas),dtype=datatype)

    def speedUpCore(nspaceL,nspaceR):

        i = nspaceL[:, 0]
        j = nspaceL[:, 1]
        l = nspaceL[:, 2]

        m = nspaceR[:, 0]
        o = nspaceR[:, 1]
        k = nspaceR[:, 2]

        iL = i[:, None]
        jL = j[:, None]
        lL = l[:, None]

        mR = m[None, :]
        oR = o[None, :]
        kR = k[None, :]

        dim = (iL == mR).astype(datatype)
        djo = (jL == oR).astype(datatype)
        dlk = (lL == kR).astype(datatype)

        dmj = (mR == jL).astype(datatype)
        dio = (iL == oR).astype(datatype)
        doj = (oR == jL).astype(datatype)

        ei = self.mo_en[i].astype(datatype)
        ej = self.mo_en[j].astype(datatype)
        el = self.mo_en[l].astype(datatype)

        eiL = ei[:, None]
        ejL = ej[:, None]
        elL = el[:, None]

        # check16(dlk)

        de = ((eiL - (elL - ejL)) * dim * djo * dlk).astype(datatype)

        # check32(de)
        #memory expensive!

        sigma=self.eri_mo_gabi.astype(datatype)


        S_ijom = sigma[iL, jL, oR, mR]
        S_ijmo = sigma[iL, jL, mR, oR]
        S_iklo = sigma[iL, kR, lL, oR]
        S_ikol = sigma[iL, kR, oR, lL]
        S_jklm = sigma[jL, kR, lL, mR]
        S_jkml = sigma[jL, kR, mR, lL]
        S_iklm = sigma[iL, kR, lL, mR]
        S_ikml = sigma[iL, kR, mR, lL]
        S_jklo = sigma[jL, kR, lL, oR]
        S_jkol = sigma[jL, kR, oR, lL]



        sqrt2 = sqrt(0.5)
        sqrt3 = (sqrt(3.0) / 2.0).astype(datatype)



        s_mo = np.where(mR != oR, 1.0, sqrt2).astype(datatype)
        s_ij = np.where(iL != jL, 1.0, sqrt2).astype(datatype)

        # check32(s_mo)

        prefacA1=datatype(0.5)
        prefacA2=datatype(1.5)

        A1 = s_mo * s_ij * (
            -dlk * (S_ijom + S_ijmo)
            + dmj * (S_iklo - prefacA1 * S_ikol)
            + dio * (S_jklm - prefacA1 * S_jkml)
            + doj * (S_iklm - prefacA1 * S_ikml)
            + dim * (S_jklo - prefacA1 * S_jkol)
        )
        # check16(dmj * (S_iklo - prefacA1 * S_ikol))
        # check16(A1)

        A2 = (
            -dlk * (S_ijom - S_ijmo)
            - dmj * (S_iklo - prefacA2 * S_ikol)
            - dio * (S_jklm - prefacA2 * S_jkml)
            + doj * (S_iklm - prefacA2 * S_ikml)
            + dim * (S_jklo - prefacA2 * S_jkol)
        )

        # check16(A2)

        F1 = s_ij * sqrt3 * (
            -dmj * S_ikol
            + dio * S_jkml
            + doj * S_ikml
            - dim * S_jkol
        )
        #
        # check16(F1)

        F2 = s_mo * sqrt3 * (
            dmj * S_ikol
            - dio * S_jkml
            + doj * S_ikml
            - dim * S_jkol
        )

        fi = (i < self.nO).astype(np.int32)
        fj = (j < self.nO).astype(np.int32)
        fl = (l < self.nO).astype(np.int32)

        fiL = fi[:, None]
        fjL = fj[:, None]
        flL = fl[:, None]

        prefac = (-((1-fiL)*(1-fjL)*flL - fiL*fjL*(1-flL))).astype(datatype)

        A = de + prefac * A1
        B = prefac * F1
        C = prefac * F2
        D = de + prefac * A2

        pref4=sqrt(3/2)
        pref=(np.where(iL==jL,sqrt2,1.0)*sqrt2).astype(datatype)

        S1 = sigma[iL, jL, lL, mwing]
        S2 = sigma[iL, jL, mwing, lL]


        C3 = pref * (S1 + S2)
        C4 = pref4 * (S1 - S2)



        return A,B,C,D,C3,C4



    for tchunkL in nchunks:
        for tchunkR in nchunks:

            (indexL0, indexL1, chunkL) = tchunkL
            (indexR0, indexR1, chunkR) = tchunkR

            # indexL0=indexL
            # indexL1=indexL+chunk_size
            # indexR0=indexR
            # indexR1=indexR+chunk_size

            A,B,C,D,C3,C4=speedUpCore(chunkL,chunkR)

            r0 = 2 * indexL0
            r1 = 2 * indexL1
            c0 = 2 * indexR0
            c1 = 2 * indexR1

            # even-even (A)
            body[r0:r1:2, c0:c1:2] = A

            # even-odd (B)
            body[r0:r1:2, c0+1:c1:2] = B

            # odd-even (C)
            body[r0+1:r1:2, c0:c1:2] = C

            # odd-odd (D)
            body[r0+1:r1:2, c0+1:c1:2] = D

            wing[r0:r1:2, :] = C3
            wing[r0+1:r1:2, :] = C4     

    body[np.abs(body) < self.sparse_tol] = 0.0
    head[np.abs(head) < self.sparse_tol] = 0.0
    wing[np.abs(wing) < self.sparse_tol] = 0.0
    # body_sparse = csr_matrix(body)
    # print(wing.shape)
    # print(body.shape)
    # print(head.shape)


    H3upd=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,body]], format='csr', dtype=datatype)

    # check16(H3upd)

    H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

    self.timed("Creating spin Opt eff. Hamiltonian sparse",2)



    return H3upd

spinAdaptedMCDESparseOrig(secondBorn=False)

Construct the spin-adapted sparse MCDE effective Hamiltonian.

This method transforms the spin-orbital three-particle basis into a spin-adapted spatial-orbital basis and constructs the corresponding MCDE effective Hamiltonian in sparse matrix format. The resulting matrix contains the one-particle sector, the spin-adapted three-particle sector, and the coupling between them.

The spin-adapted basis is generated by collapsing spin-orbital indices onto spatial-orbital indices and removing duplicate configurations. For each spatial configuration, singlet-coupled and triplet-coupled three-particle states are constructed, yielding two spin-adapted states per spatial basis function.

The effective Hamiltonian is assembled in block form,

\[ H_{\mathrm{MCDE}} = \begin{pmatrix} H_{1p} & V^\dagger \\ V & H_{3p} \end{pmatrix} \]

where \(H_{1p}\) is the one-particle block, \(H_{3p}\) is the spin-adapted three-particle block, and \(V\) contains the coupling between the one- and three-particle sectors.

Matrix elements smaller than self.sparse_tol are omitted during construction. After assembly, elements below self.zero_tol are removed and isolated diagonal states may optionally be eliminated using self.AuxillaryFunctions.remove_isolated_diagonals_sparse.

Parameters:

Name Type Description Default
secondBorn

Flag indicating whether the Second-Born approximation is used. This parameter is currently only employed for logging and consistency with other MCDE construction routines. Default is False. (bool, optional)

required

Returns:

Name Type Description
matrix

Spin-adapted MCDE effective Hamiltonian in sparse CSR format. (scipy.sparse.csr_matrix)

Notes

The size of the resulting Hamiltonian is

\[ N_{\mathrm{eff}} = N_{\mathrm{1p}} + 2 N_{\mathrm{3p}}, \]

where \(N_{\mathrm{1p}}\) is the number of one-particle basis functions and \(N_{\mathrm{3p}}\) is the number of unique spatial three-particle configurations.

The factor of two arises from the two spin-adapted coupling channels associated with each spatial three-particle configuration.

The method updates the internal attribute self.nspace_spatials_MCDE to reflect the reduced spin-adapted basis after any pruning operations.

See Also

-spinAdaptedMCDE : Dense spin-adapted MCDE Hamiltonian construction.

-spinAdaptedMCDESparse : Very fast, but memory expensive dense spin-adapted MCDE implementation.

-spinAdaptedMCDESparseChunks : A speed and memory balanced implementation of the dense spin-adapted MCDE implementation.

-spinAdaptedMCDESparseParallel : Parallelized verson of dense spin-adapted MCDE implementation.

-spinAdaptedMCDEwithWSparse : like spinAdaptedMCDESparseOrig, but with the exchange V switched with W.

Source code in src/MCDE2409_parallel.py
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
def spinAdaptedMCDESparseOrig(self,secondBorn=False):
    """
    Construct the spin-adapted sparse MCDE effective Hamiltonian.

    This method transforms the spin-orbital three-particle basis into a
    spin-adapted spatial-orbital basis and constructs the corresponding
    MCDE effective Hamiltonian in sparse matrix format. The resulting matrix
    contains the one-particle sector, the spin-adapted three-particle sector,
    and the coupling between them.

    The spin-adapted basis is generated by collapsing spin-orbital indices
    onto spatial-orbital indices and removing duplicate configurations.
    For each spatial configuration, singlet-coupled and triplet-coupled
    three-particle states are constructed, yielding two spin-adapted states
    per spatial basis function.

    The effective Hamiltonian is assembled in block form,

    \[
    H_{\mathrm{MCDE}}
    =
    \\begin{pmatrix}
    H_{1p} & V^\dagger \\\\
    V & H_{3p}
    \\end{pmatrix}
    \]

    where $H_{1p}$ is the one-particle block, $H_{3p}$ is the
    spin-adapted three-particle block, and $V$ contains the coupling
    between the one- and three-particle sectors.

    Matrix elements smaller than `self.sparse_tol` are omitted during
    construction. After assembly, elements below `self.zero_tol` are
    removed and isolated diagonal states may optionally be eliminated using
    `self.AuxillaryFunctions.remove_isolated_diagonals_sparse`.

    Parameters:
        secondBorn : 
            Flag indicating whether the Second-Born approximation is used.
            This parameter is currently only employed for logging and consistency
            with other MCDE construction routines. Default is `False`. (bool, optional)

    Returns:
        matrix:
            Spin-adapted MCDE effective Hamiltonian in sparse CSR format. (scipy.sparse.csr_matrix)

    Notes:
        The size of the resulting Hamiltonian is

        $$
        N_{\mathrm{eff}}
        =
        N_{\mathrm{1p}}
        + 2 N_{\mathrm{3p}},
        $$

        where $N_{\mathrm{1p}}$ is the number of one-particle basis
        functions and $N_{\mathrm{3p}}$ is the number of unique spatial
        three-particle configurations.

        The factor of two arises from the two spin-adapted coupling channels
        associated with each spatial three-particle configuration.

        The method updates the internal attribute
        `self.nspace_spatials_MCDE` to reflect the reduced spin-adapted basis
        after any pruning operations.

    See Also:
        -spinAdaptedMCDE :
        Dense spin-adapted MCDE Hamiltonian construction.

        -spinAdaptedMCDESparse :
        Very fast, but memory expensive dense spin-adapted MCDE implementation.

        -spinAdaptedMCDESparseChunks :
        A speed and memory balanced implementation of the dense spin-adapted MCDE implementation.

        -spinAdaptedMCDESparseParallel :
        Parallelized verson of dense spin-adapted MCDE implementation.

        -spinAdaptedMCDEwithWSparse :
        like spinAdaptedMCDESparseOrig, but with the exchange V switched with W.
    """


    self.verbose3("Spin transformed MCDE sparse")
    self.verbose3("Second Born? "+str(secondBorn))

    datatype=self.data_type_sparse

    def d(a,b):
        return 1 if a==b else 0


    #transform spinorbitals to spatial orbitals
    nspace_spatials0=[]
    for entry in self.nspace:
        nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
    #remove duplicates
    seen = set()
    nspace_spatials = []
    for item in nspace_spatials0:
        t = tuple(item)
        if t not in seen:
            seen.add(t)
            nspace_spatials.append(item)

    spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

    self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
    self.verbose4(nspace_spatials)
    ray=[]
    for i in range(self.nBas):
        ray.append(self.mo_en[i])
    head=np.diag(ray)

    #create wing

    # wing=np.zeros((len(nspace_spatials)*2,len(ray)))
    wing=lil_matrix((len(nspace_spatials)*2,len(ray)),dtype=datatype)

    for leftindex,left in enumerate(nspace_spatials):
        [i,j,l]=left
        for rightindex,m in enumerate(np.arange(self.nBas)):
            C3=np.sqrt(.5)**(d(i,j))*np.sqrt(.5)*(self.sigma_mo_gabi(i,j,l,m)+self.sigma_mo_gabi(i,j,m,l))
            C4=np.sqrt(3/2)*(self.sigma_mo_gabi(i,j,l,m)-self.sigma_mo_gabi(i,j,m,l))

            wing[2*leftindex,rightindex]=C3
            wing[2*leftindex+1,rightindex]=C4

    #create body matrix

    if self.mcde:
        # body=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        body=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
        # bodyHF=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left

            for rightindex,right in enumerate(nspace_spatials):
                [m,o,k]=right


                A1=np.sqrt(.5)**(d(m,o))*np.sqrt(.5)**(d(i,j))*(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)+self.sigma_mo_gabi(i,j,m,o))
                                                              +d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-.5*self.sigma_mo_gabi(i,k,o,l))
                                                              +d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-.5*self.sigma_mo_gabi(j,k,m,l))
                                                              +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-.5*self.sigma_mo_gabi(i,k,m,l))
                                                              +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-.5*self.sigma_mo_gabi(j,k,o,l)))
                A2=(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)-self.sigma_mo_gabi(i,j,m,o))
                                                              -d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-1.5*self.sigma_mo_gabi(i,k,o,l))
                                                              -d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-1.5*self.sigma_mo_gabi(j,k,m,l))
                                                              +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-1.5*self.sigma_mo_gabi(i,k,m,l))
                                                              +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-1.5*self.sigma_mo_gabi(j,k,o,l)))
                F1=np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(-d(m,j)*self.sigma_mo_gabi(i,k,o,l)+d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                      +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                      -d(i,m)*self.sigma_mo_gabi(j,k,o,l))
                F2=np.sqrt(.5)**(d(m,o))*(np.sqrt(3)/2)*(d(m,j)*self.sigma_mo_gabi(i,k,o,l)-d(i,o)*self.sigma_mo_gabi(j,k,m,l)
                                                      +d(o,j)*self.sigma_mo_gabi(i,k,m,l)
                                                      -d(i,m)*self.sigma_mo_gabi(j,k,o,l))


                fi = 0 if (i >= self.nO) else 1
                fj = 0 if (j >= self.nO) else 1
                fl = 0 if (l >= self.nO) else 1
                prefac=-((1-fi)*(1-fj)*fl-fi*fj*(1-fl))

                ei=self.mo_en[i]+self.virtualShift(i)
                ej=self.mo_en[j]+self.virtualShift(j)
                el=self.mo_en[l]+self.virtualShift(l)
                de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)

                A=de+prefac*A1
                B=prefac*F1
                C=prefac*F2
                D=de+prefac*A2

                if abs(A)>self.sparse_tol:
                    body[2*leftindex,2*rightindex]=A
                if abs(B)>self.sparse_tol:
                    body[2*leftindex,2*rightindex+1]=B
                if abs(C)>self.sparse_tol:
                    body[2*leftindex+1,2*rightindex]=C
                if abs(D)>self.sparse_tol:
                    body[2*leftindex+1,2*rightindex+1]=D

                # body[2*leftindex,2*rightindex]=de+prefac*A1
                # body[2*leftindex,2*rightindex+1]=prefac*F1
                # body[2*leftindex+1,2*rightindex]=prefac*F2
                # body[2*leftindex+1,2*rightindex+1]=de+prefac*A2

                # bodyHF[2*leftindex,2*rightindex]=de
                # bodyHF[2*leftindex+1,2*rightindex+1]=de
                # H3upd=np.block([[head,np.transpose(wing)],[wing,body]])
        H3upd = scipy.sparse.bmat([[head, wing.T],
              [wing, body]], format='csr',dtype=datatype)
        # H3upd[H3upd.abs() < self.zero_tol] = 0
        # H3upd.eliminate_zeros()
        mask = np.abs(H3upd.data) < self.zero_tol
        H3upd.data[mask] = 0
        # H3upd=np.where(np.abs(H3upd) < self.zero_tol, 0.0, H3upd)
        H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

    if secondBorn:
        # bodySB=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        bodySB=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left

            for rightindex,right in enumerate(nspace_spatials):
                [m,o,k]=right


                ei=self.mo_en[i]+self.virtualShift(i)
                ej=self.mo_en[j]+self.virtualShift(j)
                el=self.mo_en[l]+self.virtualShift(l)
                de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


                bodySB[2*leftindex,2*rightindex]=de
                bodySB[2*leftindex,2*rightindex+1]=0
                bodySB[2*leftindex+1,2*rightindex]=0
                bodySB[2*leftindex+1,2*rightindex+1]=de
        # H3SB=np.block([[head,np.transpose(wing)],[wing,bodySB]])
        H3SB=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,bodySB]], format='csr', dtype=datatype)
        mask = np.abs(H3SB.data) < self.zero_tol
        H3SB.data[mask] = 0
        # H3SB=np.where(np.abs(H3SB) < self.zero_tol, 0.0, H3SB)
        # H3SB=H3SB.tocsr()
        H3SB,self.nspace_spatials_SB=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3SB,spaceObj,self.remove_single_values)







    self.timed("Creating spin Opt eff. Hamiltonian sparse",2)

    if secondBorn and self.mcde:
        return H3upd,H3SB
    if secondBorn:
        return H3SB
    if self.mcde:
        return H3upd

spinAdaptedMCDESparseParallel(secondBorn=False)

Source code in src/MCDE2409_parallel.py
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
def spinAdaptedMCDESparseParallel(self,secondBorn=False):

    self.verbose3("Spin transformed MCDE sparse")
    self.verbose3("Second Born? "+str(secondBorn))

    datatype=self.data_type_sparse

    def sqrt(x):
        return np.sqrt(x).astype(datatype)

    #transform spinorbitals to spatial orbitals
    nspace_spatials0=[]
    for entry in self.nspace:
        nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
    #remove duplicates
    seen = set()
    nspace_spatials = []
    for item in nspace_spatials0:
        t = tuple(item)
        if t not in seen:
            seen.add(t)
            nspace_spatials.append(item)



    nspace = np.array(nspace_spatials)   # shape (N,3)

    spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

    self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
    self.verbose4(nspace_spatials)

    sigma=self.eri_mo_gabi.astype(datatype)

    ray=[]
    for i in range(self.nBas):
        ray.append(self.mo_en[i])
    head=lil_matrix(np.diag(ray))

    # create chunks
    n_workers = os.cpu_count()
    n = len(nspace_spatials)
    chunk_size = (n + n_workers - 1) // n_workers  # ceil division

    chunks = [
        list(range(i, min(i + chunk_size, n)))
        for i in range(0, n, chunk_size)
    ]

    tasks = [
        (chunk, nspace_spatials, self.mo_en.astype(datatype), self.nO,
         self.sparse_tol, self.zero_tol, sigma, datatype, self.sqrt)
        for chunk in chunks
    ]

    all_results = []


    with ProcessPoolExecutor() as executor:
        futures = [executor.submit(MCDE.compute_body_block, t) for t in tasks]

        for f in as_completed(futures):
            all_results.extend(f.result())

    body = lil_matrix((len(nspace_spatials)*2, 2*len(nspace_spatials)), dtype=datatype)

    for r, c, v in all_results:
        body[r, c] = v

    tasks = [
        (chunk, nspace_spatials, self.nBas, self.mo_en, self.nO,
         self.sparse_tol, self.zero_tol, sigma, datatype, self.sqrt)
        for chunk in chunks
    ]

    all_results = []

    with ProcessPoolExecutor() as executor:
        futures = [executor.submit(MCDE.compute_wing_block, t) for t in tasks]

        for f in as_completed(futures):
            all_results.extend(f.result())

    wing = lil_matrix((len(nspace_spatials)*2,len(ray)),dtype=datatype)

    for r, c, v in all_results:
        wing[r, c] = v

    H3upd = scipy.sparse.bmat([[head, wing.T],
          [wing, body]], format='csr',dtype=datatype)

    self.timed("Creating spin Opt eff. Hamiltonian sparse",2)

    H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

    return H3upd

spinAdaptedMCDEwithWSparse(secondBorn=False)

Construct the spin-adapted sparse MCDE effective Hamiltonian with the direct-\(eh\) and direct- and exchange-\(pp\) two electron integrals \(V\) replaced by \(W\) defined in self.eri_mo_gabi_W.

The method works analogously to self.spinAdaptedMCDESparseOrig.

Parameters:

Name Type Description Default
secondBorn

Flag indicating whether the Second-Born approximation is used. This parameter is currently only employed for logging and consistency with other MCDE construction routines. Default is False. (bool, optional)

required

Returns:

Name Type Description
matrix

Spin-adapted MCDE effective Hamiltonian in sparse CSR format. (scipy.sparse.csr_matrix)

See Also

-spinAdaptedMCDE : Dense spin-adapted MCDE Hamiltonian construction.

-spinAdaptedMCDESparse : Very fast, but memory expensive dense spin-adapted MCDE implementation.

-spinAdaptedMCDESparseChunks : A speed and memory balanced implementation of the dense spin-adapted MCDE implementation.

-spinAdaptedMCDESparseOrig : Slow sparse spin-adapted MCDE Hamiltonian construction.

-spinAdaptedMCDESparseParallel : Parallelized verson of dense spin-adapted MCDE implementation.

Source code in src/MCDE2409_parallel.py
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
def spinAdaptedMCDEwithWSparse(self,secondBorn=False):
    """
    Construct the spin-adapted sparse MCDE effective Hamiltonian with the 
    direct-$eh$ and direct- and exchange-$pp$ two electron integrals $V$ replaced
    by $W$ defined in `self.eri_mo_gabi_W`.

    The method works analogously to `self.spinAdaptedMCDESparseOrig`.

    Parameters:
        secondBorn : 
            Flag indicating whether the Second-Born approximation is used.
            This parameter is currently only employed for logging and consistency
            with other MCDE construction routines. Default is `False`. (bool, optional)

    Returns:
        matrix:
            Spin-adapted MCDE effective Hamiltonian in sparse CSR format. (scipy.sparse.csr_matrix)



    See Also:
        -spinAdaptedMCDE :
        Dense spin-adapted MCDE Hamiltonian construction.

        -spinAdaptedMCDESparse :
        Very fast, but memory expensive dense spin-adapted MCDE implementation.

        -spinAdaptedMCDESparseChunks :
        A speed and memory balanced implementation of the dense spin-adapted MCDE implementation.

        -spinAdaptedMCDESparseOrig :
        Slow sparse spin-adapted MCDE Hamiltonian construction.

        -spinAdaptedMCDESparseParallel :
        Parallelized verson of dense spin-adapted MCDE implementation.
    """
    # is W defined?
    if self.eri_mo_gabi_W is None:
        self.verbose1("No W defined, proceed with unscreened V.")
        return self.spinAdaptedMCDESparse(secondBorn)

    self.verbose3("Spin transformed MCDE sparse")
    self.verbose3("Second Born? "+str(secondBorn))

    datatype=self.data_type_sparse

    def d(a,b):
        return 1 if a==b else 0


    #transform spinorbitals to spatial orbitals
    nspace_spatials0=[]
    for entry in self.nspace:
        nspace_spatials0.append([entry[0]//2,entry[1]//2,entry[2]//2])
    #remove duplicates
    seen = set()
    nspace_spatials = []
    for item in nspace_spatials0:
        t = tuple(item)
        if t not in seen:
            seen.add(t)
            nspace_spatials.append(item)

    spaceObj=MCDE.Nspace(np.arange(self.nBas),np.repeat(nspace_spatials,2,axis=0))

    self.verbose3("Length of 3-particle basis: " + str(len(nspace_spatials)))
    self.verbose4(nspace_spatials)
    ray=[]
    for i in range(self.nBas):
        ray.append(self.mo_en[i])
    head=np.diag(ray)

    #create wing

    # wing=np.zeros((len(nspace_spatials)*2,len(ray)))
    wing=lil_matrix((len(nspace_spatials)*2,len(ray)),dtype=datatype)

    for leftindex,left in enumerate(nspace_spatials):
        [i,j,l]=left
        for rightindex,m in enumerate(np.arange(self.nBas)):
            C3=np.sqrt(.5)**(d(i,j))*np.sqrt(.5)*(self.sigma_mo_gabi(i,j,l,m)+self.sigma_mo_gabi_W(i,j,m,l))
            C4=np.sqrt(3/2)*(self.sigma_mo_gabi(i,j,l,m)-self.sigma_mo_gabi_W(i,j,m,l))

            wing[2*leftindex,rightindex]=C3
            wing[2*leftindex+1,rightindex]=C4

    #create body matrix

    if self.mcde:
        # body=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        body=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
        # bodyHF=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left

            for rightindex,right in enumerate(nspace_spatials):
                [m,o,k]=right


                A1=np.sqrt(.5)**(d(m,o))*np.sqrt(.5)**(d(i,j))*(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)+self.sigma_mo_gabi_W(i,j,m,o))
                                                              +d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-.5*self.sigma_mo_gabi_W(i,k,o,l))
                                                              +d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-.5*self.sigma_mo_gabi_W(j,k,m,l))
                                                              +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-.5*self.sigma_mo_gabi_W(i,k,m,l))
                                                              +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-.5*self.sigma_mo_gabi_W(j,k,o,l)))
                A2=(-d(l,k)*(self.sigma_mo_gabi(i,j,o,m)-self.sigma_mo_gabi_W(i,j,m,o))
                                                              -d(m,j)*(self.sigma_mo_gabi(i,k,l,o)-1.5*self.sigma_mo_gabi_W(i,k,o,l))
                                                              -d(i,o)*(self.sigma_mo_gabi(j,k,l,m)-1.5*self.sigma_mo_gabi_W(j,k,m,l))
                                                              +d(o,j)*(self.sigma_mo_gabi(i,k,l,m)-1.5*self.sigma_mo_gabi_W(i,k,m,l))
                                                              +d(i,m)*(self.sigma_mo_gabi(j,k,l,o)-1.5*self.sigma_mo_gabi_W(j,k,o,l)))
                F1=np.sqrt(.5)**(d(i,j))*(np.sqrt(3)/2)*(-d(m,j)*self.sigma_mo_gabi_W(i,k,o,l)+d(i,o)*self.sigma_mo_gabi_W(j,k,m,l)
                                                      +d(o,j)*self.sigma_mo_gabi_W(i,k,m,l)
                                                      -d(i,m)*self.sigma_mo_gabi_W(j,k,o,l))
                F2=np.sqrt(.5)**(d(m,o))*(np.sqrt(3)/2)*(d(m,j)*self.sigma_mo_gabi_W(i,k,o,l)-d(i,o)*self.sigma_mo_gabi_W(j,k,m,l)
                                                      +d(o,j)*self.sigma_mo_gabi_W(i,k,m,l)
                                                      -d(i,m)*self.sigma_mo_gabi_W(j,k,o,l))


                fi = 0 if (i >= self.nO) else 1
                fj = 0 if (j >= self.nO) else 1
                fl = 0 if (l >= self.nO) else 1
                prefac=-((1-fi)*(1-fj)*fl-fi*fj*(1-fl))

                ei=self.mo_en[i]+self.virtualShift(i)
                ej=self.mo_en[j]+self.virtualShift(j)
                el=self.mo_en[l]+self.virtualShift(l)
                de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)

                A=de+prefac*A1
                B=prefac*F1
                C=prefac*F2
                D=de+prefac*A2

                if abs(A)>self.sparse_tol:
                    body[2*leftindex,2*rightindex]=A
                if abs(B)>self.sparse_tol:
                    body[2*leftindex,2*rightindex+1]=B
                if abs(C)>self.sparse_tol:
                    body[2*leftindex+1,2*rightindex]=C
                if abs(D)>self.sparse_tol:
                    body[2*leftindex+1,2*rightindex+1]=D

                # body[2*leftindex,2*rightindex]=de+prefac*A1
                # body[2*leftindex,2*rightindex+1]=prefac*F1
                # body[2*leftindex+1,2*rightindex]=prefac*F2
                # body[2*leftindex+1,2*rightindex+1]=de+prefac*A2

                # bodyHF[2*leftindex,2*rightindex]=de
                # bodyHF[2*leftindex+1,2*rightindex+1]=de
                # H3upd=np.block([[head,np.transpose(wing)],[wing,body]])
        H3upd = scipy.sparse.bmat([[head, wing.T],
              [wing, body]], format='csr',dtype=datatype)
        # H3upd[H3upd.abs() < self.zero_tol] = 0
        # H3upd.eliminate_zeros()
        mask = np.abs(H3upd.data) < self.zero_tol
        H3upd.data[mask] = 0
        # H3upd=np.where(np.abs(H3upd) < self.zero_tol, 0.0, H3upd)
        H3upd,self.nspace_spatials_MCDE=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3upd,spaceObj,self.remove_single_values)

    if secondBorn:
        # bodySB=np.zeros((len(nspace_spatials)*2,2*len(nspace_spatials)))
        bodySB=lil_matrix((len(nspace_spatials)*2,2*len(nspace_spatials)),dtype=datatype)
        for leftindex,left in enumerate(nspace_spatials):
            [i,j,l]=left

            for rightindex,right in enumerate(nspace_spatials):
                [m,o,k]=right


                ei=self.mo_en[i]+self.virtualShift(i)
                ej=self.mo_en[j]+self.virtualShift(j)
                el=self.mo_en[l]+self.virtualShift(l)
                de=(ei-(el-ej))*d(i,m)*d(j,o)*d(l,k)


                bodySB[2*leftindex,2*rightindex]=de
                bodySB[2*leftindex,2*rightindex+1]=0
                bodySB[2*leftindex+1,2*rightindex]=0
                bodySB[2*leftindex+1,2*rightindex+1]=de
        # H3SB=np.block([[head,np.transpose(wing)],[wing,bodySB]])
        H3SB=scipy.sparse.bmat([[head,np.transpose(wing)],[wing,bodySB]], format='csr', dtype=datatype)
        mask = np.abs(H3SB.data) < self.zero_tol
        H3SB.data[mask] = 0
        # H3SB=np.where(np.abs(H3SB) < self.zero_tol, 0.0, H3SB)
        # H3SB=H3SB.tocsr()
        H3SB,self.nspace_spatials_SB=self.AuxillaryFunctions.remove_isolated_diagonals_sparse(H3SB,spaceObj,self.remove_single_values)







    self.timed("Creating spin Opt eff. Hamiltonian sparse",2)

    if secondBorn and self.mcde:
        return H3upd,H3SB
    if secondBorn:
        return H3SB
    if self.mcde:
        return H3upd

sqrt(x)

Source code in src/MCDE2409_parallel.py
521
522
def sqrt(self,x):
    return np.sqrt(x).astype(self.data_type_sparse)

timed(txt, verbosity)

Source code in src/MCDE2409_parallel.py
498
499
500
501
502
503
504
505
def timed(self,txt,verbosity):
    laps=time.perf_counter()
    elapsed=laps-self.intermediatetime
    self.intermediatetime=laps
    if self.verbose >= verbosity:
        print("\n")
        print(txt + f" took {elapsed:.2f} seconds")
        print("\n")

vbar()

Source code in src/MCDE2409_parallel.py
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
def vbar(self):
    vout=np.zeros((self.nBas*2,self.nBas*2,self.nBas*2,self.nBas*2))
    self.verbose4("Vout calculation")
    for spinmu in range(2):
        for spinnu in range(2):
            for spinla in range(2):
                for spinsi in range(2):
                    for mu in range(self.nBas):
                        for nu in range(self.nBas):
                            for la in range(self.nBas):
                                for si in range(self.nBas):
                                    mu2 = (mu) * 2 
                                    nu2 = (nu) * 2 
                                    la2 = (la) * 2 
                                    si2 = (si) * 2 

                                    mu2 += 1 if (spinmu == 1) else 0
                                    nu2 += 1 if (spinnu == 1) else 0
                                    la2 += 1 if (spinla == 1) else 0
                                    si2 += 1 if (spinsi == 1) else 0

                                    spinmatch1 = 0.0
                                    spinmatch2 = 0.0
                                    spintotalmatch = 0.0

                                    if ((spinmu==spinnu) or (spinla == spinsi)):
                                        spinmatch1 = 1.0
                                    if ((spinmu==spinsi) or (spinla == spinnu)):
                                        spinmatch2 = 1.0

                                    spinsum = spinmu + spinnu + spinla + spinsi
                                    if (spinsum % 2 == 0):
                                        spintotalmatch = 1.0

                                    #chemists: 1234 -> physi 1324 -> gabi 1342
                                    vout[mu2,la2,si2,nu2]=spintotalmatch * (self.eri_mo_gabi[mu,la,si,nu]*spinmatch1 - self.eri_mo_gabi[mu,la,nu,si]*spinmatch2)

                                    if (abs(vout[mu2,la2,si2,nu2])>1e-5 and self.verbose>=4):
                                        self.verbose4('%4d %4d %4d %4d      %.5f'%(mu2,la2,si2,nu2,vout[mu2,la2,si2,nu2]))
    return vout

vbarOnTheSpot(mu2, la2, si2, nu2)

Source code in src/MCDE2409_parallel.py
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
def vbarOnTheSpot(self,mu2,la2,si2,nu2):
    mu=mu2//2
    la=la2//2
    nu=nu2//2
    si=si2//2


    spinmu=mu2%2
    spinla=la2%2
    spinnu=nu2%2
    spinsi=si2%2

    spinmatch1 = 0.0
    spinmatch2 = 0.0
    spintotalmatch = 0.0

    if ((spinmu==spinnu) or (spinla == spinsi)):
        spinmatch1 = 1.0
    if ((spinmu==spinsi) or (spinla == spinnu)):
        spinmatch2 = 1.0

    spinsum = spinmu + spinnu + spinla + spinsi
    if (spinsum % 2 == 0):
        spintotalmatch = 1.0

    return spintotalmatch * (self.eri_mo_gabi[mu,la,si,nu]*spinmatch1 - self.eri_mo_gabi[mu,la,nu,si]*spinmatch2)

verbose1(txt)

Source code in src/MCDE2409_parallel.py
482
483
484
def verbose1(self,txt):
    if self.verbose >= 1:
        print(txt)

verbose2(txt)

Source code in src/MCDE2409_parallel.py
486
487
488
def verbose2(self,txt):
    if self.verbose >= 2:
        print(txt)

verbose3(txt)

Source code in src/MCDE2409_parallel.py
490
491
492
def verbose3(self,txt):
    if self.verbose >= 3:
        print(txt)

verbose4(txt)

Source code in src/MCDE2409_parallel.py
494
495
496
def verbose4(self,txt):
    if self.verbose >= 4:
        print(txt)

virtualShift(index)

Source code in src/MCDE2409_parallel.py
516
517
518
519
def virtualShift(self,index):
    if index<self.nO:
        return 0
    return self.shift_virtual_energy