Exemplo n.º 1
0
    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()
Exemplo n.º 2
0
 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()
Exemplo n.º 3
0
    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
Exemplo n.º 4
0
    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()
Exemplo n.º 5
0
    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()
Exemplo n.º 6
0
    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)])
Exemplo n.º 7
0
    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
        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
    else:
Exemplo n.º 9
0
# 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()
Exemplo n.º 10
0
    universe, outdir + "N" + str(nmolecules) + "H20T" + str(temperature) +
    "P" + str(P) + "R" + str(lattice_spacing) + "FilEAVersion" +
    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"),
            0, None, SkipSteps)
    ])

raise ()
##############################              BEGIN ANALYSIS           ##############################
#gradientTest(universe)

thetafile1 = open(
    "thetafile1-" + str(nmolecules) + "H20T" + str(temperature) + "P" +
    str(P) + "FileAVersioN" + str(numsteps) + "Steps" + label, "w")
thetafile2 = open(
    "thetafile2-" + str(nmolecules) + "H20T" + str(temperature) + "P" +
    str(P) + "FileAVersioN" + str(numsteps) + "Steps" + label, "w")

for step in trajectory:
Exemplo n.º 11
0
esqfile.close()

dt = 1.0*Units.fs
#print "Using a timestep of ", dt*1000., " fs"

# Initialize velocities
universe.initializeVelocitiesToTemperature(temperature)

# USE THE FRICTION PARAMETER FROM BEFORE
friction = 0.0

#integrator = Rigid3DRotor_PILangevinNormalModeIntegrator(universe, delta_t = dt, centroid_friction = friction, denrho = denrho, denerot = denerot, denesq = denesq, rotstep = float(Rot_Step), rotskipstep=float(Rot_Skip))

integrator = RotOnly3D_PILangevinNormalModeIntegrator(universe, delta_t = dt, centroid_friction = friction, denrho = denrho, denerot = denerot, denesq = denesq, rotstep = float(Rot_Step), rotskipstep=float(Rot_Skip))

integrator(steps = 30, 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)+"FilEDVersion"+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.
Exemplo n.º 12
0
    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
Exemplo n.º 13
0
print "E before steepest descent minimization", universe.energy()
minimizer = SteepestDescentMinimizer(universe, actions=[])
minimizer(convergence=1.e-8, steps=50)
print "E after steepest descent minimization", universe.energy()

# HERE WE USE NORMAL MODES TO DETERMINE THE TIME-STEP AND FRICTION
# OF OUR SYSTEM
universe.initializeVelocitiesToTemperature(temperature)

integrator = PIGSLangevinNormalModeIntegrator(universe,
                                              delta_t=bootstrap_dt,
                                              centroid_friction=friction)

integrator(
    steps=500,
    actions=[TrajectoryOutput(None, ('configuration', 'time'), 0, None, 100)])

print "bootstrap_dt", bootstrap_dt

universe.initializeVelocitiesToTemperature(temperature)
print "new dt=", dt, " new friction=", friction

universe.environmentObjectList(
    Environment.PathIntegrals)[0].include_spring_terms = False
universe._changed(True)

universe.initializeVelocitiesToTemperature(temperature)
#re-create integrator to use calculated friction value
integrator = PIGSLangevinNormalModeIntegrator(universe,
                                              delta_t=dt,
                                              centroid_friction=friction)
Exemplo n.º 14
0
        RotationRemover(0, None, 50),
        # Log output to screen every 100 steps.
        StandardLogOutput(100)
    ])

# "Production" run
trajectory = Trajectory(universe, "bala1.nc", "w", "A simple test case")
integrator(
    steps=100,
    # 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", "configuration"), 0,
                         None, 2),
        # Write restart data every fifth step.
        RestartTrajectoryOutput("restart.nc", 5),
        # Log output to screen every 10 steps.
        StandardLogOutput(10)
    ])
trajectory.close()

print "Starting background thread..."
thread = integrator(
    steps=10000,
    background=True,
    actions=[TranslationRemover(0, None, 50),
             RotationRemover(0, None, 50)])
print "Monitoring progress:"
while thread.is_alive():
Exemplo n.º 15
0
#integrator = Rigid3DRotor_PILangevinNormalModeIntegrator(universe, delta_t = dt, centroid_friction = friction, denrho = denrho, denerot = denerot, denesq = denesq, rotstep = float(Rot_Step), rotskipstep=float(Rot_Skip))

integrator = RotOnly3D_PILangevinNormalModeIntegrator(
    universe,
    delta_t=dt,
    centroid_friction=friction,
    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
                                           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)
trajectory_eq.close()
Exemplo n.º 17
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()
Exemplo n.º 18
0
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)
Exemplo n.º 19
0
# in a real application. The barostat relaxation time must be
# adjusted to the system size; it should be chosen smaller than
# for a realistic simulation in order to reach the final
# volume faster.
universe.setForceField(Amber94ForceField(1.4, {'method': 'ewald'}))
universe.thermostat = NoseThermostat(temperature)
universe.barostat = AndersenBarostat(pressure, 0.1*Units.ps)

# Create an integrator and a trajectory.
integrator = VelocityVerletIntegrator(universe, delta_t=1.*Units.fs)

trajectory = Trajectory(universe, "equilibration.nc", "w",
                        "Equilibration (NPT ensemble)")

# Start an NPT integration with periodic rescaling of velocities
# and resetting of the barostat. The number of steps required to
# reach a stable volume depends strongly on the system!
output_actions = [TrajectoryOutput(trajectory,
                                   ('configuration', 'energy', 'thermodynamic',
                                    'time', 'auxiliary'), 0, None, 100),
                  LogOutput("equilibration.log", ('time', 'energy'),
                            0, None, 100)]
integrator(steps = 1000,
           actions = [TranslationRemover(0, None, 200),
                      BarostatReset(0, None, 20),
                      VelocityScaler(temperature, 0., 0, None, 20)]
           + output_actions)

# Close the equilibration trajectory
trajectory.close()
Exemplo n.º 20
0
        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()
Exemplo n.º 21
0
# 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()