def __init__(self,*args,**kwargs): Trajectory.__init__(self,*args,**kwargs) resolve_undefined_molecules_name(self.universe) build_connectivity(self.universe)
def writeTrajectory(self, trajectory_name, block_size=1): trajectory = Trajectory(self.universe, trajectory_name, 'w', self.title, block_size=block_size) actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)] snapshot = SnapshotGenerator(self.universe, actions=actions) conf = self.universe.configuration() vel = self.universe.velocities() grad = ParticleVector(self.universe) try: while 1: line = self.history.readline() if not line: break data = FortranLine(line, history_timestep_line) step = data[1] natoms = data[2] nvectors = data[3]+1 pbc = data[4] dt = data[5] step_data = {'time': step*dt} if nvectors > 2: step_data['gradients'] = grad if pbc: data = FortranLine(self.history.readline(), history_pbc_line) box_x = data[0]*Units.Ang if data[1] != 0. or data[2] != 0.: raise ValueError, "box shape not supported" data = FortranLine(self.history.readline(), history_pbc_line) box_y = data[1]*Units.Ang if data[0] != 0. or data[2] != 0.: raise ValueError, "box shape not supported" data = FortranLine(self.history.readline(), history_pbc_line) box_z = data[2]*Units.Ang if data[0] != 0. or data[1] != 0.: raise ValueError, "box shape not supported" self.universe.setSize((box_x, box_y, box_z)) for i in range(natoms): self.history.readline() conf.array[i] = map(float, string.split(self.history.readline())) if nvectors > 1: vel.array[i] = map(float, string.split(self.history.readline())) if nvectors > 2: grad.array[i] = map(float, string.split(self.history.readline())) Numeric.multiply(conf.array, Units.Ang, conf.array) if nvectors > 1: Numeric.multiply(vel.array, Units.Ang/Units.ps, vel.array) if nvectors > 2: Numeric.multiply(grad.array, -Units.amu*Units.Ang/Units.ps**2, grad.array) snapshot(data=step_data) finally: trajectory.close()
def writeTrajectory(self, trajectory_name, block_size=1): trajectory = Trajectory(self.universe, trajectory_name, 'w', self.title, block_size=block_size) actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)] snapshot = SnapshotGenerator(self.universe, actions=actions) conf = self.universe.configuration() vel = self.universe.velocities() grad = ParticleVector(self.universe) try: while 1: line = self.history.readline() if not line: break data = FortranLine(line, history_timestep_line) step = data[1] natoms = data[2] nvectors = data[3]+1 pbc = data[4] dt = data[5] step_data = {'time': step*dt} if nvectors > 2: step_data['gradients'] = grad if pbc: data = FortranLine(self.history.readline(), history_pbc_line) box_x = data[0]*Units.Ang #if data[1] != 0. or data[2] != 0.: # raise ValueError, "box shape not supported" data = FortranLine(self.history.readline(), history_pbc_line) box_y = data[1]*Units.Ang #if data[0] != 0. or data[2] != 0.: # raise ValueError, "box shape not supported" data = FortranLine(self.history.readline(), history_pbc_line) box_z = data[2]*Units.Ang #if data[0] != 0. or data[1] != 0.: # raise ValueError, "box shape not supported" self.universe.setSize((box_x, box_y, box_z)) for i in range(natoms): self.history.readline() conf.array[i] = map(float, string.split(self.history.readline())) if nvectors > 1: vel.array[i] = map(float, string.split(self.history.readline())) if nvectors > 2: grad.array[i] = map(float, string.split(self.history.readline())) Numeric.multiply(conf.array, Units.Ang, conf.array) if nvectors > 1: Numeric.multiply(vel.array, Units.Ang/Units.ps, vel.array) if nvectors > 2: Numeric.multiply(grad.array, -Units.amu*Units.Ang/Units.ps**2, grad.array) snapshot(data=step_data) finally: trajectory.close()
def _writeToTrajectory(self, filename, comment, path): trajectory = Trajectory(self.universe, filename, "w", comment) snapshot = SnapshotGenerator(self.universe, actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)]) for step in path: self.universe.setConfiguration(step.conf) snapshot() trajectory.close()
def initialize(self): """ Initialize the input parameters and analysis self variables """ self._castepFile = MDFile(self.configuration["castep_file"]["filename"]) self.numberOfSteps = self._castepFile["n_frames"] self._universe = ParallelepipedicPeriodicUniverse() for symbol,number in self._castepFile["atoms"]: for i in range(number): self._universe.addObject(Atom(symbol, name="%s_%d" % (symbol,i))) self._universe.initializeVelocitiesToTemperature(0.) self._velocities = ParticleVector(self._universe) self._gradients = ParticleVector(self._universe) # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w') # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)])
def __init__(self, netcdfPath, startFrame, endFrame): from MMTK.Trajectory import Trajectory replyobj.status("Reading NetCDF file\n", blankAfter=0) try: self.trajectory = Trajectory(None, netcdfPath) finally: replyobj.status("Done reading NetCDF file\n") replyobj.status("Processing trajectory\n", blankAfter=0) self.atomNames = [] self.elements = [] self.resNames = [] self.atomIndices = {} self.bonds = [] self.ipres = [1] from chimera import Element univ = self.trajectory.universe for i, a in enumerate(univ.atomList()): self.atomIndices[a] = i self.atomNames.append(a.name) self.elements.append(Element(a.getAtomProperty(a, "symbol"))) for obj in univ: self._processObj(obj) delattr(self, "atomIndices") self.ipres.pop() self.startFrame = startFrame self.endFrame = endFrame self.name = os.path.basename(netcdfPath) replyobj.status("Done processing trajectory\n")
def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] self._partition = partition_universe(self.configuration['trajectory']['instance'].universe,self.configuration['atom_selection']['groups']) self._newUniverse = copy.copy(self.configuration['trajectory']['instance'].universe) self._newUniverse.removeObject(self._newUniverse.objectList()[:]) for i,g in enumerate(self._partition): at = Atom("H", name="com_%d" % i) at._mass = g.mass() at.index = i self._newUniverse.addObject(at) # The output trajectory is opened for writing. self._comt = Trajectory(self._newUniverse, self.configuration['output_files']['files'][0], "w") # The title for the trajectory is set. self._comt.title = self.__class__.__name__ # Create the snapshot generator. self._snapshot = SnapshotGenerator(self._newUniverse, actions = [TrajectoryOutput(self._comt, ("configuration","time"), 0, None, 1)])
def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] self.configuration['trajectory']['instance'].universe.__class__.__name__ = 'InfiniteUniverse' self.configuration['trajectory']['instance'].universe._descriptionArguments = lambda: '()' self.configuration['trajectory']['instance'].universe.is_periodic=False self._cellParametersFunction = self.configuration['trajectory']['instance'].universe.cellParameters atoms = sorted_atoms(self.configuration['trajectory']['instance'].universe) # The collection of atoms corresponding to the atoms selected for output. self._selectedAtoms = Collection([atoms[ind] for ind in self.configuration['atom_selection']['indexes']]) self._referenceAtoms = Collection([atoms[ind] for ind in self.configuration['reference_selection']['indexes']]) # The output trajectory is opened for writing. self._gmft = Trajectory(self._selectedAtoms, self.configuration['output_files']['files'][0], "w") # The title for the trajectory is set. self._gmft.title = self.__class__.__name__ # Create the snapshot generator. self.snapshot = SnapshotGenerator(self.configuration['trajectory']['instance'].universe, actions = [TrajectoryOutput(self._gmft, "all", 0, None, 1)]) # This will store the configuration used as the reference for the following step. self._referenceConfig = None
def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] atoms = sorted_atoms(self.configuration['trajectory']['instance'].universe) # The collection of atoms corresponding to the atoms selected for output. self._selectedAtoms = Collection([atoms[ind] for ind in self.configuration['atom_selection']['indexes']]) self._chemicalObjects = set([at.topLevelChemicalObject() for at in self._selectedAtoms]) # The output trajectory is opened for writing. self._outputTraj = Trajectory(self._selectedAtoms, self.configuration['output_files']['files'][0], "w") # The title for the trajectory is set. self._outputTraj.title = self.__class__.__name__ # Create the snapshot generator. self.snapshot = SnapshotGenerator(self.configuration['trajectory']['instance'].universe, actions = [TrajectoryOutput(self._outputTraj, "all", 0, None, 1)]) # This will store the configuration used as the reference for the following step. self._refCoords = None # Increase the recursion limit to avoid maximum recursion depth error when calling the contiguous_object recursive function self._oldRecursionLimit = sys.getrecursionlimit() sys.setrecursionlimit(100000)
def openTrajectory(self, event=None): """ Ths method is called when the user clicks on the 'Browse' button of the trajectory visualization dialog. It opens a file browser. After the file selection some of the dialog widgets are updated with the informations coming from the loaded trajectory. """ # Case where the user enters a file name directly in the entry widget without using the browser. if event is not None: if event.widget == self.fileBrowser.entry: filename = self.fileBrowser.getValue() else: return else: # The name of the NetCDF file to load. filename = askopenfilename(parent = self,\ filetypes = [('NetCDF file','*.nc')],\ initialdir = PREFERENCES['trajfile_path']) # The file must exist. if filename: try: # The trajectory is loaded. self.trajectory = Trajectory(None, filename, 'r') except IOError: raise Error('Can not read the trajectory.') else: # The control variables are updated with the informations about the loaded trajectory. self.fileBrowser.setValue(filename) self.selectedStepEntry.setValue('1') return 'break'
def initialize(self): ''' Initialize the job. ''' self._xtdfile = XTDFile(self.configuration["xtd_file"]["filename"]) self._xtdfile.build_universe() self._universe = self._xtdfile.universe self._hisfile = HisFile(self.configuration["his_file"]["filename"]) # The number of steps of the analysis. self.numberOfSteps = self._hisfile['n_frames'] if self._universe.is_periodic: self._universe.setShape(self._hisfile['initial_cell']) conf = Configuration(self._universe, self._hisfile["initial_coordinates"]) self._universe.setConfiguration(conf) self._universe.initializeVelocitiesToTemperature(0.) self._velocities = ParticleVector(self._universe) self._velocities.array = self._hisfile["initial_velocities"] self._universe.setVelocities(self._velocities) self._universe.foldCoordinatesIntoBox() # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w', comment=self._hisfile["title"]) # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)])
def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] self._universe = self.configuration['trajectory']['instance'].universe self._upperLeaflet = Collection([obj for obj in self._universe.objectList() if obj.name == self.configuration["upper_leaflet"]["value"]]) self._lowerLeaflet = Collection([obj for obj in self._universe.objectList() if obj.name == self.configuration["lower_leaflet"]["value"]]) self._membrane = Collection(self._upperLeaflet,self._lowerLeaflet) self._upperLeafletIndexes = [at.index for at in self._upperLeaflet.atomList()] self._lowerLeafletIndexes = [at.index for at in self._lowerLeaflet.atomList()] self._membraneIndexes = [at.index for at in self._membrane.atomList()] # The output trajectory is opened for writing. self._rmt = Trajectory(self._membrane, self.configuration['output_files']['files'][0], "w") # The title for the trajectory is set. self._rmt.title = self.__class__.__name__ # Create the snapshot generator. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._rmt, "all", 0, None, 1)]) self._axis = self.configuration["axis"]["index"]
def initialize(self): """ Initialize the input parameters and analysis self variables """ self.configuration["dcd_file"]["instance"] = DCDFile(self.configuration["dcd_file"]['filename']) # The number of steps of the analysis. self.numberOfSteps = self.configuration['dcd_file']['instance']['n_frames'] # Create all objects from the PDB file. conf = PDBConfiguration(self.configuration['pdb_file']['filename']) # Creates a collection of all the chemical objects stored in the PDB file molecules = conf.createAll() # If the input trajectory has PBC create a periodic universe. if self.configuration['dcd_file']['instance']['has_pbc_data']: self._universe = ParallelepipedicPeriodicUniverse() # Otherwise create an infinite universe. else: self._universe = InfiniteUniverse() # The chemical objects found in the PDB file introduced into the universe. self._universe.addObject(molecules) resolve_undefined_molecules_name(self._universe) # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w') # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions=[TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)])
def writeTrajectory(self, trajectory_name, block_size=1): trajectory = Trajectory(self.universe, trajectory_name, 'w', self.title, block_size=block_size) actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)] snapshot = SnapshotGenerator(self.universe, actions=actions) conf = self.universe.configuration() vel = self.universe.velocities() grad = ParticleVector(self.universe) nvectors = N_VECTORS natoms = N_ATOMS self._setSize() try: while True: vline = self.velfile.readline() pline = self.posfile.readline() if not vline: break vdata = vline.split() pdata = pline.split() if len(pdata) == 2: # Example: ["10", "0.00120944"] step = int(vdata[0]) step_data = {'time': step * DT} for i in range(natoms): conf.array[i] = map(float, string.split(self.posfile.readline())) vel.array[i] = map(float, string.split(self.velfile.readline())) conf.array = Units.Ang * conf.array if nvectors > 1: vel.array = Units.Ang / Units.ps * vel.array snapshot(data=step_data) finally: trajectory.close()
def interpreteInputParameters(self): """Parse the input parameters for the analysis. """ # Parses the parameters that are common to different analysis. Analysis.interpreteInputParameters(self) self.buildTimeInfo() self.subset = self.selectAtoms(self.subsetDefinition) self.nSelectedAtoms = len(self.subset) orderedAtoms = sorted(self.trajectory.universe.atomList(), key = operator.attrgetter('index')) selectedAtoms = Collection([orderedAtoms[ind] for ind in self.subset]) # traj_new is the filtered trajectory self.outputFile = Trajectory(selectedAtoms, self.output, "w") # Create the snapshot generator self.snapshot = SnapshotGenerator(self.trajectory.universe, actions = [TrajectoryOutput(self.outputFile, ["all"], 0, None, 1)])
def __init__(self, object, filename, mode='r', comment=None, double_precision=0, cycle=0): Trajectory.__init__(self, object, filename, mode='r', comment=None, double_precision=0, cycle=0) group_desc = eval(self.trajectory.file.variables['group_description']\ [:].tostring()) self.atoms = {} self.groups = {} for group in range(len(group_desc)): for atom in group_desc[group]: self.atoms[atom] = group self.groups[group_desc[group][0]] = group
def writeTrajectory(self, trajectory_name, block_size=1): trajectory = Trajectory(self.universe, trajectory_name, 'w', self.title, block_size=block_size) actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)] snapshot = SnapshotGenerator(self.universe, actions=actions) conf = self.universe.configuration() vel = self.universe.velocities() grad = ParticleVector(self.universe) nvectors = N_VECTORS natoms = N_ATOMS self._setSize() try: while True: vline = self.velfile.readline() pline = self.posfile.readline() if not vline: break vdata = vline.split() pdata = pline.split() if len(pdata) == 2: # Example: ["10", "0.00120944"] step = int(vdata[0]) step_data = {'time': step*DT} for i in range(natoms): conf.array[i] = map(float, string.split(self.posfile.readline())) vel.array[i] = map(float, string.split(self.velfile.readline())) conf.array = Units.Ang*conf.array if nvectors > 1: vel.array = Units.Ang/Units.ps * vel.array snapshot(data=step_data) finally: trajectory.close()
def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ if self.architecture == 'monoprocessor': t = self.trajectory else: # Load the whole trajectory set. t = Trajectory(None, self.trajectoryFilename, 'r') comsUniverse = t.universe.__copy__() comsUniverse.removeObject(comsUniverse.objectList()[:]) orderedAtoms = sorted(t.universe.atomList(), key = operator.attrgetter('index')) groups = [Collection([orderedAtoms[ind] for ind in g]) for g in self.group] comp = 1 for g in groups: comAtom = Atom('H', name = 'COM'+str(comp)) comAtom._mass = g.mass() comsUniverse.addObject(comAtom) comp += 1 # traj_new is the filtered trajectory outputFile = Trajectory(comsUniverse, self.output, "w") outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime() # Each time |snapshot| is called, the universe contents i flushed into the output file. snapshot = SnapshotGenerator(comsUniverse,\ actions = [TrajectoryOutput(outputFile, ["configuration","time"], 0, None, 1)]) # Loop over the output frames. for comp in range(self.nFrames): frameIndex = self.frameIndexes[comp] t.universe.setFromTrajectory(t, frameIndex) comsUniverse.setCellParameters(t.universe.cellParameters()) aComp = 0 for at in comsUniverse.atomList(): at.setPosition(self.comsTrajectory[frameIndex][aComp]) aComp += 1 snapshot(data = {'time': self.times[comp]}) # The output COM trajectory is closed. outputFile.close() self.toPlot = None
def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ if self.architecture == 'monoprocessor': t = self.trajectory else: # Load the whole trajectory set. t = Trajectory(None, self.trajectoryFilename, 'r') orderedAtoms = sorted(t.universe.atomList(), key = operator.attrgetter('index')) selectedAtoms = Collection([orderedAtoms[ind] for ind in self.subset]) targetAtoms = Collection([orderedAtoms[ind] for ind in self.target]) # traj_new is the filtered trajectory outputFile = Trajectory(targetAtoms, self.output, "w") outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime() # Create the snapshot generator snapshot = SnapshotGenerator(t.universe, actions = [TrajectoryOutput(outputFile, ["configuration"], 0, None, 1)]) # Loop over the output frames. for comp in range(self.nFrames): frameIndex = self.frameIndexes[comp] t.universe.setFromTrajectory(t, frameIndex) for at in targetAtoms: at.setPosition(Vector(self.filteredTrajectory[frameIndex][at.index])) snapshot(data = {'time': self.times[comp]}) outputFile.close() t.close() self.toPlot = None
def test_snapshot(self): initial = self.universe.copyConfiguration() transformation = Translation(Vector(0.,0.,0.01)) \ * Rotation(Vector(0.,0.,1.), 1.*Units.deg) trajectory = Trajectory(self.universe, "test.nc", "w", "trajectory test", double_precision=self.double_precision) snapshot = SnapshotGenerator( self.universe, actions=[TrajectoryOutput(trajectory, ["all"], 0, None, 1)]) snapshot() for i in range(100): self.universe.setConfiguration( self.universe.contiguousObjectConfiguration()) self.universe.applyTransformation(transformation) self.universe.foldCoordinatesIntoBox() snapshot() trajectory.close() self.universe.setConfiguration(initial) trajectory = Trajectory(None, "test.nc") t_universe = trajectory.universe for i in range(101): configuration = self.universe.configuration() t_configuration = trajectory[i]['configuration'] max_diff = N.maximum.reduce( N.ravel(N.fabs(configuration.array - t_configuration.array))) self.assert_(max_diff < self.tolerance) if configuration.cell_parameters is not None: max_diff = N.maximum.reduce( N.fabs(configuration.cell_parameters - t_configuration.cell_parameters)) self.assert_(max_diff < self.tolerance) self.universe.setConfiguration( self.universe.contiguousObjectConfiguration()) self.universe.applyTransformation(transformation) self.universe.foldCoordinatesIntoBox() trajectory.close()
def createTrajectoryAndIntegrator(self): '''create trajectory and integrator''' #initialize velocities--this has to happen after adding atoms self.mmtkUniverse.initializeVelocitiesToTemperature(self.inventory.sample.i.temperature) # Create trajectory and integrator. self.mmtkTrajectory = Trajectory(self.mmtkUniverse, self.inventory.trajectoryFilename, "w") self.mmtkIntegrator = VelocityVerletIntegrator(self.mmtkUniverse, delta_t=self.inventory.timeStep*Units.fs) # Periodical actions for equilibration output. self.equilibration_actions = [TranslationRemover(0, None, 100), RotationRemover(0, None, 100), LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None) ] # Periodical actions for trajectory output and text log output. self.output_actions = [TrajectoryOutput(self.mmtkTrajectory, ('configuration', 'energy', 'thermodynamic', 'time', 'auxiliary'), 0, None, 20), #TODO: Fixme so the user can specify when trajectory and sample frequency happens #this last option makes it so none of the equilibration steps are output, consistent with Gulp LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None, 20) #this last 0 makes it so all equilibration steps are output, consistent with Gulp ]
def initialize(self): """ Initialize the analysis (open trajectory, create output variables ...) """ self.numberOfSteps = self.configuration['frames']['number'] self._universe = self.configuration['trajectory']['instance'].universe # Create a MMTK collection from the atoms selected for translation. atoms = sorted_atoms(self.configuration['trajectory']['instance'].universe) self._selectedAtoms = Collection([atoms[ind] for ind in self.configuration['atom_selection']['indexes']]) # The output trajectory is opened for writing. self._btt = Trajectory(self._selectedAtoms, self.configuration['output_files']['files'][0], "w") self._btt.title = self.__class__.__name__ self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._btt, "all", 0, None, 1)]) # This will store the box coordinates of the previous configuration self._boxCoords = None
def initialize(self): ''' Initialize the job. ''' self._atomicAliases = self.configuration["atom_aliases"]["value"] self._fieldFile = FieldFile(self.configuration["field_file"]["filename"], aliases=self._atomicAliases) self._historyFile = HistoryFile(self.configuration["history_file"]["filename"], self.configuration["version"]["value"]) # The number of steps of the analysis. self.numberOfSteps = self._historyFile['n_frames'] if self._historyFile["imcon"] == 0: self._universe = InfiniteUniverse() else: self._universe = ParallelepipedicPeriodicUniverse() self._fieldFile.build_mmtk_contents(self._universe) self._velocities = None self._forces = None if self._historyFile["keytrj"] == 1: self._universe.initializeVelocitiesToTemperature(0.) self._velocities = ParticleVector(self._universe) elif self._historyFile["keytrj"] == 2: self._universe.initializeVelocitiesToTemperature(0.) self._velocities = ParticleVector(self._universe) self._forces = ParticleVector(self._universe) # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w', comment=self._fieldFile["title"]) # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)])
def createRestartTrajectoryAndIntegrator(self): '''initialize system from previous trajectory''' # Initialize system state from the restart trajectory self.mmtkUniverse.setFromTrajectory(Trajectory(self.mmtkUniverse, self.inventory.restartFilename)) # Create trajectory and integrator. self.mmtkTrajectory = Trajectory(self.mmtkUniverse, self.inventory.trajectoryFilename, "a") self.mmtkIntegrator = VelocityVerletIntegrator(self.mmtkUniverse, delta_t=self.inventory.timestep*Units.fs) # Periodical actions for equilibration output. self.equilibration_actions = [TranslationRemover(0, None, 100), RotationRemover(0, None, 100), LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None) ] # Periodical actions for trajectory output and text log output. self.output_actions = [TranslationRemover(0, None, 100), TrajectoryOutput(self.mmtkTrajectory, ('configuration', 'energy', 'thermodynamic', 'time', 'auxiliary'), 0, None, self.equilibrationSteps()), #this last option makes it so none of the equilibration steps are output, consistent with Gulp # Write restart data every time step. RestartTrajectoryOutput(self.inventory.restartFilename, 1), LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None) ]
def initialize(self): """ Initialize the input parameters and analysis self variables """ # The indices of frames which should be extacted from pdb file self.frame_list = self.configuration['nb_frame']["value"] self.numberOfSteps = self.configuration['nb_frame']["number"] # Create all objects from the PDB file. pdb_config = PDBFile(self.configuration['pdb_file']['filename'], model = 0) # Create the universe. self._universe = pdb_config.createUnitCellUniverse() # Construct system self._universe.addObject(pdb_config.createAll(None, 1)) # Open the new trajectory self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], "w", "Converted from PDB") # Make a snapshot generator for saving. self._snapshot = SnapshotGenerator(self._universe,actions = [TrajectoryOutput(self._trajectory, None, 0, None, 1)])
def initialize(self): ''' Initialize the job. ''' self._xdatcarFile = XDATCARFile(self.configuration["xdatcar_file"]["filename"]) # The number of steps of the analysis. self.numberOfSteps = self._xdatcarFile['n_frames'] self._universe = ParallelepipedicPeriodicUniverse() self._universe.setShape(self._xdatcarFile["cell_shape"]) for symbol,number in self._xdatcarFile["atoms"]: for i in range(number): self._universe.addObject(Atom(symbol, name="%s_%d" % (symbol,i))) # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w') # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)])
def initialize(self): ''' Initialize the job. ''' # The number of steps of the analysis. self.numberOfSteps = self.configuration["n_steps"]["value"] self._lammpsConfig = LAMMPSConfigFile(self.configuration["config_file"]["value"]) self.parse_first_step() # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w') self._nameToIndex = dict([(at.name,at.index) for at in self._universe.atomList()]) # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)]) self._lammps.seek(0,0) self._start = 0
def do_analysisPerElement(analysis, element, trajname): """Performs the analysis element-by-element, the element being either an atom (atom-by-atom analysis), a frame index (frame-by-frame analysis), a group of atom (group-by-group analysis) or a set of q vectors. @param analysis: the selected analysis. @type analysis: a subclass of nMOLDYN.Analysis.Analysis.Analysis class @param element: the element on which the analysis is based. @type element: MMTK.Atom|integer|MMTK.Collections.Collection|nMOLDYN.Mathematics.QVectors @param trajname: a string specifying the name of the trajectory. @type trajname: string @return: the results of the analysis performed on one element. @rtype: depends on the analysis """ global trajectory if trajectory is None: trajectory = Trajectory(None, trajname) hierarchizeUniverse(trajectory.universe) return analysis.calc(element, trajectory)
def viewTrajectory(trajectory, first=0, last=None, skip=1, subset=None, label=None): """ Launches an animation based on a trajectory using an external viewer. :param trajectory: the trajectory :type trajectory: :class:`~MMTK.Trajectory.Trajectory` :param first: the first trajectory step to be used :type first: int :param last: the first trajectory step NOT to be used :type last: int :param skip: the distance between two consecutive steps shown :type skip: int :param subset: the subset of the universe that is shown (default: the whole universe) :type subset: :class:`~MMTK.Collections.GroupOfAtoms` :param label: an optional text string that some interfaces use to pass a description of the object to the visualization system. :type label: str """ if type(trajectory) == type(''): from MMTK.Trajectory import Trajectory trajectory = Trajectory(None, trajectory, 'r') if last is None: last = len(trajectory) elif last < 0: last = len(trajectory) + last universe = trajectory.universe if subset is None: subset = universe viewSequence(subset, trajectory.configuration[first:last:skip], label)
def test_snapshot(self): initial = self.universe.copyConfiguration() transformation = Translation(Vector(0.,0.,0.01)) \ * Rotation(Vector(0.,0.,1.), 1.*Units.deg) trajectory = Trajectory(self.universe, "test.nc", "w", "trajectory test", double_precision = self.double_precision) snapshot = SnapshotGenerator(self.universe, actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)]) snapshot() for i in range(100): self.universe.setConfiguration( self.universe.contiguousObjectConfiguration()) self.universe.applyTransformation(transformation) self.universe.foldCoordinatesIntoBox() snapshot() trajectory.close() self.universe.setConfiguration(initial) trajectory = Trajectory(None, "test.nc") t_universe = trajectory.universe for i in range(101): configuration = self.universe.configuration() t_configuration = trajectory[i]['configuration'] max_diff = N.maximum.reduce(N.ravel(N.fabs(configuration.array - t_configuration.array))) self.assert_(max_diff < self.tolerance) if configuration.cell_parameters is not None: max_diff = N.maximum.reduce(N.fabs(configuration.cell_parameters - t_configuration.cell_parameters)) self.assert_(max_diff < self.tolerance) self.universe.setConfiguration( self.universe.contiguousObjectConfiguration()) self.universe.applyTransformation(transformation) self.universe.foldCoordinatesIntoBox() trajectory.close()
rotengmat=roteng, rotstep=float(rotstepval)) #integrator = Rot2DOnly_PILangevinNormalModeIntegrator(universe, delta_t=dt, centroid_friction = friction, densmat=rho,rotengmat=roteng, rotstep=float(rotstepval)) #integrator(steps=1000, actions = [ TrajectoryOutput(None,('configuration','time'), 0, None, 100)]) #raise() RunSteps = 500.0 * Units.ps / dt print "RunSteps:", RunSteps SkipSteps = 50.0 * Units.fs / dt print "SkipSteps:", SkipSteps #trajectory = Trajectory(universe, outdir+str(nCO2)+"CO2He-P"+str(P)+"-"+"T"+str(temperature)+"-"+label+"-"+testnum+".nc", "w", "A simple test case") trajectory = Trajectory( universe, outdir + str(nCO2) + "CO2" + "-" + str(nhelium) + "He-P" + str(P) + "-" + "T" + str(temperature) + "-" + label + "-" + testnum + ".nc", "w", "A simple test case") Nblocks = 1 ################################################################################################ ########################### BEGIN TRANSLATION/ROTATION SIMULATION ############################## ################################################################################################ # RUN PIMD WITH PIMC ROTATION INCLUDED print "We're going to run the Langevin integrator for ", RunSteps / SkipSteps, "independent steps of PIMD" integrator( steps=RunSteps, # Remove global translation every 50 steps. actions=[ TrajectoryOutput(
dv = -0.5*delta_t*gradients*inv_masses velocities += dv universe.setVelocities(velocities) time += delta_t snapshot(data={'time': time, 'potential_energy': energy}) if equilibration_temperature is not None \ and step % equilibration_frequency == 0: universe.scaleVelocitiesToTemperature(equilibration_temperature) # Define system universe = InfiniteUniverse(Amber99ForceField()) universe.protein = Protein('bala1') # Create trajectory and snapshot generator trajectory = Trajectory(universe, "md_trajectory.nc", "w", "Generated by a Python integrator") snapshot = SnapshotGenerator(universe, actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)]) # Initialize velocities universe.initializeVelocitiesToTemperature(50.*Units.K) # Heat and equilibrate for temperature in [50., 100., 200., 300.]: doVelocityVerletSteps(delta_t = 1.*Units.fs, nsteps = 500, equilibration_temperature = temperature*Units.K, equilibration_frequency = 1) doVelocityVerletSteps(delta_t = 1.*Units.fs, nsteps = 500, equilibration_temperature = 300*Units.K, equilibration_frequency = 10) # Production run
class DCDConverter(Converter): """ Converts a DCD trajectory to a MMTK trajectory. """ type = None settings = collections.OrderedDict() settings['pdb_file'] = ('input_file',{}) settings['dcd_file'] = ('input_file',{}) settings['output_file'] = ('output_files', {'formats':["netcdf"]}) settings['fold'] = ('boolean', {'default':False,'label':"Fold coordinates in to box"}) def initialize(self): """ Initialize the input parameters and analysis self variables """ self.configuration["dcd_file"]["instance"] = DCDFile(self.configuration["dcd_file"]['filename']) # The number of steps of the analysis. self.numberOfSteps = self.configuration['dcd_file']['instance']['n_frames'] # Create all objects from the PDB file. conf = PDBConfiguration(self.configuration['pdb_file']['filename']) # Creates a collection of all the chemical objects stored in the PDB file molecules = conf.createAll() # If the input trajectory has PBC create a periodic universe. if self.configuration['dcd_file']['instance']['has_pbc_data']: self._universe = ParallelepipedicPeriodicUniverse() # Otherwise create an infinite universe. else: self._universe = InfiniteUniverse() # The chemical objects found in the PDB file introduced into the universe. self._universe.addObject(molecules) resolve_undefined_molecules_name(self._universe) # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w') # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions=[TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)]) def run_step(self, index): """ Runs a single step of the job.\n :Parameters: #. index (int): The index of the step. :Returns: #. index (int): The index of the step. """ # The x, y and z values of the current frame. unitCell, config = self.configuration["dcd_file"]["instance"].read_step() conf = Configuration(self._universe,config) # If the universe is periodic set its shape with the current dimensions of the unit cell. if self._universe.is_periodic: self._universe.setShape(get_basis_vectors_from_cell_parameters(unitCell)) self._universe.setConfiguration(conf) if self.configuration['fold']["value"]: self._universe.foldCoordinatesIntoBox() # The current time. t = (index+1)*self.configuration["dcd_file"]["instance"]['time_step'] # Store a snapshot of the current configuration in the output trajectory. self._snapshot(data={'time': t}) return index, None def combine(self, index, x): """ Combines returned results of run_step.\n :Parameters: #. index (int): The index of the step.\n #. x (any): The returned result(s) of run_step """ pass def finalize(self): """ Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ # Close the output trajectory. self._trajectory.close()
denrho=denrho, denerot=denerot, denesq=denesq, rotstep=float(Rot_Step), rotskipstep=float(Rot_Skip)) integrator( steps=3000, actions=[TrajectoryOutput(None, ('configuration', 'time'), 0, None, 100)] ) # relates to the default_options = {'first_step': 0...} section of the main code. RunSteps = int(numsteps) * Units.fs / dt SkipSteps = 1.0 * Units.fs / dt trajectory = Trajectory( universe, outdir + "N" + str(nmolecules) + "H20T" + str(temperature) + "P" + str(P) + "R" + str(lattice_spacing) + "FilEFVersion" + str(numsteps) + "Steps" + label + ".nc", "w", "A simple test case") Nblocks = 1 ############################## BEGIN ROTATION SIMULATION ############################## # RUN PIMD WITH PIMC ROTATION INCLUDED print "We're going to run the Langevin integrator for ", RunSteps / SkipSteps, "independent steps of PIMD" integrator( steps=RunSteps, # Remove global translation every 50 steps. actions=[ TrajectoryOutput( trajectory, ("time", "thermodynamic", "energy", "configuration", "auxiliary"),
dt = 1.0*Units.fs # Initialize velocities universe.initializeVelocitiesToTemperature(temperature) # USE THE FRICTION PARAMETER FROM BEFORE friction = 0.0 integrator = RotOnlyWolff_PILangevinNormalModeIntegrator(universe, delta_t=dt, centroid_friction = friction, densmat=rho,rotengmat=roteng, rotstep=float(Rot_Step), rotskipstep=int(Rot_Skip)) integrator(steps=5000, actions = [ TrajectoryOutput(None,('configuration','time'), 0, None, 100)] ) RunSteps = 50.0*Units.ps/dt SkipSteps = 50.0*Units.fs/dt trajectory = Trajectory(universe, outdir+str(nmolecules)+"HF-P"+str(P)+"_"+label+".nc", "w", "A simple test case") Nblocks=1 ############################## BEGIN ROTATION SIMULATION ############################## # RUN PIMD WITH PIMC ROTATION INCLUDED print "We're going to run the Langevin integrator for ", RunSteps/SkipSteps, "independent steps of PIMD" integrator(steps=RunSteps, # Remove global translation every 50 steps. actions = [ TrajectoryOutput(trajectory, ("time", "thermodynamic", "energy", "configuration", "auxiliary"), 0, None, SkipSteps)]) npoints = len(trajectory) universe = trajectory.universe
#This creates the integrator object by creating the class defined in LangevinDynamics.py #Note that the restraint parameter is a list where the first element is a list of lists. The first list #contains the particle indices for which the first centre of mass should be calculated and the second list #contains the particle indices for the second centre of mass, the 2nd parameter is the k value for the restraint, #third is the equilibrium value, and finally a string that is 'com' for centre of mass or 'cog' for centre of geometry (and more could be added) integrator = LangevinIntegrator(universe, delta_t=dt, friction=friction, temperature=temperature, restraint=[[0,1,2],[3,4,5],k_restraint,r0_restraint,'com']) #Create the trajectory files for both equilbration and production runs dir = "spcfw-q_2_"+str(nb)+"_"+str(k_restraint)+"_"+str(r0_restraint) try: os.mkdir(dir) except (OSError): print 'Do not need to create directory, ' + dir + ', it is already present' trajectory_eq = Trajectory(universe, dir + "//" + dir + "_eq.nc", "w") trajectory_prod = Trajectory(universe, dir + "//" + dir + "_prod.nc", "w") # Periodical actions for trajectory output and text log output. eq_output_actions = [TrajectoryOutput(trajectory_eq, ('configuration', 'energy', 'thermodynamic', 'time', 'auxiliary','velocities'), 0, None, 100)] # StandardLogOutput(100)] prod_output_actions = [TrajectoryOutput(trajectory_prod, ('configuration', 'energy', 'thermodynamic', 'time', 'auxiliary','velocities'), 0, None, skipSteps)] #Perform the equilibration portion print '.....Beginning Equlibration.....................................................' integrator(steps = EquilSteps, actions = eq_output_actions)
maxP = P / 2 - dist c = zeros((3, maxP), float) c2 = zeros((3, maxP), float) counter = 0 label = "P-" + str(P) + "-" + str(start) c0file = open("/warehouse/mdgschmi/MBpolMonomer/corr-sym-" + label, "w") c1file = open("/warehouse/mdgschmi/MBpolMonomer/corr-bend-" + label, "w") c2file = open("/warehouse/mdgschmi/MBpolMonomer/corr-asym-" + label, "w") nmodes = 3 * natoms - 6 r = zeros((natoms, P, 3), float) trajlength = len(Trajectory(universe, traj)) mean0 = 0. mean1 = 0. mean2 = 0. for i in range(trajlength): universe.setFromTrajectory(Trajectory(universe, traj), i) r[0] = asarray(universe.atomList()[0].beadPositions()) #Hydrogen 1 r[1] = asarray(universe.atomList()[1].beadPositions()) #Hydrogen 2 r[2] = asarray(universe.atomList()[2].beadPositions()) #Oxygen bond_down = zeros((3, maxP), float) bond_up = zeros((3, maxP), float) for p in range(maxP):
def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ if self.architecture == 'monoprocessor': t = self.trajectory else: # Load the whole trajectory set. t = Trajectory(None, self.trajectoryFilename, 'r') selectedAtoms = Collection() orderedAtoms = sorted(t.universe.atomList(), key=operator.attrgetter('index')) groups = [[ selectedAtoms.addObject(orderedAtoms[index]) for index in atomIndexes ] for atomIndexes in self.group] # Create trajectory outputFile = Trajectory(selectedAtoms, self.output, 'w') # Create the snapshot generator snapshot = SnapshotGenerator( t.universe, actions=[ TrajectoryOutput(outputFile, ["configuration", "time"], 0, None, 1) ]) # The output is written for comp in range(self.nFrames): frameIndex = self.frameIndexes[comp] t.universe.setFromTrajectory(t, frameIndex) for atom in selectedAtoms: atom.setPosition(self.RBT['trajectory'][atom.index][comp, :]) snapshot(data={'time': self.times[comp]}) outputFile.close() outputFile = NetCDFFile(self.output, 'a') outputFile.title = self.__class__.__name__ outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime( ) outputFile.jobinfo += 'Input trajectory: %s\n\n' % self.trajectoryFilename outputFile.createDimension('NFRAMES', self.nFrames) outputFile.createDimension('NGROUPS', self.nGroups) outputFile.createDimension('QUATERNIONLENGTH', 4) # The NetCDF variable that stores the quaternions. QUATERNIONS = outputFile.createVariable( 'quaternion', N.Float, ('NGROUPS', 'NFRAMES', 'QUATERNIONLENGTH')) # The NetCDF variable that stores the centers of mass. COM = outputFile.createVariable('com', N.Float, ('NGROUPS', 'NFRAMES', 'xyz')) # The NetCDF variable that stores the rigid-body fit. FIT = outputFile.createVariable('fit', N.Float, ('NGROUPS', 'NFRAMES')) # Loop over the groups. for comp in range(self.nGroups): aIndexes = self.group[comp] outputFile.jobinfo += 'Group %s: %s\n' % ( comp + 1, [index for index in aIndexes]) QUATERNIONS[comp, :, :] = self.RBT[comp]['quaternions'][:, :] COM[comp, :, :] = self.RBT[comp]['com'][:, :] FIT[comp, :] = self.RBT[comp]['fit'][:] outputFile.close() self.toPlot = None
actions=[ Heater(50. * Units.K, 300. * Units.K, 0.5 * Units.K / Units.fs, 0, None, 1), # Remove global translation every 50 steps. TranslationRemover(0, None, 50), # Remove global rotation every 50 steps. RotationRemover(0, None, 50), # Log output to screen every 100 steps. StandardLogOutput(100) ]) print("Time: " + str(time.time() - start)), file.write("Time: " + str(time.time() - start)) # "Production" run trajectory = Trajectory(universe, "insulin.nc", "w", "A simple test case") universe.protein.writeToFile('folded_protein.pdb') '''integrator(steps=1000, # Remove global translation every 50 steps. actions = [TranslationRemover(0, None, 50), # Remove global rotation every 50 steps. RotationRemover(0, None, 50), # Write every second step to the trajectory file. TrajectoryOutput(trajectory, ("time", "energy", "thermodynamic", "configuration"), 0, None, 2), # Write restart data every fifth step. RestartTrajectoryOutput("restart.nc", 5), # Log output to screen every 10 steps.
class CenterOfMassesTrajectory(IJob): """ Creates a trajectory out of the center of masses motions for a selection of atoms of a given input trajectory """ type = 'comt' label = "Center Of Masses Trajectory" category = ('Trajectory',) ancestor = "mmtk_trajectory" settings = collections.OrderedDict() settings['trajectory'] = ('mmtk_trajectory',{}) settings['frames'] = ('frames', {'dependencies':{'trajectory':'trajectory'}, 'default':(0,1,1)}) settings['atom_selection'] = ('atom_selection',{'dependencies':{'trajectory':'trajectory', 'grouping_level':'grouping_level'}}) settings['grouping_level'] = ('grouping_level',{}) settings['output_files'] = ('output_files', {'formats':["netcdf"]}) def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] self._partition = partition_universe(self.configuration['trajectory']['instance'].universe,self.configuration['atom_selection']['groups']) self._newUniverse = copy.copy(self.configuration['trajectory']['instance'].universe) self._newUniverse.removeObject(self._newUniverse.objectList()[:]) for i,g in enumerate(self._partition): at = Atom("H", name="com_%d" % i) at._mass = g.mass() at.index = i self._newUniverse.addObject(at) # The output trajectory is opened for writing. self._comt = Trajectory(self._newUniverse, self.configuration['output_files']['files'][0], "w") # The title for the trajectory is set. self._comt.title = self.__class__.__name__ # Create the snapshot generator. self._snapshot = SnapshotGenerator(self._newUniverse, actions = [TrajectoryOutput(self._comt, ("configuration","time"), 0, None, 1)]) def run_step(self, index): """ Runs a single step of the job.\n :Parameters: #. index (int): The index of the step. :Returns: #. index (int): The index of the step. #. None """ # get the Frame index frameIndex = self.configuration['frames']['value'][index] # The configuration corresponding to this index is set to the universe. self.configuration['trajectory']['instance'].universe.setFromTrajectory(self.configuration['trajectory']['instance'], frameIndex) comConf = self._newUniverse.configuration().array for i, atoms in enumerate(self._partition): comConf[i,:] = atoms.centerOfMass() # The times corresponding to the running index. t = self.configuration['frames']['time'][index] self._newUniverse.foldCoordinatesIntoBox() # A snapshot of the universe is written to the output trajectory. self._snapshot(data={'time': t}) return index, None def combine(self, index, x): """ Combines returned results of run_step.\n :Parameters: #. index (int): The index of the step.\n #. x (any): The returned result(s) of run_step """ pass def finalize(self): """ Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ # The input trajectory is closed. self.configuration['trajectory']['instance'].close() # The output trajectory is closed. self._comt.close()
atom.setNumberOfBeads(P) natoms = len(universe.atomList()) universe.setForceField(mbpolForceField(universe)) #This is the conversion factor to Units of K Kper1overcm=11604.505/8065.54445 conv=Kper1overcm/1.196e-2 #print 1./(Units.k_B*0.37*Units.K) #print traj #rotskipval=float(argv[2]) mbpol_test=True if mbpol_test: trajectory = Trajectory(universe, traj) else: trajectory = Trajectory(None, traj) print 'test' npoints = len(trajectory) universe = trajectory.universe natoms = universe.numberOfAtoms() time = trajectory.time np = universe.numberOfPoints() P = np/natoms #if (rotskipval < 100.0): # rotskipratio=1.0 #else: # rotskipratio=100.0/rotskipval
class LAMMPSConverter(Converter): """ Converts a LAMMPS trajectory to a MMTK trajectory. """ type = 'lammps' label = "LAMMPS" category = ('Converters',) ancestor = None settings = collections.OrderedDict() settings['config_file'] = ('input_file', {'label':"LAMMPS configuration file"}) settings['trajectory_file'] = ('input_file', {'label':"LAMMPS trajectory file"}) settings['time_step'] = ('float', {'label':"time step (fs)", 'default':1.0, 'mini':1.0e-9}) settings['n_steps'] = ('integer', {'label':"number of time steps", 'default':1, 'mini':0}) settings['output_file'] = ('output_files', {'formats':["netcdf"]}) def initialize(self): ''' Initialize the job. ''' # The number of steps of the analysis. self.numberOfSteps = self.configuration["n_steps"]["value"] self._lammpsConfig = LAMMPSConfigFile(self.configuration["config_file"]["value"]) self.parse_first_step() # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w') self._nameToIndex = dict([(at.name,at.index) for at in self._universe.atomList()]) # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)]) self._lammps.seek(0,0) self._start = 0 def run_step(self, index): """Runs a single step of the job. @param index: the index of the step. @type index: int. @note: the argument index is the index of the loop note the index of the frame. """ for _ in range(self._itemsPosition["TIMESTEP"][0]): line = self._lammps.readline() if not line: return index, None timeStep = Units.fs*float(self._lammps.readline())*self.configuration['time_step']['value'] for _ in range(self._itemsPosition["TIMESTEP"][1], self._itemsPosition["BOX BOUNDS"][0]): self._lammps.readline() abcVectors = numpy.zeros((9), dtype=numpy.float64) temp = [float(v) for v in self._lammps.readline().split()] if len(temp) == 2: xlo, xhi = temp xy = 0.0 elif len(temp) == 3: xlo, xhi, xy = temp else: raise LAMMPSTrajectoryFileError("Bad format for A vector components") temp = [float(v) for v in self._lammps.readline().split()] if len(temp) == 2: ylo, yhi = temp xz = 0.0 elif len(temp) == 3: ylo, yhi, xz = temp else: raise LAMMPSTrajectoryFileError("Bad format for B vector components") temp = [float(v) for v in self._lammps.readline().split()] if len(temp) == 2: zlo, zhi = temp yz = 0.0 elif len(temp) == 3: zlo, zhi, yz = temp else: raise LAMMPSTrajectoryFileError("Bad format for C vector components") # The ax component. abcVectors[0] = xhi - xlo # The bx and by components. abcVectors[3] = xy abcVectors[4] = yhi - ylo # The cx, cy and cz components. abcVectors[6] = xz abcVectors[7] = yz abcVectors[8] = zhi - zlo abcVectors *= Units.Ang for _ in range(self._itemsPosition["BOX BOUNDS"][1], self._itemsPosition["ATOMS"][0]): self._lammps.readline() self._universe.setCellParameters(abcVectors) conf = self._universe.configuration() for i,_ in enumerate(range(self._itemsPosition["ATOMS"][0], self._itemsPosition["ATOMS"][1])): temp = self._lammps.readline().split() idx = self._nameToIndex[self._rankToName[i]] conf.array[idx,:] = numpy.array([temp[self._x],temp[self._y],temp[self._z]],dtype=numpy.float64) if self._fractionalCoordinates: conf.array = self._universe._boxToRealPointArray(conf.array) else: conf.array *= Units.Ang # The whole configuration is folded in to the simulation box. self._universe.foldCoordinatesIntoBox() # A snapshot is created out of the current configuration. self._snapshot(data = {'time': timeStep}) self._start += self._last return index, None def combine(self, index, x): """ @param index: the index of the step. @type index: int. @param x: @type x: any. """ pass def finalize(self): """ Finalize the job. """ self._lammps.close() if self._lammpsConfig["n_bonds"] is not None: netcdf = self._trajectory.trajectory.file netcdf.createDimension("MDANSE_NBONDS",self._lammpsConfig["n_bonds"]) netcdf.createDimension("MDANSE_TWO",2) VAR = netcdf.createVariable("mdanse_bonds", numpy.dtype(numpy.int32).char, ("MDANSE_NBONDS","MDANSE_TWO")) VAR.assignValue(self._lammpsConfig["bonds"]) # Close the output trajectory. self._trajectory.close() def parse_first_step(self): self._lammps = open(self.configuration["trajectory_file"]["value"], 'r') self._itemsPosition = collections.OrderedDict() self._universe = None comp = -1 while True: line = self._lammps.readline() comp += 1 if not line: break if line.startswith("ITEM: TIMESTEP"): self._itemsPosition["TIMESTEP"] = [comp+1, comp+2] continue elif line.startswith("ITEM: BOX BOUNDS"): self._itemsPosition["BOX BOUNDS"] = [comp+1, comp+4] continue elif line.startswith("ITEM: ATOMS"): keywords = line.split()[2:] self._id = keywords.index("id") self._type = keywords.index("type") try: self._x = keywords.index("x") self._y = keywords.index("y") self._z = keywords.index("z") except ValueError: try: self._x = keywords.index("xs") self._y = keywords.index("ys") self._z = keywords.index("zs") except ValueError: raise LAMMPSTrajectoryFileError("No coordinates could be found in the trajectory") else: self._fractionalCoordinates = True else: self._fractionalCoordinates = False self._rankToName = {} g = Graph() self._universe = ParallelepipedicPeriodicUniverse() self._itemsPosition["ATOMS"] = [comp+1,comp+self._nAtoms+1] for i in range(self._nAtoms): temp = self._lammps.readline().split() idx = int(temp[self._id])-1 ty = temp[self._type] name = "%s%s" % (self._lammpsConfig["elements"][ty],idx) self._rankToName[i] = name g.add_node(idx, element=self._lammpsConfig["elements"][ty], name=name) if self._lammpsConfig["n_bonds"] is not None: for idx1,idx2 in self._lammpsConfig["bonds"]: g.add_link(idx1,idx2) for cluster in g.build_connected_components(): if len(cluster) == 1: at = cluster.pop() obj = Atom(at.element, name=at.name) obj.index = at.id else: atList = [] for atom in cluster: at = Atom(atom.element, name=atom.name) atList.append(at) c = collections.Counter([at.element for at in cluster]) name = "".join(["%s%d" % (k,v) for k,v in sorted(c.items())]) obj = AtomCluster(atList, name=name) self._universe.addObject(obj) self._last = comp + self._nAtoms + 1 break elif line.startswith("ITEM: NUMBER OF ATOMS"): self._nAtoms = int(self._lammps.readline()) comp += 1 continue
def process(cdffile, file_output, All_Prop, SF): dirname, filepath = os.path.split(cdffile) filename, ext = os.path.splitext(filepath) traj = Trajectory(None, cdffile) universe = traj.universe forces = traj.gradients box_posvec = traj.box_coordinates chains = universe.objectList(AtomCluster) chains_indices = [[atom.index for atom in chain.atomList()] for chain in chains] chains_ns = [chain.numberOfAtoms() for chain in chains] print('In postprocessing %s' % filename) print 'ASPeriodicity = ', periodicity print 'Lja2 = ', Lja2 # Number of sample points Ns = len(traj) # Number of chains Nc = len(chains) print(Ns, Nc, chains_ns[0]) #NAs = (int(chains_ns[0]/periodicity) + 1)*Nc # total no. of associating beads for all the chains for telechelic system NAs = ( int(chains_ns[0] / periodicity) ) * Nc # total no. of associating beads for all the chains for multi-sticker system print NAs if All_Prop: # center of mass r_coms = np.zeros((Ns, Nc, 3)) # end to end distance q_sqs = np.zeros((Ns, Nc)) # Radius of gyration rg_sqs = np.zeros((Ns, Nc)) # tau xy tauxys = np.zeros(Ns) ## Neighbour matrix Mij(for association dynamics), added by Aritra #Mij = np.zeros((Ns, chains_ns[0], chains_ns[0])) # for single chain system Mij = np.zeros((Ns, NAs, NAs)) # for multi-chain system # local time correlation function Ft = np.zeros(Ns) # Connectivity matirix for cluster #Cij = Mij.astype(int) Cij = Mij.astype(int) # for multi-chain system Rank = np.zeros(1000) # Rank of the connectivity matrix clustsize = np.zeros(1000) # cluster size closedsticker = np.zeros(1000) # fraction of closed stickers opensticker = np.zeros(1000) # fraction of open stickers Pn = np.zeros( NAs) # binning to calculate probability dist of cluster size ''' for tid, conf in enumerate(traj.configuration): tauxy = 0.0 for cid, chain_indices in enumerate(chains_indices): positions = conf.array[chain_indices] r_com = positions.sum(axis = 0) / chains_ns[cid] q_sq = ((positions[0] - positions[-1])**2).sum() rel_pos = positions - r_com rg_sq = (rel_pos**2).sum() / chains_ns[cid] tauxy += (rel_pos[:, 0] * forces[tid].array[chain_indices][:, 1]).sum() r_coms[tid, cid] = r_com q_sqs[tid, cid] = q_sq rg_sqs[tid, cid] = rg_sq tauxys[tid] = tauxy # computation of Neighbour matrix for single chain for tid, conf in enumerate(traj.configuration): for cid, chain_indices in enumerate(chains_indices): positions = conf.array[chain_indices] for i in range(chains_ns[cid]-2): for j in range(i+2, chains_ns[cid]): rijsq = ((positions[i] - positions[j])**2).sum() rij = sqrt(rijsq) if rij < 1.5: Mij[tid, i, j] = 1 ''' ''' # computation of Neighbour matrix for multi-chain systems for tid, conf in enumerate(traj.box_coordinates): for cid, chain_indices in enumerate(chains_indices): positions = conf.array[chain_indices] if cid == 0: beadpositions = positions else: beadpositions = np.append(beadpositions, positions, axis=0) # writing position vectors of all the beads for all chains. p = 0 # bead index for associating bead i q = 0 # bead index for associating bead j for i in range(chains_ns[0]*Nc - 1): nc_i = int(i/chains_ns[0]) # chain number for bead i if ((i - nc_i) % periodicity == 0 and i > 0): p += 1 if (p > (NAs-1)): print 'p is greater than NAs: ', p+1 for j in range(i+1, chains_ns[0]*Nc): nc_j = int(j/chains_ns[0]) # chain number for bead j if ((j - nc_j) % periodicity == 0 and j > 0): q = p + 1 if (q > (NAs-1)): print 'q is greater than NAs: ', q+1 if (((i - nc_i) % periodicity) == 0 and ((j - nc_j) % periodicity) == 0): rijsq = ((beadpositions[i] - beadpositions[j])**2).sum() rij = sqrt(rijsq) if (rij < 1.5*Lja2): Mij[tid, p, q] = 1 q = 0 if (tid % 2000 == 0): print 'tid = ', tid ## compution of number of cluster and cluster size for single chain system for tid, conf in enumerate(traj.configuration): for cid, chain_indices in enumerate(chains_indices): positions = conf.array[chain_indices] for i in range(chains_ns[cid]): for j in range(chains_ns[cid]): rijsq = ((positions[i] - positions[j])**2).sum() rij = sqrt(rijsq) if rij < 2.8: Cij[tid, i, j] = 1 # computation of rank of connectivity matrix to find out number of cluster for t in range(Ns): if ((t+1) % 1000 == 0): tid = t+1 N0 = chains_ns[0] N = chains_ns[0] #print Cij[tid,:,:] #print "****************" for i in range(N0): if i < N: switch = 1 while (switch == 1): for j in range(i, N): switch = 0 c = np.bitwise_and(Cij[tid,:,i], Cij[tid,:,j]) if ((c**2).sum() != 0 and j!=i): switch = 1 Cij[tid,:,i] = np.bitwise_or(Cij[tid,:,i], Cij[tid,:,j]) N1 = j N = N-1 for k in range(N1+1, N+1): Cij[tid,:,k-1] = Cij[tid,:,k] break else: break Rank[tid/1000 - 1] = N clustsize[tid/1000 - 1] = float(chains_ns[0])/N #print Cij[tid,:,:] #print "#######################" ''' ## computation of number of cluster and cluster size for multi-chain system for tid, conf in enumerate(traj.box_coordinates): for cid, chain_indices in enumerate(chains_indices): positions = conf.array[chain_indices] if cid == 0: beadpositions = positions else: beadpositions = np.append( beadpositions, positions, axis=0 ) # writing position vectors of all the beads for all chains. p = 0 # bead index for associating bead i q = 0 # bead index for associating bead j for i in range(chains_ns[0] * Nc): nc_i = int(i / chains_ns[0]) # chain number for bead i # for telechelic system ''' if ((i - nc_i) % periodicity == 0 and i > 0): p += 1 if (p > (NAs-1)): print 'p is greater than NAs: ', p+1 ''' # for multi-sticker system (4 : periodicity-1) if (((i - 4) + nc_i) % periodicity == 0 and i > 4): p += 1 if (p > (NAs - 1)): print 'p is greater than NAs: ', p + 1 for j in range(chains_ns[0] * Nc): nc_j = int(j / chains_ns[0]) # chain number for bead j # for telechelic system ''' if ((j - nc_j) % periodicity == 0 and j > 0): q += 1 if (q > (NAs-1)): print 'q is greater than NAs: ', q+1 ''' # for multi-sticker system (4: periodicity-1) if (((j - 4) + nc_j) % periodicity == 0 and j > 4): q += 1 if (q > (NAs - 1)): print 'q is greater than NAs: ', q + 1 # for telechelic system ''' if (((i - nc_i) % periodicity) == 0 and ((j - nc_j) % periodicity) == 0): rijsq = ((beadpositions[i] - beadpositions[j])**2).sum() rij = sqrt(rijsq) if (rij < 1.5*Lja2): Cij[tid, p, q] = 1 ''' # for multi-sticker system if ((((i - 4) + nc_i) % periodicity) == 0 and (((j - 4) + nc_j) % periodicity) == 0): rijsq = ((beadpositions[i] - beadpositions[j])**2).sum() rij = sqrt(rijsq) if (rij < 1.82 * Lja2): Cij[tid, p, q] = 1 q = 0 if (tid % 1000 == 0): print 'tid = ', tid #computation of rank of connectivity matrix to find out number of cluster for t in range(Ns): if ((t + 1) % 5 == 0): tid = t + 1 N0 = NAs N = NAs #print Cij[tid,:,:] #print "****************" for i in range(N0): if i < N: switch = 1 while (switch == 1): for j in range(i, N): switch = 0 c = np.bitwise_and(Cij[tid, :, i], Cij[tid, :, j]) if ((c**2).sum() != 0 and j != i): switch = 1 Cij[tid, :, i] = np.bitwise_or( Cij[tid, :, i], Cij[tid, :, j]) N1 = j N = N - 1 for k in range(N1 + 1, N + 1): Cij[tid, :, k - 1] = Cij[tid, :, k] break else: break Rank[tid / 5 - 1] = N clustsize[tid / 5 - 1] = float(NAs) / N for nc in range(N): if (tid == 5): print Cij[tid, :, nc].sum() if (Cij[tid, :, nc].sum() > 1): closedsticker[tid / 5 - 1] += Cij[tid, :, nc].sum() if (Cij[tid, :, nc].sum() < NAs): Pn[Cij[tid, :, nc].sum() - 1] += 1 else: Pn[NAs - 1] += 1 else: opensticker[tid / 5 - 1] += 1 Pn[0] += 1 #print Cij[tid,:,:] #print "#######################" ''' # mean square displacement msds = np.zeros((Ns, Nc)) for dtime in range(1, Ns): for cid in range(Nc): com = r_coms[:, cid] msd = ((com[dtime:, :] - com[:-dtime, :])**2).sum() msd /= Ns - dtime msds[dtime, cid] = msd # stress autocorrelation gt = np.zeros(Ns) gt[0] = (tauxys**2).sum() / (Nc * Ns) for dtime in range(1, Ns): gt[dtime] = (tauxys[dtime:] * tauxys[:-dtime]).sum() / (Nc * (Ns - dtime)) if (dtime % 2000 == 0): print 'dtime = ', dtime # local time correlation function for association dynamics Ft[0] = (Mij**2).sum()/(Nc*Ns*chains_ns[0]) print 'dtime = 0' for dtime in range(1, Ns): Ft[dtime] = (Mij[dtime:]*Mij[:-dtime]).sum()/(Nc*(Ns - dtime)*chains_ns[0]) if (dtime % 2000 == 0): print 'dtime = ', dtime ''' #data_out = np.column_stack( (traj.time, np.mean(q_sqs, axis = 1), np.mean(rg_sqs, axis = 1), np.mean(msds, axis = 1), gt, tauxys, Ft) ) ''' Rg2 = np.mean(rg_sqs, axis = 1) Rg2mean = np.mean(Rg2) #print Rg2mean with open('Rg2mean.txt','a+') as fRg2: fRg2.write("%lf\n" % Rg2mean) ''' if file_output: #np.savetxt("dynamic%s.txt" % filename, data_out) #np.savetxt("Rg2.txt", Rg2) #np.savetxt("Ft%s.txt" % filename, Ft) #np.savetxt("Gt%s.txt" % filename, gt) np.savetxt("clustnum%s.txt" % filename, Rank) np.savetxt("clustsize%s.txt" % filename, clustsize) np.savetxt("closedstick%s.txt" % filename, closedsticker) np.savetxt("openstick%s.txt" % filename, opensticker) np.savetxt("clustdistb%s.txt" % filename, Pn) else: #print Ft #print gt print Rank if SF: # structure factor from math import sin structure_kmin, structure_kmax, structure_nks = 0.1, 8, 100 ks = np.logspace(np.log10(structure_kmin), np.log10(structure_kmax), structure_nks) structure_factors = np.zeros((structure_nks, Ns, Nc)) Npair = ((Nbpc * Nbpc) - Nbpc) / 2 r_mag = np.zeros((Ns, Nc, Npair)) Ns = len(traj) for tid, conf in enumerate(traj.configuration): for cid, chain_indices in enumerate(chains_indices): positions = conf.array[chain_indices] n = len(positions) pairid = 0 for i, position1 in enumerate(positions): for j in range(i + 1, n): position2 = positions[j] rij = position2 - position1 r_mag[tid, cid, pairid] = ((rij * rij).sum())**.5 pairid = pairid + 1 ######################################################################### for kid, k in enumerate(ks): print 'kid', kid for tid in range(Ns): for cid in range(Nc): struct_sum = 0.0 pairid = 0 for i in range(Nbpc): for j in range(i + 1, Nbpc): struct_sum += sin(k * r_mag[tid, cid, pairid]) / ( k * r_mag[tid, cid, pairid]) pairid = pairid + 1 structure_factors[kid, tid, cid] = 1.0 + ( 2 * struct_sum / Nbpc ) #multiply by two because of symmetricity and addition of 1 is because of rij=0 terms print 'kid', kid structure_factors = np.mean(structure_factors, axis=2) data_structure_factor = np.column_stack( (ks, np.mean(structure_factors, axis=1), np.std(structure_factors, ddof=1, axis=1))) if file_output: np.savetxt("structure%s.txt" % filename, data_structure_factor) traj.close()
def inputFileRead(filename): """ read and process an input file """ keywords = [ 'trajectory', 'output_files', 'title', 'time_info', 'time_steps', 'frequency_points', 'q_vector_set', 'deuter', 'projection_vector', 'reference', 'rotation_coefficients', 'ft_window', 'groups', 'weights', 'atoms', 'units_length', 'units_frequency', 'log_file', 'groups_code', 'atoms_code', 'filter_window', 'results_file', 'atoms_pdb', 'differentiation', 'verbose', 'symbols', 'ar_order', 'ar_precision' ] newvars = {} file_text = Utility.readURL(filename) exec file_text in vars(sys.modules['__builtin__']), newvars input = Quidam() for key in keywords: if newvars.has_key(key): setattr(input, key, newvars[key]) else: setattr(input, key, None) import os print os.getcwd() print input.trajectory # # general settings # if input.trajectory: if len(input.trajectory) == 1: traj = Trajectory(None, input.trajectory[0], 'r') if traj.variables().count('quaternion') > 0: traj = qTrajectory(None, input.trajectory[0], 'r') elif len(input.trajectory) > 1: traj = TrajectorySet(None, input.trajectory) if not input.units_length: input.units_length = Units.nm if not input.units_frequency: input.units_frequency = Units.tera * Units.Hz types = getTypes(traj.universe) if input.q_vector_set is None: input.q_vector_set = (N.arange(0., 100., 2.), 1., 50) # default if input.time_info is None: input.time_info = (0, len(traj), 1) qVectors = qVectorGenerator(input.q_vector_set, traj) # # Substitute Hydrogen atoms with Deuter? # if input.deuter: collection = Collection() for i in input.deuter.keys(): for ia in input.deuter[i]: gj = getChemicalObjects({i: types[i]}, {i: ia}) collection.addObject(gj) h2d = collection.atomList() print 'number of Deuter atoms: ', len(h2d) # # Atom selection related keywords # atoms selected in a different way are stored together # and filtered at the end (if there're repetitions only # atoms which occur many times are stored and passed to # further calculations, else all atoms are passed) # if input.atoms: print 'processing atom selection:\n\t', input.atoms collection = [] for i in input.atoms.keys(): for ia in input.atoms[i]: typs = {} typs[i] = types[i] vlst = {} vlst[i] = ia gj = getChemicalObjects(typs, vlst) collection = collection + gj.atomList() input.atoms = collection print '\t...done\n\tstored ', len(input.atoms), ' atoms\n' if input.atoms_pdb: print 'processing atom selection from a PDB file\n\t(', print input.atoms_pdb, '):' atoms_add = parsePDBAtomSelection(input.atoms_pdb, traj) print '\t...done\n\tstored ', len(atoms_add.atomList()), ' atoms\n' if input.atoms: input.atoms = input.atoms + atoms_add.atomList() else: input.atoms = atoms_add.atomList() if input.atoms_code: print 'processing atom selection hardcoded in Python' # syntax: # def atoms_code(traj,nothing,dummy_a='gj') # # a python code here # return Collection(atom_list) # # atoms_code is a function object whose first argument is # a Trajectory object and which returns a Collection object. print '...done\n\tstored ', len(input.atoms_code(traj).atomList()), print ' atoms' if input.atoms: input.atoms = input.atoms + input.atoms_code(traj).atomList() else: input.atoms = input.atoms_code(traj).atomList() if not input.atoms: print ' No atom selection found, taking everything... just in case' input.atoms = traj.universe else: input.atoms = Collection(input.atoms) input.atoms = ghostBusters(input.atoms) print ' # atoms in selection: ', len(input.atoms.atomList()) # # Group selection # if input.groups: input.groups, input.reference = parseGroupSelection( types, input.groups, input.reference, verbose=input.verbose) if input.groups_code: # previous def (if any) overwritten # the result returned by groups_code should be consistent # with that one from misc.paresGroupSelection input.groups, input.reference = input.groups_code(traj) # # Another piece of general settings # if input.weights == 'mass': weightsList = MassList(traj.universe, input.atoms) elif input.weights == 'incoherent': if input.deuter: weightsList = BincohList(traj.universe, input.atoms, h2d) else: weightsList = BincohList(traj.universe, input.atoms) elif input.weights == 'coherent': if input.deuter: weightsList = BcohList(traj.universe, input.atoms, h2d) else: weightsList = BcohList(traj.universe, input.atoms) else: weightsList = None # input.trajectory = (traj, input.trajectory) input.trajectory = traj input.q_vector_set = qVectors input.weights = weightsList return input
class ReducedTrajectory(Analysis): """Sets up a Reduced Trajectory analysis. A Subclass of nMOLDYN.Analysis.Analysis. Constructor: ReducedTrajectory(|parameters| = None) Arguments: - |parameters| -- a dictionnary of the input parameters, or 'None' to set up the analysis without parameters. * trajectory -- a trajectory file name or an instance of MMTK.Trajectory.Trajectory class. * timeinfo -- a string of the form 'first:last:step' where 'first' is an integer specifying the first frame number to consider, 'last' is an integer specifying the last frame number to consider and 'step' is an integer specifying the step number between two frames. * subset -- a selection string specifying the atoms to consider for the analysis. * pyroserver -- a string specifying if Pyro will be used and how to run the analysis. * output -- the output NetCDF file name. Running modes: - To run the analysis do: a.runAnalysis() where a is the analysis object. - To estimate the analysis do: a.estimateAnalysis() where a is the analysis object. - To save the analysis to 'file' file name do: a.saveAnalysis(file) where a is the analysis object. """ def __init__(self, parameters = None, statusBar = None): """The constructor. @param parameters: if not None, a dictionnary storing the input parameters names and their corresponding values. @type parameters: dict @param statusBar: if not None, an instance of nMOLDYN.GUI.Widgets.StatusBar. Will attach a status bar to the selected analysis. @type statusBar: instance of nMOLDYN.GUI.Widgets.StatusBar """ # The inheritance. Analysis.__init__(self, parameters, statusBar) path = os.path.join(GVAR['nmoldyn_analysis'],'RT') exec file(path) in None, self.__dict__ def initialize(self): """Initializes the analysis (e.g. parses and checks input parameters, set some variables ...). """ # The input parameters are parsed. self.interpreteInputParameters() self.reducedTrajectory = {} def interpreteInputParameters(self): """Parse the input parameters for the analysis. """ # Parses the parameters that are common to different analysis. Analysis.interpreteInputParameters(self) self.buildTimeInfo() self.subset = self.selectAtoms(self.subsetDefinition) self.nSelectedAtoms = len(self.subset) orderedAtoms = sorted(self.trajectory.universe.atomList(), key = operator.attrgetter('index')) selectedAtoms = Collection([orderedAtoms[ind] for ind in self.subset]) # traj_new is the filtered trajectory self.outputFile = Trajectory(selectedAtoms, self.output, "w") # Create the snapshot generator self.snapshot = SnapshotGenerator(self.trajectory.universe, actions = [TrajectoryOutput(self.outputFile, ["all"], 0, None, 1)]) def calc(self, frameIndex, trajectory): """Calculates the atomic term. @param frameIndex: the index of the frame. @type frameIndex: integer. @param trajectory: the trajectory. @type trajectory: MMTK.Trajectory.Trajectory object """ trajectory.universe.setFromTrajectory(trajectory, frameIndex) idx = self.frameIndexes.index(frameIndex) self.snapshot(data = {'time': self.times[idx]}) return frameIndex, None def combine(self, frameIndex, x): """ @param frameIndex: the index of the frame. @type frameIndex: integer. """ return def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...) """ self.outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime() self.outputFile.close() self.trajectory.close() self.toPlot = None
from MMTK import * from MMTK.Proteins import Protein from MMTK.Trajectory import Trajectory, SnapshotGenerator, TrajectoryOutput from Scientific import N # Construct system: lysozyme in vaccuum universe = InfiniteUniverse() universe.protein = Protein('~/hao/proteins/PDB/193l.pdb') # Select residues to rotate # (this particular choice here is completely arbitrary) residues = [universe.protein[0][i] for i in [11, 35, 68, 110]] # Create trajectory trajectory = Trajectory(universe, "rotamers.nc", "w", "Sidechain rotations") # Create the snapshot generator snapshot = SnapshotGenerator( universe, actions=[TrajectoryOutput(trajectory, ["all"], 0, None, 1)]) # Perform sidechain rotations and write the configurations snapshot() for residue in residues: print(f"{residue}") chi = residue.chiAngle() for angle in N.arange(-N.pi, N.pi, N.pi / 10.): chi.setValue(angle) print(f"{angle}") snapshot()
class CASTEPConverter(Converter): """ Converts a Castep Trajectory into a MMTK trajectory file. """ type = 'castep' label = "CASTEP" category = ('Converters',) ancestor = None settings = collections.OrderedDict() settings['castep_file'] = ('input_file', {}) settings['output_file'] = ('output_files', {'formats':["netcdf"]}) def initialize(self): """ Initialize the input parameters and analysis self variables """ self._castepFile = MDFile(self.configuration["castep_file"]["filename"]) self.numberOfSteps = self._castepFile["n_frames"] self._universe = ParallelepipedicPeriodicUniverse() for symbol,number in self._castepFile["atoms"]: for i in range(number): self._universe.addObject(Atom(symbol, name="%s_%d" % (symbol,i))) self._universe.initializeVelocitiesToTemperature(0.) self._velocities = ParticleVector(self._universe) self._gradients = ParticleVector(self._universe) # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w') # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)]) def run_step(self, index): """Runs a single step of the job. @param index: the index of the step. @type index: int. @note: the argument index is the index of the loop note the index of the frame. """ nAtoms = self._castepFile["n_atoms"] timeStep, basisVectors, config = self._castepFile.read_step(index) self._universe.setShape(basisVectors) conf = Configuration(self._universe, config[0:nAtoms,:]) self._universe.setConfiguration(conf) self._universe.foldCoordinatesIntoBox() data = {"time" : timeStep} self._velocities.array = config[nAtoms:2*nAtoms,:] self._universe.setVelocities(self._velocities) self._gradients.array = config[2*nAtoms:3*nAtoms,:] data["gradients"] = self._gradients # Store a snapshot of the current configuration in the output trajectory. self._snapshot(data=data) return index, None def combine(self, index, x): """ @param index: the index of the step. @type index: int. @param x: @type x: any. """ pass def finalize(self): """ Finalize the job. """ self._castepFile.close() # Close the output trajectory. self._trajectory.close()
class UnfoldedTrajectory(IJob): """ """ type = 'ut' label = "Unfolded Trajectory" category = ('Trajectory',) ancestor = "mmtk_trajectory" settings = collections.OrderedDict() settings['trajectory'] = ('mmtk_trajectory',{}) settings['frames'] = ('frames', {'dependencies':{'trajectory':'trajectory'}}) settings['atom_selection'] = ('atom_selection', {'dependencies':{'trajectory':'trajectory'}}) settings['output_files'] = ('output_files', {'formats':["netcdf"]}) def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] atoms = sorted_atoms(self.configuration['trajectory']['instance'].universe) # The collection of atoms corresponding to the atoms selected for output. self._selectedAtoms = Collection([atoms[ind] for ind in self.configuration['atom_selection']['indexes']]) self._chemicalObjects = set([at.topLevelChemicalObject() for at in self._selectedAtoms]) # The output trajectory is opened for writing. self._outputTraj = Trajectory(self._selectedAtoms, self.configuration['output_files']['files'][0], "w") # The title for the trajectory is set. self._outputTraj.title = self.__class__.__name__ # Create the snapshot generator. self.snapshot = SnapshotGenerator(self.configuration['trajectory']['instance'].universe, actions = [TrajectoryOutput(self._outputTraj, "all", 0, None, 1)]) # This will store the configuration used as the reference for the following step. self._refCoords = None # Increase the recursion limit to avoid maximum recursion depth error when calling the contiguous_object recursive function self._oldRecursionLimit = sys.getrecursionlimit() sys.setrecursionlimit(100000) def run_step(self, index): """ Runs a single step of the job.\n :Parameters: #. index (int): The index of the step. :Returns: #. index (int): The index of the step. #. None """ # get the Frame index frameIndex = self.configuration['frames']['value'][index] universe = self.configuration['trajectory']['instance'].universe # The configuration corresponding to this index is set to the universe. universe.setFromTrajectory(self.configuration['trajectory']['instance'], frameIndex) # Case of the first frame. if self._refCoords is None: self._refCoords = universe._realToBoxPointArray(universe.configuration().array) for obj in universe.objectList(): if not isChemicalObject(obj): continue if isinstance(obj,Atom): continue if not obj in self._chemicalObjects: continue atoms = obj.atomList()[:] contiguous_configuration(atoms[0],atoms,self._refCoords) # Case of the other frames. else: currentCoords = universe._realToBoxPointArray(universe.configuration().array) diff = currentCoords - self._refCoords self._refCoords = numpy.where(numpy.abs(diff)>0.5,currentCoords-numpy.round(diff),currentCoords) corrCoords = universe._boxToRealPointArray(self._refCoords) universe.configuration().array = corrCoords # The times corresponding to the running index. t = self.configuration['frames']['time'][index] # Write the step. self.snapshot(data = {'time' : t}) return index, None def combine(self, index, x): """ Combines returned results of run_step.\n :Parameters: #. index (int): The index of the step.\n #. x (any): The returned result(s) of run_step """ pass def finalize(self): """ Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ # The input trajectory is closed. self.configuration['trajectory']['instance'].close() # The output trajectory is closed. self._outputTraj.close() sys.setrecursionlimit(self._oldRecursionLimit)
# for all atoms, and then the average over the C-alpha atoms is determined. # Note that calculating the fluctuations for only the C-alpha atoms is # more complicated and no faster. # # This example illustrates: # 1) Reading trajectory files # 2) Selecting parts of a system # 3) Calculating trajectory averages # from MMTK import * from MMTK.Trajectory import Trajectory from MMTK.Proteins import Protein # Open the trajectory, use every tenth step trajectory = Trajectory(None, 'lysozyme.nc')[::10] universe = trajectory.universe # Calculate the average conformation average = ParticleVector(universe) for step in trajectory: average += step['configuration'] average /= len(trajectory) # Calculate the fluctiations for all atoms fluctuations = ParticleScalar(universe) for step in trajectory: d = step['configuration'] - average fluctuations += d * d fluctuations /= len(trajectory)
def finalize(self): """Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ if self.architecture == 'monoprocessor': t = self.trajectory else: # Load the whole trajectory set. t = Trajectory(None, self.trajectoryFilename, 'r') orderedAtoms = sorted(t.universe.atomList(), key=operator.attrgetter('index')) groups = [ Collection([orderedAtoms[ind] for ind in g]) for g in self.group ] # 'freqencies' = 1D Numeric array. Frequencies at which the DOS was computed frequencies = N.arange(self.nFrames) / (2.0 * self.nFrames * self.dt) # The NetCDF output file is opened for writing. outputFile = NetCDFFile(self.output, 'w') outputFile.title = self.__class__.__name__ outputFile.jobinfo = self.information + '\nOutput file written on: %s\n\n' % asctime( ) # Dictionnary whose keys are of the form Gi where i is the group number # and the entries are the list of the index of the atoms building the group. comp = 1 for g in self.group: outputFile.jobinfo += 'Group %d: %s\n' % (comp, [index for index in g]) comp += 1 # Some dimensions are created. outputFile.createDimension('NFRAMES', self.nFrames) # Creation of the NetCDF output variables. # The time. TIMES = outputFile.createVariable('time', N.Float, ('NFRAMES', )) TIMES[:] = self.times[:] TIMES.units = 'ps' # The resolution function. RESOLUTIONFUNCTION = outputFile.createVariable('resolution_function', N.Float, ('NFRAMES', )) RESOLUTIONFUNCTION[:] = self.resolutionFunction[:] RESOLUTIONFUNCTION.units = 'unitless' # Creation of the NetCDF output variables. # The frequencies. FREQUENCIES = outputFile.createVariable('frequency', N.Float, ('NFRAMES', )) FREQUENCIES[:] = frequencies[:] FREQUENCIES.units = 'THz' OMEGAS = outputFile.createVariable('angular_frequency', N.Float, ('NFRAMES', )) OMEGAS[:] = 2.0 * N.pi * frequencies[:] OMEGAS.units = 'rad ps-1' avacfTotal = N.zeros((self.nFrames), typecode=N.Float) adosTotal = N.zeros((self.nFrames), typecode=N.Float) comp = 1 totalMass = 0.0 for g in groups: AVACF = outputFile.createVariable('avacf-group%s' % comp, N.Float, ('NFRAMES', )) AVACF[:] = self.AVACF[comp][:] AVACF.units = 'rad^2*ps^-2' N.add(avacfTotal, self.AVACF[comp], avacfTotal) ADOS = outputFile.createVariable('ados-group%s' % comp, N.Float, ('NFRAMES', )) ADOS[:] = self.ADOS[comp][:] ADOS.units = 'rad^2*ps^-1' N.add(adosTotal, g.mass() * self.ADOS[comp], adosTotal) comp += 1 totalMass += g.mass() adosTotal *= 0.5 * self.dt / (self.nGroups * totalMass) AVACF = outputFile.createVariable('avacf-total', N.Float, ('NFRAMES', )) AVACF[:] = avacfTotal AVACF.units = 'rad^2*ps^-2' ADOS = outputFile.createVariable('ados-total', N.Float, ('NFRAMES', )) ADOS[:] = adosTotal ADOS.units = 'rad^2*ps^-1' asciiVar = sorted(outputFile.variables.keys()) outputFile.close() self.toPlot = { 'netcdf': self.output, 'xVar': 'angular_frequency', 'yVar': 'ados-total' } # Create an ASCII version of the NetCDF output file. convertNetCDFToASCII(inputFile = self.output,\ outputFile = os.path.splitext(self.output)[0] + '.cdl',\ variables = asciiVar)
# are read by this example, you must run the example dcd_export.py. # from MMTK import * from MMTK.Proteins import Protein from MMTK.PDB import PDBConfiguration from MMTK.Trajectory import Trajectory, TrajectoryOutput from MMTK.DCD import DCDReader # Create the universe. universe = InfiniteUniverse() # Create all objects from the PDB file. The PDB file *must* match the # the DCD file (same atom order), and you *must* create all objects # defined in the PDB file, otherwise interpretation of the DCD file # is not possible. conf = PDBConfiguration('rotation.pdb') chain = conf.peptide_chains[0].createPeptideChain(c_terminus=1) universe.addObject(Protein([chain])) # Create the trajectory object for output. t = Trajectory(universe, "rotation_from_dcd.nc", "w", "Converted from DCD") # Create a DCD reader that reads all configurations. dcd_reader = DCDReader(universe, dcd_file = 'rotation.dcd', actions = [TrajectoryOutput(t, "all", 0, None, 1)]) # Run the reader... dcd_reader() # ... and close the output trajectory. t.close()
# Scale down the system in small steps while current_size > real_size: scale_factor = max(0.95, real_size / current_size) for object in world: object.translateTo(scale_factor * object.position()) current_size = scale_factor * current_size world.setSize(current_size) print(f'Current size: {current_size}') stdout.flush() minimizer(steps=100) integrator(steps=200) save(world, 'water' + ` n_molecules ` + '.intermediate.setup') # Final equilibration trajectory = Trajectory(world, 'water.nc', 'w', 'Final equilibration') integrator( steps=1000, actions=[ TrajectoryOutput(trajectory, ("time", "energy", "thermodynamic", "configuration"), 0, None, 10) ]) trajectory.close() # Save final system save(world, 'water' + ` n_molecules ` + '.setup')
class RefoldedMembraneTrajectory(IJob): """ Rebuild the trajectory of a membrane such as the lipid compising the upper leaflet are actually on the up side of the simulation box and conversely the lipids that composes the lower leaflet are actually on the down side of the leaflet. The normal to the membrane is assumed to be parallel to z axis. """ type = 'rmt' label = "Refolded Membrane Trajectory" category = ('Macromolecules','Lipids') ancestor = "mmtk_trajectory" settings = collections.OrderedDict() settings['trajectory'] = ('mmtk_trajectory',{}) settings['frames'] = ('frames', {'dependencies':{'trajectory':'trajectory'}}) settings['axis'] = ('single_choice', {'label':"membrane axis", 'choices':['a','b','c'], 'default':'c'}) settings['upper_leaflet'] = ('string', {'label':"name of the lipid of the upper leaflet", 'default':"dmpcu"}) settings['lower_leaflet'] = ('string', {'label':"name of the lipid of the lower leaflet", 'default':"dmpcl"}) settings['output_files'] = ('output_files', {'formats':["netcdf"]}) def initialize(self): """ Initialize the input parameters and analysis self variables """ self.numberOfSteps = self.configuration['frames']['number'] self._universe = self.configuration['trajectory']['instance'].universe self._upperLeaflet = Collection([obj for obj in self._universe.objectList() if obj.name == self.configuration["upper_leaflet"]["value"]]) self._lowerLeaflet = Collection([obj for obj in self._universe.objectList() if obj.name == self.configuration["lower_leaflet"]["value"]]) self._membrane = Collection(self._upperLeaflet,self._lowerLeaflet) self._upperLeafletIndexes = [at.index for at in self._upperLeaflet.atomList()] self._lowerLeafletIndexes = [at.index for at in self._lowerLeaflet.atomList()] self._membraneIndexes = [at.index for at in self._membrane.atomList()] # The output trajectory is opened for writing. self._rmt = Trajectory(self._membrane, self.configuration['output_files']['files'][0], "w") # The title for the trajectory is set. self._rmt.title = self.__class__.__name__ # Create the snapshot generator. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._rmt, "all", 0, None, 1)]) self._axis = self.configuration["axis"]["index"] def run_step(self, index): """ Runs a single step of the job.\n :Parameters: #. index (int): The index of the step. :Returns: #. index (int): The index of the step. #. None """ # get the Frame index frameIndex = self.configuration['frames']['value'][index] # The configuration corresponding to this index is set to the universe. self._universe.setFromTrajectory(self.configuration['trajectory']['instance'], frameIndex) conf = self._universe.contiguousObjectConfiguration() boxCoords = self._universe._realToBoxPointArray(conf.array) # Compute the center of gravity of the whole lower leaflet. lowerLeafletCenter = center(boxCoords[self._lowerLeafletIndexes,:])[self._axis] for lip in self._upperLeaflet: idxs = [at.index for at in lip.atomList()] currCenter = center(boxCoords[idxs,:])[self._axis] if currCenter < lowerLeafletCenter: boxCoords[idxs,2] += 1.0 upperLeafletCenter = center(boxCoords[self._upperLeafletIndexes,:])[self._axis] for lip in self._lowerLeaflet: idxs = [at.index for at in lip.atomList()] currCenter = center(boxCoords[idxs,:])[self._axis] if currCenter > upperLeafletCenter: boxCoords[idxs,2] -= 1.0 conf = Configuration(self._universe, self._universe._boxToRealPointArray(boxCoords)) self._universe.setConfiguration(conf) # The times corresponding to the running index. t = self.configuration['frames']['time'][index] # A snapshot of the universe is written to the output trajectory. self._snapshot(data = {'time': t}) return index, None def combine(self, index, x): """ Combines returned results of run_step.\n :Parameters: #. index (int): The index of the step.\n #. x (any): The returned result(s) of run_step """ pass def finalize(self): """ Finalizes the calculations (e.g. averaging the total term, output files creations ...). """ # The input trajectory is closed. self.configuration['trajectory']['instance'].close() # The output trajectory is closed. self._rmt.close()
if opt in ("-e", "--end"): end = int(arg) if opt in ("-s", "--step"): step = int(arg) if opt in ("-h", "--help"): usage() sys.exit(2) if opt in ("-f", "--filename"): trajectoryPath = arg if opt in ("-t", "--temperature"): temperature = float(arg) print "Using file %s as input..."%trajectoryPath trajectory = Trajectory(None, trajectoryPath, 'r') if end == -1: end = len(trajectory.time) timeinfo = '%d:%d:%d'%(begin, end, step) print 'The complete trajectory size is', len(trajectory.time), ' elements' print "\nAnalysing trajectory from position %d to postion %d with step %d:\n"%(begin,end,step) print 'Temperature = ',temperature # print (trajectory.time[0], trajectory.time[-1], trajectory.time[1] - trajectory.time[0]) parameters = { 'trajectory': trajectory, 'timeinfo' : timeinfo, 'differentiation': 0,
from MMTK.NormalModes import VibrationalModes from MMTK.Trajectory import Trajectory, TrajectoryOutput, \ RestartTrajectoryOutput, StandardLogOutput, \ trajectoryInfo from sys import argv, exit from Scientific.Statistics import mean, standardDeviation #from nMOLDYN.Mathematics.Analysis import correlation from Scientific import N from Scientific.Geometry import Vector from numpy import * from numpy.linalg import * traj = argv[1] nCO2 = 1 label = "norotskip-" + argv[2] trajectory = Trajectory(None, traj) universe = trajectory.universe natoms = universe.numberOfAtoms() np = universe.numberOfPoints() P = np / natoms stepcount = 0 rval = zeros(len(trajectory) * P, float) cval = zeros(len(trajectory) * P, float) #vfile=open("final-pot-"+str(P)+"-"+label,"w") #rfile=open("hist-r-"+str(P)+"-"+label,"w") #ctfile=open("hist-cost-"+str(P)+"-"+label,"w") rfile = open("data-r-" + str(P) + "-" + label, "w")
# This program reads a trajecory for a solvated protein and # extracts just the protein data, which it stores in a new # trajectory. This trajectory is smaller and easier to analyze # or visualize. # # Note: You cannot run this example without having a suitable # trajectory file, whose name you should put in place of # "full_trajectory.nc" below. # from MMTK import * from MMTK.Trajectory import Trajectory, TrajectoryOutput, SnapshotGenerator # Open the input trajectory. full = Trajectory(None, 'full_trajectory.nc') # Collect the items you want to keep. Here we keep everything but # water molecules. universe = full.universe keep = Collection() for object in universe: try: is_water = object.type.name == 'water' except AttributeError: is_water = 0 if not is_water: keep.addObject(object) # Open the new trajectory for just the interesting objects. subset = Trajectory(keep, 'subset_trajectory.nc', 'w')
class DL_POLYConverter(Converter): """ Converts a DL_POLY trajectory to a MMTK trajectory. """ type = 'dl_poly' label = "DL_POLY" category = ('Converters',) ancestor = None settings = collections.OrderedDict() settings['field_file'] = ('input_file',{'wildcard':"FIELD files|FIELD*|All files|*"}) settings['history_file'] = ('input_file',{'wildcard':"HISTORY files|HISTORY*|All files|*"}) settings['atom_aliases'] = ('python_object',{'default':{}}) settings['version'] = ('single_choice', {'choices':_HISTORY_FORMAT.keys(), 'default':'2'}) settings['output_file'] = ('output_files', {'formats':["netcdf"]}) def initialize(self): ''' Initialize the job. ''' self._atomicAliases = self.configuration["atom_aliases"]["value"] self._fieldFile = FieldFile(self.configuration["field_file"]["filename"], aliases=self._atomicAliases) self._historyFile = HistoryFile(self.configuration["history_file"]["filename"], self.configuration["version"]["value"]) # The number of steps of the analysis. self.numberOfSteps = self._historyFile['n_frames'] if self._historyFile["imcon"] == 0: self._universe = InfiniteUniverse() else: self._universe = ParallelepipedicPeriodicUniverse() self._fieldFile.build_mmtk_contents(self._universe) self._velocities = None self._forces = None if self._historyFile["keytrj"] == 1: self._universe.initializeVelocitiesToTemperature(0.) self._velocities = ParticleVector(self._universe) elif self._historyFile["keytrj"] == 2: self._universe.initializeVelocitiesToTemperature(0.) self._velocities = ParticleVector(self._universe) self._forces = ParticleVector(self._universe) # A MMTK trajectory is opened for writing. self._trajectory = Trajectory(self._universe, self.configuration['output_file']['files'][0], mode='w', comment=self._fieldFile["title"]) # A frame generator is created. self._snapshot = SnapshotGenerator(self._universe, actions = [TrajectoryOutput(self._trajectory, ["all"], 0, None, 1)]) def run_step(self, index): """Runs a single step of the job. @param index: the index of the step. @type index: int. @note: the argument index is the index of the loop note the index of the frame. """ # The x, y and z values of the current frame. time, cell, config = self._historyFile.read_step(index) # If the universe is periodic set its shape with the current dimensions of the unit cell. if self._universe.is_periodic: self._universe.setShape(cell) self._universe.setConfiguration(Configuration(self._universe, config[:,0:3])) self._universe.foldCoordinatesIntoBox() data = {"time" : time} if self._velocities is not None: self._velocities.array = config[:,3:6] self._universe.setVelocities(self._velocities) if self._forces is not None: self._forces.array = config[:,6:9] data["forces"] = self._forces # Store a snapshot of the current configuration in the output trajectory. self._snapshot(data=data) return index, None def combine(self, index, x): """ @param index: the index of the step. @type index: int. @param x: @type x: any. """ pass def finalize(self): """ Finalize the job. """ self._historyFile.close() # Close the output trajectory. self._trajectory.close()
# Equilibration integrator( steps=10000, actions=[ # Scale velocities every 50 steps. VelocityScaler(temperature, 0.1 * temperature, 0, None, 50), # Remove global translation every 50 steps. TranslationRemover(0, None, 50), # Remove global rotation every 50 steps. RotationRemover(0, None, 50), # Log output to screen every 500 steps. StandardLogOutput(500) ]) # "Production" run trajectory = Trajectory(universe, "langevin.nc", "w", "Langevin test") integrator( steps=10000, actions=[ # Remove global translation every 50 steps. TranslationRemover(0, None, 50), # Remove global rotation every 50 steps. RotationRemover(0, None, 50), # Write every fifth step to the trajectory file. TrajectoryOutput(trajectory, ("time", "energy", "thermodynamic", "configuration"), 0, None, 10), # Log output to screen every 100 steps. StandardLogOutput(100) ]) trajectory.close()
# "Manual" creation of a trajectory using the snapshot generator. # from MMTK import * from MMTK.Proteins import Protein from MMTK.Trajectory import Trajectory, SnapshotGenerator, TrajectoryOutput # Construct system universe = InfiniteUniverse() universe.protein = Protein('bala1') # Transformation to be applied between the steps transformation = Rotation(Vector(0.,0.,1.), 1.*Units.deg) # Create trajectory trajectory = Trajectory(universe, "rotation.nc", "w", "A rotating molecule") # Create the snapshot generator snapshot = SnapshotGenerator(universe, actions = [TrajectoryOutput(trajectory, ["all"], 0, None, 1)]) # Perform rotations and write the configurations snapshot() for i in range(20): universe.protein.applyTransformation(transformation) snapshot() # Close trajectory trajectory.close()
class Mmtk(MolDynamics): """MMTK functionality usable in DANSE. This class maps the API to MMTK commands and executes them.""" class Inventory(MolDynamics.Inventory): import pyre.inventory as inv integrator = inv.str('integrator', default = 'velocity-verlet') integrator.meta['tip'] = 'type of integrator' runType = inv.str('runType', default = 'md') runType.validator = inv.choice(['md', 'restart md']) runType.meta['tip'] = 'type of run' forcefield = inv.facility('forcefield', default = 'amber') forcefield.meta['known_plugins']=['amber', 'lennardJones'] forcefield.meta['tip'] = 'type of forcefield' barostatParameter = inv.float('Barostat Parameter', default = 0.005) barostatParameter.meta['tip'] = '''barostat parameter to keep fluctuations relatively small''' ensemble = inv.str('Thermodynamic Ensemble', default = 'nve') ensemble.validator = inv.choice(["nve", "nvt", "npt"]) ensemble.meta['tip'] = 'thermodynamic ensemble (nve, nvt, npt, ...)' equilibrationTime = inv.float('Equilibration Time (ps)', default = 0.0) equilibrationTime.meta['tip'] = 'equilibration time of the simulation (ps)' productionTime = inv.float('Production Time (ps)', default = 5.0) productionTime.meta['tip'] = 'production time of the simulation' sampleFrequency = inv.float('Properties Calculation Frequency (fs)', default = 5.0) sampleFrequency.meta['tip'] = '''frequency at which sampled properties are written to trajectory and log file''' thermostatParameter = inv.float('Thermostat Parameter', default = 0.005) thermostatParameter.meta['tip'] = '''thermostat parameter to keep fluctuations relatively small''' timeStep = inv.float('Time step (fs)', default = 0.5) timeStep.meta['tip'] = 'integration time step (ps)' trajectoryFilename = inv.str('Trajectory Filename', default='molDynamics') trajectoryFilename.meta['tip'] = 'name of trajectory file(s)' restartFilename = inv.str('Restart Filename', default = 'molDynamics.res') restartFilename.meta['tip'] = '''restart file for resuming an md run or optimization''' dumpFrequency = inv.float('Dump Frequency (ps)', default = 0.0) dumpFrequency.meta['tip'] = '''frequency at which a restart file is written''' trajectoryType = inv.str('Trajectory Type', default='xyz') trajectoryType.meta['tip'] = 'type of trajectory output' trajectoryType.validator = inv.choice(['xyz', 'history', 'xyz and history']) def __init__(self, name='mmtk'): MolDynamics.__init__(self, name, 'engine') #self._setDefaults() self.mmtkUniverse = None # def _setDefaults(self): # '''set defaults specific to mmtk''' # self.inventory.trajectoryFilename = 'molDynamics.nc' # self.inventory.restartFilename = 'restart.nc' # self.inventory.sampleFrequency = self.inventory.timeStep*Units.fs # self.inventory.dumpFrequency = self.inventory.timeStep*Units.fs def _norm(self,vec): """gives the Euclidean _norm of a list""" temp=sum([el**2. for el in vec]) return math.sqrt(temp) def _ind(self,list): """gives the indices of the list to iterate over""" return range(len(list)) def _dot(self,v1,v2): """returns the _dot product of v1 and v2""" return sum([v1[i]*v2[i] for i in self._ind(v1)]) def _vecsToParams(self,vecs): """takes lattice vectors in cartesian coordinates with origin at {0,0,0} and returns lattice parameters""" conv=math.pi/180 [a,b,c]=vecs ma=math.sqrt(self._dot(a,a)) mb=math.sqrt(self._dot(b,b)) mc=math.sqrt(self._dot(c,c)) al=1/conv*math.acos(self._dot(b,c)/mb/mc) be=1/conv*math.acos(self._dot(a,c)/ma/mc) ga=1/conv*math.acos(self._dot(a,b)/ma/mb) return [ma, mb, mc, al, be, ga] def appEqual(self,v1,v2): '''equal to within a certain numerical accuracy''' if v1-v2<10**-6: return True else: return False def _setForcefield(self): '''This function sets the forcefield.''' self.ff=self.inventory.forcefield.getForcefield() def _setInitialConditions(self): '''map MolDynamics unit cell stuff to MMTK's. Eventually much of this will be taken by the crystal class''' atoms = self.inventory.sample.getAtomsAsStrings() uc = self.inventory.sample.getCellVectors() if uc==None: self.mmtkUniverse = MMTK.InfiniteUniverse(self.ff) else: #ucList=uc.tolist() (a,b,c,al,be,ga)=self._vecsToParams(uc) if self.appEqual(al, 90.0) and self.appEqual(be, 90.0) and self.appEqual(ga, 90.0): if a==b and b==c: self.mmtkUniverse = MMTK.CubicPeriodicUniverse(a*Units.Ang, self.ff) else: self.mmtkUniverse = MMTK.OrthorhombicPeriodicUniverse( (a*Units.Ang, b*Units.Ang, c*Units.Ang), self.ff) else: uc = self.inventory.sample.unitCell self.mmtkUniverse = MMTK.ParallelepipedicPeriodicUniverse( ((uc[0][0]*Units.Ang, uc[0][1]*Units.Ang, uc[0][2]*Units.Ang), (uc[1][0]*Units.Ang, uc[1][1]*Units.Ang, uc[1][2]*Units.Ang), (uc[2][0]*Units.Ang, uc[2][1]*Units.Ang, uc[2][2]*Units.Ang)), self.ff) #add objects to mmtkUniverse for atom in atoms: species, x, y, z = atom.split() self.mmtkUniverse.addObject(MMTK.Atom(species, position = \ MMTK.Vector(float(x)*Units.Ang, float(y)*Units.Ang, float(z)*Units.Ang))) # elif self.inventory.sample.has_attribute('molecule'): # pass def createTrajectoryAndIntegrator(self): '''create trajectory and integrator''' #initialize velocities--this has to happen after adding atoms self.mmtkUniverse.initializeVelocitiesToTemperature(self.inventory.sample.i.temperature) # Create trajectory and integrator. self.mmtkTrajectory = Trajectory(self.mmtkUniverse, self.inventory.trajectoryFilename, "w") self.mmtkIntegrator = VelocityVerletIntegrator(self.mmtkUniverse, delta_t=self.inventory.timeStep*Units.fs) # Periodical actions for equilibration output. self.equilibration_actions = [TranslationRemover(0, None, 100), RotationRemover(0, None, 100), LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None) ] # Periodical actions for trajectory output and text log output. self.output_actions = [TrajectoryOutput(self.mmtkTrajectory, ('configuration', 'energy', 'thermodynamic', 'time', 'auxiliary'), 0, None, 20), #TODO: Fixme so the user can specify when trajectory and sample frequency happens #this last option makes it so none of the equilibration steps are output, consistent with Gulp LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None, 20) #this last 0 makes it so all equilibration steps are output, consistent with Gulp ] def createRestartTrajectoryAndIntegrator(self): '''initialize system from previous trajectory''' # Initialize system state from the restart trajectory self.mmtkUniverse.setFromTrajectory(Trajectory(self.mmtkUniverse, self.inventory.restartFilename)) # Create trajectory and integrator. self.mmtkTrajectory = Trajectory(self.mmtkUniverse, self.inventory.trajectoryFilename, "a") self.mmtkIntegrator = VelocityVerletIntegrator(self.mmtkUniverse, delta_t=self.inventory.timestep*Units.fs) # Periodical actions for equilibration output. self.equilibration_actions = [TranslationRemover(0, None, 100), RotationRemover(0, None, 100), LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None) ] # Periodical actions for trajectory output and text log output. self.output_actions = [TranslationRemover(0, None, 100), TrajectoryOutput(self.mmtkTrajectory, ('configuration', 'energy', 'thermodynamic', 'time', 'auxiliary'), 0, None, self.equilibrationSteps()), #this last option makes it so none of the equilibration steps are output, consistent with Gulp # Write restart data every time step. RestartTrajectoryOutput(self.inventory.restartFilename, 1), LogOutput(self.inventory.logFilename, ('time', 'energy'), 0, None) ] def _integrateNVE(self): # Do some equilibration steps self.mmtkIntegrator(steps = self.equilibrationSteps(), actions = self.equilibration_actions) # Do some "production" steps. self.mmtkIntegrator(steps = self.productionSteps(), actions = self.output_actions) # Close the trajectory. self.mmtkTrajectory.close() def _integrateNVT(self): # Add thermostat self.mmtkUniverse.thermostat = NoseThermostat(self.inventory.sample.i.temperature) # Do some equilibration steps and rescaling velocities. self.mmtkIntegrator(steps = self.equilibrationSteps(), actions = [VelocityScaler(self.inventory.sample.i.temperature, 0.1*self.inventory.sample.i.temperature, 0, None, 100)] + self.equilibration_actions) # Do some "production" steps. self.mmtkIntegrator(steps = self.productionSteps(), actions = self.output_actions) # Close the trajectory. self.mmtkTrajectory.close() def _integrateNPT(self): # Add thermostat and barostat. self.mmtkUniverse.thermostat = NoseThermostat(self.inventory.sample.i.temperature) self.mmtkUniverse.barostat = AndersenBarostat(self.inventory.sample.i.pressure) # Do some equilibration steps, rescaling velocities and resetting the # barostat in regular intervals. self.mmtkIntegrator(steps = self.equilibrationSteps(), actions = [VelocityScaler(self.inventory.sample.i.temperature, 0.1*self.inventory.sample.i.temperature, 0, None, 100), BarostatReset(100)] + self.equilibration_actions) # Do some "production" steps. self.mmtkIntegrator(steps = self.productionSteps(), actions = self.output_actions) # Close the trajectory. self.mmtkTrajectory.close() def integrate(self): '''integrates an atomic system forward in time and produces a trajectory''' self.printWarnings() self._setForcefield() self._setInitialConditions() self.createTrajectoryAndIntegrator() if self.inventory.ensemble=='nvt': self._integrateNVT() elif self.inventory.ensemble=='npt': self._integrateNPT() elif self.inventory.ensemble=='nve': self._integrateNVE() else: raise Exception, 'your ensemble is not suppported by mmtk' return def restartIntegrate(self): '''performs a restart of an md run''' self.printWarnings() self._setForcefield() self._setInitialConditions() self.createRestartTrajectoryAndIntegrator() if self.inventory.ensemble=='nvt': self._integrateNVT() elif self.inventory.ensemble=='npt': self._integrateNPT() elif self.inventory.ensemble=='nve': self._integrateNVE() else: raise Exception, 'your ensemble is not suppported by mmtk' def execute(self): '''writes out the files, starts the executable, and parses the output files''' self.printWarnings() if self.inventory.runType=='md': self.integrate() elif self.inventory.runType=='restart md': self.restartIntegrate() def printWarnings(self): if self.inventory.sampleFrequency > self.inventory.timeStep: print '''Mmtk does not allow a different sample frequency than every timestep. Write frequency will be set to every timestep.''' if self.inventory.dumpFrequency > self.inventory.timeStep: print '''Mmtk does not allow a different dump frequency than every timestep. Dump frequency will be set to every timestep.''' def equilibrationSteps(self): '''Number of time steps to reach equilibration''' if self.inventory.timeStep==0: raise Exception, 'please set the time step to a nonzero value' else: val=int(self.inventory.equilibrationTime/self.inventory.timeStep) return val def productionSteps(self): '''Number of time steps to finish production''' if self.inventory.timeStep==0: raise Exception, 'please set the time step to a nonzero value' else: return int(self.inventory.productionTime/self.inventory.timeStep)