def open_stream(self, mode): """Opens the output stream(s).""" # prepare format string for zero-padded number of beads, # including underscpre fmt_bead = "{0:0" + str(int(1 + np.floor(np.log(self.system.beads.nbeads) / np.log(10)))) + "d}" if getkey(self.what) in ["positions", "velocities", "forces", "extras", "forces_sc", "momenta"]: # must write out trajectories for each bead, so must create b streams # prepare format string for file name if getkey(self.what) == "extras": fmt_fn = self.filename + "_" + fmt_bead else: fmt_fn = self.filename + "_" + fmt_bead + "." + self.format # open all files self.out = [] for b in range(self.system.beads.nbeads): if (self.ibead < 0 and (b % (-self.ibead) == 0)) or (self.ibead == b): self.out.append(open_backup(fmt_fn.format(b), mode)) else: # Create null outputs if a single bead output is chosen. self.out.append(None) else: # open one file filename = self.filename + "." + self.format self.out = open_backup(filename, mode)
def open_stream(self): """Opens the output stream(s).""" if getkey(self.what) in [ "positions", "velocities", "forces", "extras" ]: # must write out trajectories for each bead, so must create b streams self.out = [] for b in range(self.simul.beads.nbeads): # zero-padded bead number padb = ( ("%0" + str(int(1 + np.floor(np.log(self.simul.beads.nbeads)/np.log(10)))) + "d") % (b) ) try: if (self.ibead < 0 or self.ibead == b): if getkey(self.what) == "extras": self.out.append(open(self.filename + "_" + padb, "a")) else: self.out.append(open(self.filename + "_" + padb + "." + self.format, "a")) else: self.out.append(None) # creates null outputs if a # single bead output is chosen except: raise ValueError("Could not open file " + self.filename + "_" + padb + "." + self.format + " for output") else: try: self.out = ( open(self.filename + "." + self.format, "a") ) except: raise ValueError("Could not open file " + self.filename + "." + self.format + " for output")
def open_stream(self): """Opens the output stream.""" # Is this the start of the simulation? is_start = self.system.simul.step == 0 # Only open a new file if this is a new run, otherwise append. if is_start: mode = "w" else: mode = "a" self.out = open_backup(self.filename, mode) # print nice header if information is available on the properties if is_start: icol = 1 for what in self.outlist: ohead = "# " key = getkey(what) prop = self.system.properties.property_dict[key] if "size" in prop and prop["size"] > 1: ohead += "cols. %3d-%-3d" % (icol, icol + prop["size"] - 1) icol += prop["size"] else: ohead += "column %3d " % (icol) icol += 1 ohead += " --> %s " % (what) if "help" in prop: ohead += ": " + prop["help"] self.out.write(ohead + "\n")
def open_stream(self): """Opens the output stream.""" try: self.out = open(self.filename, "a") except: raise ValueError("Could not open file " + self.filename + " for output") # print nice header if information is available on the properties if (self.simul.step == 0): icol = 1 for what in self.outlist: ohead = "# " key = getkey(what) prop = self.simul.properties.property_dict[key] if "size" in prop and prop["size"] > 1: ohead += "cols. %3d-%-3d" % (icol, icol + prop["size"] - 1) icol += prop["size"] else: ohead += "column %3d " % (icol) icol += 1 ohead += " --> %s " % (what) if "help" in prop: ohead += ": " + prop["help"] self.out.write(ohead + "\n")
def write(self): """Writes out the required trajectories.""" if softexit.triggered: return # don't write if we are about to exit! if not (self.system.simul.step + 1) % self.stride == 0: return doflush = False self.nout += 1 if self.flush > 0 and self.nout >= self.flush: doflush = True self.nout = 0 data, dimension, units = self.system.trajs[self.what] # gets the trajectory data that must be printed # quick-and-dirty way to check if a trajectory is "global" or per-bead # Checks to see if there is a list of files or just a single file. if hasattr(self.out, "__getitem__"): if self.ibead < 0: for b in range(len(self.out)): if self.out[b] is not None: self.write_traj(data, self.what, self.out[b], b, format=self.format, dimension=dimension, units=units, cell_units=self.cell_units, flush=doflush) elif self.ibead < len(self.out): self.write_traj(data, self.what, self.out[self.ibead], self.ibead, format=self.format, dimension=dimension, units=units, cell_units=self.cell_units, flush=doflush) else: raise ValueError("Selected bead index " + str(self.ibead) + " does not exist for trajectory " + self.what) else: self.write_traj(data, getkey(self.what), self.out, b=0, format=self.format, dimension=dimension, units=units, cell_units=self.cell_units, flush=doflush)
def open_stream(self): """Opens the output stream.""" try: self.out = open(self.filename, "a") except: raise ValueError("Could not open file " + self.filename + " for output") # print nice header if information is available on the properties if (self.simul.step == 0) : icol = 1 for what in self.outlist: ohead = "# " key = getkey(what) prop = self.simul.properties.property_dict[key] if "size" in prop and prop["size"] > 1: ohead += "cols. %3d-%-3d" % ( icol, icol+prop["size"] - 1 ) icol += prop["size"] else: ohead += "column %3d " % ( icol ) icol += 1 ohead += " --> %s " % (what) if "help" in prop: ohead += ": " + prop["help"] self.out.write(ohead + "\n")
def write(self): """Writes out the required trajectories.""" if softexit.triggered: return # don't write if we are about to exit! if not (self.system.simul.step + 1) % self.stride == 0: return doflush = False self.nout += 1 if self.flush > 0 and self.nout >= self.flush: doflush = True self.nout = 0 data, dimension, units = self.system.trajs[ self.what] # gets the trajectory data that must be printed # quick-and-dirty way to check if a trajectory is "global" or per-bead # Checks to see if there is a list of files or just a single file. if hasattr(self.out, "__getitem__"): if self.ibead < 0: for b in range(len(self.out)): if self.out[b] is not None: self.write_traj( data, self.what, self.out[b], b, format=self.format, dimension=dimension, units=units, cell_units=self.cell_units, flush=doflush, ) elif self.ibead < len(self.out): self.write_traj( data, self.what, self.out[self.ibead], self.ibead, format=self.format, dimension=dimension, units=units, cell_units=self.cell_units, flush=doflush, ) else: raise ValueError("Selected bead index " + str(self.ibead) + " does not exist for trajectory " + self.what) else: self.write_traj( data, getkey(self.what), self.out, b=0, format=self.format, dimension=dimension, units=units, cell_units=self.cell_units, flush=doflush, )
def open_stream(self): """Opens the output stream(s).""" # Is this the start of the simulation? is_start = self.system.simul.step == 0 # Only open a new file if this is a new run, otherwise append. if is_start: mode = "w" else: mode = "a" # prepare format string for zero-padded number of beads, # including underscpre fmt_bead = "{0:0" + str( int(1 + np.floor(np.log(self.system.beads.nbeads) / np.log(10)))) + "d}" if getkey(self.what) in [ "positions", "velocities", "forces", "extras", "forces_sc", "momenta" ]: # must write out trajectories for each bead, so must create b streams # prepare format string for file name if getkey(self.what) == "extras": fmt_fn = self.filename + "_" + fmt_bead else: fmt_fn = self.filename + "_" + fmt_bead + "." + self.format # open all files self.out = [] for b in range(self.system.beads.nbeads): if (self.ibead < 0 and (b % (-self.ibead) == 0)) or (self.ibead == b): self.out.append(open_backup(fmt_fn.format(b), mode)) else: # Create null outputs if a single bead output is chosen. self.out.append(None) else: # open one file filename = self.filename + "." + self.format self.out = open_backup(filename, mode)
def open_stream(self, mode): """Opens the output stream(s).""" # prepare format string for zero-padded number of beads, # including underscore fmt_bead = ("{0:0" + str( int(1 + np.floor(np.log(self.system.beads.nbeads) / np.log(10)))) + "d}") if getkey(self.what) in [ "positions", "velocities", "forces", "extras", "extras_component", "forces_sc", "momenta", ]: # must write out trajectories for each bead, so must create b streams # prepare format string for file name if getkey(self.what) == "extras" or getkey( self.what) == "extras_component": fmt_fn = self.filename + "_" + fmt_bead else: fmt_fn = self.filename + "_" + fmt_bead + "." + self.format # open all files self.out = [] for b in range(self.system.beads.nbeads): if (self.ibead < 0 and (b % (-self.ibead) == 0)) or (self.ibead == b): self.out.append(open_backup(fmt_fn.format(b), mode)) else: # Create null outputs if a single bead output is chosen. self.out.append(None) else: # open one file filename = self.filename + "." + self.format self.out = open_backup(filename, mode)
def write_traj(self, data, what, stream, b=0, format="xyz", dimension="", units="automatic", cell_units="automatic", flush=True): """Prints out a frame of a trajectory for the specified quantity and bead. Args: what: A string specifying what to print. b: The bead index. Defaults to 0. stream: A reference to the stream on which data will be printed. format: The output file format. cell_units: The units used to specify the cell parameters. flush: A boolean which specifies whether to flush the output buffer after each write to file or not. """ key = getkey(what) if key in ["extras"]: stream.write(" #*EXTRAS*# Step: %10d Bead: %5d \n" % (self.system.simul.step + 1, b)) stream.write(data[b]) stream.write("\n") if flush: stream.flush() os.fsync(stream) return elif getkey(what) in ["positions", "velocities", "forces", "forces_sc", "momenta"]: fatom = Atoms(self.system.beads.natoms) fatom.names[:] = self.system.beads.names fatom.q[:] = data[b] else: fatom = Atoms(self.system.beads.natoms) fatom.names[:] = self.system.beads.names fatom.q[:] = data fcell = Cell() fcell.h = self.system.cell.h if units == "": units = "automatic" if cell_units == "": cell_units = "automatic" io.print_file(format, fatom, fcell, stream, title=("Step: %10d Bead: %5d " % (self.system.simul.step + 1, b)), key=key, dimension=dimension, units=units, cell_units=cell_units) if flush: stream.flush() os.fsync(stream)
def bind(self, system, mode="w"): """Binds output proxy to System object. Args: system: A System object to be bound. """ self.system = system # Checks as soon as possible if some asked-for trajs are missing or mispelled key = getkey(self.what) if not key in self.system.trajs.traj_dict.keys(): print "Computable trajectories list: ", self.system.trajs.traj_dict.keys() raise KeyError(key + " is not a recognized output trajectory") super(TrajectoryOutput,self).bind( mode)
def open_stream(self): """Opens the output stream(s).""" if getkey( self.what) in ["positions", "velocities", "forces", "extras"]: # must write out trajectories for each bead, so must create b streams self.out = [] for b in range(self.simul.beads.nbeads): # zero-padded bead number padb = (("%0" + str( int(1 + np.floor(np.log(self.simul.beads.nbeads) / np.log(10)))) + "d") % (b)) try: if (self.ibead < 0 or self.ibead == b): if getkey(self.what) == "extras": self.out.append( open(self.filename + "_" + padb, "a")) else: self.out.append( open( self.filename + "_" + padb + "." + self.format, "a")) else: self.out.append(None) # creates null outputs if a # single bead output is chosen except: raise ValueError("Could not open file " + self.filename + "_" + padb + "." + self.format + " for output") else: try: self.out = (open(self.filename + "." + self.format, "a")) except: raise ValueError("Could not open file " + self.filename + "." + self.format + " for output")
def bind(self, system, mode="w"): """Binds output proxy to System object. Args: system: A System object to be bound. """ self.system = system # Checks as soon as possible if some asked-for trajs are missing or mispelled key = getkey(self.what) if not key in self.system.trajs.traj_dict.keys(): print "Computable trajectories list: ", self.system.trajs.traj_dict.keys( ) raise KeyError(key + " is not a recognized output trajectory") super(TrajectoryOutput, self).bind(mode)
def bind(self, simul): """Binds output proxy to simulation object. Args: simul: A simulation object to be bound. """ self.simul = simul # Checks as soon as possible if some asked-for trajs are missing or mispelled key = getkey(self.what) if not key in self.simul.trajs.traj_dict.keys(): print "Computable trajectories list: ", self.simul.trajs.traj_dict.keys() raise KeyError(key + " is not a recognized output trajectory") self.open_stream()
def bind(self, simul): """Binds output proxy to simulation object. Args: simul: A simulation object to be bound. """ self.simul = simul # Checks as soon as possible if some asked-for trajs are missing or mispelled key = getkey(self.what) if not key in self.simul.trajs.traj_dict.keys(): print "Computable trajectories list: ", self.simul.trajs.traj_dict.keys( ) raise KeyError(key + " is not a recognized output trajectory") self.open_stream()
def bind(self, system): """Binds output proxy to System object. Args: system: A System object to be bound. """ self.system = system # Checks as soon as possible if some asked-for trajs are missing or mispelled key = getkey(self.what) if not key in self.system.trajs.traj_dict.keys(): print "Computable trajectories list: ", self.system.trajs.traj_dict.keys() raise KeyError(key + " is not a recognized output trajectory") self.open_stream() softexit.register_function(self.softexit)
def bind(self, system, mode="w"): """Binds output proxy to System object. Args: system: A System object to be bound. """ # Checks as soon as possible if some asked-for properties are # missing or mispelled self.system = system for what in self.outlist: key = getkey(what) if not key in system.properties.property_dict.keys(): print "Computable properties list: ", system.properties.property_dict.keys( ) raise KeyError(key + " is not a recognized property") super(PropertyOutput, self).bind(mode)
def bind(self, simul): """Binds output proxy to simulation object. Args: simul: A simulation object to be bound. """ self.simul = simul # Checks as soon as possible if some asked-for properties are # missing or mispelled for what in self.outlist: key = getkey(what) if not key in self.simul.properties.property_dict.keys(): print "Computable properties list: ", self.simul.properties.property_dict.keys() raise KeyError(key + " is not a recognized property") self.open_stream()
def bind(self, system, mode="w"): """Binds output proxy to System object. Args: system: A System object to be bound. """ # Checks as soon as possible if some asked-for properties are # missing or mispelled self.system = system for what in self.outlist: key = getkey(what) if not key in system.properties.property_dict.keys(): print "Computable properties list: ", system.properties.property_dict.keys() raise KeyError(key + " is not a recognized property") super(PropertyOutput,self).bind(mode)
def print_header(self): # print nice header if information is available on the properties icol = 1 for what in self.outlist: ohead = "# " key = getkey(what) prop = self.system.properties.property_dict[key] if "size" in prop and prop["size"] > 1: ohead += "cols. %3d-%-3d" % (icol, icol + prop["size"] - 1) icol += prop["size"] else: ohead += "column %3d " % (icol) icol += 1 ohead += " --> %s " % (what) if "help" in prop: ohead += ": " + prop["help"] self.out.write(ohead + "\n")
def bind(self, simul): """Binds output proxy to simulation object. Args: simul: A simulation object to be bound. """ self.simul = simul # Checks as soon as possible if some asked-for properties are # missing or mispelled for what in self.outlist: key = getkey(what) if not key in self.simul.properties.property_dict.keys(): print "Computable properties list: ", self.simul.properties.property_dict.keys( ) raise KeyError(key + " is not a recognized property") self.open_stream()
def bind(self, system): """Binds output proxy to System object. Args: system: A System object to be bound. """ self.system = system # Checks as soon as possible if some asked-for properties are # missing or mispelled for what in self.outlist: key = getkey(what) if not key in self.system.properties.property_dict.keys(): print "Computable properties list: ", self.system.properties.property_dict.keys() raise KeyError(key + " is not a recognized property") self.open_stream() softexit.register_function(self.softexit)
def print_header(self): # print nice header if information is available on the properties icol = 1 for what in self.outlist: ohead = "# " key = getkey(what) prop = self.system.properties.property_dict[key] if "size" in prop: if (type(prop["size"]) is str) or (prop["size"] <= 0): raise RuntimeError( "ERROR: property %s has undefined size." % key) elif prop["size"] > 1: ohead += "cols. %3d-%-3d" % (icol, icol + prop["size"] - 1) icol += prop["size"] else: ohead += "column %3d " % (icol) icol += 1 ohead += " --> %s " % (what) if "help" in prop: ohead += ": " + prop["help"] self.out.write(ohead + "\n")
def main(inputfile, outdir="trim"): # opens & parses the input file ifile = open(inputfile, "r") xmlrestart = io_xml.xml_parse_file(ifile) # Parses the file. ifile.close() isimul = InputSimulation() isimul.parse(xmlrestart.fields[0][1]) simul = isimul.fetch() trimstep = isimul.step.fetch() os.makedirs(outdir) # reconstructs the list of the property and trajectory files that have been output # and that should be re-ordered lprop = [] # list of property files ltraj = [] # list of trajectory files nsys = len(simul.syslist) for o in simul.outtemplate: o = deepcopy(o) # avoids overwriting the actual filename if simul.outtemplate.prefix != "": o.filename = simul.outtemplate.prefix + "." + o.filename if type(o) is CheckpointOutput: # properties and trajectories are output per system pass elif type(o) is PropertyOutput: nprop = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = outdir + "/" + filename nprop.append({"filename": filename, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 lprop.append(nprop) elif type(o) is TrajectoryOutput: # trajectories are more complex, as some have per-bead output if getkey(o.what) in ["positions", "velocities", "forces", "extras"]: # multiple beads nbeads = simul.syslist[0].beads.nbeads for b in range(nbeads): ntraj = [] isys = 0 # zero-padded bead number padb = (("%0" + str(int(1 + np.floor(np.log(nbeads) / np.log(10)))) + "d") % (b)) for s in simul.syslist: if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = outdir + "/" + filename if (o.ibead < 0 or o.ibead == b): if getkey(o.what) == "extras": filename = filename + "_" + padb ofilename = ofilename + "_" + padb else: filename = filename + "_" + padb + "." + o.format ofilename = ofilename + "_" + padb + "." + o.format ntraj.append({"filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 if ntraj != []: ltraj.append(ntraj) else: ntraj = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename filename = filename + "." + o.format ofilename = outdir + "/" + filename ntraj.append({"filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 ltraj.append(ntraj) ptfile = None wtefile = None if os.path.isfile("PARATEMP"): ptfile = open("PARATEMP", "r") optfile = open(outdir + "/PARATEMP", "w") if os.path.isfile("PARAWTE"): wtefile = open("PARAWTE", "r") owtefile = open(outdir + "/PARAWTE", "w") # now reads files one frame at a time, and re-direct output to the appropriate location for step in range(trimstep + 1): # reads one line from PARATEMP index file if not ptfile is None: line = ptfile.readline() optfile.write(line) if not wtefile is None: line = wtefile.readline() owtefile.write(line) try: for prop in lprop: for isys in range(nsys): sprop = prop[isys] if step % sprop["stride"] == 0: # property transfer iline = sprop["ifile"].readline() while iline[0] == "#": # fast forward if line is a comment prop[isys]["ofile"].write(iline) iline = sprop["ifile"].readline() prop[isys]["ofile"].write(iline) for traj in ltraj: for isys in range(nsys): straj = traj[isys] if step % straj["stride"] == 0: # property transfer # reads one frame from the input file ibuffer = [] if straj["format"] == "xyz": iline = straj["ifile"].readline() nat = int(iline) ibuffer.append(iline) ibuffer.append(straj["ifile"].readline()) for i in range(nat): ibuffer.append(straj["ifile"].readline()) traj[isys]["ofile"].write(''.join(ibuffer)) elif straj["format"] == "pdb": iline = straj["ifile"].readline() while (iline.strip() != "" and iline.strip() != "END"): ibuffer.append(iline) iline = straj["ifile"].readline() ibuffer.append(iline) traj[isys]["ofile"].write(''.join(ibuffer)) except EOFError: break
def main(inputfile, prefix="SRT_"): verbosity.level = "low" # opens & parses the input file ifile = open(inputfile, "r") xmlrestart = io_xml.xml_parse_file(ifile) # Parses the file. ifile.close() # ugly hack to remove ffplumed objects to avoid messing up with plumed output files newfields = [ f for f in xmlrestart.fields[0][1].fields if f[0] != "ffplumed" ] xmlrestart.fields[0][1].fields = newfields isimul = InputSimulation() isimul.parse(xmlrestart.fields[0][1]) simul = isimul.fetch() swapfile = "" if simul.smotion is None or (simul.smotion.mode != "remd" and simul.smotion.mode != "multi"): raise ValueError( "Simulation does not look like a parallel tempering one.") else: if simul.smotion.mode == "remd": swapfile = simul.smotion.swapfile else: for sm in simul.smotion.mlist: if sm.mode == "remd": if swapfile != "": raise ValueError( "I'm not equipped to deal with multiple REMD outputs, sorry" ) swapfile = sm.swapfile if swapfile == "": raise ValueError("Could not determine the REMD swapfile name. \ Sorry, you'll have to look carefully at your inputs.") # reconstructs the list of the property and trajectory files that have been output # and that should be re-ordered lprop = [] # list of property files ltraj = [] # list of trajectory files nsys = len(simul.syslist) for o in simul.outtemplate: o = deepcopy(o) # avoids overwriting the actual filename if simul.outtemplate.prefix != "": o.filename = simul.outtemplate.prefix + "." + o.filename if (type(o) is CheckpointOutput ): # properties and trajectories are output per system pass elif type(o) is PropertyOutput: nprop = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = prefix + filename nprop.append({ "filename": filename, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w"), }) isys += 1 lprop.append(nprop) elif (type(o) is TrajectoryOutput ): # trajectories are more complex, as some have per-bead output if getkey(o.what) in [ "positions", "velocities", "forces", "extras", ]: # multiple beads nbeads = simul.syslist[0].beads.nbeads for b in range(nbeads): ntraj = [] isys = 0 # zero-padded bead number padb = ("%0" + str( int(1 + np.floor(np.log(nbeads) / np.log(10)))) + "d") % (b) for s in simul.syslist: if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = prefix + filename if o.ibead < 0 or o.ibead == b: if getkey(o.what) == "extras": filename = filename + "_" + padb ofilename = ofilename + "_" + padb # Sets format of extras as None ntraj.append({ "filename": filename, "format": None, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w"), }) else: filename = filename + "_" + padb + "." + o.format ofilename = ofilename + "_" + padb + "." + o.format ntraj.append({ "filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w"), }) isys += 1 if ntraj != []: ltraj.append(ntraj) else: ntraj = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename filename = filename + "." + o.format ofilename = prefix + filename ntraj.append({ "filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w"), }) isys += 1 ltraj.append(ntraj) ptfile = open(simul.outtemplate.prefix + "." + swapfile, "r") # now reads files one frame at a time, # and re-direct output to the appropriate location line = ptfile.readline().split() irep = list(range(nsys)) # Could this be harmful? step = 0 while True: # reads one line from index file try: for prop in lprop: for isys in range(nsys): sprop = prop[isys] if step % sprop["stride"] == 0: # property transfer iline = sprop["ifile"].readline() if len(iline) == 0: raise EOFError # useful if line is blank while iline[ 0] == "#": # fast forward if line is a comment prop[irep[isys]]["ofile"].write(iline) iline = sprop["ifile"].readline() prop[irep[isys]]["ofile"].write(iline) for traj in ltraj: for isys in range(nsys): straj = traj[isys] if step % straj["stride"] == 0: # property transfer # reads one frame from the input file ibuffer = [] if straj["format"] is None: ibuffer.append(straj["ifile"].readline()) ibuffer.append(straj["ifile"].readline()) traj[irep[isys]]["ofile"].write("".join(ibuffer)) if straj["format"] == "xyz": iline = straj["ifile"].readline() nat = int(iline) ibuffer.append(iline) ibuffer.append(straj["ifile"].readline()) for i in range(nat): ibuffer.append(straj["ifile"].readline()) traj[irep[isys]]["ofile"].write("".join(ibuffer)) elif straj["format"] == "pdb": iline = straj["ifile"].readline() while iline.strip() != "" and iline.strip( ) != "END": ibuffer.append(iline) iline = straj["ifile"].readline() ibuffer.append(iline) traj[irep[isys]]["ofile"].write("".join(ibuffer)) except EOFError: break if len(line) > 0 and step == int(line[0]): irep = [int(i) for i in line[1:]] line = ptfile.readline() line = line.split() step += 1
def write_traj( self, data, what, stream, b=0, format="xyz", dimension="", units="automatic", cell_units="automatic", flush=True, ): """Prints out a frame of a trajectory for the specified quantity and bead. Args: what: A string specifying what to print. b: The bead index. Defaults to 0. stream: A reference to the stream on which data will be printed. format: The output file format. cell_units: The units used to specify the cell parameters. flush: A boolean which specifies whether to flush the output buffer after each write to file or not. """ key = getkey(what) if key in ["extras", "extras_component"]: stream.write(" #*EXTRAS*# Step: %10d Bead: %5d \n" % (self.system.simul.step + 1, b)) if self.extra_type in data: if np.array(data[self.extra_type][b]).ndim == 2: stream.write("\n".join([ " ".join( ["{:15.8f}".format(item) for item in row]) for row in data[self.extra_type][b] ])) elif np.array(data[self.extra_type][b]).ndim == 1: stream.write(" ".join( "%15.8f" % el for el in np.asarray(data[self.extra_type][b]))) else: stream.write("%s" % data[self.extra_type][b]) stream.write("\n") else: raise KeyError( "Extra type '" + self.extra_type + "' is not among the quantities returned by any of the forcefields." ) if flush: stream.flush() os.fsync(stream) return elif getkey(what) in [ "positions", "velocities", "forces", "forces_sc", "momenta", ]: fatom = Atoms(self.system.beads.natoms) fatom.names[:] = self.system.beads.names fatom.q[:] = data[b] else: fatom = Atoms(self.system.beads.natoms) fatom.names[:] = self.system.beads.names fatom.q[:] = data fcell = Cell() fcell.h = self.system.cell.h if units == "": units = "automatic" if cell_units == "": cell_units = "automatic" io.print_file( format, fatom, fcell, stream, title=("Step: %10d Bead: %5d " % (self.system.simul.step + 1, b)), key=key, dimension=dimension, units=units, cell_units=cell_units, ) if flush: stream.flush() os.fsync(stream)
def main(inputfile, outdir="trim"): # opens & parses the input file ifile = open(inputfile, "r") xmlrestart = io_xml.xml_parse_file(ifile) # Parses the file. ifile.close() isimul = InputSimulation() isimul.parse(xmlrestart.fields[0][1]) simul = isimul.fetch() trimstep = isimul.step.fetch() os.makedirs(outdir) # reconstructs the list of the property and trajectory files that have been output # and that should be re-ordered lprop = [] # list of property files ltraj = [] # list of trajectory files nsys = len(simul.syslist) for o in simul.outtemplate: if type(o) is CheckpointOutput: # properties and trajectories are output per system pass elif type(o) is PropertyOutput: nprop = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = outdir + "/" + filename nprop.append({"filename": filename, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 lprop.append(nprop) elif type(o) is TrajectoryOutput: # trajectories are more complex, as some have per-bead output if getkey(o.what) in ["positions", "velocities", "forces", "extras"]: # multiple beads nbeads = simul.syslist[0].beads.nbeads for b in range(nbeads): ntraj = [] isys = 0 # zero-padded bead number padb = (("%0" + str(int(1 + np.floor(np.log(nbeads) / np.log(10)))) + "d") % (b)) for s in simul.syslist: if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = outdir + "/" + filename if (o.ibead < 0 or o.ibead == b): if getkey(o.what) == "extras": filename = filename + "_" + padb ofilename = ofilename + "_" + padb else: filename = filename + "_" + padb + "." + o.format ofilename = ofilename + "_" + padb + "." + o.format ntraj.append({"filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 if ntraj != []: ltraj.append(ntraj) else: ntraj = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename filename = filename + "." + o.format ofilename = outdir + "/" + filename ntraj.append({"filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 ltraj.append(ntraj) ptfile = None wtefile = None if os.path.isfile("PARATEMP"): ptfile = open("PARATEMP", "r") optfile = open(outdir + "/PARATEMP", "w") if os.path.isfile("PARAWTE"): wtefile = open("PARAWTE", "r") owtefile = open(outdir + "/PARAWTE", "w") # now reads files one frame at a time, and re-direct output to the appropriate location for step in range(trimstep + 1): # reads one line from PARATEMP index file if not ptfile is None: line = ptfile.readline() optfile.write(line) if not wtefile is None: line = wtefile.readline() owtefile.write(line) try: for prop in lprop: for isys in range(nsys): sprop = prop[isys] if step % sprop["stride"] == 0: # property transfer iline = sprop["ifile"].readline() while iline[0] == "#": # fast forward if line is a comment prop[isys]["ofile"].write(iline) iline = sprop["ifile"].readline() prop[isys]["ofile"].write(iline) for traj in ltraj: for isys in range(nsys): straj = traj[isys] if step % straj["stride"] == 0: # property transfer # reads one frame from the input file ibuffer = [] if straj["format"] == "xyz": iline = straj["ifile"].readline() nat = int(iline) ibuffer.append(iline) ibuffer.append(straj["ifile"].readline()) for i in range(nat): ibuffer.append(straj["ifile"].readline()) traj[isys]["ofile"].write(''.join(ibuffer)) elif straj["format"] == "pdb": iline = straj["ifile"].readline() while (iline.strip() != "" and iline.strip() != "END"): ibuffer.append(iline) iline = straj["ifile"].readline() ibuffer.append(iline) traj[isys]["ofile"].write(''.join(ibuffer)) except EOFError: break
def get_output_filenames(xml_path): """ Predicts ipi output filenames based on I-PI input file. Args: xml_path: absolute path to I-PI input file Returns: list of I-PI output files that will be generated running I-PI using this input TODO A more elegant solution. This function launches I-PI in the directory of the input file and dumps output to dev/null, which would make potential bugs hard to detect. """ # Avoid to print i-pi output devnull = open('/dev/null', 'w') oldstdout_fno = os.dup(sys.stdout.fileno()) os.dup2(devnull.fileno(), 1) xml_path = os.path.abspath(xml_path) os.chdir(os.path.dirname(xml_path)) # i-pi xml file parser ifile = open(xml_path, 'r') xmlrestart = io_xml.xml_parse_file(ifile) ifile.close() isimul = InputSimulation() isimul.parse(xmlrestart.fields[0][1]) simul = isimul.fetch() # reconstructs the list of the property and trajectory files lprop = [] # list of property files ltraj = [] # list of trajectory files for o in simul.outtemplate: # properties and trajectories are output per system if isinstance(o, CheckpointOutput): pass elif isinstance(o, PropertyOutput): for _ss in simul.syslist: # create multiple copies filename = o.filename if _ss.prefix != "": filename = _ss.prefix + "_" + filename lprop.append(filename) # trajectories are more complex, as some have per-bead output elif isinstance(o, TrajectoryOutput): if getkey(o.what) in ['positions', 'velocities', 'forces', 'forces_sc', 'extras']: # multiple beads nbeads = simul.syslist[0].beads.nbeads for _bi in range(nbeads): # zero-padded bead number padb = (('%0' + str(int(1 + np.floor(np.log(nbeads) / np.log(10)))) + 'd') % (_bi)) for _ss in simul.syslist: if (o.ibead < 0 and ((_bi % (-o.ibead) == 0))) or o.ibead == _bi: filename = o.filename if _ss.prefix != "": filename = _ss.prefix + "_" + filename if getkey(o.what) == 'extras': filename += "_" + padb else: filename += "_" + padb + "." + o.format ltraj.append(filename) else: for _ss in simul.syslist: # create multiple copies filename = o.filename if _ss.prefix != "": filename = _ss.prefix + "_" + filename filename += "." + o.format ltraj.append(filename) os.dup2(oldstdout_fno, 1) return (ltraj + lprop)
def get_output_filenames(xml_path): """ Predicts ipi output filenames based on I-PI input file. Args: xml_path: absolute path to I-PI input file Returns: list of I-PI output files that will be generated running I-PI using this input TODO A more elegant solution. This function launches I-PI in the directory of the input file and dumps output to dev/null, which would make potential bugs hard to detect. """ # Avoid to print i-pi output devnull = open('/dev/null', 'w') oldstdout_fno = os.dup(sys.stdout.fileno()) os.dup2(devnull.fileno(), 1) xml_path = os.path.abspath(xml_path) os.chdir(os.path.dirname(xml_path)) # i-pi xml file parser ifile = open(xml_path, 'r') xmlrestart = io_xml.xml_parse_file(ifile) ifile.close() isimul = InputSimulation() isimul.parse(xmlrestart.fields[0][1]) simul = isimul.fetch() # reconstructs the list of the property and trajectory files lprop = [] # list of property files ltraj = [] # list of trajectory files for o in simul.outtemplate: # properties and trajectories are output per system if isinstance(o, CheckpointOutput): pass elif isinstance(o, PropertyOutput): for _ss in simul.syslist: # create multiple copies filename = o.filename if _ss.prefix != "": filename = _ss.prefix + "_" + filename lprop.append(filename) # trajectories are more complex, as some have per-bead output elif isinstance(o, TrajectoryOutput): if getkey(o.what) in [ 'positions', 'velocities', 'forces', 'forces_sc', 'extras' ]: # multiple beads nbeads = simul.syslist[0].beads.nbeads for _bi in range(nbeads): # zero-padded bead number padb = (('%0' + str( int(1 + np.floor(np.log(nbeads) / np.log(10)))) + 'd') % (_bi)) for _ss in simul.syslist: if (o.ibead < 0 and ((_bi % (-o.ibead) == 0))) or o.ibead == _bi: filename = o.filename if _ss.prefix != "": filename = _ss.prefix + "_" + filename if getkey(o.what) == 'extras': filename += "_" + padb else: filename += "_" + padb + "." + o.format ltraj.append(filename) else: for _ss in simul.syslist: # create multiple copies filename = o.filename if _ss.prefix != "": filename = _ss.prefix + "_" + filename filename += "." + o.format ltraj.append(filename) os.dup2(oldstdout_fno, 1) return (ltraj + lprop)
def get_filesname(self, xml_path, olddir, newdir): """ The test results should be analyzed number by numbers. The idea is that the testing input should never change, then the files should be always the same. It would probably be better, anyway, to use the i-pi infrastructure to retrieve the right position of the data. In fact, this would work as a further testing. Args: olddir: The path used for the 'old_filename' in the returned dictionary. newdir: The path used for the 'new_filename' in the returned dictionary. Returns: lprop nprop """ # Avoid to print i-pi output devnull = open('/dev/null', 'w') oldstdout_fno = os.dup(sys.stdout.fileno()) os.dup2(devnull.fileno(), 1) # opens & parses the input file # get in the input file location so it can find other input files for initialization cwd = os.getcwd() iodir = os.path.dirname(os.path.realpath(xml_path)) os.chdir(iodir) # print "READING FILE FROM ", iodir # print " WHILE RUNNING IN ", cwd # print "I have changed directory to ", os.getcwd() ifile = open(xml_path, "r") xmlrestart = io_xml.xml_parse_file(ifile) # Parses the file. ifile.close() isimul = InputSimulation() isimul.parse(xmlrestart.fields[0][1]) simul = isimul.fetch() os.chdir(cwd) # reconstructs the list of the property and trajectory files lprop = [] # list of property files ltraj = [] # list of trajectory files for o in simul.outtemplate: # properties and trajectories are output per system if isinstance(o, CheckpointOutput): pass elif isinstance(o, PropertyOutput): nprop = [] isys = 0 for _ss in simul.syslist: # create multiple copies filename = _ss.prefix + o.filename nprop.append({"old_filename": os.path.join(olddir, filename), "new_filename": os.path.join(newdir, filename), "stride": o.stride, "properties": o.outlist, }) isys += 1 lprop.append(nprop) # trajectories are more complex, as some have per-bead output elif isinstance(o, TrajectoryOutput): if getkey(o.what) in ["positions", "velocities", "forces", "forces_sc", "extras"]: # multiple beads nbeads = simul.syslist[0].beads.nbeads for _bi in range(nbeads): ntraj = [] isys = 0 # zero-padded bead number padb = (("%0" + str(int(1 + np.floor(np.log(nbeads) / np.log(10)))) + "d") % (_bi)) for _ss in simul.syslist: if o.ibead < 0 or o.ibead == _bi: if getkey(o.what) == "extras": filename = _ss.prefix + o.filename + "_" + padb else: filename = _ss.prefix + o.filename + "_" + padb + \ "." + o.format ntraj.append({"old_filename": os.path.join(olddir, filename), "format": o.format, "new_filename": os.path.join(newdir, filename), "stride": o.stride, "what": o.what, }) isys += 1 if ntraj != []: ltraj.append(ntraj) else: ntraj = [] isys = 0 for _ss in simul.syslist: # create multiple copies filename = _ss.prefix + o.filename filename = filename + "." + o.format ntraj.append({"old_filename": os.path.join(olddir, filename), "new_filename": os.path.join(newdir, filename), "format": o.format, "stride": o.stride, }) isys += 1 ltraj.append(ntraj) os.dup2(oldstdout_fno, 1) return ltraj, lprop
def main(inputfile, prefix="PT"): verbosity.level = "low" # opens & parses the input file ifile = open(inputfile, "r") xmlrestart = io_xml.xml_parse_file(ifile) # Parses the file. ifile.close() isimul = InputSimulation() isimul.parse(xmlrestart.fields[0][1]) simul = isimul.fetch() if simul.smotion.mode != "remd": raise ValueError("Simulation does not look like a parallel tempering one.") # reconstructs the list of the property and trajectory files that have been output # and that should be re-ordered lprop = [] # list of property files ltraj = [] # list of trajectory files nsys = len(simul.syslist) for o in simul.outtemplate: if type(o) is CheckpointOutput: # properties and trajectories are output per system pass elif type(o) is PropertyOutput: nprop = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = prefix + str(isys) + "_" + o.filename nprop.append({"filename": filename, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 lprop.append(nprop) elif type(o) is TrajectoryOutput: # trajectories are more complex, as some have per-bead output if getkey(o.what) in ["positions", "velocities", "forces", "extras"]: # multiple beads nbeads = simul.syslist[0].beads.nbeads for b in range(nbeads): ntraj = [] isys = 0 # zero-padded bead number padb = (("%0" + str(int(1 + np.floor(np.log(nbeads) / np.log(10)))) + "d") % (b)) for s in simul.syslist: if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename ofilename = prefix + str(isys) + "_" + o.filename if (o.ibead < 0 or o.ibead == b): if getkey(o.what) == "extras": filename = filename + "_" + padb ofilename = ofilename + "_" + padb else: filename = filename + "_" + padb + "." + o.format ofilename = ofilename + "_" + padb + "." + o.format ntraj.append({"filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 if ntraj != []: ltraj.append(ntraj) else: ntraj = [] isys = 0 for s in simul.syslist: # create multiple copies if s.prefix != "": filename = s.prefix + "_" + o.filename else: filename = o.filename filename = filename + "." + o.format ofilename = prefix + str(isys) + "_" + o.filename + "." + o.format ntraj.append({"filename": filename, "format": o.format, "ofilename": ofilename, "stride": o.stride, "ifile": open(filename, "r"), "ofile": open(ofilename, "w") }) isys += 1 ltraj.append(ntraj) ptfile = open("PARATEMP", "r") # now reads files one frame at a time, and re-direct output to the appropriate location line = ptfile.readline().split() irep = range(nsys) # Could this be harmful? step = 0 while True: # reads one line from PARATEMP index file try: for prop in lprop: for isys in range(nsys): sprop = prop[isys] if step % sprop["stride"] == 0: # property transfer iline = sprop["ifile"].readline() if len(iline) == 0: raise EOFError # useful if line is blank while iline[0] == "#": # fast forward if line is a comment prop[irep[isys]]["ofile"].write(iline) iline = sprop["ifile"].readline() prop[irep[isys]]["ofile"].write(iline) for traj in ltraj: for isys in range(nsys): straj = traj[isys] if step % straj["stride"] == 0: # property transfer # reads one frame from the input file ibuffer = [] if straj["format"] == "xyz": iline = straj["ifile"].readline() nat = int(iline) ibuffer.append(iline) ibuffer.append(straj["ifile"].readline()) for i in range(nat): ibuffer.append(straj["ifile"].readline()) traj[irep[isys]]["ofile"].write(''.join(ibuffer)) elif straj["format"] == "pdb": iline = straj["ifile"].readline() while (iline.strip() != "" and iline.strip() != "END"): ibuffer.append(iline) iline = straj["ifile"].readline() ibuffer.append(iline) traj[irep[isys]]["ofile"].write(''.join(ibuffer)) except EOFError: break if len(line) > 0 and step == int(line[0]): irep = [int(i) for i in line[1:]] line = ptfile.readline() line = line.split() step += 1
def write_traj( self, data, what, stream, b=0, format="xyz", dimension="", units="automatic", cell_units="automatic", flush=True, ): """Prints out a frame of a trajectory for the specified quantity and bead. Args: what: A string specifying what to print. b: The bead index. Defaults to 0. stream: A reference to the stream on which data will be printed. format: The output file format. cell_units: The units used to specify the cell parameters. flush: A boolean which specifies whether to flush the output buffer after each write to file or not. """ key = getkey(what) if key in ["extras"]: stream.write(" #*EXTRAS*# Step: %10d Bead: %5d \n" % (self.system.simul.step + 1, b)) try: index = 0 for el, item in enumerate(data): if self.xtratype in item[b].keys(): index = el try: if self.xtratype == "friction": fatom = Atoms(self.system.beads.natoms) fatom.names[:] = self.system.beads.names stream.write("# %s\n" % " ".join("%15s" % el for el in [ "xx", "yy", "zz", "xy=yx", "xz=zx", "yz=zy", ])) for na in range(self.system.beads.natoms): stream.write("%3s %s\n" % ( fatom.names[na], " ".join( "%15.8f" % el for el in data[index][b] [self.xtratype][na * 6:(na + 1) * 6]), )) else: stream.write(" ".join( "%15.8f" % el for el in data[index][b][self.xtratype])) stream.write("\n") except: stream.write(json.dumps(data[index][b][self.xtratype])) stream.write("\n") except: try: info( "Sorry, your specified xtratype %s is not among the available options. \n" "The available keys are the following: %s " % ( self.xtratype, ",".join("%s" % key for key in data[0][b].keys()), ), verbosity.low, ) except: info( "Sorry, no extras string has been passed, there are no available options for the xtratype " "attribute. \n", verbosity.low, ) if flush: stream.flush() os.fsync(stream) return elif getkey(what) in [ "positions", "velocities", "forces", "forces_sc", "momenta", ]: fatom = Atoms(self.system.beads.natoms) fatom.names[:] = self.system.beads.names fatom.q[:] = data[b] else: fatom = Atoms(self.system.beads.natoms) fatom.names[:] = self.system.beads.names fatom.q[:] = data fcell = Cell() fcell.h = self.system.cell.h if units == "": units = "automatic" if cell_units == "": cell_units = "automatic" io.print_file( format, fatom, fcell, stream, title=("Step: %10d Bead: %5d " % (self.system.simul.step + 1, b)), key=key, dimension=dimension, units=units, cell_units=cell_units, ) if flush: stream.flush() os.fsync(stream)