Пример #1
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)

        RT = R * self.getOption('T')
        ntrials = self.getOption('ntrials')

        acc = 0
        xo = np.copy(self.universe.configuration().array)
        eo = self.universe.energy()
        com = self.universe.centerOfMass().array

        for c in range(ntrials):
            step = np.random.randn(3) * self.step_size
            if c % 2 == 0:
                # Random translation and full rotation
                xn = np.dot((xo - com), random_rotate()) + com + step
            else:
                # Random translation
                xn = xo + step
            self.universe.setConfiguration(Configuration(self.universe, xn))
            en = self.universe.energy()
            if ((en < eo) or (np.random.random() < np.exp(-(en - eo) / RT))):
                acc += 1
                xo = xn
                eo = en
                com += step
            else:
                self.universe.setConfiguration(Configuration(
                    self.universe, xo))

        return ([np.copy(xo)], [en], acc, ntrials, 0.0)
Пример #2
0
    def __init__(self,
                 universe=None,
                 temperature=300. * Units.K,
                 subspace=None,
                 delta=None,
                 sparse=False):
        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(
            self, universe, subspace, delta, sparse,
            ['array', 'imaginary', 'frequencies', 'omega_sq'])
        self.temperature = temperature

        self.weights = N.sqrt(self.universe.masses().array)
        self.weights = self.weights[:, N.NewAxis]

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.imaginary = N.less(ev, 0.)
        self.omega_sq = ev
        self.frequencies = N.sqrt(N.fabs(ev)) / (2. * N.pi)
        self.sort_index = N.argsort(self.frequencies)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
Пример #3
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
      
        RT = R*self.getOption('T')
        delta_t = self.getOption('delta_t')
        
        if 'steps_per_trial' in self.call_options.keys():
          steps_per_trial = self.getOption('steps_per_trial')
          ntrials = self.getOption('steps')/steps_per_trial
        else:
          steps_per_trial = self.getOption('steps')
          ntrials = 1
  
        if 'normalize' in self.call_options.keys():
          normalize = self.getOption('normalize')
        else:
          normalize = False          
      
        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

        late_args = (
                masses.array, fixed.array, evaluator,
                N.zeros((0, 2), N.Int), N.zeros((0, ), N.Float),
                N.zeros((1,), N.Int),
                N.zeros((0,), N.Float), N.zeros((2,), N.Float),
                N.zeros((0,), N.Float), N.zeros((1,), N.Float),
                delta_t, self.getOption('first_step'),
                steps_per_trial, self.getActions(),
                'Velocity Verlet step')
      
        xs = []
        energies = []
      
        acc = 0
        for t in range(ntrials):
          # Initialize the velocity
          self.universe.initializeVelocitiesToTemperature(self.getOption('T'))

          # Store previous configuration and initial energy
          xo = self.universe.copyConfiguration()
          pe_o = self.universe.energy()
          eo = pe_o + self.universe.kineticEnergy()

          # Run the velocity verlet integrator
          self.run(MMTK_dynamics.integrateVV,
            (self.universe,
             self.universe.configuration().array,
             self.universe.velocities().array) + late_args)
  
        return (xs, energies, float(acc)/float(ntrials), delta_t)
Пример #4
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)

        RT = R * self.getOption("T")
        ntrials = self.getOption("ntrials")

        acc = 0
        xo = np.copy(self.universe.configuration().array)
        eo = self.universe.energy()
        com = self.universe.centerOfMass().array

        for c in range(ntrials):
            step = np.random.randn(3) * self.step_size
            if c % 2 == 0:
                # Random translation and full rotation
                xn = np.dot((xo - com), random_rotate()) + com + step
            else:
                # Random translation
                xn = xo + step
            self.universe.setConfiguration(Configuration(self.universe, xn))
            en = self.universe.energy()
            if (en < eo) or (np.random.random() < np.exp(-(en - eo) / RT)):
                acc += 1
                xo = xn
                eo = en
                com += step
            else:
                self.universe.setConfiguration(Configuration(self.universe, xo))

        return ([np.copy(xo)], [en], acc, ntrials, 0.0)
    def __init__(self,
                 universe=None,
                 friction=None,
                 temperature=300. * Units.K,
                 subspace=None,
                 delta=None,
                 sparse=False):
        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(self, universe, subspace, delta, sparse,
                                  ['array', 'inv_relaxation_times'])
        self.friction = friction
        self.temperature = temperature

        self.weights = N.sqrt(friction.array)
        self.weights = self.weights[:, N.NewAxis]

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.inv_relaxation_times = ev
        self.sort_index = N.argsort(self.inv_relaxation_times)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
Пример #6
0
 def __call__(self, **options):
     """
     Run the minimizer. The keyword options are the same as described
     under __init__.
     """
     self.setCallOptions(options)
     Features.checkFeatures(self, self.universe)
     configuration = self.universe.configuration()
     fixed = self.universe.getAtomBooleanArray('fixed')
     nt = self.getOption('threads')
     evaluator = self.universe.energyEvaluator(threads=nt).CEvaluator()
     args = (self.universe, configuration.array, fixed.array, evaluator,
             self.getOption('steps'), self.getOption('step_size'),
             self.getOption('convergence'), self.getActions(),
             'Conjugate gradient minimization with ' +
             self.optionString(['convergence', 'step_size', 'steps']))
     return self.run(conjugateGradient, args)
Пример #7
0
    def __call__(self, **options):
        """
        Run the minimizer. The keyword options are the same as described
        under __init__.
        """
	self.setCallOptions(options)
	Features.checkFeatures(self, self.universe)
	configuration = self.universe.configuration()
	fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
	evaluator = self.universe.energyEvaluator(threads=nt).CEvaluator()
	args =(self.universe,
               configuration.array, fixed.array, evaluator,
               self.getOption('steps'), self.getOption('step_size'),
               self.getOption('convergence'), self.getActions(),
               'Conjugate gradient minimization with ' +
               self.optionString(['convergence', 'step_size', 'steps']))
        return self.run(conjugateGradient, args)
Пример #8
0
    def __call__(self, **options):
        """
        Run the integrator. The keyword options are the same as described
        under __init__.
        """
        self.setCallOptions(options)
        used_features = Features.checkFeatures(self, self.universe)
        configuration = self.universe.configuration()
        velocities = self.universe.velocities()
        if velocities is None:
            raise ValueError("no velocities")
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()
        constraints, const_distances_sq, c_blocks = \
                     _constraintArrays(self.universe)
                                                  
        type = 'NVE'
        if Features.NoseThermostatFeature in used_features:
            type = 'NVT'
            thermostat = self.universe.environmentObjectList(
                                          Environment.NoseThermostat)[0]
            t_parameters = thermostat.parameters
            t_coordinates = thermostat.coordinates
        else:
            t_parameters = N.zeros((0,), N.Float)
            t_coordinates = N.zeros((2,), N.Float)
        if Features.AndersenBarostatFeature in used_features:
            if self.universe.cellVolume() is None:
                raise ValueError("Barostat requires finite volume universe")
            if type == 'NVE':
                type = 'NPH'
            else:
                type = 'NPT'
            barostat = self.universe.environmentObjectList(
                                          Environment.AndersenBarostat)[0]
            b_parameters = barostat.parameters
            b_coordinates = barostat.coordinates
        else:
            b_parameters = N.zeros((0,), N.Float)
            b_coordinates = N.zeros((1,), N.Float)

        args = (self.universe,
                configuration.array, velocities.array,
                masses.array, fixed.array, evaluator,
                constraints, const_distances_sq, c_blocks,
                t_parameters, t_coordinates,
                b_parameters, b_coordinates,
                self.getOption('delta_t'), self.getOption('first_step'),
                self.getOption('steps'), self.getActions(),
                type + ' dynamics trajectory with ' +
                self.optionString(['delta_t', 'steps']))
        return self.run(MMTK_dynamics.integrateVV, args)
Пример #9
0
    def __init__(self, universe=None, temperature = 300,
                 subspace = None, delta = None, sparse = False):
        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(self, universe, subspace, delta, sparse,
                                  ['array', 'force_constants'])
        self.temperature = temperature

        self.weights = N.ones((1, 1), N.Float)

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.force_constants = ev
        self.sort_index = N.argsort(self.force_constants)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
Пример #10
0
  def __call__(self, **options):
    # Process the keyword arguments
    self.setCallOptions(options)
    # Check if the universe has features not supported by the integrator
    Features.checkFeatures(self, self.universe)
  
    RT = R*self.getOption('T')
    ntrials = self.getOption('ntrials')
    natoms = self.universe.numberOfAtoms()

    acc = 0
    xo = np.copy(self.universe.configuration().array)
    com = self.universe.centerOfMass().array
    if self.sampling_universe is None:
      eo = self.universe.energy()
    else:
      self.sampling_universe.configuration().array[-natoms:,:] = xo
      eo = self.sampling_universe.energy() # <- Using sampling Hamiltonian
    
    for c in range(ntrials):
      step = np.random.randn(3)*self.step_size
      if c%2==0:
        # Random translation and full rotation
        xn = np.dot((xo - com), random_rotate()) + com + step
      else:
        # Random translation
        xn = xo + step
      if self.sampling_universe is None:
        self.universe.setConfiguration(Configuration(self.universe,xn))
        en = self.universe.energy()
      else:
        self.sampling_universe.configuration().array[-natoms:,:] = xn
        en = self.sampling_universe.energy() # <- Using sampling Hamiltonian
      if ((en<eo) or (np.random.random()<np.exp(-(en-eo)/RT))):
        acc += 1
        xo = xn
        eo = en
        com += step
      else:
        self.universe.setConfiguration(Configuration(self.universe,xo))

    return ([np.copy(xo)], [en], acc, ntrials, 0.0)
Пример #11
0
    def __call__(self, **options):
        """
        Run the integrator. The keyword options are the same as described
        under __init__.
        """
        self.setCallOptions(options)
        used_features = Features.checkFeatures(self, self.universe)
        configuration = self.universe.configuration()
        velocities = self.universe.velocities()
        if velocities is None:
            raise ValueError("no velocities")
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()
        constraints, const_distances_sq, c_blocks = \
                     _constraintArrays(self.universe)

        type = 'NVE'
        if Features.NoseThermostatFeature in used_features:
            type = 'NVT'
            thermostat = self.universe.environmentObjectList(
                Environment.NoseThermostat)[0]
            t_parameters = thermostat.parameters
            t_coordinates = thermostat.coordinates
        else:
            t_parameters = N.zeros((0, ), N.Float)
            t_coordinates = N.zeros((2, ), N.Float)
        if Features.AndersenBarostatFeature in used_features:
            if self.universe.cellVolume() is None:
                raise ValueError("Barostat requires finite volume universe")
            if type == 'NVE':
                type = 'NPH'
            else:
                type = 'NPT'
            barostat = self.universe.environmentObjectList(
                Environment.AndersenBarostat)[0]
            b_parameters = barostat.parameters
            b_coordinates = barostat.coordinates
        else:
            b_parameters = N.zeros((0, ), N.Float)
            b_coordinates = N.zeros((1, ), N.Float)

        args = (self.universe, configuration.array, velocities.array,
                masses.array, fixed.array, evaluator, constraints,
                const_distances_sq, c_blocks, t_parameters, t_coordinates,
                b_parameters, b_coordinates, self.getOption('delta_t'),
                self.getOption('first_step'), self.getOption('steps'),
                self.getActions(), type + ' dynamics trajectory with ' +
                self.optionString(['delta_t', 'steps']))
        return self.run(MMTK_dynamics.integrateVV, args)
Пример #12
0
    def __init__(self, universe = None, friction = None,
                 temperature = 300.*Units.K,
                 subspace = None, delta = None, sparse = False):
        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(self, universe, subspace, delta, sparse,
                                  ['array', 'inv_relaxation_times'])
        self.friction = friction
        self.temperature = temperature

        self.weights = N.sqrt(friction.array)
        self.weights = self.weights[:, N.NewAxis]

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.inv_relaxation_times = ev
        self.sort_index = N.argsort(self.inv_relaxation_times)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
Пример #13
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
        # Get the universe variables needed by the integrator
        configuration = self.universe.configuration()
        masses = self.universe.masses()
        velocities = self.universe.velocities()
        if velocities is None:
            raise ValueError("no velocities")

        # Get the friction coefficients. First check if a keyword argument
        # 'friction' was given to the integrator. Its value can be a
        # ParticleScalar or a plain number (used for all atoms). If no
        # such argument is given, collect the values of the attribute
        # 'friction' from all atoms (default is zero).
        try:
            friction = self.getOption('friction')
        except KeyError:
            friction = self.universe.getParticleScalar('friction')
        if not ParticleProperties.isParticleProperty(friction):
            var = ParticleProperties.ParticleScalar(self.universe)
            var.array[:] = friction
            friction = var

        # Construct a C evaluator object for the force field, using
        # the specified number of threads or the default value
        nt = self.getOption('threads')
        evaluator = self.universe.energyEvaluator(threads=nt).CEvaluator()

        # Run the C integrator
        MMTK_langevin.integrateLD(self.universe,
                                  configuration.array, velocities.array,
                                  masses.array, friction.array, evaluator,
                                  self.getOption('temperature'),
                                  self.getOption('delta_t'),
                                  self.getOption('steps'),
                                  self.getActions())
Пример #14
0
    def __init__(self,
                 universe=None,
                 temperature=300,
                 subspace=None,
                 delta=None,
                 sparse=False):
        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(self, universe, subspace, delta, sparse,
                                  ['array', 'force_constants'])
        self.temperature = temperature

        self.weights = N.ones((1, 1), N.Float)

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.force_constants = ev
        self.sort_index = N.argsort(self.force_constants)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
Пример #15
0
    def __init__(self, universe=None, temperature = 300.*Units.K,
                 subspace = None, delta = None, sparse = False):
        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(self, universe, subspace, delta, sparse,
                                  ['array', 'imaginary',
                                   'frequencies', 'omega_sq'])
        self.temperature = temperature

        self.weights = N.sqrt(self.universe.masses().array)
        self.weights = self.weights[:, N.NewAxis]

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.imaginary = N.less(ev, 0.)
        self.omega_sq = ev
        self.frequencies = N.sqrt(N.fabs(ev)) / (2.*N.pi)
        self.sort_index = N.argsort(self.frequencies)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
Пример #16
0
  def __call__(self, **options):
    if (self.confs is None) or len(self.confs)<3:
      return ([self.universe.copyConfiguration()], [self.universe.energy()], 0.0, 0.0)
    
    # Process the keyword arguments
    self.setCallOptions(options)
    # Check if the universe has features not supported by the integrator
    Features.checkFeatures(self, self.universe)
  
    RT = R*self.getOption('T')
    ntrials = self.getOption('ntrials')

    acc = 0.
    energies = []
    closest_poses = []

    xo_Cartesian = self.universe.copyConfiguration()
    xo_BAT = np.array(self._BAT_util.BAT(extended=self.extended))
    eo = self.universe.energy()
    if self.extended:
      closest_pose_o = self._closest_pose_Cartesian(\
        xo_Cartesian.array[self.molecule.heavy_atoms,:])
    else:
      closest_pose_o = self._closest_pose_BAT(xo_BAT[self._BAT_to_perturb])
      
    for t in range(ntrials):
      # Choose a pose to dart towards
      dart_towards = closest_pose_o
      while dart_towards==closest_pose_o:
        dart_towards = np.random.choice(len(self.weights), p=self.weights)
      # Generate a trial move
      xn_BAT = np.copy(xo_BAT)
      xn_BAT[self._BAT_to_perturb] = xo_BAT[self._BAT_to_perturb] + self.darts[closest_pose_o][dart_towards]
      xn_Cartesian = Configuration(self.universe,self._BAT_util.Cartesian(xn_BAT)) # Sets the universe
      en = self.universe.energy()
      if self.extended:
        closest_pose_n = self._closest_pose_Cartesian(\
          xn_Cartesian.array[self.molecule.heavy_atoms,:])
      else:
        closest_pose_n = self._closest_pose_BAT(xn_BAT[self._BAT_to_perturb])
        
      # Accept or reject the trial move
      if (en<eo) or (np.random.random()<np.exp(-(en-eo)/RT)*\
          self._p_attempt(closest_pose_n,closest_pose_o)/\
          self._p_attempt(closest_pose_o,dart_towards)):
        
        if en>(1000):
          print 'eo: %f, en: %f'%(eo,en)
          print 'closest_pose_o %d, closest_pose_n %d'%(\
            closest_pose_o,closest_pose_n)
          print '_p_attempt, forward %f, backwards %f'%(\
            self._p_attempt(closest_pose_o,dart_towards), \
            self._p_attempt(closest_pose_n,closest_pose_o))
          raise Exception('High energy pose!')
        
        xo_Cartesian = xn_Cartesian
        xo_BAT = xn_BAT
        eo = en
        closest_pose_o = closest_pose_n
        acc += 1
      else:
        self.universe.setConfiguration(xo_Cartesian)

    return ([np.copy(xo_Cartesian)], [en], float(acc)/float(ntrials), 0.0)
Пример #17
0
    def __init__(self,
                 universe=None,
                 temperature=300. * Units.K,
                 subspace=None,
                 delta=None,
                 sparse=False):
        """
        :param universe: the system for which the normal modes are calculated;
                         it must have a force field which provides the second
                         derivatives of the potential energy
        :type universe: :class:~MMTK.Universe.Universe
        :param temperature: the temperature for which the amplitudes of the
                            atomic displacement vectors are calculated. A
                            value of None can be specified to have no scaling
                            at all. In that case the mass-weighted norm
                            of each normal mode is one.
        :type temperature: float
        :param subspace: the basis for the subspace in which the normal modes
                         are calculated (or, more precisely, a set of vectors
                         spanning the subspace; it does not have to be
                         orthogonal). This can either be a sequence of
                         :class:~MMTK.ParticleProperties.ParticleVector objects
                         or a tuple of two such sequences. In the second case,
                         the subspace is defined by the space spanned by the
                         second set of vectors projected on the complement of
                         the space spanned by the first set of vectors.
                         The first set thus defines directions that are
                         excluded from the subspace.
                         The default value of None indicates a standard
                         normal mode calculation in the 3N-dimensional
                         configuration space.
        :param delta: the rms step length for numerical differentiation.
                      The default value of None indicates analytical
                      differentiation.
                      Numerical differentiation is available only when a
                      subspace basis is used as well. Instead of calculating
                      the full force constant matrix and then multiplying
                      with the subspace basis, the subspace force constant
                      matrix is obtained by numerical differentiation of the
                      energy gradients along the basis vectors of the subspace.
                      If the basis is much smaller than the full configuration
                      space, this approach needs much less memory.
        :type delta: float
        :param sparse: a flag that indicates if a sparse representation of
                       the force constant matrix is to be used. This is of
                       interest when there are no long-range interactions and
                       a subspace of smaller size then 3N is specified. In that
                       case, the calculation will use much less memory with a
                       sparse representation.
        :type sparse: bool
        """

        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(
            self, universe, subspace, delta, sparse,
            ['array', 'imaginary', 'frequencies', 'omega_sq'])
        self.temperature = temperature

        self.weights = N.sqrt(self.universe.masses().array)
        self.weights = self.weights[:, N.NewAxis]

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.imaginary = N.less(ev, 0.)
        self.omega_sq = ev
        self.frequencies = N.sqrt(N.fabs(ev)) / (2. * N.pi)
        self.sort_index = N.argsort(self.frequencies)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)

        random.seed(self.getOption('seed'))
        np.random.seed(self.getOption('seed'))
        memid = np.random.randint(2000,9999)
        np.random.seed(int(time.time() + os.getpid()))
        Random.initializeRandomNumbersFromTime()

        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
      
        RT = R*self.getOption('T')
        delta_t = self.getOption('delta_t')

        server = self.getOption('server')
        ligand_dir = self.getOption('ligand_dir')
        dyn_type = self.getOption('dyn_type')
       
        server_cmd = ''
        server_cmd = server + ' -mol2 ' + ligand_dir + 'ligand.mol2' +  ' -rb ' + ligand_dir + 'ligand.rb' + ' -gaff gaff.dat -frcmod ' + ligand_dir + 'ligand.frcmod -ictd ' + dyn_type + ' -memid ' + str(memid) + ' > tdout'
        #print server_cmd
        tdserver = subprocess.Popen(server_cmd, shell=True, preexec_fn=os.setsid)
        sleep(0.1)
 
        if 'steps_per_trial' in self.call_options.keys():
          steps_per_trial = self.getOption('steps_per_trial')
          ntrials = self.getOption('steps')/steps_per_trial
        else:
          steps_per_trial = self.getOption('steps')
          ntrials = 1
  
        if 'normalize' in self.call_options.keys():
          normalize = self.getOption('normalize')
        else:
          normalize = False          
      
        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

 
        # Deal with reordering
        #print "objectList = ", self.universe.objectList()
        #print "objectList prmtop_order = ", self.universe.objectList()[0].prmtop_order
        #print "atomList = ", self.universe.objectList()[0].atomList()
        names = []
        order = []
        for a in self.universe.objectList()[0].atomList():
          names.append(a.name)
        for i in self.universe.objectList()[0].prmtop_order:
          order.append(i.number)
        #print "names = ", names
        #print "order = ", order
        descorder = list('')
        for o in order:
          descorder = descorder + list(str(o))
          descorder = descorder + list('|')
        descorder = descorder + list('1')
        descorder = descorder + list('|')
        descorder = descorder + list(str(memid))
        descorder = descorder + list('|')
        #print descorder

      
        #print 'Py T ', self.getOption('T'), ' dt ', delta_t, ' trls ', ntrials, 'stps/trl ', steps_per_trial 

        xs = []
        energies = []
        k = 0
        acc = 0
        for t in range(ntrials):
          # Initialize the velocity
          self.universe.initializeVelocitiesToTemperature(self.getOption('T'))
          #print "Python vels= ",
          #for t in self.universe.velocities(): print t,
          #print

          # Store previous configuration and initial energy
          xo = self.universe.copyConfiguration()
          pe_o = self.universe.energy()
          eo = pe_o + self.universe.kineticEnergy()
          ke_o = self.universe.kineticEnergy()

          # Run the velocity verlet integrator
          late_args = (
                  masses.array, fixed.array, evaluator,
                  N.zeros((0, 2), N.Int), N.zeros((0, ), N.Float),
                  N.zeros((1,), N.Int),
                  N.zeros((0,), N.Float), N.zeros((2,), N.Float),
                  N.zeros((0,), N.Float), N.zeros((1,), N.Float),
                  delta_t, self.getOption('first_step'),
                  steps_per_trial, self.getActions(),
                  ''.join(descorder))
          #self.run(bTD_dynamics.integrateRKM_SPLIT,
          #tdserver = subprocess.Popen(server_cmd, shell=True, preexec_fn=os.setsid)
          #sleep(0.1)
          self.run(bTD_dynamics.integrateRKM_INTER3,
            (self.universe,
             self.universe.configuration().array,
             self.universe.velocities().array) + late_args)

          # Decide whether to accept the move
          pe_n = self.universe.energy()
          ke_n = self.universe.kineticEnergy()
          en = pe_n + ke_n
          random_number = np.random.random()
          expression = np.exp(-(en-eo)/RT)
          #expression = np.exp(-(pe_n-pe_o)/RT)
          #print ' stps Py PEo ', pe_o, ' KEo ', ke_o, ' Eo ', eo, ' PEn ', pe_n, ' KEn ', ke_n, ' En ', en, ' rand ', random_number, ' exp ', expression
          if (((en<eo) or (random_number<expression)) and (not np.isnan(en))):
          #if ((pe_n<pe_o) or (random_number<expression)): #or (t==0): # Always acc 1st step for now
            acc += 1
            #print 'Py MC acc'
            if normalize:
              self.universe.normalizeConfiguration()
            descorder[-7] = '1'
          else:
            #print 'Py MC nacc'
            self.universe.setConfiguration(xo)
            pe_n = pe_o
            descorder[-7] = '0'
          xs.append(self.universe.copyConfiguration().array)
          energies.append(pe_n)

        # Kill the server
        tdserver.terminate()
        os.killpg(tdserver.pid, signal.SIGTERM)  # Send the signal to all the process groups
        os.system('ipcrm -M ' + str(memid))      # Free shared memory
        
        #Return
        return (xs, energies, float(acc)/float(ntrials), delta_t)
Пример #19
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
      
        RT = R*self.getOption('T')
        delta_t = self.getOption('delta_t')
        
        if 'steps_per_trial' in self.call_options.keys():
          steps_per_trial = self.getOption('steps_per_trial')
          ntrials = self.getOption('steps')/steps_per_trial
        else:
          steps_per_trial = self.getOption('steps')
          ntrials = 1
  
        if 'normalize' in self.call_options.keys():
          normalize = self.getOption('normalize')
        else:
          normalize = False          

        # Seed the random number generator
        if 'random_seed' in self.call_options.keys():
          np.random.seed(self.getOption('random_seed'))
      
        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

        late_args = (
                masses.array, fixed.array, evaluator,
                N.zeros((0, 2), N.Int), N.zeros((0, ), N.Float),
                N.zeros((1,), N.Int),
                N.zeros((0,), N.Float), N.zeros((2,), N.Float),
                N.zeros((0,), N.Float), N.zeros((1,), N.Float),
                delta_t, self.getOption('first_step'),
                steps_per_trial, self.getActions(),
                'Velocity Verlet step')
      
        xs = []
        energies = []

        # Store initial configuration and potential energy
        xo = np.copy(self.universe.configuration().array)
        pe_o = self.universe.energy()
      
        acc = 0
        for t in range(ntrials):
          # Initialize the velocity
          self.universe.initializeVelocitiesToTemperature(self.getOption('T'))
          # Store total energy
          eo = pe_o + self.universe.kineticEnergy()

          # Run the velocity verlet integrator
          self.run(MMTK_dynamics.integrateVV,
            (self.universe,
             self.universe.configuration().array,
             self.universe.velocities().array) + late_args)

          # Decide whether to accept the move
          pe_n = self.universe.energy()
          en = pe_n + self.universe.kineticEnergy()
          if not np.isnan(en):
            xo = np.copy(self.universe.configuration().array)
            pe_o = pe_n
            acc += 1
            if normalize:
              self.universe.normalizePosition()
          else:
            self.universe.setConfiguration(Configuration(self.universe,xo))
          
          xs.append(np.copy(self.universe.configuration().array))
          energies.append(pe_o)
  
        return (xs, energies, acc, ntrials, delta_t)
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
      
        RT = R*self.getOption('T')
        delta_t = self.getOption('delta_t')
        
        if 'steps_per_trial' in self.call_options.keys():
          steps_per_trial = self.getOption('steps_per_trial')
          ntrials = self.getOption('steps')/steps_per_trial
        else:
          steps_per_trial = self.getOption('steps')
          ntrials = 1
  
        if 'normalize' in self.call_options.keys():
          normalize = self.getOption('normalize')
        else:
          normalize = False          

        # Seed the random number generator
        if 'random_seed' in self.call_options.keys():
          np.random.seed(self.getOption('random_seed'))

        self.universe.initializeVelocitiesToTemperature(self.getOption('T'))
        
        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

        late_args = (
                masses.array, fixed.array, evaluator,
                N.zeros((0, 2), N.Int), N.zeros((0, ), N.Float),
                N.zeros((1,), N.Int),
                N.zeros((0,), N.Float), N.zeros((2,), N.Float),
                N.zeros((0,), N.Float), N.zeros((1,), N.Float),
                delta_t, self.getOption('first_step'),
                steps_per_trial, self.getActions(),
                'Hamiltonian Monte Carlo step')

        # Variables for velocity assignment
        m3 = np.repeat(np.expand_dims(masses.array,1),3,axis=1)
        sigma_MB = np.sqrt((self.getOption('T')*Units.k_B)/m3)
        natoms = self.universe.numberOfAtoms()

        xs = []
        energies = []

        # Store initial configuration and potential energy
        xo = np.copy(self.universe.configuration().array)
        pe_o = self.universe.energy()

        acc = 0
        for t in range(ntrials):
          # Initialize the velocity
          v = self.universe.velocities()
          v.array = np.multiply(sigma_MB,np.random.randn(natoms,3))
    
          # Store total energy
          eo = pe_o + 0.5*np.sum(np.multiply(m3,np.square(v.array)))

          # Run the velocity verlet integrator
          self.run(MMTK_dynamics.integrateVV,
            (self.universe,
             self.universe.configuration().array,
             self.universe.velocities().array) + late_args)

          # Decide whether to accept the move
          pe_n = self.universe.energy()
          en = pe_n + 0.5*np.sum(np.multiply(m3,np.square(v.array)))
          
          if ((en<eo) or (np.random.random()<N.exp(-(en-eo)/RT))) and \
             ((abs(pe_o-pe_n)/RT<250.) or (abs(eo-en)/RT<250.)):
            xo = np.copy(self.universe.configuration().array)
            pe_o = pe_n
            acc += 1
            if normalize:
              self.universe.normalizePosition()
          else:
            self.universe.setConfiguration(Configuration(self.universe,xo))
          
          xs.append(np.copy(self.universe.configuration().array))
          energies.append(pe_o)
  
        return (xs, energies, acc, ntrials, delta_t)
Пример #21
0
  def __call__(self, **options):
    """
    options include:
    
    steps, 
    steps_per_trial, 
    T, 
    delta_t, 
    random_seed, 
    normalize=False, 
    adapt=False
    """
  
    # Process the keyword arguments
    self.setCallOptions(options)
    # Check if the universe has features not supported by the integrator
    Features.checkFeatures(self, self.universe)

    # Required arguments
    steps = self.getOption('steps')
    delta_t = self.getOption('delta_t')
    T = self.getOption('T')
    
    RT = R*T
    
    # Arguments with default values
    try:
      steps_per_cycle = self.getOption('steps_per_trial')
      ncycles = steps/steps_per_cycle
    except ValueError:
      steps_per_cycle = steps
      ncycles = 1

    try:
      fraction_CD = self.getOption('fraction_CD')
    except ValueError:
      fraction_CD = 0.5
      
    try:
      CD_steps_per_trial = self.getOption('CD_steps_per_trial')
    except ValueError:
      CD_steps_per_trial = 5
    
    try:
      delta_t_TD = self.getOption('delta_t_TD')
    except ValueError:
      delta_t_TD = 4.0

    # Allocate steps per cycle to TD and MD
    CD_steps_per_cycle = int(fraction_CD*steps_per_cycle)
    MD_steps_per_cycle = steps_per_cycle - CD_steps_per_cycle*CD_steps_per_trial

    if 'random_seed' in self.call_options.keys():
      random_seed = self.getOption('random_seed')
      np.random.seed(random_seed)
    else:
      import time
      random_seed = np.int(time.time()*1E3 + rand.rand()*1E3)
    
    if 'normalize' in self.call_options.keys():
      normalize = self.getOption('normalize')
    else:
      normalize = False          
    
    if self.universe.velocities() is None:
      self.universe.initializeVelocitiesToTemperature(T)
    
    # Get the universe variables needed by the integrator
    masses = self.universe.masses()
    fixed = self.universe.getAtomBooleanArray('fixed')
    nt = self.getOption('threads')
    comm = self.getOption('mpi_communicator')
    evaluator = self.universe.energyEvaluator(threads=nt,
                                              mpi_communicator=comm)
    evaluator = evaluator.CEvaluator()

    late_args = (
            masses.array, fixed.array, evaluator,
            N.zeros((0, 2), N.Int), N.zeros((0, ), N.Float),
            N.zeros((1,), N.Int),
            N.zeros((0,), N.Float), N.zeros((2,), N.Float),
            N.zeros((0,), N.Float), N.zeros((1,), N.Float),
            delta_t, self.getOption('first_step'),
            MD_steps_per_cycle, self.getActions(),
            'Mixed Hamiltonian Monte Carlo step')

    # Variables for velocity assignment
    m3 = np.repeat(np.expand_dims(masses.array,1),3,axis=1)
    sigma_MB = np.sqrt((self.getOption('T')*Units.k_B)/m3)
    natoms = self.universe.numberOfAtoms()

    xs = []
    energies = []

    CD_acc = 0
    CD_ntrials = 0
    MD_acc = 0
    for t in range(ncycles):
      # Do the constrained dynamics steps
      (CD_xs_c, CD_energies_c, CD_acc_c, CD_ntrials_c, CD_dts) = \
        self.TDintegrator.Call(CD_steps_per_cycle, CD_steps_per_trial, \
          T, delta_t_TD/1000., (random_seed+t)%32767, 1, 1, 0.5)
      xs.extend(CD_xs_c)
      energies.extend(CD_energies_c)
      CD_acc += CD_acc_c
      CD_ntrials += CD_ntrials_c

      # Store initial configuration and potential energy
      xo = np.copy(self.universe.configuration().array)
      pe_o = self.universe.energy()

      # Initialize the velocity
      v = self.universe.velocities()
      v.array = np.multiply(sigma_MB,np.random.randn(natoms,3))

      # Store total energy
      eo = pe_o + 0.5*np.sum(np.multiply(m3,np.square(v.array)))

      # Run the velocity verlet integrator
      self.run(MMTK_dynamics.integrateVV,
        (self.universe,
         self.universe.configuration().array,
         self.universe.velocities().array) + late_args)

      # Decide whether to accept the move
      pe_n = self.universe.energy()
      en = pe_n + 0.5*np.sum(np.multiply(m3,np.square(v.array)))
      
      if ((en<eo) or (np.random.random()<N.exp(-(en-eo)/RT))) and \
         ((abs(pe_o-pe_n)/RT<250.) or (abs(eo-en)/RT<250.)):
        xo = np.copy(self.universe.configuration().array)
        pe_o = pe_n
        MD_acc += 1
        if normalize:
          self.universe.normalizePosition()
      else:
        self.universe.setConfiguration(Configuration(self.universe,xo))
      
      xs.append(np.copy(self.universe.configuration().array))
      energies.append(pe_o)
      
    # print 'TD: %d/%d, MD: %d/%d'%(CD_acc,CD_ntrials,MD_acc,ncycles)
    return (xs, energies, CD_acc + MD_acc, CD_ntrials + ncycles, delta_t)
Пример #22
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)

        #the following two lines are required due to MMTK mixing up atom indices.  This sorts them.
        #atoms = self.universe.atomList()
        #atoms.sort(key=operator.attrgetter('index'))

        # Get the universe variables needed by the integrator
        configuration = self.universe.configuration()
        velocities = self.universe.velocities()
        if velocities is None:
            raise ValueError("no velocities")

        # Get the friction coefficients. First check if a keyword argument
        # 'friction' was given to the integrator. Its value can be a
        # ParticleScalar or a plain number (used for all atoms). If no
        # such argument is given, collect the values of the attribute
        # 'friction' from all atoms (default is zero).
        friction = self.getOption('friction')

        #call this method to create the OpenMM System.  Without this, creating
        #the forces will fail!!
        self.initOmmSystem()

        #call this method to ensure that the forcefield parameters get
        #passed to OpenMM.  Without this, there will be no forces to integrate!
        self.createOmmForces()

        #The restraint option must be included in the creation of the integrator for this part to be executed
        try:
            restraint = self.getOption('restraint')
        except ValueError:
            restraint = None
            print 'No restraints (Value Error)'
        except:
            print sys.exc_info()[0]
        if restraint != None:
            self.addRestraint(restraint)

        #ugly hack to get timestep skip information
        skip = -1
        if ('actions' in self.call_options):
            actions = self.call_options['actions']
            for action in actions:
                if isinstance(action, Dynamics.TranslationRemover):
                    self.addOmmCMRemover(action.skip)
                if isinstance(action, Trajectory.LogOutput):
                    break  # to avoid Logoutput skip setting problem PNR NFF SJC
                if isinstance(action, Trajectory.TrajectoryOutput):
                    skip = action.skip
                    action.skip = 1

            if skip < 0:
                for action in actions:
                    if issubclass(action.__class__,
                                  Trajectory.TrajectoryOutput):
                        skip = action.skip
                        action.skip = 1
                        break

        #we are not logging anything, so we don't have to report any intermediate values
        if skip < 0:
            skip = 100
            steps = 1

        # Run the C integrator
        atoms = self.universe.atomList()
        masses = [atom.mass() for atom in atoms]
        natoms = len(atoms)
        nmolecules = len(self.universe.objectList(Molecule))
        molecule_lengths = N.zeros(nmolecules, dtype=N.int32, order='C')
        for i in range(0, len(self.universe.objectList(Molecule))):
            molecule_lengths[i] = len(
                self.universe.objectList(Molecule)[i].atomList())

        MMTK_langevin.integrateLD(self.universe, configuration.array,
                                  velocities.array,
                                  N.array(masses, dtype=N.float64), friction,
                                  self.getOption('temperature'),
                                  self.getOption('delta_t'),
                                  self.getOption('steps'), skip, natoms,
                                  self.nbeads, nmolecules, molecule_lengths,
                                  self.getActions())

        #call this to clean up after ourselves
        self.destroyOmmSystem()
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
        
        #the following two lines are required due to MMTK mixing up atom indices.  This sorts them.
        #atoms = self.universe.atomList()
        #atoms.sort(key=operator.attrgetter('index'))
        
        # Get the universe variables needed by the integrator
        configuration = self.universe.configuration()
        velocities = self.universe.velocities()
        if velocities is None:
            raise ValueError("no velocities")

        # Get the friction coefficients. First check if a keyword argument
        # 'friction' was given to the integrator. Its value can be a
        # ParticleScalar or a plain number (used for all atoms). If no
        # such argument is given, collect the values of the attribute
        # 'friction' from all atoms (default is zero).
        friction = self.getOption('friction')  
        
        #call this method to create the OpenMM System.  Without this, creating
        #the forces will fail!!
        self.initOmmSystem()
        
        
        #call this method to ensure that the forcefield parameters get
        #passed to OpenMM.  Without this, there will be no forces to integrate!
        self.createOmmForces()

        #The restraint option must be included in the creation of the integrator for this part to be executed
        try:
            restraint = self.getOption('restraint')
        except ValueError:
            restraint = None
            print 'No restraints (Value Error)'
        except:
            print sys.exc_info()[0]
        if restraint != None:
            self.addRestraint(restraint) 
        
        #ugly hack to get timestep skip information
        skip = -1
        if ('actions' in self.call_options):
            actions = self.call_options['actions']
            for action in actions:
                if isinstance(action, Dynamics.TranslationRemover):
                    self.addOmmCMRemover(action.skip)
                if isinstance(action, Trajectory.LogOutput):
                    break # to avoid Logoutput skip setting problem PNR NFF SJC
                if isinstance(action, Trajectory.TrajectoryOutput):
                    skip = action.skip
                    action.skip = 1
        
            if skip < 0 :
                for action in actions:
                    if issubclass(action.__class__, Trajectory.TrajectoryOutput):
                        skip = action.skip
                        action.skip = 1
                        break
        
        #we are not logging anything, so we don't have to report any intermediate values
        if skip < 0:
            skip = 100
            steps = 1

        # Run the C integrator
        atoms = self.universe.atomList()
        masses = [atom.mass() for atom in atoms]
        natoms = len(atoms)
        nmolecules = len(self.universe.objectList(Molecule))
        molecule_lengths = N.zeros(nmolecules, dtype=N.int32, order='C')
        for i in range(0,len(self.universe.objectList(Molecule))):
            molecule_lengths[i] = len(self.universe.objectList(Molecule)[i].atomList())

        MMTK_langevin.integrateLD(self.universe, configuration.array, 
                                  velocities.array, N.array(masses, dtype=N.float64), 
                                  friction,
                                  self.getOption('temperature'),
                                  self.getOption('delta_t'),
                                  self.getOption('steps'), skip, natoms, self.nbeads,
                                  nmolecules, molecule_lengths,
                                  self.getActions())
        
        #call this to clean up after ourselves
        self.destroyOmmSystem()
Пример #24
0
    def __call__(self, **options):
        if (self.confs is None) or len(self.confs) < 2:
            return ([self.universe.configuration().array], [self.universe.energy()], \
              0, 0, 0.0)

        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)

        RT = R * self.getOption('T')
        ntrials = min(self.getOption('ntrials'), len(self.confs))

        # Seed the random number generator
        if 'random_seed' in self.call_options.keys():
            np.random.seed(self.getOption('random_seed'))

        acc = 0.
        energies = []
        closest_poses = []

        xo_Cartesian = np.copy(self.universe.configuration().array)
        if self.extended:
            (closest_pose_o, distance_o) = self._closest_pose_Cartesian(\
              xo_Cartesian[self.molecule.heavy_atoms,:])
        else:
            xo_BAT = self._BAT_util.BAT(xo_Cartesian, extended=self.extended)
            (closest_pose_o,
             distance_o) = self._closest_pose_BAT(xo_BAT[self._BAT_to_perturb])

        # Only attempt smart darting within
        # a sphere of radius epsilon of the minimum
        if distance_o > self.epsilon:
            return ([self.universe.configuration().array], [self.universe.energy()], \
              0, 0, 0.0)

        if self.extended:
            xo_BAT = self._BAT_util.BAT(xo_Cartesian, extended=self.extended)
        eo = self.universe.energy()

        #    report = ''
        for t in range(ntrials):
            # Choose a pose to dart towards
            dart_towards = closest_pose_o
            while dart_towards == closest_pose_o:
                dart_towards = np.random.choice(len(self.weights),
                                                p=self.weights)
            # Generate a trial move
            xn_BAT = np.copy(xo_BAT)
            xn_BAT[self._BAT_to_perturb] = xo_BAT[
                self.
                _BAT_to_perturb] + self.darts[closest_pose_o][dart_towards]

            # Check that the trial move is closest to dart_towards
            if self.extended:
                xn_Cartesian = self._BAT_util.Cartesian(xn_BAT)
                (closest_pose_n, distance_n) = self._closest_pose_Cartesian(\
                  xn_Cartesian[self.molecule.heavy_atoms,:])
                if (closest_pose_n != dart_towards):
                    print '    attempted dart from pose %d (%f) to pose %d'%(\
                      closest_pose_o,distance_o,dart_towards) + \
                      ' landed near pose %d (%f)!'%(closest_pose_n, distance_n)
                    continue
            else:
                (closest_pose_n, distance_n) = self._closest_pose_BAT(\
                  xn_BAT[self._BAT_to_perturb])
                if (closest_pose_n != dart_towards):
                    print '    attempted dart from pose %d (%f) to pose %d'%(\
                      closest_pose_o,distance_o,dart_towards) + \
                      ' landed near pose %d (%f)!'%(closest_pose_n, distance_n)
                    continue
                xn_Cartesian = self._BAT_util.Cartesian(xn_BAT)

            # Determine energy of new state
            self.universe.setConfiguration(
                Configuration(self.universe, xn_Cartesian))
            en = self.universe.energy()
            #      report += 'Attempting move from near pose %d with energy %f to pose %d with energy %f. '%(closest_pose_o,eo,closest_pose_n,en)

            # Accept or reject the trial move
            if (abs(en-eo)<1000) and \
                ((en<eo) or (np.random.random()<np.exp(-(en-eo)/RT)*\
                  self._p_attempt(closest_pose_n,closest_pose_o)/\
                  self._p_attempt(closest_pose_o,closest_pose_n))):
                xo_Cartesian = xn_Cartesian
                xo_BAT = xn_BAT
                eo = 1. * en
                closest_pose_o = closest_pose_n
                distance_o = distance_n
                acc += 1


#        report += 'Accepted.\n'
#      else:
#        report += 'Rejected.\n'
#
#    print report
        self.universe.setConfiguration(
            Configuration(self.universe, xo_Cartesian))
        return ([np.copy(xo_Cartesian)], [eo], acc, ntrials, 0.0)
Пример #25
0
    def __init__(self, universe = None, friction = None,
                 temperature = 300.*Units.K,
                 subspace = None, delta = None, sparse = False):
        """
        :param universe: the system for which the normal modes are calculated;
                         it must have a force field which provides the second
                         derivatives of the potential energy
        :type universe: :class:`~MMTK.Universe.Universe`
        :param friction: the friction coefficient for each particle.
                         Note: The friction coefficients are not mass-weighted,
                         i.e. they have the dimension of an inverse time.
        :type friction: :class:`~MMTK.ParticleProperties.ParticleScalar`
        :param temperature: the temperature for which the amplitudes of the
                            atomic displacement vectors are calculated. A
                            value of None can be specified to have no scaling
                            at all. In that case the mass-weighted norm
                            of each normal mode is one.
        :type temperature: float
        :param subspace: the basis for the subspace in which the normal modes
                         are calculated (or, more precisely, a set of vectors
                         spanning the subspace; it does not have to be
                         orthogonal). This can either be a sequence of
                         :class:`~MMTK.ParticleProperties.ParticleVector` objects
                         or a tuple of two such sequences. In the second case,
                         the subspace is defined by the space spanned by the
                         second set of vectors projected on the complement of
                         the space spanned by the first set of vectors.
                         The first set thus defines directions that are
                         excluded from the subspace.
                         The default value of None indicates a standard
                         normal mode calculation in the 3N-dimensional
                         configuration space.
        :param delta: the rms step length for numerical differentiation.
                      The default value of None indicates analytical
                      differentiation.
                      Numerical differentiation is available only when a
                      subspace basis is used as well. Instead of calculating
                      the full force constant matrix and then multiplying
                      with the subspace basis, the subspace force constant
                      matrix is obtained by numerical differentiation of the
                      energy gradients along the basis vectors of the subspace.
                      If the basis is much smaller than the full configuration
                      space, this approach needs much less memory.
        :type delta: float
        :param sparse: a flag that indicates if a sparse representation of
                       the force constant matrix is to be used. This is of
                       interest when there are no long-range interactions and
                       a subspace of smaller size then 3N is specified. In that
                       case, the calculation will use much less memory with a
                       sparse representation.
        :type sparse: bool
        """

        if universe == None:
            return
        Features.checkFeatures(self, universe)
        Core.NormalModes.__init__(self, universe, subspace, delta, sparse,
                                  ['array', 'inv_relaxation_times'])
        self.friction = friction
        self.temperature = temperature

        self.weights = N.sqrt(friction.array)
        self.weights = self.weights[:, N.NewAxis]

        self._forceConstantMatrix()
        ev = self._diagonalize()

        self.inv_relaxation_times = ev
        self.sort_index = N.argsort(self.inv_relaxation_times)
        self.array.shape = (self.nmodes, self.natoms, 3)

        self.cleanup()
Пример #26
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
      
        RT = R*self.getOption('T')
        delta_t = self.getOption('delta_t')
        
        if 'steps_per_trial' in self.call_options.keys():
          steps_per_trial = self.getOption('steps_per_trial')
          ntrials = self.getOption('steps')/steps_per_trial
        else:
          steps_per_trial = self.getOption('steps')
          ntrials = 1
  
        if 'normalize' in self.call_options.keys():
          normalize = self.getOption('normalize')
        else:
          normalize = False          

        # Seed the random number generator
        if 'random_seed' in self.call_options.keys():
          np.random.seed(self.getOption('random_seed'))

        self.universe.initializeVelocitiesToTemperature(self.getOption('T'))
        
        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

        late_args = (
                masses.array, fixed.array, evaluator,
                N.zeros((0, 2), N.Int), N.zeros((0, ), N.Float),
                N.zeros((1,), N.Int),
                N.zeros((0,), N.Float), N.zeros((2,), N.Float),
                N.zeros((0,), N.Float), N.zeros((1,), N.Float),
                delta_t, self.getOption('first_step'),
                steps_per_trial, self.getActions(),
                'Hamiltonian Monte Carlo step')

        # Variables for velocity assignment
        m3 = np.repeat(np.expand_dims(masses.array,1),3,axis=1)
        sigma_MB = np.sqrt((self.getOption('T')*Units.k_B)/m3)
        natoms = self.universe.numberOfAtoms()

        xs = []
        energies = []

        # Store initial configuration and potential energy
        xo = np.copy(self.universe.configuration().array)
        self.sampling_universe.configuration().array[-natoms:,:] = xo
        pe_o = self.sampling_universe.energy() # <- Using sampling Hamiltonian
                                            # rather than guidance Hamiltonian

        acc = 0
        for t in range(ntrials):
          # Initialize the velocity
          v = self.universe.velocities()
          v.array = np.multiply(sigma_MB,np.random.randn(natoms,3))
    
          # Store total energy
          eo = pe_o + 0.5*np.sum(np.multiply(m3,np.square(v.array)))

          # Run the velocity verlet integrator
          self.run(MMTK_dynamics.integrateVV,
            (self.universe,
             self.universe.configuration().array,
             self.universe.velocities().array) + late_args)

          # Decide whether to accept the move
          self.sampling_universe.configuration().array[-natoms:,:] = \
            self.universe.configuration().array
          pe_n = self.sampling_universe.energy() # <- Using sampling Hamiltonian
                                              # rather than guidance Hamiltonian
          en = pe_n + 0.5*np.sum(np.multiply(m3,np.square(v.array)))

          # TODO: Confirm acceptance criterion
          if ((en<eo) or (np.random.random()<N.exp(-(en-eo)/RT))) and \
             ((abs(pe_o-pe_n)/RT<250.) or (abs(eo-en)/RT<250.)):
            xo = np.copy(self.universe.configuration().array)
            pe_o = pe_n
            acc += 1
            if normalize:
              self.universe.normalizePosition()
          else:
            self.universe.setConfiguration(Configuration(self.universe,xo))
          
          xs.append(np.copy(self.universe.configuration().array))
          energies.append(pe_o)
  
        return (xs, energies, acc, ntrials, delta_t)
Пример #27
0
  def __call__(self, **options):
    if (self.confs is None) or len(self.confs)<2:
      return ([self.universe.configuration().array], [self.universe.energy()], \
        0, 0, 0.0)
    
    # Process the keyword arguments
    self.setCallOptions(options)
    # Check if the universe has features not supported by the integrator
    Features.checkFeatures(self, self.universe)
  
    RT = R*self.getOption('T')
    ntrials = min(self.getOption('ntrials'), len(self.confs))

    # Seed the random number generator
    if 'random_seed' in self.call_options.keys():
      np.random.seed(self.getOption('random_seed'))

    acc = 0.
    energies = []
    closest_poses = []

    xo_Cartesian = np.copy(self.universe.configuration().array)
    if self.extended:
      (closest_pose_o, distance_o) = self._closest_pose_Cartesian(\
        xo_Cartesian[self.molecule.heavy_atoms,:])
    else:
      xo_BAT = self._BAT_util.BAT(xo_Cartesian, extended=self.extended)
      (closest_pose_o, distance_o) = self._closest_pose_BAT(xo_BAT[self._BAT_to_perturb])

    # Only attempt smart darting within
    # a sphere of radius epsilon of the minimum
    if distance_o > self.epsilon:
      return ([self.universe.configuration().array], [self.universe.energy()], \
        0, 0, 0.0)

    if self.extended:
      xo_BAT = self._BAT_util.BAT(xo_Cartesian, extended=self.extended)
    eo = self.universe.energy()

#    report = ''
    for t in range(ntrials):
      # Choose a pose to dart towards
      dart_towards = closest_pose_o
      while dart_towards==closest_pose_o:
        dart_towards = np.random.choice(len(self.weights), p=self.weights)
      # Generate a trial move
      xn_BAT = np.copy(xo_BAT)
      xn_BAT[self._BAT_to_perturb] = xo_BAT[self._BAT_to_perturb] + self.darts[closest_pose_o][dart_towards]

      # Check that the trial move is closest to dart_towards
      if self.extended:
        xn_Cartesian = self._BAT_util.Cartesian(xn_BAT)
        (closest_pose_n, distance_n) = self._closest_pose_Cartesian(\
          xn_Cartesian[self.molecule.heavy_atoms,:])
        if (closest_pose_n!=dart_towards):
          print '    attempted dart from pose %d (%f) to pose %d'%(\
            closest_pose_o,distance_o,dart_towards) + \
            ' landed near pose %d (%f)!'%(closest_pose_n, distance_n)
          continue
      else:
        (closest_pose_n, distance_n) = self._closest_pose_BAT(\
          xn_BAT[self._BAT_to_perturb])
        if (closest_pose_n!=dart_towards):
          print '    attempted dart from pose %d (%f) to pose %d'%(\
            closest_pose_o,distance_o,dart_towards) + \
            ' landed near pose %d (%f)!'%(closest_pose_n, distance_n)
          continue
        xn_Cartesian = self._BAT_util.Cartesian(xn_BAT)

      # Determine energy of new state
      self.universe.setConfiguration(Configuration(self.universe, xn_Cartesian))
      en = self.universe.energy()
#      report += 'Attempting move from near pose %d with energy %f to pose %d with energy %f. '%(closest_pose_o,eo,closest_pose_n,en)

      # Accept or reject the trial move
      if (abs(en-eo)<1000) and \
          ((en<eo) or (np.random.random()<np.exp(-(en-eo)/RT)*\
            self._p_attempt(closest_pose_n,closest_pose_o)/\
            self._p_attempt(closest_pose_o,closest_pose_n))):
        xo_Cartesian = xn_Cartesian
        xo_BAT = xn_BAT
        eo = 1.*en
        closest_pose_o = closest_pose_n
        distance_o = distance_n
        acc += 1
#        report += 'Accepted.\n'
#      else:
#        report += 'Rejected.\n'
#
#    print report
    self.universe.setConfiguration(Configuration(self.universe, xo_Cartesian))
    return ([np.copy(xo_Cartesian)], [eo], acc, ntrials, 0.0)
Пример #28
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)

        RT = R * self.getOption('T')
        delta_t = self.getOption('delta_t')

        if 'steps_per_trial' in self.call_options.keys():
            steps_per_trial = self.getOption('steps_per_trial')
            ntrials = self.getOption('steps') / steps_per_trial
        else:
            steps_per_trial = self.getOption('steps')
            ntrials = 1

        if 'max_diff' in self.call_options.keys():
            max_diff = self.getOption('max_diff')
        else:
            max_diff = 1000.

        if 'normalize' in self.call_options.keys():
            normalize = self.getOption('normalize')
        else:
            normalize = False

        # Seed the random number generator
        if 'random_seed' in self.call_options.keys():
            np.random.seed(self.getOption('random_seed'))

        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

        late_args = (masses.array, fixed.array, evaluator,
                     N.zeros((0, 2), N.Int), N.zeros(
                         (0, ), N.Float), N.zeros((1, ), N.Int),
                     N.zeros((0, ), N.Float), N.zeros(
                         (2, ), N.Float), N.zeros(
                             (0, ), N.Float), N.zeros((1, ), N.Float), delta_t,
                     self.getOption('first_step'), steps_per_trial,
                     self.getActions(), 'Velocity Verlet step')

        xs = []
        energies = []

        # Store initial configuration and potential energy
        xo = np.copy(self.universe.configuration().array)
        pe_o = self.universe.energy()

        acc = 0
        for t in range(ntrials):
            # Initialize the velocity
            self.universe.initializeVelocitiesToTemperature(
                self.getOption('T'))
            # Store total energy
            eo = pe_o + self.universe.kineticEnergy()

            # Run the velocity verlet integrator
            self.run(MMTK_dynamics.integrateVV,
                     (self.universe, self.universe.configuration().array,
                      self.universe.velocities().array) + late_args)

            # Decide whether to accept the move
            pe_n = self.universe.energy()
            en = pe_n + self.universe.kineticEnergy()

            diff = np.abs(en - eo)

            if (not np.isnan(en)) and (diff < max_diff):
                xo = np.copy(self.universe.configuration().array)
                pe_o = pe_n
                acc += 1
                if normalize:
                    self.universe.normalizePosition()
            else:
                # print diff
                self.universe.setConfiguration(Configuration(
                    self.universe, xo))

            xs.append(np.copy(self.universe.configuration().array))
            energies.append(pe_o)

        return (xs, energies, acc, ntrials, delta_t)
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)

        random.seed(self.getOption('seed'))
        np.random.seed(self.getOption('seed'))
        memid = np.random.randint(2000, 9999)
        np.random.seed(int(time.time() + os.getpid()))
        Random.initializeRandomNumbersFromTime()

        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)

        RT = R * self.getOption('T')
        delta_t = self.getOption('delta_t')

        server = self.getOption('server')
        ligand_dir = self.getOption('ligand_dir')
        dyn_type = self.getOption('dyn_type')

        server_cmd = ''
        server_cmd = server + ' -mol2 ' + ligand_dir + 'ligand.mol2' + ' -rb ' + ligand_dir + 'ligand.rb' + ' -gaff gaff.dat -frcmod ' + ligand_dir + 'ligand.frcmod -ictd ' + dyn_type + ' -memid ' + str(
            memid) + ' > tdout'
        #print server_cmd
        tdserver = subprocess.Popen(server_cmd,
                                    shell=True,
                                    preexec_fn=os.setsid)
        sleep(0.1)

        if 'steps_per_trial' in self.call_options.keys():
            steps_per_trial = self.getOption('steps_per_trial')
            ntrials = self.getOption('steps') / steps_per_trial
        else:
            steps_per_trial = self.getOption('steps')
            ntrials = 1

        if 'normalize' in self.call_options.keys():
            normalize = self.getOption('normalize')
        else:
            normalize = False

        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

        # Deal with reordering
        #print "objectList = ", self.universe.objectList()
        #print "objectList prmtop_order = ", self.universe.objectList()[0].prmtop_order
        #print "atomList = ", self.universe.objectList()[0].atomList()
        names = []
        order = []
        for a in self.universe.objectList()[0].atomList():
            names.append(a.name)
        for i in self.universe.objectList()[0].prmtop_order:
            order.append(i.number)
        #print "names = ", names
        #print "order = ", order
        descorder = list('')
        for o in order:
            descorder = descorder + list(str(o))
            descorder = descorder + list('|')
        descorder = descorder + list('1')
        descorder = descorder + list('|')
        descorder = descorder + list(str(memid))
        descorder = descorder + list('|')
        #print descorder

        #print 'Py T ', self.getOption('T'), ' dt ', delta_t, ' trls ', ntrials, 'stps/trl ', steps_per_trial

        xs = []
        energies = []
        k = 0
        acc = 0
        for t in range(ntrials):
            # Initialize the velocity
            self.universe.initializeVelocitiesToTemperature(
                self.getOption('T'))
            #print "Python vels= ",
            #for t in self.universe.velocities(): print t,
            #print

            # Store previous configuration and initial energy
            xo = self.universe.copyConfiguration()
            pe_o = self.universe.energy()
            eo = pe_o + self.universe.kineticEnergy()
            ke_o = self.universe.kineticEnergy()

            # Run the velocity verlet integrator
            late_args = (masses.array, fixed.array, evaluator,
                         N.zeros((0, 2), N.Int), N.zeros(
                             (0, ), N.Float), N.zeros(
                                 (1, ), N.Int), N.zeros((0, ), N.Float),
                         N.zeros((2, ), N.Float), N.zeros(
                             (0, ), N.Float), N.zeros((1, ), N.Float), delta_t,
                         self.getOption('first_step'), steps_per_trial,
                         self.getActions(), ''.join(descorder))
            #self.run(bTD_dynamics.integrateRKM_SPLIT,
            #tdserver = subprocess.Popen(server_cmd, shell=True, preexec_fn=os.setsid)
            #sleep(0.1)
            self.run(bTD_dynamics.integrateRKM_INTER3,
                     (self.universe, self.universe.configuration().array,
                      self.universe.velocities().array) + late_args)

            # Decide whether to accept the move
            pe_n = self.universe.energy()
            ke_n = self.universe.kineticEnergy()
            en = pe_n + ke_n
            random_number = np.random.random()
            expression = np.exp(-(en - eo) / RT)
            #expression = np.exp(-(pe_n-pe_o)/RT)
            #print ' stps Py PEo ', pe_o, ' KEo ', ke_o, ' Eo ', eo, ' PEn ', pe_n, ' KEn ', ke_n, ' En ', en, ' rand ', random_number, ' exp ', expression
            if (((en < eo) or (random_number < expression))
                    and (not np.isnan(en))):
                #if ((pe_n<pe_o) or (random_number<expression)): #or (t==0): # Always acc 1st step for now
                acc += 1
                #print 'Py MC acc'
                if normalize:
                    self.universe.normalizeConfiguration()
                descorder[-7] = '1'
            else:
                #print 'Py MC nacc'
                self.universe.setConfiguration(xo)
                pe_n = pe_o
                descorder[-7] = '0'
            xs.append(self.universe.copyConfiguration().array)
            energies.append(pe_n)

        # Kill the server
        tdserver.terminate()
        os.killpg(tdserver.pid,
                  signal.SIGTERM)  # Send the signal to all the process groups
        os.system('ipcrm -M ' + str(memid))  # Free shared memory

        #Return
        return (xs, energies, float(acc) / float(ntrials), delta_t)
Пример #30
0
    def __call__(self, **options):
        # Process the keyword arguments
        self.setCallOptions(options)
        # Check if the universe has features not supported by the integrator
        Features.checkFeatures(self, self.universe)
      
        RT = R*self.getOption('T')
        delta_t = self.getOption('delta_t')
        
        if 'steps_per_trial' in self.call_options.keys():
          steps_per_trial = self.getOption('steps_per_trial')
          ntrials = self.getOption('steps')/steps_per_trial
        else:
          steps_per_trial = self.getOption('steps')
          ntrials = 1
  
        if 'normalize' in self.call_options.keys():
          normalize = self.getOption('normalize')
        else:
          normalize = False          
      
        # Get the universe variables needed by the integrator
        masses = self.universe.masses()
        fixed = self.universe.getAtomBooleanArray('fixed')
        nt = self.getOption('threads')
        comm = self.getOption('mpi_communicator')
        evaluator = self.universe.energyEvaluator(threads=nt,
                                                  mpi_communicator=comm)
        evaluator = evaluator.CEvaluator()

        late_args = (
                masses.array, fixed.array, evaluator,
                N.zeros((0, 2), N.Int), N.zeros((0, ), N.Float),
                N.zeros((1,), N.Int),
                N.zeros((0,), N.Float), N.zeros((2,), N.Float),
                N.zeros((0,), N.Float), N.zeros((1,), N.Float),
                delta_t, self.getOption('first_step'),
                steps_per_trial, self.getActions(),
                'Velocity Verlet step')
      
        xs = []
        energies = []
      
        acc = 0
        for t in range(ntrials):
          # Initialize the velocity
          self.universe.initializeVelocitiesToTemperature(self.getOption('T'))

          # Store previous configuration and initial energy
          xo = self.universe.copyConfiguration()
          pe_o = self.universe.energy()
          eo = pe_o + self.universe.kineticEnergy()

          # Run the velocity verlet integrator
          self.run(MMTK_dynamics.integrateVV,
            (self.universe,
             self.universe.configuration().array,
             self.universe.velocities().array) + late_args)

          # Decide whether to accept the move
          pe_n = self.universe.energy()
          en = pe_n + self.universe.kineticEnergy()
          if not math.isnan(en):
            acc += 1
            if normalize:
              self.universe.normalizePosition()
          else:
            self.universe.setConfiguration(xo)
            pe_n = pe_o
          xs.append(self.universe.copyConfiguration().array)
          energies.append(pe_n)
  
        return (xs, energies, float(acc)/float(ntrials), delta_t)