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 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 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 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 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
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 doVelocityVerletSteps(delta_t = 1.*Units.fs, nsteps = 5000) 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') 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
def fit(pdb_file, map_file, energy_cutoff, label, trajectory_freq): dmap = load(map_file) universe = InfiniteUniverse(CalphaForceField(2.5)) universe.protein = Protein(pdb_file, model='calpha') set_distances(universe.protein) modes = calc_modes(universe, 3 * universe.numberOfAtoms()) for nmodes in range(6, len(modes)): if modes[nmodes].frequency > energy_cutoff * modes[6].frequency: break if trajectory_freq > 0: trajectory_filename = 'fit_%s_m%d.nc' % (label, nmodes) print "Fit trajectory:", trajectory_filename trajectory = Trajectory( universe, trajectory_filename, 'w', 'Density fit %s using %d modes' % (label, nmodes)) actions = [ TrajectoryOutput(trajectory, ["configuration", "fit_error"], 0, None, 1) ] snapshot = SnapshotGenerator(universe, actions=actions) snapshot.available_data.append('fit_error') amplitude = 0.1 i = 0 fit = [] windex = 0 protocol_filename = 'fit_%s_m%d_fiterror.txt' % (label, nmodes) print "Fit error protocol file:", protocol_filename protocol = file(protocol_filename, 'w') nmc = 2 * nmodes modes = calc_modes(universe, nmc) windows = N.arange(10.) * modes[nmodes].frequency / 10. while 1: f, gradient = dmap.fitWithGradient(universe) fit.append(f) print >> protocol, i, fit[-1] protocol.flush() if len(fit) > 1 and fit[-1] > fit[-2]: amplitude /= 2. random_width = gradient.norm()*(random/100.) \ / N.sqrt(universe.numberOfAtoms()) random_vector = randomParticleVector(universe, random_width) gradient = gradient + random_vector displacement = ParticleVector(universe) for n in range(nmodes): m = modes[n] if n < 6: weight = 5. * weight_function(modes[6], windows[windex]) else: weight = weight_function(m, windows[windex]) displacement = displacement + \ weight*m.massWeightedDotProduct(gradient)*m displacement = displacement * amplitude / displacement.norm() universe.setConfiguration(universe.configuration() + displacement) fix_structure(universe.protein) if trajectory_freq > 0 and i % trajectory_freq == 0: snapshot(data={'fit_error': fit[-1]}) i = i + 1 if i % 20 == 0: modes = calc_modes(universe, nmc) if i % 10 == 0 and i > 50: convergence = (fit[-1] - fit[-11]) / (fit[30] - fit[20]) if convergence < 0.05: break if convergence < 0.2: windex = min(windex + 1, len(windows) - 1) if convergence < 0.1: amplitude = 0.5 * amplitude protocol.close() if trajectory_freq > 0: trajectory.close() pdb_out = 'fit_%s_m%d.pdb' % (label, nmodes) print "Writing final structure to", pdb_out universe.writeToFile(pdb_out)
chain = protein[i] chain_calpha = protein_calpha[i] for j in range(len(chain)): r = conf[chain[j].peptide.C_alpha] chain_calpha[j].peptide.C_alpha.setPosition(r) chain_calpha[j].peptide.C_alpha.index = index map.append(chain[j].peptide.C_alpha.index) index = index + 1 universe_calpha.configuration() # Open the new trajectory for just the interesting objects. trajectory_calpha = Trajectory(universe_calpha, 'calpha_trajectory.nc', 'w') # Make a snapshot generator for saving. snapshot = SnapshotGenerator(universe_calpha, actions = [TrajectoryOutput(trajectory_calpha, None, 0, None, 1)]) # Loop over all steps, eliminate rigid-body motion with reference to # the initial configuration, and save the configurations to the new # trajectory. first = 1 for step in trajectory: conf = universe.contiguousObjectConfiguration(proteins, step['configuration']) conf_calpha = Configuration(universe_calpha, N.take(conf.array, map), None) universe_calpha.setConfiguration(conf_calpha) if first: initial_conf_calpha = copy(conf_calpha) first = 0
def shrinkUniverse(universe, temperature=300.*Units.K, trajectory=None, scale_factor=0.95): """ Shrinks the universe, which must have been scaled up by :class:`~MMTK.Solvation.addSolvent`, back to its original size. The compression is performed in small steps, in between which some energy minimization and molecular dynamics steps are executed. The molecular dynamics is run at the given temperature, and an optional trajectory can be specified in which intermediate configurations are stored. :param universe: a finite universe :type universe: :class:`~MMTK.Universe.Universe` :param temperature: the temperature at which the Molecular Dynamics steps are run :type temperature: float :param trajectory: the trajectory in which the progress of the shrinking procedure is stored, or a filename :type trajectory: :class:`~MMTK.Trajectory.Trajectory` or str :param scale_factor: the factor by which the universe is scaled at each reduction step :type scale_factor: float """ # Set velocities and initialize trajectory output universe.initializeVelocitiesToTemperature(temperature) if trajectory is not None: if isinstance(trajectory, basestring): trajectory = Trajectory(universe, trajectory, "w", "solvation protocol") close_trajectory = True else: close_trajectory = False actions = [TrajectoryOutput(trajectory, ["configuration"], 0, None, 1)] snapshot = SnapshotGenerator(universe, actions=actions) snapshot() # Do some minimization and equilibration minimizer = SteepestDescentMinimizer(universe, step_size = 0.05*Units.Ang) actions = [VelocityScaler(temperature, 0.01*temperature, 0, None, 1), TranslationRemover(0, None, 20)] integrator = VelocityVerletIntegrator(universe, delta_t = 0.5*Units.fs, actions = actions) for i in range(5): minimizer(steps = 40) integrator(steps = 200) # Scale down the system in small steps i = 0 while universe.scale_factor > 1.: if trajectory is not None and i % 1 == 0: snapshot() i = i + 1 step_factor = max(scale_factor, 1./universe.scale_factor) for object in universe: object.translateTo(step_factor*object.position()) universe.scaleSize(step_factor) universe.scale_factor = universe.scale_factor*step_factor for i in range(3): minimizer(steps = 10) integrator(steps = 50) del universe.scale_factor if trajectory is not None: snapshot() if close_trajectory: trajectory.close()
# 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') # Make a snapshot generator for saving. snapshot = SnapshotGenerator( universe, actions=[TrajectoryOutput(subset, None, 0, None, 1)]) # Loop over all steps and save them to the new trajectory. for configuration in full.configuration: universe.setConfiguration(configuration) snapshot() # Close both trajectories. full.close() subset.close()