def test_new(): trjfilename = os.path.join(MODULE_DIR, 'tests/sample_files/NaSCN.lammpstrj') datfilename = os.path.join(MODULE_DIR, 'tests/sample_files/data.water_1NaSCN') logfilename = os.path.join(MODULE_DIR, 'tests/sample_files/mol.log') lrun = LammpsRun(datfilename, trjfilename, logfilename) comx, comy, comz = lrun._weighted_average()
def run_task(self, fw_spec): lammps_input = self["lammps_input"] diffusion_params = self.get("diffusion_params", {}) # get the directory that contains the LAMMPS dir to parse calc_dir = os.getcwd() if "calc_dir" in self: calc_dir = self["calc_dir"] elif self.get("calc_loc"): calc_dir = get_calc_loc(self["calc_loc"], fw_spec["calc_locs"])["path"] # parse the directory logger.info("PARSING DIRECTORY: {}".format(calc_dir)) d = {} d["dir_name"] = os.path.abspath(os.getcwd()) d["last_updated"] = datetime.today() d["input"] = lammps_input.as_dict() log_file = lammps_input.config_dict["log"] if isinstance(lammps_input.config_dict["dump"], list): dump_file = lammps_input.config_dict["dump"][0].split()[4] else: dump_file = lammps_input.config_dict["dump"].split()[4] is_forcefield = hasattr(lammps_input.lammps_data, "bonds_data") lammpsrun = LammpsRun(lammps_input.data_filename, dump_file, log_file, is_forcefield=is_forcefield) d["natoms"] = lammpsrun.natoms d["nmols"] = lammpsrun.nmols d["box_lengths"] = lammpsrun.box_lengths d["mol_masses"] = lammpsrun.mol_masses d["mol_config"] = lammpsrun.mol_config if diffusion_params: diffusion_analyzer = lammpsrun.get_diffusion_analyzer( **diffusion_params) d["analysis"]["diffusion"] = diffusion_analyzer.get_summary_dict() db_file = env_chk(self.get('db_file'), fw_spec) # db insertion if not db_file: with open("task.json", "w") as f: f.write(json.dumps(d, default=DATETIME_HANDLER)) else: mmdb = MMLammpsDb.from_db_file(db_file) # insert the task document t_id = mmdb.insert(d) logger.info("Finished parsing with task_id: {}".format(t_id)) return FWAction(stored_data={"task_id": d.get("task_id", None)})
def test_serialization(self): d = self.lammpsrun.as_dict() lmps_run = LammpsRun.from_dict(d) self.assertDictEqual(d, lmps_run.as_dict()) d2 = self.lmps_log.as_dict() lmps_log = LammpsLog.from_dict(d2) self.assertDictEqual(d2, lmps_log.as_dict())
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 setUpClass(cls): data_file = os.path.join(test_dir, "nvt.data") traj_file = os.path.join(test_dir, "nvt.dump") log_file = os.path.join(test_dir, "nvt.log") cls.lammpsrun = LammpsRun(data_file, traj_file, log_file, is_forcefield=True)
def run_task(self, fw_spec): lammps_input = self["lammps_input"] diffusion_params = self.get("diffusion_params", {}) # get the directory that contains the LAMMPS dir to parse calc_dir = os.getcwd() if "calc_dir" in self: calc_dir = self["calc_dir"] elif self.get("calc_loc"): calc_dir = get_calc_loc(self["calc_loc"], fw_spec["calc_locs"])["path"] # parse the directory logger.info("PARSING DIRECTORY: {}".format(calc_dir)) d = {} d["dir_name"] = os.path.abspath(os.getcwd()) d["last_updated"] = datetime.today() d["input"] = lammps_input.as_dict() log_file = lammps_input.config_dict["log"] if isinstance(lammps_input.config_dict["dump"], list): dump_file = lammps_input.config_dict["dump"][0].split()[4] else: dump_file = lammps_input.config_dict["dump"].split()[4] is_forcefield = hasattr(lammps_input.lammps_data, "bonds_data") lammpsrun = LammpsRun(lammps_input.data_filename, dump_file, log_file, is_forcefield=is_forcefield) d["natoms"] = lammpsrun.natoms d["nmols"] = lammpsrun.nmols d["box_lengths"] = lammpsrun.box_lengths d["mol_masses"] = lammpsrun.mol_masses d["mol_config"] = lammpsrun.mol_config if diffusion_params: diffusion_analyzer = lammpsrun.get_diffusion_analyzer(**diffusion_params) d["analysis"]["diffusion"] = diffusion_analyzer.get_summary_dict() db_file = env_chk(self.get('db_file'), fw_spec) # db insertion if not db_file: with open("task.json", "w") as f: f.write(json.dumps(d, default=DATETIME_HANDLER)) else: mmdb = MMLammpsDb.from_db_file(db_file) # insert the task document t_id = mmdb.insert(d) logger.info("Finished parsing with task_id: {}".format(t_id)) return FWAction(stored_data={"task_id": d.get("task_id", None)})
def assimilate(self, path, input_filename, log_filename="log.lammps", is_forcefield=False, data_filename=None, dump_files=None): """ Parses lammps input, data and log files and insert the result into the db. Args: path (str): path to the run folder input_filename (str): just the name of the input file log_filename (str): lammps log file name is_forcefield (bool): whether or not ot parse forcefield info data_filename (str): name of the data file dump_files ([str]): list of dump file names Returns: dict """ input_file = os.path.join(path, input_filename) data_file = os.path.join(path, data_filename) if data_filename else None log_file = os.path.join(path, log_filename) dump_files = dump_files or [] dump_files = [dump_files] if isinstance( dump_files, six.string_types) else dump_files # input set lmps_input = LammpsInputSet.from_file("lammps", input_file, {}, data_file, data_filename) # dumps dumps = [] if dump_files: for df in dump_files: dumps.append((df, LammpsDump.from_file(os.path.join(path, df)))) # log log = LammpsLog(log_file=log_file) logger.info("Getting task doc for base dir :{}".format(path)) d = self.generate_doc(path, lmps_input, log, dumps) lmps_run = None if len(dump_files) == 1 and data_file: lmps_run = LammpsRun(data_file, dump_files[0], log_file=log_filename) self.post_process(d, lmps_run) return d
def test_conductivity(): trjfilename = [ os.path.join(MODULE_DIR, 'tests/sample_files/NaSCN.lammpstrj') ] datfilename = os.path.join(MODULE_DIR, 'tests/sample_files/data.water_1NaSCN') logfilename = os.path.join(MODULE_DIR, 'tests/sample_files/mol.log') lrun = LammpsRun(datfilename, trjfilename, logfilename) cc = Conductivity() T = 350 # from lammpsio output = {} output['Conductivity'] = {} output['Conductivity']['units'] = 'S/m' (nummoltype, moltypel, moltype) = lrun.get_mols() n = lrun.natoms() (molcharges, atomcharges, n) = lrun.get_mol_charges(n) output = cc.calcConductivity(molcharges, trjfilename, logfilename, datfilename, T, output) print((output['Conductivity']['Green_Kubo']))
def calcConductivity(self, molcharges, trjfilename, logfilename, datfilename, T, output): lrun = LammpsRun(datfilename, trjfilename, logfilename) dt = lrun.timestep tsjump = lrun.jump(trjfilename) (num_lines, n, num_timesteps, count, line) = self.getnum(trjfilename) atommass = self.getmass(datfilename) V = self.getdimensions(trjfilename[0]) (vx, vy, vz, mol, atype, j, J) = self.createarrays(n, num_timesteps) (vxcol, vycol, vzcol, idcol, molcol, typecol) = self.getcolumns(trjfilename[0]) for i in range(0, len(trjfilename)): trjfile = open(trjfilename[i]) while line[i] < num_lines[i]: (vx, vy, vz, line, mol, atype) = self.readdata(trjfile, n, line, vx, vy, vz, vxcol, vycol, vzcol, idcol, i, mol, molcol, atype, typecol) if count == 0: (comvx, comvy, comvz, nummol, molmass) = self.COMprep(mol, atype, atommass, n) (comvx, comvy, comvz) = self.calcCOMv(comvx, comvy, comvz, vx, vy, vz, mol, atype, atommass, molmass, n, nummol) (j, count) = self.calcj(molcharges, comvx, comvy, comvz, j, count) J = self.clacJ(j, J) integral = self.integrateJ(J, tsjump * dt) time = [] for i in range(0, len(integral)): time.append(i * tsjump * dt) popt = self.fitcurve(time, integral) cond = self.greenkubo(popt, T, V) output['Conductivity']['Green_Kubo'] = cond file = open('integral.dat', 'w') for i in range(0, len(integral)): file.write(str(integral[i]) + '\n') return output
def test_other(): """ Sample driver file to calculate the MSD and diffusivity for all molecules in a system as well as the center of mass radial distribution function for all pairs of molecules in the system. Will also integrate the rdf to get the coordination number and calculate the ion pair lifetime for the system Requires the following comments in the lammps data file starting at the third line # 'number' 'molecule' molecules where 'number' is the number of that molecule type and 'molecule' is a name for that molecule Do not include blank lines in between the molecule types Outputs are stored in a dictionary called output to later be stored in JSON format """ trjfilename = [ os.path.join(MODULE_DIR, 'tests/sample_files/NaSCN.lammpstrj') ] datfilename = os.path.join(MODULE_DIR, 'tests/sample_files/data.water_1NaSCN') logfilename = os.path.join(MODULE_DIR, 'tests/sample_files/mol.log') lrun = LammpsRun(datfilename, trjfilename, logfilename) c = CenterOfMass() m = MeanSquareDisplacement() crd = RadialDistributionPure() ne = NernstEinsteinConductivity() cn = CoordinationNumber() ip = IonPair() output = {} output['RDF'] = {} output['RDF']['units'] = 'unitless and angstroms' output['Conductivity'] = {} output['Conductivity']['units'] = 'S/m' T = 298 # get from lammpsio tsjump = lrun.jump() (nummoltype, moltypel, moltype) = lrun.get_mols() dt = lrun.timestep n = lrun.natoms() (molcharges, atomcharges, n) = lrun.get_mol_charges(n) molcharge = lrun.get_mol_charge_dict(molcharges, moltypel, moltype) (comx, comy, comz, Lx, Ly, Lz, Lx2, Ly2, Lz2) = c.calcCOM(trjfilename, datfilename) output = m.runMSD(comx, comy, comz, Lx, Ly, Lz, Lx2, Ly2, Lz2, moltype, moltypel, dt, tsjump, output) output = ne.calcNEconductivity(output, molcharge, Lx, Ly, Lz, nummoltype, moltypel, T) ip.runionpair(comx, comy, comz, Lx, Ly, Lz, moltypel, moltype, tsjump, dt, output, skipframes=0) output = crd.runradial(datfilename, comx, comy, comz, Lx, Ly, Lz, Lx2, Ly2, Lz2, output, nummoltype, moltypel, moltype, firststep=1) output = cn.compute(output, nummoltype, moltypel, Lx * Ly * Lz)
def setUpClass(cls): data_file = os.path.join(test_dir, "nvt.data") traj_file = os.path.join(test_dir, "nvt.dump") log_file = os.path.join(test_dir, "nvt.log") cls.lmps_log = LammpsLog(log_file=log_file) cls.lammpsrun = LammpsRun(data_file, traj_file, log_file)
def lampps_properties(self, trjfile, datafile, logfile): """ calculate the MSD and diffusivity for all molecules in a system as well as the center of mass radial distribution function for all pairs of molecules in the system Requires the following comments in the lammps data file starting at the third line # "number" "molecule" molecules where "number" is the number of that molecule type and "molecule" is a name for that molecule Do not include blank lines in between the molecule types Outputs are stored in a dictionary called output to later be stored in JSON format :return: Output """ lrun = LammpsRun(datafile, trjfile, logfile) c = CenterOfMass() m = MeanSquareDisplacement() crd = RadialDistributionPure() ne = NernstEinsteinConductivity() output = {} output['RDF'] = {} output['RDF']['units'] = 'unitless and angstroms' output['Conductivity'] = {} output['Conductivity']['units'] = 'S/m' T = 298 # get from lammpsio tsjump = lrun.jump() (nummoltype, moltypel, moltype) = lrun.get_mols() dt = lrun.timestep n = lrun.natoms() (molcharges, atomcharges, n) = lrun.get_mol_charges(n) molcharge = lrun.get_mol_charge_dict(molcharges, moltypel, moltype) (comx, comy, comz, Lx, Ly, Lz, Lx2, Ly2, Lz2) = c.calcCOM([trjfile], datafile) output = m.runMSD(comx, comy, comz, Lx, Ly, Lz, Lx2, Ly2, Lz2, moltype, moltypel, dt, tsjump, output) output = ne.calcNEconductivity(output, molcharge, Lx, Ly, Lz, nummoltype, moltypel, T) output = crd.runradial(datafile, comx, comy, comz, Lx, Ly, Lz, Lx2, Ly2, Lz2, output, nummoltype, moltypel, moltype, firststep=1) return output