本文整理汇总了Python中MMTK.Trajectory.Trajectory.close方法的典型用法代码示例。如果您正苦于以下问题:Python Trajectory.close方法的具体用法?Python Trajectory.close怎么用?Python Trajectory.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类MMTK.Trajectory.Trajectory
的用法示例。
在下文中一共展示了Trajectory.close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_snapshot
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
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()
示例2: CenterOfMassesTrajectory
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
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()
示例3: LAMMPSConverter
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
#.........这里部分代码省略.........
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
示例4: DCDConverter
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
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()
示例5: BoxCenteredTrajectory
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
class BoxCenteredTrajectory(IJob):
"""
Build a new trajectory by translating a given atom selection on the center of the simulation box.
"""
type = 'btt'
label = "Box Translated 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 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 run_step(self, index):
"""
Runs a single step of the analysis.
: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)
# Get a contiguous copy of the current configuration.
conf = self._universe.contiguousObjectConfiguration()
# For the first step, the box coordinates are just set to the box coordinates of the current configuration.
if self._boxCoords is None:
self._boxCoords = self._universe._realToBoxPointArray(conf.array)
# For the other step, the box coordinates are set equal to the configuration corrected from box jumps.
else:
currBoxCoords = self._universe._realToBoxPointArray(conf.array)
diff = currBoxCoords - self._boxCoords
self._boxCoords = currBoxCoords - numpy.round(diff)
# A new configuration is made from the box coordinates set back to real coordinates.
conf = Configuration(self._universe, self._universe._boxToRealPointArray(self._boxCoords))
# The universe is translated by the center of the selected atoms.
c = center(conf.array[self.configuration['atom_selection']['indexes'],:])
conf.array -= c
self._universe.setConfiguration(conf)
# The times corresponding to the running index.
t = self.configuration['frames']['time'][index]
# The current configuration is written to the output trajectory.
self._snapshot(data = {'time': t})
return index, None
def combine(self, index, x):
"""
Update the output each time a step is performed
:Parameters:
#. index (int): The index of the step.
#. x (any): The returned result(s) of run_step
"""
pass
def finalize(self):
"""
Finalize the analysis (close trajectory, write output data ...)
#.........这里部分代码省略.........
示例6: RefoldedMembraneTrajectory
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
#.........这里部分代码省略.........
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()
示例7: UnfoldedTrajectory
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
#.........这里部分代码省略.........
# 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)
示例8: Configuration
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
# 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
else:
tr, rms = universe_calpha.findTransformation(initial_conf_calpha)
universe_calpha.applyTransformation(tr)
del step['step']
del step['configuration']
try:
del step['box_size']
except KeyError: pass
try:
del step['velocities']
except KeyError: pass
snapshot(data = step)
# Close both trajectories.
trajectory.close()
trajectory_calpha.close()
示例9: GlobalMotionFilteredTrajectory
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
#.........这里部分代码省略.........
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 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)
if self.configuration['contiguous']["value"]:
# The configuration is made contiguous.
conf = self.configuration['trajectory']['instance'].universe.contiguousObjectConfiguration()
# And set to the universe.
self.configuration['trajectory']['instance'].universe.setConfiguration(conf)
# Case of the first frame.
if frameIndex == self.configuration['frames']['first']:
# A a linear transformation that shifts the center of mass of the reference atoms to the coordinate origin
# and makes its principal axes of inertia parallel to the three coordinate axes is computed.
tr = self._referenceAtoms.normalizingTransformation()
# The first rms is set to zero by construction.
rms = 0.0
# Case of the other frames.
else:
# The linear transformation that minimizes the RMS distance between the current configuration and the previous
# one is applied to the reference atoms.
tr, rms = self._referenceAtoms.findTransformation(self._referenceConfig)
# And applied to the selected atoms for output.
self.configuration['trajectory']['instance'].universe.applyTransformation(tr)
# The current configuration becomes now the reference configuration for the next step.
self._referenceConfig = self.configuration['trajectory']['instance'].universe.copyConfiguration()
velocities = self.configuration['trajectory']['instance'].universe.velocities()
if velocities is not None:
rot = tr.rotation()
for atom in self._selectedAtoms:
velocities[atom] = rot(velocities[atom])
self.configuration['trajectory']['instance'].universe.setVelocities(velocities)
# A MMTK.InfiniteUniverse.cellParameters is set to None.
self.configuration['trajectory']['instance'].universe.cellParameters = lambda: None
# The times corresponding to the running index.
t = self.configuration['frames']['time'][index]
# Write the step.
self.snapshot(data = {'time' : t, 'rms' : rms})
# A MMTK.PeriodicUniverse.cellParameters is et back to the universe.
self.configuration['trajectory']['instance'].universe.cellParameters = self._cellParametersFunction
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._gmft.close()
示例10: shrinkUniverse
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
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()
示例11: DiscoverConverter
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
#.........这里部分代码省略.........
type = 'discover'
label = "Discover"
category = ('Converters',)
ancestor = None
settings = collections.OrderedDict()
settings['xtd_file'] = ('input_file',{})
settings['his_file'] = ('input_file',{})
settings['output_file'] = ('output_files', {'formats':["netcdf"]})
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 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, vel = self._hisfile.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)
movableAtoms = self._hisfile['movable_atoms']
self._universe.configuration().array[movableAtoms,:] = config
self._universe.foldCoordinatesIntoBox()
data = {"time" : time}
self._velocities.array[movableAtoms,:] = vel
self._universe.setVelocities(self._velocities)
# 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._hisfile.close()
# Close the output trajectory.
self._trajectory.close()
示例12: Mmtk
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
#.........这里部分代码省略.........
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.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.restartFilename))
# Create trajectory and integrator.
self.mmtkTrajectory = Trajectory(self.mmtkUniverse, self.trajectoryFilename, "a")
self.mmtkIntegrator = VelocityVerletIntegrator(self.mmtkUniverse, delta_t=self.timestep*Units.fs)
# Periodical actions for equilibration output.
self.equilibration_actions = [TranslationRemover(0, None, 100),
RotationRemover(0, None, 100),
LogOutput(self.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.restartFilename, 1),
LogOutput(self.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.temperature)
# Do some equilibration steps and rescaling velocities.
self.mmtkIntegrator(steps = self.equilibrationSteps(), actions = [VelocityScaler(self.temperature,
0.1*self.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.temperature)
self.mmtkUniverse.barostat = AndersenBarostat(self.pressure)
# Do some equilibration steps, rescaling velocities and resetting the
# barostat in regular intervals.
self.mmtkIntegrator(steps = self.equilibrationSteps(),
actions = [VelocityScaler(self.temperature,
0.1*self.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()
示例13: Mmtk
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
#.........这里部分代码省略.........
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()
示例14: VASPConverter
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
class VASPConverter(Converter):
"""
Converts a VASP trajectory to a MMTK trajectory.
"""
type = 'vasp'
label = "VASP (>=5)"
category = ('Converters',)
ancestor = None
settings = collections.OrderedDict()
settings['xdatcar_file'] = ('input_file',{})
settings['time_step'] = ('float', {'label':"time step", 'default':1.0, 'mini':1.0e-9})
settings['output_file'] = ('output_files', {'formats':["netcdf"]})
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 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.
"""
# Read the current step in the xdatcar file.
config = self._xdatcarFile.read_step(index)
conf = Configuration(self._universe,config)
conf.convertFromBoxCoordinates()
self._universe.setConfiguration(conf)
# The real coordinates are foled then into the simulation box (-L/2,L/2).
self._universe.foldCoordinatesIntoBox()
time = index*self.configuration["time_step"]["value"]*Units.fs
# A call to the snapshot generator produces the step corresponding to the current frame.
self._snapshot(data = {'time': time})
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._xdatcarFile.close()
# Close the output trajectory.
self._trajectory.close()
示例15: CASTEPConverter
# 需要导入模块: from MMTK.Trajectory import Trajectory [as 别名]
# 或者: from MMTK.Trajectory.Trajectory import close [as 别名]
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()