Esempio 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()
Esempio n. 2
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()
Esempio n. 3
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()
Esempio n. 4
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
Esempio n. 5
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()
Esempio n. 6
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()
Esempio n. 7
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()
Esempio n. 8
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
Esempio n. 9
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()
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()   
Esempio n. 11
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
Esempio n. 12
0
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            
    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()

print '.....Equilibrating Done.........................................................'

#Perform the production portion
start = time()
print '\n.....Beginning Production.......................................................'
integrator = LangevinIntegrator(universe,
                                delta_t=dt,
                                friction=friction,
                                temperature=temperature,
                                restraint=[[0, 1, 2], [3, 4, 5], k_restraint,
                                           r0_restraint, 'com'])
integrator(steps=ProdSteps, actions=prod_output_actions)

print '.....Production Done............................................................'
Esempio n. 14
0
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)

print "Number of Steps : " + str(nvt_time / skip)

# NOW WE BUILD A TRAJECTORY, AND RUN OUR ACTUAL DYNAMICS!
trajectoryNVE = Trajectory(
    universe, "/scratch/mdgschmi/" + label + ".nc", "w",
    "PIMD simulation NVE using Langevin Cartesian Integrator")

# NOTE THERE IS A BRIEF INITIALIZATIONS OF 0.05/dt time-steps!

integrator(
    steps=nvt_time,
    actions=[
        TrajectoryOutput(trajectoryNVE,
                         ('configuration', 'energy', 'time', 'velocities'), 0,
                         None, skip)
    ])

trajectoryNVE.close()
os.system("mv /scratch/mdgschmi/" + label +
          ".nc /warehouse/mdgschmi/MBpolDimer/.")
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 ...)
        """

        # The input trajectory is closed.
        self.configuration['trajectory']['instance'].close()
                                                    
        # The output trajectory is closed.
        self._btt.close()   
Esempio n. 16
0
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()
Esempio n. 17
0
class DiscoverConverter(Converter):
    """
    Converts a DL_POLY trajectory to a MMTK trajectory.
    """

    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()
Esempio n. 18
0
#       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()
Esempio n. 19
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)
Esempio n. 20
0
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()
Esempio n. 21
0
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
    print 'Lx = ', Lx
    # 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
    tdiff = 4 # N_prdt/tdiff : no. of data points for the postprocessing 

    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
        Mij_chain = np.zeros((Ns, Nc, Nc)) # to calculate connectivity matrix for chains
        # local time correlation function
        Ft = np.zeros(Ns)
 
        # Connectivity matirix for cluster
        #Cij = Mij.astype(int)  
        Cij = Mij.astype(int) # for multi-chain system
        Cij_chain = Mij_chain.astype(int) 

        Rank = np.zeros(500) # Rank of the connectivity matrix
        Rank_chain = np.zeros(500) # Rank of the connectivity matrix for chains

        pair = np.zeros((Ns, Nc*chains_ns[0])) # to define functionality in pairing

        spanning_matrix = np.zeros(500) # matrix to identify the system spanning network

        ## computation of number of cluster and cluster size for multi-chain system 
        for t, conf in enumerate(traj.box_coordinates):
            if ((t+1) % tdiff == 0):
                tid = t+1
                #print tid
                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):
                            # minimum image convention 
                            rijx = beadpositions[i][0] - beadpositions[j][0] - Lx*round((beadpositions[i][0] - beadpositions[j][0])/Lx)
                            rijy = beadpositions[i][1] - beadpositions[j][1] - Lx*round((beadpositions[i][1] - beadpositions[j][1])/Lx)
                            rijz = beadpositions[i][2] - beadpositions[j][2] - Lx*round((beadpositions[i][2] - beadpositions[j][2])/Lx)
                            rijsq = (rijx**2 + rijy**2 + rijz**2)
                            rij = sqrt(rijsq)
                            if (rij < 1.82*Lja2):
                                if (i == j):
                                    Cij[tid, p, q] = 1
                                    Cij_chain[tid, nc_i, nc_j] = 1
                                if (i != j and pair[tid, i] < 1 and pair[tid, j] < 1):
                                    Cij[tid, p, q] = 1
                                    Cij_chain[tid, nc_i, nc_j] = 1
                                    pair[tid, i] += 1
                                    pair[tid, j] += 1
                    q = 0
                if (tid % 500 == 0):
                    print 'tid = ', tid
                 
                 
        # computation of the rank of the connectivity matrix for the chains and system spanning cluster
        for t, conf in enumerate(traj.box_coordinates):
            if ((t+1) % tdiff == 0):
                tid = t+1
                #print 'tid = ', tid
                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.
                N0 = Nc
                N = Nc
                #if (tid == 8):
                #    print Cij_chain[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_chain[tid,:,i], Cij_chain[tid,:,j])
                                if ((c**2).sum() != 0 and j!=i):
                                    switch = 1
                                    Cij_chain[tid,:,i] =  np.bitwise_or(Cij_chain[tid,:,i], Cij_chain[tid,:,j])
                                    N1 = j
                                    N = N-1
                                    for k in range(N1+1, N+1):
                                        Cij_chain[tid,:,k-1] = Cij_chain[tid,:,k]
                                    break
                    else: break
                Rank_chain[tid/tdiff - 1] = N
                #if (tid == 8):
                #    print Cij_chain[tid,:,:]
                for nc in range(N):
                    if (spanning_matrix[tid/tdiff - 1] == 0):                           
                        # identifying the chain number in a cluster
                        index = np.nonzero(Cij_chain[tid,:,nc])
                        index = index[0]
                        l = list(index) 
                        #print l
                        PBCx = 0; PBCy = 0; PBCz = 0
                        for j in range(len(l)):
                            for k in range(chains_ns[0]):
                                bd_i = chains_ns[0]*l[j] + k
                                if k == 0:
                                    xmin = beadpositions[bd_i][0]
                                    xmax = beadpositions[bd_i][0]
                                    ymin = beadpositions[bd_i][1]
                                    ymax = beadpositions[bd_i][1]
                                    zmin = beadpositions[bd_i][2]
                                    zmax = beadpositions[bd_i][2]
                                if k > 0:
                                    if (abs(beadpositions[bd_i][0] - beadpositions[bd_i-1][0]) > 50.0**0.5):
                                        if beadpositions[bd_i][0] > 0.:
                                            beadpositions[bd_i][0] = -Lx + beadpositions[bd_i][0]
                                        elif beadpositions[bd_i][0] < 0.:
                                            beadpositions[bd_i][0] = Lx + beadpositions[bd_i][0]
                                    
                                    if (abs(beadpositions[bd_i][1] - beadpositions[bd_i-1][1]) > 50.0**0.5):
                                        if beadpositions[bd_i][1] > 0.:
                                            beadpositions[bd_i][1] = -Lx + beadpositions[bd_i][1]
                                        elif beadpositions[bd_i][1] < 0.:
                                            beadpositions[bd_i][1] = Lx + beadpositions[bd_i][1]
                                    
                                    if (abs(beadpositions[bd_i][2] - beadpositions[bd_i-1][2]) > 50.0**0.5):
                                        if beadpositions[bd_i][2] > 0.:
                                            beadpositions[bd_i][2] = -Lx + beadpositions[bd_i][2]
                                        elif beadpositions[bd_i][2] < 0.:
                                            beadpositions[bd_i][2] = Lx + beadpositions[bd_i][2]
                                    # calculation max and min position co-ordinates of a chain
                                    if beadpositions[bd_i][0] < xmin: 
                                        xmin = beadpositions[bd_i][0]
                                    elif beadpositions[bd_i][0] > xmax:
                                        xmax = beadpositions[bd_i][0]
                                      
                                    if beadpositions[bd_i][1] < ymin:
                                        ymin = beadpositions[bd_i][1]
                                    elif beadpositions[bd_i][1] > ymax:
                                        ymax = beadpositions[bd_i][1]

                                    if beadpositions[bd_i][2] < zmin:
                                        zmin = beadpositions[bd_i][2]
                                    elif beadpositions[bd_i][2] > zmax:
                                        zmax = beadpositions[bd_i][2]
                                #print 'k = ', k
                                #print 'xmin = ', xmin
                                #print 'xmax = ', xmax
                             
                            if xmin < -0.5*Lx:
                                xmin1 = xmin; xmin2 = xmin + Lx; xmax1 = xmax; xmax2 = xmax + Lx
                                PBCx = 1
                            if xmax > 0.5*Lx:
                                xmin1 = xmin - Lx; xmin2 = xmin; xmax1 = xmax - Lx; xmax2 = xmax
                                PBCx = 1
                            elif xmin > -0.5*Lx and xmax < 0.5*Lx:
                                xmin1 = xmin - Lx; xmin2 = xmin; xmax1 = xmax; xmax2 = xmax + Lx                               
 
                            if ymin < -0.5*Lx:
                                ymin1 = ymin; ymin2 = ymin + Lx; ymax1 = ymax; ymax2 = ymax + Lx
                                PBCy = 1
                            if ymax > 0.5*Lx:
                                ymin1 = ymin - Lx; ymin2 = ymin; ymax1 = ymax - Lx; ymax2 = ymax
                                PBCy = 1
                            elif ymin > -0.5*Lx and ymax < 0.5*Lx:
                                ymin1 = ymin - Lx; ymin2 = ymin; ymax1 = ymax; ymax2 = ymax + Lx

                            if zmin < -0.5*Lx:
                                zmin1 = zmin; zmin2 = zmin + Lx; zmax1 = zmax; zmax2 = zmax + Lx
                                PBCz = 1
                            if zmax > 0.5*Lx:
                                zmin1 = zmin - Lx; zmin2 = zmin; zmax1 = zmax - Lx; zmax2 = ymax
                                PBCz = 1
                            elif zmin > -0.5*Lx and zmax < 0.5*Lx:
                                zmin1 = zmin - Lx; zmin2 = zmin; zmax1 = zmax; zmax2 = zmax + Lx  
                            
                            if (j == 0):                          
                                xmin1c = xmin1; xmin2c = xmin2; xmax1c = xmax1; xmax2c = xmax2
                                ymin1c = ymin1; ymin2c = ymin2; ymax1c = ymax1; ymax2c = ymax2
                                zmin1c = zmin1; zmin2c = zmin2; zmax1c = zmax1; zmax2c = zmax2
                            
                            if j > 0:
                                xmax2c = min(xmax2c, xmax2); xmin1c = max(xmin1c, xmin1)
                                xmax1c = max(xmax1c, xmax1); xmin2c = min(xmin2c, xmin2)

                                ymax2c = min(ymax2c, ymax2); ymin1c = max(ymin1c, ymin1)
                                ymax1c = max(ymax1c, ymax1); ymin2c = min(ymin2c, ymin2)                             
                               
                                zmax2c = min(zmax2c, zmax2); zmin1c = max(zmin1c, zmin1)
                                zmax1c = max(zmax1c, zmax1); zmin2c = min(zmin2c, zmin2)
                            '''
                            print 'j = ', j
                            print 'xmin1c = ', xmin1c
                            print 'xmin2c = ', xmin2c
                            print 'xmax1c = ', xmax1c
                            print 'xmax2c = ', xmax2c
                            '''
                            if xmax1c >= xmin2c or ymax1c >= ymin2c or zmax1c >= zmin2c:
                                if PBCx == 0:
                                    clustrx = abs(xmax1c - xmin2c)
                                elif PBCx == 1:
                                    clustrx = min(abs(xmax2c - xmin2c), abs(xmax1c - xmin1c))
                                if PBCy == 0:
                                    clustry = abs(ymax1c - ymin2c)
                                elif PBCy == 1:
                                    clustry = min(abs(ymax2c - ymin2c), abs(ymax1c - ymin1c))
                                if PBCz == 0:
                                    clustrz = abs(zmax1c - zmin2c)
                                elif PBCz == 1:
                                    clustrz = min(abs(zmax2c - zmin2c), abs(zmax1c - zmin1c))
 
                                if clustrx >= Lx-1 or clustry >= Lx-1 or clustrz >= Lz-1:
                                    #print 'clustrx = ', clustrx
                                    #print 'clustry = ', clustry
                                    #print 'clustrz = ', clustrz
                                    spanning_matrix[tid/tdiff - 1] = 1
                                    break
                             
        if file_output: 
            np.savetxt("spanningclust%s.txt" % filename, spanning_matrix)
        else:
            #print Ft
            #print gt 
            print Rank_chain
        
    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()
# 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()
class GlobalMotionFilteredTrajectory(IJob):
    """
    It is often of interest to separate global motion from internal motion, both for quantitative
    analysis and for visualization by animated display. Obviously, this can be done under the
    hypothesis that global and internal motions are decoupled within the length and timescales of
    the analysis. MDANSE can create Global Motion Filtered Trajectory (GMFT) by filtering
    out global motions (made of the three translational and rotational degrees of freedom), either
    on the whole system or on an user-defined subset, by fitting it to a reference structure (usually
    the first frame of the MD). Global motion filtering uses a straightforward algorithm:
    
    * for the first frame, find the linear transformation such that the coordinate origin becomes
    the center of mass of the system and its principal axes of inertia are parallel to the three
    coordinates axes (also called principal axes transformation),
    
    * this provides a reference configuration C ref ,
    
    * for any other frames f, finds and applies the linear transformation that minimizes the
    RMS distance between frame f and C ref .
    
    The result is stored in a new trajectory file that contains only internal motions. This analysis
    can be useful in case where diffusive motions are not of interest or simply not accessible to the
    experiment (time resolution, powder analysis ... ).

    To do so, the universe has to be made infinite and all its configuration contiguous.
    """
    
    type = 'gmft'
    
    label = "Global Motion Filtered 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['reference_selection'] = ('atom_selection', {'dependencies':{'trajectory':'trajectory'}})
    settings['contiguous'] = ('boolean', {'default':False, 'label':"Make the chemical object contiguous"})
    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.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 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()
Esempio n. 24
0
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)
Esempio n. 25
0
pot_eng_error = standardDeviation(data2/Units.k_B)/sqrt(npoints)

print "Potential estimator:", pot_eng, "+/-", pot_eng_error, " K"
print "Kinetic estimator:", mean(data-data2)/Units.k_B
#data = trajectory.kinetic_energy
#print "Kinetic estimator:", mean(data/Units.k_B), "+/-",  standardDeviation(data/Units.k_B)/sqrt(npoints), " K"
#data = trajectory.spring_energy
#print "Spring estimator:", mean(data/Units.k_B), "+/-",  standardDeviation(data/Units.k_B)/sqrt(npoints), " K"

#data = trajectory.quantum_energy_virial
#print "Virial estimator:", mean(data), "+/-",  standardDeviation(data)/sqrt(npoints), " kj/mol"
#data = trajectory.quantum_energy_centroid_virial
#print "Centroid virial estimator:", mean(data), "+/-",  standardDeviation(data)/sqrt(npoints), " kj/mol"
data3 = trajectory.quantum_energy_rotation
output_rot=open('KErot','w')
for e in data3:
    output_rot.write(str(e)+'\n')
output_rot.close()

rot_eng = mean(data3/Units.k_B)
rot_eng_error = standardDeviation(data3/Units.k_B)/sqrt(npoints)

print "Rotational Energy estimator:", rot_eng, "+/-", rot_eng_error, " K"

filename = "energy-T"+str(temperature)+"steps"+str(numberofsteps)+"nmolecules"+str(nmolecules)
filestream = open(filename, "a")
filestream.write(str(lattice_spacing)+" "+str(pot_eng)+"    "+str(pot_eng_error)+"    "+str(rot_eng)+"    "+str(rot_eng_error)+"\n")
filestream.close()

trajectory.close()
Esempio n. 26
0
class Mmtk(MolDynamics):
    """MMTK engine for MolDynamics interface.
    
    This class maps the API to MMTK commands and executes them.
    """
    ensemble = 'nvt'
    equilibrationTime = 0.0
    productionTime = 0.0
    propCalcInterval = 5.0
    thermostatParameter = 0.05
    barostatParameter = 0.0
    timeStep = 0.002
    trajectoryFilename = 'molDynamics.his'
    restartFilename = 'molDynamics.res'
    dumpInterval = 0.0
    temperature=0.0
    pressure=0.0
    integrator = 'velocity-verlet'
    restarting = False
    forcefield = 'amber'
    ljCutoff = 15.*Units.Ang
    #'amber', 'lennardJones']
        
    def __init__(self, **kwds):
        MolDynamics.__init__(self, **kwds)
        for k, v in kwds.iteritems():
            setattr(self, k, v)  
        self.mmtkUniverse = None
        
#    def _setDefaults(self):
#        '''set defaults specific to mmtk'''
#        self.trajectoryFilename = 'molDynamics.nc'
#        self.restartFilename = 'restart.nc'
#        self.propCalcInterval = self.timeStep*Units.fs
#        self.dumpInterval = self.timeStep*Units.fs
        
    def _ind(self,list):
        """gives the indices of the list to iterate over"""
        return range(len(list))
    
    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):         
        if self.forcefield=='amber94':
            self.ff=Amber94ForceField()
        elif self.forcefield=='lennard jones':
            self.ff=LennardJonesFF(eval(self.ljCutoff))
        else: #'amber99'
            self.ff=Amber99ForceField()
        
    def _setInitialConditions(self):
        '''map MolDynamics unit cell stuff to MMTK's. 
        Eventually much of this will be taken by the crystal class''' 
        #atoms = self.getAtomsAsStrings()
        #uc = self.getCellVectors()
        uc=self.structure.lattice.base
        if uc.all()==np.array([[1.0, 0, 0],[0, 1.0, 0.0],[0.0, 0.0, 1.0]]).all():
            self.mmtkUniverse = MMTK.InfiniteUniverse(self.ff)
        else:
            #ucList=uc.tolist()
            a,b,c,al,be,ga = uc.abcABG()
            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.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 self.structure:
            x, y, z = atom.xyz_cartn
            self.mmtkUniverse.addObject(MMTK.Atom(atom.symbol, position = \
                MMTK.Vector(x*Units.Ang, y*Units.Ang, z*Units.Ang))) 
#        elif self.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.temperature)
        # Create trajectory and integrator.
        self.mmtkTrajectory = Trajectory(self.mmtkUniverse, self.trajectoryFilename, "w")
        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 = [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.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()
        self._setForcefield()
        self._setInitialConditions()
        self.createTrajectoryAndIntegrator()
        if self.ensemble=='nvt':
            self._integrateNVT()
        elif self.ensemble=='npt':
            self._integrateNPT()
        elif self.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.ensemble=='nvt':
            self._integrateNVT()
        elif self.ensemble=='npt':
            self._integrateNPT()
        elif self.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.restarting:
            self.restartIntegrate()
        else:
            self.integrate()
            
    def printWarnings(self):
        if self.propCalcInterval > self.timeStep:
            print '''Mmtk does not allow a different sample frequency than every timestep.
            Write frequency will be set to every timestep.''' 
        if self.dumpInterval > self.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.timeStep==0:
            raise Exception, 'please set the time step to a nonzero value'
        else:
            val=int(self.equilibrationTime/self.timeStep)
        return val
    
    def productionSteps(self):
        '''Number of time steps to finish production'''
        if self.timeStep==0:
            raise Exception, 'please set the time step to a nonzero value'
        else:
            return int(self.productionTime/self.timeStep)
Esempio n. 27
0
class PDBConverter(Converter):
    """
    Converts a PDB trajectory to a MMTK trajectory.
    """
    type = 'pdb'
    
    label = "PDB"

    category = ('Converters',)
    
    ancestor = None

    settings = collections.OrderedDict()  
    settings['pdb_file'] = ('input_file',{})
    settings['nb_frame'] = ('range', {'valueType':int, 'includeLast':True, 'mini':0.0, 'default':(0,1,1)})
    settings['time_step'] = ('float', {'mini':1.0e-6, 'default':1.0})
    settings['output_file'] = ('output_files', {'formats':["netcdf"]})
     
    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 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. 
        """
    
        frame = self.frame_list[index]

        pdb_config = PDBFile(self.configuration['pdb_file']['filename'], model = frame)
        uni = pdb_config.createUnitCellUniverse()
        uni.addObject(pdb_config.createAll(None, 1))
        univ_config  = Configuration(self._universe, uni.configuration().array)
        
        self._universe.setConfiguration(univ_config)
        self._universe.foldCoordinatesIntoBox()
        self._snapshot(data = {'time':frame})

        return index, None
    
    def combine(self, index, x):
        """
        Not used here
        """   
        pass
    
    def finalize(self):
        """
        Finalizes the calculations (e.g. averaging the total term, output files creations ...).
        """ 
        # 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)                
Esempio n. 29
0
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()
Esempio n. 30
0
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()
Esempio n. 31
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()
Esempio n. 32
0
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        
Esempio n. 33
0
    def body(self, master):
        """Create dialog body. Return widget that should have initial focus.
        """

        # The frame that will contain the widgets whose the analysis dialog is built up.
        widgetsFrame = LabelFrame(master, text='Setup', bd=2, relief=GROOVE)
        widgetsFrame.grid(row=0, column=0, padx=3, pady=3, sticky=EW)
        widgetsFrame.grid_columnconfigure(0, weight=1)

        self.widgets = {}

        for widget in self.db_parameternames:

            widget = widget.lower()

            if widget == 'angminmax':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "HB angle min:max values (in deg)",\
                                                        tagName = 'angle_min_max',\
                                                        contents = "150.0:180.0")

            elif widget == 'armodelorder':
                self.widgets[widget] = ComboIntegerEntry(widgetsFrame,\
                                                         frameLabel = "Model order", \
                                                         tagName = 'model_order',\
                                                         contents = 50)

            elif widget == 'atomorder':

                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "Atom order",\
                                                   tagName = 'atom_selection',\
                                                   contents = "Select",\
                                                   withEntry = '')

                t = Trajectory(None, self.trajectory, 'r')

                self.widgets[widget].command = lambda s=self, n=sorted(
                    set([at.name for at in t.universe.atomList()])
                ): AtomOrderDialog(s, n)

                t.close()

            elif widget == 'truebreakstep':
                self.widgets[widget] = ComboIntegerEntry(widgetsFrame,\
                                                         frameLabel = "True break step", \
                                                         tagName = 'true_break_step',\
                                                         contents = 1)

            elif widget == 'comselection':
                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "Center of mass selection",\
                                                   tagName = 'center_of_mass_selection',\
                                                   contents = "Select",\
                                                   withEntry = 'all')

                self.widgets[
                    widget].command = lambda s=self, t='subset', c=self.chemicalObjectInfo, w=self.widgets[
                        widget]: SelectionDialog(s, t, c, w)

            elif widget == 'deuteration':
                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "Deuteration selection",\
                                                   tagName = 'deuteration_selection',\
                                                   contents = "Select",\
                                                   withEntry = 'no')

                self.widgets[
                    widget].command = lambda s=self, t='deuteration', c=self.chemicalObjectInfo, w=self.widgets[
                        widget]: SelectionDialog(s, t, c, w)

            elif widget == 'differentiation':

                t = Trajectory(None, GVAR['current_traj'], 'r')

                if 'velocities' in t.variables():
                    diffOrder = (0, 1, 2, 3, 4, 5)
                else:
                    diffOrder = (1, 2, 3, 4, 5)

                t.close()

                self.widgets[widget] = ComboSpinbox(widgetsFrame,\
                                                    frameLabel = "Differentiation order",\
                                                    tagName = 'differentiation_order',\
                                                    contents = diffOrder)

            elif widget == 'direction':
                self.widgets[widget] = ComboRadiobutton(widgetsFrame,\
                                                        frameLabel = "Direction",\
                                                        tagName = 'direction',\
                                                        contents = ["X", "Y", "Z"],\
                                                        layout = (1,3))

            elif widget == 'disminmax':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "HB distance min:max values",\
                                                        tagName = 'dis_min_max',\
                                                        contents = "0.0:0.35")

            elif widget == 'distanceunits':
                self.widgets[widget] = ComboRadiobutton(widgetsFrame,\
                                                        frameLabel = "Distance units",\
                                                        tagName = 'distanceunits',\
                                                        contents = ["nm", "ang", "fm"],\
                                                        layout = (1,3))

            elif widget == 'filter':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Pass-Band filter (in tHz)",\
                                                        tagName = 'pass_band_filer',\
                                                        contents = "0.0:1000.0")

            elif widget == 'frequencyunits':
                self.widgets[widget] = ComboRadiobutton(widgetsFrame,\
                                                        frameLabel = "Frequency units",\
                                                        tagName = 'frequencyunits',\
                                                        contents = ["THz", "rad s^-1", "cm^-1", "meV", "ueV"],\
                                                        layout = (1,5))

            elif widget == 'group':
                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "Group selection",\
                                                   tagName = 'group_selection',\
                                                   contents = "Select",\
                                                   withEntry = 'all')

                self.widgets[
                    widget].command = lambda s=self, t='group', c=self.chemicalObjectInfo, w=self.widgets[
                        widget]: SelectionDialog(s, t, c, w)

            elif widget == 'normalize':
                self.widgets[widget] = ComboCheckbutton(widgetsFrame,\
                                                        frameLabel = "Normalize",\
                                                        tagName = 'normalize',\
                                                        onvalue = "yes",\
                                                        offvalue = "no")

            elif widget == 'output':
                # The basename of the input trajectory name.
                baseName = self.db_shortname.upper() + '_' + os.path.basename(
                    self.trajectory)

                try:
                    outputFilename = os.path.join(
                        PREFERENCES['outputfile_path'], baseName)

                except TypeError:
                    outputFilename = baseName

                self.widgets[widget] = ComboFileBrowser(widgetsFrame,\
                                                        frameLabel = "Output file",\
                                                        tagName= "output_file",\
                                                        contents = outputFilename,\
                                                        save = True,\
                                                        filetypes = [("NetCDF file", ".nc"),])

            elif widget == 'phivalues':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Phi values (in deg)",\
                                                        tagName = 'phi_values',\
                                                        contents = "-180.0:180.0:10.0")

            elif widget == 'projection':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Project displacement on",\
                                                        tagName = 'project_displacement_on',\
                                                        contents = "no")

            elif widget == 'pyroserver':

                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "Pyro server",\
                                                   tagName = 'pyro_server',\
                                                   contents = "Select",\
                                                   withEntry = 'monoprocessor')

                self.widgets[widget].command = lambda s=self, w=self.widgets[
                    widget]: PyroServerDialog(s, w)

            elif widget == 'qshellvalues':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Q values (in nm-1)",\
                                                        tagName = 'qshell_values',\
                                                        contents = "0.0:100.0:1.0")

            elif widget == 'qshellwidth':
                self.widgets[widget] = ComboFloatEntry(widgetsFrame,\
                                                       frameLabel = "Q shell width (in nm-1)",\
                                                       tagName = 'qshell_width',\
                                                       contents = 1.0)

            elif widget == 'qunits':
                self.widgets[widget] = ComboRadiobutton(widgetsFrame,\
                                                        frameLabel = "Q units",\
                                                        tagName = 'qunits',\
                                                        contents = ["nm^-1", "ang^-1"],\
                                                        layout = (1,2))

            elif widget == 'qvectors':
                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "Q vectors",\
                                                   tagName = 'qvectors',\
                                                   contents = "Setup",\
                                                   withEntry = {'qgeometry': 'spatial', \
                                                                'qshellwidth': 1.0, \
                                                                'qshellvalues': '0.0:10.0:1.0', \
                                                                'qvectorspershell': 50,\
                                                                'hkls' : None})

                self.widgets[widget].command = lambda s=self, w=self.widgets[
                    widget]: QVectorsDialog(s, w)

            elif widget == 'qvectorsdirection':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Q vectors direction",\
                                                        tagName = 'qvectors_direction',\
                                                        contents = "no")

            elif widget == 'qvectorsgenerator':
                self.widgets[widget] = ComboRadiobutton(widgetsFrame,\
                                                        frameLabel = "Q vectors generator",\
                                                        tagName = 'qvectors_generator',\
                                                        contents = ["3D isotropic", "2D isotropic", "anisotropic"],\
                                                        layout = (1,3))

            elif widget == 'qvectorspershell':
                self.widgets[widget] = ComboIntegerEntry(widgetsFrame,\
                                                         frameLabel = "Q vectors per shell",\
                                                         tagName= 'qvectors_per_shell',\
                                                         contents = 50)

            elif widget == 'referencedirection':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Reference direction",\
                                                        tagName = 'reference_direction',\
                                                        contents = "0.0,0.0,1.0")

            elif widget == 'referenceframe':
                self.widgets[widget] = ComboIntegerEntry(widgetsFrame,\
                                                         frameLabel = "Reference frame",\
                                                         tagName= 'reference_frame',\
                                                         contents = 1)

            elif widget == 'removetranslation':
                self.widgets[widget] = ComboCheckbutton(widgetsFrame,\
                                                        frameLabel = "Remove translation",\
                                                        tagName = 'remove_translation',\
                                                        onvalue = "yes",\
                                                        offvalue = "no")

            elif widget == 'resolution':
                self.widgets[widget] = ComboFloatEntry(widgetsFrame,\
                                                       frameLabel = "Resolution (FWHM meV)",\
                                                       tagName = 'resolution',\
                                                       contents = 10.0)

                self.updateResolution()

                self.widgets[widget].entry.variable.trace_vdelete(
                    'w', self.widgets[widget].entry.cbname)

                self.widgets[widget].entry.variable.trace_variable(
                    'w', self.updateResolution)

                self.widgets[widget].entry.variable.trace_variable(
                    'w', self.widgets[widget].entry._callback)

            elif widget == 'rvalues':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Distances (in nm)",\
                                                        tagName = 'distances',\
                                                        contents = "0.0:1.0:0.1")

            elif widget == 'stepwiserbt':
                self.widgets[widget] = ComboCheckbutton(widgetsFrame,\
                                                        frameLabel = "Stepwise RBT",\
                                                        tagName = 'stepwise_rbt',\
                                                        onvalue = "yes",\
                                                        offvalue = "no")

            elif widget == 'storerbtdetails':
                self.widgets[widget] = ComboCheckbutton(widgetsFrame,\
                                                        frameLabel = "Store RBT details",\
                                                        tagName = 'store_rbt_details',\
                                                        onvalue = "yes",\
                                                        offvalue = "no")

            elif widget in ['subset', 'subset1', 'subset2']:
                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "%s selection" % widget.capitalize(),\
                                                   tagName = 'subset_selection',\
                                                   contents = "Select",\
                                                   withEntry = 'all')

                self.widgets[
                    widget].command = lambda s=self, t='subset', c=self.chemicalObjectInfo, w=self.widgets[
                        widget]: SelectionDialog(s, t, c, w)

            elif widget == 'target':
                self.widgets[widget] = ComboButton(widgetsFrame,\
                                                   frameLabel = "Target selection",\
                                                   tagName = 'target_selection',\
                                                   contents = "Select",\
                                                   withEntry = 'all')

                if self.db_shortname == "GMFT":
                    self.widgets[
                        widget].command = lambda s=self, t='subset', c=self.chemicalObjectInfo, w=self.widgets[
                            widget]: SelectionDialog(s, t, c, w)
                else:
                    self.widgets[
                        widget].command = lambda s=self, t='group', c=self.chemicalObjectInfo, w=self.widgets[
                            widget]: SelectionDialog(s, t, c, w)

            elif widget == 'temperature':
                self.widgets[widget] = ComboFloatEntry(widgetsFrame,\
                                                       frameLabel = "Temperature (in K)",\
                                                       tagName = 'temperature',\
                                                       contents = 1.0)

            elif widget == 'thetavalues':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Theta values (in deg)",\
                                                        tagName = 'theta_values',\
                                                        contents = "0.0:180.0:10.0")

            elif widget == 'thickness':
                self.widgets[widget] = ComboFloatEntry(widgetsFrame,\
                                                       frameLabel = "Thickness (in nm)",\
                                                       tagName = 'thickness',\
                                                       contents = 0.05)

            elif widget == 'timeinfo':

                t = load_trajectory_file(self.trajectory)
                timeInfo = '%d:%d:%d' % (1, len(t), 1)
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Frame selection",\
                                                        tagName = 'frame_selection',\
                                                        contents = timeInfo)

                self.updateTimeInfo(t)

                self.widgets[widget].entry.variable.trace_variable(
                    'w', lambda: self.updateTimeInfo(t))

            elif widget == 'timeunits':
                self.widgets[widget] = ComboRadiobutton(widgetsFrame,\
                                                        frameLabel = "Time units",\
                                                        tagName = 'timeunits',\
                                                        contents = ["ps", "ns", "fs"],\
                                                        layout = (1,3))

            elif widget == 'trajectory':
                self.widgets[widget] = ComboLabel(widgetsFrame,\
                                                  frameLabel = "Trajectory file",\
                                                  tagName = 'tajectory_file',\
                                                  contents = self.trajectory)

            elif widget == 'weights':
                self.widgets[widget] = ComboRadiobutton(widgetsFrame,\
                                                        frameLabel = "Weights",\
                                                        tagName = 'weights',\
                                                        contents = ["equal", "mass", "coherent", "incoherent", "atomicNumber"],\
                                                        layout = (2,3))

            elif widget == 'wignerindexes':
                self.widgets[widget] = ComboStringEntry(widgetsFrame,\
                                                        frameLabel = "Wigner indexes",\
                                                        tagName = 'wigner_indexes',\
                                                        contents = "0,0,0")

            # The tagName for the combo widget is set.
            setattr(
                self.widgets[widget], 'tagName',
                '%s_%s' % (self.db_shortname.lower(),
                           self.widgets[widget].tagName.lower()))

            # And displayed into the analysis dialog.
            self.widgets[widget].grid(column=0, sticky=EW, padx=2, pady=2)
            self.widgets[widget].grid_columnconfigure(0, weight=1)

        if hasattr(self, 'db_modulator'):
            for k, v in self.db_modulator.items():
                k = k.lower()
                if k == 'weights':
                    self.widgets[k].setValue(v)

                elif k == 'differentiation':
                    self.widgets[k].spinbox.config(values=v)

        return None
Esempio n. 34
0
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()
        
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()

print '.....Equilibrating Done.........................................................'

#Perform the production portion
start = time()       
print '\n.....Beginning Production.......................................................'     
integrator = LangevinIntegrator(universe, delta_t=dt,
                                friction=friction, temperature=temperature, restraint=[[0,1,2],[3,4,5],k_restraint,r0_restraint,'com'])      
integrator(steps = ProdSteps, actions = prod_output_actions)

print '.....Production Done............................................................'
end = time()

print '\n.....Production Statistics......................................................'
print 'Completed', ProdSteps, 'production steps in ', (end-start), 'seconds or ', (end-start)/ProdSteps, 'seconds/step'
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()
Esempio n. 37
0
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()
Esempio n. 38
0
# "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()
Esempio n. 39
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()