def calc(file, basis, cycle): atom_coords = getAtomCoordsfromPDB('nicola/'+file, cycle) key = file.split('.')[0][1:] LOGGER.info('Loading {:} ...'.format(file)) #optimise in chosen basis, calculate density in cube file, convert to array and then output chosen isosurface LOGGER.info('Building molecule in {:} basis'.format(basis.upper())) molecule, method = BuildandOptimise(atom_coords, basis) cubegen.density(molecule, '{:}_den.cube'.format(key), method.make_rdm1(), resolution=(1/6)) array, dim_array = ConvertCubetoArray('{:}_den.cube'.format(key)) os.remove('{:}_den.cube'.format(key)) LOGGER.info('Generating isosurface ... ') isosurface, volume = CalcIsosurface(array, dim_array) del array LOGGER.info('Complete') #call function that produces numpy array with potential at index 0, followed by x, y, and z coordinates LOGGER.info('Generating molecular electrostatic potential surface... ') LOGGER.debug(isosurface) mep_arr = mep(isosurface, molecule, method.make_rdm1()) LOGGER.debug(mep_arr) del isosurface del molecule del method LOGGER.info('Complete') potentials = np.transpose(mep_arr)[0] potmax = max(potentials) potmin = min(potentials) result = [key, potmax, potmin] LOGGER.info('Job complete:\n InchiKey: {:}\n Max. Pot: {:}\n Min. Pot: {:}\n'.format(key, potmax, potmin)) return result
def __init__(self, mf_full,mol_frag, mol_env, Ne_frag, Ne_env, boundary_atoms=None, boundary_atoms2=None, \ umat = None, oep_params = oep.OEPparams(), smear_sigma = 0.0,\ ecw_method = 'HF', mf_method = 'HF', ex_nroots = 1, \ plot_dens = True, scf_max_cycle=50): self.mf_full = mf_full self.mol = self.mf_full.mol self.mol_full = self.mol self.boundary_atoms = boundary_atoms self.boundary_atoms2 = boundary_atoms2 self.umat = umat self.smear_sigma = smear_sigma self.scf_max_cycle = scf_max_cycle self.P_ref = self.mf_full.make_rdm1() self.P_imp = None self.P_bath = None self.mol_frag = mol_frag self.mol_env = mol_env self.sym_tab = None self.Ne_frag = Ne_frag self.Ne_env = Ne_env self.ecw_method = ecw_method.lower() self.mf_method = mf_method.lower() self.ex_nroots = ex_nroots self.oep_params = oep_params self.dim = self.mol.nao_nr() if (self.umat is None): self.umat = np.zeros((self.dim, self.dim)) self.plot_dens = plot_dens self.vnuc_bound_frag = None self.vnuc_bound_env = None if (boundary_atoms is not None): self.vnuc_bound_frag = self.bound_vnuc_ao(boundary_atoms) if (boundary_atoms2 is not None): self.vnuc_bound_env = self.bound_vnuc_ao(boundary_atoms2) if (self.plot_dens): cubegen.density(self.mol, "tot_dens.cube", self.P_ref, nx=100, ny=100, nz=100) #self.P_imp, self.P_bath = init_density_partition(self) self.P_imp, self.P_bath = oep.init_dens_par(self, self.dim, False)
def test_rho(self): ftmp = tempfile.NamedTemporaryFile() rho = cubegen.density(mol, ftmp.name, mf.make_rdm1(), nx=10, ny=10, nz=10) self.assertEqual(rho.shape, (10, 10, 10)) self.assertAlmostEqual(lib.finger(rho), -0.3740462814001553, 9) rho = cubegen.density(mol, ftmp.name, mf.make_rdm1(), nx=10, ny=10, nz=10, resolution=0.5) self.assertEqual(rho.shape, (12, 18, 15)) self.assertAlmostEqual(lib.finger(rho), -1.007950007160415, 9)
def embedding_potential(self): mo_lo = self.mo_lo pop = self.pop_lo mol = self.mf_full.mol s = mol.intor_symmetric('int1e_ovlp') norb_frozen = 0 Ne_env = self.Ne_env if Ne_env is None: is_env = pop > 0.4 norb_frozen = np.sum(is_env) elif Ne_env > 1: norb_frozen = Ne_env // 2 print("{n:2d} enviroment orbitals kept frozen.".format(n=norb_frozen)) if (norb_frozen > 0): self.P_env = np.dot(mo_lo[:, :norb_frozen], mo_lo[:, :norb_frozen].T) self.P_env = self.P_env + self.P_env.T else: raise RuntimeError("There is no frozen orbital!") proj_op = 0.5 * self.mu * reduce(np.dot, (s, self.P_env, s)) proj_ks = rks_ao(mol, xc_func=self.xc_func, coredm=self.P_env, vext_1e=proj_op, smear_sigma=self.smear_sigma) proj_ks.kernel(dm0=self.P_ref - self.P_env) P_frag = proj_ks.make_rdm1() print("level shift energy:", np.trace(np.dot(P_frag, proj_op))) P_diff = P_frag + self.P_env - self.P_ref print('|P_frag + P_bath - P_ref| / N = ', np.linalg.norm(P_diff) / P_diff.shape[0]) print('max(P_frag + P_bath - P_ref) = ', np.amax(np.absolute(P_diff))) cubegen.density(mol, "dens_error.cube", P_diff, nx=100, ny=100, nz=100) cubegen.density(mol, "dens_frag.cube", P_frag, nx=100, ny=100, nz=100) cubegen.density(mol, "dens_env.cube", self.P_env, nx=100, ny=100, nz=100) return None
def embedding_potential(self): self.calc_umat() ovlp = self.mol.intor_symmetric('int1e_ovlp') inv_S = np.linalg.inv(ovlp) #print(np.dot(ovlp,inv_S)) umat_ao = reduce(np.dot, (inv_S, self.umat, inv_S)) #tools.MatPrint(umat_ao,'S^-1*umat_ao*S^-1') #tools.MatPrint(self.P_imp,'P_frag') if (self.plot_dens): cubegen.density(self.mol, "frag_dens.cube", self.P_imp, nx=100, ny=100, nz=100) cubegen.density(self.mol, "env_dens.cube", self.P_bath, nx=100, ny=100, nz=100) cubegen.density(self.mol, "vemb.cube", umat_ao, nx=100, ny=100, nz=100) cubegen.density(self.mol, "error_dens.cube", self.P_imp + self.P_bath - self.P_ref, nx=100, ny=100, nz=100) return self.umat
def test_cubegen(self): """ Compute the density and store into a cube file """ cubegen.density(mol, 'h2o_den.cube', mf.make_rdm1(), nx=20, ny=20, nz=20) cubegen.mep(mol, 'h2o_pot.cube', mf.make_rdm1(), nx=20, ny=20, nz=20) #slow
''' Write orbitals, electron density, molecular electrostatic potential in Gaussian cube file format. ''' from pyscf import gto, scf from pyscf.tools import cubegen mol = gto.M(atom=''' O 0.0000000, 0.000000, 0.00000000 H 0.761561 , 0.478993, 0.00000000 H -0.761561, 0.478993, 0.00000000''', basis='6-31g*') mf = scf.RHF(mol).run() # electron density cubegen.density(mol, 'h2o_den.cube', mf.make_rdm1()) # electron density slice cubegen.density(mol, 'h2o_den_slice.cube', mf.make_rdm1(), nx=1, ny=1, nz=80) # molecular electrostatic potential cubegen.mep(mol, 'h2o_pot.cube', mf.make_rdm1()) # molecular electrostatic potential slice cubegen.mep(mol, 'h2o_pot_slice.cube', mf.make_rdm1(), nx=1, ny=1, nz=80) # 1st MO cubegen.orbital(mol, 'h2o_mo1.cube', mf.mo_coeff[:,0]) # 1st MO orbital slice cubegen.orbital(mol, 'h2o_mo1_slice.cube', mf.mo_coeff[:,0], nx=1, ny=1, nz=80)
mol = gto.M(atom='H 0 0 0; F 0 0 1.1', basis='ccpvdz') mf = scf.RHF(mol).run() mycc = cc.CCSD(mf).run() # # CCSD density matrix in MO basis # dm1 = mycc.make_rdm1() dm2 = mycc.make_rdm2() # # CCSD energy based on density matrices # h1 = numpy.einsum('pi,pq,qj->ij', mf.mo_coeff.conj(), mf.get_hcore(), mf.mo_coeff) nmo = mf.mo_coeff.shape[1] eri = ao2mo.kernel(mol, mf.mo_coeff, compact=False).reshape([nmo] * 4) E = numpy.einsum('pq,qp', h1, dm1) # Note dm2 is transposed to simplify its contraction to integrals E += numpy.einsum('pqrs,pqrs', eri, dm2) * .5 E += mol.energy_nuc() print('E(CCSD) = %s, reference %s' % (E, mycc.e_tot)) # When plotting CCSD density on the grids, CCSD density matrices need to be # first transformed to AO basis. dm1_ao = numpy.einsum('pi,ij,qj->pq', mf.mo_coeff, dm1, mf.mo_coeff.conj()) from pyscf.tools import cubegen cubegen.density(mol, 'rho_ccsd.cube', dm1_ao)
def parse_nx(data): d = data.split() return int(d[0]), numpy.array([float(x) for x in d[1:]]) self.nx, self.xs = parse_nx(f.readline()) self.ny, self.ys = parse_nx(f.readline()) self.nz, self.zs = parse_nx(f.readline()) atoms = [] for ia in range(natm): d = f.readline().split() atoms.append([int(d[0]), [float(x) for x in d[2:]]]) self.mol = gto.M(atom=atoms, unit='Bohr') data = f.read() cube_data = numpy.array([float(x) for x in data.split()]) return cube_data.reshape([self.nx, self.ny, self.nz]) if __name__ == '__main__': from pyscf import gto, scf from pyscf.tools import cubegen mol = gto.M(atom='''O 0.00000000, 0.000000, 0.000000 H 0.761561, 0.478993, 0.00000000 H -0.761561, 0.478993, 0.00000000''', basis='6-31g*') mf = scf.RHF(mol).run() cubegen.density(mol, 'h2o_den.cube', mf.make_rdm1()) #makes total density cubegen.mep(mol, 'h2o_pot.cube', mf.make_rdm1()) cubegen.orbital(mol, 'h2o_mo1.cube', mf.mo_coeff[:, 0])
def main(filename): #uses the parameters specified in the inp object to optimize the geometry of the given molecule and outputs a file with the updated geometry #TO PARAMATERIZE min_grad = (1 * 10 ^ (-6)) # initialize and print header pstr("", delim="*", addline=False) pstr(" FREEZE-AND-THAW GEOMETRY CALCULATION ", delim="*", fill=False, addline=False) pstr("", delim="*", addline=False) # print input options to stdout pstr("Input File") [ print(i[:-1]) for i in open(filename).readlines() if ((i[0] not in ['#', '!']) and (i[0:2] not in ['::', '//'])) ] pstr("End Input", addline=False) # read input file inp = read_input(filename) inp.timer = simple_timer.timer() nsub = inp.nsubsys inp.DIIS = None inp.ndiags = [0 for i in range(nsub)] # use supermolecular grid for all subsystem grids inp.grids = gen_grids(inp) sna = inp.smol.nao_nr() na = [inp.mol[i].nao_nr() for i in range(nsub)] # initialize 1e matrices from supermolecular system inp.timer.start("OVERLAP INTEGRALS") pstr("Getting subsystem overlap integrals", delim=" ") inp.sSCF = get_scf(inp, inp.smol) Hcore = inp.sSCF.get_hcore() Smat = inp.sSCF.get_ovlp() Fock = np.zeros((sna, sna)) Dmat = [None for i in range(nsub)] inp.timer.end("OVERLAP INTEGRALS") # get initial density for each subsystem inp.timer.start("INITIAL SUBSYSTEMS") inp.mSCF = [None for i in range(nsub)] # SCF objects pstr('Initial subsystem densities', delim=' ') for i in range(nsub): inp.mSCF[i] = get_scf(inp, inp.mol[i]) # read density from file if inp.read and os.path.isfile(inp.read + '.dm{0}'.format(i)): print("Reading initial densities from file: {0}".format( inp.read + '.dm{0}'.format(i))) Dmat[i] = pickle.load(open(inp.read + '.dm{0}'.format(i), 'rb')) # guess density else: print("Guessing initial subsystem densities") Dmat[i] = inp.mSCF[i].init_guess_by_atom() #Dmat[i] = inp.mSCF[i].init_guess_by_minao() inp.sub2sup = get_sub2sup(inp, inp.mSCF) inp.timer.end("INITIAL SUBSYSTEMS") # start with supermolecule calculation if inp.embed.localize: pstr("Supermolecular DFT") inp.sSCF = do_supermol_scf(inp, Dmat, Smat) from localize import localize pstr("Localizing Orbitals", delim="=") Dmat = localize(inp, inp.sSCF, inp.mSCF, Dmat, Smat) # do freeze-and-thaw cycles inp.timer.start("FREEZE AND THAW") if inp.embed.cycles == 1: smethod = "SCF" else: smethod = "Freeze-and-Thaw" if inp.embed.cycles > 0: pstr("Starting " + smethod) inp.error = 1. inp.ift = 0 while ((inp.error > inp.embed.conv) and (inp.ift < inp.embed.cycles)): inp.ift += 1 inp.prev_error = copy(inp.error) inp.error = 0. # cycle over active subsystems for a in range(nsub): if inp.embed.freezeb and a > 0: continue # perform embedding of this subsystem inp.timer.start("TOT. EMBED. OF {0}".format(a + 1)) Fock, inp.mSCF[a], Dnew, eproj, err = do_embedding( a, inp, inp.mSCF, Hcore, Dmat, Smat, Fock, cycles=inp.embed.subcycles, conv=inp.embed.conv, llast=False) er = sp.linalg.norm(Dnew - Dmat[a]) Dmat[a] = np.copy(Dnew) print(' iter: {0:>3d}:{1:<2d} |ddm|: {2:12.6e} ' 'Tr[DP] {3:13.6e}'.format(inp.ift, a + 1, er, eproj)) inp.error += er inp.timer.end("TOT. EMBED. OF {0}".format(a + 1)) print("FOCK") print(Fock) # print whether freeze-and-thaw has converged if ((inp.embed.cycles > 1 and inp.error < inp.embed.conv) or (inp.embed.cycles == 1 and err < inp.embed.conv)): pstr(smethod + " converged!", delim=" ", addline=False) elif inp.embed.cycles == 0: pass else: pstr(smethod + " NOT converged!", delim=" ", addline=False) #DFT in DFT Breakdown superMol = concatenate_mols(inp.mol[0], inp.mol[1]) # do final embedded cycle at high level of theory if inp.embed.cycles > -1: inp.timer.start("TOT. EMBED. OF 1") maxiter = inp.embed.subcycles conv = inp.embed.conv if inp.embed.method != inp.method: pstr("Subsystem 1 at higher mean-field method", delim="=") maxiter = inp.maxiter conv = inp.conv Fock, mSCF_A, DA, eproj, err = do_embedding(0, inp, inp.mSCF, Hcore, Dmat, Smat, Fock, cycles=maxiter, conv=conv, llast=True) er = sp.linalg.norm(DA - Dmat[0]) print(' iter: {0:>3d}:{1:<2d} |ddm|: {2:12.6e} ' 'Tr[DP] {3:13.6e}'.format(inp.ift + 1, 1, er, eproj)) inp.timer.end("TOT. EMBED. OF 1") if inp.embed.method != inp.method: inp.eHI = mSCF_A.e_tot else: inp.eHI = None inp.timer.end("FREEZE AND THAW") # if WFT-in-(DFT/HF), do WFT theory calculation here if inp.method == 'ccsd' or inp.method == 'ccsd(t)': inp.timer.start("CCSD") pstr("Doing CCSD Calculation on Subsystem 1") mCCSD = cc.CCSD(mSCF_A) ecc, t1, t2 = mCCSD.kernel() inp.eHI = mSCF_A.e_tot + ecc inp.timer.end("CCSD") print("Hartree-Fock Energy: {0:19.14f}".format(mSCF_A.e_tot)) print("CCSD Correlation: {0:19.14f}".format(ecc)) print("CCSD Energy: {0:19.14f}".format(mSCF_A.e_tot + ecc)) if inp.method == 'ccsd(t)': from pyscf.cc import ccsd_t, ccsd_t_lambda_slow, ccsd_t_rdm_slow inp.timer.start("CCSD(T)") pstr("Doing CCSD(T) Calculation on Subsystem 1") ecc += ccsd_t.kernel(mCCSD, mCCSD.ao2mo()) inp.eHI = mSCF_A.e_tot + ecc inp.timer.end("CCSD(T)") print("Hartree-Fock Energy: {0:19.14f}".format(mSCF_A.e_tot)) print("CCSD(T) Correlation: {0:19.14f}".format(ecc)) print("CCSD(T) Energy: {0:19.14f}".format(mSCF_A.e_tot + ecc)) if inp.method == 'fci': from pyscf import fci inp.timer.start("FCI") pstr("Doing FCI Calculation on Subsystem 1") #Found here: https://github.com/sunqm/pyscf/blob/master/examples/fci/00-simple_fci.py cisolver = fci.FCI(inp.mol[0], mSCF_A.mo_coeff) efci = cisolver.kernel()[0] inp.eHI = efci inp.timer.end("FCI") print("Hartree-Fock Energy: {0:19.14f}".format(mSCF_A.e_tot)) print("FCI Correlation: {0:19.14f}".format(efci - mSCF_A.e_tot)) print("FCI Energy: {0:19.14f}".format(efci)) # get interaction energy inp.timer.start("INTERACTION ENERGIES") ldosup = not inp.embed.localize if ldosup: pstr("Supermolecular DFT") Etot, EA = get_interaction_energy(inp, Dmat, Smat, ldosup=ldosup) inp.timer.end("INTERACTION ENERGIES") if inp.gencube == "final": inp.timer.start("Generate Cube file") molA_cubename = filename.split(".")[0] + "_A.cube" molB_cubename = filename.split(".")[0] + "_B.cube" cubegen.density(inp.mol[0], molA_cubename, Dmat[0]) cubegen.density(inp.mol[1], molB_cubename, Dmat[1]) inp.timer.end("Generate Cube file") pstr("Embedding Energies", delim="=") Eint = Etot - EA Ediff = inp.Esup - Etot print("Subsystem DFT {0:19.14f}".format(EA)) print("Interaction {0:19.14f}".format(Eint)) print("DFT-in-DFT {0:19.14f}".format(Etot)) print("Supermolecular DFT {0:19.14f}".format(inp.Esup)) print("Difference {0:19.14f}".format(Ediff)) print("Corrected DFT-in-DFT {0:19.14f}".format(Etot + Ediff)) if inp.eHI is not None: print("WF-in-DFT {0:19.14f}".format(inp.eHI + Eint)) print("Corrected WF-in-DFT {0:19.14f}".format(inp.eHI + Eint + Ediff)) # close and print timings inp.timer.close() # print end of file pstr("", delim="*") pstr("END OF CYCLE", delim="*", fill=False, addline=False) pstr("", delim="*", addline=False) G_tot = grad.rks.Gradient(inp.sSCF) G_tot_mat = G_tot.grad() print(G_tot_mat)
basis = 'ccpvdz') mf = scf.RHF(mol).run() mycc = cc.CCSD(mf).run() # # CCSD density matrix in MO basis # dm1 = mycc.make_rdm1() dm2 = mycc.make_rdm2() # # CCSD energy based on density matrices # h1 = numpy.einsum('pi,pq,qj->ij', mf.mo_coeff.conj(), mf.get_hcore(), mf.mo_coeff) nmo = mf.mo_coeff.shape[1] eri = ao2mo.kernel(mol, mf.mo_coeff, compact=False).reshape([nmo]*4) E = numpy.einsum('pq,qp', h1, dm1) # Note dm2 is transposed to simplify its contraction to integrals E+= numpy.einsum('pqrs,pqrs', eri, dm2) * .5 E+= mol.energy_nuc() print('E(CCSD) = %s, reference %s' % (E, mycc.e_tot)) # When plotting CCSD density on the grids, CCSD density matrices need to be # first transformed to AO basis. dm1_ao = numpy.einsum('pi,ij,qj->pq', mf.mo_coeff, dm1, mf.mo_coeff.conj()) from pyscf.tools import cubegen cubegen.density(mol, 'rho_ccsd.cube', dm1_ao)
dm_vv = np.einsum('ia,ic->ac', cis_t1, cis_t1.conj()) # The ground state density matrix in mo_basis mf = td._scf dm = np.diag(mf.mo_occ) # Add CIS contribution nocc = cis_t1.shape[0] dm[:nocc, :nocc] += dm_oo * 2 dm[nocc:, nocc:] += dm_vv * 2 # Transform density matrix to AO basis mo = mf.mo_coeff dm = np.einsum('pi,ij,qj->pq', mo, dm, mo.conj()) return dm # Density matrix for the 3rd excited state dm = tda_denisty_matrix(mytd, 2) # Write to cube format from pyscf.tools import cubegen cubegen.density(mol, 'tda_density.cube', dm) # Write the difference between excited state and ground state cubegen.density(mol, 'density_diff.cube', dm - mf.make_rdm1()) # The positive and negative parts can be overlayed in Jmol # isosurface ID "surf1" cutoff 0.02 density_diff.cube # isosurface ID "surf2" cutoff -0.02 density_diff.cube
def main(sample_index): msg.print_level = 2 msg.info("Hi. Measurements for butadien", 2) #--- fetch dataset and constants --- msg.info("Fetching sample " + str(sample_index) + " from datase", 2) dim = DIM molecules = np.load( "butadien/data/molecules.npy" ) S = np.load( "butadien/data/S.npy") P = np.load( "butadien/data/P.npy") dataset = make_butadien_dataset(molecules, S, P)[0] molecule = molecules[sample_index].get_pyscf_molecule() s = S[sample_index].reshape(dim, dim) s_normed = dataset.inverse_input_transform(s.reshape(1, -1)).reshape(1,-1) p = P[sample_index].reshape(dim, dim) #--- #--- fetch network --- msg.info("Fetching pretained network ", 2) graph = tf.Graph() structure, weights, biases = np.load( "butadien/data/network.npy", encoding="latin1" ) with graph.as_default(): sess = tf.Session() network = EluFixedValue(structure, weights, biases) network.setup() sess.run(tf.global_variables_initializer()) #--- #--- calculate guesses --- msg.info("Calculating guesses ...",2) msg.info("Neural network ", 1) p_nn = network.run(sess, s_normed).reshape(dim, dim) msg.info("McWheenys", 1) p_mcw1 = multi_mc_wheeny(p_nn, s, n_max=1) p_mcw5 = multi_mc_wheeny(p_nn, s, n_max=5) msg.info("Classics", 1) p_sap = hf.init_guess_by_atom(molecule) p_minao = hf.init_guess_by_minao(molecule) p_gwh = hf.init_guess_by_wolfsberg_helmholtz(molecule) #--- #--- Measureing & print --- outfile = "butadien/results/cube_" + str(sample_index) + "_" msg.info("Results Converged ", 1) cubegen.density(molecule, outfile + "converged.cube", p.astype("float64")) msg.info("Results NN: ", 1) cubegen.density(molecule, outfile + "nn.cube", p_nn.astype("float64")) msg.info("Results McWheeny 1: ",1) cubegen.density(molecule, outfile + "mcw1.cube", p_mcw1.astype("float64")) msg.info("Results McWheeny 5: ", 1) cubegen.density(molecule, outfile + "mcw5.cube", p_mcw5.astype("float64")) msg.info("Results SAP: ", 1) cubegen.density(molecule, outfile + "sap.cube", p_sap) msg.info("Results MINAO: ", 1) cubegen.density(molecule, outfile + "minao.cube", p_minao) msg.info("Results GWH: ", 1) cubegen.density(molecule, outfile + "gwh.cube", p_gwh)
#!/usr/bin/env python ''' Write orbitals, electron density, molecular electrostatic potential in Gaussian cube file format. ''' from pyscf import gto, scf from pyscf.tools import cubegen mol = gto.M(atom=''' O 0.0000000, 0.000000, 0.00000000 H 0.761561 , 0.478993, 0.00000000 H -0.761561, 0.478993, 0.00000000''', basis='6-31g*') mf = scf.RHF(mol).run() # electron density cubegen.density(mol, 'h2o_den.cube', mf.make_rdm1()) # molecular electrostatic potential cubegen.mep(mol, 'h2o_pot.cube', mf.make_rdm1()) # 1st MO cubegen.orbital(mol, 'h2o_mo1.cube', mf.mo_coeff[:,0])
def embedding_potential(self): #if(self.umat is None): self.calc_umat() #dim_big = self.dim_frag + self.dim_bath dim_big = self.dim_big ''' occ_mo_imp = self.frag_mo[:,:self.Ne_frag//2] occ_mo_bath = self.env_mo[:,:self.Ne_env//2] self.umat = self.pad_umat(occ_mo_imp, occ_mo_bath, self.dim_sub, dim_big, self.core1PDM_loc) ''' #tools.MatPrint(self.P_imp,'self.P_imp') #tools.MatPrint(self.P_bath,'self.P_bath') #tools.MatPrint(self.P_ref_sub,'P_ref') ao2sub = self.ao2sub[:, :dim_big] P_imp_ao = tools.dm_sub2ao(self.P_imp, ao2sub) P_bath_ao = tools.dm_sub2ao(self.P_bath, ao2sub) #tools.MatPrint(P_imp_ao,'P_frag') umat_ao = reduce(np.dot, (ao2sub, self.umat, ao2sub.T)) diffP = P_imp_ao + P_bath_ao + self.core1PDM_ao - self.P_ref_ao print('|diffP_ao| = ', np.linalg.norm(diffP), 'max(diffP_ao) = ', np.max(diffP)) if (self.plot_dens): cubegen.density(self.mol, "tot_dens.cube", self.P_ref_ao, nx=100, ny=100, nz=100) cubegen.density(self.mol, "frag_dens.cube", P_imp_ao, nx=100, ny=100, nz=100) cubegen.density(self.mol, "bath_dens.cube", P_bath_ao, nx=100, ny=100, nz=100) cubegen.density(self.mol, "core_dens.cube", self.core1PDM_ao, nx=100, ny=100, nz=100) cubegen.density(self.mol, "env_dens.cube", P_bath_ao + self.core1PDM_ao, nx=100, ny=100, nz=100) cubegen.density(self.mol, "vemb.cube", umat_ao, nx=100, ny=100, nz=100) cubegen.density(self.mol, "error_dens.cube", diffP, nx=100, ny=100, nz=100)
from pyscf.tools import cubegen from pyscf.data.nist import BOHR import numpy as np ang2bohr = 1.0 / BOHR mol = gto.M(atom=''' O 0.0000000000000000 0.0000000000000000 0.000 H -0.26312631683261728 0.92177640310981912 0.000 H 0.9645910938303689 4.0006988432649347E-002 0.000 ''', basis='aug-cc-pVDZ') mm_crd = np.array( [[2.9125407227330018, 0.0000000000000000, 0.000], [3.3354011353264896, -0.41314678971687741, -0.75710308103585677], [3.3354011558614673, -0.41314667699843621, 0.75710313896414105]]) mm_crd *= ang2bohr mm_chgs = np.array([-0.68, 0.34, 0.34]) mf = qmmm.mm_charge(scf.RHF(mol), mm_crd, mm_chgs).run() # electron density cubegen.density(mol, 'h2o_den_qmmm.cube', mf.make_rdm1()) # molecular electrostatic potential cubegen.mep(mol, 'h2o_pot_qmmm.cube', mf.make_rdm1()) # 1st MO nhomo = mf.mol.nelec[0] cubegen.orbital(mol, 'h2o_homo_qmmm.cube', mf.mo_coeff[:, nhomo - 1])
def get_density_cube(mol, mf, cube_fn="density.cub"): cubegen.density(mol, cube_fn, mf.make_rdm1())
f.write('%12.6f%12.6f%12.6f\n' % tuple(self.boxorig.tolist())) f.write('%5d%12.6f%12.6f%12.6f\n' % (self.nx, self.xs[1], 0, 0)) f.write('%5d%12.6f%12.6f%12.6f\n' % (self.ny, 0, self.ys[1], 0)) f.write('%5d%12.6f%12.6f%12.6f\n' % (self.nz, 0, 0, self.zs[1])) for ia in range(mol.natm): chg = mol.atom_charge(ia) f.write('%5d%12.6f'% (chg, chg)) f.write('%12.6f%12.6f%12.6f\n' % tuple(coord[ia])) for ix in range(self.nx): for iy in range(self.ny): for iz0, iz1 in lib.prange(0, self.nz, 6): fmt = '%13.5E' * (iz1-iz0) + '\n' f.write(fmt % tuple(field[ix,iy,iz0:iz1].tolist())) def read(self, cube_file): raise NotImplementedError if __name__ == '__main__': from pyscf import gto, scf from pyscf.tools import cubegen mol = gto.M(atom='''O 0.00000000, 0.000000, 0.000000 H 0.761561, 0.478993, 0.00000000 H -0.761561, 0.478993, 0.00000000''', basis='6-31g*') mf = scf.RHF(mol).run() cubegen.density(mol, 'h2o_den.cube', mf.make_rdm1()) #makes total density cubegen.mep(mol, 'h2o_pot.cube', mf.make_rdm1()) cubegen.orbital(mol, 'h2o_mo1.cube', mf.mo_coeff[:,0])
ao = numint.eval_ao(mol, coords[ip0:ip1]) rho[ip0:ip1] = numint.eval_rho(mol, ao, dm) rho = rho.reshape(nx, ny, nz) with open(outfile, 'w') as f: f.write('Electron density in real space (e/Bohr^3)\n') f.write('PySCF Version: %s Date: %s\n' % (pyscf.__version__, time.ctime())) f.write('%5d' % mol.natm) f.write(' %14.8f %14.8f %14.8f\n' % tuple(boxorig.tolist())) f.write('%5d %14.8f %14.8f %14.8f\n' % (nx, xs[1], 0, 0)) f.write('%5d %14.8f %14.8f %14.8f\n' % (ny, 0, ys[1], 0)) f.write('%5d %14.8f %14.8f %14.8f\n' % (nz, 0, 0, zs[1])) for ia in range(mol.natm): chg = mol.atom_charge(ia) f.write('%5d %f' % (chg, chg)) f.write(' %14.8f %14.8f %14.8f\n' % tuple(coord[ia])) fmt = ' %14.8e' * nz + '\n' for ix in range(nx): for iy in range(ny): f.write(fmt % tuple(rho[ix, iy].tolist())) if __name__ == '__main__': from pyscf import gto, scf from pyscf.tools import cubegen mol = gto.M(atom='H 0 0 0; H 0 0 1') mf = scf.RHF(mol) mf.scf() cubegen.density(mol, 'h2.cube', mf.make_rdm1())
ao = numint.eval_ao(mol, coords[ip0:ip1]) rho[ip0:ip1] = numint.eval_rho(mol, ao, dm) rho = rho.reshape(nx, ny, nz) with open(outfile, "w") as f: f.write("Density in real space\n") f.write("Comment line\n") f.write("%5d" % mol.natm) f.write(" %14.8f %14.8f %14.8f\n" % tuple(boxorig.tolist())) f.write("%5d %14.8f %14.8f %14.8f\n" % (nx, xs[1], 0, 0)) f.write("%5d %14.8f %14.8f %14.8f\n" % (ny, 0, ys[1], 0)) f.write("%5d %14.8f %14.8f %14.8f\n" % (nz, 0, 0, zs[1])) for ia in range(mol.natm): chg = mol.atom_charge(ia) f.write("%5d %f" % (chg, chg)) f.write(" %14.8f %14.8f %14.8f\n" % tuple(coord[ia])) fmt = " %14.8e" * nz + "\n" for ix in range(nx): for iy in range(ny): f.write(fmt % tuple(rho[ix, iy].tolist())) if __name__ == "__main__": from pyscf import gto, scf from pyscf.tools import cubegen mol = gto.M(atom="H 0 0 0; H 0 0 1") mf = scf.RHF(mol) mf.scf() cubegen.density(mol, "h2.cube", mf.make_rdm1())