-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelper_cc.py
1680 lines (1304 loc) · 63.7 KB
/
helper_cc.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
# A simple Psi4 script to compute CCSD linear response properties (spin-free) from
# RHF reference Scipy and numpy python modules are required
# Algorithms were taken directly from Daniel Crawford's programming website:
# http://sirius.chem.vt.edu/wiki/doku.php?id=crawdad:programming
# Equations were spin-adapted using unitary group approach used in the moelcular
# electronic structure theory book.
# Special thanks to Dr. T Daniel Crawford for help in spin-adaptation of
# the equations and Lori Burns for integral help
#
# Created by: Ashutosh Kumar, Daniel G. A. Smith.
# Date: 5/17/2017
# License: GPL v3.0
#
import time
import numpy as np
import psi4
# N dimensional dot
# Like a mini DPD library
def ndot(input_string, op1, op2, prefactor=None):
"""
No checks, if you get weird errors its up to you to debug.
ndot('abcd,cdef->abef', arr1, arr2)
"""
inp, output_ind = input_string.split('->')
input_left, input_right = inp.split(',')
size_dict = {}
for s, size in zip(input_left, op1.shape):
size_dict[s] = size
for s, size in zip(input_right, op2.shape):
size_dict[s] = size
set_left = set(input_left)
set_right = set(input_right)
set_out = set(output_ind)
idx_removed = (set_left | set_right) - set_out
keep_left = set_left - idx_removed
keep_right = set_right - idx_removed
# Tensordot axes
left_pos, right_pos = (), ()
for s in idx_removed:
left_pos += (input_left.find(s),)
right_pos += (input_right.find(s),)
tdot_axes = (left_pos, right_pos)
# Get result ordering
tdot_result = input_left + input_right
for s in idx_removed:
tdot_result = tdot_result.replace(s, '')
rs = len(idx_removed)
dim_left, dim_right, dim_removed = 1, 1, 1
for key, size in size_dict.items():
if key in keep_left:
dim_left *= size
if key in keep_right:
dim_right *= size
if key in idx_removed:
dim_removed *= size
shape_result = tuple(size_dict[x] for x in tdot_result)
used_einsum = False
# Matrix multiply
# No transpose needed
if input_left[-rs:] == input_right[:rs]:
new_view = np.dot(op1.reshape(dim_left, dim_removed),
op2.reshape(dim_removed, dim_right))
# Transpose both
elif input_left[:rs] == input_right[-rs:]:
new_view = np.dot(op1.reshape(dim_removed, dim_left).T,
op2.reshape(dim_right, dim_removed).T)
# Transpose right
elif input_left[-rs:] == input_right[-rs:]:
new_view = np.dot(op1.reshape(dim_left, dim_removed),
op2.reshape(dim_right, dim_removed).T)
# Tranpose left
elif input_left[:rs] == input_right[:rs]:
new_view = np.dot(op1.reshape(dim_removed, dim_left).T,
op2.reshape(dim_removed, dim_right))
# If we have to transpose vector-matrix, einsum is faster
elif (len(keep_left) == 0) or (len(keep_right) == 0):
new_view = np.einsum(input_string, op1, op2)
used_einsum = True
else:
new_view = np.tensordot(op1, op2, axes=tdot_axes)
# Make sure the resulting shape is correct
if (new_view.shape != shape_result) and not used_einsum:
if (len(shape_result) > 0):
new_view = new_view.reshape(shape_result)
else:
new_view = np.squeeze(new_view)
# In-place mult by prefactor if requested
if prefactor is not None:
new_view *= prefactor
# Do final tranpose if needed
if used_einsum:
return new_view
elif tdot_result == output_ind:
return new_view
else:
return np.einsum(tdot_result + '->' + output_ind, new_view)
class helper_ccenergy(object):
#def __init__(self, mol, freeze_core=False, memory=2):
def __init__(self, mol, rhf_e, rhf_wfn, memory=2):
#if freeze_core:
# raise Exception("Frozen core doesnt work yet!")
print("\nInitalizing CCSD object...\n")
# Integral generation from Psi4's MintsHelper
time_init = time.time()
#print('Computing RHF reference.')
#psi4.core.set_active_molecule(mol)
#psi4.set_module_options('SCF', {'SCF_TYPE':'PK'})
#psi4.set_module_options('SCF', {'E_CONVERGENCE':10e-13})
#psi4.set_module_options('SCF', {'D_CONVERGENCE':10e-13})
# Core is frozen by default
#if not freeze_core:
# psi4.set_module_options('CCENERGY', {'FREEZE_CORE':'FALSE'})
#self.rhf_e, self.wfn = psi4.energy('SCF', return_wfn=True)
#print('RHF Final Energy % 16.10f\n' % (self.rhf_e))
self.rhf_e = rhf_e
self.wfn = rhf_wfn
self.ccsd_corr_e = 0.0
self.ccsd_e = 0.0
#self.eps = np.asarray(self.wfn.epsilon_a())
self.ndocc = self.wfn.doccpi()[0]
self.nmo = self.wfn.nmo()
self.memory = memory
self.nfzc = 0
# Freeze core
#if freeze_core:
# Zlist = np.array([mol.Z(x) for x in range(mol.natom())])
# self.nfzc = np.sum(Zlist > 2)
# self.nfzc += np.sum(Zlist > 10) * 4
# if np.any(Zlist > 18):
# raise Exception("Frozen core for Z > 18 not yet implemented")
# print("Cutting %d core orbitals." % self.nfzc)
# # Copy C
# oldC = np.array(self.wfn.Ca(), copy=True)
# # Build new C matrix and view, set with numpy slicing
# self.C = psi.Matrix(self.nmo, self.nmo - self.nfzc)
# self.npC = np.asarray(self.C)
# self.npC[:] = oldC[:, self.nfzc:]
# self.ndocc -= self.nfzc
#else:
# self.C = self.wfn.Ca()
# self.npC = np.asarray(self.C)
self.C = self.wfn.Ca()
self.npC = np.asarray(self.C)
self.mints = psi4.core.MintsHelper(self.wfn.basisset())
H = np.asarray(self.mints.ao_kinetic()) + np.asarray(self.mints.ao_potential())
self.nmo = H.shape[0]
# Update H, transform to MO basis
H = np.einsum('uj,vi,uv', self.npC, self.npC, H)
print('Starting AO -> MO transformation...')
ERI_Size = self.nmo * 128.e-9
memory_footprint = ERI_Size * 5
if memory_footprint > self.memory:
psi.clean()
raise Exception("Estimated memory utilization (%4.2f GB) exceeds numpy_memory \
limit of %4.2f GB." % (memory_footprint, self.memory))
# Integral generation from Psi4's MintsHelper
self.MO = np.asarray(self.mints.mo_eri(self.C, self.C, self.C, self.C))
self.MO = self.MO.swapaxes(1,2)
print("Size of the ERI tensor is %4.2f GB, %d basis functions." % (ERI_Size, self.nmo))
# Update nocc and nvirt
self.nocc = self.ndocc
self.nvirt = self.nmo - self.nocc - self.nfzc
# Make slices
self.slice_nfzc = slice(0, self.nfzc)
self.slice_o = slice(self.nfzc, self.nocc + self.nfzc)
self.slice_v = slice(self.nocc + self.nfzc, self.nmo)
self.slice_a = slice(0, self.nmo)
self.slice_dict = {'f': self.slice_nfzc, 'o' : self.slice_o, 'v' : self.slice_v,
'a' : self.slice_a}
# Compute Fock matrix
self.F = H + 2.0 * np.einsum('pmqm->pq', self.MO[:, self.slice_o, :, self.slice_o])
self.F -= np.einsum('pmmq->pq', self.MO[:, self.slice_o, self.slice_o, :])
### Build D matrices
Focc = np.diag(self.F)[self.slice_o]
Fvir = np.diag(self.F)[self.slice_v]
#print(Focc)
tmp = Focc.reshape(-1,1)
#print(tmp)
#print(Fvir)
self.Dia = Focc.reshape(-1, 1) - Fvir
#print(self.Dia)
self.Dijab = Focc.reshape(-1, 1, 1, 1) + Focc.reshape(-1, 1, 1) - Fvir.reshape(-1, 1) - Fvir
### Construct initial guess
print('Building initial guess...')
# t^a_i
self.t1 = np.zeros((self.nocc, self.nvirt))
# t^{ab}_{ij}
self.t2 = self.MO[self.slice_o, self.slice_o, self.slice_v, self.slice_v] / self.Dijab
print('\n..initialized CCSD in %.3f seconds.\n' % (time.time() - time_init))
# occ orbitals i, j, k, l, m, n
# virt orbitals a, b, c, d, e, f
# all oribitals p, q, r, s, t, u, v
def get_MO(self, string):
if len(string) != 4:
psi4.core.clean()
raise Exception('get_MO: string %s must have 4 elements.' % string)
return self.MO[self.slice_dict[string[0]], self.slice_dict[string[1]],
self.slice_dict[string[2]], self.slice_dict[string[3]]]
def get_F(self, string):
if len(string) != 2:
psi4.core.clean()
raise Exception('get_F: string %s must have 4 elements.' % string)
return self.F[self.slice_dict[string[0]], self.slice_dict[string[1]]]
#Bulid Eqn 9: tilde{\Tau})
def build_tilde_tau(self):
ttau = self.t2.copy()
tmp = 0.5 * np.einsum('ia,jb->ijab', self.t1, self.t1)
ttau += tmp
return ttau
#Build Eqn 10: \Tau)
def build_tau(self):
ttau = self.t2.copy()
tmp = np.einsum('ia,jb->ijab', self.t1, self.t1)
ttau += tmp
return ttau
#Build Eqn 3:
def build_Fae(self):
Fae = self.get_F('vv').copy()
Fae -= ndot('me,ma->ae', self.get_F('ov'), self.t1, prefactor=0.5)
Fae += ndot('mf,mafe->ae', self.t1, self.get_MO('ovvv'), prefactor=2.0)
Fae += ndot('mf,maef->ae', self.t1, self.get_MO('ovvv'), prefactor=-1.0)
Fae -= ndot('mnaf,mnef->ae', self.build_tilde_tau(), self.get_MO('oovv'), prefactor=2.0)
Fae -= ndot('mnaf,mnfe->ae', self.build_tilde_tau(), self.get_MO('oovv'), prefactor=-1.0)
return Fae
#Build Eqn 4:
def build_Fmi(self):
Fmi = self.get_F('oo').copy()
Fmi += ndot('ie,me->mi', self.t1, self.get_F('ov'), prefactor=0.5)
Fmi += ndot('ne,mnie->mi', self.t1, self.get_MO('ooov'), prefactor=2.0)
Fmi += ndot('ne,mnei->mi', self.t1, self.get_MO('oovo'), prefactor=-1.0)
Fmi += ndot('inef,mnef->mi', self.build_tilde_tau(), self.get_MO('oovv'), prefactor=2.0)
Fmi += ndot('inef,mnfe->mi', self.build_tilde_tau(), self.get_MO('oovv'), prefactor=-1.0)
return Fmi
#Build Eqn 5:
def build_Fme(self):
Fme = self.get_F('ov').copy()
Fme += ndot('nf,mnef->me', self.t1, self.get_MO('oovv'), prefactor=2.0)
Fme += ndot('nf,mnfe->me', self.t1, self.get_MO('oovv'), prefactor=-1.0)
return Fme
#Build Eqn 6:
def build_Wmnij(self):
Wmnij = self.get_MO('oooo').copy()
Wmnij += ndot('je,mnie->mnij', self.t1, self.get_MO('ooov'))
Wmnij += ndot('ie,mnej->mnij', self.t1, self.get_MO('oovo'))
Wmnij += ndot('ijef,mnef->mnij', self.build_tau(), self.get_MO('oovv'), prefactor=1.0)
return Wmnij
#Build Eqn 8:
def build_Wmbej(self):
Wmbej = self.get_MO('ovvo').copy()
Wmbej += ndot('jf,mbef->mbej', self.t1, self.get_MO('ovvv'))
Wmbej -= ndot('nb,mnej->mbej', self.t1, self.get_MO('oovo'))
tmp = (0.5 * self.t2)
tmp += np.einsum('jf,nb->jnfb', self.t1, self.t1)
Wmbej -= ndot('jnfb,mnef->mbej', tmp, self.get_MO('oovv'))
Wmbej += ndot('njfb,mnef->mbej', self.t2, self.get_MO('oovv'), prefactor=1.0)
Wmbej += ndot('njfb,mnfe->mbej', self.t2, self.get_MO('oovv'), prefactor=-0.5)
return Wmbej
def build_Wmbje(self):
Wmbje = -1.0 * (self.get_MO('ovov').copy())
Wmbje -= ndot('jf,mbfe->mbje', self.t1, self.get_MO('ovvv'))
Wmbje += ndot('nb,mnje->mbje', self.t1, self.get_MO('ooov'))
tmp = (0.5 * self.t2)
tmp += np.einsum('jf,nb->jnfb', self.t1, self.t1)
Wmbje += ndot('jnfb,mnfe->mbje', tmp, self.get_MO('oovv'))
return Wmbje
def build_Zmbij(self):
Zmbij = 0
Zmbij += ndot('mbef,ijef->mbij', self.get_MO('ovvv'), self.build_tau())
return Zmbij
def update(self):
# Updates amplitudes
### Build intermediates
Fae = self.build_Fae()
Fmi = self.build_Fmi()
Fme = self.build_Fme()
#### Build residual of self.t1 equations
r_T1 = self.get_F('ov').copy()
r_T1 += ndot('ie,ae->ia', self.t1, Fae)
r_T1 -= ndot('ma,mi->ia', self.t1, Fmi)
r_T1 += ndot('imae,me->ia', self.t2, Fme, prefactor=2.0)
r_T1 += ndot('imea,me->ia', self.t2, Fme, prefactor=-1.0)
r_T1 += ndot('nf,nafi->ia', self.t1, self.get_MO('ovvo'), prefactor=2.0)
r_T1 += ndot('nf,naif->ia', self.t1, self.get_MO('ovov'), prefactor=-1.0)
r_T1 += ndot('mief,maef->ia', self.t2, self.get_MO('ovvv'), prefactor=2.0)
r_T1 += ndot('mife,maef->ia', self.t2, self.get_MO('ovvv'), prefactor=-1.0)
r_T1 -= ndot('mnae,nmei->ia', self.t2, self.get_MO('oovo'), prefactor=2.0)
r_T1 -= ndot('mnae,nmie->ia', self.t2, self.get_MO('ooov'), prefactor=-1.0)
### Build RHS side of self.t2 equations
r_T2 = self.get_MO('oovv').copy()
# P^(ab)_(ij) {t_ijae Fae_be }
tmp = ndot('ijae,be->ijab', self.t2, Fae)
r_T2 += tmp
r_T2 += tmp.swapaxes(0,1).swapaxes(2,3)
# P^(ab)_(ij) {-0.5 * t_ijae t_mb Fme_me }
tmp = ndot('mb,me->be', self.t1, Fme)
first = ndot('ijae,be->ijab', self.t2, tmp, prefactor=0.5)
r_T2 -= first
r_T2 -= first.swapaxes(0,1).swapaxes(2,3)
# P^(ab)_(ij) {-t_imab Fmi_mj }
tmp = ndot('imab,mj->ijab', self.t2, Fmi, prefactor=1.0)
r_T2 -= tmp
r_T2 -= tmp.swapaxes(0,1).swapaxes(2,3)
# P^(ab)_(ij) {-0.5 * t_imab t_je Fme_me }
tmp = ndot('je,me->jm', self.t1, Fme)
first = ndot('imab,jm->ijab', self.t2, tmp, prefactor=0.5)
r_T2 -= first
r_T2 -= first.swapaxes(0,1).swapaxes(2,3)
# tau_mnab Wmnij_mnij + tau_ijef <ab|ef> }
tmp_tau = self.build_tau()
Wmnij = self.build_Wmnij()
Wmbej = self.build_Wmbej()
Wmbje = self.build_Wmbje()
Zmbij = self.build_Zmbij()
r_T2 += ndot('mnab,mnij->ijab', tmp_tau, Wmnij, prefactor=1.0)
r_T2 += ndot('ijef,abef->ijab', tmp_tau, self.get_MO('vvvv'), prefactor=1.0)
# P^(ab)_(ij) {t_ie <ab|ej> }
tmp = ndot('ie,abej->ijab', self.t1, self.get_MO('vvvo'), prefactor=1.0)
r_T2 += tmp
r_T2 += tmp.swapaxes(0,1).swapaxes(2,3)
# P^(ab)_(ij) {-t_ma <mb|ij> }
tmp = ndot('ma,mbij->ijab', self.t1, self.get_MO('ovoo'), prefactor=1.0)
r_T2 -= tmp
r_T2 -= tmp.swapaxes(0,1).swapaxes(2,3)
# P...
r_T2 += ndot('imae,mbej->ijab', self.t2, Wmbej, prefactor=1.0)
r_T2 += ndot('imea,mbej->ijab', self.t2, Wmbej, prefactor=-1.0)
r_T2 += ndot('imae,mbej->ijab', self.t2, Wmbej, prefactor=1.0)
r_T2 += ndot('imae,mbje->ijab', self.t2, Wmbje, prefactor=1.0)
r_T2 += ndot('mjae,mbie->ijab', self.t2, Wmbje, prefactor=1.0)
r_T2 += ndot('imeb,maje->ijab', self.t2, Wmbje, prefactor=1.0)
r_T2 += ndot('jmbe,maei->ijab', self.t2, Wmbej, prefactor=1.0)
r_T2 += ndot('jmbe,maie->ijab', self.t2, Wmbje, prefactor=1.0)
r_T2 += ndot('jmbe,maei->ijab', self.t2, Wmbej, prefactor=1.0)
r_T2 += ndot('jmeb,maei->ijab', self.t2, Wmbej, prefactor=-1.0)
# P....
tmp = ndot('ie,ma->imea', self.t1, self.t1)
r_T2 -= ndot('imea,mbej->ijab', tmp, self.get_MO('ovvo'))
tmp = ndot('ie,mb->imeb', self.t1, self.t1)
r_T2 -= ndot('imeb,maje->ijab', tmp, self.get_MO('ovov'))
tmp = ndot('je,ma->jmea', self.t1, self.t1)
r_T2 -= ndot('jmea,mbie->ijab', tmp, self.get_MO('ovov'))
tmp = ndot('je,mb->jmeb', self.t1, self.t1)
r_T2 -= ndot('jmeb,maei->ijab', tmp, self.get_MO('ovvo'))
r_T2 -= ndot('ma,mbij->ijab', self.t1, Zmbij)
r_T2 -= ndot('ma,mbij->jiba', self.t1, Zmbij)
### Update T1 and T2 amplitudes
self.t1 += r_T1 / self.Dia
self.t2 += r_T2 / self.Dijab
rms = np.einsum('ia,ia->', r_T1/self.Dia, r_T1/self.Dia)
rms += np.einsum('ijab,ijab->', r_T2/self.Dijab, r_T2/self.Dijab)
return np.sqrt(rms)
def compute_corr_energy(self):
CCSDcorr_E = 2.0 * np.einsum('ia,ia->', self.get_F('ov'), self.t1)
tmp_tau = self.build_tau()
CCSDcorr_E += 2.0 * np.einsum('ijab,ijab->', tmp_tau, self.get_MO('oovv'))
CCSDcorr_E -= 1.0 * np.einsum('ijab,ijba->', tmp_tau, self.get_MO('oovv'))
self.ccsd_corr_e = CCSDcorr_E
self.ccsd_e = self.rhf_e + self.ccsd_corr_e
return CCSDcorr_E
def compute_energy(self, r_conv=1e-7, maxiter=50, max_diis=8):
### Setup DIIS
diis_vals_t1 = [self.t1.copy()]
diis_vals_t2 = [self.t2.copy()]
diis_errors = []
### Start Iterations
ccsd_tstart = time.time()
# Compute MP2 energy
CCSDcorr_E_old = self.compute_corr_energy()
print("CCSD Iteration %3d: CCSD correlation = %.15f dE = % .5E MP2" % (0, CCSDcorr_E_old, -CCSDcorr_E_old))
# Iterate!
diis_size = 0
for CCSD_iter in range(1, maxiter + 1):
# Save new amplitudes
oldt1 = self.t1.copy()
oldt2 = self.t2.copy()
rms = self.update()
# Compute CCSD correlation energy
CCSDcorr_E = self.compute_corr_energy()
# Print CCSD iteration information
print('CCSD Iteration %3d: CCSD correlation = %.15f dE = % .5E DIIS = %d' % (CCSD_iter, CCSDcorr_E, (CCSDcorr_E - CCSDcorr_E_old), diis_size))
# Check convergence
#if (abs(CCSDcorr_E - CCSDcorr_E_old) < e_conv and rms < r_conv):
if (rms < r_conv): # to be consistent with ugacc
print('\nCCSD has converged in %.3f seconds!' % (time.time() - ccsd_tstart))
return CCSDcorr_E
# Add DIIS vectors
diis_vals_t1.append(self.t1.copy())
diis_vals_t2.append(self.t2.copy())
# Build new error vector
error_t1 = (diis_vals_t1[-1] - oldt1).ravel()
error_t2 = (diis_vals_t2[-1] - oldt2).ravel()
diis_errors.append(np.concatenate((error_t1, error_t2)))
# Update old energy
CCSDcorr_E_old = CCSDcorr_E
if CCSD_iter >= 1:
# Limit size of DIIS vector
if (len(diis_vals_t1) > max_diis):
del diis_vals_t1[0]
del diis_vals_t2[0]
del diis_errors[0]
diis_size = len(diis_vals_t1) - 1
# Build error matrix B
B = np.ones((diis_size + 1, diis_size + 1)) * -1
B[-1, -1] = 0
for n1, e1 in enumerate(diis_errors):
B[n1, n1] = np.dot(e1, e1)
for n2, e2 in enumerate(diis_errors):
if n1 >= n2: continue
B[n1, n2] = np.dot(e1, e2)
B[n2, n1] = B[n1, n2]
B[:-1, :-1] /= np.abs(B[:-1, :-1]).max()
# Build residual vector
resid = np.zeros(diis_size + 1)
resid[-1] = -1
# Solve pulay equations
ci = np.linalg.solve(B, resid)
# Calculate new amplitudes
self.t1[:] = 0
self.t2[:] = 0
for num in range(diis_size):
self.t1 += ci[num] * diis_vals_t1[num + 1]
self.t2 += ci[num] * diis_vals_t2[num + 1]
# End DIIS amplitude update
# End helper_ccenergy class
class helper_cchbar(object):
def __init__(self, ccsd, memory=2):
# Integral generation from Psi4's MintsHelper
time_init = time.time()
self.MO = ccsd.MO
self.ndocc = ccsd.ndocc
self.nmo = ccsd.nmo
self.nfzc = 0
self.nocc = ccsd.ndocc
self.nvirt = ccsd.nmo - ccsd.nocc - ccsd.nfzc
self.slice_nfzc = slice(0, self.nfzc)
self.slice_o = slice(self.nfzc, self.nocc + self.nfzc)
self.slice_v = slice(self.nocc + self.nfzc, self.nmo)
self.slice_a = slice(0, self.nmo)
self.slice_dict = {'f': self.slice_nfzc, 'o' : self.slice_o, 'v' : self.slice_v,
'a' : self.slice_a}
self.F = ccsd.F
self.Dia = ccsd.Dia
self.Dijab = ccsd.Dijab
self.t1 = ccsd.t1
self.t2 = ccsd.t2
#print(self.t1)
#print(self.t2)
print('\nBuilding appropriate pieces of similarity transformed hamiltonian ...')
#tmp = self.MO.copy()
#self.L = 2.0 * tmp
#self.L -= tmp.swapaxes(2,3)
self.build_Loovv()
self.build_Looov()
self.build_Lvovv()
self.build_Hov()
#print('\n Hov \n')
#print(self.Hov)
self.build_Hoo()
#print('\n Hoo \n')
#print(self.Hoo)
self.build_Hvv()
#print('\n Hvv \n')
#print(self.Hvv)
self.build_Hoooo()
#print('\n Hoooo \n')
#print(self.Hoooo)
self.build_Hvvvv()
#print('\n Hvvvv \n')
#print(self.Hvvvv)
self.build_Hvovv()
#print('\n Hvovv \n')
#print(self.Hvovv)
self.build_Hooov()
#print('\n Hoovv \n')
#print(self.Hooov)
self.build_Hovvo()
#print('\n Hovvo \n')
#print(self.Hovvo)
self.build_Hovov()
#print('\n Hovov \n')
#print(self.Hovov)
self.build_Hvvvo()
#print('\n Hvvvo \n')
#print(self.Hvvvo)
self.build_Hovoo()
#print('\n Hovoo \n')
#print(self.Hovoo)
print('\n..CCHBAR completed !!')
# occ orbitals i, j, k, l, m, n
# virt orbitals a, b, c, d, e, f
# all oribitals p, q, r, s, t, u, v
def get_MO(self, string):
if len(string) != 4:
psi4.core.clean()
raise Exception('get_MO: string %s must have 4 elements.' % string)
return self.MO[self.slice_dict[string[0]], self.slice_dict[string[1]],
self.slice_dict[string[2]], self.slice_dict[string[3]]]
#def get_L(self, string):
# if len(string) != 4:
# psi4.core.clean()
# raise Exception('get_L: string %s must have 4 elements.' % string)
# return (self.L[self.slice_dict[string[0]], self.slice_dict[string[1]],
# self.slice_dict[string[2]], self.slice_dict[string[3]]])
def get_F(self, string):
if len(string) != 2:
psi4.core.clean()
raise Exception('get_F: string %s must have 4 elements.' % string)
return self.F[self.slice_dict[string[0]], self.slice_dict[string[1]]]
def build_Loovv(self):
tmp = self.get_MO('oovv').copy()
self.Loovv = 2.0 * tmp - tmp.swapaxes(2,3)
return self.Loovv
def build_Looov(self):
tmp = self.get_MO('ooov').copy()
self.Looov = 2.0 * tmp - tmp.swapaxes(0,1)
return self.Looov
def build_Lvovv(self):
tmp = self.get_MO('vovv').copy()
self.Lvovv = 2.0 * tmp - tmp.swapaxes(2,3)
return self.Lvovv
def build_tau(self):
self.ttau = self.t2.copy()
tmp = np.einsum('ia,jb->ijab', self.t1, self.t1)
self.ttau += tmp
return self.ttau
def build_Hov(self):
self.Hov = self.get_F('ov').copy()
self.Hov += ndot('nf,mnef->me', self.t1, self.Loovv)
return self.Hov
def build_Hoo(self):
self.Hoo = self.get_F('oo').copy()
self.Hoo += ndot('ie,me->mi', self.t1, self.get_F('ov'))
self.Hoo += ndot('ne,mnie->mi', self.t1, self.Looov)
self.Hoo += ndot('mnef,inef->mi', self.Loovv, self.build_tau())
return self.Hoo
def build_Hvv(self):
self.Hvv = self.get_F('vv').copy()
self.Hvv -= ndot('ma,me->ae', self.t1, self.get_F('ov'))
self.Hvv += ndot('amef,mf->ae', self.Lvovv, self.t1)
self.Hvv -= ndot('mnfa,mnfe->ae', self.build_tau(), self.Loovv)
return self.Hvv
def build_Hoooo(self):
self.Hoooo = self.get_MO('oooo').copy()
self.Hoooo += ndot('je,mnie->mnij', self.t1, self.get_MO('ooov'), prefactor=2.0)
self.Hoooo += ndot('mnef,ijef->mnij', self.get_MO('oovv'), self.build_tau())
return self.Hoooo
def build_Hvvvv(self):
self.Hvvvv = self.get_MO('vvvv').copy()
self.Hvvvv -= ndot('mb,amef->abef', self.t1, self.get_MO('vovv'), prefactor=2.0)
self.Hvvvv += ndot('mnab,mnef->abef', self.build_tau(), self.get_MO('oovv'))
return self.Hvvvv
def build_Hvovv(self):
self.Hvovv = self.get_MO('vovv').copy()
self.Hvovv -= ndot('na,nmef->amef', self.t1, self.get_MO('oovv'))
return self.Hvovv
def build_Hooov(self):
self.Hooov = self.get_MO('ooov').copy()
self.Hooov += ndot('if,nmef->mnie', self.t1, self.get_MO('oovv'))
return self.Hooov
def build_Hovvo(self):
self.Hovvo = self.get_MO('ovvo').copy()
self.Hovvo += ndot('jf,mbef->mbej', self.t1, self.get_MO('ovvv'))
self.Hovvo -= ndot('nb,mnej->mbej', self.t1, self.get_MO('oovo'))
self.Hovvo -= ndot('njbf,mnef->mbej', self.build_tau(), self.get_MO('oovv'))
self.Hovvo += ndot('njfb,mnef->mbej', self.t2, self.Loovv)
return self.Hovvo
def build_Hovov(self):
self.Hovov = self.get_MO('ovov').copy()
self.Hovov += ndot('jf,bmef->mbje', self.t1, self.get_MO('vovv'))
self.Hovov -= ndot('nb,mnje->mbje', self.t1, self.get_MO('ooov'))
self.Hovov -= ndot('jnfb,nmef->mbje', self.build_tau(), self.get_MO('oovv'))
return self.Hovov
def build_Hvvvo(self):
self.Hvvvo = self.get_MO('vvvo').copy()
self.Hvvvo += ndot('if,abef->abei', self.t1, self.get_MO('vvvv'))
self.Hvvvo -= ndot('mb,amei->abei', self.t1, self.get_MO('vovo'))
self.Hvvvo -= ndot('ma,bmie->abei', self.t1, self.get_MO('voov'))
self.Hvvvo -= ndot('imfa,mbef->abei', self.build_tau(), self.get_MO('ovvv'))
self.Hvvvo -= ndot('imfb,amef->abei', self.build_tau(), self.get_MO('vovv'))
self.Hvvvo += ndot('mnab,mnei->abei', self.build_tau(), self.get_MO('oovo'))
self.Hvvvo -= ndot('me,miab->abei', self.get_F('ov'), self.t2)
self.Hvvvo += ndot('mifb,amef->abei', self.t2, self.Lvovv)
tmp = ndot('mnef,if->mnei', self.get_MO('oovv'), self.t1)
self.Hvvvo += ndot('mnab,mnei->abei', self.t2, tmp)
tmp = ndot('mnef,ma->anef', self.get_MO('oovv'), self.t1)
self.Hvvvo += ndot('infb,anef->abei', self.t2, tmp)
tmp = ndot('mnef,nb->mefb', self.get_MO('oovv'), self.t1)
self.Hvvvo += ndot('miaf,mefb->abei', self.t2, tmp)
tmp = ndot('mnfe,mf->ne', self.Loovv, self.t1)
self.Hvvvo -= ndot('niab,ne->abei', self.t2, tmp)
tmp = ndot('mnfe,na->mafe', self.Loovv, self.t1)
self.Hvvvo -= ndot('mifb,mafe->abei', self.t2, tmp)
tmp1 = ndot('if,ma->imfa', self.t1, self.t1)
tmp2 = ndot('mnef,nb->mbef', self.get_MO('oovv'), self.t1)
self.Hvvvo += ndot('imfa,mbef->abei', tmp1, tmp2)
return self.Hvvvo
def build_Hovoo(self):
self.Hovoo = self.get_MO('ovoo').copy()
self.Hovoo += ndot('mbie,je->mbij', self.get_MO('ovov'), self.t1)
self.Hovoo += ndot('ie,bmje->mbij', self.t1, self.get_MO('voov'))
self.Hovoo -= ndot('nb,mnij->mbij', self.t1, self.get_MO('oooo'))
self.Hovoo -= ndot('ineb,nmje->mbij', self.build_tau(), self.get_MO('ooov'))
self.Hovoo -= ndot('jneb,mnie->mbij', self.build_tau(), self.get_MO('ooov'))
self.Hovoo += ndot('ijef,mbef->mbij', self.build_tau(), self.get_MO('ovvv'))
self.Hovoo += ndot('me,ijeb->mbij', self.get_F('ov'), self.t2)
self.Hovoo += ndot('njeb,mnie->mbij', self.t2, self.Looov)
tmp = ndot('mnef,jf->mnej', self.get_MO('oovv'), self.t1)
self.Hovoo -= ndot('ineb,mnej->mbij', self.t2, tmp)
tmp = ndot('mnef,ie->mnif', self.get_MO('oovv'), self.t1)
self.Hovoo -= ndot('jnfb,mnif->mbij', self.t2, tmp)
tmp = ndot('mnef,nb->mefb', self.get_MO('oovv'), self.t1)
self.Hovoo -= ndot('ijef,mefb->mbij', self.t2, tmp)
tmp = ndot('mnef,njfb->mejb', self.Loovv, self.t2)
self.Hovoo += ndot('mejb,ie->mbij', tmp, self.t1)
tmp = ndot('mnef,nf->me', self.Loovv, self.t1)
self.Hovoo += ndot('me,ijeb->mbij', tmp, self.t2)
tmp1 = ndot('ie,jf->ijef', self.t1, self.t1)
tmp2 = ndot('mnef,nb->mbef', self.get_MO('oovv'), self.t1)
self.Hovoo -= ndot('mbef,ijef->mbij', tmp2, tmp1)
return self.Hovoo
class helper_cclambda(object):
def __init__(self, ccsd, hbar):
# Integral generation from Psi4's MintsHelper
time_init = time.time()
self.MO = ccsd.MO
self.ndocc = ccsd.ndocc
self.nmo = ccsd.nmo
self.nfzc = 0
self.nocc = ccsd.ndocc
self.nvirt = ccsd.nmo - ccsd.nocc - ccsd.nfzc
self.slice_nfzc = slice(0, self.nfzc)
self.slice_o = slice(self.nfzc, self.nocc + self.nfzc)
self.slice_v = slice(self.nocc + self.nfzc, self.nmo)
self.slice_a = slice(0, self.nmo)
self.slice_dict = {'f': self.slice_nfzc, 'o' : self.slice_o, 'v' : self.slice_v,
'a' : self.slice_a}
self.F = ccsd.F
self.Dia = ccsd.Dia
self.Dijab = ccsd.Dijab
self.t1 = ccsd.t1
self.t2 = ccsd.t2
self.ttau = hbar.ttau
self.Loovv = hbar.Loovv
self.Looov = hbar.Looov
self.Lvovv = hbar.Lvovv
self.Hov = hbar.Hov
self.Hvv = hbar.Hvv
self.Hoo = hbar.Hoo
self.Hoooo = hbar.Hoooo
self.Hvvvv = hbar.Hvvvv
self.Hvovv = hbar.Hvovv
self.Hooov = hbar.Hooov
self.Hovvo = hbar.Hovvo
self.Hovov = hbar.Hovov
self.Hvvvo = hbar.Hvvvo
self.Hovoo = hbar.Hovoo
self.l1 = 2.0 * self.t1
tmp = self.t2
self.l2 = 2.0 * (2.0 * tmp - tmp.swapaxes(2,3))
# occ orbitals i, j, k, l, m, n
# virt orbitals a, b, c, d, e, f
# all oribitals p, q, r, s, t, u, v
def get_MO(self, string):
if len(string) != 4:
psi4.core.clean()
raise Exception('get_MO: string %s must have 4 elements.' % string)
return self.MO[self.slice_dict[string[0]], self.slice_dict[string[1]],
self.slice_dict[string[2]], self.slice_dict[string[3]]]
def get_F(self, string):
if len(string) != 2:
psi4.core.clean()
raise Exception('get_F: string %s must have 4 elements.' % string)
return self.F[self.slice_dict[string[0]], self.slice_dict[string[1]]]
def build_Goo(self):
self.Goo = 0
self.Goo += ndot('mjab,ijab->mi', self.t2, self.l2)
return self.Goo
def build_Gvv(self):
self.Gvv = 0
self.Gvv -= ndot('ijab,ijeb->ae', self.l2, self.t2)
return self.Gvv
def update(self):
r_l1 = 2.0 * self.Hov.copy()
r_l1 += ndot('ie,ea->ia', self.l1, self.Hvv)
r_l1 -= ndot('im,ma->ia', self.Hoo, self.l1)
r_l1 += ndot('ieam,me->ia', self.Hovvo, self.l1, prefactor=2.0)
r_l1 += ndot('iema,me->ia', self.Hovov, self.l1, prefactor=-1.0)
r_l1 += ndot('imef,efam->ia', self.l2, self.Hvvvo)
r_l1 -= ndot('iemn,mnae->ia', self.Hovoo, self.l2)
r_l1 -= ndot('eifa,ef->ia', self.Hvovv, self.build_Gvv(), prefactor=2.0)
r_l1 -= ndot('eiaf,ef->ia', self.Hvovv, self.build_Gvv(), prefactor=-1.0)
r_l1 -= ndot('mina,mn->ia', self.Hooov, self.build_Goo(), prefactor=2.0)
r_l1 -= ndot('imna,mn->ia', self.Hooov, self.build_Goo(), prefactor=-1.0)
r_l2 = self.Loovv.copy()
r_l2 += ndot('ia,jb->ijab', self.l1, self.Hov, prefactor=2.0)
r_l2 -= ndot('ja,ib->ijab', self.l1, self.Hov)
r_l2 += ndot('ijeb,ea->ijab', self.l2, self.Hvv)
r_l2 -= ndot('im,mjab->ijab', self.Hoo, self.l2)
r_l2 += ndot('ijmn,mnab->ijab', self.Hoooo, self.l2, prefactor=0.5)
r_l2 += ndot('ijef,efab->ijab', self.l2, self.Hvvvv, prefactor=0.5)
r_l2 += ndot('ie,ejab->ijab', self.l1, self.Hvovv, prefactor=2.0)
r_l2 += ndot('ie,ejba->ijab', self.l1, self.Hvovv, prefactor=-1.0)
r_l2 -= ndot('mb,jima->ijab', self.l1, self.Hooov, prefactor=2.0)
r_l2 -= ndot('mb,ijma->ijab', self.l1, self.Hooov, prefactor=-1.0)
r_l2 += ndot('ieam,mjeb->ijab', self.Hovvo, self.l2, prefactor=2.0)
r_l2 += ndot('iema,mjeb->ijab', self.Hovov, self.l2, prefactor=-1.0)
r_l2 -= ndot('mibe,jema->ijab', self.l2, self.Hovov)
r_l2 -= ndot('mieb,jeam->ijab', self.l2, self.Hovvo)
r_l2 += ndot('ijeb,ae->ijab', self.Loovv, self.build_Gvv())
r_l2 -= ndot('mi,mjab->ijab', self.build_Goo(), self.Loovv)
self.l1 += r_l1/self.Dia
old_l2 = self.l2
self.l2 += r_l2/self.Dijab
self.l2 += (r_l2/self.Dijab).swapaxes(0,1).swapaxes(2,3)
rms = 2.0 * np.einsum('ia,ia->', r_l1/self.Dia, r_l1/self.Dia)
rms += np.einsum('ijab,ijab->', old_l2 - self.l2, old_l2 - self.l2)
return np.sqrt(rms)
def pseudoenergy(self):
pseudoenergy = 0
pseudoenergy += ndot('ijab,ijab->', self.get_MO('oovv'), self.l2, prefactor=0.5)
#pseudoenergy += ndot('ia,ia->', self.l1, self.l1)
return pseudoenergy
def compute_lambda(self, r_conv=1e-7, maxiter=100, max_diis=8):
print('\n Solving lambda equations ...\n')
### Setup DIIS
diis_vals_l1 = [self.l1.copy()]
diis_vals_l2 = [self.l2.copy()]
diis_errors = []
### Start Iterations
cclambda_tstart = time.time()
pseudoenergy_old = self.pseudoenergy()
print("CCLAMBDA Iteration %3d: pseudoenergy = %.15f dE = % .5E MP2" % (0, pseudoenergy_old, -pseudoenergy_old))
# Iterate!
diis_size = 0
for CCLAMBDA_iter in range(1, maxiter + 1):
# Save new amplitudes
oldl1 = self.l1.copy()
oldl2 = self.l2.copy()
rms = self.update()
# Compute lambda
pseudoenergy = self.pseudoenergy()
# Print CCLAMBDA iteration information
print('CCLAMBDA Iteration %3d: pseudoenergy = %.15f dE = % .5E DIIS = %d' % (CCLAMBDA_iter, pseudoenergy, (pseudoenergy - pseudoenergy_old), diis_size))
# Check convergence
#if (abs(pseudoenergy - pseudoenergy_old) < r_conv):
if (rms < r_conv):
print('\nCCLAMBDA has converged in %.3f seconds!' % (time.time() - cclambda_tstart))
#print(self.l1)
#print(self.l2)
return pseudoenergy
# Add DIIS vectors
diis_vals_l1.append(self.l1.copy())
diis_vals_l2.append(self.l2.copy())
# Build new error vector
error_l1 = (diis_vals_l1[-1] - oldl1).ravel()
error_l2 = (diis_vals_l2[-1] - oldl2).ravel()
diis_errors.append(np.concatenate((error_l1, error_l2)))
# Update old energy
pseudoenergy_old = pseudoenergy
if CCLAMBDA_iter >= 1:
# Limit size of DIIS vector
if (len(diis_vals_l1) > max_diis):
del diis_vals_l1[0]
del diis_vals_l2[0]
del diis_errors[0]
diis_size = len(diis_vals_l1) - 1
# Build error matrix B
B = np.ones((diis_size + 1, diis_size + 1)) * -1
B[-1, -1] = 0
for n1, e1 in enumerate(diis_errors):
B[n1, n1] = np.dot(e1, e1)
for n2, e2 in enumerate(diis_errors):
if n1 >= n2: continue
B[n1, n2] = np.dot(e1, e2)
B[n2, n1] = B[n1, n2]
B[:-1, :-1] /= np.abs(B[:-1, :-1]).max()
# Build residual vector
resid = np.zeros(diis_size + 1)
resid[-1] = -1
# Solve pulay equations
ci = np.linalg.solve(B, resid)
# Calculate new amplitudes
self.l1[:] = 0