def test_matched_rmsd(): geom1 = geom_from_xyz_file(THIS_DIR / "eins.xyz") # Calling with the identical geometries should return RMSD of 0. min_rmsd, (geom1_matched, geom2_matched) = matched_rmsd(geom1, geom1) np.testing.assert_allclose(min_rmsd, 0.0, atol=1e-10) np.testing.assert_allclose(geom1_matched.coords, geom2_matched.coords) geom2 = geom_from_xyz_file(THIS_DIR / "zwei.xyz") min_rmsd, _ = matched_rmsd(geom1, geom2) np.testing.assert_allclose(min_rmsd, 0.057049, atol=1e-5)
def test_redund(): initial = geom_from_xyz_file("bare_split.image_000.xyz", coord_type="redund") final = geom_from_xyz_file("bare_split.image_056.xyz", coord_type="redund") from pysisyphus.interpolate.helpers import interpolate_all geoms = interpolate_all((initial, final), 18, kind="redund", align=True) out_fn = "dlc_interpolate.trj" write_geoms_to_trj(geoms, out_fn) print("Wrote ", out_fn)
def test_idpp(): # initial = geom_from_library("dipeptide_init.xyz") # final = geom_from_library("dipeptide_fin.xyz") initial = geom_from_xyz_file("09_htransfer_product.xyz") final = geom_from_xyz_file("10_po_diss_product_xtbopt.xyz") geoms = (initial, final) idpp = IDPP(geoms, 18, align=True) geoms = idpp.interpolate_all() idpp.all_geoms_to_trj("idpp_opt.trj")
def make_N_init_dict(): THIS_DIR = Path(os.path.abspath(os.path.dirname(__file__))) xyz_path = THIS_DIR / "../../xyz_files/baker_ts" xyzs = natsorted(xyz_path.glob("*.xyz")) N_dict = dict() for guess, initial in [xyzs[2*i:2*i+2] for i in range(25)]: assert "downhill" in initial.stem assert guess.stem[:2] == initial.stem[:2] guess_geom = geom_from_xyz_file(guess) initial_geom = geom_from_xyz_file(initial) N_init = guess_geom.coords - initial_geom.coords N_dict[guess.name] = N_init return N_dict
def test_h2o_wfoverlap(): path1 = THIS_DIR / "h2o1_wfoverlap" path2 = THIS_DIR / "h2o2_wfoverlap" geom1 = geom_from_xyz_file(path1 / "h2o1.xyz") geom2 = geom_from_xyz_file(path2 / "h2o2.xyz") turbo = Turbomole(path1) get_mos_ciss = lambda path: (str(path / "mos"), str(path / "ciss_a")) mos1, ciss1 = get_mos_ciss(path1) mos2, ciss2 = get_mos_ciss(path2) turbo.td_vec_fn = ciss1 turbo.mos = mos1 turbo.td_vec_fn = ciss2 turbo.mos = mos2
def turbo_comp(): calc_kwargs = { "xc": "pbe", "method": "tddft", "basis": "def2-SVP", "pal": 4, "nstates": 2, "root": 1, "track": True, } pyscf_ = PySCF(**calc_kwargs) geom = geom_from_xyz_file("cytosin.xyz") geom.set_calculator(pyscf_) f = geom.forces.reshape(-1, 3) print("pyscf") print(f.reshape(-1, 3)) ref_geom = geom.copy() turbo_kwargs = { "control_path": "/scratch/turbontos/control_pbe_clean", "track": True, "ovlp_type": "wf", "ovlp_with": "first", "pal": 4, } turbo = Turbomole(**turbo_kwargs) ref_geom.set_calculator(turbo) f_ref = ref_geom.forces print("Turbo") print(f_ref.reshape(-1, 3))
def test_h2o2_opt(): xyz_fn = "h2o2_hf_def2svp_opt.xyz" geom = geom_from_xyz_file(xyz_fn, coord_type="redund") cart_H_fn = "h2o2_opt_cart.hessian" xyz_path = Path(xyz_fn) H_fn = xyz_path.with_suffix(".hessian") cart_forces_fn = "h2o2_opt_cart.forces" calc_kwargs = { "method": "HF", "basis": "def2-svp", "charge": 0, "mult": 1, "pal": 4, } calc = Psi4(**calc_kwargs) geom.set_calculator(calc) cart_H = np.loadtxt(cart_H_fn) cart_f = np.loadtxt(cart_forces_fn) geom._forces = cart_f geom._hessian = cart_H import pdb pdb.set_trace() H = geom.hessian np.savetxt(H_fn, H) np.savetxt(cart_H_fn, geom._hessian) np.savetxt(cart_forces_fn, geom._forces) print(f"Wrote hessian of '{xyz_fn}' to '{H_fn}'")
def test_forces(): geom = geom_from_xyz_file(THIS_DIR / "h2o.xyz") control_path = THIS_DIR / "h2o_forces" turbo = Turbomole(control_path) geom.set_calculator(turbo) forces = geom.forces ref_forces = -np.loadtxt("h2o_gradient.ref") np.testing.assert_allclose(forces, ref_forces, atol=1e-8)
def run(): fn = "07_ref_rx_phosphine_def2tzvp_reopt.xyz" geom = geom_from_xyz_file(fn) bm = get_bond_mat(geom) print(bm) node_attrs = {i: {"atom": atom} for i, atom in enumerate(geom.atoms)} g = nx.from_numpy_array(bm) nx.set_node_attributes(g, node_attrs) # import pdb; pdb.set_trace() # fig, ax = plt.subplots() # draw_kwargs = { # "ax": ax, # "with_labels": True, # "node_size": 250, # } # nx.draw(g, labels=get_labels(geom), **draw_kwargs) # plt.show() prod_fn = "01_ref_rx_product_opt.xyz" prod = geom_from_xyz_file(prod_fn) pbm = get_bond_mat(prod) gp = nx.from_numpy_array(pbm) pnode_attrs = {i: {"atom": atom} for i, atom in enumerate(prod.atoms)} nx.set_node_attributes(gp, pnode_attrs) # fig, ax = plt.subplots() # draw_kwargs["ax"] = ax # nx.draw(gp, labels=get_labels(prod), **draw_kwargs) # plt.show() gm = isomorphism.GraphMatcher(gp, g) si = gm.subgraph_is_isomorphic() sims = list(gm.subgraph_isomorphisms_iter()) llens = [len(_) for _ in sims] pprint(sims) print(llens) ms = [i for i, d in enumerate(sims) if all([i == j for i, j in d.items()])] mapping = sims[ms[0]] pprint(mapping) # import pdb; pdb.set_trace() # for mapping in sims: # import pdb; pdb.set_trace() pass
def test_wfo_ref(): in_path = THIS_DIR / "butadiene_twist" geom = geom_from_xyz_file(in_path / "02_buta_twist.xyz") turbo = Turbomole(in_path, track=True, wfo_basis="def2-svp") geom.set_calculator(turbo) opt_kwargs = { "max_cycles": 2, "dump": True, } opt = SteepestDescent(geom, **opt_kwargs) opt.run()
def test_wfo_compare_neon(): in_path = THIS_DIR / "neon" geom = geom_from_xyz_file(in_path / "neon.xyz") turbo = Turbomole(in_path, track=True, wfo_basis="def2-svp") geom.set_calculator(turbo) opt_kwargs = { "max_cycles": 1, "dump": True, } opt = SteepestDescent(geom, **opt_kwargs) opt.run() wfow = turbo.wfow wfow.compare(wfow)
def parse_opt(self, path, keep_log=False): xtbopt = path / "xtbopt.xyz" if not xtbopt.exists(): self.log(f"{self.calc_number:03d} failed") return None opt_geom = geom_from_xyz_file(xtbopt) opt_geom.energy = self.parse_energy(path) opt_log = None if keep_log: opt_log = geoms_from_trj(path / "xtbopt.log") opt_result = OptResult(opt_geom=opt_geom, opt_log=opt_log) return opt_result
def test_wfo_compare_sto3g(): in_path = THIS_DIR / "butadiene_twist_sto3g" geom = geom_from_xyz_file(in_path / "02_buta_twist.xyz") turbo = Turbomole(in_path, track=True, wfo_basis="sto-3g") geom.set_calculator(turbo) opt_kwargs = { "max_cycles": 1, "dump": True, } opt = SteepestDescent(geom, **opt_kwargs) opt.run() wfow = turbo.wfow wfow.compare(wfow)
def test_wfo_compare_butadiene_cc2_sto3g(): in_path = THIS_DIR / "butadiene_cc2_sto3g" geom = geom_from_xyz_file(in_path / "buta.xyz") turbo = Turbomole(in_path, track=True, wfo_basis="sto3g") geom.set_calculator(turbo) # opt_kwargs = { # "max_cycles": 1, # "dump": True, # } # opt = SteepestDescent(geom, **opt_kwargs) # opt.run() turbo.run_calculation(geom.atoms, geom.coords) wfow = turbo.wfow wfow.compare(wfow)
def test_do_final_hessian(data_dir): fn = data_dir / "final_geometry.xyz" geom = geom_from_xyz_file(fn, coord_type="redund") calc = ORCA("") grad = np.load(data_dir / "grad.npy") hess = np.load(data_dir / "hess.npy") geom.hessian = hess geom.gradient = grad res = do_final_hessian(geom, save_hessian=False) neg_eigvals = res.neg_eigvals assert len(neg_eigvals) == 1 np.testing.assert_allclose(neg_eigvals[0], -0.00224392407)
def test_wfo_compare_neon_dimer(): in_path = THIS_DIR / "neon_dimer" geom = geom_from_xyz_file(in_path / "neon_dimer.xyz") turbo = Turbomole(in_path, track=True, wfo_basis="def2-svp") geom.set_calculator(turbo) opt_kwargs = { "max_cycles": 5, "dump": True, "track": True, # "convergence": { # "max_force_thresh": 2.5e-8, # } } opt = SteepestDescent(geom, **opt_kwargs) #import pdb; pdb.set_trace() opt.run()
def test_fragmentation(): fn = "01_dihedral_scan.009.xyz" geom = geom_from_xyz_file(fn, coord_type="redund") prim_coord = (19, 20) bbis = geom.internal.bare_bond_indices.tolist() _ = bbis.copy() bbis.remove(list(sorted(prim_coord))) import pdb pdb.set_trace() # bbis.delete( frag_kwargs = { "step": 6, "step_num": 10, } cc = fragment(geom, prim_coord, **frag_kwargs) cc = np.reshape(cc, (-1, len(geom.atoms), 3)) * BOHR2ANG trj_str = make_trj_str(geom.atoms, cc) with open("fragmented.xyz", "w") as handle: handle.write(trj_str)
def test_butadiene_track_opt(): in_path = THIS_DIR / "butadiene" geom = geom_from_xyz_file(in_path / "butadiene_hf_sto3g.xyz") turbo = Turbomole(in_path, track=True, wfo_basis="def2-svp") geom.set_calculator(turbo) #fn = "/scratch/programme/pysisyphus/tests/test_turbo_butadien_td_opt/wfo_backup.out" #with open(fn) as handle: # stdout = handle.read() #wfo = turbo.wfow #a = wfo.parse_wfoverlap_out(stdout) #print(a) #print(a.reshape(-1, 6)) opt_kwargs = { "max_cycles": 10, "dump": True, } opt = ConjugateGradient(geom, **opt_kwargs) opt = SteepestDescent(geom, **opt_kwargs) opt.run()
def test_base(xyz_fn): try: geom = geom_from_library(xyz_fn, coord_type="redund") except FileNotFoundError: geom = geom_from_xyz_file(xyz_fn, coord_type="redund") import pdb pdb.set_trace() calc_kwargs = { # "route": "HF/3-21G", "route": "B3LYP/6-31G*", "charge": 0, "mult": 1, "pal": 4, } calc = Gaussian16(**calc_kwargs) geom.set_calculator(calc) H = geom.hessian xyz_path = Path(xyz_fn) H_fn = xyz_path.with_suffix(".hessian") np.savetxt(H_fn, H) print(f"Wrote hessian of '{xyz_fn}' to '{H_fn}'")
def test_molcas_s1_opt(): """ Optimization of the S1 of trans-Butadien Spent 23.6 s preparing the first cycle. cycle max(force) rms(force) max(step) rms(step) s/cycle 1 0.072748 0.033504 0.040000 0.019036 26.0 2 0.020289 0.008667 0.040000 0.017887 25.1 3 0.011788 0.005995 0.016634 0.007007 25.2 4 0.010659 0.005249 0.005894 0.002998 25.3 5 0.007637 0.003809 0.020000 0.009861 24.9 Number of cycles exceeded! """ path = Path(os.path.dirname(os.path.abspath(__file__))) xyz_fn = path / "trans_butadien.xyz" inporb_fn = path / "butadien_vdzp.RasOrb" geom = geom_from_xyz_file(xyz_fn) kwargs = { "basis": "ano-rcc-vdzp", "inporb": inporb_fn, "charge": 0, "mult": 1, "roots": 5, "mdrlxroot": 2, } calc = OpenMolcas(**kwargs) geom.set_calculator(calc) opt_kwargs = { "dump": True, "max_cycles": 5, } opt = BFGS(geom, **opt_kwargs) opt.run() assert opt.max_forces[-1] == pytest.approx(0.0076367199999) assert opt.rms_forces[-1] == pytest.approx(0.0038088424813)
def run(): # geom = AnaPot.get_geom((-0.366, 2.03, 0)) # H = geom.mw_hessian # geom = geom_from_xyz_file("azetidine_guess.xyz", coord_type="redund") geom = geom_from_xyz_file("azetidine_guess.xyz") geom.set_calculator(XTB()) # H = geom.mw_hessian # H = geom.hessian H = geom.get_initial_hessian() import pdb pdb.set_trace() M = geom.mm_sqrt_inv trust = 0.8 max_cycles = 75 steps = list() gradients = list() coords = list() energies = list() pred_changes = list() trj = open("opt.trj", "w") for i in range(max_cycles): coords.append(geom.coords.copy()) trj.write(geom.as_xyz() + "\n") g = geom.gradient gradients.append(g) energies.append(geom.energy) if i > 0: last_step_norm = np.linalg.norm(steps[-1]) pred = pred_changes[-1] actual = energies[-1] - energies[-2] # predicted will be defined when i > 0 coeff = predicted / actual # noqa: F821 trust = update_trust_radius(trust, coeff, last_step_norm) # Hess update dg = gradients[-1] - gradients[-2] dx = steps[-1] # dH, _ = bfgs_update(H, dx, dg) dH, _ = flowchart_update(H, dx, dg) H = H + dH # H = geom.hessian # Convert gradient to normal mode gradient # cart_step = rfo(g, H, trust=trust) # eigvals, eigvecsT = np.linalg.eigh(H) # gq = eigvecsT.T.dot(g) # H_diag = np.diag(eigvals) # # Convert gradient to normal mode gradient # dq = rfo(gq, H_diag)#, trust=trust) # cart_step = eigvecsT.dot(dq) # norm = np.linalg.norm(cart_step) # if norm > trust: # cart_step = cart_step / norm * trust mwH = M.dot(H).dot(M) vm, vemT = np.linalg.eigh(mwH) S = M.dot(vemT) gqm = S.T.dot(g) Hm_diag = np.diag(vm) dqm = rfo(gqm, Hm_diag) cart_step = S.dot(dqm) norm = np.linalg.norm(cart_step) if norm > trust: cart_step = cart_step / norm * trust step_norm = np.linalg.norm(cart_step) # print(f"norm(step)={step_norm:.6f}") rms_g = rms(g) max_g = max_(g) rms_s = rms(cart_step) max_s = max_(cart_step) norm_g = np.linalg.norm(g) # print(f"Cycle {i:02d}: " # f"\tmax(grad)={max_g:.6f} rms(grad)={rms_g:.6f} " # f"max(step)={max_s:.6f} rms(step)={rms_s:.6f}") print( f"{i:02d}: {max_g:.6f} {rms_g:.6f} {max_s:.6f} {rms_s:.6f} {norm_g:.6f} {geom.energy:.6f} {trust:.6f}" ) converged = (max_g <= 4.5e-4) and (rms_g <= 3e-4) #\ # and (max_s <= 1.8e-3) and (rms_s <= 1.2e-3) if converged: print("Converged!") break steps.append(cart_step) new_coords = geom.coords + cart_step geom.coords = new_coords predicted = cart_step.dot(g) + 0.5 * cart_step.dot(H).dot(cart_step) pred_changes.append(predicted) print(f"Energy: {geom.energy:.8f}") pot = geom.calculator # pot.plot() # coords_arr = np.array(coords) # pot.ax.plot(coords_arr[:,0], coords_arr[:,1], "o-") # plt.show() trj.close()
def run(): geom = geom_from_xyz_file("03_00_water_addition_ts.xyz") geom.set_calculator(XTB(pal=4)) run_relaxations(geom, 1)
except KeyError: self.log("No .fchk file found!") return if self.track: self.dump_635r = kept_fns["dump_635r"] def get_chkfiles(self): return { "fchk": self.fchk, } def set_chkfiles(self, chkfiles): try: fchk = chkfiles["fchk"] self.fchk = fchk self.log(f"Set chkfile '{fchk}' as fchk.") except KeyError: self.log("Found no fchk information in chkfiles!") def __str__(self): return "Gaussian16 calculator" if __name__ == "__main__": from pysisyphus.helpers import geom_from_xyz_file geom = geom_from_xyz_file("/scratch/baker_ircs/15/15_hocl_ts_opt.xyz") g16 = Gaussian16(route="HF/3-21G", pal=4) geom.set_calculator(g16) hess = geom.hessian print(hess)
#!/usr/bin/env python3 from pysisyphus.calculators.Gaussian16 import Gaussian16 from pysisyphus.helpers import geom_from_library, geom_from_xyz_file, do_final_hessian # from pysisyphus.optimizers.ANCOptimizer import ANCOptimizer from pysisyphus.optimizers.NCOptimizer import NCOptimizer # geom = geom_from_library("azetidine_guess.xyz") # calc = Gaussian16("HF 4-31G", pal=4) # geom = geom_from_xyz_file("guess.xyz") #geom = geom_from_xyz_file("guess2.xyz") geom = geom_from_xyz_file("guess3.xyz") calc = Gaussian16("PM6", pal=4) # from pysisyphus.calculators.XTB import XTB # calc = XTB(pal=4) geom.set_calculator(calc) # opt = ANCOptimizer(geom, dump=True) opt_kwargs = { "dump": True, "hessian_init": "calc", "freeze_modes": 200, "max_cycles": 20, "prefix": "frozen_" } opt = NCOptimizer(geom, **opt_kwargs) opt.run() do_final_hessian(geom) # from pysisyphus.Geometry import Geometry # from pysisyphus.tsoptimizers.RSIRFOptimizer import RSIRFOptimizer
def run(): geom = geom_from_xyz_file("shaked.xyz") calc = XTB(pal=4) geom.set_calculator(calc) kill_modes(geom)
def test_freq_distort(): geom = geom_from_xyz_file("final_geometry.xyz") print(geom) # calc = ORCA("") # print(calc) # cwd = Path(".") # results = calc.parse_hessian(cwd) # print(results) # hess = results["hessian"] # np.save("hess", hess) # hess = np.load("hess.npy") hess = np.loadtxt("calculated_final_cart_hessian") # print("Non-mass-weighted") # w, v = np.linalg.eigh(hess) # nus = eigval_to_wavenumber(w) # neg_inds = w < 0 # print(w[neg_inds]) # print(nus[neg_inds]) # print("Mass-weighted") mw_hess = geom.mass_weigh_hessian(hess) # w, v = np.linalg.eigh(mw_hess) # nus = eigval_to_wavenumber(w) # neg_inds = w < 0 # print(w[neg_inds]) # print(nus[neg_inds]) # shaked = geom.copy() # shaked.coords = shake_coords(shaked.coords, scale=0.05, seed=25032018) # shaked.set_calculator(XTB(pal=4, base_name="shake")) # shess = shaked.hessian # sw, sv = np.linalg.eigh(shess) # with open("shaked.xyz", "w") as handle: # handle.write(shaked.as_xyz()) print("Eckart projected") proj_hess = geom.eckart_projection(mw_hess) w, v = np.linalg.eigh(proj_hess) nus = eigval_to_wavenumber(w) neg_inds = w < 0 print(w[neg_inds]) print(nus[neg_inds]) imag_mode = v[:, 0] print(imag_mode) lengths = np.linspace(-1, 1, 21) print(lengths) coords_list = list() M = np.sqrt(geom.masses_rep) for l in lengths: new_coords = (geom.mw_coords + l * imag_mode) / M coords_list.append(new_coords) coords_to_trj("displaced.trj", geom.atoms, coords_list) # calc = XTB(pal=4) # geom.set_calculator(calc) # energies = list() # for cs in coords_list: # geom.coords = cs # energy = geom.energy # energies.append(energy) # pass # print(energies) # energies = np.array(energies) # np.save("energies", energies) energies = np.load("energies.npy") energies -= energies.min() energies *= 2625.25 def func_harmonic(x, a, b, c): return a + b * (x + c)**2 fromto = 4 slice_ = slice(fromto, -fromto + 1) ydata = energies[slice_] xdata = np.arange(energies.size)[slice_] popt, pcov = curve_fit(func_harmonic, xdata, ydata) print("popt") print(popt) print("pcov") print(pcov) fig, ax = plt.subplots() ax.plot(energies, "o-", label="True") ax.plot(xdata, func_harmonic(xdata, *popt), "--", label="Harmonic") ax.legend() plt.show() pass
def func_harmonic(x, a, b, c): return a + b * (x + c)**2 fromto = 4 slice_ = slice(fromto, -fromto + 1) ydata = energies[slice_] xdata = np.arange(energies.size)[slice_] popt, pcov = curve_fit(func_harmonic, xdata, ydata) print("popt") print(popt) print("pcov") print(pcov) fig, ax = plt.subplots() ax.plot(energies, "o-", label="True") ax.plot(xdata, func_harmonic(xdata, *popt), "--", label="Harmonic") ax.legend() plt.show() pass if __name__ == "__main__": # test_freq_distort() # run() geom = geom_from_xyz_file("03_00_water_addition_ts.xyz") geom.set_calculator(XTB(pal=4)) # freq_distort(geom, 1) tmp(geom, 1)
def get_geom(): geom = geom_from_xyz_file(THIS_DIR / "benzene.xyz") return geom
def get_geoms(): benz = geom_from_xyz_file(THIS_DIR / "benzene.xyz") # Here the atom at index 3 was moved to index 5 benz_mod = geom_from_xyz_file(THIS_DIR / "benzene_mod.xyz") return benz, benz_mod
def discover_geometries(self, path): xyz_fns = natsorted(path.glob("*.xyz")) geoms = [geom_from_xyz_file(xyz_fn) for xyz_fn in xyz_fns] self.restore_calculators(geoms) return geoms