forked from ml-electron-project/NNfunctional
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumint.py
More file actions
2080 lines (1877 loc) · 89.1 KB
/
numint.py
File metadata and controls
2080 lines (1877 loc) · 89.1 KB
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
#!/usr/bin/env python
#######################
#Changed by Ryo Nagai, March 2019.
#For PySCF ver 1.6.2
#This software includes the work that is distributed in the Apache License 2.0.
#######################
# Copyright 2014-2018 The PySCF Developers. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
import warnings
import ctypes
import numpy
import scipy.linalg
from pyscf import lib
from pyscf.lib import logger
try:
from pyscf.dft import libxc
except (ImportError, OSError):
try:
from pyscf.dft import xcfun
libxc = xcfun
except (ImportError, OSError):
import warnings
warnings.warn('XC functional libraries (libxc or XCfun) are not available.')
from pyscf.dft import xc
libxc = xc
from pyscf.dft.gen_grid import make_mask, BLKSIZE
from pyscf import __config__
libdft = lib.load_library('libdft')
OCCDROP = getattr(__config__, 'dft_numint_OCCDROP', 1e-12)
# The system size above which to consider the sparsity of the density matrix.
# If the number of AOs in the system is less than this value, all tensors are
# treated as dense quantities and contracted by dgemm directly.
SWITCH_SIZE = getattr(__config__, 'dft_numint_SWITCH_SIZE', 800)
def eval_ao(mol, coords, deriv=0, shls_slice=None,
non0tab=None, out=None, verbose=None):
'''Evaluate AO function value on the given grids.
Args:
mol : an instance of :class:`Mole`
coords : 2D array, shape (N,3)
The coordinates of the grids.
Kwargs:
deriv : int
AO derivative order. It affects the shape of the return array.
If deriv=0, the returned AO values are stored in a (N,nao) array.
Otherwise the AO values are stored in an array of shape (M,N,nao).
Here N is the number of grids, nao is the number of AO functions,
M is the size associated to the derivative deriv.
relativity : bool
No effects.
shls_slice : 2-element list
(shl_start, shl_end).
If given, only part of AOs (shl_start <= shell_id < shl_end) are
evaluated. By default, all shells defined in mol will be evaluated.
non0tab : 2D bool array
mask array to indicate whether the AO values are zero. The mask
array can be obtained by calling :func:`make_mask`
out : ndarray
If provided, results are written into this array.
verbose : int or object of :class:`Logger`
No effects.
Returns:
2D array of shape (N,nao) for AO values if deriv = 0.
Or 3D array of shape (:,N,nao) for AO values and AO derivatives if deriv > 0.
In the 3D array, the first (N,nao) elements are the AO values,
followed by (3,N,nao) for x,y,z compoents;
Then 2nd derivatives (6,N,nao) for xx, xy, xz, yy, yz, zz;
Then 3rd derivatives (10,N,nao) for xxx, xxy, xxz, xyy, xyz, xzz, yyy, yyz, yzz, zzz;
...
Examples:
>>> mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0', basis='ccpvdz')
>>> coords = numpy.random.random((100,3)) # 100 random points
>>> ao_value = eval_ao(mol, coords)
>>> print(ao_value.shape)
(100, 24)
>>> ao_value = eval_ao(mol, coords, deriv=1, shls_slice=(1,4))
>>> print(ao_value.shape)
(4, 100, 7)
>>> ao_value = eval_ao(mol, coords, deriv=2, shls_slice=(1,4))
>>> print(ao_value.shape)
(10, 100, 7)
'''
comp = (deriv+1)*(deriv+2)*(deriv+3)//6
if mol.cart:
feval = 'GTOval_cart_deriv%d' % deriv
else:
feval = 'GTOval_sph_deriv%d' % deriv
return mol.eval_gto(feval, coords, comp, shls_slice, non0tab, out=out)
#TODO: \nabla^2 rho and tau = 1/2 (\nabla f)^2
def eval_rho(mol, ao, dm, non0tab=None, xctype='LDA', hermi=0, verbose=None):
r'''Calculate the electron density for LDA functional, and the density
derivatives for GGA functional.
Args:
mol : an instance of :class:`Mole`
ao : 2D array of shape (N,nao) for LDA, 3D array of shape (4,N,nao) for GGA
or (5,N,nao) for meta-GGA. N is the number of grids, nao is the
number of AO functions. If xctype is GGA, ao[0] is AO value
and ao[1:3] are the AO gradients. If xctype is meta-GGA, ao[4:10]
are second derivatives of ao values.
dm : 2D array
Density matrix
Kwargs:
non0tab : 2D bool array
mask array to indicate whether the AO values are zero. The mask
array can be obtained by calling :func:`make_mask`
xctype : str
LDA/GGA/mGGA. It affects the shape of the return density.
hermi : bool
dm is hermitian or not
verbose : int or object of :class:`Logger`
No effects.
Returns:
1D array of size N to store electron density if xctype = LDA; 2D array
of (4,N) to store density and "density derivatives" for x,y,z components
if xctype = GGA; (6,N) array for meta-GGA, where last two rows are
\nabla^2 rho and tau = 1/2(\nabla f)^2
Examples:
>>> mol = gto.M(atom='O 0 0 0; H 0 0 1; H 0 1 0', basis='ccpvdz')
>>> coords = numpy.random.random((100,3)) # 100 random points
>>> ao_value = eval_ao(mol, coords, deriv=0)
>>> dm = numpy.random.random((mol.nao_nr(),mol.nao_nr()))
>>> dm = dm + dm.T
>>> rho, dx_rho, dy_rho, dz_rho = eval_rho(mol, ao, dm, xctype='LDA')
'''
xctype = xctype.upper()
if xctype == 'LDA' or xctype == 'HF':
ngrids, nao = ao.shape
else:
ngrids, nao = ao[0].shape
if non0tab is None:
non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,mol.nbas),
dtype=numpy.uint8)
if not hermi:
# (D + D.T)/2 because eval_rho computes 2*(|\nabla i> D_ij <j|) instead of
# |\nabla i> D_ij <j| + |i> D_ij <\nabla j| for efficiency
dm = (dm + dm.conj().T) * .5
shls_slice = (0, mol.nbas)
ao_loc = mol.ao_loc_nr()
if xctype == 'LDA' or xctype == 'HF':
c0 = _dot_ao_dm(mol, ao, dm, non0tab, shls_slice, ao_loc)
#:rho = numpy.einsum('pi,pi->p', ao, c0)
rho = _contract_rho(ao, c0)
elif xctype in ('GGA', 'NLC'):
rho = numpy.empty((4,ngrids))
c0 = _dot_ao_dm(mol, ao[0], dm, non0tab, shls_slice, ao_loc)
#:rho[0] = numpy.einsum('pi,pi->p', c0, ao[0])
rho[0] = _contract_rho(c0, ao[0])
for i in range(1, 4):
#:rho[i] = numpy.einsum('pi,pi->p', c0, ao[i])
rho[i] = _contract_rho(c0, ao[i])
rho[i] *= 2 # *2 for +c.c. in the next two lines
#c1 = _dot_ao_dm(mol, ao[i], dm, non0tab, shls_slice, ao_loc)
#rho[i] += numpy.einsum('pi,pi->p', c1, ao[0])
else: # meta-GGA
# rho[4] = \nabla^2 rho, rho[5] = 1/2 |nabla f|^2
rho = numpy.empty((6,ngrids))
c0 = _dot_ao_dm(mol, ao[0], dm, non0tab, shls_slice, ao_loc)
#:rho[0] = numpy.einsum('pi,pi->p', ao[0], c0)
rho[0] = _contract_rho(ao[0], c0)
rho[5] = 0
for i in range(1, 4):
#:rho[i] = numpy.einsum('pi,pi->p', c0, ao[i]) * 2 # *2 for +c.c.
rho[i] = _contract_rho(c0, ao[i]) * 2
c1 = _dot_ao_dm(mol, ao[i], dm.T, non0tab, shls_slice, ao_loc)
#:rho[5] += numpy.einsum('pi,pi->p', c1, ao[i])
rho[5] += _contract_rho(c1, ao[i])
XX, YY, ZZ = 4, 7, 9
ao2 = ao[XX] + ao[YY] + ao[ZZ]
#:rho[4] = numpy.einsum('pi,pi->p', c0, ao2)
rho[4] = _contract_rho(c0, ao2)
rho[4] += rho[5]
rho[4] *= 2
rho[5] *= .5
return rho
def eval_rho2(mol, ao, mo_coeff, mo_occ, non0tab=None, xctype='LDA',
verbose=None):
r'''Calculate the electron density for LDA functional, and the density
derivatives for GGA functional. This function has the same functionality
as :func:`eval_rho` except that the density are evaluated based on orbital
coefficients and orbital occupancy. It is more efficient than
:func:`eval_rho` in most scenario.
Args:
mol : an instance of :class:`Mole`
ao : 2D array of shape (N,nao) for LDA, 3D array of shape (4,N,nao) for GGA
or (5,N,nao) for meta-GGA. N is the number of grids, nao is the
number of AO functions. If xctype is GGA, ao[0] is AO value
and ao[1:3] are the AO gradients. If xctype is meta-GGA, ao[4:10]
are second derivatives of ao values.
dm : 2D array
Density matrix
Kwargs:
non0tab : 2D bool array
mask array to indicate whether the AO values are zero. The mask
array can be obtained by calling :func:`make_mask`
xctype : str
LDA/GGA/mGGA. It affects the shape of the return density.
verbose : int or object of :class:`Logger`
No effects.
Returns:
1D array of size N to store electron density if xctype = LDA; 2D array
of (4,N) to store density and "density derivatives" for x,y,z components
if xctype = GGA; (6,N) array for meta-GGA, where last two rows are
\nabla^2 rho and tau = 1/2(\nabla f)^2
'''
xctype = xctype.upper()
if xctype == 'LDA' or xctype == 'HF':
ngrids, nao = ao.shape
else:
ngrids, nao = ao[0].shape
if non0tab is None:
non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,mol.nbas),
dtype=numpy.uint8)
shls_slice = (0, mol.nbas)
ao_loc = mol.ao_loc_nr()
pos = mo_occ > OCCDROP
if pos.sum() > 0:
cpos = numpy.einsum('ij,j->ij', mo_coeff[:,pos], numpy.sqrt(mo_occ[pos]))
if xctype == 'LDA' or xctype == 'HF':
c0 = _dot_ao_dm(mol, ao, cpos, non0tab, shls_slice, ao_loc)
#:rho = numpy.einsum('pi,pi->p', c0, c0)
rho = _contract_rho(c0, c0)
elif xctype in ('GGA', 'NLC'):
rho = numpy.empty((4,ngrids))
c0 = _dot_ao_dm(mol, ao[0], cpos, non0tab, shls_slice, ao_loc)
#:rho[0] = numpy.einsum('pi,pi->p', c0, c0)
rho[0] = _contract_rho(c0, c0)
for i in range(1, 4):
c1 = _dot_ao_dm(mol, ao[i], cpos, non0tab, shls_slice, ao_loc)
#:rho[i] = numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.
rho[i] = _contract_rho(c0, c1) * 2
else: # meta-GGA
# rho[4] = \nabla^2 rho, rho[5] = 1/2 |nabla f|^2
rho = numpy.empty((6,ngrids))
c0 = _dot_ao_dm(mol, ao[0], cpos, non0tab, shls_slice, ao_loc)
#:rho[0] = numpy.einsum('pi,pi->p', c0, c0)
rho[0] = _contract_rho(c0, c0)
rho[5] = 0
for i in range(1, 4):
c1 = _dot_ao_dm(mol, ao[i], cpos, non0tab, shls_slice, ao_loc)
#:rho[i] = numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.
#:rho[5] += numpy.einsum('pi,pi->p', c1, c1)
rho[i] = _contract_rho(c0, c1) * 2
rho[5] += _contract_rho(c1, c1)
XX, YY, ZZ = 4, 7, 9
ao2 = ao[XX] + ao[YY] + ao[ZZ]
c1 = _dot_ao_dm(mol, ao2, cpos, non0tab, shls_slice, ao_loc)
#:rho[4] = numpy.einsum('pi,pi->p', c0, c1)
rho[4] = _contract_rho(c0, c1)
rho[4] += rho[5]
rho[4] *= 2
rho[5] *= .5
else:
if xctype == 'LDA' or xctype == 'HF':
rho = numpy.zeros(ngrids)
elif xctype in ('GGA', 'NLC'):
rho = numpy.zeros((4,ngrids))
else:
rho = numpy.zeros((6,ngrids))
neg = mo_occ < -OCCDROP
if neg.sum() > 0:
cneg = numpy.einsum('ij,j->ij', mo_coeff[:,neg], numpy.sqrt(-mo_occ[neg]))
if xctype == 'LDA' or xctype == 'HF':
c0 = _dot_ao_dm(mol, ao, cneg, non0tab, shls_slice, ao_loc)
#:rho -= numpy.einsum('pi,pi->p', c0, c0)
rho -= _contract_rho(c0, c0)
elif xctype == 'GGA':
c0 = _dot_ao_dm(mol, ao[0], cneg, non0tab, shls_slice, ao_loc)
#:rho[0] -= numpy.einsum('pi,pi->p', c0, c0)
rho[0] -= _contract_rho(c0, c0)
for i in range(1, 4):
c1 = _dot_ao_dm(mol, ao[i], cneg, non0tab, shls_slice, ao_loc)
#:rho[i] -= numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.
rho[i] -= _contract_rho(c0, c1) * 2 # *2 for +c.c.
else:
c0 = _dot_ao_dm(mol, ao[0], cneg, non0tab, shls_slice, ao_loc)
#:rho[0] -= numpy.einsum('pi,pi->p', c0, c0)
rho[0] -= _contract_rho(c0, c0)
rho5 = 0
for i in range(1, 4):
c1 = _dot_ao_dm(mol, ao[i], cneg, non0tab, shls_slice, ao_loc)
#:rho[i] -= numpy.einsum('pi,pi->p', c0, c1) * 2 # *2 for +c.c.
#:rho5 += numpy.einsum('pi,pi->p', c1, c1)
rho[i] -= _contract_rho(c0, c1) * 2 # *2 for +c.c.
rho5 += _contract_rho(c1, c1)
XX, YY, ZZ = 4, 7, 9
ao2 = ao[XX] + ao[YY] + ao[ZZ]
c1 = _dot_ao_dm(mol, ao2, cneg, non0tab, shls_slice, ao_loc)
#:rho[4] -= numpy.einsum('pi,pi->p', c0, c1) * 2
rho[4] -= _contract_rho(c0, c1) * 2
rho[4] -= rho5 * 2
rho[5] -= rho5 * .5
return rho
def _vv10nlc(rho,coords,vvrho,vvweight,vvcoords,nlc_pars):
thresh=1e-8
#output
exc=numpy.zeros(rho[0,:].size)
vxc=numpy.zeros([2,rho[0,:].size])
#outer grid needs threshing
threshind=rho[0,:]>=thresh
coords=coords[threshind]
R=rho[0,:][threshind]
Gx=rho[1,:][threshind]
Gy=rho[2,:][threshind]
Gz=rho[3,:][threshind]
G=Gx**2.+Gy**2.+Gz**2.
#threshed output
excthresh=numpy.zeros(R.size)
vxcthresh=numpy.zeros([2,R.size])
#inner grid needs threshing
innerthreshind=vvrho[0,:]>=thresh
vvcoords=vvcoords[innerthreshind]
vvweight=vvweight[innerthreshind]
Rp=vvrho[0,:][innerthreshind]
RpW=Rp*vvweight
Gxp=vvrho[1,:][innerthreshind]
Gyp=vvrho[2,:][innerthreshind]
Gzp=vvrho[3,:][innerthreshind]
Gp=Gxp**2.+Gyp**2.+Gzp**2.
#constants and parameters
Pi=numpy.pi
Pi43=4.*Pi/3.
Bvv, Cvv = nlc_pars
Kvv=Bvv*1.5*Pi*((9.*Pi)**(-1./6.))
Beta=((3./(Bvv*Bvv))**(0.75))/32.
#inner grid
W0p=Gp/(Rp*Rp)
W0p=Cvv*W0p*W0p
W0p=(W0p+Pi43*Rp)**0.5
Kp=Kvv*(Rp**(1./6.))
#outer grid
W0tmp=G/(R**2)
W0tmp=Cvv*W0tmp*W0tmp
W0=(W0tmp+Pi43*R)**0.5
dW0dR=(0.5*Pi43*R-2.*W0tmp)/W0
dW0dG=W0tmp*R/(G*W0)
K=Kvv*(R**(1./6.))
dKdR=(1./6.)*K
for i in range(R.size):
DX=vvcoords[:,0]-coords[i,0]
DY=vvcoords[:,1]-coords[i,1]
DZ=vvcoords[:,2]-coords[i,2]
R2=DX*DX+DY*DY+DZ*DZ
gp=R2*W0p+Kp
g=R2*W0[i]+K[i]
gt=g+gp
T=RpW/(g*gp*gt)
F=numpy.sum(T)
T*=(1./g+1./gt)
U=numpy.sum(T)
W=numpy.sum(T*R2)
F*=-1.5
#excthresh is multiplied by Rho later
excthresh[i]=Beta+0.5*F
vxcthresh[0,i]=Beta+F+1.5*(U*dKdR[i]+W*dW0dR[i])
vxcthresh[1,i]=1.5*W*dW0dG[i]
exc[threshind]=excthresh
vxc[0,threshind]=vxcthresh[0,:]
vxc[1,threshind]=vxcthresh[1,:]
return exc,vxc
def eval_mat(mol, ao, weight, rho, vxc,
non0tab=None, xctype='LDA', spin=0, verbose=None):
r'''Calculate XC potential matrix.
Args:
mol : an instance of :class:`Mole`
ao : ([4/10,] ngrids, nao) ndarray
2D array of shape (N,nao) for LDA,
3D array of shape (4,N,nao) for GGA
or (10,N,nao) for meta-GGA.
N is the number of grids, nao is the number of AO functions.
If xctype is GGA, ao[0] is AO value and ao[1:3] are the real space
gradients. If xctype is meta-GGA, ao[4:10] are second derivatives
of ao values.
weight : 1D array
Integral weights on grids.
rho : ([4/6,] ngrids) ndarray
Shape of ((*,N)) for electron density (and derivatives) if spin = 0;
Shape of ((*,N),(*,N)) for alpha/beta electron density (and derivatives) if spin > 0;
where N is number of grids.
rho (*,N) are ordered as (den,grad_x,grad_y,grad_z,laplacian,tau)
where grad_x = d/dx den, laplacian = \nabla^2 den, tau = 1/2(\nabla f)^2
In spin unrestricted case,
rho is ((den_u,grad_xu,grad_yu,grad_zu,laplacian_u,tau_u)
(den_d,grad_xd,grad_yd,grad_zd,laplacian_d,tau_d))
vxc : ([4,] ngrids) ndarray
XC potential value on each grid = (vrho, vsigma, vlapl, vtau)
vsigma is GGA potential value on each grid.
If the kwarg spin != 0, a list [vsigma_uu,vsigma_ud] is required.
Kwargs:
xctype : str
LDA/GGA/mGGA. It affects the shape of `ao` and `rho`
non0tab : 2D bool array
mask array to indicate whether the AO values are zero. The mask
array can be obtained by calling :func:`make_mask`
spin : int
If not 0, the returned matrix is the Vxc matrix of alpha-spin. It
is computed with the spin non-degenerated UKS formula.
Returns:
XC potential matrix in 2D array of shape (nao,nao) where nao is the
number of AO functions.
'''
xctype = xctype.upper()
if xctype == 'LDA' or xctype == 'HF':
ngrids, nao = ao.shape
else:
ngrids, nao = ao[0].shape
if non0tab is None:
non0tab = numpy.ones(((ngrids+BLKSIZE-1)//BLKSIZE,mol.nbas),
dtype=numpy.uint8)
shls_slice = (0, mol.nbas)
ao_loc = mol.ao_loc_nr()
transpose_for_uks = False
if xctype == 'LDA' or xctype == 'HF':
if not isinstance(vxc, numpy.ndarray) or vxc.ndim == 2:
vrho = vxc[0]
else:
vrho = vxc
# *.5 because return mat + mat.T
#:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho)
aow = _scale_ao(ao, .5*weight*vrho)
mat = _dot_ao_ao(mol, ao, aow, non0tab, shls_slice, ao_loc)
else:
#wv = weight * vsigma * 2
#aow = numpy.einsum('pi,p->pi', ao[1], rho[1]*wv)
#aow += numpy.einsum('pi,p->pi', ao[2], rho[2]*wv)
#aow += numpy.einsum('pi,p->pi', ao[3], rho[3]*wv)
#aow += numpy.einsum('pi,p->pi', ao[0], .5*weight*vrho)
vrho, vsigma = vxc[:2]
wv = numpy.empty((4,ngrids))
if spin == 0:
assert(vsigma is not None and rho.ndim==2)
wv[0] = weight * vrho * .5
wv[1:4] = rho[1:4] * (weight * vsigma * 2)
else:
rho_a, rho_b = rho
wv[0] = weight * vrho * .5
try:
wv[1:4] = rho_a[1:4] * (weight * vsigma[0] * 2) # sigma_uu
wv[1:4]+= rho_b[1:4] * (weight * vsigma[1]) # sigma_ud
except ValueError:
warnings.warn('Note the output of libxc.eval_xc cannot be '
'directly used in eval_mat.\nvsigma from eval_xc '
'should be restructured as '
'(vsigma[:,0],vsigma[:,1])\n')
transpose_for_uks = True
vsigma = vsigma.T
wv[1:4] = rho_a[1:4] * (weight * vsigma[0] * 2) # sigma_uu
wv[1:4]+= rho_b[1:4] * (weight * vsigma[1]) # sigma_ud
#:aow = numpy.einsum('npi,np->pi', ao[:4], wv)
aow = _scale_ao(ao[:4], wv)
mat = _dot_ao_ao(mol, ao[0], aow, non0tab, shls_slice, ao_loc)
# JCP, 138, 244108
# JCP, 112, 7002
if xctype == 'MGGA':
vlapl, vtau = vxc[2:]
if vlapl is None:
vlapl = 0
else:
if spin != 0:
if transpose_for_uks:
vlapl = vlapl.T
vlapl = vlapl[0]
XX, YY, ZZ = 4, 7, 9
ao2 = ao[XX] + ao[YY] + ao[ZZ]
#:aow = numpy.einsum('pi,p->pi', ao2, .5 * weight * vlapl, out=aow)
aow = _scale_ao(ao2, .5 * weight * vlapl, out=aow)
mat += _dot_ao_ao(mol, ao[0], aow, non0tab, shls_slice, ao_loc)
if spin != 0:
if transpose_for_uks:
vtau = vtau.T
vtau = vtau[0]
wv = weight * (.25*vtau + vlapl)
#:aow = numpy.einsum('pi,p->pi', ao[1], wv, out=aow)
aow = _scale_ao(ao[1], wv, out=aow)
mat += _dot_ao_ao(mol, ao[1], aow, non0tab, shls_slice, ao_loc)
#:aow = numpy.einsum('pi,p->pi', ao[2], wv, out=aow)
aow = _scale_ao(ao[2], wv, out=aow)
mat += _dot_ao_ao(mol, ao[2], aow, non0tab, shls_slice, ao_loc)
#:aow = numpy.einsum('pi,p->pi', ao[3], wv, out=aow)
aow = _scale_ao(ao[3], wv, out=aow)
mat += _dot_ao_ao(mol, ao[3], aow, non0tab, shls_slice, ao_loc)
return mat + mat.T.conj()
def _dot_ao_ao(mol, ao1, ao2, non0tab, shls_slice, ao_loc, hermi=0):
'''return numpy.dot(ao1.T, ao2)'''
ngrids, nao = ao1.shape
if nao < SWITCH_SIZE:
return lib.dot(ao1.T.conj(), ao2)
if not ao1.flags.f_contiguous:
ao1 = lib.transpose(ao1)
if not ao2.flags.f_contiguous:
ao2 = lib.transpose(ao2)
if ao1.dtype == ao2.dtype == numpy.double:
fn = libdft.VXCdot_ao_ao
else:
fn = libdft.VXCzdot_ao_ao
ao1 = numpy.asarray(ao1, numpy.complex128)
ao2 = numpy.asarray(ao2, numpy.complex128)
if non0tab is None or shls_slice is None or ao_loc is None:
pnon0tab = pshls_slice = pao_loc = lib.c_null_ptr()
else:
pnon0tab = non0tab.ctypes.data_as(ctypes.c_void_p)
pshls_slice = (ctypes.c_int*2)(*shls_slice)
pao_loc = ao_loc.ctypes.data_as(ctypes.c_void_p)
vv = numpy.empty((nao,nao), dtype=ao1.dtype)
fn(vv.ctypes.data_as(ctypes.c_void_p),
ao1.ctypes.data_as(ctypes.c_void_p),
ao2.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(nao), ctypes.c_int(ngrids),
ctypes.c_int(mol.nbas), ctypes.c_int(hermi),
pnon0tab, pshls_slice, pao_loc)
return vv
def _dot_ao_dm(mol, ao, dm, non0tab, shls_slice, ao_loc, out=None):
'''return numpy.dot(ao, dm)'''
ngrids, nao = ao.shape
if nao < SWITCH_SIZE:
return lib.dot(dm.T, ao.T).T
if not ao.flags.f_contiguous:
ao = lib.transpose(ao)
if ao.dtype == dm.dtype == numpy.double:
fn = libdft.VXCdot_ao_dm
else:
fn = libdft.VXCzdot_ao_dm
ao = numpy.asarray(ao, numpy.complex128)
dm = numpy.asarray(dm, numpy.complex128)
if non0tab is None or shls_slice is None or ao_loc is None:
pnon0tab = pshls_slice = pao_loc = lib.c_null_ptr()
else:
pnon0tab = non0tab.ctypes.data_as(ctypes.c_void_p)
pshls_slice = (ctypes.c_int*2)(*shls_slice)
pao_loc = ao_loc.ctypes.data_as(ctypes.c_void_p)
vm = numpy.ndarray((ngrids,dm.shape[1]), dtype=ao.dtype, order='F', buffer=out)
dm = numpy.asarray(dm, order='C')
fn(vm.ctypes.data_as(ctypes.c_void_p),
ao.ctypes.data_as(ctypes.c_void_p),
dm.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(nao), ctypes.c_int(dm.shape[1]),
ctypes.c_int(ngrids), ctypes.c_int(mol.nbas),
pnon0tab, pshls_slice, pao_loc)
return vm
def _scale_ao(ao, wv, out=None):
#:aow = numpy.einsum('npi,np->pi', ao[:4], wv)
if wv.ndim == 2:
ao = ao.transpose(0,2,1)
else:
ngrids, nao = ao.shape
ao = ao.T.reshape(1,nao,ngrids)
wv = wv.reshape(1,ngrids)
wv = numpy.asarray(wv, order='C')
comp, nao, ngrids = ao.shape
aow = numpy.ndarray((nao,ngrids), dtype=ao.dtype, buffer=out).T
if not ao.flags.c_contiguous:
aow = numpy.einsum('nip,np->pi', ao, wv)
elif aow.dtype == numpy.double:
libdft.VXC_dscale_ao(aow.ctypes.data_as(ctypes.c_void_p),
ao.ctypes.data_as(ctypes.c_void_p),
wv.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(comp), ctypes.c_int(nao),
ctypes.c_int(ngrids))
elif aow.dtype == numpy.complex128:
libdft.VXC_zscale_ao(aow.ctypes.data_as(ctypes.c_void_p),
ao.ctypes.data_as(ctypes.c_void_p),
wv.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(comp), ctypes.c_int(nao),
ctypes.c_int(ngrids))
else:
aow = numpy.einsum('nip,np->pi', ao, wv)
return aow
def _contract_rho(bra, ket):
#:rho = numpy.einsum('pi,pi->p', bra.real, ket.real)
#:rho += numpy.einsum('pi,pi->p', bra.imag, ket.imag)
bra = bra.T
ket = ket.T
nao, ngrids = bra.shape
rho = numpy.empty(ngrids)
if not (bra.flags.c_contiguous and ket.flags.c_contiguous):
rho = numpy.einsum('ip,ip->p', bra.real, ket.real)
rho += numpy.einsum('ip,ip->p', bra.imag, ket.imag)
elif bra.dtype == numpy.double and ket.dtype == numpy.double:
libdft.VXC_dcontract_rho(rho.ctypes.data_as(ctypes.c_void_p),
bra.ctypes.data_as(ctypes.c_void_p),
ket.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(nao), ctypes.c_int(ngrids))
elif bra.dtype == numpy.complex128 and ket.dtype == numpy.complex128:
libdft.VXC_zcontract_rho(rho.ctypes.data_as(ctypes.c_void_p),
bra.ctypes.data_as(ctypes.c_void_p),
ket.ctypes.data_as(ctypes.c_void_p),
ctypes.c_int(nao), ctypes.c_int(ngrids))
else:
rho = numpy.einsum('ip,ip->p', bra.real, ket.real)
rho += numpy.einsum('ip,ip->p', bra.imag, ket.imag)
return rho
def nr_vxc(mol, grids, xc_code, dms, spin=0, relativity=0, hermi=0,
max_memory=2000, verbose=None):
'''
Evaluate RKS/UKS XC functional and potential matrix on given meshgrids
for a set of density matrices. See :func:`nr_rks` and :func:`nr_uks`
for more details.
Args:
mol : an instance of :class:`Mole`
grids : an instance of :class:`Grids`
grids.coords and grids.weights are needed for coordinates and weights of meshgrids.
xc_code : str
XC functional description.
See :func:`parse_xc` of pyscf/dft/libxc.py for more details.
dms : 2D array or a list of 2D arrays
Density matrix or multiple density matrices
Kwargs:
hermi : int
Input density matrices symmetric or not
max_memory : int or float
The maximum size of cache to use (in MB).
Returns:
nelec, excsum, vmat.
nelec is the number of electrons generated by numerical integration.
excsum is the XC functional value. vmat is the XC potential matrix in
2D array of shape (nao,nao) where nao is the number of AO functions.
Examples:
>>> from pyscf import gto, dft
>>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')
>>> grids = dft.gen_grid.Grids(mol)
>>> grids.coords = numpy.random.random((100,3)) # 100 random points
>>> grids.weights = numpy.random.random(100)
>>> nao = mol.nao_nr()
>>> dm = numpy.random.random((2,nao,nao))
>>> nelec, exc, vxc = dft.numint.nr_vxc(mol, grids, 'lda,vwn', dm, spin=1)
'''
ni = NumInt()
return ni.nr_vxc(mol, grids, xc_code, dms, spin, relativity,
hermi, max_memory, verbose)
def nr_rks(ni, mol, grids, xc_code, dms, relativity=0, hermi=0,
max_memory=2000, verbose=None):
'''Calculate RKS XC functional and potential matrix on given meshgrids
for a set of density matrices
Args:
ni : an instance of :class:`NumInt`
mol : an instance of :class:`Mole`
grids : an instance of :class:`Grids`
grids.coords and grids.weights are needed for coordinates and weights of meshgrids.
xc_code : str
XC functional description.
See :func:`parse_xc` of pyscf/dft/libxc.py for more details.
dms : 2D array a list of 2D arrays
Density matrix or multiple density matrices
Kwargs:
hermi : int
Input density matrices symmetric or not
max_memory : int or float
The maximum size of cache to use (in MB).
Returns:
nelec, excsum, vmat.
nelec is the number of electrons generated by numerical integration.
excsum is the XC functional value. vmat is the XC potential matrix in
2D array of shape (nao,nao) where nao is the number of AO functions.
Examples:
>>> from pyscf import gto, dft
>>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')
>>> grids = dft.gen_grid.Grids(mol)
>>> grids.coords = numpy.random.random((100,3)) # 100 random points
>>> grids.weights = numpy.random.random(100)
>>> nao = mol.nao_nr()
>>> dm = numpy.random.random((nao,nao))
>>> ni = dft.numint.NumInt()
>>> nelec, exc, vxc = ni.nr_rks(mol, grids, 'lda,vwn', dm)
'''
xctype = ni._xc_type(xc_code)
make_rho, nset, nao = ni._gen_rho_evaluator(mol, dms, hermi)
shls_slice = (0, mol.nbas)
ao_loc = mol.ao_loc_nr()
nelec = numpy.zeros(nset)
excsum = numpy.zeros(nset)
vmat = numpy.zeros((nset,nao,nao))
aow = None
if xctype == 'LDA':
ao_deriv = 0
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
aow = numpy.ndarray(ao.shape, order='F', buffer=aow)
for idm in range(nset):
rho = make_rho(idm, ao, mask, 'LDA')
exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1, verbose)[:2]
vrho = vxc[0]
den = rho * weight
nelec[idm] += den.sum()
excsum[idm] += numpy.dot(den, exc)
# *.5 because vmat + vmat.T
#:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho, out=aow)
aow = _scale_ao(ao, .5*weight*vrho, out=aow)
vmat[idm] += _dot_ao_ao(mol, ao, aow, mask, shls_slice, ao_loc)
rho = exc = vxc = vrho = None
elif xctype == 'GGA':
ao_deriv = 1
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
ngrid = weight.size
aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)
for idm in range(nset):
rho = make_rho(idm, ao, mask, 'GGA')
exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1, verbose)[:2]
den = rho[0] * weight
nelec[idm] += den.sum()
excsum[idm] += numpy.dot(den, exc)
# ref eval_mat function
wv = _rks_gga_wv0(rho, vxc, weight)
#:aow = numpy.einsum('npi,np->pi', ao, wv, out=aow)
aow = _scale_ao(ao, wv, out=aow)
vmat[idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)
rho = exc = vxc = wv = None
elif xctype == 'NLC':
nlc_pars = ni.nlc_coeff(xc_code[:-6])
if nlc_pars == [0,0]:
raise NotImplementedError('VV10 cannot be used with %s. '
'The supported functionals are %s' %
(xc_code[:-6], ni.libxc.VV10_XC))
ao_deriv = 1
vvrho=numpy.empty([nset,4,0])
vvweight=numpy.empty([nset,0])
vvcoords=numpy.empty([nset,0,3])
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
rhotmp = numpy.empty([0,4,weight.size])
weighttmp = numpy.empty([0,weight.size])
coordstmp = numpy.empty([0,weight.size,3])
for idm in range(nset):
rho = make_rho(idm, ao, mask, 'GGA')
rho = numpy.expand_dims(rho,axis=0)
rhotmp = numpy.concatenate((rhotmp,rho),axis=0)
weighttmp = numpy.concatenate((weighttmp,numpy.expand_dims(weight,axis=0)),axis=0)
coordstmp = numpy.concatenate((coordstmp,numpy.expand_dims(coords,axis=0)),axis=0)
rho = None
vvrho=numpy.concatenate((vvrho,rhotmp),axis=2)
vvweight=numpy.concatenate((vvweight,weighttmp),axis=1)
vvcoords=numpy.concatenate((vvcoords,coordstmp),axis=1)
rhotmp = weighttmp = coordstmp = None
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
ngrid = weight.size
aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)
for idm in range(nset):
rho = make_rho(idm, ao, mask, 'GGA')
exc, vxc = _vv10nlc(rho,coords,vvrho[idm],vvweight[idm],vvcoords[idm],nlc_pars)
den = rho[0] * weight
nelec[idm] += den.sum()
excsum[idm] += numpy.dot(den, exc)
# ref eval_mat function
wv = _rks_gga_wv0(rho, vxc, weight)
#:aow = numpy.einsum('npi,np->pi', ao, wv, out=aow)
aow = _scale_ao(ao, wv, out=aow)
vmat[idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)
rho = exc = vxc = wv = None
vvrho = vvweight = vvcoords = None
elif xctype == 'MGGA':
if (any(x in xc_code.upper() for x in ('CC06', 'CS', 'BR89', 'MK00'))):
raise NotImplementedError('laplacian in meta-GGA method')
ao_deriv = 2
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
ngrid = weight.size
aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)
for idm in range(nset):
rho = make_rho(idm, ao, mask, 'MGGA')
exc, vxc = ni.eval_xc(xc_code, rho, 0, relativity, 1, verbose)[:2]
vrho, vsigma, vlapl, vtau = vxc[:4]
den = rho[0] * weight
nelec[idm] += den.sum()
excsum[idm] += numpy.dot(den, exc)
wv = _rks_gga_wv0(rho, vxc, weight)
#:aow = numpy.einsum('npi,np->pi', ao[:4], wv, out=aow)
aow = _scale_ao(ao[:4], wv, out=aow)
vmat[idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)
# FIXME: .5 * .5 First 0.5 for v+v.T symmetrization.
# Second 0.5 is due to the Libxc convention tau = 1/2 \nabla\phi\dot\nabla\phi
wv = (.5 * .5 * weight * vtau).reshape(-1,1)
vmat[idm] += _dot_ao_ao(mol, ao[1], wv*ao[1], mask, shls_slice, ao_loc)
vmat[idm] += _dot_ao_ao(mol, ao[2], wv*ao[2], mask, shls_slice, ao_loc)
vmat[idm] += _dot_ao_ao(mol, ao[3], wv*ao[3], mask, shls_slice, ao_loc)
rho = exc = vxc = vrho = vsigma = wv = None
elif xctype == 'MGGA+':
if (any(x in xc_code.upper() for x in ('CC06', 'CS', 'BR89', 'MK00'))):
raise NotImplementedError('laplacian in meta-GGA method')
ao_deriv = 2
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
ngrid = weight.size
aow = numpy.ndarray(ao[0].shape, order='F', buffer=aow)
for idm in range(nset):
rho = make_rho(idm, ao, mask, 'MGGA')
exc, vxc = ni.eval_xc(xc_code,rho,0,weight,coords, relativity, 1, verbose)[:2]
vrho, vsigma, vlapl, vtau = vxc[:4]
den = rho[0] * weight
nelec[idm] += den.sum()
excsum[idm] += numpy.dot(den, exc)
wv = _rks_gga_wv0(rho, vxc, weight)
aow = numpy.einsum('npi,np->pi', ao[:4], wv, out=aow)
vmat[idm] += _dot_ao_ao(mol, ao[0], aow, mask, shls_slice, ao_loc)
# FIXME: .5 * .5 First 0.5 for v+v.T symmetrization.
# Second 0.5 is due to the Libxc convention tau = 1/2 \nabla\phi\dot\nabla\phi
wv = (.5 * .5 * weight * vtau).reshape(-1,1)
vmat[idm] += _dot_ao_ao(mol, ao[1], wv*ao[1], mask, shls_slice, ao_loc)
vmat[idm] += _dot_ao_ao(mol, ao[2], wv*ao[2], mask, shls_slice, ao_loc)
vmat[idm] += _dot_ao_ao(mol, ao[3], wv*ao[3], mask, shls_slice, ao_loc)
rho = exc = vxc = vrho = vsigma = wv = None
for i in range(nset):
vmat[i] = vmat[i] + vmat[i].T
if nset == 1:
nelec = nelec[0]
excsum = excsum[0]
vmat = vmat.reshape(nao,nao)
return nelec, excsum, vmat
def nr_uks(ni, mol, grids, xc_code, dms, relativity=0, hermi=0,
max_memory=2000, verbose=None):
'''Calculate UKS XC functional and potential matrix on given meshgrids
for a set of density matrices
Args:
mol : an instance of :class:`Mole`
grids : an instance of :class:`Grids`
grids.coords and grids.weights are needed for coordinates and weights of meshgrids.
xc_code : str
XC functional description.
See :func:`parse_xc` of pyscf/dft/libxc.py for more details.
dms : a list of 2D arrays
A list of density matrices, stored as (alpha,alpha,...,beta,beta,...)
Kwargs:
hermi : int
Input density matrices symmetric or not
max_memory : int or float
The maximum size of cache to use (in MB).
Returns:
nelec, excsum, vmat.
nelec is the number of (alpha,beta) electrons generated by numerical integration.
excsum is the XC functional value.
vmat is the XC potential matrix for (alpha,beta) spin.
Examples:
>>> from pyscf import gto, dft
>>> mol = gto.M(atom='H 0 0 0; H 0 0 1.1')
>>> grids = dft.gen_grid.Grids(mol)
>>> grids.coords = numpy.random.random((100,3)) # 100 random points
>>> grids.weights = numpy.random.random(100)
>>> nao = mol.nao_nr()
>>> dm = numpy.random.random((2,nao,nao))
>>> ni = dft.numint.NumInt()
>>> nelec, exc, vxc = ni.nr_uks(mol, grids, 'lda,vwn', dm)
'''
xctype = ni._xc_type(xc_code)
if xctype == 'NLC':
dms_sf = dms[0] + dms[1]
nelec, excsum, vmat = nr_rks(ni, mol, grids, xc_code, dms_sf, relativity, hermi,
max_memory, verbose)
return [nelec,nelec], excsum, numpy.asarray([vmat,vmat])
shls_slice = (0, mol.nbas)
ao_loc = mol.ao_loc_nr()
dma, dmb = _format_uks_dm(dms)
nao = dma.shape[-1]
make_rhoa, nset = ni._gen_rho_evaluator(mol, dma, hermi)[:2]
make_rhob = ni._gen_rho_evaluator(mol, dmb, hermi)[0]
nelec = numpy.zeros((2,nset))
excsum = numpy.zeros(nset)
vmat = numpy.zeros((2,nset,nao,nao))
aow = None
if xctype == 'LDA':
ao_deriv = 0
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
aow = numpy.ndarray(ao.shape, order='F', buffer=aow)
for idm in range(nset):
rho_a = make_rhoa(idm, ao, mask, xctype)
rho_b = make_rhob(idm, ao, mask, xctype)
exc, vxc = ni.eval_xc(xc_code, (rho_a, rho_b),
1, relativity, 1, verbose)[:2]
vrho = vxc[0]
den = rho_a * weight
nelec[0,idm] += den.sum()
excsum[idm] += numpy.dot(den, exc)
den = rho_b * weight
nelec[1,idm] += den.sum()
excsum[idm] += numpy.dot(den, exc)
# *.5 due to +c.c. in the end
#:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho[:,0], out=aow)
aow = _scale_ao(ao, .5*weight*vrho[:,0], out=aow)
vmat[0,idm] += _dot_ao_ao(mol, ao, aow, mask, shls_slice, ao_loc)
#:aow = numpy.einsum('pi,p->pi', ao, .5*weight*vrho[:,1], out=aow)
aow = _scale_ao(ao, .5*weight*vrho[:,1], out=aow)
vmat[1,idm] += _dot_ao_ao(mol, ao, aow, mask, shls_slice, ao_loc)
rho_a = rho_b = exc = vxc = vrho = None
elif xctype == 'GGA':
ao_deriv = 1
for ao, mask, weight, coords \
in ni.block_loop(mol, grids, nao, ao_deriv, max_memory):
ngrid = weight.size