def get_input(t21file): import kf f = kf.kffile(t21file) inp = f.read('General', 'Input').tolist() #print inp d_sections = ['units', 'atoms', 'fragments', 'qmmm'] d_keys = [] do = True newinp = [] for line in inp: if not line.split(): continue if not do: if 'end' == line.lower().split()[0]: do = True continue if line.lower().split()[0] in d_sections: do = False continue if line.lower().split()[0] in d_keys: continue newinp.append(line) #print newinp return newinp
def before_run(self): import kf adfimportgridjob.before_run(self) f = kf.kffile('refdens.t41') if self._refdens.nspin == 2: self._refdens.grid.write_grid_to_t41(f) values = self._refdens['alpha'].get_values() f.writereals('SCF', 'Density_A', values.reshape((values.size, ), order='Fortran')) values = self._refdens['beta'].get_values() f.writereals('SCF', 'Density_B', values.reshape((values.size, ), order='Fortran')) else: self._refdens.grid.write_grid_to_t41(f) values = self._refdens.get_values() f.writereals('SCF', 'Density', values.reshape((values.size, ), order='Fortran')) f.close() if self._startpot is not None: f = kf.kffile('startpot.t41') self._startpot.grid.write_grid_to_t41(f) if self._refdens.nspin == 2: if self._startpot.nspin == 2: values = self._startpot['alpha'].get_values() f.writereals( 'Potential', 'Total_A', values.reshape((values.size, ), order='Fortran')) values = self._startpot['beta'].get_values() f.writereals( 'Potential', 'Total_B', values.reshape((values.size, ), order='Fortran')) else: values = self._startpot.get_values() f.writereals( 'Potential', 'Total_A', values.reshape((values.size, ), order='Fortran')) f.writereals( 'Potential', 'Total_B', values.reshape((values.size, ), order='Fortran')) else: values = self._startpot.get_values() f.writereals('Potential', 'Total', values.reshape((values.size, ), order='Fortran')) f.close()
def get_tape41(self, filename, section, variable): import kf f = kf.kffile(filename) self.grid.write_grid_to_t41(f) f.writereals(section, variable, self.values) f.close()
def GetCPTypes(T21FileName): TypeList = [] T21 = kf.kffile(T21FileName) Types = T21.stringData("Properties","CP code number for (Rank,Signatu") Types = Types.split('\n') Types = Types[3:len(Types)-1] for i in Types: for j in i.split(): TypeList.append(int(float(j))) T21.close() return TypeList
def before_run(self): import kf adfimportgridjob.before_run(self) f = kf.kffile('embpot.t41') self._embpot.grid.write_grid_to_t41(f) if self._embpot.nspin == 2: raise PyAdfError("IMPORTEMBPOT not implemented for nspin=2") else: values = self._embpot.get_values() f.writereals('Potential', 'EmbeddingPot', values.reshape((values.size, ), order='Fortran')) f.close()
def GetDataFromT41(T41FileName): T41Data = {} T41VarStrs = ['Density'] for i in ['X','Y','Z']: T41VarStrs.append('DensityGrad' + i) for i in ['XX','XY','XZ','YY','YZ','ZZ']: T41VarStrs.append('DensityHess' + i) T41 = kf.kffile(T41FileName) for i in T41VarStrs: T41Data[i] = T41.read('SCF', i) T41.close() T41.delete() return T41Data
def GetAtomInfo(T21FileName): global AtomInfoList T21 = kf.kffile(T21FileName) NumAtoms = len(T21.read("Properties","Bader atomic charges")) for InfoType in AtomInfoList: if InfoType['collect']: tmp = T21.read("Properties",InfoType['kf_name']) InfoType['data'] = [] for i in range(NumAtoms): InfoType['data'].append([]) for j in range(i, NumAtoms * len(InfoType['name']), NumAtoms): InfoType['data'][i].append(tmp[j]) T21.close() return
def GetCPCoords(T21FileName): T21 = kf.kffile(T21FileName) FullList = T21.read("Properties", "CP coordinates") NumCPs = T21.read("Properties","CP number of") T21.close() CoordList = [] for i in range(NumCPs): tmp = np.empty([3]) k = 0 for j in range(i,NumCPs * 3,NumCPs): tmp[k] = FullList[j] k += 1 CoordList.append(tmp) return CoordList
def write_tape10(cls, grid, filename='TAPE10'): """ Write a TAPE10 file containing the gridpoints. """ f = kf.kffile(filename) lblock = 128 if grid.npoints % lblock == 0: dummypoints = 0 else: dummypoints = lblock - (grid.npoints % lblock) npoints_total = grid.npoints + dummypoints nblock = npoints_total / lblock f.writeints('General', 'nspin', 1) f.writeints("Points", "nblock", nblock) f.writeints("Points", "lblock", lblock) f.writeints("Points", "nmax", npoints_total) f.writeints("Points", "Equivalent Blocks", 1) f.writeints("Points", "Length of Blocks", [lblock] * nblock) data = numpy.zeros((npoints_total, 4)) data[:grid.npoints, :3] = grid.get_coordinates(bohr=True) data[:grid.npoints, 3] = grid.get_weights() outdata = numpy.zeros((nblock, lblock * 4)) for iblock in range(nblock): ipoint = lblock * iblock # get one block of points block = data[ipoint:ipoint + lblock, :] # points have to be written in Fortran ordering ! block = block.flatten(True) outdata[iblock, :] = block outdata = outdata.flatten() f.writereals('Points', 'Data', outdata) f.close()
def GetCPEigVals(T21FileName): from numpy import linalg as la T21 = kf.kffile(T21FileName) Hess = T21.read("Properties", "CP density Hessian at") NumCPs = T21.read("Properties","CP number of") T21.close() EigValList = [] for i in range(NumCPs): tmp = np.empty([6]) k = 0 for j in range(i, NumCPs * 6, NumCPs): tmp[k] = Hess[j] k += 1 EVal, tmp1 = la.eigh(GetFullHess(tmp)) EigValList.append(EVal) return EigValList
def get_geometry(t21file): import kf f = kf.kffile(t21file) geom = f.read('Geometry', 'xyz InputOrder').tolist() atomtype = f.read('Geometry', 'atomtype').tolist() atomindex = f.read('Geometry', 'fragment and atomtype index').tolist() atomorder = f.read('Geometry', 'atom order index').tolist() natom = int(f.read('Geometry', 'nr of atoms')) NAO = int(f.read('Basis', 'naos')) geometry = [] for iatom in range(natom): index = atomorder[iatom] - 1 atype = atomindex[natom + index] - 1 el = atomtype[atype].strip() geometry.append([ el, geom[3 * iatom + 0], geom[3 * iatom + 1], geom[3 * iatom + 2] ]) return geometry, NAO
def get_smat(filename): import kf f = kf.kffile(filename) NAO = f.read('Basis', 'naos') Smat = f.read('Matrices', 'Smat') f.close() # Smat is lower triangular matrix, len is NAO*(NAO+1)/2 ao_ovl = makermatrix(NAO, NAO) x = 0 y = 0 for el in Smat: ao_ovl[x][y] = el ao_ovl[y][x] = el x += 1 if x > y: x = 0 y += 1 return NAO, ao_ovl
def GetCPInfo(T21FileName): from numpy import linalg as la global CPInfoList, CPEigVals, CPEigVecs T21 = kf.kffile(T21FileName) NumCPs = T21.read("Properties","CP number of") for i in [CPEigVals,CPEigVecs]: if i['collect']: i['data'] = [] for InfoType in CPInfoList: if InfoType['collect']: tmp = T21.read("Properties",InfoType['kf_name']) InfoType['data'] = [] for i in range(NumCPs): InfoType['data'].append([]) for j in range(i, NumCPs * len(InfoType['name']), NumCPs): InfoType['data'][i].append(tmp[j]) if 'Hessian' in InfoType['kf_name']: EVal, EVec = la.eigh(GetFullHess(InfoType['data'][i])) CPEigVals['data'].append(EVal) CPEigVecs['data'].append([EVec[y,x] for x in range(3) for y in range(3)]) T21.close() return
def get_result_from_tape(self, section, variable, tape=21, always_array=False): """ Get a specific variable from a tape. @param section: the section on tape to be read @type section: str @param variable: the variable on tape to be read @type variable: str @param tape: the number of the tape to use, default is 21 @type tape: int @param always_array: always return a numpy array, even if these have only one element @type always_array: bool @returns: the contents of the variable as read. @rtype: depends on the variable to be read """ f = kf.kffile(self.get_tape_filename(tape)) result = f.read(section, variable) f.close() if result is None: raise PyAdfError("Variable " + section + "%" + variable + " not found in tape file") if (not always_array) and (len(result) == 1): result = result[0] return result
def get_dets_from_tape21(filename, mults, wfthres, nfrozen): print '%-40s' % ' importing ...', datetime.datetime.now() - starttime # get all info from TAPE21 import kf f = kf.kffile(filename) nspin = int(f.read('ActiveFrag', 'nspin')) if nspin == 1: restr = True else: restr = False print '%-40s' % ' getting general info ...', datetime.datetime.now( ) - starttime # get general infos if restr: if 1 in mults: extrmults = ['S', 'T'] else: extrmults = ['T'] gsmult = 1 else: extrmults = ['S'] #get gsmult occ_A = f.read('A', 'froc_A').tolist() occ_B = f.read('A', 'froc_B').tolist() nA = sum(occ_A) nB = sum(occ_B) ndiff = int(nA - nB) gsmult = ndiff + 1 nstates_to_extract = [0 for i in range(max(mults))] if not restr or 1 in mults: n = int(f.read('Excitations SS A', 'nr of excenergies')) nstates_to_extract[gsmult - 1] = n if restr and 3 in mults: n = int(f.read('Excitations ST A', 'nr of excenergies')) if n: nstates_to_extract[2] = n inp = f.read('General', 'Input') tda = False for line in inp: if 'tda' in line.lower(): tda = True lhybrid = f.read('General', 'lhybrid')[0] occ_A = f.read('A', 'froc_A').tolist() occ_A = [int(i) for i in occ_A] if restr: nocc_A = sum(occ_A) / 2 nvir_A = len(occ_A) - nocc_A else: nocc_A = sum(occ_A) nvir_A = len(occ_A) - nocc_A NMO_B = int(f.read('A', 'nmo_B')) occ_B = f.read('A', 'froc_B').tolist() occ_B = [int(i) for i in occ_B] nocc_B = sum(occ_B) nvir_B = len(occ_B) - nocc_B # make step vectors (0:empty, 1:alpha, 2:beta, 3:docc) if restr: m = {0: 0, 2: 3} occ_A = [m[i] for i in occ_A] else: m = {0: 0, 1: 2} occ_B = [m[i] for i in occ_B] occ_A = tuple(occ_A) if not restr: occ_B = tuple(occ_B) #print occ_A #print nocc_A,nvir_A #if not restr: #print occ_B #print nocc_B,nvir_B print '%-40s' % ' processing eigenvectors ...', datetime.datetime.now( ) - starttime # get eigenvectors eigenvectors = {} for imult, mult in enumerate(mults): print '%-40s' % (' Multiplicity: %i' % (mult)), datetime.datetime.now() - starttime eigenvectors[mult] = [] if mult == gsmult: # add ground state if restr: key = tuple(occ_A[nfrozen:]) else: key = tuple(occ_A[nfrozen:] + occ_B[nfrozen:]) eigenvectors[mult].append({key: 1.0}) for istate in range(nstates_to_extract[mult - 1]): print '%-40s' % (' State: %i' % (istate + 1)), datetime.datetime.now() - starttime print '%-40s' % ' Reading ...', datetime.datetime.now( ) - starttime section = 'Excitations S%s A' % extrmults[imult] key = 'eigenvector %i' % (istate + 1) try: eig = f.read(section, key).tolist() except AttributeError: print 'No eigenvectors found in file %s!' % (filename) sys.exit(11) if lhybrid and not tda: key = 'left eigenvector %i' % (istate + 1) eigl = f.read(section, key).tolist() for i in range(len(eig)): eig[i] = (eig[i] + eigl[i]) / 2. # make dictionary print '%-40s' % ' Converting ...', datetime.datetime.now( ) - starttime dets = {} if restr: for iocc in range(nocc_A): for ivirt in range(nvir_A): index = iocc * nvir_A + ivirt dets[(iocc, ivirt, 1)] = eig[index] else: for iocc in range(nocc_A): for ivirt in range(nvir_A): index = iocc * nvir_A + ivirt dets[(iocc, ivirt, 1)] = eig[index] # beta excitation for iocc in range(nocc_B): for ivirt in range(nvir_B): index = iocc * nvir_B + ivirt + max( nvir_A, nvir_B) * max(nocc_A, nocc_B) dets[(iocc, ivirt, 2)] = eig[index] # truncate vector print '%-40s' % ' Truncating vector ...', datetime.datetime.now( ) - starttime norm = 0. for k in sorted(dets, key=lambda x: dets[x]**2, reverse=True): if norm > wfthres: del dets[k] continue norm += dets[k]**2 # create strings print '%-40s' % ' Making determinants ...', datetime.datetime.now( ) - starttime dets2 = {} if restr: for iocc, ivirt, dummy in dets: if mult == 1: # alpha excitation key = list(occ_A) key[iocc] = 2 key[nocc_A + ivirt] = 1 dets2[tuple(key)] = dets[(iocc, ivirt, dummy)] / math.sqrt(2.) # beta excitation key[iocc] = 1 key[nocc_A + ivirt] = 2 dets2[tuple(key)] = dets[(iocc, ivirt, dummy)] / math.sqrt(2.) elif mult == 3: key = list(occ_A) key[iocc] = 1 key[nocc_A + ivirt] = 1 dets2[tuple(key)] = dets[(iocc, ivirt, dummy)] else: for iocc, ivirt, dummy in dets: if dummy == 1: key = list(occ_A + occ_B) key[iocc] = 0 key[nocc_A + ivirt] = 1 dets2[tuple(key)] = dets[(iocc, ivirt, dummy)] elif dummy == 2: key = list(occ_A + occ_B) key[nocc_A + nvir_A + iocc] = 0 key[nocc_A + nvir_A + nocc_B + ivirt] = 2 dets2[tuple(key)] = dets[(iocc, ivirt, dummy)] # remove frozen core print '%-40s' % ' Removing frozen core ...', datetime.datetime.now( ) - starttime dets3 = {} for key in dets2: problem = False if restr: if any([key[i] != 3 for i in range(nfrozen)]): problem = True else: if any([key[i] != 1 for i in range(nfrozen)]): problem = True if any([ key[i] != 2 for i in range(nocc_A + nvir_A, nocc_A + nvir_A + nfrozen) ]): problem = True if problem: print 'WARNING: Non-occupied orbital inside frozen core!' continue if restr: key2 = key[nfrozen:] else: key2 = key[nfrozen:nocc_A + nvir_A] + key[nocc_A + nvir_A + nfrozen:] dets3[key2] = dets2[key] # append eigenvectors[mult].append(dets3) print '%-40s' % ' formatting eigenvectors ...', datetime.datetime.now( ) - starttime strings = {} for imult, mult in enumerate(mults): filename = os.path.join('dets.%i' % mult) strings[filename] = format_ci_vectors(eigenvectors[mult]) return strings
f.write(line) elif isinstance(content, str): f.write(content) else: print 'Content %s cannot be written to file!' % (content) f.close() except IOError: print 'Could not write to file %s!' % (filename) sys.exit(13) # ======================================================================= # filename = 'TAPE15' filename = sys.argv[1] file1 = kf.kffile(filename) NAO = int(file1.read('Basis', 'naos')) Smat = file1.read("Matrices", "Smat") npart_a = file1.read("A", "npart") npart = npart_a.tolist() Full_Smat = [[0. for i in range(NAO)] for j in range(NAO)] x = 0 y = 0 for el in Smat: x1 = npart.index(x + 1) y1 = npart.index(y + 1) Full_Smat[x1][y1] = el Full_Smat[y1][x1] = el x += 1 if x > y:
def main(): import ast import os import sys import subprocess global T21BaseName, ScriptDir, CurrentDir, CPInfoList, AtomInfoList # InputFilePath = "C:\\Users\\Haiiro\\Dropbox\\EclipseWin\\Python\\CPGobbler\\input.txt" # InputFilePath = "/Users/Haiiro/Safe/CP_Gobbler/input.txt" InputFilePath = "/Users/Haiiro/ADFdata/input.txt" if len(sys.argv) > 1: InputFilePath = sys.argv[1] InputFile = open(InputFilePath, 'r') InputFileContents = InputFile.readlines() InputFile.close() ScriptDir = os.path.dirname(os.path.realpath(__file__)) InputDir = os.path.dirname(os.path.realpath(InputFilePath)) FileNum = 0 CurrentDir = os.path.dirname(InputFilePath) OutBRCCSVName = CurrentDir + SubDir + "/CPs.csv" OutNCSVName = CurrentDir + SubDir + "/BaderAtoms.csv" if IsWindows: subprocess.Popen('mkdir "' + CurrentDir + SubDir + '"', shell=True, stdout=subprocess.PIPE).stdout.read() else: subprocess.Popen('mkdir -p "' + CurrentDir + SubDir + '"', shell=True, stdout=subprocess.PIPE).stdout.read() BRCHeaders = "Filename,InCP#,CP#,CP Rank,CP Type," NHeaders = "Filename,InCP#,CP#,x,y,z," FirstCP = True FirstBaderAtom = True for aLine in InputFileContents: FileNum += 1 if len(aLine) > 0 and aLine[0] == '#': continue print "Running file " + str(FileNum) + " of " + str(len(InputFileContents)) aLine = aLine.split('\t') if len(aLine) > 1: InputT21FileName = aLine[0] TargetCPs = ast.literal_eval(aLine[1]) AllCPs = (TargetCPs[0] < 0) if AllCPs: print "Getting all CP information" T21BaseName = os.path.basename(InputT21FileName) CurrentDir = os.path.dirname(InputT21FileName) if not os.path.exists(CurrentDir): if IsWindows: InputT21FileName = InputDir + '\\' + T21BaseName else: InputT21FileName = InputDir + '/' + T21BaseName if '?' in InputT21FileName or '*' in InputT21FileName: if IsWindows: T21FileNames = subprocess.Popen("dir /b " + InputT21FileName, shell=True, stdout=subprocess.PIPE).stdout.read() else: T21FileNames = subprocess.Popen('ls ' + InputT21FileName, shell=True, stdout=subprocess.PIPE).stdout.read() T21FileNames = T21FileNames.split('\n') else: T21FileNames = [InputT21FileName] OrigCPCoords = [] OrigCPTypes = [] for T21FileName in T21FileNames: if len(T21FileName) > 2: if IsWindows: T21FileName = (CurrentDir + '\\' + T21FileName).replace('\r','') if os.path.exists(T21FileName): T21BaseName = os.path.basename(T21FileName) if '.' in T21BaseName: T21BaseName = T21BaseName.rpartition('.')[0] print "Full file path: %s" % T21FileName T21 = kf.kffile(T21FileName) RunType = T21.stringData("General", "runtype") print "Run type: %s" % RunType ExitStatus = T21.stringData("General", "termination status") if not 'NORMAL TERMINATION' in ExitStatus: print "T21 file reports abnormal termination: %s. skipping..." % ExitStatus continue NumCPs = T21.read("Properties", "CP number of") if NumCPs is None or NumCPs <= 0: print "No CPs found, skipping..." continue T21.close() GetCPInfo(T21FileName) GetAtomInfo(T21FileName) CPCoords = GetCPCoords(T21FileName) CPTypes = GetCPTypes(T21FileName) # CPEigVals = GetCPEigVals(T21FileName) T21 = kf.kffile(T21FileName) # CPDens = T21.read("Properties", "CP density at") # BaderCharges = T21.read("Properties", "Bader atomic charges") if AllCPs: NumCPs = T21.read("Properties", "CP number of") TargetCPs = [i+1 for i in range(NumCPs)] AtomOrderIndex = T21.read("Geometry","atom order index") NumAtoms = len(AtomOrderIndex) / 2 T21.close() if len(OrigCPCoords) == 0: OrigCPCoords = CPCoords if len(OrigCPTypes) == 0: OrigCPTypes = CPTypes for CPNum in TargetCPs: CurCPNum = GetCPsFromCoords(CPNum, CPCoords, CPTypes, OrigCPCoords, OrigCPTypes) if not AllCPs else CPNum CurCPType = CPTypes[CurCPNum-1] print "Getting CP " + str(CurCPNum) + " from " + T21BaseName if FirstCP: FirstCP = False if IsWindows: subprocess.Popen('mkdir "' + CurrentDir + SubDir + '"', shell=True, stdout=subprocess.PIPE).stdout.read() else: subprocess.Popen('mkdir -p "' + CurrentDir + SubDir + '"', shell=True, stdout=subprocess.PIPE).stdout.read() CPCSV = open(OutBRCCSVName, 'a') CPCSV.write(BRCHeaders) for i in CPInfoList: if i['collect']: for j in i['name']: CPCSV.write(j + ',') if 'Hessian' in i['kf_name']: if CPEigVals['collect']: for j in CPEigVals['name']: CPCSV.write(j + ',') if CPEigVecs['collect']: for j in CPEigVecs['name']: CPCSV.write(j + ',') CPCSV.write('\n') for i in [T21FileName,CPNum,CurCPNum,CPRankInd[CPTypes[CurCPNum-1]-1],CPTypeInd[CPTypes[CurCPNum-1]-1]]: CPCSV.write(str(i) + ",") for i in CPInfoList: if i['collect']: for j in i['data'][CurCPNum-1]: CPCSV.write(str(j) + ",") if 'Hessian' in i['kf_name']: if CPEigVals['collect']: for j in CPEigVals['data'][CurCPNum-1]: CPCSV.write(str(j) + ',') if CPEigVecs['collect']: for j in CPEigVecs['data'][CurCPNum-1]: CPCSV.write(str(j) + ',') # for i in CPCoords[CurCPNum-1]: # CPCSV.write(str(i) + ",") # CPCSV.write(str(CPDens[CurCPNum-1]) + ",") # for i in CPEigVals[CurCPNum-1]: # CPCSV.write(str(i) + ",") CPCSV.write("\n") if CurCPType == 1: if FirstBaderAtom: FirstBaderAtom = False if IsWindows: subprocess.Popen('mkdir "' + CurrentDir + SubDir + '"', shell=True, stdout=subprocess.PIPE).stdout.read() else: subprocess.Popen('mkdir -p "' + CurrentDir + SubDir + '"', shell=True, stdout=subprocess.PIPE).stdout.read() BACSV = open(OutNCSVName, 'a') BACSV.write(NHeaders) for i in AtomInfoList: if i['collect']: for j in i['name']: BACSV.write(j + ',') BACSV.write("\n") # Fetch the input atom number of the current nuclear CP. # I guess this isn't necessary, so it's commented out. # AtomNum = AtomOrderIndex[CurCPNum-1 + NumAtoms] AtomNum = CurCPNum for i in [T21FileName,CPNum,AtomNum]: BACSV.write(str(i) + ",") for i in CPCoords[CurCPNum-1]: BACSV.write(str(i) + ",") for i in AtomInfoList: if i['collect']: for j in i['data'][AtomNum-1]: BACSV.write(str(j) + ",") # BACSV.write(str(CPDens[CurCPNum-1]) + ",") # BACSV.write(str(BaderCharges[CurCPNum-1]) + ",") BACSV.write("\n") if not FirstCP: CPCSV.close() if not FirstBaderAtom: BACSV.close() print "Finished" return
def KFextract(): kf15Path = glob.glob('*.t15') print kf15Path kf21Path = glob.glob('*.t21') print kf21Path if len(kf15Path) != 1 or len(kf21Path) != 1: print 'One and only one of t15 and t21 files allowed in directory!' return # <======================================================================> # DebugFlag Hook: # Use the kfwrapper which dumps everything or you can use kffile # silently. Don't change kf cause that is provided (and supported) by # ADF directly: debugFlag = True if debugFlag : kf15 = kfwrapper.kffileWrapper(kf15Path[0]) kf21 = kfwrapper.kffileWrapper(kf21Path[0]) else: kf15 = kf.kffile(kf15Path[0]) kf21 = kf.kffile(kf21Path[0]) # <======================================================================> Symmetry_symlab = kf15.read ('Symmetry', 'bb') # Read the names of the KS orbitals print Symmetry_symlab moList = [] # Will contain an array of MOs irrepList = [] # Will contain an array of info associated with the symmetry # <======================================================================> # Extract the data from the key files associated with each KS orbital # # Eash KS Symmetry (irrep includes: # - symmetry name (irrepName) # - the expansion coefficients for duplicate atoms (e.g. 1/sqrt(2)) # .... (SFO_proto) # - list of bas functions that support the symmetry (npart) # # Each KS Orbital (mo) includes: # - unique symmetry index associated with the sym array # - symmetry name (irrepName) # - instance ID within symmetry name and spin # - spin A or B # - energy in eV (escale .. converted from AU in key file) # - coefficients in terms of Lowdins (Eigen-Low) # - occupancy (froc) # # <======================================================================> irrepID = 0 for irrepName in Symmetry_symlab: irrepID = irrepID + 1 # -------------------------------------------------------------------- # First extract the bulk data # -------------------------------------------------------------------- # -------------------------------------------------------------------- # Array of SFOs associated with this irrep SFO_proto = kf15.read(irrepName, 'SFO_proto') # SFO expansion coeff SFO_nofr = kf15.read(irrepName, 'nofr') # fragment indices SFO_nofrs = kf15.read(irrepName, 'nofrs') # SFO indices within fragment SFO_nrcoef = kf15.read(irrepName, 'nrcoef') # number of coeff for symmetry irrepList.append(ADF.Irrep(irrepName, SFO_proto, SFO_nofr, SFO_nofrs, SFO_nrcoef)) # <==== irrep # -------------------------------------------------------------------- # The expansion of this KS MO in Lowdin orbitals EigenLow_A = kf15.read(irrepName, 'Eigen-Low_A') EigenLow_B = kf15.read(irrepName, 'Eigen-Low_B') # The number of MOs associated with this symmetry nmo_A = kf15.read(irrepName, 'nmo_A') nmo_B = kf15.read(irrepName, 'nmo_B') # The energy eigenvalue associated with this MO escale_A = kf21.read (irrepName, 'escale_A') escale_B = kf21.read (irrepName, 'escale_B') # The electronic occupancy of this MO froc_A = kf21.read(irrepName,'froc_A') froc_B = kf21.read(irrepName,'froc_B') # -------------------------------------------------------------------- # Now, for each KS orbital, build an mo instance by spin type A/B # -------------------------------------------------------------------- moInst = 1 # -------------------------------------------------------------------- for moIndex in range(nmo_A): strt = moIndex*nmo_A end = strt + nmo_A moList.append(ADF.KSOrbital(irrepID, moInst, # <==== KS MO 'A', escale_A[moIndex], EigenLow_A[strt:end], froc_A[moIndex])) moInst = moInst + 1 # -------------------------------------------------------------------- # -------------------------------------------------------------------- moInst = 1 for moIndex in range(nmo_B): strt = moIndex*nmo_B end = strt + nmo_B moList.append(ADF.KSOrbital(irrepID, moInst, # <============= 'B', escale_B[moIndex], EigenLow_B[strt:end], froc_B[moIndex])) moInst = moInst + 1 # -------------------------------------------------------------------- # <======================================================================> # Extract the information about the SFOs from the fragment files # # Each sfo includes: # - the sfo symmetry name e.g. P:x (ftyp_symlab) # - the sfo atom type (e.g. H, O, Pu) (ftyp_atomtyp) # - list of bas functions that support the symmetry (npart) # ... linked to the same in the sym array above # <======================================================================> # -------------------------------------------------------------------- # read the number of fragment types .. really the number of different # atoms since each atom has a unique fragment file in our implementation # -------------------------------------------------------------------- ntyp = kf21.read('Geometry', 'ntyp') # -------------------------------------------------------------------- fragList = [] fragID = 0 # Loop through each fragment type # Each fragment type is associated with one atom type # If that changes, then this extraction code probably won't work for fragTypeIndex in range(ntyp): fragID = fragID + 1 # Probably works as long as the number of frags is less than 10 ftyp_str = 'Ftyp '+str(fragTypeIndex + 1) # Atomic Label Pu,H,O,etc. ftyp_atomtype = kf21.read(ftyp_str, 'atomtype') # Symbolic label - the SFO label like P:x, D:xy etc. ftyp_symlab = kf21.read(ftyp_str, 'bb') # The number of orbitals for each SFO # ADF says size of the fock matrix but doesn't make sense ftyp_norb = kf21.read(ftyp_str, 'norb') ftyp_nfrag = kf21.read(ftyp_str, 'nfrag') # Force a fragment instance for each atom # eventhough they are the same type for n in range(ftyp_nfrag): fragList.append(ADF.Frag(ftyp_atomtype[0], ftyp_symlab, ftyp_norb)) # -------------------------------------------------------------------- sfoGlobalID = 1 for ks in moList: sfoGlobalID = ks.link(irrepList, fragList, sfoGlobalID) # -------------------------------------------------------------------- for f in fragList: f.dump() # <======================================================================> # Read in the property list for the appropriate SFO's to keep # <======================================================================> pl = Plist.AtomicOrbitalPlist() pl.readPlist() aoList = pl.aoList nStates = aoList.nStates sfoPlist = SFOPropertyList() # <======================================================================> nKSOrbitals = len(moList) print 'Number of KS Orbitals = ', nKSOrbitals Hdft = np.mat(np.zeros((nKSOrbitals, nKSOrbitals), float)) moIndex = 0 Uo = np.mat(np.zeros((nStates, nKSOrbitals), float)) Uks = np.mat(np.zeros((nKSOrbitals, nKSOrbitals), float)) Occ = np.zeros((nKSOrbitals), float) for mo in moList: # <====================== Energy Matrix =================================> irrep = irrepList[mo.irrepID - 1] Hdft[moIndex,moIndex] = mo.escale print 'E(', irrep.irrepName, '.', mo.instance,'.', mo.spin, ') = ', mo.escale, '(', mo.occ, ')' # <====================== Occupation List =================================> Occ[moIndex] = mo.occ # <======================================================================> moIndex = moIndex + 1 # End for mo in moList moIndex = 0 row = 0 for moIndex, mo in enumerate(moList): coeffIndex = 0 nrcoefIndex = 0 count = 0 irrep = irrepList[mo.irrepID - 1] # <======================================================================> for fragID, sfoFragID, SFO_proto in zip(irrep.nofr, irrep.nofrs, irrep.SFO_proto): # ADF doesnt print out each coefficient if they are the same # move to next coefficients or reset back to reuse previous ones if count == 0: count = irrep.nrcoef[nrcoefIndex] nrcoefIndex = nrcoefIndex + 1 else: coeffIndex = saveCoeffIndex count = count - 1 # ADF indexes each fragment file ... # but it doesn't index each SFO f = fragList[fragID - 1] sfo = f.sfoList[sfoFragID - 1] saveCoeffIndex = coeffIndex # <======================================================================> # Loop thru the sfo's # norb - multiple SFOs per SFO, as it were # <======================================================================> for norb in range(sfo.norb): # Generate a unique ID associated with the atomic orbital [rowO, rowKS] = sfoPlist.validSFO(aoList, f, fragID, sfo, norb+1, mo.spin) #print rowO, rowKS, f.atomtype, fragID, sfo.sym, norb+1, mo.spin if (rowO >= 0): Uo[rowO,moIndex] = SFO_proto*mo.eigenLow[coeffIndex] #print 'Uo[', rowO,'(', f.atomtype, fragID, sfo.sym, norb+1,'),',moIndex,'] = ', Uo[rowO,moIndex] if (rowKS == -1): raise(KohnShamError('rowKS is not valid!')) Uks[rowKS,moIndex] = SFO_proto*mo.eigenLow[coeffIndex] #print 'Uks[', rowKS,'(', f.atomtype, fragID, sfo.sym, norb+1,'),',moIndex,'] = ', Uks[rowKS,moIndex] coeffIndex = coeffIndex + 1 # <======================================================================> # end of sfo loop - looping thru the atomic orbitals # <======================================================================> # <======================================================================> # end of frag loop # <======================================================================> # <======================================================================> # end of mo loop ... looping through the KS orbitals # <======================================================================> Nks = np.multiply(np.resize(Occ, Uo.shape), np.multiply(Uo,Uo.conjugate())).sum() print 'Nks = ', Nks f = open('Uo.pkl', 'w') pickle.dump(Uo, f) f.close() f = open('Uks.pkl', 'w') pickle.dump(Uks, f) f.close() f = open('Occ.pkl', 'w') pickle.dump(Occ, f) f.close() f = open('Hdft.pkl', 'w') pickle.dump(Hdft, f) f.close() f = open('Nks.pkl', 'w') pickle.dump(Nks, f) f.close() #f = open('irrep.pkl', 'w') #pickle.dump(irrep, f) #f.close() #f = open('mo.pkl', 'w') #pickle.dump(mo, f) #f.close() #f = open('frag.pkl', 'w') #pickle.dump(frag, f) #f.close() return
def get_MO_from_tape21(filename, nfrozen): print '%-40s' % ' importing ...', datetime.datetime.now() - starttime # get all info from TAPE21 import kf f = kf.kffile(filename) print '%-40s' % ' getting info ...', datetime.datetime.now() - starttime nspin = int(f.read('ActiveFrag', 'nspin')) if nspin == 1: restr = True else: restr = False NAO = int(f.read('Basis', 'naos')) npart = f.read('A', 'npart').tolist() NMO_A = int(f.read('A', 'nmo_A')) mocoef_A = f.read('A', 'Eigen-Bas_A').tolist() if not restr: NMO_B = int(f.read('A', 'nmo_B')) mocoef_B = f.read('A', 'Eigen-Bas_B').tolist() # prepare npart for i in range(len(npart)): npart[i] -= 1 print '%-40s' % ' building matrices ...', datetime.datetime.now( ) - starttime # build MO matrices MO_A = [[0. for iao in range(NAO)] for imo in range(NMO_A)] iao = 0 imo = 0 for i, el in enumerate(mocoef_A): iao1 = npart[iao] MO_A[imo][iao1] = el iao += 1 if iao >= NAO: iao = 0 imo += 1 if not restr: MO_B = [[0. for iao in range(NAO)] for imo in range(NMO_B)] iao = 0 imo = 0 for i, el in enumerate(mocoef_B): iao1 = npart[iao] MO_B[imo][iao1] = el iao += 1 if iao >= NAO: iao = 0 imo += 1 if restr: NMO = NMO_A - nfrozen else: NMO = NMO_A + NMO_B - 2 * nfrozen print '%-40s' % ' formatting ...', datetime.datetime.now() - starttime # make string string = '''2mocoef header 1 MO-coefficients from ADF 1 %i %i a mocoef (*) ''' % (NAO, NMO) x = 0 for imo, mo in enumerate(MO_A): if imo < nfrozen: continue for c in mo: if x >= 3: string += '\n' x = 0 string += '% 6.12e ' % c x += 1 if x > 0: string += '\n' x = 0 if not restr: x = 0 for imo, mo in enumerate(MO_B): if imo < nfrozen: continue for c in mo: if x >= 3: string += '\n' x = 0 string += '% 6.12e ' % c x += 1 if x > 0: string += '\n' x = 0 string += 'orbocc\n(*)\n' x = 0 for i in range(NMO): if x >= 3: string += '\n' x = 0 string += '% 6.12e ' % (0.0) x += 1 return string
def startDocument(self): self.variables = [] self.outfile = kffile(self.data_tape)
def pack_results(self, fileid): """ Pack a TAPE21 results file of an FDE job. This will reduce the size of a FDE TAPE21 file by only keeping the ActiceFragment section and related essential information. All information about frozen fragments will be deleted. This is useful for manual freeze-and-thaw calculations with many subsystems, where this packing can reduce the size of the stored files significantly. @param fileid: The results ID for the coresponding job. @type fileid: int """ if self._ispacked[fileid]: return import subprocess from xml.dom.minidom import parseString import kf fn = self.get_results_filename(fileid, 21) os.rename(fn, fn + ".orig") if kf.kffile.env is None: env = os.environ else: env = kf.kffile.env toc = subprocess.Popen([os.path.join(env['ADFBIN'], 'dmpkf'), fn + ".orig", '--xmltoc'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env).communicate()[0] dom = parseString(toc) f = kf.kffile(fn + ".orig") atomtypeIndices = f.read('ActiveFrag', 'atomtypeIndices') f.close() keepsections = ['General', 'Properties', 'Num Int Params', 'LinearScaling', 'Geometry%nr of fragmenttypes'] keepsections_if_exist = ['Total Energy', 'Energy'] for section in dom.getElementsByTagName('section'): secname = section.getAttribute('id') if secname in keepsections_if_exist: keepsections.append(secname) for i in atomtypeIndices: if secname.startswith('Atyp%3i' % i): keepsections.append(secname) # fixme: use a more general format expression elif secname.startswith('Atyp%4i' % i): keepsections.append(secname) elif secname.startswith('Atyp%5i' % i): keepsections.append(secname) if secname.startswith('ActiveFrag'): keepsections.append(secname) subprocess.Popen([os.path.join(env['ADFBIN'], 'cpkf'), fn + ".orig", fn] + keepsections, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env).wait() os.remove(fn + ".orig")
def __init__(self, filename): self.kf = kf.kffile(filename) print 'Using ', filename