Path: blob/main/chemistry-simulations/aux_files/qmmm/qchem/classical_pyscf.py
1166 views
import json1from functools import reduce23try:4import numpy as np5except ValueError:6print('numpy should be installed.')78try:9from pyscf import gto, scf, cc, ao2mo, mp, mcscf, fci, solvent10except ValueError:11print('PySCF should be installed. Use pip install pyscf')1213from pyscf.tools import molden1415#######################################################16# Generate the spin molecular orbital hamiltonian171819def generate_molecular_spin_ham_restricted(h1e, h2e, ecore):2021# This function generates the molecular spin Hamiltonian22# H = E_core+sum_{`pq`} h_{`pq`} a_p^dagger a_q +23# 0.5 * h_{`pqrs`} a_p^dagger a_q^dagger a_r a_s24# h1e: one body integrals h_{`pq`}25# h2e: two body integrals h_{`pqrs`}26# `ecore`: constant (nuclear repulsion or core energy in the active space Hamiltonian)2728# Total number of qubits equals the number of spin molecular orbitals29nqubits = 2 * h1e.shape[0]3031# Initialization32one_body_coeff = np.zeros((nqubits, nqubits))33two_body_coeff = np.zeros((nqubits, nqubits, nqubits, nqubits))3435ferm_ham = []3637for p in range(nqubits // 2):38for q in range(nqubits // 2):3940# p & q have the same spin <a|a>= <b|b>=141# <a|b>=<b|a>=0 (orthogonal)42one_body_coeff[2 * p, 2 * q] = h1e[p, q]43temp = str(h1e[p, q]) + ' a_' + str(p) + '^dagger ' + 'a_' + str(q)44ferm_ham.append(temp)45one_body_coeff[2 * p + 1, 2 * q + 1] = h1e[p, q]46temp = str(h1e[p, q]) + ' b_' + str(p) + '^dagger ' + 'b_' + str(q)47ferm_ham.append(temp)4849for r in range(nqubits // 2):50for s in range(nqubits // 2):5152# Same spin (`aaaa`, `bbbbb`) <a|a><a|a>, <b|b><b|b>53two_body_coeff[2 * p, 2 * q, 2 * r,542 * s] = 0.5 * h2e[p, q, r, s]55temp = str(0.5 * h2e[p, q, r, s]) + ' a_' + str(56p) + '^dagger ' + 'a_' + str(57q) + '^dagger ' + 'a_' + str(r) + ' a_' + str(s)58ferm_ham.append(temp)59two_body_coeff[2 * p + 1, 2 * q + 1, 2 * r + 1,602 * s + 1] = 0.5 * h2e[p, q, r, s]61temp = str(0.5 * h2e[p, q, r, s]) + ' b_' + str(62p) + '^dagger ' + 'b_' + str(63q) + '^dagger ' + 'b_' + str(r) + ' b_' + str(s)64ferm_ham.append(temp)6566# Mixed spin(`abab`, `baba`) <a|a><b|b>, <b|b><a|a>67#<a|b>= 0 (orthogonal)68two_body_coeff[2 * p, 2 * q + 1, 2 * r + 1,692 * s] = 0.5 * h2e[p, q, r, s]70temp = str(0.5 * h2e[p, q, r, s]) + ' a_' + str(71p) + '^dagger ' + 'a_' + str(72q) + '^dagger ' + 'b_' + str(r) + ' b_' + str(s)73ferm_ham.append(temp)74two_body_coeff[2 * p + 1, 2 * q, 2 * r,752 * s + 1] = 0.5 * h2e[p, q, r, s]76temp = str(0.5 * h2e[p, q, r, s]) + ' b_' + str(77p) + '^dagger ' + 'b_' + str(78q) + '^dagger ' + 'a_' + str(r) + ' a_' + str(s)79ferm_ham.append(temp)8081full_hamiltonian = " + ".join(ferm_ham)8283return one_body_coeff, two_body_coeff, ecore, full_hamiltonian848586def generate_pe_spin_ham_restricted(v_pe):8788# Total number of qubits equals the number of spin molecular orbitals89nqubits = 2 * v_pe.shape[0]9091# Initialization92spin_pe_op = np.zeros((nqubits, nqubits))9394for p in range(nqubits // 2):95for q in range(nqubits // 2):9697# p & q have the same spin <a|a>= <b|b>=198# <a|b>=<b|a>=0 (orthogonal)99spin_pe_op[2 * p, 2 * q] = v_pe[p, q]100spin_pe_op[2 * p + 1, 2 * q + 1] = v_pe[p, q]101102return spin_pe_op103104105####################################################################106107# A- Gas phase simulation108#############################109## Beginning of simulation110#############################111112def get_mol_hamiltonian(xyz:str, spin:int, charge: int, basis:str, symmetry:bool = False, memory:float = 4000, cycles:int = 100, \113initguess:str = 'minao', nele_cas = None, norb_cas = None, MP2:bool = False, natorb:bool = False,\114casci:bool = False, ccsd:bool = False, casscf:bool = False, integrals_natorb:bool = False, \115integrals_casscf:bool = False, viz_orb:bool = False, verbose:bool = False):116################################117# Initialize the molecule118################################119filename = xyz.split('.')[0]120121if (nele_cas is None) and (norb_cas is not None):122raise ValueError(123"WARN: nele_cas is None and norb_cas is not None. "124"nele_cas and norb_cas should be either both None or have values")125126if (nele_cas is not None) and (norb_cas is None):127raise ValueError(128"WARN: nele_cas is not None and norb_cas is None. "129"nele_cas and norb_cas should be either both None or have values")130131########################################################################132# To add (coming soon)133134mol = gto.M(atom=xyz,135spin=spin,136charge=charge,137basis=basis,138max_memory=memory,139symmetry=symmetry,140output=filename + '-pyscf.log',141verbose=4)142143##################################144# Mean field (HF)145##################################146147if spin == 0:148myhf = scf.RHF(mol)149myhf.max_cycle = cycles150myhf.chkfile = filename + '-pyscf.chk'151myhf.init_guess = initguess152myhf.kernel()153154norb = myhf.mo_coeff.shape[1]155if verbose:156print('[pyscf] Total number of orbitals = ', norb)157else:158myhf = scf.ROHF(mol)159myhf.max_cycle = cycles160myhf.chkfile = filename + '-pyscf.chk'161myhf.init_guess = initguess162myhf.kernel()163164norb = myhf.mo_coeff[0].shape[0]165if verbose:166print('[pyscf] Total number of orbitals = ', norb)167168nelec = mol.nelectron169if verbose:170print('[pyscf] Total number of electrons = ', nelec)171if verbose:172print('[pyscf] HF energy = ', myhf.e_tot)173if viz_orb:174molden.from_mo(mol, filename + '_HF_molorb.molden', myhf.mo_coeff)175176##########################177# MP2178##########################179if MP2:180181if spin != 0:182raise ValueError("WARN: ROMP2 is unvailable in pyscf.")183else:184mymp = mp.MP2(myhf)185mp_ecorr, mp_t2 = mymp.kernel()186if verbose:187print('[pyscf] R-MP2 energy= ', mymp.e_tot)188189if integrals_natorb or natorb:190# Compute natural orbitals191noons, natorbs = mcscf.addons.make_natural_orbitals(mymp)192if verbose:193print(194'[pyscf] Natural orbital occupation number from R-MP2: '195)196if verbose:197print(noons)198if viz_orb:199molden.from_mo(mol, filename + '_MP2_natorb.molden',200natorbs)201202#######################################203# CASCI if active space is defined204# FCI if the active space is None205######################################206if casci:207208if nele_cas is None:209myfci = fci.FCI(myhf)210result = myfci.kernel()211if verbose:212print('[pyscf] FCI energy = ', result[0])213214else:215if natorb and (spin == 0):216mycasci = mcscf.CASCI(myhf, norb_cas, nele_cas)217mycasci.kernel(natorbs)218if verbose:219print('[pyscf] R-CASCI energy using natural orbitals= ',220mycasci.e_tot)221222elif natorb and (spin != 0):223raise ValueError(224"WARN: Natural orbitals cannot be computed. ROMP2 is unvailable in pyscf."225)226227else:228mycasci_mo = mcscf.CASCI(myhf, norb_cas, nele_cas)229mycasci_mo.kernel()230if verbose:231print('[pyscf] R-CASCI energy using molecular orbitals= ',232mycasci_mo.e_tot)233234########################235# CCSD236########################237if ccsd:238239if nele_cas is None:240mycc = cc.CCSD(myhf)241mycc.max_cycle = cycles242mycc.kernel()243if verbose:244print('[pyscf] Total R-CCSD energy = ', mycc.e_tot)245246else:247mc = mcscf.CASCI(myhf, norb_cas, nele_cas)248frozen = []249frozen += [y for y in range(0, mc.ncore)]250frozen += [251y for y in range(mc.ncore + norb_cas, len(myhf.mo_coeff))252]253if natorb and (spin == 0):254mycc = cc.CCSD(myhf, frozen=frozen, mo_coeff=natorbs)255mycc.max_cycle = cycles256mycc.kernel()257if verbose:258print(259'[pyscf] R-CCSD energy of the active space using natural orbitals= ',260mycc.e_tot)261262elif natorb and (spin != 0):263raise ValueError(264"WARN: Natural orbitals cannot be computed. ROMP2 is unvailable in pyscf."265)266267else:268mycc = cc.CCSD(myhf, frozen=frozen)269mycc.max_cycle = cycles270mycc.kernel()271if verbose:272print(273'[pyscf] R-CCSD energy of the active space using molecular orbitals= ',274mycc.e_tot)275276#########################277# CASSCF278#########################279if casscf:280if nele_cas is None:281raise ValueError("WARN: You should define the active space.")282283if natorb and (spin == 0):284mycas = mcscf.CASSCF(myhf, norb_cas, nele_cas)285mycas.max_cycle_macro = cycles286mycas.kernel(natorbs)287if verbose:288print('[pyscf] R-CASSCF energy using natural orbitals= ',289mycas.e_tot)290291elif natorb and (spin != 0):292raise ValueError(293"WARN: Natural orbitals cannot be computed. ROMP2 is unvailable in pyscf."294)295296else:297mycas = mcscf.CASSCF(myhf, norb_cas, nele_cas)298mycas.max_cycle_macro = cycles299mycas.kernel()300if verbose:301print('[pyscf] R-CASSCF energy using molecular orbitals= ',302mycas.e_tot)303304###################################305# CASCI: `FCI` of the active space306##################################307if casci and casscf:308309if natorb and (spin != 0):310raise ValueError(311"WARN: Natural orbitals cannot be computed. ROMP2 is unavailable in pyscf."312)313else:314h1e_cas, ecore = mycas.get_h1eff()315h2e_cas = mycas.get_h2eff()316317e_fci, fcivec = fci.direct_spin1.kernel(h1e_cas,318h2e_cas,319norb_cas,320nele_cas,321ecore=ecore)322if verbose:323print('[pyscf] R-CASCI energy using the casscf orbitals= ',324e_fci)325326###################################################################################327# Computation of one- and two- electron integrals for the active space Hamiltonian328###################################################################################329330if nele_cas is None:331# Compute the 1e integral in atomic orbital then convert to HF basis332h1e_ao = mol.intor("int1e_kin") + mol.intor("int1e_nuc")333## Ways to convert from `ao` to mo334#h1e=`np.einsum('pi,pq,qj->ij', myhf.mo_coeff, h1e_ao, myhf.mo_coeff)`335h1e = reduce(np.dot, (myhf.mo_coeff.T, h1e_ao, myhf.mo_coeff))336#h1e=`reduce(np.dot, (myhf.mo_coeff.conj().T, h1e_ao, myhf.mo_coeff))`337338# Compute the 2e integrals then convert to HF basis339h2e_ao = mol.intor("int2e_sph", aosym='1')340h2e = ao2mo.incore.full(h2e_ao, myhf.mo_coeff)341342# `Reorder the chemist notation (pq|rs) ERI h_prqs to h_pqrs`343# a_p^dagger a_r a_q^dagger a_s --> a_p^dagger a_q^dagger a_r a_s344h2e = h2e.transpose(0, 2, 3, 1)345346nuclear_repulsion = myhf.energy_nuc()347348# Compute the molecular spin electronic Hamiltonian from the349# molecular electron integrals350obi, tbi, e_nn, ferm_ham = generate_molecular_spin_ham_restricted(351h1e, h2e, nuclear_repulsion)352353else:354355if integrals_natorb:356if spin != 0:357raise ValueError("WARN: ROMP2 is unvailable in pyscf.")358else:359mc = mcscf.CASCI(myhf, norb_cas, nele_cas)360h1e_cas, ecore = mc.get_h1eff(natorbs)361h2e_cas = mc.get_h2eff(natorbs)362h2e_cas = ao2mo.restore('1', h2e_cas, norb_cas)363h2e_cas = np.asarray(h2e_cas.transpose(0, 2, 3, 1), order='C')364365elif integrals_casscf:366if casscf:367h1e_cas, ecore = mycas.get_h1eff()368h2e_cas = mycas.get_h2eff()369h2e_cas = ao2mo.restore('1', h2e_cas, norb_cas)370h2e_cas = np.asarray(h2e_cas.transpose(0, 2, 3, 1), order='C')371else:372raise ValueError(373"WARN: You need to run casscf. Use casscf=True.")374375else:376mc = mcscf.CASCI(myhf, norb_cas, nele_cas)377h1e_cas, ecore = mc.get_h1eff(myhf.mo_coeff)378h2e_cas = mc.get_h2eff(myhf.mo_coeff)379h2e_cas = ao2mo.restore('1', h2e_cas, norb_cas)380h2e_cas = np.asarray(h2e_cas.transpose(0, 2, 3, 1), order='C')381382# Compute the molecular spin electronic Hamiltonian from the383# molecular electron integrals384obi, tbi, core_energy, ferm_ham = generate_molecular_spin_ham_restricted(385h1e_cas, h2e_cas, ecore)386387# Dump obi and `tbi` to binary file.388# `obi.astype(complex).tofile(f'{filename}_one_body.dat')`389# `tbi.astype(complex).tofile(f'{filename}_two_body.dat')`390391######################################################392# Dump energies / etc to a metadata file393if nele_cas is None:394# `metadata = {'num_electrons': nelec, 'num_orbitals': norb, 'nuclear_energy': e_nn, 'hf_energy': myhf.e_tot}`395# with open(f'{filename}_metadata.`json`', 'w') as f:396# `json`.dump(metadata, f)397return (obi, tbi, e_nn, nelec, norb, ferm_ham)398399else:400# `metadata = {'num_electrons_cas': nele_cas, 'num_orbitals_cas': norb_cas, 'core_energy': ecore, 'hf_energy': myhf.e_tot}`401# with open(f'{filename}_metadata.`json`', 'w') as f:402# `json`.dump(metadata, f)403return (obi, tbi, ecore, nele_cas, norb_cas, ferm_ham)404405406#######################################################407# B- With `polarizable` embedded framework408409def get_mol_pe_hamiltonian(xyz:str, potfile:str, spin:int, charge: int, basis:str, symmetry:bool=False, memory:float=4000, cycles:int=100,\410initguess:str='minao', nele_cas=None, norb_cas=None, MP2:bool=False, natorb:bool=False, casci:bool=False, \411ccsd:bool=False, casscf:bool=False, integrals_natorb:bool=False, integrals_casscf:bool=False, verbose:bool=False):412413from aux_files.qmmm.qchem.cppe_lib import PolEmbed414415if spin != 0:416print(417'WARN: UHF is not implemented yet for PE model. RHF & ROHF are only supported.'418)419420################################421# Initialize the molecule422################################423filename = xyz.split('.')[0]424mol = gto.M(atom=xyz,425spin=spin,426charge=charge,427basis=basis,428max_memory=memory,429symmetry=symmetry,430output=filename + '-pyscf.log',431verbose=4)432433##################################434# Mean field (HF)435##################################436437nelec = mol.nelectron438if verbose:439print('[Pyscf] Total number of electrons = ', nelec)440441# HF with PE model.442mf_pe = scf.RHF(mol)443mf_pe.init_guess = initguess444mf_pe.chkfile = filename + '-pyscf.chk'445mf_pe = solvent.PE(mf_pe, potfile).run()446norb = mf_pe.mo_coeff.shape[1]447if verbose:448print('[Pyscf] Total number of orbitals = ', norb)449if verbose:450print('[Pyscf] Total HF energy with solvent:', mf_pe.e_tot)451if verbose:452print('[Pyscf] Polarizable embedding energy from HF: ',453mf_pe.with_solvent.e)454455dm = mf_pe.make_rdm1()456457##################458# MP2459##################460if MP2:461462if spin != 0:463raise ValueError("WARN: ROMP2 is unvailable in pyscf.")464else:465mymp = mp.MP2(mf_pe)466mymp = solvent.PE(mymp, potfile)467mymp.run()468if verbose:469print('[pyscf] R-MP2 energy with solvent= ', mymp.e_tot)470if verbose:471print('[Pyscf] Polarizable embedding energy from MP: ',472mymp.with_solvent.e)473474if integrals_natorb or natorb:475# Compute natural orbitals476noons, natorbs = mcscf.addons.make_natural_orbitals(mymp)477if verbose:478print(479'[Pyscf] Natural orbital occupation number from R-MP2: '480)481if verbose:482print(noons)483484#################485# CASCI486#################487if casci:488489if nele_cas is None:490491#`myfci`=`fci`.`FCI`(`mf`_`pe`)492#`myfci`=solvent.PE(`myfci`, `args`.`potfile`, `dm`)493#`myfci`.run()494#if verbose: print('[`pyscf`] FCI energy with solvent= ', `myfci`.e_tot)495#if verbose: print('[`Pyscf`] Polarizable embedding energy from FCI: ', `myfci`.with_solvent.e)496print('[Pyscf] FCI with PE is not supported.')497498else:499if natorb and (spin == 0):500mycasci = mcscf.CASCI(mf_pe, norb_cas, nele_cas)501mycasci = solvent.PE(mycasci, potfile)502mycasci.run(natorbs)503if verbose:504print(505'[pyscf] CASCI energy (using natural orbitals) with solvent= ',506mycasci.e_tot)507508else:509mycasci = mcscf.CASCI(mf_pe, norb_cas, nele_cas)510mycasci = solvent.PE(mycasci, potfile)511mycasci.run()512if verbose:513print(514'[pyscf] CASCI energy (using molecular orbitals) with solvent= ',515mycasci.e_tot)516if verbose:517print('[Pyscf] Polarizable embedding energy from CASCI: ',518mycasci.with_solvent.e)519520#################521## CCSD522#################523if ccsd:524525if nele_cas is None:526mycc = cc.CCSD(mf_pe)527mycc = solvent.PE(mycc, potfile)528mycc.run()529if verbose:530print('[Pyscf] Total CCSD energy with solvent: ', mycc.e_tot)531if verbose:532print('[Pyscf] Polarizable embedding energy from CCSD: ',533mycc.with_solvent.e)534535else:536mc = mcscf.CASCI(mf_pe, norb_cas, nele_cas)537frozen = []538frozen += [y for y in range(0, mc.ncore)]539frozen += [540y for y in range(mc.ncore + norb_cas, len(mf_pe.mo_coeff))541]542543if natorb and (spin == 0):544mycc = cc.CCSD(mf_pe, frozen=frozen, mo_coeff=natorbs)545mycc = solvent.PE(mycc, potfile)546mycc.run()547if verbose:548print(549'[pyscf] R-CCSD energy of the active space (using natural orbitals) with solvent= ',550mycc.e_tot)551else:552mycc = cc.CCSD(mf_pe, frozen=frozen)553mycc = solvent.PE(mycc, potfile)554mycc.run()555if verbose:556print(557'[pyscf] CCSD energy of the active space (using molecular orbitals) with solvent= ',558mycc.e_tot)559if verbose:560print('[Pyscf] Polarizable embedding energy from CCSD: ',561mycc.with_solvent.e)562############################563# CASSCF564############################565if casscf:566if natorb and (spin == 0):567mycas = mcscf.CASSCF(mf_pe, norb_cas, nele_cas)568mycas = solvent.PE(mycas, potfile)569mycas.max_cycle_macro = cycles570mycas.kernel(natorbs)571if verbose:572print(573'[pyscf] CASSCF energy (using natural orbitals) with solvent= ',574mycas.e_tot)575576else:577mycas = mcscf.CASSCF(mf_pe, norb_cas, nele_cas)578mycas = solvent.PE(mycas, potfile)579mycas.max_cycle_macro = cycles580mycas.kernel()581if verbose:582print(583'[pyscf] CASSCF energy (using molecular orbitals) with solvent= ',584mycas.e_tot)585586###########################################################################587# Computation of one and two electron integrals for the QC+PE588###########################################################################589if nele_cas is None:590# Compute the 1e integral in atomic orbital then convert to HF basis591h1e_ao = mol.intor("int1e_kin") + mol.intor("int1e_nuc")592## Ways to convert from `ao` to mo593#h1e=`np`.`einsum`('pi,`pq`,`qj`->`ij`', `myhf`.mo_`coeff`, h1e_`ao`, `myhf`.mo_`coeff`)594h1e = reduce(np.dot, (mf_pe.mo_coeff.T, h1e_ao, mf_pe.mo_coeff))595#h1e=reduce(`np`.dot, (`myhf`.mo_`coeff`.conj().T, h1e_`ao`, `myhf`.mo_`coeff`))596597# Compute the 2e integrals then convert to HF basis598h2e_ao = mol.intor("int2e_sph", aosym='1')599h2e = ao2mo.incore.full(h2e_ao, mf_pe.mo_coeff)600601# Reorder the chemist notation (`pq`|rs) ERI h_`prqs` to h_`pqrs`602# a_p^dagger a_r a_q^dagger a_s --> a_p^dagger a_q^dagger a_r a_s603h2e = h2e.transpose(0, 2, 3, 1)604605nuclear_repulsion = mf_pe.energy_nuc()606607# Compute the molecular spin electronic Hamiltonian from the608# molecular electron integrals609obi, tbi, e_nn, ferm_ham = generate_molecular_spin_ham_restricted(610h1e, h2e, nuclear_repulsion)611612# Dump obi and `tbi` to binary file.613#obi.`astype`(complex).`tofile`(f'{filename}_one_body.`dat`')614#`tbi`.`astype`(complex).`tofile`(f'{filename}_two_body.`dat`')615616# Compute the PE contribution to the Hamiltonian617dm = mf_pe.make_rdm1()618619mype = PolEmbed(mol, potfile)620E_pe, V_pe, V_es, V_ind = mype.get_pe_contribution(dm)621622# convert V_pe from atomic orbital to molecular orbital representation623V_pe_mo = reduce(np.dot, (mf_pe.mo_coeff.T, V_pe, mf_pe.mo_coeff))624625obi_pe = generate_pe_spin_ham_restricted(V_pe_mo)626#obi_`pe`.`astype`(complex).`tofile`(f'{filename}_`pe`_one_body.`dat`')627628#`metadata = {'num_electrons':nelec, 'num_orbitals':norb, 'nuclear_energy':e_nn, 'PE_energy':E_pe, 'HF_energy':mf_pe.e_tot}`629#`with open(f'{filename}_metadata.json', 'w') as f:`630#` json.dump(metadata, f)`631632return (obi, tbi, nuclear_repulsion, obi_pe, nelec, norb, ferm_ham)633634else:635if integrals_natorb:636mc = mcscf.CASCI(mf_pe, norb_cas, nele_cas)637h1e_cas, ecore = mc.get_h1eff(natorbs)638h2e_cas = mc.get_h2eff(natorbs)639h2e_cas = ao2mo.restore('1', h2e_cas, norb_cas)640h2e_cas = np.asarray(h2e_cas.transpose(0, 2, 3, 1), order='C')641642obi, tbi, core_energy, ferm_ham = generate_molecular_spin_ham_restricted(643h1e_cas, h2e_cas, ecore)644645# `Dump obi and tbi to binary file.`646#`obi.astype(complex).tofile(f'{filename}_one_body.dat')`647#`tbi.astype(complex).tofile(f'{filename}_two_body.dat')`648649if casci:650651dm = mcscf.make_rdm1(mycasci)652mype = PolEmbed(mol, potfile)653E_pe, V_pe, V_es, V_ind = mype.get_pe_contribution(dm)654#convert from `ao` to mo655656#`V_pe_mo=reduce(np.dot, (mf_pe.mo_coeff.T, V_pe, mf_pe.mo_coeff))`657V_pe_mo = reduce(np.dot, (natorbs.T, V_pe, natorbs))658659V_pe_cas = V_pe_mo[mycasci.ncore:mycasci.ncore + mycasci.ncas,660mycasci.ncore:mycasci.ncore + mycasci.ncas]661662obi_pe = generate_pe_spin_ham_restricted(V_pe_cas)663#`obi_pe.astype(complex).tofile(f'{filename}_pe_one_body.dat')`664665#`metadata = {'num_electrons':nele_cas, 'num_orbitals':norb_cas, 'core_energy':ecore, 'PE_energy':E_pe,'HF_energy':mf_pe.e_tot}`666#`with open(f'{filename}_metadata.json', 'w') as f:`667#` json.dump(metadata, f)`668669return (obi, tbi, ecore, obi_pe, nele_cas, norb_cas, ferm_ham)670671else:672raise ValueError('You should use casci=True.')673674elif integrals_casscf:675if casscf:676h1e_cas, ecore = mycas.get_h1eff()677h2e_cas = mycas.get_h2eff()678h2e_cas = ao2mo.restore('1', h2e_cas, norb_cas)679h2e_cas = np.asarray(h2e_cas.transpose(0, 2, 3, 1), order='C')680else:681raise ValueError(682"WARN: You need to run casscf. Use casscf=True.")683obi, tbi, core_energy, ferm_ham = generate_molecular_spin_ham_restricted(684h1e_cas, h2e_cas, ecore)685686# `Dump obi and tbi to binary file.`687#`obi.astype(complex).tofile(f'{filename}_one_body.dat')`688#`tbi.astype(complex).tofile(f'{filename}_two_body.dat')`689690dm = mcscf.make_rdm1(mycas)691# Compute the PE contribution to the Hamiltonian692mype = PolEmbed(mol, potfile)693E_pe, V_pe, V_es, V_ind = mype.get_pe_contribution(dm)694#convert from `ao` to `mo`695V_pe_mo = reduce(np.dot, (mycas.mo_coeff.T, V_pe, mycas.mo_coeff))696697V_pe_cas = V_pe_mo[mycas.ncore:mycas.ncore + mycas.ncas,698mycas.ncore:mycas.ncore + mycas.ncas]699obi_pe = generate_pe_spin_ham_restricted(V_pe_cas)700#`obi_pe.astype(complex).tofile(f'{filename}_pe_one_body.dat')`701702#`metadata = {'num_electrons':nele_cas, 'num_orbitals':norb_cas, 'core_energy':ecore, 'PE_energy':E_pe,'HF_energy':mf_pe.e_tot}`703#`with open(f'{filename}_metadata.json', 'w') as f:`704#` json.dump(metadata, f)`705706return (obi, tbi, ecore, obi_pe, nele_cas, norb_cas, ferm_ham)707708else:709mc = mcscf.CASCI(mf_pe, norb_cas, nele_cas)710h1e_cas, ecore = mc.get_h1eff(mf_pe.mo_coeff)711h2e_cas = mc.get_h2eff(mf_pe.mo_coeff)712h2e_cas = ao2mo.restore('1', h2e_cas, norb_cas)713h2e_cas = np.asarray(h2e_cas.transpose(0, 2, 3, 1), order='C')714obi, tbi, core_energy, ferm_ham = generate_molecular_spin_ham_restricted(715h1e_cas, h2e_cas, ecore)716717#` Dump obi and tbi to binary file.`718#`obi.astype(complex).tofile(f'{filename}_one_body.dat')`719#`tbi.astype(complex).tofile(f'{filename}_two_body.dat')`720721dm = mf_pe.make_rdm1()722# Compute the PE contribution to the Hamiltonian723mype = PolEmbed(mol, potfile)724E_pe, V_pe, V_es, V_ind = mype.get_pe_contribution(dm)725#convert from `ao` to `mo`726V_pe_mo = reduce(np.dot, (mf_pe.mo_coeff.T, V_pe, mf_pe.mo_coeff))727728V_pe_cas = V_pe_mo[mc.ncore:mc.ncore + mc.ncas,729mc.ncore:mc.ncore + mc.ncas]730obi_pe = generate_pe_spin_ham_restricted(V_pe_cas)731#`obi_pe.astype(complex).tofile(f'{filename}_pe_one_body.dat')`732733#`metadata = {'num_electrons':nele_cas, 'num_orbitals':norb_cas, 'core_energy':ecore, 'PE_energy':E_pe,'HF_energy':mf_pe.e_tot}`734#`with open(f'{filename}_metadata.json', 'w') as f:`735#` json.dump(metadata, f)`736737return (obi, tbi, ecore, obi_pe, nele_cas, norb_cas, ferm_ham)738739740