def test_label_orb_symm(self): l = addons.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, mf.mo_coeff) lab0 = [ 'A1', 'A1', 'B1', 'A1', 'B2', 'A1', 'B1', 'B1', 'A1', 'A1', 'B2', 'B1', 'A1', 'A2', 'B2', 'A1', 'B1', 'B1', 'A1', 'B2', 'A2', 'A1', 'A1', 'B1' ] self.assertEqual(list(l), lab0)
def test_label_orb_symm(self): l = addons.label_orb_symm(mol, mol.irrep_name, mol.symm_orb, mf.mo_coeff) lab0 = ['A1', 'A1', 'B1', 'A1', 'B2', 'A1', 'B1', 'B1', 'A1', 'A1', 'B2', 'B1', 'A1', 'A2', 'B2', 'A1', 'B1', 'B1', 'A1', 'B2', 'A2', 'A1', 'A1', 'B1'] self.assertEqual(l, lab0)
def solve (frag, guess_1RDM, chempot_imp): # Augment OEI with the chemical potential OEI = frag.impham_OEI_C - chempot_imp # Do I need to get the full RHF solution? guess_orbs_av = len (frag.imp_cache) == 2 or frag.norbs_as > 0 # Get the RHF solution mol = gto.Mole() abs_2MS = int (round (2 * abs (frag.target_MS))) abs_2S = int (round (2 * abs (frag.target_S))) sign_MS = int (np.sign (frag.target_MS)) or 1 mol.spin = abs_2MS mol.verbose = 0 if frag.mol_stdout is None: mol.output = frag.mol_output mol.verbose = 0 if frag.mol_output is None else lib.logger.DEBUG mol.atom.append(('H', (0, 0, 0))) mol.nelectron = frag.nelec_imp if frag.enforce_symmetry: mol.groupname = frag.symmetry mol.symm_orb = get_subspace_symmetry_blocks (frag.loc2imp, frag.loc2symm) mol.irrep_name = frag.ir_names mol.irrep_id = frag.ir_ids mol.max_memory = frag.ints.max_memory mol.build () if frag.mol_stdout is None: frag.mol_stdout = mol.stdout else: mol.stdout = frag.mol_stdout mol.verbose = 0 if frag.mol_output is None else lib.logger.DEBUG if frag.enforce_symmetry: mol.symmetry = True #mol.incore_anyway = True mf = scf.RHF(mol) mf.get_hcore = lambda *args: OEI mf.get_ovlp = lambda *args: np.eye(frag.norbs_imp) mf.energy_nuc = lambda *args: frag.impham_CONST if frag.impham_CDERI is not None: mf = mf.density_fit () mf.with_df._cderi = frag.impham_CDERI else: mf._eri = ao2mo.restore(8, frag.impham_TEI, frag.norbs_imp) mf = fix_my_RHF_for_nonsinglet_env (mf, frag.impham_OEI_S) mf.__dict__.update (frag.mf_attr) if guess_orbs_av: mf.max_cycle = 2 mf.scf (guess_1RDM) if (not mf.converged) and (not guess_orbs_av): if np.any (np.abs (frag.impham_OEI_S) > 1e-8) and mol.spin != 0: raise NotImplementedError('Gradient and Hessian fixes for nonsinglet environment of Newton-descent ROHF algorithm') print ("CASSCF RHF-step not converged on fixed-point iteration; initiating newton solver") mf = mf.newton () mf.kernel () # Instability check and repeat if not guess_orbs_av: for i in range (frag.num_mf_stab_checks): if np.any (np.abs (frag.impham_OEI_S) > 1e-8) and mol.spin != 0: raise NotImplementedError('ROHF stability-check fixes for nonsinglet environment') mf.mo_coeff = mf.stability ()[0] guess_1RDM = mf.make_rdm1 () mf = scf.RHF(mol) mf.get_hcore = lambda *args: OEI mf.get_ovlp = lambda *args: np.eye(frag.norbs_imp) mf._eri = ao2mo.restore(8, frag.impham_TEI, frag.norbs_imp) mf = fix_my_RHF_for_nonsinglet_env (mf, frag.impham_OEI_S) mf.scf (guess_1RDM) if not mf.converged: mf = mf.newton () mf.kernel () E_RHF = mf.e_tot print ("CASSCF RHF-step energy: {}".format (E_RHF)) # Get the CASSCF solution CASe = frag.active_space[0] CASorb = frag.active_space[1] checkCAS = (CASe <= frag.nelec_imp) and (CASorb <= frag.norbs_imp) if (checkCAS == False): CASe = frag.nelec_imp CASorb = frag.norbs_imp if (abs_2MS > abs_2S): CASe = ((CASe + sign_MS * abs_2S) // 2, (CASe - sign_MS * abs_2S) // 2) else: CASe = ((CASe + sign_MS * abs_2MS) // 2, (CASe - sign_MS * abs_2MS) // 2) if frag.impham_CDERI is not None: mc = mcscf.DFCASSCF(mf, CASorb, CASe) else: mc = mcscf.CASSCF(mf, CASorb, CASe) smult = abs_2S + 1 if frag.target_S is not None else (frag.nelec_imp % 2) + 1 mc.fcisolver = csf_solver (mf.mol, smult, symm=frag.enforce_symmetry) if frag.enforce_symmetry: mc.fcisolver.wfnsym = frag.wfnsym mc.max_cycle_macro = 50 if frag.imp_maxiter is None else frag.imp_maxiter mc.conv_tol = min (1e-9, frag.conv_tol_grad**2) mc.ah_start_tol = mc.conv_tol / 10 mc.ah_conv_tol = mc.conv_tol / 10 mc.__dict__.update (frag.corr_attr) mc = fix_my_CASSCF_for_nonsinglet_env (mc, frag.impham_OEI_S) norbs_amo = mc.ncas norbs_cmo = mc.ncore norbs_imo = frag.norbs_imp - norbs_amo nelec_amo = sum (mc.nelecas) norbs_occ = norbs_amo + norbs_cmo #mc.natorb = True # Guess orbitals ci0 = None dm_imp = frag.get_oneRDM_imp () fock_imp = mf.get_fock (dm=dm_imp) if len (frag.imp_cache) == 2: imp2mo, ci0 = frag.imp_cache print ("Taking molecular orbitals and ci vector from cache") elif frag.norbs_as > 0: nelec_imp_guess = int (round (np.trace (frag.oneRDMas_loc))) norbs_cmo_guess = (frag.nelec_imp - nelec_imp_guess) // 2 print ("Projecting stored amos (frag.loc2amo; spanning {} electrons) onto the impurity basis and filling the remainder with default guess".format (nelec_imp_guess)) imp2mo, my_occ = project_amo_manually (frag.loc2imp, frag.loc2amo, fock_imp, norbs_cmo_guess, dm=frag.oneRDMas_loc) elif frag.loc2amo_guess is not None: print ("Projecting stored amos (frag.loc2amo_guess) onto the impurity basis (no amo dm available)") imp2mo, my_occ = project_amo_manually (frag.loc2imp, frag.loc2amo_guess, fock_imp, norbs_cmo, dm=None) frag.loc2amo_guess = None else: dm_imp = np.asarray (mf.make_rdm1 ()) while dm_imp.ndim > 2: dm_imp = dm_imp.sum (0) imp2mo = mf.mo_coeff fock_imp = mf.get_fock (dm=dm_imp) fock_mo = represent_operator_in_basis (fock_imp, imp2mo) _, evecs = matrix_eigen_control_options (fock_mo, sort_vecs=1) imp2mo = imp2mo @ evecs my_occ = ((dm_imp @ imp2mo) * imp2mo).sum (0) print ("No stored amos; using mean-field canonical MOs as initial guess") # Guess orbital processing if callable (frag.cas_guess_callback): mo = reduce (np.dot, (frag.ints.ao2loc, frag.loc2imp, imp2mo)) mo = frag.cas_guess_callback (frag.ints.mol, mc, mo) imp2mo = reduce (np.dot, (frag.imp2loc, frag.ints.ao2loc.conjugate ().T, frag.ints.ao_ovlp, mo)) frag.cas_guess_callback = None # Guess CI vector if len (frag.imp_cache) != 2 and frag.ci_as is not None: loc2amo_guess = np.dot (frag.loc2imp, imp2mo[:,norbs_cmo:norbs_occ]) metric = np.arange (CASorb) + 1 gOc = np.dot (loc2amo_guess.conjugate ().T, (frag.ci_as_orb * metric[None,:])) umat_g, svals, umat_c = matrix_svd_control_options (gOc, sort_vecs=1, only_nonzero_vals=True) if (svals.size == norbs_amo): print ("Loading ci guess despite shifted impurity orbitals; singular value error sum: {}".format (np.sum (svals - metric))) imp2mo[:,norbs_cmo:norbs_occ] = np.dot (imp2mo[:,norbs_cmo:norbs_occ], umat_g) ci0 = transform_ci_for_orbital_rotation (frag.ci_as, CASorb, CASe, umat_c) else: print ("Discarding stored ci guess because orbitals are too different (missing {} nonzero svals)".format (norbs_amo-svals.size)) # Symmetry align if possible imp2unac = frag.align_imporbs_symm (np.append (imp2mo[:,:norbs_cmo], imp2mo[:,norbs_occ:], axis=1), sorting_metric=fock_imp, sort_vecs=1, orbital_type='guess unactive', mol=mol)[0] imp2mo[:,:norbs_cmo] = imp2unac[:,:norbs_cmo] imp2mo[:,norbs_occ:] = imp2unac[:,norbs_cmo:] #imp2mo[:,:norbs_cmo] = frag.align_imporbs_symm (imp2mo[:,:norbs_cmo], sorting_metric=fock_imp, sort_vecs=1, orbital_type='guess inactive', mol=mol)[0] imp2mo[:,norbs_cmo:norbs_occ], umat = frag.align_imporbs_symm (imp2mo[:,norbs_cmo:norbs_occ], sorting_metric=fock_imp, sort_vecs=1, orbital_type='guess active', mol=mol) #imp2mo[:,norbs_occ:] = frag.align_imporbs_symm (imp2mo[:,norbs_occ:], sorting_metric=fock_imp, sort_vecs=1, orbital_type='guess external', mol=mol)[0] if frag.enforce_symmetry: imp2mo = cleanup_subspace_symmetry (imp2mo, mol.symm_orb) err_symm = measure_subspace_blockbreaking (imp2mo, mol.symm_orb) err_orth = measure_basis_nonorthonormality (imp2mo) print ("Initial symmetry error after cleanup = {}".format (err_symm)) print ("Initial orthonormality error after cleanup = {}".format (err_orth)) if ci0 is not None: ci0 = transform_ci_for_orbital_rotation (ci0, CASorb, CASe, umat) # Guess orbital printing if frag.mfmo_printed == False and frag.ints.mol.verbose: ao2mfmo = reduce (np.dot, [frag.ints.ao2loc, frag.loc2imp, imp2mo]) print ("Writing {} {} orbital molden".format (frag.frag_name, 'CAS guess')) molden.from_mo (frag.ints.mol, frag.filehead + frag.frag_name + '_mfmorb.molden', ao2mfmo, occ=my_occ) frag.mfmo_printed = True elif len (frag.active_orb_list) > 0: # This is done AFTER everything else so that the _mfmorb.molden always has consistent ordering print('Applying caslst: {}'.format (frag.active_orb_list)) imp2mo = mc.sort_mo(frag.active_orb_list, mo_coeff=imp2mo) frag.active_orb_list = [] if len (frag.frozen_orb_list) > 0: mc.frozen = copy.copy (frag.frozen_orb_list) print ("Applying frozen-orbital list (this macroiteration only): {}".format (frag.frozen_orb_list)) frag.frozen_orb_list = [] if frag.enforce_symmetry: imp2mo = lib.tag_array (imp2mo, orbsym=label_orb_symm (mol, mol.irrep_id, mol.symm_orb, imp2mo, s=mf.get_ovlp (), check=False)) t_start = time.time() E_CASSCF = mc.kernel(imp2mo, ci0)[0] if (not mc.converged) and np.all (np.abs (frag.impham_OEI_S) < 1e-8): mc = mc.newton () E_CASSCF = mc.kernel(mc.mo_coeff, mc.ci)[0] if not mc.converged: print ('Assuming ci vector is poisoned; discarding...') imp2mo = mc.mo_coeff.copy () mc = mcscf.CASSCF(mf, CASorb, CASe) smult = abs_2S + 1 if frag.target_S is not None else (frag.nelec_imp % 2) + 1 mc.fcisolver = csf_solver (mf.mol, smult) E_CASSCF = mc.kernel(imp2mo)[0] if not mc.converged: if np.any (np.abs (frag.impham_OEI_S) > 1e-8): raise NotImplementedError('Gradient and Hessian fixes for nonsinglet environment of Newton-descent CASSCF algorithm') mc = mc.newton () E_CASSCF = mc.kernel(mc.mo_coeff, mc.ci)[0] assert (mc.converged) ''' mc.conv_tol = 1e-12 mc.ah_start_tol = 1e-10 mc.ah_conv_tol = 1e-12 E_CASSCF = mc.kernel(mc.mo_coeff, mc.ci)[0] if not mc.converged: mc = mc.newton () E_CASSCF = mc.kernel(mc.mo_coeff, mc.ci)[0] #assert (mc.converged) ''' # Get twoRDM + oneRDM. cs: MC-SCF core, as: MC-SCF active space # I'm going to need to keep some representation of the active-space orbitals # Symmetry align if possible oneRDM_amo, twoRDM_amo = mc.fcisolver.make_rdm12 (mc.ci, mc.ncas, mc.nelecas) fock_imp = mc.get_fock () mc.mo_coeff[:,:norbs_cmo] = frag.align_imporbs_symm (mc.mo_coeff[:,:norbs_cmo], sorting_metric=fock_imp, sort_vecs=1, orbital_type='optimized inactive', mol=mol)[0] mc.mo_coeff[:,norbs_cmo:norbs_occ], umat = frag.align_imporbs_symm (mc.mo_coeff[:,norbs_cmo:norbs_occ], sorting_metric=oneRDM_amo, sort_vecs=-1, orbital_type='optimized active', mol=mol) mc.mo_coeff[:,norbs_occ:] = frag.align_imporbs_symm (mc.mo_coeff[:,norbs_occ:], sorting_metric=fock_imp, sort_vecs=1, orbital_type='optimized external', mol=mol)[0] if frag.enforce_symmetry: amo2imp = mc.mo_coeff[:,norbs_cmo:norbs_occ].conjugate ().T mc.mo_coeff = cleanup_subspace_symmetry (mc.mo_coeff, mol.symm_orb) umat = umat @ (amo2imp @ mc.mo_coeff[:,norbs_cmo:norbs_occ]) err_symm = measure_subspace_blockbreaking (mc.mo_coeff, mol.symm_orb) err_orth = measure_basis_nonorthonormality (mc.mo_coeff) print ("Final symmetry error after cleanup = {}".format (err_symm)) print ("Final orthonormality error after cleanup = {}".format (err_orth)) mc.ci = transform_ci_for_orbital_rotation (mc.ci, CASorb, CASe, umat) # Cache stuff imp2mo = mc.mo_coeff #mc.cas_natorb()[0] loc2mo = np.dot (frag.loc2imp, imp2mo) imp2amo = imp2mo[:,norbs_cmo:norbs_occ] loc2amo = loc2mo[:,norbs_cmo:norbs_occ] frag.imp_cache = [mc.mo_coeff, mc.ci] frag.ci_as = mc.ci frag.ci_as_orb = loc2amo.copy () t_end = time.time() # oneRDM oneRDM_imp = mc.make_rdm1 () # twoCDM oneRDM_amo, twoRDM_amo = mc.fcisolver.make_rdm12 (mc.ci, mc.ncas, mc.nelecas) oneRDMs_amo = np.stack (mc.fcisolver.make_rdm1s (mc.ci, mc.ncas, mc.nelecas), axis=0) oneSDM_amo = oneRDMs_amo[0] - oneRDMs_amo[1] if frag.target_MS >= 0 else oneRDMs_amo[1] - oneRDMs_amo[0] oneSDM_imp = represent_operator_in_basis (oneSDM_amo, imp2amo.conjugate ().T) print ("Norm of spin density: {}".format (linalg.norm (oneSDM_amo))) # Note that I do _not_ do the *real* cumulant decomposition; I do one assuming oneSDM_amo = 0. # This is fine as long as I keep it consistent, since it is only in the orbital gradients for this impurity that # the spin density matters. But it has to stay consistent! twoCDM_amo = get_2CDM_from_2RDM (twoRDM_amo, oneRDM_amo) twoCDM_imp = represent_operator_in_basis (twoCDM_amo, imp2amo.conjugate ().T) print('Impurity CASSCF energy (incl chempot): {}; spin multiplicity: {}; time to solve: {}'.format (E_CASSCF, spin_square (mc)[1], t_end - t_start)) # Active-space RDM data frag.oneRDMas_loc = symmetrize_tensor (represent_operator_in_basis (oneRDM_amo, loc2amo.conjugate ().T)) frag.oneSDMas_loc = symmetrize_tensor (represent_operator_in_basis (oneSDM_amo, loc2amo.conjugate ().T)) frag.twoCDMimp_amo = twoCDM_amo frag.loc2mo = loc2mo frag.loc2amo = loc2amo frag.E2_cum = np.tensordot (ao2mo.restore (1, mc.get_h2eff (), mc.ncas), twoCDM_amo, axes=4) / 2 frag.E2_cum += (mf.get_k (dm=oneSDM_imp) * oneSDM_imp).sum () / 4 # The second line compensates for my incorrect cumulant decomposition. Anything to avoid changing the checkpoint files... # General impurity data frag.oneRDM_loc = frag.oneRDMfroz_loc + symmetrize_tensor (represent_operator_in_basis (oneRDM_imp, frag.imp2loc)) frag.oneSDM_loc = frag.oneSDMfroz_loc + frag.oneSDMas_loc frag.twoCDM_imp = None # Experiment: this tensor is huge. Do I actually need to keep it? In principle, of course not. frag.E_imp = E_CASSCF + np.einsum ('ab,ab->', chempot_imp, oneRDM_imp) return None