/* Copyright (C) 2008 Jiri Pittner or This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . */ //this code is too slow - cf. JCTC 12.1207,2016 for improvements - mainly precomputing of alpha and beta factors and laplace expansion of last column for CIS w.f.s //the main improvement coult be easy to implement by making a hashtable of already computed alpha, beta factors on the fly //and reading from the table if already has been computed previously //this program computes overlaps of arbitrary wave functions expressed in Slater determinants or GUGA CSFs //UHF version now available //NO particular order of determinants is assumed - all dets are listed in Slaterfile and CI coefficients //in matching order are in the input // //-m selects the algorithm (notes and references in doc/cioverlap.tex), the default is 2: //0 the original one: loop over pairs of determinants with screening (-t, -e, -A) and precomputed elimination of inactive orbitals (-i) //1 string tables: the determinants are split into distinct alpha and beta strings, the determinant of the MO overlaps is computed // once for each pair of strings (frozen core orbitals and orbitals common to all strings are eliminated beforehand) // and the tables are contracted with the CI vectors; no screening, any wave function //2 closed formulas for CIS-type wave functions (single replacements in one spin from a common reference) and for spin-flip lists // (one electron removed from one spin and added to the other): no determinants for pairs of strings, only matrix products // if the overlap block of the reference orbitals is ill-conditioned (the reference changed its character between the geometries), // a warning is printed and the overlap is computed by 1; other wave functions are computed by 1 as well #undef oldversion #include #include #include #include #include #include #include #include #include #include #include "gelfand.h" #include "drt.h" #include "readintegrals.h" #include "options.h" //LA #include "vec.h" #include "mat.h" #include "smat.h" #include "sparsemat.h" #include "nonclass.h" #include "qsort.h" #undef DEBUG #undef DEBUG2 #undef DEBUG3 #include #include #include template struct twooverlaps { NRMat::elementtype> alpha; NRMat::elementtype> beta; int rowparity; //parity of permutation to get rows in alpha,beta order int colparity; //parity of permutation to get columns in alpha,beta order }; template const twooverlaps slatersubmatrices(const MAT (&a)[2], const int nelec, const INDEX rows, const INDEX cols, const int ncore, const int nactive, const bool inversedorbitals) { twooverlaps r; const int ncoreshift=0; //even with frozen core, the numbering of MOs is NOT shifted int nalpha=0; int nbeta=0; for(int j=0; j0 && cols[j]>0) r.alpha(ncore+ia,ncore+ja) = a[0](nactive-abs(rows[i])+ncoreshift,nactive-abs(cols[j])+ncoreshift); if(cols[j]<0) ++jb; else ++ja; } if(rows[i]<0) ++ib; else ++ia; } } else { int ia=0; int ib=0; for(int i=0; i0 && cols[j]>0) r.alpha(ncore+ia,ncore+ja) = a[0](abs(rows[i])+ncoreshift-1,abs(cols[j])+ncoreshift-1); if(cols[j]<0) ++jb; else ++ja; } if(rows[i]<0) ++ib; else ++ia; } } return r; } #if defined(oldversion) || defined(DEBUG3) template const NRMat::elementtype> slatersubmatrix(const MAT (&a)[2], const int nelec, const INDEX rows, const INDEX cols, const int ncore, const int nactive, const bool inversedorbitals) { const int ncoreshift=0; //even with frozen core, the numbering of MOs is NOT shifted int ncore2=2*ncore; NRMat::elementtype> r(nelec+ncore2,nelec+ncore2); //core-core block for(int i=0; i submat; NRSMat coeffs; REAL det; }; static part_eliminated *precompa=NULL, *precompb=NULL; void prepare_elimination(part_eliminated **precomp, const NRMat &a, int inactive) { *precomp = new part_eliminated; (*precomp)->submat = a.submatrix(0,inactive-1,0,inactive-1); (*precomp)->coeffs.resize(inactive); (*precomp)->coeffs.clear(); //cout <<"Constant part of overlap matrices\n"<<(*precomp)->submat; //no pivoting necessary, assumed inactive orbitals do not change character and diagonal elements are about 0.99 for(int i=0; isubmat(i,i); for(int j=i+1; jsubmat(j,i)/p; (*precomp)->coeffs(i,j) = q; xaxpy(inactive,q,(*precomp)->submat[i],1,(*precomp)->submat[j],1); } } REAL d=1.; for(int i=0; isubmat(i,i); (*precomp)->det=d; //cout <<"Pre-eliminated ovelap submatrix\n"<<(*precomp)->submat; //cout.flush(); //cout <<"Elimination coefficients\n"<<(*precomp)->coeffs; //cout.flush(); } REAL finish_elimination(const part_eliminated *precomp, NRMat &a, int inactive) { //store in the matrix the precomputed part a.storesubmatrix(0,0,precomp->submat); //perform the precomputed linear combinations on the right columns for(int i=0; icoeffs(i,j),a[i]+inactive,1,a[j]+inactive,1); //finish elimination //should a pivoting be done for accuracy (in principle an orbital swap could lead to division by a near-zero) ? for(int i=0; i jlow) jlow= inactive; for(int j=jlow; jdet; for(int i=inactive; i0) { REAL s=0.; for(int a=0; a overlaps=slatersubmatrix(Smo,nelec,slaters[i],slaters[k],ncore,mo,inversedorbitals); REAL dd=determinant_destroy(overlaps); #else #ifdef DEBUG3 NRMat overlaps=slatersubmatrix(Smo,nelec,slaters[i],slaters[k],ncore,mo,inversedorbitals); #ifdef DEBUG2 if(i==0 && k==13) { cout <<"Ssl "<1) //simplified computation from a precomputed intermediate for efficiency { if(!precompa) prepare_elimination(&precompa,overlaps2.alpha,inactive); if(!precompb) prepare_elimination(&precompb,overlaps2.beta,inactive); da = finish_elimination(precompa,overlaps2.alpha,inactive); db = finish_elimination(precompb,overlaps2.beta,inactive); } else //full determinant computation { da=determinant_destroy(overlaps2.alpha); db=determinant_destroy(overlaps2.beta); } REAL dd=da*db; if((overlaps2.rowparity+overlaps2.colparity)&1) dd= -dd; #ifdef DEBUG cout <<"da db rowparity colparity = "< S; //MO overlaps after the pivot transform with respect to the eliminated orbitals REAL det0; //determinant of the overlap block of the eliminated orbitals NRMat rest; //the orbitals of each string which are not eliminated (no columns if there are none) NRVec sign; //parity of moving the eliminated orbitals of each string in front of the others stringfactors(const NRMat &Smo, const NRMat &strings, const int ncore); void block(const int *rows, const int nrows, const int *cols, const int ncols, NRMat &f) const; //f(i,j) for the strings rows[i] and cols[j] }; stringfactors::stringfactors(const NRMat &Smo, const NRMat &strings, const int ncore) { const int nstr=strings.nrows(); const int nel=strings.ncols(); const int norb=Smo.nrows(); //orbitals common to all strings (orbital number o in a string is the MO number o-1, the frozen core MOs come first) NRVec count(0,norb); for(int i=0; inorb) laerror("orbital number in slaterfile out of range"); ++count[strings(i,e)-1]; } int ncommon=ncore; for(int o=ncore; o0) ++ncommon; NRVec common(ncommon); for(int o=0; o0) common[j++]=o; } det0=1.; const int nrest=nel-(ncommon-ncore); if(nstr==0 || nrest==0) //a single string made of common orbitals only: its factor is the determinant of their overlaps { if(ncommon) det0=determinant(Smo.submatrix(common,common)); return; } sign.resize(nstr); if(ncommon) { //the elimination needs a well-conditioned overlap block of the eliminated orbitals (it is not, if one of them //changed its character between the geometries); otherwise they are left in the determinants, in front of the others const REAL cond=CondNumber(Smo.submatrix(common,common),'1'); if(!(cond<=STRINGS_MAXCOND)) { char buf[32]; sprintf(buf,"%.1e",cond); cout <<"WARNING: -m 1: the overlap block of the frozen core orbitals and of the orbitals common to all strings of one spin is ill-conditioned (condition number "< &f) const { const int n=rest.ncols(); f.resize(nrows,ncols); if(n==0) //a single string made of the eliminated orbitals only { for(int i=0; i c(norb,n); //c(o,k) = S(orbital k of the bra string, o): the possible columns of the determinant, contiguous NRMat L(n,n); //L(r,m) multiplier of the row r in the step m NRVec x(n),t(n),y(n); NRVec detp(n+1); //determinant of the leading columns including the sign of the pivoting, zero if they are singular NRVec piv(n); //pivot row of each step NRMat rem(n+1,n); //rows not yet used as pivots before each step, in increasing order NRVec prev(n); //orbitals of the eliminated columns for(int i=0; ibig) {big=abs(x[rl[q]]); p=rl[q]; parity=q;} if(!(big>=LA_precision::det_tiny())) {detp[l+1]=0.; continue;} //singular, as in determinant() of LA piv[l]=p; detp[l+1]= parity&1 ? -detp[l]*x[p] : detp[l]*x[p]; const REAL r=1./x[p]; int *rn=rem[l+1]; for(int q=0; q=0; --m) { const REAL *lm=L[piv[m]]; y[piv[m]]=t[m]; for(int q=0; q cachedslaterstrings(const slaterbasis &slaters, NRMat (&strings)[2]) { const lexindex sl=slaters.nrows(); const int nelec=slaters.ncols(); const unsigned long long header[3]={sl,(unsigned long long)nelec,slaters.hash()}; int f=open("slaterstringsfile",O_CREAT|O_RDWR|O_LARGEFILE,0777); if(f<0) {perror("cannot open slaterstringsfile");laerror("IO error");} NRVec ds; unsigned long long h[3]; const ssize_t r=read(f,h,sizeof(h)); if(r==(ssize_t)sizeof(h) && h[0]==header[0] && h[1]==header[1] && h[2]==header[2]) { strings[0].get(f,true); strings[1].get(f,true); ds.get(f,true); cout <<"Strings of the determinants read from slaterstringsfile"< &ds, const int nstr[2], NRVec (&cls)[2], int ncls[2]) { for(int spin=0; spin<2; ++spin) { NRVec h((unsigned long long)0,nstr[spin]); NRVec count(0,nstr[spin]); for(lexindex k=0; k<(lexindex)ds.size(); ++k) { h[ds[k].string[spin]]+=hash_mix(ds[k].string[1-spin],0); //the sum is independent of the order of the determinants ++count[ds[k].string[spin]]; } std::map,int> classes; cls[spin].resize(nstr[spin]); for(int i=0; i key(h[i],count[i]); std::map,int>::const_iterator c=classes.find(key); if(c==classes.end()) { cls[spin][i]=classes.size(); classes[key]=cls[spin][i]; } else cls[spin][i]=c->second; } ncls[spin]=classes.size(); } } //largest number of classes of strings of one spin for which the contraction by blocks is used #ifndef STRINGS_MAXCLASSES #define STRINGS_MAXCLASSES 64 #endif //largest number of elements of the matrices processed at once in the contraction by blocks (a batch of rows of a block of factors) #ifndef STRINGS_BATCH #define STRINGS_BATCH 4000000 #endif //for the bra block (ca,cb) and the ket block (ka,kb) with the numbers of strings nca,ncb,nka,nkb: are the products //Fa(ca,ka) D'(ka,kb) and D(ca,cb) Fb(cb,kb) cheaper than D(ca,cb)^T Fa(ca,ka) and Fb(cb,kb) D'(ka,kb)^T? static inline bool ketalphafirst(const REAL nca, const REAL ncb, const REAL nka, const REAL nkb) { return nca*nkb*(nka+ncb) <= nka*ncb*(nkb+nca); } //overlap of the CI vectors by means of the factors for pairs of alpha and beta strings (-m 1), any wave function //S_IJ = sum_{a,b,a',b'} D_I(a,b) Fa(a,a') D'_J(a',b') Fb(b,b'), where D(a,b) is the CI coefficient (with the sign) of the determinant //made of the alpha string a and the beta string b, or zero if there is no such determinant //the strings are divided into classes (see stringclasses), so that D consists of dense blocks; for a block (ca,cb) of the bras and //a block (ka,kb) of the kets the contribution is the scalar product either of Fa(ca,ka) D'(ka,kb) with D(ca,cb) Fb(cb,kb) //or of D(ca,cb)^T Fa(ca,ka) with Fb(cb,kb) D'(ka,kb)^T, whichever needs less operations //each block of the factors thus occurs only in products with the coefficients: it is computed once, in batches of rows, and not stored //if the determinants have no such structure (too many classes), the tables of the factors of all pairs of strings are stored and //contracted determinant by determinant: W_J(b,a') = sum_{l with alpha string a'} Fb(b,b_l) D'_J(l), S_IJ = sum_k D_I(k) sum_a' Fa(a_k,a') W_J(b_k,a') static NRMat CIoverlap_strings(const NRMat &brasl, const NRMat &ketsl, const NRMat (&Smo)[2], const slaterbasis &slaters, const int ncore, const NRVec *slperm) { const lexindex sl=slaters.nrows(); const int nbra=brasl.ncols(); const int nket=ketsl.ncols(); clock_t t0=clock(); clock_t tfactors=0; NRMat strings[2]; const NRVec ds=cachedslaterstrings(slaters,strings); const int nstr[2]={strings[0].nrows()?strings[0].nrows():1, strings[1].nrows()?strings[1].nrows():1}; //a spin without electrons has one empty string const stringfactors Fa(Smo[0],strings[0],ncore), Fb(Smo[1],strings[1],ncore); cout <<"Number of determinants in the wavefunctions = "< cls[2],pos[2]; NRVec > members[2]; int ncls[2]; stringclasses(ds,nstr,cls,ncls); for(int spin=0; spin<2; ++spin) { NRVec n(0,ncls[spin]); for(int i=0; i isblock(ncls[0],ncls[1]); isblock.clear(); for(lexindex k=0; kSTRINGS_MAXCLASSES || ncls[1]>STRINGS_MAXCLASSES || blocksize>2.*sl) //no block structure { cout <<"The determinants do not consist of a few blocks of classes of strings, the tables of factors for all pairs of strings are used"< Fat,Fbt; { NRVec all(nstr[0]>nstr[1]?nstr[0]:nstr[1]); for(int i=0; i result(nbra,nket); NRMat Wt(na,nb); //transposed W is accumulated to access the memory contiguously NRVec x(sl); //in the order of the CI coefficients for(int J=0; J W=Wt.transpose(); for(lexindex k=0; k s(nbra); s.gemv(0.,brasl,'t',1.,x); for(int I=0; I &strings, const NRVec &weight, const int kind, const int ncore, const int norb, NRVec &ref, NRVec &virt, NRMat &hp) { const int nstr=strings.nrows(); const int nel=strings.ncols(); NRVec count(0,norb), common(0,norb); for(int i=0; i=norb) laerror("orbital number in slaterfile out of range"); count[o]+=weight[i]; ++common[o]; } NRVec isref((char)0,norb); int nref=0; if(kind==0) //the nel most occupied orbitals, the lower one of equally occupied { if(nel>norb-ncore) laerror("more electrons than orbitals"); for(int e=0; ecount[best])) best=o; isref[best]=1; ++nref; } } else for(int o=ncore; o0 ? (nstr>0 && common[o]==nstr) : common[o]>0) {isref[o]=1; ++nref;} if(nref!=nel-kind) return false; ref.resize(ncore+nref); virt.resize(norb-ncore-nref); NRVec pos(norb); //position in ref or in virt { int r=0,v=0; for(int o=0; o occ((char)0,norb); for(int i=0; i1||np>1) return false; hp(i,2)= parity&1? -1:1; } return true; } //overlap of CIS-type wave functions and of spin-flip wave functions by closed formulas (-m 2) //with the pivot transform of the MO overlaps with respect to the reference orbitals o (v are the other orbitals), //M=s_oo^-1, X=s_vo M, Y=M s_ov, Sigma=s_vv-s_vo M s_ov, D=det s_oo, the determinant of the overlaps of two strings is //D for reference-reference, D X_vi for (i->v)-reference, D Y_jw for reference-(j->w), D (X_vi Y_jw + M_ji Sigma_vw) for (i->v)-(j->w), //D Sigma_vw for strings with a particle v, w added and D M_ji for strings with a hole i, j (signs in holesparticles) //CIS: S_IJ = Da Db [(c0_I + x_I)(c0'_J + y_J) + sum_spin Tr(C_I^T M^T C'_J Sigma^T)], x_I = sum_spin Tr(C_I X), y_J = sum_spin Tr(C'_J^T Y) //spin-flip: S_IJ = Dp Dh Tr(C_I^T M_h^T C'_J Sigma_p^T), h is the spin with the hole and p the spin with the particle //if the determinants are not of these kinds or s_oo is ill-conditioned, nothing is computed and method is changed to 1 //for the caller to use that algorithm static NRMat CIoverlap_cis(const NRMat &brasl, const NRMat &ketsl, const NRMat (&Smo)[2], const slaterbasis &slaters, const int ncore, const NRVec *slperm, int &method) { const lexindex sl=slaters.nrows(); const int norb=Smo[0].nrows(); clock_t t0=clock(); NRMat strings[2]; const NRVec ds=cachedslaterstrings(slaters,strings); NRVec weight[2]; for(int spin=0; spin<2; ++spin) { weight[spin].resize(strings[spin].nrows()?strings[spin].nrows():1); weight[spin].clear(); for(lexindex k=0; k ref[2],virt[2]; NRMat hp[2]; int kind[2]={0,0}; bool ok=holesparticles(strings[0],weight[0],0,ncore,norb,ref[0],virt[0],hp[0]) && holesparticles(strings[1],weight[1],0,ncore,norb,ref[1],virt[1],hp[1]); if(ok) for(lexindex k=0; k=0 && hp[1](ds[k].string[1],0)>=0) {ok=false; break;} //both spins excited for(int pspin=0; pspin<2 && !ok; ++pspin) //spin-flip, pspin is the spin with the particle { kind[pspin]=1; kind[1-pspin]= -1; ok=holesparticles(strings[0],weight[0],kind[0],ncore,norb,ref[0],virt[0],hp[0]) && holesparticles(strings[1],weight[1],kind[1],ncore,norb,ref[1],virt[1],hp[1]); } if(!ok) { method=1; cout <<"The determinants are neither single replacements from one reference nor a spin-flip list, the overlap is computed by -m 1"<(); } const bool spinflip= kind[0]!=0; cout <<"Number of determinants in the wavefunctions = "<0?"alpha":"beta")<(); } } //pivot transforms of the MO overlaps REAL det=1.; NRMat M[2],Xt[2],Y[2],Sigma[2]; for(int spin=0; spin<2; ++spin) { if(ref[spin].size()==0 || virt[spin].size()==0) continue; //no electrons or no other orbitals: nothing to contract REAL d; const NRMat P=pivot_transform(Smo[spin],ref[spin],ref[spin],&d); det*=d; M[spin]=P.submatrix(ref[spin],ref[spin]); Sigma[spin]=P.submatrix(virt[spin],virt[spin]); if(!spinflip) { Xt[spin]=P.submatrix(virt[spin],ref[spin]).transpose(); Y[spin]=P.submatrix(ref[spin],virt[spin]); Y[spin]*= -1.; } } for(int spin=0; spin<2; ++spin) if(ref[spin].size() && virt[spin].size()==0) det*=determinant(Smo[spin]); //all orbitals occupied //channels of the contraction: CIS has one for each spin, spin-flip a single one with the hole in hspin and the particle in pspin const int nchannel= spinflip?1:2; const int pspin= kind[1]>0?1:0; const int hspin= spinflip?1-pspin:0; int nh[2],np[2]; //dimensions of the coefficient matrices bool active[2]; for(int c=0; c0 && np[c]>0; } //coefficients of the reference determinant and matrices of the coefficients C(hole,particle) with the signs const int nbra=brasl.ncols(); const int nket=ketsl.ncols(); NRVec c0[2]; NRVec > C[2][2]; //[bra or ket][channel] for(int bk=0; bk<2; ++bk) { const NRMat &v= bk?ketsl:brasl; c0[bk].resize(v.ncols()); c0[bk].clear(); for(int c=0; c=0) { const REAL sign=ds[k].sign*hp[0](a,2); for(int I=0; I=0) { const REAL sign=ds[k].sign*hp[1](b,2); for(int I=0; I result(nbra,nket); result.clear(); NRVec x(nbra); x.clear(); if(!spinflip) for(int I=0; I tmp(nh[c],np[c]), G(nh[c],np[c]); tmp.gemm(0.,M[spinflip?hspin:c],'t',C[1][c][J],'n',1.); G.gemm(0.,tmp,'n',Sigma[spinflip?pspin:c],'t',1.); for(int I=0; I CIoverlap_slater( bool uhf, const NRMat &brasl, //slaterCIsize x n const NRMat &ketsl, //slaterCIsize x m const NRMat &Sraw, //2*AO x 2*AO (generated by artificial doubled geometry input) const NRMat (&braLCAO)[2], //AO x MO const NRMat (&ketLCAO)[2], //AO x MO int slaterfile, //file descriptor for slater basis int excitlistfile, //file descriptor for list of not neglected excitations const int nelec, const int mo, //active MOs const int ncore=0, const int ndiscarded=0, bool make_excitlist=true, const int truncation=4, //neglect overlap of Slater dets differing in more than ... spinorbitals (take into account arbitrary MO swapping) const bool inversedorbitals=true, //lowest MOs are at the top of DRT when true const int slaterorder=1, const bool reorderslbasis=true, //the slater basis was not sorted before const int slaterpermfile=-1, //file handle for permutation of slater overlap matrix (slater CI vectors will remain same, slater basis is permuted) REAL screeningthr=0, NRMat *activerange=NULL, int inactive=0, //for performance improving precompute a constant part of the determinants NRMat *screening_mask = NULL, bool SMO_only=false, int method=0 //0 pairs of determinants with screening, 1 string tables, 2 closed formulas for CIS and spin-flip ) { int motot=mo+ncore+ndiscarded; cout <<"Number of frozen+active+discarded MOs = "<mo||(*activerange)(0,1)>mo||(*activerange)(1,0)>mo||(*activerange)(1,1)>mo) laerror("illegal active orbital range specified"); } //consistency checks if(ao!=ketLCAO[0].nrows() || ao!=ketLCAO[1].nrows() || ao!=braLCAO[0].nrows() || ao!=braLCAO[1].nrows() || 2*ao!=Sraw.nrows() || motot!=braLCAO[0].ncols() || motot!=ketLCAO[0].ncols() || motot!=braLCAO[1].ncols() || motot!=ketLCAO[1].ncols() || sl!=(lexindex)ketsl.nrows() ) { cout <<"ao " < Smo[2]; Smo[0].resize(motot,motot); Smo[1].resize(motot,motot); { NRMat Sao12=Sraw.submatrix(0,ao-1,ao,2*ao-1); #if 0 cout <<"test Sao12\n"< tmp; for(int spin=0; spin<2; ++spin) { tmp=Sao12*ketLCAO[spin]; Smo[spin].gemm(0.,braLCAO[spin],'t',tmp,'n',1.); } } /* for test symmetrize Smo and test symmetry of Ssl Smo[0]= (Smo[0]+Smo[0].transpose())*.5; Smo[1]= (Smo[1]+Smo[1].transpose())*.5; */ for(int spin=0; spin<2; ++spin) { #if 0 cout <<"test Smo["< bra2ketperm[2]; #if 0 //the application of the permutation is switched off (see the end of this block), so the mapping is not computed either NRVec bra2ket[2]; bra2ket[0].resize(motot); bra2ket[1].resize(motot); { NRMat Sao11=realsqrt(Sraw.submatrix(0,ao-1,0,ao-1)); NRMat Sao22=realsqrt(Sraw.submatrix(ao,2*ao-1,ao,2*ao-1)); for(int spin=0; spin<2; ++spin) { NRMat braL = Sao11 * braLCAO[spin]; NRMat ketL = Sao22 * ketLCAO[spin]; NRMat Sloewdin(motot,motot); Sloewdin.gemm(0.,braL,'t',ketL,'n',1.); cout <<"test Sloewdin["< counts(motot); NRVec mophase(motot); counts=0; mophase=0; for(int i=0; i smax && j != jmaxforbid) { jmax=j; smax=abs(Sloewdin(i,j)); pmax = Sloewdin(i,j)>0. ?1 : -1; } bra2ket[spin][i]=jmax; mophase[i] = pmax; if(counts[jmax] && jmaxforbid== -1) //this already had a big overlap and we were not in the second search already { //find second biggest one jmaxforbid=jmax; goto findmax; } else counts[jmax]++; } cout <<"test bra2ket["<=motot-ndiscarded) {cout <<"Warning: MO swap outside of active space occured for spin "<0) permuteslvectors=true; } if(reorderslbasis && !permuteslvectors) //was not reordered previously { //read the input basis lseek(slaterfile,0,SEEK_SET); slaters.get(slaterfile,false); //check that the whole slaterfile has been exhausted by the read to prevent mismatch in the number of electrons { unsigned char dummy; int r = read(slaterfile,&dummy,1); if (r>0) laerror("slaterfile is larger than expected, check the number of electrons in cioverlap input"); if (r<0) laerror("unexpected error when testing slaterfile eof"); } //check for illegal content (orbital number 0) if(slaters.checkzero()) laerror("malformed slaterfile encountered, perhaps cipc/mcpc was compiled without --assume byterecl"); //sort NRVec slperm(sl); for(lexindex i=0; i0 ? slsort_slbascmp : slsort_slbascmp2 ,slsort_slbasswap); //save the new basis lseek(slaterfile,0,SEEK_SET); for(lexindex i=0; i0) laerror("slaterfile is larger than expected, check the number of electrons in cioverlap input"); if (r<0) laerror("unexpected error when testing slaterfile eof"); } //check for illegal content (orbital number 0) if(slaters.checkzero()) laerror("malformed slaterfile encountered, perhaps cipc was compiled without --assume byterecl"); #ifdef DEBUG cout <<"slater basis "< slperm; if(permuteslvectors) { lseek(slaterpermfile,0,SEEK_SET); slperm.get(slaterpermfile,true); if(sl!= (lexindex)slperm.size()) laerror("inconsistent slaterpermfile"); } NRMat result; if(method==2) result=CIoverlap_cis(brasl,ketsl,Smo,slaters,ncore,permuteslvectors?&slperm:NULL,method); //may change method to 1 if(method==1) result=CIoverlap_strings(brasl,ketsl,Smo,slaters,ncore,permuteslvectors?&slperm:NULL); if(screening_mask) for(int i=0; i allowedlist(sl); NRVec n_act_elec((unsigned char)0,sl); if(activerange) //count electrons in active orbitals for each determinant for(lexindex i=0; i0 && imo>=(*activerange)(0,0) && imo<=(*activerange)(0,1) || imo<0 && imo>=(*activerange)(1,0) && imo<=(*activerange)(1,1)) ++n_act_elec[i]; } } for(lexindex i=0; i notocc_i(2*(mo+ncore)+1); //is in principle a bitvector but the "unpacked form" should be more efficient for(int o=0; o<2*(mo+ncore)+1; ++o) notocc_i[o]=1; for(int e=0; etruncation) goto skipthis ; //replaced by more optimized code int include_it = truncation; int activediff = (int)n_act_elec[j] - (int)n_act_elec[i]; spinorbindex *sj = slaters[j]; if(abs(activediff) > truncation) goto skipthis; if(activediff>0) include_it -= activediff; //account for electrons excited into active orbitals if(include_it<0) goto skipthis; for(int e=0; emaxlen) maxlen=ntot; if(sizeof(lexindex)!=write(excitlistfile,&ntot,sizeof(lexindex))) laerror("write error"); if((lexindex)ntot*sizeof(lexindex)!=(lexindex)write(excitlistfile,&allowedlist[0],ntot*sizeof(lexindex))) laerror("write error"); } lseek(excitlistfile,0,SEEK_SET); if(sizeof(lexindex)!=write(excitlistfile,&maxlen,sizeof(lexindex))) laerror("write error"); cout <<"make_excitlist cpu time "<<(1.*clock()-t0)/CLOCKS_PER_SEC< slperm; if(permuteslvectors) { lseek(slaterpermfile,0,SEEK_SET); slperm.get(slaterpermfile,true); if(sl!= (lexindex)slperm.size()) laerror("inconsistent slaterpermfile"); } SparseMat Ssl(sl,sl); unsigned long skipcount=0; unsigned long computedcount=0; clock_t t0=clock(); if(truncation>=0) lseek(excitlistfile,0,SEEK_SET); lexindex maxlen=0; if(truncation>=0) { if(sizeof(lexindex)!=read(excitlistfile,&maxlen,sizeof(lexindex))) laerror("excitlist read error 1"); if(maxlen==0) laerror("unfinished excitlistfile encountered"); } else maxlen=1; NRVec excitlist(maxlen); cout<<"Number of determinants in the wavefunctions = "< percent) { percent = (i*100)/sl; cout<<" "<=0) { if(sizeof(lexindex)!=read(excitlistfile,&ntot,sizeof(lexindex))) laerror("excitlist read error 2"); if(ntot*sizeof(lexindex)!=(lexindex)read(excitlistfile,&excitlist[0],ntot*sizeof(lexindex))) laerror("excitlist read error 3"); } for(lexindex jj= (truncation>=0? 0 : i) ; jj<(truncation>=0? ntot :sl); ++jj) { lexindex jjx; jjx = truncation>=0 ? excitlist[jj] : jj; #ifdef DEBUG cout<< "Processing its peer "<Ssltest(Ssl); /* for(lexindex i=0; i.01) cout <<"Ssl "< CIoverlap( bool uhf, const NRMat &bras, //CIsize x n const NRMat &kets, //CIsize x m const NRMat &Sraw, //2*AO x 2*AO (generated by artificial doubled geometry input) const NRMat (&braLCAO)[2], //AO x MO const NRMat (&ketLCAO)[2], //AO x MO const drt &d, int slaterfile, //file descriptor for slater basis int citrfile, //file descriptor for CItrafo matrix int excitlistfile, //file descriptor for list of not neglected excitations const int ncore=0, const int ndiscarded=0, bool generate_trafo=true, bool make_excitlist=true, const int truncation=4, //neglect overlap of Slater dets differing in more than ... spinorbitals (take into account arbitrary MO swapping) const bool inversedorbitals=true, //lowest MOs are at the top of DRT when true const bool inverselex=false, const int slaterorder=1, REAL screeningthr=0, NRMat *activerange=NULL, int inactive=0, NRMat *screening_mask = NULL, bool SMO_only=false, int method=0 ) { //generate and save, or read from files Slater basis and transformation matrix //this computation can be done only once and remains constant lexindex ci=d.cisize(); NRMat brasl, ketsl; if(!SMO_only) //with -S only the MO overlaps are computed in CIoverlap_slater { SparseMat citrafo; if(generate_trafo) { citrafo=CItrafo(slaterfile,d,slaterorder,inverselex); citrafo.put(citrfile,true); } else { lseek(citrfile,0,SEEK_SET); citrafo.get(citrfile,true); if((lexindex)citrafo.ncols()!=ci) laerror("inconsistent dimension of citrafo"); } //transform CI vectors to the Slater basis brasl=citrafo*bras; ketsl=citrafo*kets; citrafo.resize(0,0); //free memory } return CIoverlap_slater(uhf,brasl,ketsl,Sraw,braLCAO,ketLCAO,slaterfile,excitlistfile,d.electrons(),d.orbnum(),ncore,ndiscarded,make_excitlist,truncation,inversedorbitals,slaterorder,false,-1,screeningthr,activerange,inactive,screening_mask,SMO_only,method); } //defaults of the option -C: largest deviations from orthonormality of the MOs and of the CI vectors accepted by the check of the input //accurate inputs give below 1e-8; the AO overlap with 5 decimals (Turbomole >= 7.5 print) gives 1e-3..5e-2 and exchanged halves of the //doubled molecule (Columbus interface) 4e-2..6e-2, both stop the program with these defaults #ifndef CHECK_MOTHRESHOLD #define CHECK_MOTHRESHOLD 1e-6 #endif #ifndef CHECK_CITHRESHOLD #define CHECK_CITHRESHOLD 1e-6 #endif //largest element (in the absolute value) of C^T S C - 1 for the AO overlap S and the MO coefficients in the columns of C static REAL nonorthonormality(const NRMat &S, const NRMat &C) { NRMat x=C.transpose()*(S*C); for(int i=0; i &bras, const NRMat &kets, const NRMat &Sraw, const NRMat (&braLCAO)[2], const NRMat (&ketLCAO)[2]) { const int ao=braLCAO[0].nrows(); if(Sraw.nrows()!=2*ao || Sraw.ncols()!=2*ao) laerror("-C: the dimensions of the AO overlap and of the MO coefficients are inconsistent"); const NRMat S11=Sraw.submatrix(0,ao-1,0,ao-1); const NRMat S22=Sraw.submatrix(ao,2*ao-1,ao,2*ao-1); cout.setf(ios::scientific,ios::floatfield); const streamsize precision=cout.precision(1); cout <<"Check of the input (-C), largest deviations from orthonormality:"<0) for(int spin=0; spin<(uhf?2:1); ++spin) { const REAL b=nonorthonormality(S11,braLCAO[spin]); const REAL k=nonorthonormality(S22,ketLCAO[spin]); cout <<"bra "<<(uhf?(spin?"beta ":"alpha "):"")<<"MOs in the first half of the AO overlap "<0 && bras.nrows() && kets.nrows()) { NRMat x=bras.transpose()*bras; for(int i=0; i docigugaoverlap(bool uhf, REAL screeningthr, int excitrank, NRMat *activerange=NULL,int inactive=0, char *screening_mask_file=NULL,bool SMO_only=false,int method=0,REAL checkmo=0,REAL checkci=0) { NRVec gelfbasis; gelfpat g; cin >>g; paldustab paldus(g); int n=g.nrows(); drt mydrt(paldus[n]); cout <>nbas >>ncore >>ndisc; if(nbas!=n) laerror("inconsistent CIoverlap input"); NRMat bras,kets; int f; int slaterfile,citrfile,excitlistfile; if(!SMO_only) { slaterfile=open("slaterfile",O_CREAT|O_RDWR|O_LARGEFILE,0777); if(slaterfile<0) {perror("cannot open slaterfile");laerror("IO error");} citrfile=open("citrfile",O_CREAT|O_RDWR|O_LARGEFILE,0777); if(citrfile<0) {perror("cannot open");laerror("IO error");} excitlistfile=open("excitlistfile",O_CREAT|O_RDWR|O_LARGEFILE,0777); if(excitlistfile<0) {perror("cannot open excitlistfile");laerror("IO error");} f=open("eivectors1",O_RDONLY|O_LARGEFILE); if(f<0) {perror("cannot open");laerror("IO error");} bras.get(f,true,true); close(f); f=open("eivectors2",O_RDONLY|O_LARGEFILE); if(f<0) {perror("cannot open");laerror("IO error");} kets.get(f,true,true); close(f); } NRMat *screening_mask=NULL; if(!SMO_only) screening_mask = read_screening_mask(screening_mask_file,bras.ncols(), kets.ncols()); NRMat Sraw; //this is in AO basis cin >>Sraw; NRMat braLCAO[2],ketLCAO[2]; cin >> braLCAO[0]; if(uhf) cin >> braLCAO[1]; else braLCAO[1] = braLCAO[0]; cin >> ketLCAO[0]; if(uhf) cin >> ketLCAO[1]; else ketLCAO[1] = ketLCAO[0]; if(checkmo>0||checkci>0) checkinput(checkmo,checkci,uhf,bras,kets,Sraw,braLCAO,ketLCAO); NRMat SCI = CIoverlap(uhf, bras, kets, Sraw, braLCAO, ketLCAO, mydrt, slaterfile, citrfile, excitlistfile, ncore, ndisc, true, true, excitrank,inverseorb,inverselex,slaterorder,screeningthr,activerange,inactive,screening_mask,SMO_only,method); close(slaterfile); close(excitlistfile); close(citrfile); return SCI; } NRMat docislateroverlap(bool uhf, REAL screeningthr, int excitrank,NRMat *activerange=NULL,int inactive=0, char *screening_mask_file=NULL, bool SMO_only=false, int method=0, REAL checkmo=0, REAL checkci=0) { //NOTE: ncore are only such core orbitals which are not included in slaterfile //NOTE: slaterfile numbering is expected to start from ncore+1 //NOTE inactive orbitals by -i option are NOT counted as core here, they are only approximation to make computation faster //NOTE: discarded orbitals have to be included so that all dimensions fit //NOTE: nelec should NOT include the 2*ncore frozen electrons // int nbas,ncore,ndisc,nactive,nelec; cin >>nbas >>ncore >>ndisc >>nelec; //NOTE: nelec here does not have to distinguish alpha and beta nactive=nbas-ncore-ndisc; cout << "Number of frozen core orbitals (not in slaterfile) = "< bras,kets; int f; if(!SMO_only) { slaterfile=open("slaterfile",O_RDWR|O_LARGEFILE,0777); if(slaterfile<0) {perror("cannot open slaterfile");laerror("IO error");} excitlistfile=open("excitlistfile",O_CREAT|O_LARGEFILE|O_RDWR,0777); if(excitlistfile<0) {perror("cannot open excitlistfile");laerror("IO error");} slaterpermfile=open("slaterpermfile",O_CREAT|O_RDWR|O_LARGEFILE,0777); if(slaterpermfile<0) {perror("cannot open slaterpermfile");laerror("IO error");} f=open("eivectors1",O_RDONLY|O_LARGEFILE); if(f<0) {perror("cannot open eivectors1");laerror("IO error");} bras.get(f,true,true); close(f); f=open("eivectors2",O_RDONLY|O_LARGEFILE); if(f<0) {perror("cannot open eivectors2");laerror("IO error");} kets.get(f,true,true); close(f); } #ifdef DEBUG cout <<"test eivectors1 (bras) "<0.1) cout <<"det "<0.1) cout <<"det "< *screening_mask = read_screening_mask(screening_mask_file,bras.ncols(), kets.ncols()); if(!SMO_only) { cout <<"Coefficient-overlap bra-ket:\n"; cout << bras.transpose() * kets; } NRMat Sraw; cin >>Sraw; NRMat braLCAO[2],ketLCAO[2]; cin >> braLCAO[0]; if(uhf) cin >> braLCAO[1]; else braLCAO[1] = braLCAO[0]; cin >> ketLCAO[0]; if(uhf) cin >> ketLCAO[1]; else ketLCAO[1] = ketLCAO[0]; if(checkmo>0||checkci>0) checkinput(checkmo,checkci,uhf,bras,kets,Sraw,braLCAO,ketLCAO); bool make_excitlist=true; if(SMO_only||method) make_excitlist=false; else { struct stat64 buf; if(fstat64(excitlistfile,&buf)) laerror("cannot stat excitlistfile"); if(buf.st_size>0) make_excitlist=false; } NRMat SCI = CIoverlap_slater(uhf, bras, kets, Sraw, braLCAO, ketLCAO, slaterfile, excitlistfile, nelec, nactive, ncore, ndisc, make_excitlist, excitrank,inverseorb,slaterorder,false /*we do not need lexical order now*/,slaterpermfile,screeningthr,activerange,inactive,screening_mask,SMO_only,method); close(slaterfile); close(slaterpermfile); close(excitlistfile); return SCI; } int main(int argc, char **argv) { //without the synchronization with C stdio the long formatted input of the matrices from cin is several times faster //(stdio locks at every character as soon as the threads of the BLAS exist); no C stdio is used on stdin and stdout here ios::sync_with_stdio(false); sigtraceback(SIGSEGV,1); sigtraceback(SIGABRT,1); sigtraceback(SIGBUS,1); sigtraceback(SIGFPE,1); clock_t clock0 = clock(); cout.setf(ios::fixed); //cout.setf(ios::scientific); cout.precision(12); print_version(argc,argv,cout); bool SMO_only=false; bool uhf=0; char *screening_mask_file=NULL; bool alignrows=0; bool useoldphase=0; bool nooldphase=0; //-o overrides -a and -b in any order bool aligncolumns=0; REAL oldphasediff_threshold = 0.02; REAL screeningthr=0.; int excitrank=3; int inactive=0; NRMat *activerange=NULL; bool computenormalized = false; bool computelog = false; int method=2; REAL checkmo=CHECK_MOTHRESHOLD; REAL checkci=CHECK_CITHRESHOLD; //options can be given in any order: repeat until no option is recognized for(char **argv0=NULL; argv0!=argv;) { argv0=argv; if(argc>1 && !strcmp(argv[1],"-S")) { SMO_only=true; argc -=1; argv+=1; } if(argc>1 && !strcmp(argv[1],"-U")) { uhf=1; if(activerange) laerror("-U has to be given before -A, which reads 4 numbers with -U and 2 without"); argc -=1; argv+=1; } if(argc>2 && !strcmp(argv[1],"-s")) { screening_mask_file=strdup(argv[2]); argc -=2; argv+=2; } if(argc>1 && !strcmp(argv[1],"-a")) { alignrows=1; useoldphase=1; --argc; ++argv; } if(argc>1 && !strcmp(argv[1],"-b")) { aligncolumns=1; useoldphase=1; --argc; ++argv; } if(argc>1 && !strcmp(argv[1],"-o")) { nooldphase=1; --argc; ++argv; } if(argc>2 && !strcmp(argv[1],"-T")) { sscanf(argv[2],"%lf",&oldphasediff_threshold); argc -=2; argv+=2; } if(argc>2 && !strcmp(argv[1],"-t")) { sscanf(argv[2],"%lf",&screeningthr); argc -=2; argv+=2; } if(argc>2 && !strcmp(argv[1],"-e")) { sscanf(argv[2],"%d",&excitrank); argc -=2; argv+=2; } if(argc>2 && !strcmp(argv[1],"-i")) { sscanf(argv[2],"%d",&inactive); argc -=2; argv+=2; } if(argc>(uhf?5:3) && !strcmp(argv[1],"-A")) { activerange = new NRMat(2,2); if(uhf) { sscanf(argv[2],"%d",&(*activerange)(0,0)); sscanf(argv[3],"%d",&(*activerange)(0,1)); sscanf(argv[4],"%d",&(*activerange)(1,0)); sscanf(argv[5],"%d",&(*activerange)(1,1)); argc -=5; argv+=5; } else { sscanf(argv[2],"%d",&(*activerange)(0,0)); sscanf(argv[3],"%d",&(*activerange)(0,1)); (*activerange)(1,0)= -(*activerange)(0,1); (*activerange)(1,1)= -(*activerange)(0,0); argc -=3; argv+=3; } } if(argc>1 && !strcmp(argv[1],"-N")) { computenormalized = true; --argc; ++argv; } if(argc>1 && !strcmp(argv[1],"-L")) { computelog = true; --argc; ++argv; } if(argc>2 && !strcmp(argv[1],"-m")) { sscanf(argv[2],"%d",&method); argc -=2; argv+=2; } if(argc>3 && !strcmp(argv[1],"-C")) { sscanf(argv[2],"%lf",&checkmo); sscanf(argv[3],"%lf",&checkci); argc -=3; argv+=3; } if(argc>1 && !strcmp(argv[1],"-h")) { cout <<"Usage: cioverlap [options] [type] 1) sscanf(argv[1],"%d",&type); NRMat SCI; if(type) SCI = docigugaoverlap(uhf,screeningthr,excitrank,activerange,inactive,screening_mask_file,SMO_only,method,checkmo,checkci); else SCI = docislateroverlap(uhf,screeningthr,excitrank,activerange,inactive,screening_mask_file,SMO_only,method,checkmo,checkci); cout << "CI overlap before alignment\n"; cout << SCI; //find maximum overlap , make it positive; store the resulting phases, use previous phases SCI.copyonwrite(); if(aligncolumns) SCI.transposeme(); //new approach for tracing the phases using a generalized permutation matrix NRMat phasetrace(SCI.nrows(),SCI.nrows()); phasetrace.clear(); for(int i=0; i maxoverlap) { maxoverlapindex=j; maxoverlap=abs(SCI(i,j)); } phasetrace(i,maxoverlapindex) = SCI(i,maxoverlapindex)<0 ? -1 : 1; } cout <<"Phase trace matrix\n"< phases,oldphases; phases.resize(SCI.nrows()); oldphases.resize(SCI.nrows()); //default init old phases for(int j=0; j=0) { oldphases.get(f,true,false); close(f); cout <<"Old phases:\n"< SCI2(SCI); SCI2.copyonwrite(); { NRVec oldphasediff; NRVec oldphasepair; int f=open("phasediff",O_RDONLY); if(f>=0) { oldphasediff.get(f,true); oldphasepair.get(f,true); close(f); //delete phasediff file after the overlap of critical states falls below threshold if(fabs(SCI(oldphasepair[0],oldphasepair[1]))+fabs(SCI(oldphasepair[1],oldphasepair[0])) < 2.*oldphasediff_threshold) unlink("phasediff"); cout <<"Old phase diff:\n"< diagonalphases; diagonalphases.resize(SCI2.nrows()); for(int i=0; i phasepair(2); bool storephasediff=false; for(int i=0; i maxoverlap) { maxoverlapindex=j; maxoverlap=abs(SCI(i,j)); } if(i!=maxoverlapindex) { phasepair[0]=i; phasepair[1]=maxoverlapindex; cout <<"Note: state character exchanged, phase based on off-diagonal overlap: "< "< phasediff(diagonalphases.size()); for(int i=0; i phases2 = phasetrace * oldphases; if((phases2-phases).norm()>1e-12) cout <<"Warning: new and old phase alignment does not match\n"; } if(aligncolumns) SCI.transposeme(); cout << "CPU time "<< (clock()-clock0)/CLOCKS_PER_SEC< SS(SCI.transpose()*SCI); NRMat SCInorm = SCI * sqrtinv(SS); cout << "Orthonormalized CI overlap matrix\n"; cout << SCInorm; } if(computelog) { if(!alignrows && !aligncolumns) cout<<"Warning: without phase alignment the overlap may not be positive definite and log() might fail\n"; NRMat SCIlog = log(SCI); cout << "Logarithm of the CI overlap matrix\n"; cout << SCIlog; } }