def test_structure(self): quartz = self.quartz.structure np.testing.assert_array_equal(quartz.lattice.matrix, [[4.913400, 0, 0], [-2.456700, 4.255129, 0], [0, 0, 5.405200]]) self.assertEqual(quartz.formula, "Si3 O6") self.assertNotIn("molecule-ID", self.quartz.atoms.columns) ethane = self.ethane.structure np.testing.assert_array_equal(ethane.lattice.matrix, np.diag([10.0] * 3)) lbounds = np.array(self.ethane.box.bounds)[:, 0] coords = self.ethane.atoms[["x", "y", "z"]].values - lbounds np.testing.assert_array_equal(ethane.cart_coords, coords) np.testing.assert_array_equal(ethane.site_properties["charge"], self.ethane.atoms["q"]) tatb = self.tatb.structure frac_coords = tatb.frac_coords[381] real_frac_coords = frac_coords - np.floor(frac_coords) np.testing.assert_array_almost_equal(real_frac_coords, [0.01553397, 0.71487872, 0.14134139]) co = Structure.from_spacegroup(194, Lattice.hexagonal(2.50078, 4.03333), ["Co"], [[1/3, 2/3, 1/4]]) ld_co = LammpsData.from_structure(co) self.assertEqual(ld_co.structure.composition.reduced_formula, "Co") ni = Structure.from_spacegroup(225, Lattice.cubic(3.50804), ["Ni"], [[0, 0, 0]]) ld_ni = LammpsData.from_structure(ni) self.assertEqual(ld_ni.structure.composition.reduced_formula, "Ni")
def test_structure(self): quartz = self.quartz.structure np.testing.assert_array_almost_equal( quartz.lattice.matrix, [[4.913400, 0, 0], [-2.456700, 4.255129, 0], [0, 0, 5.405200]]) self.assertEqual(quartz.formula, "Si3 O6") self.assertNotIn("molecule-ID", self.quartz.atoms.columns) ethane = self.ethane.structure np.testing.assert_array_almost_equal(ethane.lattice.matrix, np.diag([10.0] * 3)) lbounds = np.array(self.ethane.box.bounds)[:, 0] coords = self.ethane.atoms[["x", "y", "z"]].values - lbounds np.testing.assert_array_almost_equal(ethane.cart_coords, coords) np.testing.assert_array_almost_equal(ethane.site_properties["charge"], self.ethane.atoms["q"]) tatb = self.tatb.structure frac_coords = tatb.frac_coords[381] real_frac_coords = frac_coords - np.floor(frac_coords) np.testing.assert_array_almost_equal( real_frac_coords, [0.01553397, 0.71487872, 0.14134139]) co = Structure.from_spacegroup(194, Lattice.hexagonal(2.50078, 4.03333), ["Co"], [[1 / 3, 2 / 3, 1 / 4]]) ld_co = LammpsData.from_structure(co) self.assertEqual(ld_co.structure.composition.reduced_formula, "Co") ni = Structure.from_spacegroup(225, Lattice.cubic(3.50804), ["Ni"], [[0, 0, 0]]) ld_ni = LammpsData.from_structure(ni) self.assertEqual(ld_ni.structure.composition.reduced_formula, "Ni")
def setUp(self): self.structure = PymatgenTest.get_structure("Li2O") self.lammps_data = LammpsData.from_structure(self.structure) neutral_structure = self.structure.copy() neutral_structure.remove_oxidation_states() self.lammps_data_neutral = LammpsData.from_structure(neutral_structure, set_charge=False)
def setUpClass(cls): h2o_coords = [[9.626, 6.787, 12.673], [9.626, 8.420, 12.673], [10.203, 7.604, 12.673]] molecule = Molecule(["H", "H", "O"], h2o_coords) box_size = [[0.0, 10.0], [0.0, 10.0], [0.0, 10.0]] cls.lammps_data = LammpsData.from_structure(molecule, box_size)
def test_from_structure(self): latt = Lattice.monoclinic(9.78746, 4.75058, 8.95892, 115.9693) structure = Structure.from_spacegroup( 15, latt, ["Os", "O", "O"], [ [0, 0.25583, 0.75], [0.11146, 0.46611, 0.91631], [0.11445, 0.04564, 0.69518], ], ) velocities = np.random.randn(20, 3) * 0.1 structure.add_site_property("velocities", velocities) ld = LammpsData.from_structure(structure=structure, ff_elements=["O", "Os", "Na"]) i = random.randint(0, 19) a = latt.matrix[0] va = velocities[i].dot(a) / np.linalg.norm(a) self.assertAlmostEqual(va, ld.velocities.loc[i + 1, "vx"]) self.assertAlmostEqual(velocities[i, 1], ld.velocities.loc[i + 1, "vy"]) np.testing.assert_array_almost_equal(ld.masses["mass"], [22.989769, 190.23, 15.9994]) np.testing.assert_array_equal(ld.atoms["type"], [2] * 4 + [3] * 16)
def from_structure(cls, structure, input_template, user_settings, data_filename="in.data", name="basic"): """ Returns inputset from structure Args: structure (Structure/Molecule): input_template (string): path to the input template file. user_settings (dict): User lammps settings, the keys must correspond to the keys in the template. data_filename (string): name of the the lammps data file. Returns: LammpsInputSet """ lammps_data = LammpsData.from_structure(structure) return cls.from_file(name, input_template, user_settings, lammps_data=lammps_data, data_filename=data_filename)
def test_sort_structure(self): s = Structure(Lattice.cubic(4), ["S", "Fe"], [[0, 0, 0], [0.5, 0.5, 0.5]]) lmp = LammpsData.from_structure(s, is_sort=False) lmp.write_file("test1.data") lmp2 = LammpsData.from_file("test1.data", atom_style="charge") # internally element:type will be {Fe: 1, S: 2}, # therefore without sorting the atom types in structure # will be [2, 1], i.e., (S, Fe) self.assertListEqual(lmp2.atoms["type"].values.tolist(), [2, 1]) # with sorting the atom types in structures will be [1, 2] lmp = LammpsData.from_structure(s, is_sort=True) lmp.write_file("test1.data") lmp2 = LammpsData.from_file("test1.data", atom_style="charge") self.assertListEqual(lmp2.atoms["type"].values.tolist(), [1, 2])
def get_snap_site_features(d): feature = [] data_filename = "lammps_snap.data" input_template = "lammps_snap_template.in" input_filename = "lammps_snap.in" dump_filename = "dump.sna" log_filename = "log.lammps" sbp.check_call(["rm", "-f", input_filename]) sbp.check_call(["rm", "-f", data_filename]) sbp.check_call(["rm", "-f", dump_filename]) sbp.check_call(["rm", "-f", log_filename]) structure = Structure.from_dict(d["structure"]) feature.append(structure[d["absorbing_atom"]].specie.number) try: mol = Molecule.from_dict(d["cluster"]) except TypeError: atoms = Atoms(structure, d["absorbing_atom"], 10.0) mol = atoms.cluster logger.info(mol.formula) lmp_data = LammpsData.from_structure(mol, [[0,25], [0,25],[0,25]], translate=False) lmp_data.write_file(data_filename) el_sorted = sorted(mol.composition, key=lambda x:x.atomic_mass) cutoff = "" weight = "" for i, e in enumerate(el_sorted): cutoff += " {}".format(float(e.atomic_radius)) weight += " {}".format(1.0) settings = { 'data_file': data_filename, 'rcutfac': 1.4, 'rfac0': 0.993630, 'twojmax': 6.0, 'cutoff': cutoff, 'weight': weight, 'dump_file': dump_filename } lmp_in = LammpsInput.from_file(input_template, settings) lmp_in.write_file(input_filename) #try: logger.info("Running LAMMPS ... ") exit_code = sbp.check_call(["./lmp_serial", "-in", input_filename]) if exit_code != 0: logger.error("lammps run failed") raise RuntimeError("lammps run failed") logger.info("Processing LAMMPS outputs ... ") lmp_run = LammpsRun(data_filename, dump_filename, log_filename) t = list(lmp_run.trajectory[0]) try: assert np.linalg.norm(t[2:5]) <= 1e-6 except AssertionError: logger.info("xyz: {}".format(t[2:5])) logger.error("assertion failed: first one not at origin") raise logger.info("# bispectrum coeffs: {}".format(len(t[5:]))) feature.extend(t[5:]) return feature
def lammps_forces(structures, inputfile): forces = [] with ScratchDir("."): shutil.copy(inputfile, 'in.forces') for s in structures: lmp_data = LammpsData.from_structure(s) lmp_data.write_file('data.dump') # the structure is written to data.dump run_file('in.forces') forces.append(read_forces('force.data')) return forces
def test_write(self): s = Structure( Lattice( np.array([[3.16, 0.1, 0.2], [0.1, 3.17, 0.3], [0.1, 0.2, 3]])), ["Mo", "Mo"], [[0, 0, 0], [0.13, 0.4, 0.2]]) with ScratchDir("."): write_data_from_structure(s, 'test.data') lmp = LammpsData.from_file('test.data', atom_style="charge") lmp2 = LammpsData.from_structure(s) lmp2.write_file("test2.data") self.assertTrue(str(lmp) == str(lmp2))
def test_md(self): s = Structure.from_spacegroup(225, Lattice.cubic(3.62126), ["Cu"], [[0, 0, 0]]) ld = LammpsData.from_structure(s, atom_style="atomic") ff = "\n".join(["pair_style eam", "pair_coeff * * Cu_u3.eam"]) md = LammpsRun.md(data=ld, force_field=ff, temperature=1600.0, nsteps=10000) md.write_inputs(output_dir="md") with open(os.path.join("md", "in.md")) as f: md_script = f.read() script_string = """# Sample input script template for MD # Initialization units metal atom_style atomic # Atom definition read_data md.data #read_restart md.restart # Force field settings (consult official document for detailed formats) pair_style eam pair_coeff * * Cu_u3.eam # Create velocities velocity all create 1600.0 142857 mom yes rot yes dist gaussian # Ensemble constraints #fix 1 all nve fix 1 all nvt temp 1600.0 1600.0 0.1 #fix 1 all npt temp 1600.0 1600.0 0.1 iso $pressure $pressure 1.0 # Various operations within timestepping #fix ... #compute ... # Output settings #thermo_style custom ... # control the thermo data type to output thermo 100 # output thermo data every N steps #dump 1 all atom 100 traj.*.gz # dump a snapshot every 100 steps # Actions run 10000 """ self.assertEqual(md_script, script_string) self.assertTrue(os.path.exists(os.path.join("md", "md.data")))
def test_md(self): s = Structure.from_spacegroup(225, Lattice.cubic(3.62126), ["Cu"], [[0, 0, 0]]) ld = LammpsData.from_structure(s, atom_style="atomic") ff = "\n".join(["pair_style eam", "pair_coeff * * Cu_u3.eam"]) md = LammpsRun.md(data=ld, force_field=ff, temperature=1600.0, nsteps=10000) md.write_inputs(output_dir="md") with open(os.path.join("md", "in.md")) as f: md_script = f.read() script_string = """# Sample input script template for MD # Initialization units metal atom_style atomic # Atom definition read_data md.data #read_restart md.restart # Force field settings (consult official document for detailed formats) pair_style eam pair_coeff * * Cu_u3.eam # Create velocities velocity all create 1600.0 142857 mom yes rot yes dist gaussian # Ensemble constraints #fix 1 all nve fix 1 all nvt temp 1600.0 1600.0 0.1 #fix 1 all npt temp 1600.0 1600.0 0.1 iso $pressure $pressure 1.0 # Various operations within timestepping #fix ... #compute ... # Output settings #thermo_style custom ... # control the thermo data type to output thermo 100 # output thermo data every N steps #dump 1 all atom 100 traj.*.gz # dump a snapshot every 100 steps # Actions run 10000 """ self.assertEqual(md_script, script_string) self.assertTrue(os.path.exists(os.path.join("md", "md.data")))
def calculate(self, structures): """ Perform the calculation on a series of structures. Args: structures [Structure]: Input structures in a list. Returns: List of computed data corresponding to each structure, varies with different subclasses. """ for struct in structures: assert self._sanity_check( struct) is True, "Incompatible structure found" ff_elements = None if hasattr(self, "element_profile"): element_profile = getattr(self, "element_profile") ff_elements = element_profile.keys() if hasattr(self, "ff_settings"): ff_settings = getattr(self, "ff_settings") if hasattr(ff_settings, "elements"): ff_elements = getattr(ff_settings, "elements") with ScratchDir("."): input_file = self._setup() data = [] for struct in structures: ld = LammpsData.from_structure(struct, ff_elements) ld.write_file("data.static") p = subprocess.Popen([self.LMP_EXE, "-in", input_file], stdout=subprocess.PIPE) stdout = p.communicate()[0] rc = p.returncode if rc != 0: error_msg = "LAMMPS exited with return code %d" % rc msg = stdout.decode("utf-8").split("\n")[:-1] try: error_line = [ i for i, m in enumerate(msg) if m.startswith("ERROR") ][0] error_msg += ", ".join(msg[error_line:]) except Exception: error_msg += msg[-1] raise RuntimeError(error_msg) results = self._parse() data.append(results) return data
def _setup(self): template_dir = os.path.join(os.path.dirname(__file__), "templates", "defect") with open(os.path.join(template_dir, "in.defect"), "r") as f: defect_template = f.read() unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=self.alat) lattice_calculator = LatticeConstant(ff_settings=self.ff_settings) a, _, _ = lattice_calculator.calculate([unit_cell])[0] unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=a) if self.lattice == "fcc": idx, scale_factor = 95, [3, 3, 3] elif self.lattice == "bcc": idx, scale_factor = 40, [3, 3, 3] elif self.lattice == "diamond": idx, scale_factor = 7, [2, 2, 2] else: raise ValueError("Lattice type is invalid.") super_cell = unit_cell * scale_factor efs_calculator = EnergyForceStress(ff_settings=self.ff_settings) energy_per_atom = efs_calculator.calculate([super_cell ])[0][0] / len(super_cell) super_cell_ld = LammpsData.from_structure( super_cell, ff_elements=self.ff_settings.elements) super_cell_ld.write_file("data.supercell") input_file = "in.defect" with open(input_file, "w") as f: f.write( defect_template.format( ff_settings="\n".join(self.ff_settings.write_param()), lattice=self.lattice, alat=a, specie=self.specie, del_id=idx + 1, relaxed_file="data.relaxed", )) return input_file, energy_per_atom, len(super_cell) - 1
def _setup(self): template_dir = os.path.join(os.path.dirname(__file__), 'templates', 'defect') with open(os.path.join(template_dir, 'in.defect'), 'r') as f: defect_template = f.read() unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=self.alat) lattice_calculator = LatticeConstant(ff_settings=self.ff_settings) a, _, _ = lattice_calculator.calculate([unit_cell])[0] unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=a) if self.lattice == 'fcc': idx, scale_factor = 95, [3, 3, 3] elif self.lattice == 'bcc': idx, scale_factor = 40, [3, 3, 3] elif self.lattice == 'diamond': idx, scale_factor = 7, [2, 2, 2] else: raise ValueError("Lattice type is invalid.") super_cell = unit_cell * scale_factor efs_calculator = EnergyForceStress(ff_settings=self.ff_settings) energy_per_atom = efs_calculator.calculate([super_cell ])[0][0] / len(super_cell) super_cell_ld = LammpsData.from_structure(super_cell, atom_style='atomic') super_cell_ld.write_file('data.supercell') input_file = 'in.defect' with open(input_file, 'w') as f: f.write( defect_template.format(ff_settings='\n'.join( self.ff_settings.write_param()), lattice=self.lattice, alat=a, specie=self.specie, del_id=idx + 1, relaxed_file='data.relaxed')) return input_file, energy_per_atom, len(super_cell) - 1
def calculate(self, structures): """ Perform the calculation on a series of structures. Args: structures [Structure]: Input structures in a list. Returns: List of computed data corresponding to each structure, varies with different subclasses. """ for s in structures: assert self._sanity_check(s) is True, \ 'Incompatible structure found' ff_elements = None if hasattr(self, 'element_profile'): ff_elements = self.element_profile.keys() with ScratchDir('.'): input_file = self._setup() data = [] for s in structures: ld = LammpsData.from_structure(s, ff_elements) ld.write_file('data.static') p = subprocess.Popen([self.LMP_EXE, '-in', input_file], stdout=subprocess.PIPE) stdout = p.communicate()[0] rc = p.returncode if rc != 0: error_msg = 'LAMMPS exited with return code %d' % rc msg = stdout.decode("utf-8").split('\n')[:-1] try: error_line = [ i for i, m in enumerate(msg) if m.startswith('ERROR') ][0] error_msg += ', '.join([e for e in msg[error_line:]]) except Exception: error_msg += msg[-1] raise RuntimeError(error_msg) results = self._parse() data.append(results) return data
def from_structure(cls, structure, input_template, user_settings, data_filename="in.data", name="basic"): """ Returns inputset from structure Args: structure (Structure/Molecule): input_template (string): path to the input template file. user_settings (dict): User lammps settings, the keys must correspond to the keys in the template. data_filename (string): name of the the lammps data file. Returns: LammpsInputSet """ lammps_data = LammpsData.from_structure(structure) return cls.from_file(name, input_template, user_settings, lammps_data=lammps_data, data_filename=data_filename)
def test_from_structure(self): latt = Lattice.monoclinic(9.78746, 4.75058, 8.95892, 115.9693) structure = Structure.from_spacegroup(15, latt, ["Os", "O", "O"], [[0, 0.25583, 0.75], [0.11146, 0.46611, 0.91631], [0.11445, 0.04564, 0.69518]]) velocities = np.random.randn(20, 3) * 0.1 structure.add_site_property("velocities", velocities) ld = LammpsData.from_structure(structure=structure, ff_elements=["O", "Os", "Na"]) i = random.randint(0, 19) a = latt.matrix[0] va = velocities[i].dot(a) / np.linalg.norm(a) self.assertAlmostEqual(va, ld.velocities.loc[i + 1, "vx"]) self.assertAlmostEqual(velocities[i, 1], ld.velocities.loc[i + 1, "vy"]) np.testing.assert_array_almost_equal(ld.masses["mass"], [22.989769, 190.23, 15.9994]) np.testing.assert_array_equal(ld.atoms["type"], [2] * 4 + [3] * 16)
def test_structure(self): structure = self.lammps_data.structure self.assertEqual(len(structure.composition.elements), 2) self.assertEqual(structure.num_sites, 3) self.assertEqual(structure.formula, "Li2 O1") lammps_data = LammpsData.from_file(os.path.join(test_dir, "nvt.data"), 'full') self.assertEqual(type(lammps_data.structure).__name__, 'Structure') self.assertEqual(len(lammps_data.structure.composition.elements), 2) self.assertEqual(lammps_data.structure.num_sites, 648) self.assertEqual(lammps_data.structure.symbol_set[0], 'O') self.assertEqual(lammps_data.structure.symbol_set[1], 'H') self.assertEqual(lammps_data.structure.volume, 27000) # test tilt structure tilt_str = mg.Structure.from_file(os.path.join(test_dir, "POSCAR")) lmp_tilt_data = LammpsData.from_structure(tilt_str) s = StructureMatcher() groups = s.group_structures([lmp_tilt_data.structure, tilt_str]) self.assertEqual(len(groups), 1)
def writeLammpsStruct(struct, args): from pymatgen.io.lammps.data import LammpsData from pymatgen import Element from json import dumps, loads # Get the LammpsData object lammps_dict = LammpsData.from_structure(struct, atom_style="atomic").as_dict() # Relabel the atom types in the LammpsData object masses = { "columns": ["mass"], "index": [val for val in range(1, len(args["atom_mapping"]) + 1)] } mass_data = [None] * len(args["atom_mapping"]) for key in args["atom_mapping"].keys(): mass_data[args["atom_mapping"][key]] = [Element(key).atomic_mass] masses["data"] = mass_data lammps_dict["masses"] = dumps(masses) atoms = loads(lammps_dict["atoms"]) try: for i in range(len(atoms["data"])): atoms["data"][i][0] = args["atom_mapping"][ struct[i].species_string] + 1 except KeyError as e: raise Exception( "{} Missing From atom_mapping Keyword from Input File".format( e.args[0])) # Move the correct labels back to the LammpsData object lammps_dict["atoms"] = dumps(atoms) LammpsData.from_dict(lammps_dict).write_file("atom.data", distance=16, velocity=16, charge=16) return
break # remove old temporary directory if os.path.exists("./tmp"): shutil.rmtree("./tmp") # introduce a vacancy prior to secondary relaxation vacancy_structure = copy.deepcopy(bulk_relax_data.structure) vacancy_structure.remove_sites([i]) # create and enter a temporary directory for the secondary relaxation os.mkdir("./tmp") os.chdir("./tmp") # write the vacancy structure to file vacancy_data = LammpsData.from_structure(vacancy_structure, atom_style="atomic") with open("vacancy.lmp", "w") as f: f.write(vacancy_data.get_string()) # relax the vacancy structure settings = { "structure_path": "vacancy.lmp", "pair_style": CONFIGURATION["pair_style"], "potential_path": CONFIGURATION["potential_path"], "atom_types": CONFIGURATION["atom_types"], "output_path": "vacancy.relax.lmp", } write_lammps_inputs(".", secondary_relax_template, settings=settings) cmd = "$LAMMPS_SERIAL_BIN -in in.lammps >/dev/null" print("Running secondary structure relaxation...") os.system(cmd)
def setUpClass(cls): polymer_chain = Molecule.from_file(os.path.join(test_dir, "polymer_chain.xyz")) box_size = [[0.0, 20.0], [0.0, 20.0], [0.0, 20.0]] cls.lammps_data = LammpsData.from_structure(polymer_chain, box_size)
def _setup(self): template_dir = os.path.join(os.path.dirname(__file__), "templates", "neb") with open(os.path.join(template_dir, "in.relax"), "r") as f: relax_template = f.read() with open(os.path.join(template_dir, "in.neb"), "r") as f: neb_template = f.read() unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=self.alat) lattice_calculator = LatticeConstant(ff_settings=self.ff_settings) a, _, _ = lattice_calculator.calculate([unit_cell])[0] unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=a) if self.lattice == "fcc": start_idx, final_idx = 95, 49 scale_factor = [3, 3, 3] elif self.lattice == "bcc": start_idx, final_idx = 40, 14 scale_factor = [3, 3, 3] elif self.lattice == "diamond": start_idx, final_idx = 7, 15 scale_factor = [2, 2, 2] else: raise ValueError("Lattice type is invalid.") super_cell = unit_cell * scale_factor super_cell_ld = LammpsData.from_structure( super_cell, ff_elements=self.ff_settings.elements) super_cell_ld.write_file("data.supercell") with open("in.relax", "w") as f: f.write( relax_template.format( ff_settings="\n".join(self.ff_settings.write_param()), lattice=self.lattice, alat=a, specie=self.specie, del_id=start_idx + 1, relaxed_file="initial.relaxed", )) p = subprocess.Popen([self.LMP_EXE, "-in", "in.relax"], stdout=subprocess.PIPE) stdout = p.communicate()[0] rc = p.returncode if rc != 0: error_msg = "LAMMPS exited with return code %d" % rc msg = stdout.decode("utf-8").split("\n")[:-1] try: error_line = [ i for i, m in enumerate(msg) if m.startswith("ERROR") ][0] error_msg += ", ".join(msg[error_line:]) except Exception: error_msg += msg[-1] raise RuntimeError(error_msg) with open("in.relax", "w") as f: f.write( relax_template.format( ff_settings="\n".join(self.ff_settings.write_param()), lattice=self.lattice, alat=a, specie=self.specie, del_id=final_idx + 1, relaxed_file="final.relaxed", )) p = subprocess.Popen([self.LMP_EXE, "-in", "in.relax"], stdout=subprocess.PIPE) stdout = p.communicate()[0] rc = p.returncode if rc != 0: error_msg = "LAMMPS exited with return code %d" % rc msg = stdout.decode("utf-8").split("\n")[:-1] try: error_line = [ i for i, m in enumerate(msg) if m.startswith("ERROR") ][0] error_msg += ", ".join(msg[error_line:]) except Exception: error_msg += msg[-1] raise RuntimeError(error_msg) final_relaxed_struct = LammpsData.from_file( "final.relaxed", atom_style="charge").structure lines = ["{}".format(final_relaxed_struct.num_sites)] for idx, site in enumerate(final_relaxed_struct): if idx == final_idx: idx = final_relaxed_struct.num_sites elif idx == start_idx: idx = final_idx else: idx = idx lines.append("{} {:.3f} {:.3f} {:.3f}".format( idx + 1, site.x, site.y, site.z)) with open("data.final_replica", "w") as f: f.write("\n".join(lines)) input_file = "in.neb" with open(input_file, "w") as f: f.write( neb_template.format( ff_settings="\n".join(self.ff_settings.write_param()), start_replica="initial.relaxed", final_replica="data.final_replica", )) return input_file
def setUpClass(cls): polymer_chain = Molecule.from_file( os.path.join(test_dir, "polymer_chain.xyz")) box_size = [[0.0, 20.0], [0.0, 20.0], [0.0, 20.0]] cls.lammps_data = LammpsData.from_structure(polymer_chain, box_size)
def _setup(self): template_dir = os.path.join(os.path.dirname(__file__), 'templates', 'neb') with open(os.path.join(template_dir, 'in.relax'), 'r') as f: relax_template = f.read() with open(os.path.join(template_dir, 'in.neb'), 'r') as f: neb_template = f.read() unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=self.alat) lattice_calculator = LatticeConstant(ff_settings=self.ff_settings) a, _, _ = lattice_calculator.calculate([unit_cell])[0] unit_cell = self.get_unit_cell(specie=self.specie, lattice=self.lattice, alat=a) if self.lattice == 'fcc': start_idx, final_idx = 95, 49 scale_factor = [3, 3, 3] elif self.lattice == 'bcc': start_idx, final_idx = 40, 14 scale_factor = [3, 3, 3] elif self.lattice == 'diamond': start_idx, final_idx = 7, 15 scale_factor = [2, 2, 2] else: raise ValueError("Lattice type is invalid.") super_cell = unit_cell * scale_factor super_cell_ld = LammpsData.from_structure(super_cell, atom_style='atomic') super_cell_ld.write_file('data.supercell') with open('in.relax', 'w') as f: f.write( relax_template.format(ff_settings='\n'.join( self.ff_settings.write_param()), lattice=self.lattice, alat=a, specie=self.specie, del_id=start_idx + 1, relaxed_file='initial.relaxed')) p = subprocess.Popen([self.LMP_EXE, '-in', 'in.relax'], stdout=subprocess.PIPE) stdout = p.communicate()[0] rc = p.returncode if rc != 0: error_msg = 'LAMMPS exited with return code %d' % rc msg = stdout.decode("utf-8").split('\n')[:-1] try: error_line = [ i for i, m in enumerate(msg) if m.startswith('ERROR') ][0] error_msg += ', '.join([e for e in msg[error_line:]]) except: error_msg += msg[-1] raise RuntimeError(error_msg) with open('in.relax', 'w') as f: f.write( relax_template.format(ff_settings='\n'.join( self.ff_settings.write_param()), lattice=self.lattice, alat=a, specie=self.specie, del_id=final_idx + 1, relaxed_file='final.relaxed')) p = subprocess.Popen([self.LMP_EXE, '-in', 'in.relax'], stdout=subprocess.PIPE) stdout = p.communicate()[0] rc = p.returncode if rc != 0: error_msg = 'LAMMPS exited with return code %d' % rc msg = stdout.decode("utf-8").split('\n')[:-1] try: error_line = [ i for i, m in enumerate(msg) if m.startswith('ERROR') ][0] error_msg += ', '.join([e for e in msg[error_line:]]) except: error_msg += msg[-1] raise RuntimeError(error_msg) final_relaxed_struct = LammpsData.from_file( 'final.relaxed', atom_style='atomic').structure lines = ['{}'.format(final_relaxed_struct.num_sites)] for idx, site in enumerate(final_relaxed_struct): if idx == final_idx: idx = final_relaxed_struct.num_sites elif idx == start_idx: idx = final_idx else: idx = idx lines.append('{} {:.3f} {:.3f} {:.3f}'.format( idx + 1, site.x, site.y, site.z)) with open('data.final_replica', 'w') as f: f.write('\n'.join(lines)) input_file = 'in.neb' with open(input_file, 'w') as f: f.write( neb_template.format(ff_settings='\n'.join( self.ff_settings.write_param()), start_replica='initial.relaxed', final_replica='data.final_replica')) return input_file
def setUpClass(cls): h2o_coords = [[9.626, 6.787, 12.673], [9.626, 8.420, 12.673], [10.203, 7.604, 12.673]] molecule = Molecule(["H", "H", "O"], h2o_coords) box_size = [[0.0, 10.0], [0.0, 10.0], [0.0, 10.0]] cls.lammps_data = LammpsData.from_structure(molecule, box_size)
def get_dump(self, structure, elements): """Convert Pymatgen structure object to LAMMPS dump file.""" data = LammpsData.from_structure(structure, elements) return data