def test_artemisin(): # geom = geom_from_library("birkholz/artemisin.xyz", coord_type="redund") geom = geom_from_library("birkholz/artemisin.xyz") calc = XTB(charge=0, mult=1, pal=4) # geom = geom_from_library("birkholz/zn_edta.xyz", coord_type="redund") # geom = geom_from_library("birkholz/zn_edta.xyz") # calc = XTB(charge=-2, mult=1, pal=4) geom.set_calculator(calc) opt_kwargs_base = { "max_cycles": 50, # "max_cycles": 15, # "max_cycles": 8, "thresh": "gau", "trust_radius": 0.5, "trust_update": True, "hessian_update": "damped_bfgs", # "hessian_init": "fischer", "hessian_init": "calc", "hessian_recalc": 1, "line_search": True, # "hybrid": True, # "dump": True, } opt = RFOptimizer(geom, **opt_kwargs_base) opt.run() H = opt.H w, v = np.linalg.eigh(H) print(w)
def xtb_hessian(geom, gfn=None): calc = geom.calculator xtb_kwargs = {"charge": calc.charge, "mult": calc.mult, "pal": calc.pal} if gfn is not None: xtb_kwargs["gfn"] = gfn xtb_calc = XTB(**xtb_kwargs) geom_ = geom.copy() geom_.set_calculator(xtb_calc) return geom_.hessian
def test_gradient(): geom = geom_from_library("benzene.xyz") geom.set_calculator(XTB(gfn=1)) grad = geom.gradient reference_fn = THIS_DIR / "gradient.reference" reference = np.loadtxt(reference_fn) # Quite some difference between xTB 5.8 and 4.9.4 ... np.testing.assert_allclose(reference.flatten(), grad, rtol=1e-5)
def run_geom_opt(self, geom): if self.calc_getter is not None: calc = self.calc_getter(calc_number=self.calc_counter) geom.set_calculator(calc) opt_kwargs = { "gdiis": False, "thresh": "gau_loose", "overachieve_factor": 2, "max_cycles": 75, } opt = RFOptimizer(geom, **opt_kwargs) opt.run() opt_geom = geom if opt.is_converged else None else: calc = XTB(calc_number=self.calc_counter, **self.calc_kwargs) opt_result = calc.run_opt(geom.atoms, geom.coords, keep=False) opt_geom = opt_result.opt_geom self.calc_counter += 1 return opt_geom
def test_rsprfo_hcn_ts_xtb(): geom = geom_from_library("hcn_iso_ts.xyz", coord_type="redund") xtb = XTB() geom.set_calculator(xtb) opt_kwargs = { "thresh": "gau_tight", "max_micro_cycles": 1, } opt = RSPRFOptimizer(geom, **opt_kwargs) opt.run() assert opt.is_converged assert opt.cur_cycle == 7
def test_thermostat(): geom = geom_loader("lib:dynamics/10_water.xyz") from pysisyphus.calculators.XTB import XTB geom.set_calculator(XTB(pal=2)) opt = RFOptimizer(geom, thresh="gau_loose", max_cycles=25) opt.run() T = 298.15 seed = 20182503 v0 = get_mb_velocities_for_geom(geom, T, seed=seed).flatten() # steps = 6000 steps = 250 dt = 0.5 md_kwargs = { "v0": v0, "steps": steps, "dt": dt, "remove_com_v": True, "thermostat": "csvr", "timecon": 25, } res = md(geom, **md_kwargs) # assert dt * steps / 1000 == pytest.approx(res.t) import matplotlib.pyplot as plt E_tot = res.E_tot E_tot -= E_tot.mean() from pysisyphus.constants import AU2KJPERMOL E_tot *= AU2KJPERMOL T = res.T fig, (ax0, ax1) = plt.subplots(nrows=2) ax0.plot(E_tot) ax0.axhline(E_tot.mean()) ax0.set_title("$\Delta$E$_{tot}$ / kJ mol⁻¹") ax1.plot(T) T_mean = T.mean() print("T_mean", T_mean, "K") ax1.axhline(T_mean) ax1.set_title(f"T / K, avg. = {T_mean:.2f} K") plt.tight_layout() plt.show() fig.savefig("md.pdf")
def test_sqnm_bio_mode(): atoms = "h h".split() coords = ((0, 0, 0), (0, 0, 1)) geom = Geometry(atoms, coords) xtb = XTB() geom.set_calculator(xtb) opt = StabilizedQNMethod(geom) cur_grad = geom.gradient stretch_grad, rem_grad = opt.bio_mode(cur_grad) # There is only one bond in H2, so stretch_gradient == cur_grad and the # remainder should be the zero vector. np.testing.assert_allclose(stretch_grad, cur_grad) np.testing.assert_allclose(np.linalg.norm(rem_grad), 0.) return
def test_sqnm_xtb(): geom = geom_from_library("split.image_021.xyz") # geom = geom_from_library("split.image_021.xyz", coord_type="redund") xtb = XTB() geom.set_calculator(xtb) opt_kwargs = { "max_cycles": 100, "hist_max": 10, "dump": True, "trust_radius": 0.1, } opt = StabilizedQNMethod(geom, **opt_kwargs) # from pysisyphus.optimizers.RFOptimizer import RFOptimizer # opt = RFOptimizer(geom) opt.run()
def run(): xyz_fn = "fluorethylene.xyz" geom = geom_from_library(xyz_fn, coord_type="dlc") freeze = ((0, 1), (2, 0, 3)) geom.internal.freeze_primitives(freeze) # XTB calc = XTB() # Psi4 # from pysisyphus.calculators.Psi4 import Psi4 # calc = Psi4(method="hf", basis="sto-3g") geom.set_calculator(calc) opt_kwargs = { # "max_cycles": 1, "thresh": "gau_tight", "trust_max": 0.3, "trust_radius": 0.1, } opt = RFOptimizer(geom, **opt_kwargs) opt.run() assert opt.is_converged
def test_mecoome_sqnm_xtb(): geom = geom_from_library("mecoome_split.image_010.xyz") xtb = XTB() geom.set_calculator(xtb) opt_kwargs = { # "alpha": 0.5, # "alpha_stretch": 0.5, "alpha": 0.5, "alpha_stretch": 0.5, "hist_max": 5, "dump": True, "trust_radius": 0.5, "bio": False, # "thresh": "gau", } opt = StabilizedQNMethod(geom, **opt_kwargs) # from pysisyphus.optimizers.RFOptimizer import RFOptimizer # opt = RFOptimizer(geom) opt.run()
def prepare_opt(idpp=True): path = Path(os.path.dirname(os.path.abspath(__file__))) fns = ("hcn.xyz", "hcn_iso_ts.xyz", "nhc.xyz") geoms = [geom_from_library(fn) for fn in fns] calc_kwargs = { "charge": 0, "mult": 1, } cos_kwargs = { #"parallel": 4, #"fix_ends": True, } if idpp: geoms = idpp_interpolate(geoms, 5) neb = NEB(geoms, **cos_kwargs) else: neb = NEB(geoms, **cos_kwargs) neb.interpolate(5) for i, image in enumerate(neb.images): image.set_calculator(XTB(calc_number=i, **calc_kwargs)) return neb
def test_socketcalc(): host = "localhost" port = 8080 calc = XTB(pal=2) funcs = { "energy": calc.get_energy, "forces": calc.get_forces, "hessian": calc.get_hessian, } with socket.socket() as s: s.connect((host, port)) data = s.recv(1024) try: js = json.loads(data.decode("utf-8")) print("Decoded json", js) except json.JSONDecodeError: js = None print("JSONDecode error") if js: print("Got valid JSON") atoms = js["atoms"] print("atoms", atoms) coords = np.array(js["coords"], dtype=float) print("coords", coords) result = funcs[js["request"]](atoms, coords) if "forces" in result: result["forces"] = result["forces"].tolist() if "hessian" in result: result["hessian"] = result["hessian"].tolist() print("result", result) response = (json.dumps(result) + "\n").encode("utf-8") s.sendall(response)
def run_bare_rfo(xyz_fn, charge, mult, trust=0.3, max_cycles=150): geom = geom_from_library(xyz_fn, coord_type="redund") # geom = geom_from_library(xyz_fn) geom.set_calculator(XTB(pal=4, charge=charge, mult=mult)) # geom.set_calculator(Gaussian16(pal=3, route="HF 3-21G", charge=charge, mult=mult)) grads = list() steps = list() H = geom.get_initial_hessian() converged = False for i in range(max_cycles): grad = -geom.forces grads.append(grad) if i > 0: dx = steps[-1] dg = grads[-1] - grads[-2] dH, _ = bfgs_update(H, dx, dg) H += dH H_proj = H.copy() if geom.internal: H_proj = geom.internal.project_hessian(H_proj) step = rfo(grad, H_proj, trust=trust) steps.append(step) max_g = np.abs(grad).max() rms_g = np.sqrt(np.mean(grad**2)) max_s = np.abs(step).max() rms_s = np.sqrt(np.mean(step**2)) print(f"{i:02d}: max(f)={max_g:.6f}, rms(f)={rms_g:.6f}, " f"max(step)={max_s:.6f}, rms(step)={rms_s:.6f}") converged = ((max_g < 4.5e-4) and (rms_g < 1.5e-4) and (max_s < 1.8e-3) and (rms_s < 1.2e-3)) if converged: print("Converged") break new_coords = geom.coords + step geom.coords = new_coords return converged, i + 1
def test_rfo_benzene(): geom = geom_from_library("benzene_shaken.xyz", coord_type="redund") calc = XTB(pal=4) geom.set_calculator(calc) opt = RFOptimizer(geom, dump=True) opt.run()
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("shaked.xyz") calc = XTB(pal=4) geom.set_calculator(calc) kill_modes(geom)
def run(): geom = geom_from_xyz_file("03_00_water_addition_ts.xyz") geom.set_calculator(XTB(pal=4)) run_relaxations(geom, 1)
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_neb(): geoms = get_geoms() for g in geoms: g.set_calculator(XTB()) neb = NEB(geoms) return neb
def run(): # pysis_in = np.loadtxt("ref_rsa/in_hess") # this_in = np.loadtxt("test_in_hess") # geom = geom_from_library("codein.xyz") # geom = geom_from_xyz_file("ref_rsa/codeine.xyz") geom = geom_from_library("birkholz/vitamin_c.xyz") # geom.coords = shake_coords(geom.coords, seed=25032019) calc = XTB(charge=0, mult=1, pal=4) geom.set_calculator(calc) from pysisyphus.optimizers.RSAlgorithm import RSAlgorithm rsa_kwargs = { "hessian_recalc": 5, } opt = RSAlgorithm(geom, **rsa_kwargs) opt.run() return # g = geom.gradient # np.savetxt("gradient", g) # H = geom.hessian H = np.eye(geom.coords.size) np.savetxt("test_in_hess", H) # H = np.loadtxt("hessian") # g = np.loadtxt("gradient") # H = geom.hessian # from pysisyphus.calculators.AnaPot import AnaPot # pot = AnaPot() # geom = AnaPot.get_geom((0, 3, 0)) # H = geom.hessian # H = np.eye(geom.coords.shape[0]) / 2 trust = 0.3 max_cycles = 50 coords = list() steps = list() grads = list() # import pdb; pdb.set_trace() for i in range(max_cycles): coords.append(geom.coords.copy()) g = geom.gradient grads.append(g) grad_norm = np.linalg.norm(g) if i > 0: dg = grads[-1] - grads[-2] dx = steps[-1] dH, _ = bfgs_update(H, dx, dg) H = H + dH # H = geom.hessian rms_g = np.sqrt(np.mean(g**2)) print(f"Cycle {i:02d}: norm(g)={grad_norm:.4e}, rms(g)={rms_g:.6f}") if grad_norm < 1e-3: print("Converged") break # import pdb; pdb.set_trace() step = rsa(H, g, trust) new_coords = geom.coords + step geom.coords = new_coords steps.append(step) with open("opt.xyz", "w") as handle: handle.write(geom.as_xyz()) coords = np.array(coords) # pot.plot() # ax = pot.ax # ax.plot(*coords.T[:2], "bo-") plt.show()
def test_birkholz(): base_path = Path("birkholz") results = dict() tot_cycles = 0 tot_cycles_with_fails = 0 fails = 0 start = time.time() # GEOMS = { "bisphenol_a.xyz": (0, 1), } # GEOMS = { "sphingomyelin.xyz": (0, 1), } # GEOMS = { "vitamin_c.xyz": (0, 1), } for xyz_fn, (charge, mult) in GEOMS.items(): print(xyz_fn, charge, mult) geom = geom_from_library(base_path / xyz_fn, coord_type="redund") # geom = geom_from_library(base_path / xyz_fn) # geom = geom_from_library(base_path / xyz_fn, coord_type="dlc") calc = XTB(charge=charge, mult=mult, pal=4) # calc = ORCA("HF 3-21G", charge=charge, mult=mult, pal=4) # route = "HF/3-21G" # if xyz_fn in ("vitamin_c.xyz", "easc.xyz"): # route = "B3LYP/6-31G**" # calc = Gaussian16(route=route, charge=charge, mult=mult, pal=4) geom.set_calculator(calc) opt_kwargs_base = { "max_cycles": 150, "thresh": "gau", "trust_radius": 0.5, "trust_update": True, "hessian_init": "fischer", "hessian_update": "damped_bfgs", # "hessian_update": "flowchart", # "hessian_update": "bfgs", # "dump": True, "line_search": True, # "gdiis": True, } opt_kwargs = opt_kwargs_base.copy() opt = RFOptimizer(geom, **opt_kwargs) opt.run() # opt_kwargs = opt_kwargs_base.copy() # opt = RSAlgorithm(geom, **opt_kwargs) # opt.run() converged = opt.is_converged cycles = opt.cur_cycle + 1 results[xyz_fn] = (converged, cycles) pprint(results) if converged: tot_cycles += cycles else: fails += 1 tot_cycles_with_fails += cycles print() end = time.time() print() print(f"Total runtime: {end-start:.1f} s") pprint(results) print(f"Total cycles: {tot_cycles}") if fails: print(f"Total cycles (with fails): {tot_cycles_with_fails}") print(f"Fails: {fails}") opt_kwargs["time"] = time.time() to_pickle = (results, opt_kwargs, type(opt)) hash_ = hash(frozenset(opt_kwargs.items())) pickle_fn = f"results_{hash_}.pickle" with open(pickle_fn, "wb") as handle: cloudpickle.dump(to_pickle, handle) print(f"Save pickled results to {pickle_fn}")
def calc_getter(): return XTB(pal=4)