Esempio n. 1
0
    def setX(self, xVec):
        currentParams = AmberParm(self.currentPrmtop)

        for x, p in zip(xVec, self.parameter2optimize):
            if p.kind == "bond":
                for b in currentParams.bonds:
                    if set([b.atom1.type, b.atom2.type]) == p.atomMask:
                        if p.valueType == "req":
                            b.type.req = x
                        elif p.valueType == "kr":
                            b.type.k = x

                        break

            elif p.kind == "angle":
                for a in currentParams.angles:
                    angleTypes = [a.atom1.type, a.atom2.type, a.atom3]
                    angleTypesRev = reversed(angleTypes)
                    if angleTypes == p.atomMask or angleTypesRev == p.atomMask:
                        if p.valueType == "kt":
                            a.type.k = x
                        elif p.valueType == "theq":
                            a.type.theteq = x

                        break

        currentParams.write_parm(self.currentPrmtop)
Esempio n. 2
0
    def test_gas_energy_conf_2(self):
        """ Compare Amber and OpenMM gas phase energies and forces (topology 2) """
        parm = AmberParm(get_fn('hydrogen-peroxide_T0_2.prmtop'), get_fn('hydrogen-peroxide_T0_2.rst7'))
        self.assertEqual(parm.combining_rule, 'lorentz')
        system = parm.createSystem() # Default, no cutoff
        integrator = mm.VerletIntegrator(1.0*u.femtoseconds)
        sim = app.Simulation(parm.topology, system, integrator, platform=CPU)
        sim.context.setPositions(parm.positions)
        energies = energy_decomposition(parm, sim.context)
#BOND    =        0.0319  ANGLE   =        2.1690  DIHED      =       -2.7931
#VDWAALS =        0.0000  EEL     =        0.0000  HBOND      =        0.0000
#1-4 VDW =        0.0000  1-4 EEL =        0.0000  RESTRAINT  =        0.0000
        # Compare OpenMM energies with the Amber energies (above)
        self.assertAlmostEqual(energies['bond'], 0.0319, places=4)
        self.assertAlmostEqual(energies['angle'], 2.1690, places=4)
        self.assertAlmostEqual(energies['dihedral'],-2.7931, places=4)
        self.assertRelativeEqual(energies['nonbonded'], 0.0, places=3)

        # Now test the forces to make sure that they are computed correctly in
        # the presence of extra points
        pstate = sim.context.getState(getForces=True)
        pf = pstate.getForces().value_in_unit(u.kilojoule_per_mole/u.nanometer)
# gmx forces:
#     f[    0]={ 3.14357e+02, -5.90363e+02,  2.11410e+02}
#     f[    1]={-3.14357e+02,  5.90363e+02,  2.11410e+02}
#     f[    2]={ 2.70641e+02,  5.90363e+02, -2.11410e+02}
#     f[    3]={-2.70641e+02, -5.90363e+02, -2.11410e+02}
        gf = [  ( 3.14357e+02, -5.90363e+02,  2.11410e+02), 
                (-3.14357e+02,  5.90363e+02,  2.11410e+02), 
                ( 2.70641e+02,  5.90363e+02, -2.11410e+02), 
                (-2.70641e+02, -5.90363e+02, -2.11410e+02)] 
        for p, s in zip(pf, gf):
            for x1, x2 in zip(p, s):
                self.assertAlmostEqual(x1, x2, places=3)
Esempio n. 3
0
 def setup_hmr(self):
     if not SETTINGS["md"]["use_hmr"]:
         return
     top_file = SETTINGS["data_files"]["top_file"]
     logger.info(f"Applying HMR on topology file {top_file}")
     parm = AmberParm(top_file)
     HMassRepartition(parm).execute()
     parm.write_parm(top_file)
     logger.info("HMR applied")
def main():

    prmtop_filename = '<topology>'
    crd_filename = '<coordinate>'

    prmtop = AmberParm(prmtop_filename, crd_filename)

    system = prmtop.createSystem(nonbondedMethod=app.PME, nonbondedCutoff=10*unit.angstrom,
                                 constraints=app.HBonds, switchDistance=8*unit.angstrom)

    temperature = 300 * unit.kelvin
    pressure = 1 * unit.atmosphere
    collision_rate = 5 / unit.picosecond
    timestep = 2 * unit.femtosecond

    integrator = openmm.LangevinIntegrator(temperature, collision_rate, timestep)
    barostat = openmm.MonteCarloBarostat(temperature, pressure)
    system.addForce(barostat)

    system.setDefaultPeriodicBoxVectors(*prmtop.box_vectors)

    simulation = app.Simulation(prmtop.topology, system, integrator)

    simulation.context.setPositions(prmtop.positions)
    simulation.context.setVelocitiesToTemperature(temperature)

    print('System contains {} atoms.'.format(system.getNumParticles()))
    print('Using platform "{}".'.format(simulation.context.getPlatform().getName()))

    print('Minimizing energy to avoid clashes.')
    simulation.minimizeEnergy(maxIterations=100)

    print('Initial potential energy is {}'.format(simulation.context.getState(getEnergy=True).getPotentialEnergy()))

    # Warm up the integrator to compile kernels, etc
    print('Warming up integrator to trigger kernel compilation...')
    simulation.step(10)

    # Time integration
    print('Benchmarking...')
    nsteps = <numsteps>
    initial_time = time.time()
    integrator.step(nsteps)
    final_time = time.time()
    elapsed_time = (final_time - initial_time) * unit.seconds
    simulated_time = nsteps * timestep
    performance = (simulated_time / elapsed_time)
    print('Completed {} steps in {}.'.format(nsteps, elapsed_time))
    print('Performance is {} ns/day'.format(performance / (unit.nanoseconds/unit.day)))
    print('Final potential energy is {}'.format(simulation.context.getState(getEnergy=True).getPotentialEnergy()))
Esempio n. 5
0
def perturb_parameters(perturb, hmr, prmtop):
    """
    Use ParmEd to make parameter perturbations
    """
    new_param = prmtop
    parm = AmberParm(prmtop + '.prmtop')
    logfile = open('parmed.log', 'w')

    if perturb == 'yes':
        # Parsing the input file that includes new parameters
        with open('new_params.dat') as fr:
            lines = fr.read().splitlines()
            lines = list(line for line in lines if line)  # Remove blank lines

        for line in lines:
            if not line[0] == ';':
                splitline = line.split()
                if len(splitline) < 4:
                    print 'Aborted. Wrong format! Please provide atom type(e.g.,OW), parameter type(e.g.,vdw), and the corresponding radius/epsilon parameters '
                    print '(separated with spaces.)\n'
                atom_type = splitline[0]
                param_type = splitline[1]
                radius = splitline[2]
                epsilon = splitline[3]
                if param_type.lower() == 'vdw':
                    action = changeLJSingleType(parm, "@%" + atom_type, radius,
                                                epsilon)
                    action.execute()
                    logfile.write(('%s\n' % action))
                else:
                    print 'Aborted. Only the feauture of perturbing vdW parameters is supported for now.\n'
                    sys.exit(1)
        new_param += '.perturbed'
        if os.path.isfile(new_param + '.prmtop'):
            os.remove(new_param + '.prmtop')
        Structure.save(parm, new_param + '.prmtop')

    if hmr == 'yes':
        parm = AmberParm(new_param + '.prmtop')
        # Use the ParmEd API, which is more stable than calling a subprocess
        action = HMassRepartition(parm)
        action.execute()
        logfile.write(('%s\n' % action))
        new_param += '.hmr'
        if os.path.isfile(new_param + '.prmtop'):
            os.remove(new_param + '.prmtop')
        Structure.save(parm, new_param + '.prmtop')

    return new_param
    def test_gas_energy_conf_4(self):
        """ Compare Amber and OpenMM gas phase energies and forces (topology 4) """
        parm = AmberParm(get_fn('ethanol_T0.prmtop'),
                         get_fn('ethanol_T0.rst7'))
        self.assertEqual(parm.combining_rule, 'geometric')
        system = parm.createSystem()  # Default, no cutoff
        integrator = mm.VerletIntegrator(1.0 * u.femtoseconds)
        sim = app.Simulation(parm.topology, system, integrator, platform=CPU)
        sim.context.setPositions(parm.positions)
        energies = energy_decomposition(parm, sim.context)
        #BOND    =        0.0239  ANGLE   =        0.0298  DIHED      =        0.0093
        #VDWAALS =        0.0000  EEL     =        6.7526  HBOND      =        0.0000
        #1-4 VDW =        0.0492  1-4 EEL =       -6.0430  RESTRAINT  =        0.0000
        # Compare OpenMM energies with the Amber energies (above)
        self.assertAlmostEqual(energies['bond'], 0.0239, places=4)
        self.assertAlmostEqual(energies['angle'], 0.0298, places=4)
        self.assertAlmostEqual(energies['dihedral'], 0.0093, places=4)
        self.assertRelativeEqual(energies['nonbonded'],
                                 0.0000 + 6.7526 + 0.0492 - 6.0430,
                                 places=3)

        # Now test the forces to make sure that they are computed correctly in
        # the presence of extra points
        pstate = sim.context.getState(getForces=True)
        pf = pstate.getForces().value_in_unit(u.kilojoule_per_mole /
                                              u.nanometer)
        # gmx forces:
        #      f[    0]={ 1.73101e+02,  5.67250e+01, -4.02950e+01}
        #      f[    1]={-8.13704e+00, -1.79612e+01,  9.88537e+01}
        #      f[    2]={-2.83120e+01,  6.23352e+00, -5.47393e+00}
        #      f[    3]={-1.03312e+01, -1.00966e+01, -5.12129e+00}
        #      f[    4]={-1.69636e+02,  3.34850e+01, -1.73612e+02}
        #      f[    5]={ 4.19932e+00, -2.58283e+00,  1.29999e+02}
        #      f[    6]={ 3.02865e+01, -6.68331e+00, -2.99153e+01}
        #      f[    7]={ 1.00113e+02, -5.22480e+01,  4.80526e+01}
        #      f[    8]={-9.12828e+01, -6.87157e+00, -2.24877e+01}

        gf = [(1.73101e+02, 5.67250e+01, -4.02950e+01),
              (-8.13704e+00, -1.79612e+01, 9.88537e+01),
              (-2.83120e+01, 6.23352e+00, -5.47393e+00),
              (-1.03312e+01, -1.00966e+01, -5.12129e+00),
              (-1.69636e+02, 3.34850e+01, -1.73612e+02),
              (4.19932e+00, -2.58283e+00, 1.29999e+02),
              (3.02865e+01, -6.68331e+00, -2.99153e+01),
              (1.00113e+02, -5.22480e+01, 4.80526e+01),
              (-9.12828e+01, -6.87157e+00, -2.24877e+01)]
        for p, s in zip(pf, gf):
            for x1, x2 in zip(p, s):
                self.assertAlmostEqual(x1, x2, places=3)
Esempio n. 7
0
    def readX(self):
        currentParams = AmberParm(self.currentPrmtop)
        x = []

        for p in self.parameter2optimize:
            if p.kind == "bond":
                for b in currentParams.bonds:
                    if set([b.atom1.type, b.atom2.type]) == p.atomMask:
                        if p.valueType == "req":
                            value = b.type.req
                        elif p.valueType == "kr":
                            value = b.type.k

                        x.append(value)
                        break

            elif p.kind == "angle":
                for a in currentParams.angles:
                    angleTypes = [a.atom1.type, a.atom2.type, a.atom3]
                    angleTypesRev = reversed(angleTypes)
                    if angleTypes == p.atomMask or angleTypesRev == p.atomMask:
                        if p.valueType == "kt":
                            value = a.type.k
                        elif p.valueType == "theq":
                            value = a.type.theteq

                        x.append(value)
                        break

        return x
Esempio n. 8
0
    def solvate(self, solvent, suffix=None, tmp=True):
        """
        Solvate system in OFF using solvent *solvent*. A PRMTOP and PRMCRD files will be saved and paths stored to :attr:`top` and :attr:`crd`.

        :arg solvent: Solvent Instance or Name to fetch the Solvent Instance in the database.
        :type: str or :class:`~Solvents.Solvent`
        :arg str suffix: Suffix for output files. Prefix will be the system name. E.g.: ``systemname_suffix.prmtop`` and ``systemname_suffix.prmcrd``.
        :arg bool tmp: Work in temporary folder.
        """
        if not self.amberOFF:
            raise SystemError, "Can not solvate if no Amber Object File is assigned."
        
        if isinstance(solvent, str): solvent = Solvents.getSolvent(solvent)
        if not solvent:
            raise SystemError, 'Invalid solvent instance or name.'

        # Build a loger just for this method
        log = logging.getLogger("SystemLogger")
        log.info("Solvating %s with solvent mixture %s"%(self.name, solvent.name))

        suffix = suffix or solvent.name
        name = '{0}_{1}'.format(self.name, suffix)
        prmtop = name+'.prmtop'
        prmcrd = name+'.prmcrd'

        if tmp:
            if isinstance(tmp, str): path = tmp
            else: path = T.tempDir()
            prmtop = osp.join(path, prmtop)
            prmcrd = osp.join(path, prmcrd)

        # Initiate AmberCreateSystem with loaded AmberOFF
        # Solvate, neutralize
        self.__initCreate()
        self.create.solvateOrganic(self.unitName, solvent=solvent)  # It will work even if its water
        self.create.saveAmberParm(self.unitName, prmtop, prmcrd)
        # Added by Xiaofeng 01/12/2016
        parm = AmberParm(prmtop)
        action = HMassRepartition(parm)
        action.execute()
        log.info(str(action))
        parm.write_parm(prmtop)
        #
        self.__cleanCreate()

        s = SolvatedSystem(name, prmtop, prmcrd, solvent=solvent.name, ref=self.ref)
        return s
Esempio n. 9
0
    def test_gas_energy_conf_4(self):
        """ Compare Amber and OpenMM gas phase energies and forces (topology 4) """
        parm = AmberParm(get_fn('ethanol_T0.prmtop'), get_fn('ethanol_T0.rst7'))
        self.assertEqual(parm.combining_rule, 'geometric')
        system = parm.createSystem() # Default, no cutoff
        integrator = mm.VerletIntegrator(1.0*u.femtoseconds)
        sim = app.Simulation(parm.topology, system, integrator, platform=CPU)
        sim.context.setPositions(parm.positions)
        energies = energy_decomposition(parm, sim.context)
#BOND    =        0.0239  ANGLE   =        0.0298  DIHED      =        0.0093
#VDWAALS =        0.0000  EEL     =        6.7526  HBOND      =        0.0000
#1-4 VDW =        0.0492  1-4 EEL =       -6.0430  RESTRAINT  =        0.0000
        # Compare OpenMM energies with the Amber energies (above)
        self.assertAlmostEqual(energies['bond'], 0.0239, places=4)
        self.assertAlmostEqual(energies['angle'], 0.0298, places=4)
        self.assertAlmostEqual(energies['dihedral'], 0.0093, places=4)
        self.assertRelativeEqual(energies['nonbonded'], 0.0000+6.7526+0.0492-6.0430, places=3)

        # Now test the forces to make sure that they are computed correctly in
        # the presence of extra points
        pstate = sim.context.getState(getForces=True)
        pf = pstate.getForces().value_in_unit(u.kilojoule_per_mole/u.nanometer)
# gmx forces:
#      f[    0]={ 1.73101e+02,  5.67250e+01, -4.02950e+01}
#      f[    1]={-8.13704e+00, -1.79612e+01,  9.88537e+01}
#      f[    2]={-2.83120e+01,  6.23352e+00, -5.47393e+00}
#      f[    3]={-1.03312e+01, -1.00966e+01, -5.12129e+00}
#      f[    4]={-1.69636e+02,  3.34850e+01, -1.73612e+02}
#      f[    5]={ 4.19932e+00, -2.58283e+00,  1.29999e+02}
#      f[    6]={ 3.02865e+01, -6.68331e+00, -2.99153e+01}
#      f[    7]={ 1.00113e+02, -5.22480e+01,  4.80526e+01}
#      f[    8]={-9.12828e+01, -6.87157e+00, -2.24877e+01}

        gf = [  ( 1.73101e+02,  5.67250e+01, -4.02950e+01),
                (-8.13704e+00, -1.79612e+01,  9.88537e+01),
                (-2.83120e+01,  6.23352e+00, -5.47393e+00),
                (-1.03312e+01, -1.00966e+01, -5.12129e+00),
                (-1.69636e+02,  3.34850e+01, -1.73612e+02),
                ( 4.19932e+00, -2.58283e+00,  1.29999e+02),
                ( 3.02865e+01, -6.68331e+00, -2.99153e+01),
                ( 1.00113e+02, -5.22480e+01,  4.80526e+01),
                (-9.12828e+01, -6.87157e+00, -2.24877e+01)]
        for p, s in zip(pf, gf):
            for x1, x2 in zip(p, s):
                self.assertAlmostEqual(x1, x2, places=3)
Esempio n. 10
0
def oemol_to_openmm_system_amber(oemol, molecule_name):
    """
    Create an openmm system out of an oemol

    Returns
    -------
    system : openmm.System object
        the system from the molecule
    positions : [n,3] np.array of floats
    """

    _ , tripos_mol2_filename = openmoltools.openeye.molecule_to_mol2(oemol, tripos_mol2_filename=molecule_name + '.tripos.mol2', conformer=0, residue_name='MOL')
    gaff_mol2, frcmod = openmoltools.amber.run_antechamber(molecule_name, tripos_mol2_filename)
    prmtop_file, inpcrd_file = openmoltools.amber.run_tleap(molecule_name, gaff_mol2, frcmod)
    from parmed.amber import AmberParm
    prmtop = AmberParm(prmtop_file)
    system = prmtop.createSystem(implicitSolvent=None, removeCMMotion=False)
    crd = app.AmberInpcrdFile(inpcrd_file)
    return system, crd.getPositions(asNumpy=True), prmtop.topology
def oemol_to_openmm_system_amber(oemol, molecule_name):
    """
    Create an openmm system out of an oemol

    Returns
    -------
    system : openmm.System object
        the system from the molecule
    positions : [n,3] np.array of floats
    """

    _ , tripos_mol2_filename = openmoltools.openeye.molecule_to_mol2(oemol, tripos_mol2_filename=molecule_name + '.tripos.mol2', conformer=0, residue_name='MOL')
    gaff_mol2, frcmod = openmoltools.amber.run_antechamber(molecule_name, tripos_mol2_filename)
    prmtop_file, inpcrd_file = openmoltools.amber.run_tleap(molecule_name, gaff_mol2, frcmod)
    from parmed.amber import AmberParm
    prmtop = AmberParm(prmtop_file)
    system = prmtop.createSystem(implicitSolvent=None, removeCMMotion=False)
    crd = app.AmberInpcrdFile(inpcrd_file)
    return system, crd.getPositions(asNumpy=True), prmtop.topology
Esempio n. 12
0
    def test_gas_energy_conf_3(self):
        """ Compare Amber and OpenMM gas phase energies and forces (topology 3) """
        parm = AmberParm(get_fn('methanol_T0.prmtop'),
                         get_fn('methanol_T0.rst7'))
        self.assertEqual(parm.combining_rule, 'geometric')
        system = parm.createSystem()  # Default, no cutoff
        integrator = mm.VerletIntegrator(1.0 * u.femtoseconds)
        sim = app.Simulation(parm.topology, system, integrator, platform=CPU)
        sim.context.setPositions(parm.positions)
        energies = energy_decomposition(parm, sim.context)
        #BOND    =        0.0224  ANGLE   =        0.0469  DIHED      =        0.0039
        #VDWAALS =        0.0000  EEL     =        0.0000  HBOND      =        0.0000
        #1-4 VDW =        0.0000  1-4 EEL =        3.3789  RESTRAINT  =        0.0000
        # Compare OpenMM energies with the Amber energies (above)
        self.assertAlmostEqual(energies['bond'], 0.0224, places=4)
        self.assertAlmostEqual(energies['angle'], 0.0469, places=4)
        self.assertAlmostEqual(energies['dihedral'], 0.0039, places=4)
        self.assertRelativeEqual(energies['nonbonded'], 3.3789, places=3)

        # Now test the forces to make sure that they are computed correctly in
        # the presence of extra points
        pstate = sim.context.getState(getForces=True)
        pf = pstate.getForces().value_in_unit(u.kilojoule_per_mole /
                                              u.nanometer)
        # gmx forces:
        #     f[    0]={ 2.19935e+01,  8.60143e+01,  1.77895e+02}
        #     f[    1]={ 5.25347e+01,  3.46119e+01, -9.73738e+01}
        #     f[    2]={ 1.76138e+01, -7.13778e+01, -1.08807e+00}
        #     f[    3]={-3.74994e+01, -5.39602e+01, -6.75679e+01}
        #     f[    4]={-8.35142e+01, -7.86616e+01, -1.60611e+02}
        #     f[    5]={ 2.88716e+01,  8.33735e+01,  1.48746e+02}

        gf = [(2.19935e+01, 8.60143e+01, 1.77895e+02),
              (5.25347e+01, 3.46119e+01, -9.73738e+01),
              (1.76138e+01, -7.13778e+01, -1.08807e+00),
              (-3.74994e+01, -5.39602e+01, -6.75679e+01),
              (-8.35142e+01, -7.86616e+01, -1.60611e+02),
              (2.88716e+01, 8.33735e+01, 1.48746e+02)]
        for p, s in zip(pf, gf):
            for x1, x2 in zip(p, s):
                self.assertAlmostEqual(x1, x2, places=3)
Esempio n. 13
0
    def test_gas_energy_conf_3(self):
        """ Compare Amber and OpenMM gas phase energies and forces (topology 3) """
        parm = AmberParm(get_fn('methanol_T0.prmtop'), get_fn('methanol_T0.rst7'))
        self.assertEqual(parm.combining_rule, 'geometric')
        system = parm.createSystem() # Default, no cutoff
        integrator = mm.VerletIntegrator(1.0*u.femtoseconds)
        sim = app.Simulation(parm.topology, system, integrator, platform=CPU)
        sim.context.setPositions(parm.positions)
        energies = energy_decomposition(parm, sim.context)
#BOND    =        0.0224  ANGLE   =        0.0469  DIHED      =        0.0039
#VDWAALS =        0.0000  EEL     =        0.0000  HBOND      =        0.0000
#1-4 VDW =        0.0000  1-4 EEL =        3.3789  RESTRAINT  =        0.0000
        # Compare OpenMM energies with the Amber energies (above)
        self.assertAlmostEqual(energies['bond'], 0.0224, places=4)
        self.assertAlmostEqual(energies['angle'], 0.0469, places=4)
        self.assertAlmostEqual(energies['dihedral'], 0.0039, places=4)
        self.assertRelativeEqual(energies['nonbonded'], 3.3789, places=3)

        # Now test the forces to make sure that they are computed correctly in
        # the presence of extra points
        pstate = sim.context.getState(getForces=True)
        pf = pstate.getForces().value_in_unit(u.kilojoule_per_mole/u.nanometer)
# gmx forces:
#     f[    0]={ 2.19935e+01,  8.60143e+01,  1.77895e+02}
#     f[    1]={ 5.25347e+01,  3.46119e+01, -9.73738e+01}
#     f[    2]={ 1.76138e+01, -7.13778e+01, -1.08807e+00}
#     f[    3]={-3.74994e+01, -5.39602e+01, -6.75679e+01}
#     f[    4]={-8.35142e+01, -7.86616e+01, -1.60611e+02}
#     f[    5]={ 2.88716e+01,  8.33735e+01,  1.48746e+02}

        gf = [  ( 2.19935e+01,  8.60143e+01,  1.77895e+02),
                ( 5.25347e+01,  3.46119e+01, -9.73738e+01),
                ( 1.76138e+01, -7.13778e+01, -1.08807e+00),
                (-3.74994e+01, -5.39602e+01, -6.75679e+01),
                (-8.35142e+01, -7.86616e+01, -1.60611e+02),
                ( 2.88716e+01,  8.33735e+01,  1.48746e+02)]
        for p, s in zip(pf, gf):
            for x1, x2 in zip(p, s):
                self.assertAlmostEqual(x1, x2, places=3)
Esempio n. 14
0
def main():
    parser = argparse.ArgumentParser(
        description="Create CVs file from amber masks")
    parser.add_argument("top", help="Topology file")
    parser.add_argument("defs", help="CV definitions")
    args = parser.parse_args()

    top = AmberParm(args.top)
    with open(args.defs, 'r') as f:
        cv_defs = f.readlines()

    print('{}'.format(len(cv_defs)))
    for cv_def in cv_defs:
        write_cv(top, cv_def)
Esempio n. 15
0
def read_amber_prm(pfile, cfile):

    prmtop = AmberParm(pfile)
    crds = read_rstf(cfile)

    atids = list(range(1, len(prmtop.parm_data['ATOM_NAME']) + 1))
    resids = list(range(1, len(prmtop.parm_data['RESIDUE_LABEL']) + 1))

    if len(prmtop.parm_data['ATOM_NAME']) != len(crds):
        raise ReadError('The toplogy and coordinates file are not \
                          consistent in the atom numbers.')

    residues = {}
    atoms = {}
    for i in range(0, len(prmtop.parm_data['RESIDUE_LABEL'])):

        resid = i + 1
        resname = prmtop.parm_data['RESIDUE_LABEL'][i]

        if i < len(prmtop.parm_data['RESIDUE_LABEL']) - 1:
            resconter = list(range(prmtop.parm_data['RESIDUE_POINTER'][i], \
                         prmtop.parm_data['RESIDUE_POINTER'][i+1]))
        else:
            resconter = list(range(prmtop.parm_data['RESIDUE_POINTER'][i], \
                         len(prmtop.parm_data['ATOM_NAME'])+1))

        residues[resid] = Residue(resid, resname, resconter)

        for j in resconter:
            gtype = 'ATOM'
            atid = j
            atname = prmtop.parm_data['ATOM_NAME'][j - 1]
            element = prmtop.parm_data['ATOMIC_NUMBER'][j - 1]
            atomtype = prmtop.parm_data['AMBER_ATOM_TYPE'][j - 1]
            crd = crds[j - 1]
            charge = prmtop.parm_data['CHARGE'][j - 1]

            try:
                element = AtnumRev[element]
            except:
                print(resname, atname, atomtype)
                element = 'X'

            atoms[j] = Atom(gtype, atid, atname, element, atomtype, crd, charge, \
                           resid, resname)

    mol = Molecule(atoms, residues)

    return prmtop, mol, atids, resids
Esempio n. 16
0
    def test_gas_energy_conf_2(self):
        """ Compare Amber and OpenMM gas phase energies and forces (topology 2) """
        parm = AmberParm(get_fn('hydrogen-peroxide_T0_2.prmtop'),
                         get_fn('hydrogen-peroxide_T0_2.rst7'))
        self.assertEqual(parm.combining_rule, 'lorentz')
        system = parm.createSystem()  # Default, no cutoff
        integrator = mm.VerletIntegrator(1.0 * u.femtoseconds)
        sim = app.Simulation(parm.topology, system, integrator, platform=CPU)
        sim.context.setPositions(parm.positions)
        energies = energy_decomposition(parm, sim.context)
        #BOND    =        0.0319  ANGLE   =        2.1690  DIHED      =       -2.7931
        #VDWAALS =        0.0000  EEL     =        0.0000  HBOND      =        0.0000
        #1-4 VDW =        0.0000  1-4 EEL =        0.0000  RESTRAINT  =        0.0000
        # Compare OpenMM energies with the Amber energies (above)
        self.assertAlmostEqual(energies['bond'], 0.0319, places=4)
        self.assertAlmostEqual(energies['angle'], 2.1690, places=4)
        self.assertAlmostEqual(energies['dihedral'], -2.7931, places=4)
        self.assertRelativeEqual(energies['nonbonded'], 0.0, places=3)

        # Now test the forces to make sure that they are computed correctly in
        # the presence of extra points
        pstate = sim.context.getState(getForces=True)
        pf = pstate.getForces().value_in_unit(u.kilojoule_per_mole /
                                              u.nanometer)
        # gmx forces:
        #     f[    0]={ 3.14357e+02, -5.90363e+02,  2.11410e+02}
        #     f[    1]={-3.14357e+02,  5.90363e+02,  2.11410e+02}
        #     f[    2]={ 2.70641e+02,  5.90363e+02, -2.11410e+02}
        #     f[    3]={-2.70641e+02, -5.90363e+02, -2.11410e+02}
        gf = [(3.14357e+02, -5.90363e+02, 2.11410e+02),
              (-3.14357e+02, 5.90363e+02, 2.11410e+02),
              (2.70641e+02, 5.90363e+02, -2.11410e+02),
              (-2.70641e+02, -5.90363e+02, -2.11410e+02)]
        for p, s in zip(pf, gf):
            for x1, x2 in zip(p, s):
                self.assertAlmostEqual(x1, x2, places=3)
Esempio n. 17
0
def get_total_energy(agls):
    # get the coor from pyrosetta
    inp_coor=generate_coord(agls)
    # initialize the object topology with coordinates
    parm=AmberParm("tpp-1.prmtop",inp_coor)
    # set up the input options
    inp=sander.gas_input() 
    sander.setup (parm, parm.coordinates, None, inp)

    # compute the energy and force
    eney, frc=sander.energy_forces()
    # print('sander',eney.tot,eney.gb,eney.vdw, eney.elec, eney.dihedral,eney.angle, eney.bond)

    # clean and finish
    sander.cleanup()
    return eney.tot
Esempio n. 18
0
def main():
    parser = argparse.ArgumentParser(
        description="Create CVs file for unbinding")
    parser.add_argument("top", help="Topology file")
    parser.add_argument("masks",
                        help="Masks file (with masks for 6 centers (P1..L3")
    args = parser.parse_args()

    top = AmberParm(args.top)
    masks = read_masks(args.masks)
    centers = {name: get_center(top, mask) for name, mask in masks.items()}

    with open('CVs', 'w') as f:
        f.write('6\n\n')
        for cv in CVS:
            compile_cv(f, centers, *cv)
Esempio n. 19
0
 def Get_prmtop_info(self):
     self.prmtop=AmberParm(self.prmname)
     self.natom=len(self.prmtop.atoms)
     self.nres=len(self.prmtop.residues)
     atomname=self.prmtop.parm_data["ATOM_NAME"]
     eleindex=self.prmtop.parm_data['ATOMIC_NUMBER']
     atomcrg=self.prmtop.parm_data['CHARGE']
     self.totalcharge=round(np.sum(atomcrg))
     self.atoms=np.array(eleindex)
     self.respts=np.array(self.prmtop.parm_data['RESIDUE_POINTER'])-1
     respte=self.prmtop.parm_data['RESIDUE_POINTER'][1:]
     respte.append(self.natom+1)
     self.respte=np.array(respte)-2
     self.rescrg=np.zeros(self.nres) 
     for i in range(self.nres):
         self.rescrg[i]=round(np.sum(atomcrg[self.respts[i]:self.respte[i]+1]))
     print (self.rescrg)
Esempio n. 20
0
 def test_add_amber_parm(self):
     """ Test adding AmberParm-derived instances to ParmList """
     parms = ParmList()
     amber = AmberParm(get_fn('tip4p.parm7'))
     chamber = ChamberParm(get_fn('ala_ala_ala.parm7'))
     amoeba = AmoebaParm(get_fn('nma.parm7'))
     parms.add_parm(amber)
     parms.add_parm(chamber)
     parms.add_parm(amoeba)
     self.assertEqual(len(parms), 3)
     # Test int indexing
     self.assertIs(parms[0], amber)
     self.assertIs(parms[1], chamber)
     self.assertIs(parms[2], amoeba)
     self.assertRaises(IndexError, lambda: parms[3])
     # Test name indexing
     self.assertIs(parms[get_fn('tip4p.parm7')], amber)
     self.assertIs(parms[get_fn('ala_ala_ala.parm7')], chamber)
     self.assertIs(parms[get_fn('nma.parm7')], amoeba)
     self.assertRaises(IndexError, lambda: parms['noparm'])
     # Check that the last added parm is active
     self.assertIs(parms.parm, amoeba)
     # Set a new active topology
     parms.set_new_active(0)
     self.assertIs(parms.parm, amber)
     parms.set_new_active(get_fn('ala_ala_ala.parm7'))
     self.assertIs(parms.parm, chamber)
     self.assertRaises(IndexError, lambda: parms.set_new_active(3))
     self.assertIs(parms.parm, chamber)
     self.assertRaises(exc.DuplicateParm,
                       lambda: parms.add_parm(get_fn('ala_ala_ala.parm7')))
     self.assertRaises(
         exc.DuplicateParm,
         lambda: parms.add_parm(load_file(get_fn('ala_ala_ala.parm7'))))
     self.assertRaises(
         exc.ParmError, lambda: parms.add_parm(
             os.path.join(get_fn('pptest1'), 'pptest1.h')))
     self.assertRaises(exc.ParmError,
                       lambda: parms.add_parm(get_fn('amino12.lib')))
     self.assertRaises(exc.ParmError, lambda: parms.add_parm(object()))
Esempio n. 21
0
    def prepare_prefinal_topology(self):
        import os
        # self.path_to_final_struct
        from runmd2.MD import TleapInput

        from parmed.amber import AmberParm, AmberMask
        from parmed.topologyobjects import Atom

        final_tleap = TleapInput()
        final_tleap.source(os.environ["PRMTOP_HOME"] +
                           "/cmd/leaprc.protein.chlorolys.ff14SB")
        final_tleap.source(os.environ["PRMTOP_HOME"] +
                           "/cmd/leaprc.water.tip3p")
        final_tleap.add_command("loadamberparams frcmod.ionsjc_tip3p")
        final_tleap.load_pdb("./input2.pdb")
        #final_tleap.add_command("bond wbox.32.SG wbox.69.C2 ")
        final_tleap.solvate_oct("TIP3PBOX", 15.0)
        final_tleap.add_ions("Na+", target_charge=0)
        final_tleap.save_params(output_name=MD._build_dir + "/prefinal_box")
        final_tleap.save_pdb(output_name=MD._build_dir + "/prefinal_box")
        final_tleap.add_command("quit")

        final_tleap.write_commands_to(MD._build_dir + "/prefinal_tleap.rc")

        self.call_cmd(
            ["tleap", "-s", "-f", MD._build_dir + "/prefinal_tleap.rc"])

        # strip redundant water molecules
        parm_old = AmberParm(MD._build_dir + "/box.prmtop")
        parm_new = AmberParm(MD._build_dir + "/prefinal_box.prmtop")
        old_res = set()
        new_res = set()
        for r in parm_old.residues:
            old_res.add(r.number)
            number = r.number
        old_res.add(number + 1)
        for r in parm_new.residues:
            new_res.add(r.number)
        residues_to_delete = sorted(list(new_res - old_res))
        res_mask = ":" + ','.join(list(map(str, residues_to_delete)))
        parm_new.strip(res_mask)
        parm_new.write_parm(MD._build_dir + "/prefinal_box.mod.prmtop")
Esempio n. 22
0
def get_rmsd(initparas):

    global idxs, mcresids2, atompairs

    #Modify the C4 terms in the prmtop file
    for i in range(0, len(idxs)):
        prmtop.parm_data['LENNARD_JONES_CCOEF'][idxs[i]] = initparas[i]

    #Overwrite the prmtop file
    prmtop.write_parm('OptC4.top')

    #Perform the OpenMM optimization
    #Use AmberParm function to transfer the topology and
    #coordinate file to the object OpenMM can use
    Ambermol = AmberParm('OptC4.top', options.cfile)

    # Create the OpenMM system
    print('Creating OpenMM System')
    if options.simupha == 'gas':
        system = Ambermol.createSystem(nonbondedMethod=app.NoCutoff)
    elif options.simupha == 'liquid':
        system = Ambermol.createSystem(
            nonbondedMethod=app.PME,
            nonbondedCutoff=8.0 * u.angstroms,
            constraints=app.HBonds,
        )

    #Add restraints
    force = mm.CustomExternalForce("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)")
    force.addGlobalParameter("k", 200.0)
    force.addPerParticleParameter("x0")
    force.addPerParticleParameter("y0")
    force.addPerParticleParameter("z0")
    #for i in range(0, len(Ambermol.atoms)):
    for i, atom_crd in enumerate(Ambermol.positions):
        #if (Ambermol.atoms[i].residue.number+1 not in mcresids2) and \
        if (i+1 not in mcresids2) and \
          (Ambermol.atoms[i].residue.name not in ['WAT', 'HOH']) and \
          (Ambermol.atoms[i].name in ['CA', 'C', 'N']):
            force.addParticle(i, atom_crd.value_in_unit(u.nanometers))
    system.addForce(force)

    # Create the integrator to do Langevin dynamics
    # Temperature of heat bath, Friction coefficient, Time step
    integrator = mm.LangevinIntegrator(
        300 * u.kelvin,
        1.0 / u.picoseconds,
        1.0 * u.femtoseconds,
    )

    # Define the platform to use; CUDA, OpenCL, CPU, or Reference. Or do not
    # specify the platform to use the default (fastest) platform
    # Create the Simulation object
    if options.platf == 'ref':
        platform = mm.Platform.getPlatformByName('Reference')
        sim = app.Simulation(Ambermol.topology, system, integrator, platform)
    elif options.platf == 'cpu':
        platform = mm.Platform.getPlatformByName('CPU')
        sim = app.Simulation(Ambermol.topology, system, integrator, platform)
    elif options.platf == 'cuda':
        platform = mm.Platform.getPlatformByName('CUDA')
        prop = dict(CudaPrecision=options.presn)
        sim = app.Simulation(Ambermol.topology, system, integrator, platform,
                             prop)
    elif options.platf == 'opencl':
        platform = mm.Platform.getPlatformByName('OpenCL')
        prop = dict(OpenCLPrecision=options.presn)
        sim = app.Simulation(Ambermol.topology, system, integrator, platform,
                             prop)

    # Set the particle positions
    sim.context.setPositions(Ambermol.positions)

    # Output the rst file
    restrt = RestartReporter(options.rfile, 100, write_velocities=False)
    sim.reporters.append(restrt)

    # Minimize the energy
    print('Minimizing energy ' + str(options.maxsteps) + ' steps.')
    sim.minimizeEnergy(maxIterations=options.maxsteps)

    # Overwrite the final file
    state = sim.context.getState(getPositions=True, enforcePeriodicBox=True)
    restrt.report(sim, state)

    val_aft_min = []
    crds_aft_min = read_rstf(options.rfile)
    for i in atompairs:
        if len(i) == 2:
            crd1 = crds_aft_min[i[0] - 1]
            crd2 = crds_aft_min[i[1] - 1]
            bond = calc_bond(crd1, crd2)
            val_aft_min.append(('bond', bond))
        elif len(i) == 3:
            crd1 = crds_aft_min[i[0] - 1]
            crd2 = crds_aft_min[i[1] - 1]
            crd3 = crds_aft_min[i[2] - 1]
            angle = calc_angle(crd1, crd2, crd3)
            val_aft_min.append(('angle', angle))
        elif len(i) == 4:
            crd1 = crds_aft_min[i[0] - 1]
            crd2 = crds_aft_min[i[1] - 1]
            crd3 = crds_aft_min[i[2] - 1]
            crd4 = crds_aft_min[i[3] - 1]
            dih = calc_dih(crd1, crd2, crd3, crd4)
            val_aft_min.append(('dih', dih))

    valdiffs = []
    for i in range(0, len(atompairs)):
        if val_bf_min[i][0] == 'bond':
            valdiff = abs(val_aft_min[i][1] - val_bf_min[i][1]) * 1.0 / 100.0
        elif val_bf_min[i][0] == 'angle':
            valdiff = abs(val_aft_min[i][1] - val_bf_min[i][1]) * 1.0 / 2.0
        elif val_bf_min[i][0] == 'dih':
            valdiff = abs(val_aft_min[i][1] - val_bf_min[i][1])
            if (360.0 - valdiff < valdiff):
                valdiff = 360.0 - valdiff
        valdiffs.append(valdiff)

    fnldiff = numpy.sum(valdiffs)
    print(fnldiff)

    return fnldiff
Esempio n. 23
0
def main(opt):
    # Check all of the arguments
    if not os.path.exists(opt.prmtop):
        raise AmberError('prmtop file (%s) is missing' % opt.prmtop)

    # Process the arguments that take multiple args
    resstates = process_arglist(opt.resstates, int)
    resnums = process_arglist(opt.resnums, int)
    notresnums = process_arglist(opt.notresnums, int)
    resnames = process_arglist(opt.resnames, str)
    notresnames = process_arglist(opt.notresnames, str)
    minpka = opt.minpka
    maxpka = opt.maxpka

    if not opt.igb in (1, 2, 5, 7, 8):
        raise AmberError('-igb must be 1, 2, 5, 7, or 8!')

    if resnums is not None and notresnums is not None:
        raise AmberError('Cannot specify -resnums and -notresnums together')

    if resnames is not None and notresnames is not None:
        raise AmberError('Cannot specify -resnames and -notresnames together')

    if opt.intdiel != 1 and opt.intdiel != 2:
        raise AmberError('-intdiel must be either 1 or 2 currently')

    # Print warning about old format
    if opt.oldfmt:
        sys.stderr.write('Warning: The old format of the CPIN file can only be used for simulations with temp0=300.0!\n'
                         '         You should use the new format for simulations with temperatures other than 300.0 Kelvins\n')

    # Set the list of residue names we will be willing to titrate
    titratable_residues = []
    if notresnames is not None:
        for resname in residues.titratable_residues:
            if resname in notresnames: continue
            titratable_residues.append(resname)
    elif resnames is not None:
        for resname in resnames:
            if not resname in residues.titratable_residues:
                raise AmberError('%s is not a titratable residue!' % resname)
            elif not getattr(residues, resname).typ == "ph":
                raise AmberError('%s is not a pH-active titratable residue!' % resname)
            titratable_residues.append(resname)
    else:
        for resname in residues.titratable_residues:
            if getattr(residues, resname).typ == "ph":
                titratable_residues.append(resname)

    solvent_ions = ['WAT', 'Na+', 'Br-', 'Cl-', 'Cs+', 'F-', 'I-', 'K+', 'Li+',
                    'Mg+', 'Rb+', 'CIO', 'IB', 'MG2']

    # Filter titratable residues based on min and max pKa
    new_reslist = []
    for res in titratable_residues:
        # @jaimergp: If None values are not filtered out, comparisons
        # will fail in Py3k. This patch was discussed and approved in
        # GitLab issue 122 (@vwcruzeiro, @swails)
        # Error obtained in serial tests in conda-forge builds:
        #       Traceback (most recent call last):
        #         File "/home/conda/amber/bin/cpinutil.py", line 325, in <module>
        #           main(opt)
        #         File "/home/conda/amber/bin/cpinutil.py", line 191, in main
        #           if getattr(residues, res).pKa < minpka: continue
        #       TypeError: '<' not supported between instances of 'NoneType' and 'int'
        #         ./Run.cpin:  Program error
        #       make[1]: *** [test.cpinutil] Error 1
        if getattr(residues, res).pKa is None: continue
        # /@jaimergp
        if getattr(residues, res).pKa < minpka: continue
        if getattr(residues, res).pKa > maxpka: continue
        new_reslist.append(res)
    titratable_residues = new_reslist
    del new_reslist

    # Make sure we still have a couple residues
    if len(titratable_residues) == 0:
        raise AmberError('No titratable residues fit your criteria!')

    # Load the topology file
    parm = AmberParm(opt.prmtop)

    # Replace an un-set notresnums with an empty list so we get __contains__()
    if notresnums is None:
        notresnums = []

    # If we have a list of residue numbers, check that they're all titratable
    if resnums is not None:
        for resnum in resnums:
            if resnum > parm.ptr('nres'):
                raise AmberError('%s only has %d residues. (%d chosen)' %
                                     (parm, parm.ptr('nres'), resnum))
            if resnum <= 0:
                raise AmberError('Cannot select negative residue numbers.')
            resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
            if not resname in titratable_residues:
                raise AmberError('Residue number %s [%s] is not titratable'
                                     % (resnum, resname))
    else:
        # Select every residue except those in notresnums
        resnums = []
        for resnum in range(1, parm.ptr('nres') + 1):
            if resnum in notresnums: continue
            resnums.append(resnum)

    solvated = False
    first_solvent = 0
    if 'WAT' in parm.parm_data['RESIDUE_LABEL']:
        solvated = True
        for i, res in enumerate(parm.parm_data['RESIDUE_LABEL']):
            if res in solvent_ions:
                first_solvent = parm.parm_data['RESIDUE_POINTER'][i]
                break
    main_reslist = TitratableResidueList(system_name=opt.system,
                        solvated=solvated, first_solvent=first_solvent)
    trescnt = 0
    for resnum in resnums:
        resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
        if not resname in titratable_residues: continue
        res = getattr(residues, resname)
        # Filter out termini (make sure the residue in the prmtop has as many
        # atoms as the titratable residue defined in residues.py)
        if resnum == parm.ptr('nres'):
            natoms = (parm.ptr('natom') + 1 -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        else:
            natoms = (parm.parm_data['RESIDUE_POINTER'][resnum] -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        if natoms != len(res.atom_list): continue
        # If we have gotten this far, add it to the list.
        main_reslist.add_residue(res, resnum,
                                 parm.parm_data['RESIDUE_POINTER'][resnum-1])
        trescnt += 1

    # Prints a warning if the number of titratable residues is larger than 50
    if trescnt > 50: sys.stderr.write('Warning: Your CPIN file has more than 50 titratable residues! pmemd and sander have a\n'
                                      '         default limit of 50 titrable residues, thus this CPIN file can only be used\n'
                                      '         if the definitions for this limit are modified at the top of\n'
                                      '         $AMBERHOME/src/pmemd/src/constantph.F90 or $AMBERHOME/AmberTools/src/sander/constantph.F90.\n'
                                      '         AMBER needs to be recompilied after these files are modified.\n')

    # Set the states if requested
    if resstates is not None:
        main_reslist.set_states(resstates)

    # Open the output file
    if opt.output is None:
        output = sys.stdout
    else:
        output = open(opt.output, 'w')

    main_reslist.write_cpin(output, opt.igb, opt.intdiel, opt.oldfmt, "ph")

    if opt.output is not None:
        output.close()

    if solvated:
        if opt.outparm is None:
            has_carboxylate = False
            for res in main_reslist:
                if res is residues.AS4 or res is residues.GL4 or res is residues.PRN:
                    has_carboxylate = True
                    break
            if has_carboxylate:
                sys.stderr.write(
                        'Warning: Carboxylate residues in explicit solvent '
                        'simulations require a modified topology file!\n'
                        '         Use the -op flag to print one.\n'
                )
        else:
            changeRadii(parm, 'mbondi2').execute()
            change(parm, 'RADII', ':AS4,GL4,PRN@OD=,OE=,O1=,O2=', 1.3).execute()
            parm.overwrite = True
            parm.write_parm(opt.outparm)
    else:
        if opt.outparm is not None:
            sys.stderr.write(
                    'A new prmtop is only necessary for explicit solvent '
                    'CpHMD/pH-REMD simulations.\n'
            )

    sys.stderr.write('CPIN generation complete!\n')
Esempio n. 24
0
def main(opt):
    # Check all of the arguments
    if not os.path.exists(opt.prmtop):
        raise AmberError('prmtop file (%s) is missing' % opt.prmtop)
   
    # Process the arguments that take multiple args
    resstates = process_arglist(opt.resstates, int)
    resnums = process_arglist(opt.resnums, int)
    notresnums = process_arglist(opt.notresnums, int)
    resnames = process_arglist(opt.resnames, str)
    notresnames = process_arglist(opt.notresnames, str)
    minpka = opt.minpka
    maxpka = opt.maxpka

    if not opt.igb in (2, 5, 8):
        raise AmberError('-igb must be 2, 5, or 8!')
   
    if resnums is not None and notresnums is not None:
        raise AmberError('Cannot specify -resnums and -notresnums together')
   
    if resnames is not None and notresnames is not None:
        raise AmberError('Cannot specify -resnames and -notresnames together')
   
    if opt.intdiel != 1 and opt.intdiel != 2:
        raise AmberError('-intdiel must be either 1 or 2 currently')

    # Set the list of residue names we will be willing to titrate
    titratable_residues = []
    if notresnames is not None:
        for resname in residues.titratable_residues:
            if resname in notresnames: continue
            titratable_residues.append(resname)
    elif resnames is not None:
        for resname in resnames:
            if not resname in residues.titratable_residues:
                raise AmberError('%s is not a titratable residue!' % resname)
            titratable_residues.append(resname)
    else:
        titratable_residues = residues.titratable_residues[:]
   
    solvent_ions = ['WAT', 'Na+', 'Br-', 'Cl-', 'Cs+', 'F-', 'I-', 'K+', 'Li+',
                    'Mg+', 'Rb+', 'CIO', 'IB', 'MG2']
   
    # Filter titratable residues based on min and max pKa
    new_reslist = []
    for res in titratable_residues:
        if getattr(residues, res).pKa < minpka: continue
        if getattr(residues, res).pKa > maxpka: continue
        new_reslist.append(res)
    titratable_residues = new_reslist
    del new_reslist
   
    # Make sure we still have a couple residues
    if len(titratable_residues) == 0:
        raise AmberError('No titratable residues fit your criteria!')
   
    # Load the topology file
    parm = AmberParm(opt.prmtop)
   
    # Replace an un-set notresnums with an empty list so we get __contains__()
    if notresnums is None:
        notresnums = []
   
    # If we have a list of residue numbers, check that they're all titratable
    if resnums is not None:
        for resnum in resnums:
            if resnum > parm.ptr('nres'):
                raise AmberError('%s only has %d residues. (%d chosen)' %
                                     (parm, parm.ptr('nres'), resnum))
            if resnum <= 0:
                raise AmberError('Cannot select negative residue numbers.')
            resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
            if not resname in titratable_residues:
                raise AmberError('Residue number %s [%s] is not titratable'
                                     % (resnum, resname))
    else:
        # Select every residue except those in notresnums
        resnums = []
        for resnum in range(1, parm.ptr('nres') + 1):
            if resnum in notresnums: continue
            resnums.append(resnum)
   
    solvated = False
    first_solvent = 0
    if 'WAT' in parm.parm_data['RESIDUE_LABEL']:
        solvated = True
        for i, res in enumerate(parm.parm_data['RESIDUE_LABEL']):
            if res in solvent_ions:
                first_solvent = parm.parm_data['RESIDUE_POINTER'][i]
                break
    main_reslist = TitratableResidueList(system_name=opt.system, 
                        solvated=solvated, first_solvent=first_solvent)
    for resnum in resnums:
        resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
        if not resname in titratable_residues: continue
        res = getattr(residues, resname)
        # Filter out termini (make sure the residue in the prmtop has as many
        # atoms as the titratable residue defined in residues.py)
        if resnum == parm.ptr('nres'):
            natoms = (parm.ptr('natom') + 1 -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        else:
            natoms = (parm.parm_data['RESIDUE_POINTER'][resnum] -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        if natoms != len(res.atom_list): continue
        # If we have gotten this far, add it to the list.
        main_reslist.add_residue(res, resnum,
                                 parm.parm_data['RESIDUE_POINTER'][resnum-1])
   
    # Set the states if requested
    if resstates is not None:
        main_reslist.set_states(resstates)
   
    # Open the output file
    if opt.output is None:
        output = sys.stdout
    else:
        output = open(opt.output, 'w')
   
    main_reslist.write_cpin(output, opt.igb, opt.intdiel)
   
    if opt.output is not None:
        output.close()
   
    if solvated:
        if opt.outparm is None:
            has_carboxylate = False
            for res in main_reslist:
                if res is residues.AS4 or res is residues.GL4:
                    has_carboxylate = True
                    break
            if has_carboxylate:
                sys.stderr.write(
                        'Warning: Carboxylate residues in explicit solvent '
                        'simulations require a modified topology file!\n'
                        'Use the -op flag to print one.\n'
                )
        else:
            changeRadii(parm, 'mbondi2').execute()
            change(parm, 'RADII', ':AS4,GL4@OD=,OE=', 1.3).execute()
            parm.overwrite = True
            parm.writeParm(opt.outparm)
    else:
        if opt.outparm is not None:
            sys.stderr.write(
                    'A new prmtop is only necessary for explicit solvent '
                    'CpHMD/pH-REMD simulations.\n'
            )
Esempio n. 25
0
from msmbuilder.io import save_generic
import parmed as pmd
from parmed.amber import AmberParm

struct = AmberParm('proc_traj/2agy-as1.prmtop')
angles = [(x.atom1.idx, x.atom2.idx, x.atom3.idx) for x in struct.angles]
bonds = [(x.atom1.idx, x.atom2.idx) for x in struct.bonds]
dihedrals = [(x.atom1.idx, x.atom2.idx, x.atom3.idx, x.atom4.idx)
             for x in struct.dihedrals]
print('Number of angles {}'.format(len(angles)))
print('Number of bonds {}'.format(len(bonds)))
print('Number of dihedrals {}'.format(len(dihedrals)))

# save_generic(bonds, 'proc_traj/2agy_as-1_bonds.pickl')
# save_generic(angles, 'proc_traj/2agy_as-1_angles.pickl')
# save_generic(dihedrals, 'proc_traj/2agy_as-1_dihedrals.pickl')

struct2 = AmberParm('proc_traj/2agy-as2.prmtop')
angles2 = [(x.atom1.idx, x.atom2.idx, x.atom3.idx) for x in struct2.angles]
bonds2 = [(x.atom1.idx, x.atom2.idx) for x in struct2.bonds]
dihedrals2 = [(x.atom1.idx, x.atom2.idx, x.atom3.idx, x.atom4.idx)
              for x in struct2.dihedrals]
tuples = [bonds, angles, dihedrals]
tuples2 = [bonds2, angles2, dihedrals2]

for k in range(len(tuples)):
    tuple1 = tuples[k]
    tuple2 = tuples2[k]
    for i in range(len(tuple1)):
        print('Testing {0} and {1}'.format(tuple1[i], tuple2[i]))
        for j in range(len(tuple1[i])):
Esempio n. 26
0
def parmed_topology(top_file, param_type, param_list, TIP3P_param_list, index):
    """
    Use ParmEd to edit water parameters
    """
    parm = AmberParm(top_file)
    local_param_list = TIP3P_param_list
    ow_charge_column = hw_charge_column = ow_rad_column = ow_eps_column = 999

    # Write a log file for parmEd
    f = open('waterbot_parmed.log', 'w')
    logfile = open('parmed.log', 'w')
    for i, nonbonded_term in enumerate(param_type):
        if 'charge' in nonbonded_term.lower() and 'ow' in nonbonded_term.lower(
        ):
            ow_charge_column = i
            f.write('The partial charge of water oxygen will be perturbed; ')
            f.write('the value of the new parameter is %.4f.\n' %
                    (param_list[i][index]))
            local_param_list[2] = param_list[i][index]
        elif 'charge' in nonbonded_term.lower(
        ) and 'hw' in nonbonded_term.lower():
            hw_charge_column = i
            f.write('The partial charge of water hydrogen will be perturbed; ')
            f.write('the value of the new parameter is %.4f.\n' %
                    (param_list[i][index]))
            local_param_list[3] = param_list[i][index]
        elif 'radius' in nonbonded_term.lower():
            ow_rad_column = i
            f.write(
                'The radii parameter of water hydrogen will be perturbed; ')
            f.write('the value of the new parameter is %.4f.\n' %
                    (param_list[i][index]))
            local_param_list[0] = param_list[i][index]
        elif 'epsilon' in nonbonded_term.lower():
            ow_eps_column = i
            f.write(
                'The epsilon parameter of water hydrogen will be perturbed; ')
            f.write('the value of the new parameter is %.4f.\n' %
                    (param_list[i][index]))
            local_param_list[1] = param_list[i][index]

    # if only one of the charges were provided:
    if ow_charge_column == 999 and hw_charge_column != 999:
        f.write('\nThe charge of water oxygen was not provided.')
        local_param_list[2] = -2.0 * local_param_list[3]
        f.write(
            'A value of %.4f was computed and used to make sure this water model is neutral.'
            % (local_param_list[2]))
    elif hw_charge_column == 999 and ow_charge_column != 999:
        f.write('\nThe charge of water hydrogen was not provided.')
        local_param_list[3] = -local_param_list[2] / 2.0
        f.write(
            'A value of %.4f was computed and used to make sure this water model is neutral.'
            % (local_param_list[3]))

    # Check whether the water model has a neutral charge
    if (local_param_list[2] + 2 * local_param_list[3]) != 0:
        f.write('\nAborted.The new water model is not neutral!!!\n')
        sys.exit(1)

    if ow_rad_column != 999 or ow_eps_column != 999:
        # It looks like there is no way to only change radius or epsilon
        action = changeLJSingleType(parm, "@%OW", local_param_list[0],
                                    local_param_list[1])
        action.execute()
        logfile.write(('%s\n' % action))
    if ow_charge_column != 999 or hw_charge_column != 999:
        action = change(parm, 'CHARGE', "@%OW", local_param_list[2])
        action.execute()
        logfile.write(('%s\n' % action))
    Structure.save(parm, 'solvated_perturbed.prmtop')
Esempio n. 27
0
def prepare_prmtop(args, name):
    """ Places appropriate prmtop file into the calculation folder and scales
    it's charges if necessary.

    Parameters
    ----------

    args : Namespace
        Command line arguments

    Returns
    -------

    out : string
        Path to prmtop file.

    """
    # The atom specification in ParmedActions is terrible and requires the use
    # of masks. A good description of what it is can be found in Amber14 manual
    # section 28.2.3
    if args.file.endswith('.prmtop'):
        prmtop_name = args.file
    else:
        prmtop_name = generate_prmtop(name, args)
    if args.new_name:
        new_name = args.new_name
    else:
        new_name = prmtop_name
    if args.minimize:
        minimize_solute(name, prmtop_name, args)
    if args.nomod:
        # we are done
        return 0
    parm = AmberParm(prmtop_name)
    if args.charge_model == 'opls' or args.lennard_jones == 'opls':
        opls_radii, opls_epss, opls_chgs = get_opls_parameters(args, name)
    # account for scenario when charge_f is submitted along with existing prmtop
    if args.charge_f and args.file.endswith('.prmtop'):
        chargef_charges = get_chargef_charges(args.charge_f)
    #iterate over atoms
    for i, atom in enumerate(parm.atoms):
        attyp, atname, attchg = atom.type, atom.name, float(atom.charge)
        #print(attchg)
        nbidx = parm.LJ_types[attyp]
        lj_r = float(parm.LJ_radius[nbidx - 1])
        lj_eps = float(parm.LJ_depth[nbidx - 1])
        # change attyp to atnmae
        act = pact.change(parm, '@{} AMBER_ATOM_TYPE {}'.format(atname, atname))
        act.execute()
        # deal with chgs
        if args.input_chg:
            print()
            attchg = get_usr_input('charge', atname, attchg)
        elif args.charge_model == 'opls':
            attchg = opls_chgs[i]
        elif args.charge_f and args.file.endswith('.prmtop'):
            attchg = float(chargef_charges[i])
        attchg = attchg * args.scale_chg
        act = pact.change(parm, '@{} charge {:f}'.format(atname, float(attchg)))
        act.execute()
        # deal with lj
        if args.input_lj:
            if args.lj_radius_type == 'sigma':
                lj_r = lj_r*2./(2**(1./6))  # convert to sigma
            lj_r = get_usr_input('lj_r', atname, lj_r)
            if args.lj_radius_type == 'sigma':
                lj_r = lj_r/2.*(2**(1./6))
            lj_eps = get_usr_input('lj_eps', atname, lj_eps)
        elif args.lennard_jones== 'opls':
            lj_r = opls_radii[i]
            lj_eps = opls_epss[i]
        lj_r = lj_r * args.scale_r
        lj_eps = lj_eps * args.scale_eps
        #print(lj_r, lj_eps)
        act = pact.changeLJSingleType(parm, '@{} {:f} {:f}'.format(atname, lj_r, lj_eps))
        act.execute()
    #parm.overwrite = True
    parm.write_parm(new_name)
if len(sys.argv) < 2:
    print("Args: <mol.topo> ")
    print("Aborted. Please specify the name of the topology file.")
    sys.exit()
elif len(sys.argv) > 2:
    print("Args: <mol.topo> ")
    print("Aborted. Too many arguments!")
    sys.exit()

topfile = sys.argv[1]

if not os.path.isfile(topfile):
    print('The input file %s does not exist.' % topfile)
    sys.exit()

parm = AmberParm(topfile)

bondedInfoFile = open('moleculeInfo', 'w')
action = summary(parm)
action.execute()
bondedInfoFile.write('%s\n' % action)

# Print out force field parameters
action = writeFrcmod(parm, 'FFparameters.dat')
action.execute()

# Generate the "dry" topology file
action = strip(parm, ':WAT')
action.execute()

# Print out the connectivity (bond, angle, torsion) from the dry topology
Esempio n. 29
0
    def write(self, prmtop_name):
        """
        Creates a prmtop with either AMBER or CHARMM parameters.
        """
        self.prmtop_name = prmtop_name

        # Charmm forcefield
        if "charmm" in self.forcefield:
            psfgen = CharmmWriter(molid=self.molid,
                                  tmp_dir=self.tmp_dir,
                                  lipid_sel=self.lipid_sel,
                                  extra_topos=self.extra_topos,
                                  override_defaults=self.override)
            self.topologies = psfgen.write(self.prmtop_name)
            self._psf_to_charmm_amber()

        # Amber forcefield
        elif "amber" in self.forcefield:

            # Initialize the matcher
            self.matcher = AmberMatcher(self.topologies)
            print("Using the following topologies:")
            for top in self.topologies:
                print("  - %s" % top.split("/")[-1])
                top = os.path.abspath(top)

            for par in self.parameters:
                par = os.path.abspath(par)

            # Assign atom types
            print("Assigning AMBER atom types...")
            conect = self._rename_atoms_amber()

            # Create temporary pdb files that will be leap inputs
            pdbs = []
            pdbs.append(self._write_lipids())
            prot_pdbseqs = self._write_protein()
            pdbs.extend(self._write_solvent())
            ligfiles = self._write_ligands()

            # Now invoke leap to create the prmtop and inpcrd
            outfile = self._run_leap(ligfiles, prot_pdbseqs, pdbs, conect)

            # Repartion hydrogen masses if requested
            if self.hmr:
                print("\nRepartitioning hydrogen masses...")
                parm = AmberParm(prm_name=outfile + ".prmtop",
                                 xyz=outfile + ".inpcrd")
                action = HMassRepartition(parm, "dowater")
                action.execute()
                write = parmout(action.parm, "%s.prmtop" % self.prmtop_name)
                #self.prmtop_name))
                write.execute()
                parm = write.parm

            # Check validity of output prmtop using parmed
            parm = AmberParm(prm_name=self.prmtop_name + ".prmtop",
                             xyz=self.prmtop_name + ".inpcrd")
            print("\nChecking for problems with the prmtop...")
            print("        Verify all warnings!")
            action = checkValidity(parm)
            action.execute()

        else:
            raise DabbleError("Unhandled forcefield: %s" % self.forcefield)
Esempio n. 30
0
    def _psf_to_charmm_amber(self):
        """
        Runs the chamber command of ParmEd to produce AMBER format input files.

        Returns:
          True if successful
        """

        # Ask the user for additional parameter files
        if self.prompt_params:
            sys.stdout.flush()
            print("\nCurrently using the following parameter files:")
            for prm in self.parameters:
                print("  - %s" % prm.split("/")[-1])
            print(
                "Enter the path to the filename(s) from the current working "
                "directory, separated by a comma, of any additional prm or str files "
                "you wish to use.\n")
            sys.stdout.flush()
            try:
                input = raw_input
            except NameError:
                pass
            inp = input('> ')
            if inp:
                self.parameters.extend(inp.split(','))
        else:
            print("Using the following parameter files:")
            for prm in self.parameters:
                print("  - %s" % prm.split("/")[-1])
            print("\n")

        # Begin assembling chamber input string
        args = "-crd %s.pdb -psf %s.psf" % (self.prmtop_name, self.prmtop_name)

        # Add topology and parameter arguments
        for inp in set(self.topologies + self.parameters):
            args += ' -toppar %s' % inp

        # Add box information since it is not in the pdb
        box = molecule.get_periodic(molid=self.molid)
        args += " -box %f,%f,%f" % (box['a'], box['b'], box['c'])
        args += " nosettle"

        print("Running chamber. This may take a while...")
        sys.stdout.flush()
        parm = AmberParm()
        with warnings.catch_warnings(record=True) as w:
            action = chamber(parm, args)
            action.execute()
            w = [i for i in w if issubclass(i.category, ParameterWarning)]

        # Do hydrogen mass repartitioning if requested
        if self.hmr:
            print("Repartitioning hydrogen masses...")
            parm = action.parm
            action = HMassRepartition(parm, "dowater")
            print(action)
            action.execute()

        print("\tRan chamber")
        write = parmout(
            action.parm,
            "%s.prmtop %s.inpcrd" % (self.prmtop_name, self.prmtop_name))
        write.execute()
        print("\nWrote output prmtop and inpcrd")
        return True
Esempio n. 31
0
 def setUp(self):
     super().setUp()
     self.amber_gas = AmberParm(self.get_fn('ash.parm7'),
                                self.get_fn('ash.rst7'))
Esempio n. 32
0
class TestStateDataReporter(FileIOTestCase):
    def setUp(self):
        super().setUp()
        self.amber_gas = AmberParm(self.get_fn('ash.parm7'),
                                   self.get_fn('ash.rst7'))

    def test_state_data_reporter(self):
        """ Test StateDataReporter with various options """
        system = self.amber_gas.createSystem()
        integrator = mm.LangevinIntegrator(300 * u.kelvin, 5.0 / u.picoseconds,
                                           1.0 * u.femtoseconds)
        sim = app.Simulation(self.amber_gas.topology,
                             system,
                             integrator,
                             platform=CPU)
        sim.context.setPositions(self.amber_gas.positions)
        f = open(self.get_fn('akma5.dat', written=True), 'w')
        sim.reporters.extend([
            StateDataReporter(self.get_fn('akma1.dat', written=True), 10),
            StateDataReporter(self.get_fn('akma2.dat', written=True),
                              10,
                              time=False,
                              potentialEnergy=False,
                              kineticEnergy=False,
                              totalEnergy=False,
                              temperature=False),
            StateDataReporter(self.get_fn('akma3.dat', written=True),
                              10,
                              volume=True,
                              density=True),
            StateDataReporter(self.get_fn('akma4.dat', written=True),
                              10,
                              separator='\t'),
            StateDataReporter(self.get_fn('units.dat', written=True),
                              10,
                              volume=True,
                              density=True,
                              energyUnit=u.kilojoules_per_mole,
                              volumeUnit=u.nanometers**3),
            StateDataReporter(f, 10)
        ])
        sim.step(500)
        f.close()

        # Now open all of the reporters and check that the information in there
        # is what we expect it to be
        akma1 = open(self.get_fn('akma1.dat', written=True), 'r')
        akma2 = open(self.get_fn('akma2.dat', written=True), 'r')
        akma3 = open(self.get_fn('akma3.dat', written=True), 'r')
        akma4 = open(self.get_fn('akma4.dat', written=True), 'r')
        akma5 = open(self.get_fn('akma5.dat', written=True), 'r')
        units = open(self.get_fn('units.dat', written=True), 'r')
        # AKMA 1 first
        header = akma1.readline().strip()[1:].split(',')
        self.assertEqual(len(header), 6)
        for i, label in enumerate(
            ('Step', 'Time', 'Potential Energy', 'Kinetic Energy',
             'Total Energy', 'Temperature')):
            self.assertTrue(label in header[i])
        for i, line in enumerate(akma1):
            words = line.replace('\n', '').split(',')
            self.assertEqual(i * 10 + 10, int(words[0]))  # step
        akma1.close()
        # AKMA 2
        header = akma2.readline().strip()[1:].split(',')
        self.assertEqual(len(header), 1)
        self.assertTrue('Step' in header[0])
        for i, line in enumerate(akma2):
            self.assertEqual(int(line.replace('\n', '').split(',')[0]),
                             10 * i + 10)
        akma2.close()
        # AKMA 3 -- save energies so we can compare to the file with different
        # units
        header = akma3.readline().strip()[1:].split(',')
        self.assertEqual(len(header), 8)
        for i, label in enumerate(
            ('Step', 'Time', 'Potential Energy', 'Kinetic Energy',
             'Total Energy', 'Temperature', 'Box Volume', 'Density')):
            self.assertTrue(label in header[i])
        akma_energies = [[0.0 for i in range(8)] for j in range(50)]
        for i, line in enumerate(akma3):
            words = line.replace('\n', '').split(',')
            akma_energies[i][0] = int(words[0])
            for j in range(1, 8):
                akma_energies[i][j] = float(words[j])
        akma3.close()
        # AKMA 4 -- tab delimiter
        header = akma4.readline().strip()[1:].split('\t')
        self.assertEqual(len(header), 6)
        for i, label in enumerate(
            ('Step', 'Time', 'Potential Energy', 'Kinetic Energy',
             'Total Energy', 'Temperature')):
            self.assertTrue(label in header[i])
        for i, line in enumerate(akma4):
            words = line.replace('\n', '').split('\t')
            self.assertEqual(i * 10 + 10, int(words[0]))  # step
        akma4.close()
        # AKMA 5 -- write to open file handle
        header = akma5.readline().strip()[1:].split(',')
        self.assertEqual(len(header), 6)
        for i, label in enumerate(
            ('Step', 'Time', 'Potential Energy', 'Kinetic Energy',
             'Total Energy', 'Temperature')):
            self.assertTrue(label in header[i])
        for i, line in enumerate(akma5):
            words = line.replace('\n', '').split(',')
            self.assertEqual(i * 10 + 10, int(words[0]))  # step
        akma5.close()
        # UNITS -- compare other units
        ene = u.kilojoule_per_mole.conversion_factor_to(u.kilocalorie_per_mole)
        volume = u.nanometers.conversion_factor_to(u.angstroms)**3
        conversions = [1, 1, ene, ene, ene, 1, volume, 1]
        headers = units.readline().strip()[1:].split(',')
        self.assertEqual(len(headers), 8)
        for i, line in enumerate(units):
            words = line.replace('\n', '').split(',')
            self.assertEqual(int(words[0]), akma_energies[i][0])
            for j in range(1, 8):
                self.assertAlmostEqual(float(words[j]) * conversions[j],
                                       akma_energies[i][j],
                                       places=5)
        units.close()

    def test_progress_reporter(self):
        """ Test ProgressReporter with various options """
        self.assertRaises(ValueError,
                          lambda: ProgressReporter(sys.stdout, 1, 5))
        system = self.amber_gas.createSystem()
        integrator = mm.LangevinIntegrator(300 * u.kelvin, 5.0 / u.picoseconds,
                                           1.0 * u.femtoseconds)
        sim = app.Simulation(self.amber_gas.topology,
                             system,
                             integrator,
                             platform=CPU)
        sim.context.setPositions(self.amber_gas.positions)
        sim.reporters.append(
            ProgressReporter(self.get_fn('progress_reporter.dat',
                                         written=True),
                             10,
                             500,
                             step=True,
                             time=True,
                             potentialEnergy=True,
                             kineticEnergy=True,
                             totalEnergy=True,
                             temperature=True,
                             volume=True,
                             density=True,
                             systemMass=None))
        sim.step(500)
        self.assertEqual(len(os.listdir(self._temporary_directory.name)), 1)
        text = open(self.get_fn('progress_reporter.dat', written=True),
                    'r').read()
        self.assertTrue('Estimated time to completion' in text)
        self.assertTrue('Total Energy' in text)
        self.assertTrue('Potential Energy' in text)
        self.assertTrue('Kinetic Energy' in text)
        self.assertTrue('Temperature' in text)
Esempio n. 33
0
class TestTrajRestartReporter(FileIOTestCase):
    def setUp(self):
        super().setUp()
        self.amber_gas = AmberParm(self.get_fn('ash.parm7'),
                                   self.get_fn('ash.rst7'))

    def test_reporters(self):
        """ Test NetCDF and ASCII restart and trajectory reporters (no PBC) """
        with self.assertRaises(ValueError):
            NetCDFReporter(self.get_fn('blah', written=True), 1, crds=False)
        with self.assertRaises(ValueError):
            MdcrdReporter(self.get_fn('blah', written=True), 1, crds=False)
        with self.assertRaises(ValueError):
            MdcrdReporter(self.get_fn('blah', written=True),
                          1,
                          crds=True,
                          vels=True)
        system = self.amber_gas.createSystem()
        integrator = mm.LangevinIntegrator(300 * u.kelvin, 5.0 / u.picoseconds,
                                           1.0 * u.femtoseconds)
        sim = app.Simulation(self.amber_gas.topology,
                             system,
                             integrator,
                             platform=CPU)
        sim.context.setPositions(self.amber_gas.positions)
        sim.reporters.extend([
            NetCDFReporter(self.get_fn('traj1.nc', written=True), 10),
            NetCDFReporter(self.get_fn('traj2.nc', written=True),
                           10,
                           vels=True),
            NetCDFReporter(self.get_fn('traj3.nc', written=True),
                           10,
                           frcs=True),
            NetCDFReporter(self.get_fn('traj4.nc', written=True),
                           10,
                           vels=True,
                           frcs=True),
            NetCDFReporter(self.get_fn('traj5.nc', written=True),
                           10,
                           crds=False,
                           vels=True),
            NetCDFReporter(self.get_fn('traj6.nc', written=True),
                           10,
                           crds=False,
                           frcs=True),
            NetCDFReporter(self.get_fn('traj7.nc', written=True),
                           10,
                           crds=False,
                           vels=True,
                           frcs=True),
            MdcrdReporter(self.get_fn('traj1.mdcrd', written=True), 10),
            MdcrdReporter(self.get_fn('traj2.mdcrd', written=True),
                          10,
                          crds=False,
                          vels=True),
            MdcrdReporter(self.get_fn('traj3.mdcrd', written=True),
                          10,
                          crds=False,
                          frcs=True),
            RestartReporter(self.get_fn('restart.ncrst', written=True),
                            10,
                            write_multiple=True,
                            netcdf=True),
            RestartReporter(self.get_fn('restart.rst7', written=True), 10),
        ])
        sim.step(500)
        for reporter in sim.reporters:
            reporter.finalize()

        self.assertEqual(len(os.listdir(self._temporary_directory.name)), 61)
        ntraj = [
            NetCDFTraj.open_old(self.get_fn('traj1.nc', written=True)),
            NetCDFTraj.open_old(self.get_fn('traj2.nc', written=True)),
            NetCDFTraj.open_old(self.get_fn('traj3.nc', written=True)),
            NetCDFTraj.open_old(self.get_fn('traj4.nc', written=True)),
            NetCDFTraj.open_old(self.get_fn('traj5.nc', written=True)),
            NetCDFTraj.open_old(self.get_fn('traj6.nc', written=True)),
            NetCDFTraj.open_old(self.get_fn('traj7.nc', written=True))
        ]
        atraj = [
            AmberMdcrd(self.get_fn('traj1.mdcrd', written=True),
                       self.amber_gas.ptr('natom'),
                       hasbox=False,
                       mode='r'),
            AmberMdcrd(self.get_fn('traj2.mdcrd', written=True),
                       self.amber_gas.ptr('natom'),
                       hasbox=False,
                       mode='r'),
            AmberMdcrd(self.get_fn('traj3.mdcrd', written=True),
                       self.amber_gas.ptr('natom'),
                       hasbox=False,
                       mode='r'),
        ]
        for traj in ntraj:
            self.assertEqual(traj.frame, 50)
            self.assertEqual(traj.Conventions, 'AMBER')
            self.assertEqual(traj.ConventionVersion, '1.0')
            self.assertEqual(traj.application, 'AmberTools')
            self.assertEqual(traj.program, 'ParmEd')
            self.assertFalse(traj.hasbox)
        self.assertTrue(ntraj[0].hascrds)
        self.assertFalse(ntraj[0].hasvels)
        self.assertFalse(ntraj[0].hasfrcs)
        self.assertTrue(ntraj[1].hascrds)
        self.assertTrue(ntraj[1].hasvels)
        self.assertFalse(ntraj[1].hasfrcs)
        self.assertTrue(ntraj[2].hascrds)
        self.assertFalse(ntraj[2].hasvels)
        self.assertTrue(ntraj[2].hasfrcs)
        self.assertTrue(ntraj[3].hascrds)
        self.assertTrue(ntraj[3].hasvels)
        self.assertTrue(ntraj[3].hasfrcs)
        self.assertFalse(ntraj[4].hascrds)
        self.assertTrue(ntraj[4].hasvels)
        self.assertFalse(ntraj[4].hasfrcs)
        self.assertFalse(ntraj[5].hascrds)
        self.assertFalse(ntraj[5].hasvels)
        self.assertTrue(ntraj[5].hasfrcs)
        self.assertFalse(ntraj[6].hascrds)
        self.assertTrue(ntraj[6].hasvels)
        self.assertTrue(ntraj[6].hasfrcs)
        for i in (0, 2, 3, 4, 5, 6):
            ntraj[i].close()  # still need the 2nd
        for traj in atraj:
            traj.close()
        # Now test the NetCDF restart files
        fn = self.get_fn('restart.ncrst.%d', written=True)
        for i, j in enumerate(range(10, 501, 10)):
            ncrst = NetCDFRestart.open_old(fn % j)
            self.assertEqual(ncrst.coordinates.shape, (1, 25, 3))
            self.assertEqual(ncrst.velocities.shape, (1, 25, 3))
            np.testing.assert_allclose(ncrst.coordinates[0],
                                       ntraj[1].coordinates[i])
            np.testing.assert_allclose(ncrst.velocities[0],
                                       ntraj[1].velocities[i],
                                       rtol=1e-6)
        # Now test the ASCII restart file
        f = AmberAsciiRestart(self.get_fn('restart.rst7', written=True), 'r')
        # Compare to ncrst and make sure it's the same data
        np.testing.assert_allclose(ncrst.coordinates, f.coordinates, atol=1e-3)
        np.testing.assert_allclose(ncrst.velocities, f.velocities, rtol=1e-3)
        # Make sure the EnergyMinimizerReporter does not fail
        f = StringIO()
        rep = EnergyMinimizerReporter(f)
        rep.report(sim, frame=10)
        rep.finalize()

    @unittest.skipUnless(HAS_GROMACS, 'Cannot test without GROMACS')
    def test_reporters_pbc(self):
        """ Test NetCDF and ASCII restart and trajectory reporters (w/ PBC) """
        systemsolv = load_file(self.get_fn('ildn.solv.top'),
                               xyz=self.get_fn('ildn.solv.gro'))
        system = systemsolv.createSystem(nonbondedMethod=app.PME,
                                         nonbondedCutoff=8 * u.angstroms)
        integrator = mm.LangevinIntegrator(300 * u.kelvin, 5.0 / u.picoseconds,
                                           1.0 * u.femtoseconds)
        sim = app.Simulation(systemsolv.topology, system, integrator, CPU)
        sim.context.setPositions(systemsolv.positions)
        sim.reporters.extend([
            NetCDFReporter(self.get_fn('traj.nc', written=True),
                           1,
                           vels=True,
                           frcs=True),
            MdcrdReporter(self.get_fn('traj.mdcrd', written=True), 1),
            RestartReporter(self.get_fn('restart.ncrst', written=True),
                            1,
                            netcdf=True),
            RestartReporter(self.get_fn('restart.rst7', written=True), 1),
            StateDataReporter(self.get_fn('state.o', written=True),
                              1,
                              volume=True,
                              density=True,
                              systemMass=1)
        ])
        sim.step(5)
        for reporter in sim.reporters:
            reporter.finalize()
        ntraj = NetCDFTraj.open_old(self.get_fn('traj.nc', written=True))
        atraj = AmberMdcrd(self.get_fn('traj.mdcrd', written=True),
                           len(systemsolv.atoms),
                           True,
                           mode='r')
        nrst = NetCDFRestart.open_old(
            self.get_fn('restart.ncrst', written=True))
        arst = AmberAsciiRestart(self.get_fn('restart.rst7', written=True),
                                 'r')
        self.assertEqual(ntraj.frame, 5)
        self.assertEqual(atraj.frame, 5)
        self.assertTrue(ntraj.hasvels)
        self.assertTrue(ntraj.hasfrcs)
        for i in range(ntraj.frame):
            for x1, x2 in zip(ntraj.box[i], atraj.box[i]):
                self.assertAlmostEqual(x1, x2, places=3)
        self.assertEqual(len(nrst.box), 6)
        self.assertEqual(len(arst.box), 6)
        # Make sure the EnergyMinimizerReporter does not fail
        f = StringIO()
        rep = EnergyMinimizerReporter(f, volume=True)
        rep.report(sim)
        rep.finalize()

    def test_private_functions(self):
        """ Tests private helper functions for OMM reporters """
        self.assertEqual(_format_time(7200), (2, 'hr.'))
        self.assertEqual(_format_time(3600), (60, 'min.'))
        self.assertEqual(_format_time(40), (40, 'sec.'))
Esempio n. 34
0
def main(opt):
    # Check all of the arguments
    if not os.path.exists(opt.prmtop):
        raise AmberError('prmtop file (%s) is missing' % opt.prmtop)

    # Process the arguments that take multiple args
    resstates = process_arglist(opt.resstates, int)
    resnums = process_arglist(opt.resnums, int)
    notresnums = process_arglist(opt.notresnums, int)
    resnames = process_arglist(opt.resnames, str)
    notresnames = process_arglist(opt.notresnames, str)
    minpka = opt.minpka
    maxpka = opt.maxpka

    if not opt.igb in (1, 2, 5, 7, 8):
        raise AmberError('-igb must be 1, 2, 5, 7, or 8!')

    if resnums is not None and notresnums is not None:
        raise AmberError('Cannot specify -resnums and -notresnums together')

    if resnames is not None and notresnames is not None:
        raise AmberError('Cannot specify -resnames and -notresnames together')

    if opt.intdiel != 1 and opt.intdiel != 2:
        raise AmberError('-intdiel must be either 1 or 2 currently')

    # Print warning about old format
    if opt.oldfmt:
        sys.stderr.write(
            'Warning: The old format of the CPIN file can only be used for simulations with temp0=300.0!\n'
            '         You should use the new format for simulations with temperatures other than 300.0 Kelvins\n'
        )

    # Set the list of residue names we will be willing to titrate
    titratable_residues = []
    if notresnames is not None:
        for resname in residues.titratable_residues:
            if resname in notresnames: continue
            titratable_residues.append(resname)
    elif resnames is not None:
        for resname in resnames:
            if not resname in residues.titratable_residues:
                raise AmberError('%s is not a titratable residue!' % resname)
            elif not getattr(residues, resname).typ == "ph":
                raise AmberError('%s is not a pH titratable residue!' %
                                 resname)
            titratable_residues.append(resname)
    else:
        for resname in residues.titratable_residues:
            if getattr(residues, resname).typ == "ph":
                titratable_residues.append(resname)

    solvent_ions = [
        'WAT', 'Na+', 'Br-', 'Cl-', 'Cs+', 'F-', 'I-', 'K+', 'Li+', 'Mg+',
        'Rb+', 'CIO', 'IB', 'MG2'
    ]

    # Filter titratable residues based on min and max pKa
    new_reslist = []
    for res in titratable_residues:
        if getattr(residues, res).pKa < minpka: continue
        if getattr(residues, res).pKa > maxpka: continue
        new_reslist.append(res)
    titratable_residues = new_reslist
    del new_reslist

    # Make sure we still have a couple residues
    if len(titratable_residues) == 0:
        raise AmberError('No titratable residues fit your criteria!')

    # Load the topology file
    parm = AmberParm(opt.prmtop)

    # Replace an un-set notresnums with an empty list so we get __contains__()
    if notresnums is None:
        notresnums = []

    # If we have a list of residue numbers, check that they're all titratable
    if resnums is not None:
        for resnum in resnums:
            if resnum > parm.ptr('nres'):
                raise AmberError('%s only has %d residues. (%d chosen)' %
                                 (parm, parm.ptr('nres'), resnum))
            if resnum <= 0:
                raise AmberError('Cannot select negative residue numbers.')
            resname = parm.parm_data['RESIDUE_LABEL'][resnum - 1]
            if not resname in titratable_residues:
                raise AmberError('Residue number %s [%s] is not titratable' %
                                 (resnum, resname))
    else:
        # Select every residue except those in notresnums
        resnums = []
        for resnum in range(1, parm.ptr('nres') + 1):
            if resnum in notresnums: continue
            resnums.append(resnum)

    solvated = False
    first_solvent = 0
    if 'WAT' in parm.parm_data['RESIDUE_LABEL']:
        solvated = True
        for i, res in enumerate(parm.parm_data['RESIDUE_LABEL']):
            if res in solvent_ions:
                first_solvent = parm.parm_data['RESIDUE_POINTER'][i]
                break
    main_reslist = TitratableResidueList(system_name=opt.system,
                                         solvated=solvated,
                                         first_solvent=first_solvent)
    for resnum in resnums:
        resname = parm.parm_data['RESIDUE_LABEL'][resnum - 1]
        if not resname in titratable_residues: continue
        res = getattr(residues, resname)
        # Filter out termini (make sure the residue in the prmtop has as many
        # atoms as the titratable residue defined in residues.py)
        if resnum == parm.ptr('nres'):
            natoms = (parm.ptr('natom') + 1 -
                      parm.parm_data['RESIDUE_POINTER'][resnum - 1])
        else:
            natoms = (parm.parm_data['RESIDUE_POINTER'][resnum] -
                      parm.parm_data['RESIDUE_POINTER'][resnum - 1])
        if natoms != len(res.atom_list): continue
        # If we have gotten this far, add it to the list.
        main_reslist.add_residue(res, resnum,
                                 parm.parm_data['RESIDUE_POINTER'][resnum - 1])

    # Set the states if requested
    if resstates is not None:
        main_reslist.set_states(resstates)

    # Open the output file
    if opt.output is None:
        output = sys.stdout
    else:
        output = open(opt.output, 'w')

    main_reslist.write_cpin(output, opt.igb, opt.intdiel, opt.oldfmt, "ph")

    if opt.output is not None:
        output.close()

    if solvated:
        if opt.outparm is None:
            has_carboxylate = False
            for res in main_reslist:
                if res is residues.AS4 or res is residues.GL4 or res is residues.PRN:
                    has_carboxylate = True
                    break
            if has_carboxylate:
                sys.stderr.write(
                    'Warning: Carboxylate residues in explicit solvent '
                    'simulations require a modified topology file!\n'
                    'Use the -op flag to print one.\n')
        else:
            changeRadii(parm, 'mbondi2').execute()
            change(parm, 'RADII', ':AS4,GL4,PRN@OD=,OE=,O1=,O2=',
                   1.3).execute()
            parm.overwrite = True
            parm.write_parm(opt.outparm)
    else:
        if opt.outparm is not None:
            sys.stderr.write(
                'A new prmtop is only necessary for explicit solvent '
                'CpHMD/pH-REMD simulations.\n')

    sys.stderr.write('CPIN generation complete!\n')
Esempio n. 35
0
def main(opt):
    # Check all of the arguments
    if not os.path.exists(opt.prmtop):
        raise AmberError('prmtop file (%s) is missing' % opt.prmtop)

    # Process the arguments that take multiple args
    resstates = process_arglist(opt.resstates, int)
    resnums = process_arglist(opt.resnums, int)
    notresnums = process_arglist(opt.notresnums, int)
    resnames = process_arglist(opt.resnames, str)
    notresnames = process_arglist(opt.notresnames, str)
    minpka = opt.minpka
    maxpka = opt.maxpka

    if not opt.igb in (1, 2, 5, 7, 8):
        raise AmberError('-igb must be 1, 2, 5, 7, or 8!')

    if resnums is not None and notresnums is not None:
        raise AmberError('Cannot specify -resnums and -notresnums together')

    if resnames is not None and notresnames is not None:
        raise AmberError('Cannot specify -resnames and -notresnames together')

    if opt.intdiel != 1 and opt.intdiel != 2:
        raise AmberError('-intdiel must be either 1 or 2 currently')

    # Print warning about old format
    if opt.oldfmt:
        sys.stderr.write('Warning: The old format of the CPIN file can only be used for simulations with temp0=300.0!\n'
                         '         You should use the new format for simulations with temperatures other than 300.0 Kelvins\n')

    # Set the list of residue names we will be willing to titrate
    titratable_residues = []
    if notresnames is not None:
        for resname in residues.titratable_residues:
            if resname in notresnames: continue
            titratable_residues.append(resname)
    elif resnames is not None:
        for resname in resnames:
            if not resname in residues.titratable_residues:
                raise AmberError('%s is not a titratable residue!' % resname)
            elif not getattr(residues, resname).typ == "ph":
                raise AmberError('%s is not a pH-active titratable residue!' % resname)
            titratable_residues.append(resname)
    else:
        for resname in residues.titratable_residues:
            if getattr(residues, resname).typ == "ph":
                titratable_residues.append(resname)

    solvent_ions = ['WAT', 'Na+', 'Br-', 'Cl-', 'Cs+', 'F-', 'I-', 'K+', 'Li+',
                    'Mg+', 'Rb+', 'CIO', 'IB', 'MG2']

    # Filter titratable residues based on min and max pKa
    new_reslist = []
    for res in titratable_residues:
        if getattr(residues, res).pKa < minpka: continue
        if getattr(residues, res).pKa > maxpka: continue
        new_reslist.append(res)
    titratable_residues = new_reslist
    del new_reslist

    # Make sure we still have a couple residues
    if len(titratable_residues) == 0:
        raise AmberError('No titratable residues fit your criteria!')

    # Load the topology file
    parm = AmberParm(opt.prmtop)

    # Replace an un-set notresnums with an empty list so we get __contains__()
    if notresnums is None:
        notresnums = []

    # If we have a list of residue numbers, check that they're all titratable
    if resnums is not None:
        for resnum in resnums:
            if resnum > parm.ptr('nres'):
                raise AmberError('%s only has %d residues. (%d chosen)' %
                                     (parm, parm.ptr('nres'), resnum))
            if resnum <= 0:
                raise AmberError('Cannot select negative residue numbers.')
            resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
            if not resname in titratable_residues:
                raise AmberError('Residue number %s [%s] is not titratable'
                                     % (resnum, resname))
    else:
        # Select every residue except those in notresnums
        resnums = []
        for resnum in range(1, parm.ptr('nres') + 1):
            if resnum in notresnums: continue
            resnums.append(resnum)

    solvated = False
    first_solvent = 0
    if 'WAT' in parm.parm_data['RESIDUE_LABEL']:
        solvated = True
        for i, res in enumerate(parm.parm_data['RESIDUE_LABEL']):
            if res in solvent_ions:
                first_solvent = parm.parm_data['RESIDUE_POINTER'][i]
                break
    main_reslist = TitratableResidueList(system_name=opt.system,
                        solvated=solvated, first_solvent=first_solvent)
    trescnt = 0
    for resnum in resnums:
        resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
        if not resname in titratable_residues: continue
        res = getattr(residues, resname)
        # Filter out termini (make sure the residue in the prmtop has as many
        # atoms as the titratable residue defined in residues.py)
        if resnum == parm.ptr('nres'):
            natoms = (parm.ptr('natom') + 1 -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        else:
            natoms = (parm.parm_data['RESIDUE_POINTER'][resnum] -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        if natoms != len(res.atom_list): continue
        # If we have gotten this far, add it to the list.
        main_reslist.add_residue(res, resnum,
                                 parm.parm_data['RESIDUE_POINTER'][resnum-1])
        trescnt += 1

    # Prints a warning if the number of titratable residues is larger than 50
    if trescnt > 50: sys.stderr.write('Warning: Your CPIN file has more than 50 titratable residues! pmemd and sander have a\n'
                                      '         default limit of 50 titrable residues, thus this CPIN file can only be used\n'
                                      '         if the definitions for this limit are modified at the top of\n'
                                      '         $AMBERHOME/src/pmemd/src/constantph.F90 or $AMBERHOME/AmberTools/src/sander/constantph.F90.\n'
                                      '         AMBER needs to be recompilied after these files are modified.\n')

    # Set the states if requested
    if resstates is not None:
        main_reslist.set_states(resstates)

    # Open the output file
    if opt.output is None:
        output = sys.stdout
    else:
        output = open(opt.output, 'w')

    main_reslist.write_cpin(output, opt.igb, opt.intdiel, opt.oldfmt, "ph")

    if opt.output is not None:
        output.close()

    if solvated:
        if opt.outparm is None:
            has_carboxylate = False
            for res in main_reslist:
                if res is residues.AS4 or res is residues.GL4 or res is residues.PRN:
                    has_carboxylate = True
                    break
            if has_carboxylate:
                sys.stderr.write(
                        'Warning: Carboxylate residues in explicit solvent '
                        'simulations require a modified topology file!\n'
                        '         Use the -op flag to print one.\n'
                )
        else:
            changeRadii(parm, 'mbondi2').execute()
            change(parm, 'RADII', ':AS4,GL4,PRN@OD=,OE=,O1=,O2=', 1.3).execute()
            parm.overwrite = True
            parm.write_parm(opt.outparm)
    else:
        if opt.outparm is not None:
            sys.stderr.write(
                    'A new prmtop is only necessary for explicit solvent '
                    'CpHMD/pH-REMD simulations.\n'
            )

    sys.stderr.write('CPIN generation complete!\n')
Esempio n. 36
0
def main(opt):
    # Check all of the arguments
    if not os.path.exists(opt.prmtop):
        raise AmberError('prmtop file (%s) is missing' % opt.prmtop)

    # Process the arguments that take multiple args
    resstates = process_arglist(opt.resstates, int)
    resnums = process_arglist(opt.resnums, int)
    notresnums = process_arglist(opt.notresnums, int)
    resnames = process_arglist(opt.resnames, str)
    notresnames = process_arglist(opt.notresnames, str)
    mineo = opt.mineo
    maxeo = opt.maxeo

    if not opt.igb in (1, 2, 5, 7, 8):
        raise AmberError('-igb must be 1, 2, 5, 7, or 8!')

    if resnums is not None and notresnums is not None:
        raise AmberError('Cannot specify -resnums and -notresnums together')

    if resnames is not None and notresnames is not None:
        raise AmberError('Cannot specify -resnames and -notresnames together')

    if opt.intdiel != 1 and opt.intdiel != 2:
        raise AmberError('-intdiel must be either 1 or 2 currently')

    # Set the list of residue names we will be willing to titrate
    titratable_residues = []
    if notresnames is not None:
        for resname in residues.titratable_residues:
            if resname in notresnames: continue
            titratable_residues.append(resname)
    elif resnames is not None:
        for resname in resnames:
            if not resname in residues.titratable_residues:
                raise AmberError('%s is not a titratable residue!' % resname)
            elif not getattr(residues, resname).typ == "redox":
                raise AmberError(
                    '%s is not a redox-active titratable residue!' % resname)
            titratable_residues.append(resname)
    else:
        for resname in residues.titratable_residues:
            if getattr(residues, resname).typ == "redox":
                titratable_residues.append(resname)

    solvent_ions = [
        'WAT', 'Na+', 'Br-', 'Cl-', 'Cs+', 'F-', 'I-', 'K+', 'Li+', 'Mg+',
        'Rb+', 'CIO', 'IB', 'MG2'
    ]

    # Filter titratable residues based on min and max pKa
    new_reslist = []
    for res in titratable_residues:
        if getattr(residues, res).Eo < mineo: continue
        if getattr(residues, res).Eo > maxeo: continue
        new_reslist.append(res)
    titratable_residues = new_reslist
    del new_reslist

    # Make sure we still have a couple residues
    if len(titratable_residues) == 0:
        raise AmberError('No titratable residues fit your criteria!')

    # Load the topology file
    parm = AmberParm(opt.prmtop)

    # Replace an un-set notresnums with an empty list so we get __contains__()
    if notresnums is None:
        notresnums = []

    # If we have a list of residue numbers, check that they're all titratable
    if resnums is not None:
        for resnum in resnums:
            if resnum > parm.ptr('nres'):
                raise AmberError('%s only has %d residues. (%d chosen)' %
                                 (parm, parm.ptr('nres'), resnum))
            if resnum <= 0:
                raise AmberError('Cannot select negative residue numbers.')
            resname = parm.parm_data['RESIDUE_LABEL'][resnum - 1]
            if not resname in titratable_residues:
                raise AmberError('Residue number %s [%s] is not titratable' %
                                 (resnum, resname))
    else:
        # Select every residue except those in notresnums
        resnums = []
        for resnum in range(1, parm.ptr('nres') + 1):
            if resnum in notresnums: continue
            resnums.append(resnum)

    solvated = False
    first_solvent = 0
    if 'WAT' in parm.parm_data['RESIDUE_LABEL']:
        solvated = True
        for i, res in enumerate(parm.parm_data['RESIDUE_LABEL']):
            if res in solvent_ions:
                first_solvent = parm.parm_data['RESIDUE_POINTER'][i]
                break
    main_reslist = TitratableResidueList(system_name=opt.system,
                                         solvated=solvated,
                                         first_solvent=first_solvent)
    trescnt = 0
    for resnum in resnums:
        resname = parm.parm_data['RESIDUE_LABEL'][resnum - 1]
        if not resname in titratable_residues: continue
        res = getattr(residues, resname)
        # Filter out termini (make sure the residue in the prmtop has as many
        # atoms as the titratable residue defined in residues.py)
        if resnum == parm.ptr('nres'):
            natoms = (parm.ptr('natom') + 1 -
                      parm.parm_data['RESIDUE_POINTER'][resnum - 1])
        else:
            natoms = (parm.parm_data['RESIDUE_POINTER'][resnum] -
                      parm.parm_data['RESIDUE_POINTER'][resnum - 1])
        if natoms != len(res.atom_list): continue
        # If we have gotten this far, add it to the list.
        main_reslist.add_residue(res, resnum,
                                 parm.parm_data['RESIDUE_POINTER'][resnum - 1])
        trescnt += 1

    # Prints a warning if the number of titratable residues is larger than 50
    if trescnt > 50:
        sys.stderr.write(
            'Warning: Your CEIN file has more than 50 titratable residues! pmemd and sander have a\n'
            '         default limit of 50 titrable residues, thus this CEIN file can only be used\n'
            '         if the definitions for this limit are modified at the top of\n'
            '         $AMBERHOME/src/pmemd/src/constante.F90 or $AMBERHOME/AmberTools/src/sander/constante.F90.\n'
            '         AMBER needs to be recompilied after these files are modified.\n'
        )

    # Set the states if requested
    if resstates is not None:
        main_reslist.set_states(resstates)

    # Open the output file
    if opt.output is None:
        output = sys.stdout
    else:
        output = open(opt.output, 'w')

    main_reslist.write_cpin(output, opt.igb, opt.intdiel, False, "redox")

    if opt.output is not None:
        output.close()

    sys.stderr.write('CEIN generation complete!\n')
Esempio n. 37
0
def main(opt):
    # Check all of the arguments
    if not os.path.exists(opt.prmtop):
        raise AmberError('prmtop file (%s) is missing' % opt.prmtop)

    # Process the arguments that take multiple args
    resstates = process_arglist(opt.resstates, int)
    resnums = process_arglist(opt.resnums, int)
    notresnums = process_arglist(opt.notresnums, int)
    resnames = process_arglist(opt.resnames, str)
    notresnames = process_arglist(opt.notresnames, str)
    mineo = opt.mineo
    maxeo = opt.maxeo

    if not opt.igb in (1, 2, 5, 7, 8):
        raise AmberError('-igb must be 1, 2, 5, 7, or 8!')

    if resnums is not None and notresnums is not None:
        raise AmberError('Cannot specify -resnums and -notresnums together')

    if resnames is not None and notresnames is not None:
        raise AmberError('Cannot specify -resnames and -notresnames together')

    if opt.intdiel != 1 and opt.intdiel != 2:
        raise AmberError('-intdiel must be either 1 or 2 currently')

    # Set the list of residue names we will be willing to titrate
    titratable_residues = []
    if notresnames is not None:
        for resname in residues.titratable_residues:
            if resname in notresnames: continue
            titratable_residues.append(resname)
    elif resnames is not None:
        for resname in resnames:
            if not resname in residues.titratable_residues:
                raise AmberError('%s is not a titratable residue!' % resname)
            elif not getattr(residues, resname).typ == "redox":
                raise AmberError('%s is not a redox-active titratable residue!' % resname)
            titratable_residues.append(resname)
    else:
        for resname in residues.titratable_residues:
            if getattr(residues, resname).typ == "redox":
                titratable_residues.append(resname)

    solvent_ions = ['WAT', 'Na+', 'Br-', 'Cl-', 'Cs+', 'F-', 'I-', 'K+', 'Li+',
                    'Mg+', 'Rb+', 'CIO', 'IB', 'MG2']

    # Filter titratable residues based on min and max pKa
    new_reslist = []
    for res in titratable_residues:
        if getattr(residues, res).Eo < mineo: continue
        if getattr(residues, res).Eo > maxeo: continue
        new_reslist.append(res)
    titratable_residues = new_reslist
    del new_reslist

    # Make sure we still have a couple residues
    if len(titratable_residues) == 0:
        raise AmberError('No titratable residues fit your criteria!')

    # Load the topology file
    parm = AmberParm(opt.prmtop)

    # Replace an un-set notresnums with an empty list so we get __contains__()
    if notresnums is None:
        notresnums = []

    # If we have a list of residue numbers, check that they're all titratable
    if resnums is not None:
        for resnum in resnums:
            if resnum > parm.ptr('nres'):
                raise AmberError('%s only has %d residues. (%d chosen)' %
                                     (parm, parm.ptr('nres'), resnum))
            if resnum <= 0:
                raise AmberError('Cannot select negative residue numbers.')
            resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
            if not resname in titratable_residues:
                raise AmberError('Residue number %s [%s] is not titratable'
                                     % (resnum, resname))
    else:
        # Select every residue except those in notresnums
        resnums = []
        for resnum in range(1, parm.ptr('nres') + 1):
            if resnum in notresnums: continue
            resnums.append(resnum)

    solvated = False
    first_solvent = 0
    if 'WAT' in parm.parm_data['RESIDUE_LABEL']:
        solvated = True
        for i, res in enumerate(parm.parm_data['RESIDUE_LABEL']):
            if res in solvent_ions:
                first_solvent = parm.parm_data['RESIDUE_POINTER'][i]
                break
    main_reslist = TitratableResidueList(system_name=opt.system,
                        solvated=solvated, first_solvent=first_solvent)
    trescnt = 0
    for resnum in resnums:
        resname = parm.parm_data['RESIDUE_LABEL'][resnum-1]
        if not resname in titratable_residues: continue
        res = getattr(residues, resname)
        # Filter out termini (make sure the residue in the prmtop has as many
        # atoms as the titratable residue defined in residues.py)
        if resnum == parm.ptr('nres'):
            natoms = (parm.ptr('natom') + 1 -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        else:
            natoms = (parm.parm_data['RESIDUE_POINTER'][resnum] -
                      parm.parm_data['RESIDUE_POINTER'][resnum-1])
        if natoms != len(res.atom_list): continue
        # If we have gotten this far, add it to the list.
        main_reslist.add_residue(res, resnum,
                                 parm.parm_data['RESIDUE_POINTER'][resnum-1])
        trescnt += 1

    # Prints a warning if the number of titratable residues is larger than 50
    if trescnt > 50: sys.stderr.write('Warning: Your CEIN file has more than 50 titratable residues! pmemd and sander have a\n'
                                      '         default limit of 50 titrable residues, thus this CEIN file can only be used\n'
                                      '         if the definitions for this limit are modified at the top of\n'
                                      '         $AMBERHOME/src/pmemd/src/constante.F90 or $AMBERHOME/AmberTools/src/sander/constante.F90.\n'
                                      '         AMBER needs to be recompilied after these files are modified.\n')

    # Set the states if requested
    if resstates is not None:
        main_reslist.set_states(resstates)

    # Open the output file
    if opt.output is None:
        output = sys.stdout
    else:
        output = open(opt.output, 'w')

    main_reslist.write_cpin(output, opt.igb, opt.intdiel, False, "redox")

    if opt.output is not None:
        output.close()

    sys.stderr.write('CEIN generation complete!\n')