def read_json(filedesc, **kwargs): """Reads a JSON-style file with i-pi style comments and creates an Atoms and Cell object. Args: filedesc: An open readable file object from a json formatted file with i-PI header comments. Returns: An Atoms object with the appropriate atom labels, masses and positions. A Cell object. """ try: line = json.loads(filedesc.readline()) except ValueError: raise EOFError("The file descriptor hit EOF.") atoms = Atoms(line[0]) atoms.q = np.asarray(line[8]) atoms.names = np.asarray(line[9], dtype='|S4') atoms.m = np.asarray(map(Elements.mass, atoms.names)) a = float(line[1]) b = float(line[2]) c = float(line[3]) alpha = float(line[4]) * np.pi / 180 beta = float(line[5]) * np.pi / 180 gamma = float(line[6]) * np.pi / 180 h = mt.abc2h(a, b, c, alpha, beta, gamma) cell = Cell(h) return {"atoms": atoms, "cell": cell}
def create_random_xyz_traj_to_write(request): natoms, frames, comment, expected_cell, precision = request.param a, b, c, alpha, beta, gamma = mt.h2abc_deg(expected_cell) fmt_header = "# CELL(abcABC): %10.5f %10.5f %10.5f %10.5f %10.5f %10.5f %s" comment = fmt_header % (a, b, c, alpha, beta, gamma, comment) filedesc, xyz, atom_names = xyz_gen.xyz_traj_filedesc(natoms, frames, comment) filedesc.seek(0) masses = [Elements.mass(_am) for _am in atom_names] cell_list = [] atoms_list = [] for _fr in xrange(frames): cell = Cell(expected_cell) atoms = Atoms(natoms) atoms.q[:] = xyz[_fr * natoms * 3:(_fr + 1) * natoms * 3] atoms.names = atom_names[_fr * natoms:(_fr + 1) * natoms] atoms.m[:] = masses[_fr * natoms:(_fr + 1) * natoms] atoms_list.append(atoms) cell_list.append(cell) return (filedesc, atoms_list, cell_list, comment, precision)
def main(prefix, suffix="pos", outprefix="fixcom"): ipos = [] imode = [] for filename in sorted(glob.glob(prefix + "." + suffix + "*")): imode.append(filename.split(".")[-1]) ipos.append(open(filename, "r")) nbeads = len(ipos) natoms = 0 ifr = 0 lout = [] for b in range(nbeads): # zero-padded bead number padb = ("%0" + str(int(1 + np.floor(np.log(nbeads) / np.log(10)))) + "d") % (b) lout.append( open( prefix + "." + outprefix + "." + suffix + "_" + padb + "." + imode[b], "a", ) ) while True: allbeads = [] for i in range(nbeads): try: poscell = read_file(imode[i], ipos[i]) cell = poscell["cell"] pos = poscell["atoms"] allbeads.append(pos) if natoms == 0: natoms = pos.natoms atoms = Atoms(natoms) atoms.q += pos.q atoms.names = pos.names atoms.m += pos.m except EOFError: # finished reading files for ib in range(nbeads): lout[ib].close() sys.exit(0) atoms.q /= nbeads atoms.m /= nbeads com = np.zeros(3) tm = 0 for i in range(atoms.natoms): com += atoms.m[i] * atoms.q[3 * i : 3 * (i + 1)] tm += atoms.m[i] com /= tm for ib in range(nbeads): for i in range(allbeads[ib].natoms): allbeads[ib].q[3 * i : 3 * (i + 1)] -= com print_file(imode[ib], allbeads[ib], cell, filedesc=lout[ib]) atoms.q[:] = 0.0 atoms.m[:] = 0.0 ifr += 1
def read_pdb(filedesc): """Takes a pdb-style file and creates an Atoms and Cell object. Args: filedesc: An open readable file object from a pdb formatted file. Returns: An Atoms object with the appropriate atom labels, masses and positions, and a Cell object with the appropriate cell dimensions and an estimate of a reasonable cell mass. """ header = filedesc.readline() if "TITLE" in header: header = filedesc.readline() # skip the comment field if header == "": raise EOFError("End of file or empty header in PDB file") a = float(header[6:15]) b = float(header[15:24]) c = float(header[24:33]) alpha = float(header[33:40]) beta = float(header[40:47]) gamma = float(header[47:54]) alpha *= np.pi / 180.0 beta *= np.pi / 180.0 gamma *= np.pi / 180.0 h = mt.abc2h(a, b, c, alpha, beta, gamma) cell = Cell(h) natoms = 0 body = filedesc.readline() qatoms = [] names = [] masses = [] while (body.strip() != "" and body.strip() != "END"): natoms += 1 name = body[12:16].strip() names.append(name) masses.append(Elements.mass(name)) x = float(body[31:39]) y = float(body[39:47]) z = float(body[47:55]) qatoms.append(x) qatoms.append(y) qatoms.append(z) body = filedesc.readline() atoms = Atoms(natoms) atoms.q = np.asarray(qatoms) atoms.names = np.asarray(names, dtype='|S4') atoms.m = np.asarray(masses) return atoms, cell
def read_pdb(filedesc): """Takes a pdb-style file and creates an Atoms and Cell object. Args: filedesc: An open readable file object from a pdb formatted file. Returns: An Atoms object with the appropriate atom labels, masses and positions, and a Cell object with the appropriate cell dimensions and an estimate of a reasonable cell mass. """ header = filedesc.readline() if "TITLE" in header: header = filedesc.readline() # skip the comment field if header == "": raise EOFError("End of file or empty header in PDB file") a = float(header[6:15]) b = float(header[15:24]) c = float(header[24:33]) alpha = float(header[33:40]) beta = float(header[40:47]) gamma = float(header[47:54]) alpha *= np.pi/180.0 beta *= np.pi/180.0 gamma *= np.pi/180.0 h = mt.abc2h(a, b, c, alpha, beta, gamma) cell = Cell(h) natoms = 0 body = filedesc.readline() qatoms = [] names = [] masses = [] while (body.strip() != "" and body.strip() != "END"): natoms += 1 name = body[12:16].strip() names.append(name) masses.append(Elements.mass(name)) x = float(body[31:39]) y = float(body[39:47]) z = float(body[47:55]) qatoms.append(x) qatoms.append(y) qatoms.append(z) body = filedesc.readline() atoms = Atoms(natoms) atoms.q = np.asarray(qatoms) atoms.names = np.asarray(names,dtype='|S4') atoms.m = np.asarray(masses) return atoms, cell
def read_xyz(filedesc): """Takes a xyz-style file and creates an Atoms object. Args: filedesc: An open readable file object from a xyz formatted file. Returns: An Atoms object with the appropriate atom labels, masses and positions. """ natoms = filedesc.readline() if natoms == "": raise EOFError("The file descriptor hit EOF.") natoms = int(natoms) comment = filedesc.readline() qatoms = [] names = [] masses = [] iat = 0 while (iat < natoms): body = filedesc.readline() if body.strip() == "": break body = body.split() name = body[0] names.append(name) masses.append(Elements.mass(name)) x = float(body[1]) y = float(body[2]) z = float(body[3]) qatoms.append(x) qatoms.append(y) qatoms.append(z) iat += 1 if natoms != len(names): raise ValueError( "The number of atom records does not match the header of the xyz file." ) atoms = Atoms(natoms) # for i in range(natoms): # nat = atoms[i] # nat.q = qatoms[i] # nat.name = names[i] # nat.m = Elements.mass(names[i]) atoms.q = np.asarray(qatoms) atoms.names = np.asarray(names, dtype='|S4') atoms.m = np.asarray(masses) return atoms
def read_xyz(filedesc): """Takes a xyz-style file and creates an Atoms object. Args: filedesc: An open readable file object from a xyz formatted file. Returns: An Atoms object with the appropriate atom labels, masses and positions. """ natoms = filedesc.readline() if natoms == "": raise EOFError("The file descriptor hit EOF.") natoms = int(natoms) comment = filedesc.readline() qatoms = [] names = [] masses = [] iat = 0 while iat < natoms: body = filedesc.readline() if body.strip() == "": break body = body.split() name = body[0] names.append(name) masses.append(Elements.mass(name)) x = float(body[1]) y = float(body[2]) z = float(body[3]) qatoms.append(x) qatoms.append(y) qatoms.append(z) iat += 1 if natoms != len(names): raise ValueError("The number of atom records does not match the header of the xyz file.") atoms = Atoms(natoms) # for i in range(natoms): # nat = atoms[i] # nat.q = qatoms[i] # nat.name = names[i] # nat.m = Elements.mass(names[i]) atoms.q = np.asarray(qatoms) atoms.names = np.asarray(names, dtype="|S4") atoms.m = np.asarray(masses) return atoms
def contract_trajectory(fns_in, fn_out_template, n_new, cell_units_in, cell_units_out): verbosity.level = "low" n = len(fns_in) # Generate output file names. if n_new == 1: fns_out = [fn_out_template] else: fns_out = [fn_out_template.format(i) for i in range(n_new)] print("Contracting {:d} beads to {:d} beads.".format(n, n_new)) print() print("input file names:") for fn in fns_in: print(fn) print() print("output file names:") for fn in fns_out: print(fn) print() # Open input trajectory iterators. trjs_in = [iter_file_name_raw(fn) for fn in fns_in] mode = os.path.splitext(fn)[-1] # Open output files. fs_out = [open_backup(fn, "w") for fn in fns_out] mode_out = os.path.splitext(fn_out_template)[-1] # prepare ring polymer rescaler rescale = nm_rescale(n, n_new) # Loop over all frames. i_frame = 0 while True: try: # Get the frames for all beads. frames = [trj.next() for trj in trjs_in] except StopIteration: # Stop when any of the trajectories runs out of frames. break # gets units from first frame dimension, units, cell_units = auto_units(comment=frames[0]["comment"], cell_units=cell_units_in) if cell_units_out == "automatic": cell_units_out = cell_units # re-use units unless otherwise specified # Consistency check. h = frames[0]["cell"] natoms = len(frames[0]["data"]) / 3 for i in range(n): # Check that all the cells are the same. if (frames[i]["cell"] != h).any(): msg = "Cell for beads {:d} and {:d} differ in frame {:d}." raise ValueError(msg.format(0, i, i_frame)) # Check that the numbers of atoms are the same. if len(frames[i]["data"]) != 3 * natoms: msg = "Different numbers of atoms for beads {:d} and {:d} in frame {:d}." raise ValueError(msg.format(0, i, i_frame)) cell = Cell() cell.h = frames[0]["cell"] atoms = Atoms(natoms) atoms.names = frames[0]["names"] # Compose the ring polymer. q = np.vstack([frame["data"] for frame in frames]) * unit_to_internal(dimension, units, 1) # units transformation # Contract the coordinates to `n_new` beads. q_c = rescale.b1tob2(q) # Save the output data. for i, f_out in enumerate(fs_out): atoms.q = q_c[i, :] print_file(mode_out, atoms, cell, f_out, dimension=dimension, units=units, cell_units=cell_units_out) # Count frames and print information on progress. i_frame += 1 if i_frame % 100 == 0: print("\rframe {:d}".format(i_frame), end="") sys.stdout.flush() for f_out in fs_out: f_out.close() print() print() print("Processed {:d} frames.".format(i_frame))
def contract_trajectory(fns_in, fn_out_template, n_new, cell_units_in, cell_units_out): verbosity.level = "low" n = len(fns_in) # Generate output file names. if n_new == 1: fns_out = [fn_out_template] else: fns_out = [fn_out_template.format(i) for i in range(n_new)] print("Contracting {:d} beads to {:d} beads.".format(n, n_new)) print() print("input file names:") for fn in fns_in: print(fn) print() print("output file names:") for fn in fns_out: print(fn) print() # Open input trajectory iterators. trjs_in = [iter_file_name_raw(fn) for fn in fns_in] mode = os.path.splitext(fn)[-1] # Open output files. fs_out = [open_backup(fn, "w") for fn in fns_out] mode_out = os.path.splitext(fn_out_template)[-1] # prepare ring polymer rescaler rescale = nm_rescale(n, n_new) # Loop over all frames. i_frame = 0 while True: try: # Get the frames for all beads. frames = [trj.next() for trj in trjs_in] except StopIteration: # Stop when any of the trajectories runs out of frames. break # gets units from first frame dimension, units, cell_units = auto_units(comment=frames[0]["comment"], cell_units=cell_units_in) if cell_units_out == "automatic": cell_units_out = cell_units # re-use units unless otherwise specified # Consistency check. h = frames[0]["cell"] natoms = len(frames[0]["data"]) / 3 for i in range(n): # Check that all the cells are the same. if (frames[i]["cell"] != h).any(): msg = "Cell for beads {:d} and {:d} differ in frame {:d}." raise ValueError(msg.format(0, i, i_frame)) # Check that the numbers of atoms are the same. if len(frames[i]["data"]) != 3 * natoms: msg = "Different numbers of atoms for beads {:d} and {:d} in frame {:d}." raise ValueError(msg.format(0, i, i_frame)) cell = Cell() cell.h = frames[0]["cell"] atoms = Atoms(natoms) atoms.names = frames[0]["names"] # Compose the ring polymer. q = np.vstack([frame["data"] for frame in frames]) * unit_to_internal( dimension, units, 1) # units transformation # Contract the coordinates to `n_new` beads. q_c = rescale.b1tob2(q) # Save the output data. for i, f_out in enumerate(fs_out): atoms.q = q_c[i, :] print_file(mode_out, atoms, cell, f_out, dimension=dimension, units=units, cell_units=cell_units_out) # Count frames and print information on progress. i_frame += 1 if i_frame % 100 == 0: print("\rframe {:d}".format(i_frame), end="") sys.stdout.flush() for f_out in fs_out: f_out.close() print() print() print("Processed {:d} frames.".format(i_frame))