This repository has been archived by the owner on Jul 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
relforte.py
2810 lines (2346 loc) · 144 KB
/
relforte.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import pyscf, pyscf.mcscf, pyscf.fci
from pyscf import mp, mcscf
import numpy as np
import h5py
import time
import scipy
import itertools
import copy
import os, glob
import warnings
from contractions import *
from wicked_contractions import *
import gc
MACHEPS = 1e-9
EH_TO_WN = 219474.63
EH_TO_EV = 27.211399
def eigh_gen(A, S, eta=1e-9):
sevals, sevecs = np.linalg.eigh(S)
trunc_indices = np.where(np.abs(sevals) > eta)[0]
X = sevecs[:,trunc_indices] / np.sqrt(sevals[trunc_indices])
Ap = X.T @ A @ X
return np.linalg.eigh(Ap)
def fnorm_op(o0, o1, o2):
return np.sqrt((o1**2).sum() + (o2**2).sum())
def zero_mat(mat):
mat[np.abs(mat) < 1e-12] = 0
return mat
def antisymmetrize_and_hermitize(T, herm=True):
# antisymmetrize the residual
if herm: T += np.einsum("ijab->abij",T.conj()) # This is the Hermitized version (i.e., [H,A]), which should then be antisymmetrized
temp = T.copy()
T -= np.einsum("ijab->jiab", temp)
T += np.einsum("ijab->jiba", temp)
T -= np.einsum("ijab->ijba", temp)
def compute_ht_h1_only(fixed_args, C1, C2, H1, T1, T2):
H1_T2_C2(None, C2, H1, None, None, T2, *fixed_args)
H1_T2_C1(C1, None, H1, None, None, T2, *fixed_args)
H1_T1_C1(C1, None, H1, None, T1, None, *fixed_args)
antisymmetrize_and_hermitize(C2)
C1 = C1 + C1.T.conj()
def compute_ht(fixed_args, C1, C2, H1, H2, T1, T2):
H1_T1_C1(C1, None, H1, None, T1, None, *fixed_args)
H1_T2_C1(C1, None, H1, None, None, T2, *fixed_args)
H2_T1_C1(C1, None, None, H2, T1, None, *fixed_args)
H2_T2_C1(C1, None, None, H2, None, T2, *fixed_args)
H1_T2_C2(None, C2, H1, None, None, T2, *fixed_args)
H2_T1_C2(None, C2, None, H2, T1, None, *fixed_args)
H2_T2_C2(None, C2, None, H2, None, T2, *fixed_args)
antisymmetrize_and_hermitize(C2)
C1 = C1 + C1.T.conj()
def compute_ht_c0(fixed_args, H1, H2, T1, T2):
C0 = H_T_C0(None, None, H1, H2, T1, T2, *fixed_args)
return C0
def regularized_denominator(x, s):
z = np.sqrt(s) * x
if abs(z) <= MACHEPS:
return np.sqrt(s)*(z - z**3/2 + z**5/6)
return (1. - np.exp(-s * x**2)) / x
def set_bit(bit_loc):
"""
Set the bit_loc-th bit in bit string f. Returns unchanged if the bit is already set. bit_loc is zero-indexed.
"""
f = 0
for loc in bit_loc:
f = f | 1<<loc
return f
def set_bit_single(f, bit_loc):
"""
Set the bit_loc-th bit in bit string f. Returns unchanged if the bit is already set. bit_loc is zero-indexed.
"""
return f | 1<<bit_loc
def clear_bit(f, bit_loc):
"""
Unset the bit_loc-th bit in bit string f. Returns unchanged if the bit is already unset. bit_loc is zero-indexed.
"""
return f & ~(1<<bit_loc)
def test_bit(f, bit_loc):
"""
Test if bit_loc in f is set. Returns 1 if set, 0 if not set.
"""
return (f & (1<<bit_loc)) >> bit_loc
def count_set_bits(f):
"""
Return the number of set (1) bits in the bit string f.
"""
return int(bin(f).count('1'))
def get_excitation_level(f1, f2):
"""
Get the excitation level between two bit strings f1 and f2, i.e., half the Hamming distance.
"""
return int(count_set_bits(f1^f2)/2)
def annop(bit_string, ispinor):
"""
Annihilation operator, annihilates spinorb in bit_string, returns the sign and the resulting bit string.
If spinorb is already empty, sign is zero and the bit string is returned unchanged.
"""
if (not test_bit(bit_string, ispinor)):
sgn = 0
else:
test_string = 0
for i in range(ispinor):
test_string = set_bit_single(test_string, i)
sgn = (-1)**(count_set_bits(bit_string & test_string))
bit_string = clear_bit(bit_string, ispinor)
return (sgn, bit_string)
def bstring_to_occ_vec(f, nelec, norbs):
occ_vec = np.zeros(nelec, dtype='int')
nfound = 0
for i in range(norbs):
if test_bit(f, i)==1:
occ_vec[nfound] = i
nfound += 1
if (nfound==nelec):
break
return occ_vec
def bstring_to_unocc_vec(f, nelec, norbs):
unocc_vec = np.zeros(norbs-nelec, dtype='int')
nfound = 0
for i in range(norbs):
if test_bit(f, i)==0:
unocc_vec[nfound] = i
nfound += 1
if (nfound==norbs-nelec):
break
return unocc_vec
def get_excit_connection(f1, f2, exlvl, nelec, norbs):
excit_bstring = f1^f2
excit = np.zeros((2,exlvl), dtype='int')
nbit_f1_found = 0
nbit_f2_found = 0
for i in range(norbs):
if (test_bit(excit_bstring, i)==1):
# Check where this electron is coming from / going to
if (test_bit(f1, i)):
excit[0][nbit_f1_found] = i
nbit_f1_found += 1
else:
excit[1][nbit_f2_found] = i
nbit_f2_found += 1
if (nbit_f1_found == exlvl and nbit_f2_found==exlvl):
break
# Get permutation!
perm = annop_mult(f1, excit[0])[0] * annop_mult(f2, excit[1])[0]
return excit, perm
def annop_mult(f, orbs):
fold = f
perm = 1
for orb in orbs:
iperm, fnew = annop(fold, orb)
perm *= iperm
fold = fnew
return perm, fnew
def make_cumulants(rdm):
try:
assert rdm['max_rdm_level'] >= 2
except AssertionError:
raise Exception('Max RDM level is 1, cumulants not necessary!')
_lamb = {'max_cumulant_level':rdm['max_rdm_level']}
_lamb['gamma1'] = rdm['1rdm']
_lamb['eta1'] = -rdm['1rdm'] + np.diag(np.zeros(rdm['1rdm'].shape[0])+1)
_lamb['lambda2'] = rdm['2rdm'] - np.einsum('pr,qs->pqrs', rdm['1rdm'], rdm['1rdm']) + np.einsum('ps,qr->pqrs', rdm['1rdm'], rdm['1rdm'])
if (rdm['max_rdm_level'] == 3):
_lamb['lambda3'] = rdm['3rdm'] - np.einsum('ps,qrtu->pqrstu',rdm['1rdm'],rdm['2rdm']) + np.einsum('pt,qrsu->pqrstu',rdm['1rdm'],rdm['2rdm']) + np.einsum('pu,qrts->pqrstu',rdm['1rdm'],rdm['2rdm'])- np.einsum('qt,prsu->pqrstu',rdm['1rdm'],rdm['2rdm']) + np.einsum('qs,prtu->pqrstu',rdm['1rdm'],rdm['2rdm']) + np.einsum('qu,prst->pqrstu',rdm['1rdm'],rdm['2rdm'])- np.einsum('ru,pqst->pqrstu',rdm['1rdm'],rdm['2rdm']) + np.einsum('rs,pqut->pqrstu',rdm['1rdm'],rdm['2rdm']) + np.einsum('rt,pqsu->pqrstu',rdm['1rdm'],rdm['2rdm'])+ 2*(np.einsum('ps,qt,ru->pqrstu',rdm['1rdm'],rdm['1rdm'],rdm['1rdm']) + np.einsum('pt,qu,rs->pqrstu',rdm['1rdm'],rdm['1rdm'],rdm['1rdm']) + np.einsum('pu,qs,rt->pqrstu',rdm['1rdm'],rdm['1rdm'],rdm['1rdm']))- 2*(np.einsum('ps,qu,rt->pqrstu',rdm['1rdm'],rdm['1rdm'],rdm['1rdm']) + np.einsum('pu,qt,rs->pqrstu',rdm['1rdm'],rdm['1rdm'],rdm['1rdm']) + np.einsum('pt,qs,ru->pqrstu',rdm['1rdm'],rdm['1rdm'],rdm['1rdm']))
return _lamb
def cq_to_pyscf(mol, bin_name):
"""
Reorder ChronusQuantum DHF MO coeffs to PySCF order, and transform to spinor AO basis.
CQ order: [La1, La2, ..., Sa1, Sa2, ..., Lb1, Lb2, ..., Sb1, Sb2, ...]
PySCF order: [La1, Lb1, ..., Sa1, Sb1, ...]
"""
f = h5py.File(bin_name, 'r')
mo_cq = f['SCF']['MO1'][:]
nspinor = mo_cq.shape[0]//2
coeffs_reorder = np.zeros_like(mo_cq)
coeffs_reorder[::2,:] = mo_cq[:,:nspinor].T
coeffs_reorder[1::2,:] = mo_cq[:,nspinor:].T
coeffs_spinor = sph_to_spinor(mol, coeffs_reorder)[0]
return coeffs_spinor
def sph_to_spinor(mol, coeffs):
"""
Transfer DHF MOs coefficients in a real spherical AO spinor basis,
>>> e.g. {p_xa, p_xb, p_ya, p_yb, p_za, p_zb},
>>> each of the above is a two-spinor, for example, p_xa=(px, 0), p_xb=(0, px) etc.
to the corresponding complex spinor basis.
>>> e.g. {p_{1/2,-1/2}, p_{1/2,+1/2}, p_{3/2,-3/2}, p_{3/2,-1/2}, p_{3/2,+1/2}, p_{3/2,+3/2}},
>>> each of the above is a two-spinor, for example, p_{1/2,-1/2} = (x-iy, z)/sqrt(3)
"""
nspinor = coeffs.shape[0]//2
rotmat = np.zeros((nspinor,nspinor), dtype='complex128')
rotmat[::2,:] = mol.sph2spinor_coeff()[0]
rotmat[1::2,:] = mol.sph2spinor_coeff()[1]
mo_rot = coeffs.copy()
# To see why the complex conjugate needs to be taken, we use an example:
# p_{1/2,-1/2} \propto (x-iy, z), so our rotmat gives for the column of p_{1/2,-1/2}
# [1, 0, -i, 0, 0, -1] for the real spherical AO spinors [pxa, pxb, pya, pyb, pza, pzb].
# This means to rotate this linear combination of real spherical p spinors to p_{1/2,-1/2}
# (i.e., [-1, 0, 0, 0, 0, 0] in the complex representation),
# we need to dot it with [1, 0, i, 0, 0, -1], which suggests that we need to take the complex conjugate of the rotmat.
mo_rot[:nspinor,:] = np.einsum('uv,ui->vi', np.conj(rotmat), coeffs[:nspinor,:])
mo_rot[nspinor:,:] = np.einsum('uv,ui->vi', np.conj(rotmat), coeffs[nspinor:,:])
return mo_rot, rotmat
def form_cas_hamiltonian(H1body, H2body, det_strings, verbose, cas, ncore=0, dtype='complex128'):
ncombs = len(det_strings)
_mem = ncombs**2*16/1e9
if (_mem < 1.0):
if (verbose): print(f'Will now allocate {_mem*1000:.3f} MB memory for the CASCI Hamiltonian!')
else:
if (verbose): print(f'Will now allocate {_mem:.3f} GB memory for the CASCI Hamiltonian!')
_hamil_det = np.zeros((ncombs,ncombs), dtype=dtype)
for i in range(ncombs):
for j in range(i+1):
exlvl = get_excitation_level(det_strings[i], det_strings[j])
if (exlvl <= 2):
if (i==j):
occ = bstring_to_occ_vec(det_strings[i], *cas)
_hamil_det[i,i] = 0
for iocc in occ:
_hamil_det[i,i] += H1body[iocc,iocc]
for jocc in occ:
_hamil_det[i,i] += 0.5*H2body[iocc+ncore,jocc+ncore,iocc+ncore,jocc+ncore]
elif (exlvl == 1):
occ = bstring_to_occ_vec(det_strings[i], *cas)
conn, perm = get_excit_connection(det_strings[i], det_strings[j], exlvl, *cas)
_hamil_det[i,j] = H1body[conn[0],conn[1]]
for iocc in occ:
_hamil_det[i,j] += H2body[conn[0]+ncore, iocc+ncore, conn[1]+ncore, iocc+ncore]
_hamil_det[i,j] *= perm
_hamil_det[j,i] = np.conj(_hamil_det[i,j])
elif (exlvl == 2):
conn, perm = get_excit_connection(det_strings[i], det_strings[j], exlvl, *cas)
_hamil_det[i,j] = perm*H2body[conn[0][0]+ncore, conn[0][1]+ncore, conn[1][0]+ncore, conn[1][1]+ncore]
_hamil_det[j,i] = np.conj(_hamil_det[i,j])
return _hamil_det
def get_hamil_element(f0, f1, H1body, H2body, cas, ncore=0):
"""
<f0|H|f1>
"""
_hmatel = 0.0
exlvl = get_excitation_level(f0, f1)
if (exlvl <= 2):
if (exlvl == 0):
occ = bstring_to_occ_vec(f0, *cas)
_hmatel = 0
for iocc in occ:
_hmatel += H1body[iocc,iocc]
for jocc in occ:
_hmatel += 0.5*H2body[iocc+ncore,jocc+ncore,iocc+ncore,jocc+ncore]
elif (exlvl == 1):
occ = bstring_to_occ_vec(f0, *cas)
conn, perm = get_excit_connection(f0, f1, exlvl, *cas)
_hmatel = H1body[conn[0],conn[1]]
for iocc in occ:
_hmatel += H2body[conn[0]+ncore, iocc+ncore, conn[1]+ncore, iocc+ncore]
_hmatel *= perm
elif (exlvl == 2):
conn, perm = get_excit_connection(f0, f1, exlvl, *cas)
_hmatel = perm*H2body[conn[0][0]+ncore, conn[0][1]+ncore, conn[1][0]+ncore, conn[1][1]+ncore]
return _hmatel
def form_cas_determinant_strings(nelec, norbs):
"""
Returns the unrestricted (no spin or spatial symmetry imposed) list of bitstrings in a (nelec, n(spin(or))orbs) CAS.
"""
ncombs = scipy.special.comb(norbs, nelec, exact=True)
det_strings = list(map(set_bit, list(itertools.combinations(range(norbs),nelec))))
assert(len(det_strings) == ncombs)
return ncombs, det_strings
def form_cas_determinant_strings_general(occlist, actlist, nelec):
"""
Returns the unrestricted (no spin or spatial symmetry imposed) list of bitstrings in the active space generated by distributing nelec in the occlist.
"""
# just in case..
actlist = list(np.sort(actlist))
occlist = list(np.sort(occlist))
norbs = len(actlist)
ncombs = scipy.special.comb(norbs, nelec, exact=True)
det_strings = list(map(set_bit, [list(_) + occlist for _ in list(itertools.combinations(actlist,nelec))] ))
assert(len(det_strings) == ncombs)
return ncombs, det_strings
def get_1_rdm_sa(det_strings, cas, states, weights, verbose, dtype):
_sa_rdm = np.zeros((cas[1],cas[1]), dtype=dtype)
for i in range(len(weights)):
_sa_rdm += weights[i] * get_1_rdm(det_strings, cas, states[i], verbose, dtype)
return _sa_rdm
def get_2_rdm_sa(det_strings, cas, states, weights, verbose, dtype):
_sa_rdm = np.zeros((cas[1],cas[1],cas[1],cas[1]), dtype=dtype)
for i in range(len(weights)):
_sa_rdm += weights[i] * get_2_rdm(det_strings, cas, states[i], verbose, dtype)
return _sa_rdm
def get_3_rdm_sa(det_strings, cas, states, weights, verbose, dtype):
_sa_rdm = np.zeros((cas[1],cas[1],cas[1],cas[1],cas[1],cas[1]), dtype=dtype)
for i in range(len(weights)):
_sa_rdm += weights[i] * get_3_rdm(det_strings, cas, states[i], verbose, dtype)
return _sa_rdm
def get_1_rdm(det_strings, cas, psi, verbose, dtype):
return pyscf.fci.fci_dhf_slow.make_rdm12(psi, cas[1], cas[0], reorder=True)[0]
def get_2_rdm(det_strings, cas, psi, verbose, dtype):
return pyscf.fci.fci_dhf_slow.make_rdm12(psi, cas[1], cas[0], reorder=True)[1].transpose(0,2,1,3) # pyscf rdm2[p,q,r,s] is gamma2^{pr}_{qs}
def get_1_rdm_slow(det_strings, cas, psi, verbose, dtype):
_t0 = time.time()
_rdm = np.zeros((cas[1],cas[1]), dtype=dtype)
for i in range(len(det_strings)):
occ_vec = bstring_to_occ_vec(det_strings[i], *cas)
contrib = np.conjugate(psi[i])*psi[i]
for p in occ_vec:
_rdm[p, p] += contrib
for j in range(len(det_strings)):
if (get_excitation_level(det_strings[i], det_strings[j]) == 1):
[[p], [q]], perm = get_excit_connection(det_strings[i], det_strings[j], 1, *cas)
_rdm[p, q] += perm*np.conjugate(psi[i])*psi[j]
_t1 = time.time()
if (verbose): print(f'Time taken for 1-RDM build: {(_t1-_t0):15.7f} s')
return _rdm
def get_2_rdm_slow(det_strings, cas, psi, verbose, dtype):
_t0 = time.time()
_rdm = np.zeros((cas[1],cas[1],cas[1],cas[1]), dtype=dtype)
if (cas[0] < 2): return _rdm
for i in range(len(det_strings)):
# <p+ q+ q p>
occ_vec = bstring_to_occ_vec(det_strings[i], *cas)
# get all possible pairs of occupied spinorb
contrib = np.conjugate(psi[i])*psi[i]
for ip, p in enumerate(occ_vec):
for q in occ_vec[:ip]:
_rdm[p, q, p, q] += contrib
_rdm[p, q, q, p] -= contrib
_rdm[q, p, p, q] -= contrib
_rdm[q, p, q, p] += contrib
for j in range(len(det_strings)):
exlvl = get_excitation_level(det_strings[i], det_strings[j])
if (exlvl==1):
# We need to accumulate all <p+ q+ q r>, it's sufficient to get the parity of <p+ r> since q+ q always cancel out
[[p],[r]], perm = get_excit_connection(det_strings[i], det_strings[j], 1, *cas)
f = annop(det_strings[i],p)[1]
occ_vec = bstring_to_occ_vec(f, cas[0]-1, cas[1])
contrib = perm*np.conjugate(psi[i])*psi[j]
for q in occ_vec:
_rdm[p, q, r, q] += contrib
_rdm[p, q, q, r] -= contrib
_rdm[q, p, r, q] -= contrib
_rdm[q, p, q, r] += contrib
elif (exlvl==2):
# <p+ q+ s r>
conn, perm = get_excit_connection(det_strings[i], det_strings[j], 2, *cas)
p, q = conn[0] # get_excit_connection's perm is <q+ p+ r s>
r, s = conn[1] # conn is in ascending order in spinor index,
contrib = perm*np.conjugate(psi[i])*psi[j]
_rdm[p, q, r, s] += contrib
_rdm[p, q, s, r] -= contrib
_rdm[q, p, r, s] -= contrib
_rdm[q, p, s, r] += contrib
_t1 = time.time()
if (verbose): print(f'Time taken for 2-RDM build: {(_t1-_t0):15.7f} s')
return _rdm
def get_3_rdm(det_strings, cas, psi, verbose, dtype):
"""
gamma3^{pqr}_{stu} = <p+ q+ r+ u t s>
"""
_t0 = time.time()
_rdm = np.zeros((cas[1],cas[1],cas[1],cas[1],cas[1],cas[1]), dtype=dtype)
if (cas[0] < 3): return _rdm
for i in range(len(det_strings)):
occ_vec = bstring_to_occ_vec(det_strings[i], *cas)
# get all possible triplets of occupied spinors
contrib = np.conjugate(psi[i])*psi[i]
for ip, p in enumerate(occ_vec):
for iq, q in enumerate(occ_vec[:ip]):
for r in occ_vec[:iq]:
_rdm[p, q, r, p, q, r] += contrib
_rdm[q, r, p, p, q, r] += contrib
_rdm[r, p, q, p, q, r] += contrib
_rdm[p, r, q, p, q, r] -= contrib
_rdm[r, q, p, p, q, r] -= contrib
_rdm[q, p, r, p, q, r] -= contrib
_rdm[p, q, r, q, r, p] += contrib
_rdm[q, r, p, q, r, p] += contrib
_rdm[r, p, q, q, r, p] += contrib
_rdm[p, r, q, q, r, p] -= contrib
_rdm[r, q, p, q, r, p] -= contrib
_rdm[q, p, r, q, r, p] -= contrib
_rdm[p, q, r, r, p, q] += contrib
_rdm[q, r, p, r, p, q] += contrib
_rdm[r, p, q, r, p, q] += contrib
_rdm[p, r, q, r, p, q] -= contrib
_rdm[r, q, p, r, p, q] -= contrib
_rdm[q, p, r, r, p, q] -= contrib
_rdm[p, q, r, p, r, q] -= contrib
_rdm[q, r, p, p, r, q] -= contrib
_rdm[r, p, q, p, r, q] -= contrib
_rdm[p, r, q, p, r, q] += contrib
_rdm[r, q, p, p, r, q] += contrib
_rdm[q, p, r, p, r, q] += contrib
_rdm[p, q, r, r, q, p] -= contrib
_rdm[q, r, p, r, q, p] -= contrib
_rdm[r, p, q, r, q, p] -= contrib
_rdm[p, r, q, r, q, p] += contrib
_rdm[r, q, p, r, q, p] += contrib
_rdm[q, p, r, r, q, p] += contrib
_rdm[p, q, r, q, p, r] -= contrib
_rdm[q, r, p, q, p, r] -= contrib
_rdm[r, p, q, q, p, r] -= contrib
_rdm[p, r, q, q, p, r] += contrib
_rdm[r, q, p, q, p, r] += contrib
_rdm[q, p, r, q, p, r] += contrib
for j in range(len(det_strings)):
exlvl = get_excitation_level(det_strings[i], det_strings[j])
if (exlvl==1):
# We need to accumulate all <p+ q+ r+ r q s>, it's sufficient to get the parity of <p+ s> since q+r+ rq always cancel out
[[p], [s]], perm = get_excit_connection(det_strings[i], det_strings[j], 1, *cas)
f = annop(det_strings[i],p)[1]
occ_vec = bstring_to_occ_vec(f, cas[0]-1, cas[1])
contrib = perm*np.conjugate(psi[i])*psi[j]
for iq, q in enumerate(occ_vec):
# q cannot be == r as violates exclusion principle
for r in occ_vec[:iq]:
_rdm[p, q, r, s, q, r] += contrib
_rdm[q, r, p, s, q, r] += contrib
_rdm[r, p, q, s, q, r] += contrib
_rdm[p, r, q, s, q, r] -= contrib
_rdm[r, q, p, s, q, r] -= contrib
_rdm[q, p, r, s, q, r] -= contrib
_rdm[p, q, r, q, r, s] += contrib
_rdm[q, r, p, q, r, s] += contrib
_rdm[r, p, q, q, r, s] += contrib
_rdm[p, r, q, q, r, s] -= contrib
_rdm[r, q, p, q, r, s] -= contrib
_rdm[q, p, r, q, r, s] -= contrib
_rdm[p, q, r, r, s, q] += contrib
_rdm[q, r, p, r, s, q] += contrib
_rdm[r, p, q, r, s, q] += contrib
_rdm[p, r, q, r, s, q] -= contrib
_rdm[r, q, p, r, s, q] -= contrib
_rdm[q, p, r, r, s, q] -= contrib
_rdm[p, q, r, s, r, q] -= contrib
_rdm[q, r, p, s, r, q] -= contrib
_rdm[r, p, q, s, r, q] -= contrib
_rdm[p, r, q, s, r, q] += contrib
_rdm[r, q, p, s, r, q] += contrib
_rdm[q, p, r, s, r, q] += contrib
_rdm[p, q, r, r, q, s] -= contrib
_rdm[q, r, p, r, q, s] -= contrib
_rdm[r, p, q, r, q, s] -= contrib
_rdm[p, r, q, r, q, s] += contrib
_rdm[r, q, p, r, q, s] += contrib
_rdm[q, p, r, r, q, s] += contrib
_rdm[p, q, r, q, s, r] -= contrib
_rdm[q, r, p, q, s, r] -= contrib
_rdm[r, p, q, q, s, r] -= contrib
_rdm[p, r, q, q, s, r] += contrib
_rdm[r, q, p, q, s, r] += contrib
_rdm[q, p, r, q, s, r] += contrib
if (exlvl==2):
# We need to accumulate all <p+ q+ r+ r t s>
conn, perm = get_excit_connection(det_strings[i], det_strings[j], 2, *cas)
p, q = conn[0] # get_excit_connection's perm is <q+ p+ r s>
s, t = conn[1] # conn is in ascending order in spinor index,
f = annop_mult(det_strings[i],conn[0])[1]
occ_vec = bstring_to_occ_vec(f, cas[0]-2, cas[1])
contrib = perm*np.conjugate(psi[i])*psi[j]
for r in occ_vec:
_rdm[p, q, r, s, t, r] += contrib
_rdm[q, r, p, s, t, r] += contrib
_rdm[r, p, q, s, t, r] += contrib
_rdm[p, r, q, s, t, r] -= contrib
_rdm[r, q, p, s, t, r] -= contrib
_rdm[q, p, r, s, t, r] -= contrib
_rdm[p, q, r, t, r, s] += contrib
_rdm[q, r, p, t, r, s] += contrib
_rdm[r, p, q, t, r, s] += contrib
_rdm[p, r, q, t, r, s] -= contrib
_rdm[r, q, p, t, r, s] -= contrib
_rdm[q, p, r, t, r, s] -= contrib
_rdm[p, q, r, r, s, t] += contrib
_rdm[q, r, p, r, s, t] += contrib
_rdm[r, p, q, r, s, t] += contrib
_rdm[p, r, q, r, s, t] -= contrib
_rdm[r, q, p, r, s, t] -= contrib
_rdm[q, p, r, r, s, t] -= contrib
_rdm[p, q, r, s, r, t] -= contrib
_rdm[q, r, p, s, r, t] -= contrib
_rdm[r, p, q, s, r, t] -= contrib
_rdm[p, r, q, s, r, t] += contrib
_rdm[r, q, p, s, r, t] += contrib
_rdm[q, p, r, s, r, t] += contrib
_rdm[p, q, r, r, t, s] -= contrib
_rdm[q, r, p, r, t, s] -= contrib
_rdm[r, p, q, r, t, s] -= contrib
_rdm[p, r, q, r, t, s] += contrib
_rdm[r, q, p, r, t, s] += contrib
_rdm[q, p, r, r, t, s] += contrib
_rdm[p, q, r, t, s, r] -= contrib
_rdm[q, r, p, t, s, r] -= contrib
_rdm[r, p, q, t, s, r] -= contrib
_rdm[p, r, q, t, s, r] += contrib
_rdm[r, q, p, t, s, r] += contrib
_rdm[q, p, r, t, s, r] += contrib
if (exlvl==3):
conn, perm = get_excit_connection(det_strings[i], det_strings[j], 3, *cas)
p, q, r = conn[0]
s, t, u = conn[1]
contrib = perm*np.conjugate(psi[i])*psi[j]
_rdm[p, q, r, s, t, u] += contrib
_rdm[q, r, p, s, t, u] += contrib
_rdm[r, p, q, s, t, u] += contrib
_rdm[p, r, q, s, t, u] -= contrib
_rdm[r, q, p, s, t, u] -= contrib
_rdm[q, p, r, s, t, u] -= contrib
_rdm[p, q, r, t, u, s] += contrib
_rdm[q, r, p, t, u, s] += contrib
_rdm[r, p, q, t, u, s] += contrib
_rdm[p, r, q, t, u, s] -= contrib
_rdm[r, q, p, t, u, s] -= contrib
_rdm[q, p, r, t, u, s] -= contrib
_rdm[p, q, r, u, s, t] += contrib
_rdm[q, r, p, u, s, t] += contrib
_rdm[r, p, q, u, s, t] += contrib
_rdm[p, r, q, u, s, t] -= contrib
_rdm[r, q, p, u, s, t] -= contrib
_rdm[q, p, r, u, s, t] -= contrib
_rdm[p, q, r, s, u, t] -= contrib
_rdm[q, r, p, s, u, t] -= contrib
_rdm[r, p, q, s, u, t] -= contrib
_rdm[p, r, q, s, u, t] += contrib
_rdm[r, q, p, s, u, t] += contrib
_rdm[q, p, r, s, u, t] += contrib
_rdm[p, q, r, u, t, s] -= contrib
_rdm[q, r, p, u, t, s] -= contrib
_rdm[r, p, q, u, t, s] -= contrib
_rdm[p, r, q, u, t, s] += contrib
_rdm[r, q, p, u, t, s] += contrib
_rdm[q, p, r, u, t, s] += contrib
_rdm[p, q, r, t, s, u] -= contrib
_rdm[q, r, p, t, s, u] -= contrib
_rdm[r, p, q, t, s, u] -= contrib
_rdm[p, r, q, t, s, u] += contrib
_rdm[r, q, p, t, s, u] += contrib
_rdm[q, p, r, t, s, u] += contrib
_t1 = time.time()
if (verbose): print(f'Time taken for 3-RDM build: {(_t1-_t0):15.7f} s')
return _rdm
def enumerate_determinants(f0, nelec, norb, exlvl):
occ_vec = bstring_to_occ_vec(f0, nelec, norb)
unocc_vec = bstring_to_unocc_vec(f0, nelec, norb)
nunocc = norb - nelec
ndets = scipy.special.comb(nelec, exlvl, exact=True) * scipy.special.comb(nunocc, exlvl, exact=True)
occ_excited = list(itertools.combinations(occ_vec,nelec-exlvl))
unocc_excited = list(itertools.combinations(unocc_vec,exlvl))
excited_occ_vecs = [sum(_, ()) for _ in list(itertools.product(occ_excited, unocc_excited))]
det_strings = list(map(set_bit, excited_occ_vecs))
assert len(det_strings) == ndets
return det_strings
def get_H_IP(fi, pspace, psi, H1body, H2body, cas):
"""
Evaluates <Phi_I|H|Psi_P> = V*
"""
vj = 0.j
for j, cj in enumerate(psi):
vj += cj*get_hamil_element(fi, pspace[j], H1body, H2body, cas)
return vj
def annihilate_state(psi, orb, basis):
ann_psi = np.zeros_like(psi)
ann_basis = np.zeros(len(basis), dtype='int')
iann = 0
for i in range(len(psi)):
_ann_i = annop(basis[i], orb)
if (_ann_i[0] != 0):
ann_psi[iann] = _ann_i[0] * psi[i]
ann_basis[iann] = _ann_i[1]
iann += 1
ann_psi = ann_psi[:iann]
ann_basis = ann_basis[:iann]
argsort = np.argsort(ann_basis)
return ann_psi[argsort], ann_basis[argsort]
def eri_h5_write(mol, mo_coeffs, intor, erifile='tmp.h5', gaunt=False, terminal=False):
phase = -1 if gaunt else 1
pyscf.ao2mo.r_outcore.general(mol, mo_coeffs, erifile=erifile, dataname='tmp', intor=intor, aosym='s1')
blksize = 400
nij = mo_coeffs[0].shape[1] * mo_coeffs[1].shape[1]
with h5py.File(erifile, mode='r+') as feri:
for i0, i1 in pyscf.lib.prange(0, nij, blksize):
buf = feri['mo_eri'][i0:i1]
buf += phase*feri['tmp'][i0:i1]
feri['mo_eri'][i0:i1] = buf
if (terminal):
del feri['tmp']
def clean_tmp():
for i in glob.glob('tmp*'):
os.remove(i)
def print_energies(energies, nstates=None, splitting=True):
if (nstates is None): nstates = len(energies)
print('{:<10}{:<20}{:<20}{:<20}{:<20}'.format('State','Energy / Eh','Splitting / Eh','Splitting / cm-1', 'Splitting / meV'))
for istate in range(nstates):
splitting = energies[istate] - energies[istate-1] if (istate>0) else 0
print('{:<10}{:<20}{:<20}{:<20}{:<20}'.format(f'{istate:d}',f'{energies[istate]:+.7e}',f'{splitting:+.7e}',f'{splitting*EH_TO_WN:+.7e}',f'{splitting*EH_TO_EV*1000:+.7e}'))
class RelForte:
def __init__(self, mol, complex=True, c0=None, verbose=True, density_fitting=False, decontract=False):
if (type(density_fitting) is bool):
self.density_fitting = density_fitting
self.df_basis = None
elif(type(density_fitting) is str):
self.density_fitting = True
self.df_basis = density_fitting
self.decontract = decontract
if (self.decontract):
self.mol, _ = mol.decontract_basis()
else:
self.mol = mol
self.nuclear_repulsion = self.mol.energy_nuc()
self.nelec = sum(self.mol.nelec)
self.nocc = self.nelec
self.nao = self.mol.nao
self.nlrg = self.mol.nao*2
self.nvirtual = self.nlrg - self.nocc
self.verbose = verbose
self.mf_in = None
self.dtype = 'complex128' if complex else 'float64'
if (c0 is None):
self.c0 = pyscf.lib.param.LIGHT_SPEED
else:
self.c0 = c0
#pyscf.lib.param.LIGHT_SPEED = c0
def run_rhf(self, mf_in=None, transform=False, debug=True, frozen=None, dump_mo_coeff=None):
_ti = time.time()
if (self.verbose):
print('='*47)
print('{:^47}'.format('PySCF RHF interface'))
print('='*47)
self.mf_in = None
if mf_in is not None:
self.mf_energy = mf_in.e_tot
self.mo_coeff = mf_in.mo_coeff
self.mf_in = mf_in
else:
if (self.density_fitting):
if (self.verbose): print('{:#^47}'.format('Enabling density fitting!'))
self.rhf = pyscf.scf.RHF(self.mol).density_fit() if self.df_basis is None else pyscf.scf.RHF(self.mol).density_fit(self.df_basis)
else:
self.rhf = pyscf.scf.RHF(self.mol)
self.mf_energy = self.rhf.kernel()
if (self.verbose): print(f"Non-relativistic RHF Energy: {self.mf_energy:15.7f} Eh")
if (dump_mo_coeff is not None):
if dump_mo_coeff != False:
if type(dump_mo_coeff) is str:
_fname = dump_mo_coeff
else:
_fname = 'mo_coeff'
if (self.verbose): print(f'Dumping MO coefficients to {_fname}')
np.save(_fname, self.rhf.mo_coeff)
self.mo_coeff = self.rhf.mo_coeff
_t1 = time.time()
print(f'PySCF RHF time: {_t1-_ti:15.7f} s')
print('-'*47)
if (transform):
self.nonrel_ao2mo(self.mo_coeff, frozen)
if (debug and self.verbose):
self.rhf_e1 = np.einsum('ii->',self.rhf_hcore_spinorb[:self.nocc, :self.nocc])
self.rhf_e2 = 0.5*np.einsum('ijij->',self.eri[:self.nocc, :self.nocc, :self.nocc, :self.nocc])
self.rhf_e_rebuilt = self.rhf_e1 + self.rhf_e2 + self.nuclear_repulsion
print(f"Rebuilt RHF Energy: {self.rhf_e_rebuilt.real:15.7f} Eh")
print(f"Error to PySCF: {np.abs(self.rhf_e_rebuilt.real - self.mf_energy):15.7f} Eh")
if (frozen is None): print(f"Diff 1e: {np.abs(self.rhf.scf_summary['e1']-self.rhf_e1):15.7f} Eh")
if (frozen is None): print(f"Diff 2e: {np.abs(self.rhf.scf_summary['e2']-self.rhf_e2):15.7f} Eh")
print('-'*47)
if (self.verbose):
_tf = time.time()
print(f'RHF time: {_tf-_ti:15.7f} s')
print('='*47)
def run_dhf(self, transform=False, debug=False, frozen=None, with_gaunt=False, with_breit=False, with_ssss=True, dump_mo_coeff=None, algo='disk', erifile=None, fake_dhf=None, init_guess='minao'):
_ti = time.time()
if (self.verbose):
print('='*47)
print('{:^47}'.format('PySCF DHF interface'))
print('='*47)
# Run relativistic Dirac-Hartree-Fock
if (self.density_fitting):
if (self.verbose): print('{:#^47}'.format('Enabling density fitting!'))
self.dhf = pyscf.scf.DHF(self.mol).density_fit() if self.df_basis is None else pyscf.scf.DHF(self.mol).density_fit(self.df_basis)
else:
self.dhf = pyscf.scf.DHF(self.mol)
self.dhf.with_gaunt = with_gaunt
self.dhf.with_breit = with_breit
self.dhf.with_ssss = with_ssss
if (type(fake_dhf) is str):
f = h5py.File(fake_dhf, 'r')
self.mf_energy = f['SCF']['TOTAL_ENERGY'][:][0]
else:
self.dhf.init_guess = init_guess
self.mf_energy = self.dhf.kernel()
if (self.verbose):
_t0 = time.time()
print(f"Relativistic DHF Energy: {self.mf_energy:15.7f} Eh")
print(f'PySCF RHF time: {_t0-_ti:15.7f} s')
print('-'*47)
if (dump_mo_coeff is not None):
if dump_mo_coeff != False:
if type(dump_mo_coeff) is str:
_fname = dump_mo_coeff
else:
_fname = 'mo_coeff'
if (self.verbose): print(f'Dumping MO coefficients to {_fname}')
np.save(_fname, self.dhf.mo_coeff)
if (transform):
self.rel_ao2mo(self.dhf.mo_coeff, frozen, algo, erifile)
self.dhf_e1 = np.einsum('ii->',self.dhf_hcore_mo[:self.nocc, :self.nocc])
self.dhf_e2 = 0.5*np.einsum('ijij->',self.eri[:self.nocc, :self.nocc, :self.nocc, :self.nocc])
self.dhf_e_rebuilt = self.dhf_e1 + self.dhf_e2 + self.nuclear_repulsion
if (debug and self.verbose):
print(f"Rebuilt DHF Energy: {self.dhf_e_rebuilt.real:15.7f} Eh")
print(f"Error to PySCF: {np.abs(self.dhf_e_rebuilt.real - self.mf_energy):15.7f} Eh")
if (frozen is None):
print(f"Diff 1e: {np.abs(self.dhf.scf_summary['e1']-self.dhf_e1):15.7f} Eh")
print(f"Diff 2e: {np.abs(self.dhf.scf_summary['e2']-self.dhf_e2):15.7f} Eh")
_t3 = time.time()
if (self.verbose):
print(f'Total time taken: {(_t3-_t0):15.7f} s')
print('='*47)
def do_mmfx2c(self, mo_coeff, mode='orthonormal'):
if (mode == 'orthonormal'):
_s, _U_ovlp = np.linalg.eigh(self.dhf.get_ovlp()) # Diagonalize overlap matrix
_X_lowdin = _U_ovlp @ np.diag(_s**(-0.5)) # The Lowdin canonicalization matrix
_Xinv = np.diag(np.sqrt(_s)) @ _U_ovlp.T.conj()
assert (np.allclose(_X_lowdin @ _Xinv, np.eye(self.norb)))
_F_4c = _X_lowdin.T.conj() @ self.dhf.get_fock() @ _X_lowdin
_e, _mo_coeff_on = np.linalg.eigh(_F_4c)
assert np.allclose(self.dhf.mo_energy, _e)
_cp_neg = _mo_coeff_on[self.nlrg:, :self.nlrg]
_cl_neg = _mo_coeff_on[:self.nlrg, :self.nlrg]
_Xtrans = np.linalg.solve(_cp_neg@_cp_neg.T.conj(), -_cp_neg@_cl_neg.T.conj())
_W1 = np.block([[np.eye(self.nlrg), -_Xtrans.T.conj()],[_Xtrans, np.eye(self.nlrg)]])
_W2 = np.block([[np.diag((1+np.diag(_Xtrans.T.conj()@_Xtrans))**(-0.5)) , np.zeros((self.nlrg, self.nlrg))],\
[np.zeros((self.nlrg, self.nlrg)), np.diag(((1+np.diag(_Xtrans@_Xtrans.T.conj()))**(-0.5)))]])
self.U_x2c = _W1 @ _W2
print(np.abs(self.U_x2c).sum())
_F_2c = (self.U_x2c.T.conj() @ _F_4c @ self.U_x2c)[:self.nlrg, :self.nlrg]
_e_2c, _C_2c_on = np.linalg.eigh(_F_2c)
_X_lowdin_2c = (_X_lowdin @ self.U_x2c)[:self.nlrg, :self.nlrg]
return _X_lowdin_2c @ _C_2c_on
elif (mode == 'atomic'):
_cp_neg = mo_coeff[self.nlrg:, :self.nlrg]
_cl_neg = mo_coeff[:self.nlrg, :self.nlrg]
_Xtrans = np.linalg.solve(_cp_neg@_cp_neg.T.conj(), -_cp_neg@_cl_neg.T.conj())
_W1 = np.block([[np.eye(self.nlrg), -_Xtrans.T.conj()],[_Xtrans, np.eye(self.nlrg)]])
_W2 = np.block([[np.diag((1+np.diag(_Xtrans.T.conj()@_Xtrans))**(-0.5)) , np.zeros((self.nlrg, self.nlrg))],\
[np.zeros((self.nlrg, self.nlrg)), np.diag(((1+np.diag(_Xtrans@_Xtrans.T.conj()))**(-0.5)))]])
self.U_x2c = _W1 @ _W2
return (self.U_x2c.T.conj() @ mo_coeff)[:self.nlrg, self.nlrg:]
def run_mp2(self, relativistic=True):
if (relativistic):
_hcore = self.dhf_hcore_mo
_eri = self.eri
_method = 'Relativistic'
_e_scf = self.mf_energy
else:
_hcore = self.rhf_hcore_spinorb
_eri = self.eri
_method = 'Non-relativistic'
_e_scf = self.mf_energy
if (self.verbose):
print('')
print('='*47)
print('{:^47}'.format(f'{_method} MP2'))
print('='*47)
_t0 = time.time()
_upq = np.einsum('piqi->pq',_eri[:,:self.nocc,:,:self.nocc])
self.fock_mo = _upq + _hcore
self.D2 = np.zeros((self.nocc,self.nocc,self.nvirtual,self.nvirtual))
_e = np.diag(self.fock_mo)
for i in range(self.nocc):
for j in range(self.nocc):
for a in range(self.nvirtual):
for b in range(self.nvirtual):
self.D2[i,j,a,b] = -1./((_e[a+self.nocc] + _e[b+self.nocc] - _e[i] - _e[j]).real)
_oovv = _eri[:self.nocc,:self.nocc,self.nocc:,self.nocc:]
_vvoo = _eri[self.nocc:,self.nocc:,:self.nocc,:self.nocc]
self.e_mp2 = 0.25*np.einsum('ijab,ijab,abij->',_oovv,self.D2,_vvoo)
try:
assert(abs(self.e_mp2.imag) < MACHEPS)
except AssertionError:
print(f'Imaginary part of MP2 energy is larger than {MACHEPS}')
self.e_mp2 = self.e_mp2.real
if (not relativistic):
self.nonrel_mp2 = pyscf.mp.MP2(self.rhf)
_e_mp2 = self.nonrel_mp2.kernel()[0]
_t1 = time.time()
if (self.verbose):
print(f'MP2 Ecorr: {self.e_mp2.real:15.7f} Eh')
print(f'MP2 Energy: {(self.e_mp2 + _e_scf).real:15.7f} Eh')
if (not relativistic): print(f'Error to PySCF: {(self.e_mp2-_e_mp2):15.7f} Eh')
print(f'Time taken: {(_t1-_t0):15.7f} s')
print('='*47)
def run_casci(self, cas=None, do_fci=False, rdm_level=0, relativistic=True, semi_canonicalize=True, state_avg=None, sa_weights=None):
_t0 = time.time()
try:
assert ((cas is None) and do_fci) or ((cas is not None) and (not do_fci))
except AssertionError:
raise Exception("If not doing FCI then a CAS must be provided via the 'cas' argument!")
if (self.mf_in is not None and isinstance(self.mf_in, pyscf.mcscf.casci.CASCI)):
if (isinstance(self.mf_in.fcisolver, pyscf.mcscf.addons.StateAverageFCISolver)):
state_avg = np.arange(len(self.mf_in.fcisolver.weights))
sa_weights = self.mf_in.fcisolver.weights
else:
state_avg = [0]
sa_weights = [1.0]
elif (state_avg is not None):
try:
assert (type(state_avg) is list)
except AssertionError:
raise Exception("state_avg must be a list of CASCI states to average over!")
try:
assert (type(sa_weights) is list and len(sa_weights) == len(state_avg))
except AssertionError:
raise Exception("sa_weights must be a list of the same length as state_avg!")
try:
assert (np.isclose(sum(sa_weights), 1.0))
except AssertionError:
raise Exception("sa_weights doesn't add up to 1.0!")
else:
state_avg = [0]
sa_weights = [1.0]
self.state_avg = state_avg
self.sa_weights = sa_weights
if (do_fci):
cas = (self.nelec, self.nlrg)
self.cas = cas
if (type(cas) is tuple):
if (type(cas[0]) is int):
# Using a CAS
try:
assert int(cas[0]) <= int(cas[1])
except AssertionError:
raise Exception("Number of CAS electrons must be <= number of CAS spinors!")
self.ncore = self.nelec - self.cas[0]
self.nact = self.cas[1]
self.nvirt = self.nlrg-(self.ncore+self.nact) # This is different from nvirtual, which is in the single-reference sense (nvirt in the HF reference)
self.nhole = self.ncore+self.nact
self.npart = self.nact+self.nvirt
self.core = slice(0,self.ncore)
self.active = slice(self.ncore, self.ncore+self.nact)
self.virt = slice(self.ncore+self.nact, self.nlrg)
self.hole = slice(0,self.ncore+self.nact)
self.part = slice(self.ncore, self.nlrg)
elif (type(cas[0]) is list):
# Using a GAS: cas = (occ_orbs, active_orbs)
try:
assert len(cas[1]) + len(cas[2]) > self.nelec
except AssertionError:
raise Exception("Number of frozen + active spinorbitals <= number of electrons!")
self.ncore = len(self.cas[0])
self.nact = len(self.cas[1])
self.nvirt = self.nlrg-(self.ncore+self.nact) # This is different from nvirtual, which is in the single-reference sense (nvirt in the HF reference)
self.nhole = self.ncore+self.nact
self.npart = self.nact+self.nvirt
self.core = self.cas[0]
self.active = self.cas[1]
self.virt = list(np.sort(list(set(list(range(self.nlrg))) - set(self.core) - set(self.active))))
self.hole = list(np.sort(self.core + self.active))
self.part = list(np.sort(self.active + self.virt))