def test_ComplexCoordSys(self): x = cs.XYZ(file2str("H2.xyz")) a_h2o1 = cs.RotAndTrans(numpy.array([1., 0., 0., 3., 1., 1.]), parent=x) a_h2o2 = cs.RotAndTrans(numpy.array([1., 0., 0., 1., 1., 1.]), parent=x) a_ch4 = cs.RotAndTrans(numpy.array([1., 0., 0., 1., -1., 1.]), parent=x) h2o1 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o1) h2o2 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o2) ch4 = cs.ZMatrix(file2str("CH4.zmt"), anchor=a_ch4) parts = [x, h2o1, h2o2, ch4] ccs = cs.ComplexCoordSys(parts) ccs.set_calculator(test_calc()) dyn = ase.LBFGS(ccs) list = [] for i in range(8): list.append(ccs.atoms.copy()) dyn.run(steps=1, fmax=0.01) list.append(ccs.atoms.copy()) if visual: ase.view(list)
def test_ComplexCoordSys(self): x = cs.XYZ(file2str("H2.xyz")) a_h2o1 = cs.RotAndTrans(numpy.array([1.,0.,0.,3.,1.,1.]), parent=x) a_h2o2 = cs.RotAndTrans(numpy.array([1.,0.,0.,1.,1.,1.]), parent=x) a_ch4 = cs.RotAndTrans(numpy.array([1.,0.,0.,1.,-1.,1.]), parent=x) h2o1 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o1) h2o2 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o2) ch4 = cs.ZMatrix(file2str("CH4.zmt"), anchor=a_ch4) parts = [x, h2o1, h2o2, ch4] ccs = cs.ComplexCoordSys(parts) ccs.set_calculator(test_calc()) dyn = ase.LBFGS(ccs) list = [] for i in range(8): list.append(ccs.atoms.copy()) dyn.run(steps=1,fmax=0.01) list.append(ccs.atoms.copy()) if visual: ase.view(list)
def test_ComplexCoordSys_pickling(self): calc = test_calc() x = cs.XYZ(file2str("H2.xyz")) a = cs.RotAndTrans(numpy.array([1., 0., 0., 3., 1., 1.]), parent=x) z = cs.ZMatrix(file2str("butane1.zmt"), anchor=a) parts = [x, z] ccs = cs.ComplexCoordSys(parts) ccs.set_calculator(calc) forces0 = ccs.get_forces() ccs_pickled = pickle.loads(pickle.dumps(ccs)) ccs_pickled.set_calculator(calc) forces_pickled0 = ccs.get_forces() dyn = ase.LBFGS(ccs_pickled) dyn.run(steps=3) forces_pickled1 = ccs_pickled.get_forces() dyn = ase.LBFGS(ccs) dyn.run(steps=3) forces1 = ccs.get_forces() self.assert_((forces0 == forces_pickled0).all()) self.assert_((forces1 == forces_pickled1).all()) self.assert_((forces0 != forces1).any())
def test_ComplexCoordSys_pickling(self): calc = test_calc() x = cs.XYZ(file2str("H2.xyz")) a = cs.RotAndTrans(numpy.array([1.,0.,0.,3.,1.,1.]), parent=x) z = cs.ZMatrix(file2str("butane1.zmt"), anchor=a) parts = [x, z] ccs = cs.ComplexCoordSys(parts) ccs.set_calculator(calc) forces0 = ccs.get_forces() ccs_pickled = pickle.loads(pickle.dumps(ccs)) ccs_pickled.set_calculator(calc) forces_pickled0 = ccs.get_forces() dyn = ase.LBFGS(ccs_pickled) dyn.run(steps=3) forces_pickled1 = ccs_pickled.get_forces() dyn = ase.LBFGS(ccs) dyn.run(steps=3) forces1 = ccs.get_forces() self.assert_((forces0 == forces_pickled0).all()) self.assert_((forces1 == forces_pickled1).all()) self.assert_((forces0 != forces1).any())
def test_get_transform_matrix(self): common.ANGSTROMS_TO_BOHRS = 1.8897 common.DEG_TO_RAD = numpy.pi / 180. RAD_TO_DEG = 180. / numpy.pi m1 = file2str("CH4.zmt") z = cs.ZMatrix(m1) m, e = z.get_transform_matrix(z.get_internals()) print "Testing that the numerical diff errors are small" self.assert_(numpy.linalg.norm(e) < 1e-8) z = cs.ZMatrix(file2str("benzyl.zmt")) m, e = z.get_transform_matrix(z.get_internals()) print "Testing numerical differentiation" max_rms_err = 1e-8 err_msg = "Numerical differentiation RMS error should be less than " + str( max_rms_err) + " but errors were: " + str(e) self.assert_(numpy.linalg.norm(e) / len(e) < max_rms_err, err_msg) print "Testing generation of forces coordinate system transform matrix" zmt_grads_from_benzyl_log = numpy.array([ -0.02391, -0.03394, -0.08960, -0.03412, -0.12382, -0.15768, -0.08658, -0.01934, 0.00099, 0.00000, -0.00541, 0.00006, -0.00067, 0.00000, -0.00556, 0.00159, 0.00000, -0.00482, -0.00208 ]) xyz_grads_from_benzyl_xyz_log = numpy.array([ 0.023909846, 0.0, 0.034244932, 0.053971884, 0.0, -0.124058188, -0.004990116, 0.000000000, 0.000806757, -0.005402561, 0.000000000, -0.006533931, 0.008734562, 0.000000000, -0.006763414, -0.002889556, 0.000000000, -0.013862257, -0.072130600, 0.000000000, 0.125686058, -0.005409690, 0.000000000, 0.000029026, -0.002717236, 0.000000000, -0.005359264, 0.002107675, 0.000000000, -0.005198587, 0.004815793, 0., 0.001008869 ]) calculated_zmt_grads = numpy.dot(m, xyz_grads_from_benzyl_xyz_log) """Gradients in Gaussian are in Hartree/Bohr or radian, but the transform matrix generated by the ZMatrix class has units of angstroms/bohr or degree. For this reason, when comparing Gaussian's gradients in terms of z-matrix coordinates (in benzyl.log) with those computed by transforming Gaussian's forces in terms of cartesians (in benzyl_zmt.log), one needs to multiply the angular forces from benzyl.log by the following factor: (ANGSTROMS_TO_BOHRS * RAD_TO_DEG). That's what the following two lines are for.""" for i in [2, 4, 6, 7, 8, 9, 11, 12, 13, 15, 16, 18]: calculated_zmt_grads[i] *= (common.ANGSTROMS_TO_BOHRS) self.assertAlmostEqualVec(calculated_zmt_grads, zmt_grads_from_benzyl_log, 1e-3)
def setup(argv): """Deal with command line arguments""" import os from pts.common import file2str import getopt from numpy import array, ndarray execname = argv[0] argv = argv[1:] init_state_vec = None params_file = None prev_results_file = None overrides = "" try: opts, reagents = getopt.getopt( argv, "h", ["params=", "path=", "load=", "help", "override="]) for o, a in opts: if o in ("-h", "--help"): usage(execname) return 0 elif o in ("--params"): params_file = a elif o in ("--load"): prev_results_file = a elif o in ("--override"): overrides += a + "\n" elif o in ("--path"): init_state_vec = eval(file2str(a)) t = type(init_state_vec) if init_state_vec != None and t != ndarray: raise UsageException("Object from %s had type %s" % (a, str(t))) else: raise UsageException("Unrecognised: " + o) if params_file == None: raise UsageException("You must supply a parameters file.") if len(reagents) < 2: raise UsageException("You must supply at least two reagents") mol_strings = [file2str(f) for f in reagents] except UsageException, e: usage(execname) exit(1)
def setup(argv): """Deal with command line arguments""" import os from pts.common import file2str import getopt from numpy import array, ndarray execname = argv[0] argv = argv[1:] init_state_vec = None params_file = None prev_results_file = None overrides = "" try: opts, reagents = getopt.getopt(argv, "h", ["params=", "path=", "load=", "help", "override="]) for o, a in opts: if o in ("-h", "--help"): usage(execname) return 0 elif o in ("--params"): params_file = a elif o in ("--load"): prev_results_file = a elif o in ("--override"): overrides += a + "\n" elif o in ("--path"): init_state_vec = eval(file2str(a)) t = type(init_state_vec) if init_state_vec != None and t != ndarray: raise UsageException("Object from %s had type %s" % (a, str(t))) else: raise UsageException("Unrecognised: " + o) if params_file == None: raise UsageException("You must supply a parameters file.") if len(reagents) < 2: raise UsageException("You must supply at least two reagents") mol_strings = [file2str(f) for f in reagents] except UsageException, e: usage(execname) exit(1)
def test_ZMatrix(self): hexane_zmt = file2str("hexane.zmt") z = cs.ZMatrix(hexane_zmt) print "Testing hexane.zmt -> xyz" self.assertEqual(geom_str_summ(z.xyz_str()), geom_str_summ(file2str("hexane.xyz"))) print "Testing hexane2.zmt -> zmt" self.assertEqual(geom_str_summ(z.zmt_str()), geom_str_summ(file2str("hexane2.zmt"))) z = cs.ZMatrix(file2str("benzyl.zmt")) print "Testing benzyl.zmt -> xyz" self.assertEqual(geom_str_summ(file2str("benzyl.xyz")), geom_str_summ(z.xyz_str()))
def test_gaussian_water(self): g = pts.gaussian.Gaussian(charge=0, mult=2) b = cs.ZMatrix(file2str("H2O.zmt")) b.set_calculator(g) self.assertRaises(pts.gaussian.GaussDriverError, b.get_forces) g = pts.gaussian.Gaussian(charge=-1, mult=2) b = cs.ZMatrix(file2str("H2O.zmt")) expect = numpy.array([0.0632226, -0.00272265, 0.]) b.set_calculator(g) actual = b.get_forces() self.assertAlmostEqualVec(expect, actual)
def test_opts(self): z = cs.ZMatrix(file2str("butane1.zmt")) new_coords = z.get_internals() * 1.15 z.set_internals(new_coords) string_rep = z.xyz_str() z.set_calculator(test_calc()) dyn = ase.LBFGS(z) print "Running z-matrix optimisation" dyn.run(steps=5) e1 = z.get_potential_energy() xyz = cs.XYZ(string_rep) xyz.set_calculator(test_calc()) dyn = ase.LBFGS(xyz) print "Running cartesian optimisation" dyn.run(steps=5) e2 = xyz.get_potential_energy() self.assert_(e1 < e2)
def form_ccs_waters(self, n): """Forms a ComplexCoordSys object with n water molecules with random orientations.""" from random import random r = numpy.arange(numpy.ceil(n**0.333)) water_positions = [numpy.array([x,y,z]) for x in r for y in r for z in r] water_positions = water_positions[:n] print water_positions parts = [] var_types = "" for pos in water_positions: rs = [random() for i in range(3)] quat = numpy.array(rs) quat = quat / numpy.linalg.norm(quat) gps = numpy.hstack([quat, pos*3]) a = cs.RotAndTrans(gps) h2o = cs.ZMatrix(file2str("H2O.zmt"), anchor=a) parts.append(h2o) # setup mask to identify nature of variables later var_types += "".join(["i" for j in range(h2o._dims)]) var_types += "rrrppp" ccs = cs.ComplexCoordSys(parts) return ccs, var_types
def test_Anchoring(self): #self.assertRaises(cs.ComplexCoordSysException, cs.RotAndTrans, numpy.array([0.,0.,0.,0.,0.,0.])) # Generates a series of rotated molecular geometries and views them. a = cs.RotAndTrans(numpy.array([1.,0.,0.,1.,1.,1.])) z = cs.ZMatrix(file2str("butane1.zmt"), anchor=a) print z.get_internals() atoms1 = z.atoms.copy() alphas = numpy.arange(0., 1., 0.01) * 2 * numpy.pi vs = numpy.arange(0., 1., 0.01) geoms_list = [] for alpha, v in zip(alphas, vs): vec = common.normalise([1,v,-v]) vec = numpy.sin(alpha / 2) * vec q = numpy.hstack([vec]) v = numpy.array([1.,1.,1.]) a.set(numpy.hstack([q,v])) geoms_list.append(z.atoms.copy()) if visual: ase.view(geoms_list)
def test_Anchoring(self): #self.assertRaises(cs.ComplexCoordSysException, cs.RotAndTrans, numpy.array([0.,0.,0.,0.,0.,0.])) # Generates a series of rotated molecular geometries and views them. a = cs.RotAndTrans(numpy.array([1., 0., 0., 1., 1., 1.])) z = cs.ZMatrix(file2str("butane1.zmt"), anchor=a) print z.get_internals() atoms1 = z.atoms.copy() alphas = numpy.arange(0., 1., 0.01) * 2 * numpy.pi vs = numpy.arange(0., 1., 0.01) geoms_list = [] for alpha, v in zip(alphas, vs): vec = common.normalise([1, v, -v]) vec = numpy.sin(alpha / 2) * vec q = numpy.hstack([vec]) v = numpy.array([1., 1., 1.]) a.set(numpy.hstack([q, v])) geoms_list.append(z.atoms.copy()) if visual: ase.view(geoms_list)
def test_opts(self): z = cs.ZMatrix(file2str("butane1.zmt")) new_coords = z.get_internals() * 1.15 z.set_internals(new_coords) string_rep = z.xyz_str() z.set_calculator(test_calc()) dyn = ase.LBFGS(z) print "Running z-matrix optimisation" dyn.run(steps=5) e1 = z.get_potential_energy() xyz = cs.XYZ(string_rep) xyz.set_calculator(test_calc()) dyn = ase.LBFGS(xyz) print "Running cartesian optimisation" dyn.run(steps=5) e2 = xyz.get_potential_energy() self.assert_(e1 < e2)
def form_ccs_waters(self, n): """Forms a ComplexCoordSys object with n water molecules with random orientations.""" from random import random r = numpy.arange(numpy.ceil(n**0.333)) water_positions = [ numpy.array([x, y, z]) for x in r for y in r for z in r ] water_positions = water_positions[:n] print water_positions parts = [] var_types = "" for pos in water_positions: rs = [random() for i in range(3)] quat = numpy.array(rs) quat = quat / numpy.linalg.norm(quat) gps = numpy.hstack([quat, pos * 3]) a = cs.RotAndTrans(gps) h2o = cs.ZMatrix(file2str("H2O.zmt"), anchor=a) parts.append(h2o) # setup mask to identify nature of variables later var_types += "".join(["i" for j in range(h2o._dims)]) var_types += "rrrppp" ccs = cs.ComplexCoordSys(parts) return ccs, var_types
def test_gaussian_chkpointing(self): print """Testing that for a tricky wavefunction, the gaussian driver will read in a guess and achieve speedier convergence the second time around.""" print "This test will take around 20 seconds..." start = time.time() g = pts.gaussian.Gaussian(mult=2) b = cs.XYZ(file2str("benzyl.xyz")) b.set_calculator(g) b.get_potential_energy() t0 = time.time() - start coords = b.get_internals() coords *= 1.05 start = time.time() b.set_internals(coords) b.get_potential_energy() t1 = time.time() - start print "Times for first calc and second calculations:", t0, t1 print "Ratio of times", (t1 / t0) low, high = 0.3, 0.6 print "Must be between %f and %f" % (low, high) self.assert_(low < t1 / t0 < high)
def form_ccs2(self): """Forms a complex coordinate system object from a few bits and pieces.""" x = cs.XYZ(file2str("H2.xyz")) a_h2o1 = cs.RotAndTrans(numpy.array([1.,0.,0.,3.,1.,1.]), parent=x) a_h2o2 = cs.RotAndTrans(numpy.array([1.,0.,0.,1.,1.,1.]), parent=x) a_ch4 = cs.RotAndTrans(numpy.array([1.,0.,0.,1.,-1.,1.]), parent=x) h2o1 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o1) h2o2 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o2) ch4 = cs.ZMatrix(file2str("CH4.zmt"), anchor=a_ch4) parts = [x, h2o1] #, h2o2, ch4] ccs = cs.ComplexCoordSys(parts) return ccs, x, h2o1, a_h2o1, h2o2, ch4, a_h2o2, a_ch4
def test_ZMatrix(self): hexane_zmt = file2str("hexane.zmt") z = cs.ZMatrix(hexane_zmt) print "Testing hexane.zmt -> xyz" self.assertEqual(geom_str_summ(z.xyz_str()), geom_str_summ(file2str("hexane.xyz"))) print "Testing hexane2.zmt -> zmt" self.assertEqual(geom_str_summ(z.zmt_str()), geom_str_summ(file2str("hexane2.zmt"))) z = cs.ZMatrix(file2str("benzyl.zmt")) print "Testing benzyl.zmt -> xyz" self.assertEqual(geom_str_summ(file2str("benzyl.xyz")), geom_str_summ(z.xyz_str()))
def run(self, item): job = item.job tmp_dir = common.get_tmp_dir() # job_name will be related to the bead number if given ix = self.__get_job_counter() if job.num_bead != None: ix = job.num_bead if self.output_path != None: job_name = self.output_path + "/" + "beadjob%2.2i" % ix else: job_name = "beadjob%2.2i" % ix item.job_name = job_name mol_pickled = os.path.join(tmp_dir, job_name + common.INPICKLE_EXT) ase_stdout_file = os.path.join(tmp_dir, job_name + ".stdout") results_file = job_name + common.OUTPICKLE_EXT results_file = os.path.join(tmp_dir, results_file) # print "HERE", tmp_dir, job_name # compile package of extra data extra_data = dict() extra_data['item'] = item # write input file as pickled object coord_sys_obj = self.build_coord_sys(job.v) f = open(mol_pickled, "wb") packet = coord_sys_obj, extra_data pickle.dump(packet, f, protocol=2) f.close() cmd = ["python", "-m", "pts.pickle_runner", mol_pickled] # Generate placement command, e.g. for dplace if callable(self.place_str): placement = self.place_str(item.tag) cmd = placement.split() + cmd lg.info("Running with placement command %s" % placement) print "Final command", ' '.join(cmd) t0 = time.time() p = Popen(cmd, stdout=open(ase_stdout_file, "w"), stderr=STDOUT) (pid, ret_val) = os.waitpid(p.pid, 0) t1 = time.time() print "Time taken to run job %s was %.1f" % (job_name, (t1 - t0)) if ret_val != 0: raise MolInterfaceException("pickle_runner.py returned with " + str(ret_val) + "\nwhen attempting to run " + ' '.join(cmd) + "\nMake sure $PYTHONPATH contains " + sys.path[0] + "\n" + common.file2str(ase_stdout_file)) # load results from file (e, g, dir) = pickle.load(open(results_file, "r")) return common.Result(job.v, e, g, dir=dir)
def form_ccs1(self): """Forms a complex coordinate system object from a few bits and pieces.""" x = cs.XYZ(file2str("H2.xyz")) a_h2o1 = cs.RotAndTrans(numpy.array([1., 0., 0., 0., 1., 1.]), parent=x) # a_h2o2 = cs.RotAndTrans(numpy.array([1.,0.,0.,0.,1.,1.,1.]), parent=x) # a_ch4 = cs.RotAndTrans(numpy.array([1.,0.,0.,0.,1.,-1.,1.]), parent=x) h2o1 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o1) # h2o2 = cs.ZMatrix(file2str("H2O.zmt"), anchor=a_h2o2) # ch4 = cs.ZMatrix(file2str("CH4.zmt"), anchor=a_ch4) parts = [x, h2o1] #, h2o2, ch4] ccs = cs.ComplexCoordSys(parts) return ccs, x, h2o1, a_h2o1 #, h2o2, ch4, a_h2o2, a_ch4
def test_ZMatrix_BigComplex(self): print "Test Sum of all Cartesian Coordinates" z = cs.ZMatrix(file2str("bigComplex.zmt")) xyz_str = z.xyz_str() import re list = re.findall(r"[+-]?\d+\.\d*", xyz_str) var_sum = sum([float(n) for n in list]) self.assertAlmostEqual(183.156839765, var_sum, 3)
def test_ZMatrix_BigComplex(self): print "Test Sum of all Cartesian Coordinates" z = cs.ZMatrix(file2str("bigComplex.zmt")) xyz_str = z.xyz_str() import re list = re.findall(r"[+-]?\d+\.\d*", xyz_str) var_sum = sum([float(n) for n in list]) self.assertAlmostEqual(183.156839765, var_sum, 3)
def get_calculator(file_name): calculator = None if file_name in default_calcs: calculator = eval("%s" % (file_name)) else: str1 = file2str(file_name) # file file_name has to # contain line calculator = ... exec(str1) return calculator
def test_get_transform_matrix(self): common.ANGSTROMS_TO_BOHRS = 1.8897 common.DEG_TO_RAD = numpy.pi / 180. RAD_TO_DEG = 180. / numpy.pi m1 = file2str("CH4.zmt") z = cs.ZMatrix(m1) m, e = z.get_transform_matrix(z.get_internals()) print "Testing that the numerical diff errors are small" self.assert_(numpy.linalg.norm(e) < 1e-8) z = cs.ZMatrix(file2str("benzyl.zmt")) m, e = z.get_transform_matrix(z.get_internals()) print "Testing numerical differentiation" max_rms_err = 1e-8 err_msg = "Numerical differentiation RMS error should be less than " + str(max_rms_err) + " but errors were: " + str(e) self.assert_(numpy.linalg.norm(e) / len(e) < max_rms_err, err_msg) print "Testing generation of forces coordinate system transform matrix" zmt_grads_from_benzyl_log = numpy.array([-0.02391, -0.03394, -0.08960, -0.03412, -0.12382, -0.15768, -0.08658, -0.01934, 0.00099, 0.00000, -0.00541, 0.00006, -0.00067, 0.00000, -0.00556, 0.00159, 0.00000, -0.00482, -0.00208]) xyz_grads_from_benzyl_xyz_log = numpy.array([0.023909846, 0.0, 0.034244932, 0.053971884, 0.0, -0.124058188, -0.004990116, 0.000000000, 0.000806757, -0.005402561, 0.000000000, -0.006533931, 0.008734562, 0.000000000, -0.006763414, -0.002889556, 0.000000000, -0.013862257, -0.072130600, 0.000000000, 0.125686058, -0.005409690, 0.000000000, 0.000029026, -0.002717236, 0.000000000, -0.005359264, 0.002107675, 0.000000000, -0.005198587, 0.004815793, 0., 0.001008869]) calculated_zmt_grads = numpy.dot(m, xyz_grads_from_benzyl_xyz_log) """Gradients in Gaussian are in Hartree/Bohr or radian, but the transform matrix generated by the ZMatrix class has units of angstroms/bohr or degree. For this reason, when comparing Gaussian's gradients in terms of z-matrix coordinates (in benzyl.log) with those computed by transforming Gaussian's forces in terms of cartesians (in benzyl_zmt.log), one needs to multiply the angular forces from benzyl.log by the following factor: (ANGSTROMS_TO_BOHRS * RAD_TO_DEG). That's what the following two lines are for.""" for i in [2,4,6,7,8,9,11,12,13,15,16,18]: calculated_zmt_grads[i] *= (common.ANGSTROMS_TO_BOHRS) self.assertAlmostEqualVec(calculated_zmt_grads, zmt_grads_from_benzyl_log, 1e-3)
def test_constructor_XYZ(self): print "Testing: MolecularInterface constructor with XYZ" params = dict() params["calculator"] = ase.EMT, [], [] m1 = file2str("benzyl.xyz") m2 = m1 mi = ami.MolInterface([m1, m2], params) print "Testing: MolecularInterface" print mi
def test_ComplexCoordSys2(self): x = cs.XYZ(file2str("H2.xyz")) a = cs.RotAndTrans(numpy.array([1.,0.,0.,3.,1.,1.]), parent=x) z = cs.ZMatrix(file2str("butane1.zmt"), anchor=a) parts = [x, z] ccs = cs.ComplexCoordSys(parts) ccs.set_calculator(test_calc()) print ccs.get_potential_energy() print ccs.get_forces() dyn = ase.LBFGS(ccs) list = [] for i in range(8): dyn.run(steps=1,fmax=0.01) list.append(ccs.atoms.copy()) if visual: ase.view(list)
def test_constructor_ZMatrix(self): print "Testing: MolecularInterface constructor with ZMatrices" params = dict() params["calculator"] = ase.EMT, [], dict() m1 = file2str("CH4.zmt") m2 = m1 mi = ami.MolInterface([m1, m2], params) print mi # XYZ with ZMatrix m2 = file2str("benzyl.xyz") self.assertRaises(cs.ZMatrixException, ami.MolInterface, [m1, m2], params) # non-matching atoms m2 = file2str("NH4.zmt") self.assertRaises(ami.MolInterfaceException, ami.MolInterface, [m1, m2], params) # mixed dihedrals m2 = file2str("CH4-mixeddih.zmt") self.assertRaises(ami.MolInterfaceException, ami.MolInterface, [m1, m2], params)
def test_ComplexCoordSys2(self): x = cs.XYZ(file2str("H2.xyz")) a = cs.RotAndTrans(numpy.array([1., 0., 0., 3., 1., 1.]), parent=x) z = cs.ZMatrix(file2str("butane1.zmt"), anchor=a) parts = [x, z] ccs = cs.ComplexCoordSys(parts) ccs.set_calculator(test_calc()) print ccs.get_potential_energy() print ccs.get_forces() dyn = ase.LBFGS(ccs) list = [] for i in range(8): dyn.run(steps=1, fmax=0.01) list.append(ccs.atoms.copy()) if visual: ase.view(list)
def test_constructor_run_calc(self): print "Testing: MolecularInterface constructor with XYZ" params = dict() d = dict() params["calculator"] = ase.EMT, [], d m1 = file2str("benzyl.xyz") m2 = m1 mi = ami.MolInterface([m1, m2], params) c = mi.reagent_coords[0] j = Job(c, Job.G()) print mi.run(j)
def test_var_mask_basic(self): print "Running basic tests with masking of variables" ccs1, _, _, _ = self.form_ccs1() ccs2, _, _, _, _, _, _, _ = self.form_ccs2() benzyl = cs.ZMatrix(file2str("benzyl.zmt")) sys_list = [ccs1, ccs2, benzyl] tf = lambda i: i % 2 == 0 for sys in sys_list: mask = map(tf, range(sys.dims)) sys.set_var_mask(mask) # check that computed dimensionality is correct self.assert_(sum(sys._var_mask) == sys.dims) # check that masking/demasking is ok self.assert_( (sys._coords == sys._demask(sys.get_internals())).all()) should_be = sys._demask(sys._mask(sys._coords)) self.assert_((sys._coords == should_be).all()) # check that state is not altered by a few function calls before = sys._coords.copy() sys.int2cart(sys.get_internals()) after = sys._coords.copy() self.assert_((before == after).all()) # play with state, check that forces don't change sys.set_calculator(test_calc()) f1 = sys.get_forces() before = sys.get_internals() sys.set_internals(before * 1.2) sys.get_forces() sys.set_internals(before) f2 = sys.get_forces() self.assert_((f1 == f2).all())
def test_var_mask_basic(self): print "Running basic tests with masking of variables" ccs1, _, _, _ = self.form_ccs1() ccs2, _, _, _, _, _, _, _ = self.form_ccs2() benzyl = cs.ZMatrix(file2str("benzyl.zmt")) sys_list = [ccs1, ccs2, benzyl] tf = lambda i: i % 2 == 0 for sys in sys_list: mask = map(tf, range(sys.dims)) sys.set_var_mask(mask) # check that computed dimensionality is correct self.assert_(sum(sys._var_mask) == sys.dims) # check that masking/demasking is ok self.assert_((sys._coords == sys._demask(sys.get_internals())).all()) should_be = sys._demask(sys._mask(sys._coords)) self.assert_((sys._coords == should_be).all()) # check that state is not altered by a few function calls before = sys._coords.copy() sys.int2cart(sys.get_internals()) after = sys._coords.copy() self.assert_((before == after).all()) # play with state, check that forces don't change sys.set_calculator(test_calc()) f1 = sys.get_forces() before = sys.get_internals() sys.set_internals(before*1.2) sys.get_forces() sys.set_internals(before) f2 = sys.get_forces() self.assert_((f1 == f2).all())
def test_CoordSys_pickling(self): print "Creating a Z-matrix, pickling it, then performing an dientical" print "optimisation on each one, then checking that the forces are identical." z1 = cs.ZMatrix(file2str("butane1.zmt")) s = pickle.dumps(z1) z1.set_calculator(test_calc()) opt = ase.LBFGS(z1) opt.run(steps=4) forces1 = z1.get_forces() z2 = pickle.loads(s) z2.set_calculator(test_calc()) opt = ase.LBFGS(z2) opt.run(steps=4) forces2 = z2.get_forces() self.assert_((forces1 == forces2).all())
def test_CoordSys_pickling(self): print "Creating a Z-matrix, pickling it, then performing an dientical" print "optimisation on each one, then checking that the forces are identical." z1 = cs.ZMatrix(file2str("butane1.zmt")) s = pickle.dumps(z1) z1.set_calculator(test_calc()) opt = ase.LBFGS(z1) opt.run(steps=4) forces1 = z1.get_forces() z2 = pickle.loads(s) z2.set_calculator(test_calc()) opt = ase.LBFGS(z2) opt.run(steps=4) forces2 = z2.get_forces() self.assert_((forces1 == forces2).all())
exit() geo_dict = {"format": None, "zmt_format": "direct"} direct_path = None paramfile = None geos = [] add_param = {} zmatrix = [] # Now loop over the arguments. As one reads in usually two at # once, one might run out of arguements before the loop is over: for o, a in opts: # filter out the special ones if o == "paramfile": # file containing parameters paramfile = file2str(a) elif o in ("old_results", "cache"): # file to take results from previous calculations from add_param["cache"] = a elif o in ("zmatrix"): # zmatrix if given separate to the geometries zmatrix.append(a) elif o in ("init_path"): # zmatrix if given separate to the geometries direct_path = loadtxt(a) elif o in geo_params: # only needed to build up the geometry if o in ("mask"): # needed to build up the geometry and wanted for params output geo_dict[o] = get_mask(a) elif o in ("cell", "pbc"):
def run(self, item): job = item.job tmp_dir = common.get_tmp_dir() # job_name will be related to the bead number if given ix = self.__get_job_counter() if job.num_bead != None: ix = job.num_bead if self.output_path != None: job_name = self.output_path + "/" + "beadjob%2.2i" % ix else: job_name = "beadjob%2.2i" % ix item.job_name = job_name mol_pickled = os.path.join(tmp_dir, job_name + common.INPICKLE_EXT) ase_stdout_file = os.path.join(tmp_dir, job_name + ".stdout") results_file = job_name + common.OUTPICKLE_EXT results_file = os.path.join(tmp_dir, results_file) # print "HERE", tmp_dir, job_name # compile package of extra data extra_data = dict() extra_data['item'] = item # write input file as pickled object coord_sys_obj = self.build_coord_sys(job.v) f = open(mol_pickled, "wb") packet = coord_sys_obj, extra_data pickle.dump(packet, f, protocol=2) f.close() cmd = ["python", "-m", "pts.pickle_runner", mol_pickled] # Generate placement command, e.g. for dplace if callable(self.place_str): placement = self.place_str(item.tag) cmd = placement.split() + cmd lg.info("Running with placement command %s" % placement) print "Final command", ' '.join(cmd) t0 = time.time() p = Popen(cmd, stdout=open(ase_stdout_file, "w"), stderr=STDOUT) (pid, ret_val) = os.waitpid(p.pid, 0) t1 = time.time() print "Time taken to run job %s was %.1f" % (job_name, (t1 - t0)) if ret_val != 0: raise MolInterfaceException("pickle_runner.py returned with " + str(ret_val) + "\nwhen attempting to run " + ' '.join(cmd) + "\nMake sure $PYTHONPATH contains " + sys.path[0] + "\n" + common.file2str(ase_stdout_file)) # load results from file (e, g, dir) = pickle.load(open(results_file, "r")) return common.Result(job.v, e, g, dir=dir)
def read_zmt_from_file(zmat_file): """ Read zmatrix from file """ zmat_string = file2str(zmat_file) return read_zmt_from_string(zmat_string)
ss = record['pathps'] path_list.append((i, state, es, gs, ss)) max_coord_change = np.abs(state[0] - state[-1]).max() print "Last archive entry" print "Max change in any one coordinate was %.2f" % max_coord_change print " Per bead %.2f" % (max_coord_change / len(state)) print "Energy of all beads %s" % es print "Energy of highest bead %.2f" % es.max() ts_known = len(args) == 2 if ts_known: fn_ts = args[1] ts = pts.coord_sys.XYZ(file2str(fn_ts)) ts_carts = ts.get_cartesians() ts_energy = ts.get_potential_energy() if gnuplot_out: s = '\n'.join(['%.2f' % e for e in es]) print s if forces: disp_forces(pt) if ts_from_path: for path in path_list: i, state, es, gs, ss = path
def read_dimer_input(rest, name): """ This function is similar to the one for pathsearcher """ from pts.ui.read_inputs import from_params_file from pts.ui.read_COS import geo_params from pts.defaults import are_strings from pts.common import file2str from pts.func import compose from pts.qfunc import QFunc from pts.memoize import Memoize, FileStore from pts.defaults import di_default_params, qn_default_params, ln_default_params from pts.trajectories import dimer_log from pts.defaults import di_default_params, qn_default_params, di_default_params_rot #This variables will be needed afterwards anyway # independent of beeing given by user geo_dict = {"format" : None, "zmt_format" : "direct"} add_param = {} paramfile = None zmatrix = [] geo = None mode = None as_pickle = False ts_estim = None accept_all = False give_help_if_needed(rest, name) if rest[0] == "--accept_all": rest = rest[1:] accept_all = True defaults_available = True if name in ["dimer"]: default_params = di_default_params elif name in ["lanczos"]: default_params = ln_default_params elif name in ["lanczos-rotate", "dimer-rotate"]: default_params = di_default_params_rot elif name in ["qn", "simple_qn", "quasi-newton"]: default_params = qn_default_params else: print >> stderr, "WARNING: No default parameter for specific method found" print >> stderr, " There will be no test if the given parameter make sense" default_params = {} accept_all = True defaults_available = False if "--defaults" in rest: if defaults_available: print "The default parameters for the algorithm ", name, " are:" for param, value in default_params.iteritems(): print " %s = %s" % (str(param), str(value)) else: print "No default values available for the specific method", name exit() for i in range(len(rest)): if rest == []: break # filter out all the options if rest[0].startswith("--"): o = rest[0][2:] a = rest[1] # filter out the special ones if o == "paramfile": # file containing parameters paramfile = file2str(a) elif o in ("zmatrix"): # zmatrix if given separate to the geometries zmatrix.append(a) elif o in ("pickle"): as_pickle = True ts_estim = a elif o in geo_params: # only needed to build up the geometry if o in ("mask"): # needed to build up the geometry and wanted for params output geo_dict[o] = get_mask(a) elif o in ("cell", "pbc"): geo_dict[o] = eval(a) else: geo_dict[o] = a else: # suppose that the rest are setting parameters # we do not have a complete list of them if not accept_all: assert o in default_params or o == "rot_method", "Parameter %s" % (o) if o in are_strings: add_param[o] = a else: add_param[o] = eval(a) rest = rest[2:] else: # This two files are needed any way: one geometry file and one # for the modevector, expect the geoemtry file to be given first if geo == None: # For reusing pathsearcher routines with several geoemtries for input geo = [ rest[0]] else: mode = rest[0] rest = rest[1:] if paramfile == None: params_dict = add_param geo_dict_dim = geo_dict else: if accept_all: params_dict, geo_dict_dim = from_params_file_dimer(paramfile ) else: params_dict, geo_dict_dim = from_params_file(paramfile, default_params ) params_dict.update(add_param) geo_dict_dim.update(geo_dict) if as_pickle: start_geo, init_mode, funcart, atoms = read_from_pickle(geo[0], ts_estim, geo_dict_dim) else: start_geo, funcart, atoms = build_new(geo, geo_dict_dim, zmatrix) if name in ["lanczos", "dimer", "lanczos-rotate", "dimer-rotate"]: init_mode = build_mode(mode, start_geo, funcart) else: assert mode == None init_mode = None # Build up the qfunc, calculator is included in atoms already pes = compose(QFunc(atoms, calc = atoms.get_calculator()), funcart) if "cache" in params_dict: if params_dict["cache"] == None: pes = Memoize(pes, FileStore("%s.ResultDict.pickle" % (name))) else: pes = Memoize(pes, FileStore(params_dict["cache"])) else: pes = Memoize(pes, FileStore("%s.ResultDict.pickle" % (name))) #Attention inital mode need not be normed (and cannot as metric is not yet known) return pes, start_geo, init_mode, params_dict, atoms, funcart
def read_dimer_input(rest, name): """ This function is similar to the one for pathsearcher """ from pts.ui.read_inputs import from_params_file from pts.ui.read_COS import geo_params from pts.defaults import are_strings from pts.common import file2str from pts.func import compose from pts.qfunc import QFunc from pts.memoize import Memoize, FileStore from pts.defaults import di_default_params, qn_default_params, ln_default_params from pts.trajectories import dimer_log from pts.defaults import di_default_params, qn_default_params, di_default_params_rot #This variables will be needed afterwards anyway # independent of beeing given by user geo_dict = {"format": None, "zmt_format": "direct"} add_param = {} paramfile = None zmatrix = [] geo = None mode = None as_pickle = False ts_estim = None accept_all = False give_help_if_needed(rest, name) if rest[0] == "--accept_all": rest = rest[1:] accept_all = True defaults_available = True if name in ["dimer"]: default_params = di_default_params elif name in ["lanczos"]: default_params = ln_default_params elif name in ["lanczos-rotate", "dimer-rotate"]: default_params = di_default_params_rot elif name in ["qn", "simple_qn", "quasi-newton"]: default_params = qn_default_params else: print >> stderr, "WARNING: No default parameter for specific method found" print >> stderr, " There will be no test if the given parameter make sense" default_params = {} accept_all = True defaults_available = False if "--defaults" in rest: if defaults_available: print "The default parameters for the algorithm ", name, " are:" for param, value in default_params.iteritems(): print " %s = %s" % (str(param), str(value)) else: print "No default values available for the specific method", name exit() for i in range(len(rest)): if rest == []: break # filter out all the options if rest[0].startswith("--"): o = rest[0][2:] a = rest[1] # filter out the special ones if o == "paramfile": # file containing parameters paramfile = file2str(a) elif o in ("zmatrix"): # zmatrix if given separate to the geometries zmatrix.append(a) elif o in ("pickle"): as_pickle = True ts_estim = a elif o in geo_params: # only needed to build up the geometry if o in ("mask"): # needed to build up the geometry and wanted for params output geo_dict[o] = get_mask(a) elif o in ("cell", "pbc"): geo_dict[o] = eval(a) else: geo_dict[o] = a else: # suppose that the rest are setting parameters # we do not have a complete list of them if not accept_all: assert o in default_params or o == "rot_method", "Parameter %s" % ( o) if o in are_strings: add_param[o] = a else: add_param[o] = eval(a) rest = rest[2:] else: # This two files are needed any way: one geometry file and one # for the modevector, expect the geoemtry file to be given first if geo == None: # For reusing pathsearcher routines with several geoemtries for input geo = [rest[0]] else: mode = rest[0] rest = rest[1:] if paramfile == None: params_dict = add_param geo_dict_dim = geo_dict else: if accept_all: params_dict, geo_dict_dim = from_params_file_dimer(paramfile) else: params_dict, geo_dict_dim = from_params_file( paramfile, default_params) params_dict.update(add_param) geo_dict_dim.update(geo_dict) if as_pickle: start_geo, init_mode, funcart, atoms = read_from_pickle( geo[0], ts_estim, geo_dict_dim) else: start_geo, funcart, atoms = build_new(geo, geo_dict_dim, zmatrix) if name in ["lanczos", "dimer", "lanczos-rotate", "dimer-rotate"]: init_mode = build_mode(mode, start_geo, funcart) else: assert mode == None init_mode = None # Build up the qfunc, calculator is included in atoms already pes = compose(QFunc(atoms, calc=atoms.get_calculator()), funcart) if "cache" in params_dict: if params_dict["cache"] == None: pes = Memoize(pes, FileStore("%s.ResultDict.pickle" % (name))) else: pes = Memoize(pes, FileStore(params_dict["cache"])) else: pes = Memoize(pes, FileStore("%s.ResultDict.pickle" % (name))) #Attention inital mode need not be normed (and cannot as metric is not yet known) return pes, start_geo, init_mode, params_dict, atoms, funcart
from pts.coord_sys import * from pts.common import file2str import ase from pts.gaussian import Gaussian from ase.io.trajectory import PickleTrajectory import sys # contents of the variables in the following are arbitrary since they are # set based on the cartesian objects. Make sure, however, that the z-matrix # variables are non-zero, since this can cause a divide by zero error. fn = sys.argv[1] print "Filename", fn ccs = ComplexCoordSys(file2str(fn)) #print ccs._coords #print ccs.get_internals() #exit() g = Gaussian() ccs.set_calculator((Gaussian, [], {'charge': 0, 'mult': 3})) opt = ase.LBFGS(ccs) pt = PickleTrajectory("test.traj", mode='w') def cb(): print ccs.xyz_str() print "internals", ccs.get_internals().round(2) pt.write(ccs.atoms.copy()) opt.attach(cb)
from pts.common import file2str # zmatrix spec = "temp.zmt" # input xyz format files xyz1 = "reactants.xyz.t" xyz2 = "products.xyz.t" # output z-matrices zmt1 = "reactants.zmt" zmt2 = "products.zmt" try: # read in files z = ZMatrix2(file2str(spec)) x1 = XYZ(file2str(xyz1)) x2 = XYZ(file2str(xyz2)) except IOError: print "You must create the relevant input files! See code." exit(1) # Cartesian -> z-matrix and write files z.set_cartesians(x1.get_cartesians()) open(zmt1, 'w').write(repr(z)) z.set_cartesians(x2.get_cartesians()) open(zmt2, 'w').write(repr(z))
def test_gaussian_benzyl(self): g = pts.gaussian.Gaussian(charge=0, mult=2) b = cs.XYZ(file2str("benzyl.xyz")) b.set_calculator(g) print b.get_forces()