Exemplo n.º 1
0
    def test_update_param_struct_cont(self):
        """ Tests that update parameter updates assigned parameters in the structure """
        param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                                   get_fn('par_all36_cgenff.prm'))
        structure = get_fn('butane.psf')
        logfiles = get_fn('MP2_torsion_scan/')
        frag = qmdb.parse_psi4_out(logfiles, structure)
        frag = frag.remove_nonoptimized()
        to_optimize = [('CG331', 'CG321', 'CG321', 'CG331')]

        model = TorsionFitModelOMM(param=param,
                                   frags=frag,
                                   param_to_opt=to_optimize,
                                   sample_phase=True,
                                   continuous_phase=True)
        par.update_param_from_sample(model.parameters_to_optimize,
                                     param,
                                     model=model,
                                     rj=model.rj,
                                     phase=model.sample_phase,
                                     n_5=model.sample_n5,
                                     model_type='openmm')
        torsion = frag.structure.dihedrals[0]
        self.assertEqual(
            torsion.type,
            param.dihedral_types[(torsion.atom1.type, torsion.atom2.type,
                                  torsion.atom3.type, torsion.atom4.type)])
Exemplo n.º 2
0
 def test_par_parameters(self, ethane):
     ethane.save(filename='ethane-opls.par', forcefield_name='oplsaa')
     from parmed.charmm import CharmmParameterSet
     pset = CharmmParameterSet.load_set(pfile='ethane-opls.par')
     assert len(pset.bond_types) == 3
     assert len(pset.angle_types) == 3
     assert len(pset.atom_types) == 2
Exemplo n.º 3
0
    def __init__(self, true_value=None, initial_value=None, n_increments=18, rj=True, sample_phase=False,
                 continuous=False):
        self._param = CharmmParameterSet(get_fun('toy.str'))
        self._struct = CharmmPsfFile(get_fun('toy.psf'))
        self._pdb = app.PDBFile(get_fun('toy.pdb'))
        self._topology = md.load_psf(get_fun('toy.psf'))
        self.synthetic_energy = units.Quantity()
        self._positions = units.Quantity()
        self._platform = mm.Platform.getPlatformByName('Reference')

        # Replace ('CG331', 'CG321', 'CG321', 'CG331') torsion with true_value
        self._dih_type = ('CG331', 'CG321', 'CG321', 'CG331')
        original_torsion = self._param.dihedral_types[self._dih_type]
        if true_value is not None:
            if type(true_value) == DihedralTypeList:
                dih_tlist = true_value
            elif type(true_value) == DihedralType:
                dih_tlist = DihedralTypeList()
                dih_tlist.append(true_value)
        else:
            dih_tlist = self._randomize_dih_param(return_dih=True)
        self.true_value = copy.deepcopy(dih_tlist)
        self._param.dihedral_types[self._dih_type] = dih_tlist

        # parametrize toy
        self._struct.load_parameters(self._param, copy_parameters=False)
        self._struct.positions = self._pdb.positions

        # generate synthetic torsion scan
        self._torsion_scan(n_increments=n_increments)

        # initialize parameter
        if initial_value is not None:
            if type(initial_value) == DihedralTypeList:
                dih_tlist = initial_value
            if type(initial_value) == DihedralType:
                dih_tlist = DihedralTypeList()
                dih_tlist.append(initial_value)
            elif initial_value == 'cgenff':
                dih_tlist = original_torsion
        else:
            dih_tlist = self._randomize_dih_param(return_dih=True)

        self.initial_value = copy.deepcopy(dih_tlist)
        self._param.dihedral_types[self._dih_type] = dih_tlist

        # create torsionfit.TorsionScanSet
        torsions = np.zeros((len(self._positions), 4))
        torsions[:] = [1, 2, 3, 4]
        direction = None
        steps = None
        self.scan_set = ScanSet.QMDataBase(positions=self._positions.value_in_unit(units.nanometers),
                                           topology=self._topology, structure=self._struct, torsions=torsions,
                                           steps=steps, directions=direction,
                                           qm_energies=self.synthetic_energy.value_in_unit(units.kilojoules_per_mole))

        self.model = model.TorsionFitModel(param=self._param, frags=self.scan_set, platform=self._platform,
                                           param_to_opt=[self._dih_type], rj=rj, continuous_phase=continuous,
                                           sample_phase=sample_phase)
Exemplo n.º 4
0
    def test_create_simple_system(self):
        psf = CharmmPsfFile(get_fn("ala3_solv_drude.psf"))
        crd = CharmmCrdFile(get_fn("ala3_solv_drude.crd"))

        params = CharmmParameterSet(
            get_fn("toppar_drude_master_protein_2013e.str"))

        system = psf.createSystem(params)
Exemplo n.º 5
0
 def test_copy_torsions(self):
     """ Test copy torsions"""
     structure = get_fn('butane.psf')
     scan = get_fn('MP2_torsion_scan/')
     test_scan = qmdb.parse_psi4_out(scan, structure)
     param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                                get_fn('par_all36_cgenff.prm'))
     test_scan.compute_energy(param)
     test_scan.copy_torsions()
Exemplo n.º 6
0
 def test_create_context(self):
     """ Test create context """
     structure = get_fn('butane.psf')
     scan = get_fn('MP2_torsion_scan/')
     test_scan = qmdb.parse_psi4_out(scan, structure)
     param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                                get_fn('par_all36_cgenff.prm'))
     test_scan.integrator = mm.VerletIntegrator(0.004 * u.picoseconds)
     test_scan.create_context(param)
Exemplo n.º 7
0
 def test_to_optimize(self):
     """Tests generate to_optimize list"""
     param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                                get_fn('par_all36_cgenff.prm'))
     stream = (get_fn('PRL.str'))
     to_optimize = qmdb.to_optimize(param, stream)
     self.assert_(len(to_optimize) == 19)
     reverse = tuple(reversed(to_optimize[0]))
     self.assert_(reverse not in to_optimize)
Exemplo n.º 8
0
 def __init__(self,
              psf_filepath,
              param_filepath,
              crds=None,
              positions=None):
     super(Molecule, self).__init__()
     self.psf = pmd.load_file(psf_filepath)
     self.params = CharmmParameterSet(param_filepath)
     self.crds = crds
     self.initialize(positions)
Exemplo n.º 9
0
    def generate_nonbonded_params(self):
        """
        Obtains non-bonded parameters for each atom in the system.
        """

        # use parmed to get parameters
        self.water_sites = self.wat_oxygen_atom_ids[1] - self.wat_oxygen_atom_ids[0]

        vdw = []
        chg = []
        if self.supporting_file.endswith(".txt"):
            nb_data = np.loadtxt(self.supporting_file)
            for c in nb_data[:, 0]:
                chg.append(c)
            for v in nb_data[:, 1:]:
                vdw.append(v)
            chg = np.asarray(chg)

        elif self.topology_file.endswith(".psf"):
            parmed_topology_object = pmd.load_file(self.topology_file)
            param_dir = os.path.abspath(self.supporting_file)
            param_files = [os.path.join(param_dir, f) for f in os.listdir(param_dir) 
                if os.path.isfile(os.path.join(param_dir, f)) and f.endswith((".rtf", ".top", ".par", ".prm", ".inp", ".str"))]
            params = CharmmParameterSet(*param_files)
            try:
                parmed_topology_object.load_parameters(params)
            except Exception as e:
                print(e)
            for at in self.all_atom_ids:
                vdw.append([parmed_topology_object.atoms[at].sigma,
                            parmed_topology_object.atoms[at].epsilon])
                chg.append(parmed_topology_object.atoms[at].charge)

        # .prmtop, .gro, .
        else:
            parmed_topology_object = pmd.load_file(self.supporting_file)
            for at in self.all_atom_ids:
                vdw.append([parmed_topology_object.atoms[at].sigma,
                            parmed_topology_object.atoms[at].epsilon])
                chg.append(parmed_topology_object.atoms[at].charge)

        # User provided charges are supposed to be in correct units.
        if not self.supporting_file.endswith(".txt"):
            chg = np.asarray(chg) * 18.2223
        vdw = np.asarray(vdw)
        water_chg = chg[self.wat_atom_ids[0:self.water_sites]].reshape(self.water_sites, 1)
        self.chg_product = water_chg * np.tile(chg[self.all_atom_ids], (self.water_sites, 1))
        water_sig = vdw[self.wat_atom_ids[0:self.water_sites], 0].reshape(self.water_sites, 1)
        water_eps = vdw[self.wat_atom_ids[0:self.water_sites], 1].reshape(self.water_sites, 1)
        self.acoeff, self.bcoeff = self.apply_combination_rules(water_sig, water_eps, vdw, self.comb_rule)
        """
Exemplo n.º 10
0
 def test_compute_energy(self):
     """ Tests compute mm energy"""
     structure = get_fn('butane.psf')
     scan = get_fn('MP2_torsion_scan/')
     test_scan = qmdb.parse_psi4_out(scan, structure, pattern="*.out2")
     param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                                get_fn('par_all36_cgenff.prm'))
     self.assertFalse(test_scan._have_mm_energy)
     scan_opt = test_scan.remove_nonoptimized()
     scan_opt.compute_energy(param)
     self.assertTrue(scan_opt._have_mm_energy)
     mm_energy = np.array([
         22.66381775, 13.11040092, 3.04552792, 7.83767718, 15.21426107,
         7.0116804, 0., 7.00802623, 15.21461956, 7.83696204, 3.04525798,
         13.10813678, 22.66375837
     ])
     np.testing.assert_almost_equal(scan_opt.mm_energy._value, mm_energy, 4)
Exemplo n.º 11
0
    def test_update_param_continuous(self):
        """ Tests that update parameter updates the reverse dihedral too in continuous  """

        param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                                   get_fn('par_all36_cgenff.prm'))
        structure = get_fn('butane.psf')
        logfiles = get_fn('MP2_torsion_scan/')
        frag = qmdb.parse_psi4_out(logfiles, structure)
        frag = frag.remove_nonoptimized()
        to_optimize = [('CG331', 'CG321', 'CG321', 'CG331')]

        model = TorsionFitModelOMM(param=param,
                                   frags=frag,
                                   param_to_opt=to_optimize,
                                   sample_phase=True,
                                   continuous_phase=True)
        torsion = model.parameters_to_optimize[0]
        torsion_reverse = tuple(reversed(torsion))
        self.assertEqual(param.dihedral_types[torsion],
                         param.dihedral_types[torsion_reverse])
Exemplo n.º 12
0
    def test_add_missing_cond(self):
        """ Tests that add_missing adds missing terms to parameters_to_optimize """

        param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                                   get_fn('par_all36_cgenff.prm'))
        structure = get_fn('butane.psf')
        logfiles = get_fn('MP2_torsion_scan/')
        frag = qmdb.parse_psi4_out(logfiles, structure)
        frag = frag.remove_nonoptimized()
        to_optimize = [('CG331', 'CG321', 'CG321', 'HGA2')]

        model = TorsionFitModelOMM(param=param,
                                   frags=frag,
                                   param_to_opt=to_optimize,
                                   sample_phase=True,
                                   continuous_phase=True)

        par.add_missing(param_list=to_optimize, param=param)
        for i in model.frags[0].structure.dihedrals:
            key = (i.atom1.type, i.atom2.type, i.atom3.type, i.atom4.type)
            key_reverse = tuple(reversed(key))
            if key in model.parameters_to_optimize or key_reverse in model.parameters_to_optimize:
                self.assert_(len(i.type) == 5)
from torsionfit.hydration_energy import energy
from parmed.charmm import CharmmParameterSet
try:
    import cPickle as pickle
except:
    import pickle

# Load CHARMM parameters files
params = CharmmParameterSet('../../charmm_ff/top_all36_cgenff.rtf',
                            '../../charmm_ff/par_all36_cgenff.prm',
                            '../../charmm_ff/toppar_water_ions.str',
                            '../pyrrol.str')

db = energy.create_openmm_system('pyrrole', '../structure', params)
db_solv = energy.generate_simulation_data(db, params, n_steps=3000, n_iter=400)

# remove system and context because pickle is giving me problems pickling them

db_new = {}
for key in db_solv['solvated'].keys():
    if key == 'system' or key == 'context':
        continue
    db_new[key] = db_solv['solvated'][key]

pickle.dump(db_new, open('solvated.pickle', 'w'))
pickle.dump(db_solv, open('solvated_test.pickle', 'w'))
    def generate_nonbonded_params(self):
        """
        Generates non-bonded parameters for energy calculations.

        Returns
        -------
        chg_product : numpy.ndarray
            An N_sites x N_particles matrix where N_sites is the number of sites in the water model and N_atoms
            is the total number of particles in the system, each entry of the matrix is the product of the charges
            q_i*q_j used for the calculation of electrostatic interactions.
        acoeff : numpy.ndarray
            An N_sites x N_particles matrix where N_sites is the number of sites in the water model and N_atoms
            is the total number of particles in the system, each entry of the matrix is the A coefficient in the
            AB form of Lennard Jones potential.
        bcoeff  : numpy.ndarray
            An N_sites x N_particles matrix where N_sites is the number of sites in the water model and N_atoms
            is the total number of particles in the system, each entry of the matrix is the B coefficient in the
            AB form of Lennard Jones potential.
        """

        vdw = []
        chg = []
        if self.supporting_file.endswith(".txt"):
            nb_data = np.loadtxt(self.supporting_file)
            for c in nb_data[:, 0]:
                chg.append(c)
            for v in nb_data[:, 1:]:
                vdw.append(v)
            chg = np.asarray(chg)
        elif self.supporting_file.endswith(".txth5"):
            nb_data = np.loadtxt(self.supporting_file)
            for c in nb_data[:, 0]:
                chg.append(c)
            for v in nb_data[:, 1:]:
                vdw.append(v)

        elif self.topology_file.endswith(".psf"):
            parmed_topology_object = pmd.load_file(self.topology_file)
            param_dir = os.path.abspath(self.supporting_file)
            param_files = [
                os.path.join(param_dir, f) for f in os.listdir(param_dir)
                if os.path.isfile(os.path.join(param_dir, f)) and f.endswith((
                    ".rtf", ".top", ".par", ".prm", ".inp", ".str"))
            ]
            params = CharmmParameterSet(*param_files)
            try:
                parmed_topology_object.load_parameters(params)
            except Exception as e:
                print(e)
            for at in self.all_atom_ids:
                vdw.append([
                    parmed_topology_object.atoms[at].sigma,
                    parmed_topology_object.atoms[at].epsilon
                ])
                chg.append(parmed_topology_object.atoms[at].charge)
        else:
            parmed_topology_object = pmd.load_file(self.supporting_file)
            for at in self.all_atom_ids:
                vdw.append([
                    parmed_topology_object.atoms[at].sigma,
                    parmed_topology_object.atoms[at].epsilon
                ])
                chg.append(parmed_topology_object.atoms[at].charge)

        # User provided charges are assumed to be in correct units.
        # TODO: Make the units for charges explicit in docstring
        if not self.supporting_file.endswith(".txt"):
            chg = np.asarray(chg) * 18.2223
        vdw = np.asarray(vdw)
        water_chg = chg[self.wat_atom_ids[0:self.water_sites]].reshape(
            self.water_sites, 1)
        chg_product = water_chg * np.tile(chg[self.all_atom_ids],
                                          (self.water_sites, 1))

        water_sig = vdw[self.wat_atom_ids[0:self.water_sites],
                        0].reshape(self.water_sites, 1)
        water_eps = vdw[self.wat_atom_ids[0:self.water_sites],
                        1].reshape(self.water_sites, 1)
        mixed_sig, mixed_eps = None, None
        if self.comb_rule is None or self.comb_rule == "lorentz-bertholot":
            mixed_sig = 0.5 * (water_sig + vdw[self.all_atom_ids, 0])
            mixed_eps = np.sqrt(water_eps * vdw[self.all_atom_ids, 1])
        if self.comb_rule == "geometric":
            mixed_sig = np.sqrt(water_sig * vdw[self.all_atom_ids, 0])
            mixed_eps = np.sqrt(water_eps * vdw[self.all_atom_ids, 1])

        if mixed_eps is not None and mixed_sig is not None:
            acoeff = 4 * mixed_eps * (mixed_sig**12)
            bcoeff = 4 * mixed_eps * (mixed_sig**6)
        else:
            raise Exception("Couldn't assign vdw params")
        return chg_product, acoeff, bcoeff
Exemplo n.º 15
0
import unittest
from utils import get_fn, TestCaseRelative, mm, app, has_openmm, CPU, Reference
import warnings

# Suppress warning output from bad psf file... sigh.
warnings.filterwarnings('ignore', category=CharmmWarning)

# System
charmm_gas = CharmmPsfFile(get_fn('ala_ala_ala.psf'))
charmm_gas_crds = load_file(get_fn('ala_ala_ala.pdb'))
charmm_nbfix = CharmmPsfFile(get_fn('ala3_solv.psf'))
charmm_nbfix_crds = CharmmCrdFile(get_fn('ala3_solv.crd'))
charmm_nbfix.box = [3.271195e1, 3.299596e1, 3.300715e1, 90, 90, 90]

# Parameter sets
param22 = CharmmParameterSet(get_fn('top_all22_prot.inp'),
                             get_fn('par_all22_prot.inp'))
param36 = CharmmParameterSet(get_fn('par_all36_prot.prm'),
                             get_fn('toppar_water_ions.str'))

@unittest.skipUnless(has_openmm, "Cannot test without OpenMM")
class TestCharmmFiles(TestCaseRelative):

    def test_gas_energy(self):
        """ Compare OpenMM and CHARMM gas phase energies """
        parm = charmm_gas
        system = parm.createSystem(param22)
        self.assertEqual(parm.combining_rule, 'lorentz')
        integrator = mm.VerletIntegrator(1.0*u.femtoseconds)
        sim = app.Simulation(parm.topology, system, integrator, platform=CPU)
        sim.context.setPositions(charmm_gas_crds.positions)
        energies = energy_decomposition(parm, sim.context)
Exemplo n.º 16
0
from torsionfit.hydration_energy import energy
from parmed.charmm import CharmmParameterSet, CharmmPsfFile
from parmed.topologyobjects import DihedralType
import cPickle as pickle
from torsionfit import sqlite_plus, utils
import simtk.openmm as mm
import simtk.unit as u
import simtk.openmm.app as app
from pymbar import timeseries
import numpy as np
from tqdm import *

param_1 = CharmmParameterSet('../../data/charmm_ff/par_all36_cgenff.prm',
                             '../../data/charmm_ff/top_all36_prot.rtf',
                             '../../data/charmm_ff/toppar_water_ions.str')
param_2 = CharmmParameterSet('../../data/charmm_ff/par_all36_cgenff.prm',
                             '../../data/charmm_ff/top_all36_prot.rtf',
                             '../../data/charmm_ff/toppar_water_ions.str')
database = energy.create_openmm_system('butane', '../structure/', param_1)

solvated = pickle.load(open('solvated.pickle', 'r'))
vacuum = pickle.load(open('vacuum_db.pickle', 'r'))

database['solvated']['x_n'] = solvated['solvated']['x_n']
database['solvated']['u_n'] = solvated['solvated']['u_n']
database['vacuum']['x_n'] = vacuum['vacuum']['x_n']
database['vacuum']['u_n'] = vacuum['vacuum']['u_n']

# load sampled parameters
db = sqlite_plus.load('../butane_n5_decouple_n.db')
Exemplo n.º 17
0
def compare_energies(system_name,
                     pdb_filename,
                     psf_filename,
                     ffxml_filenames,
                     toppar_filenames,
                     box_vectors_filename=None,
                     system_kwargs=None,
                     tolerance=1e-5,
                     units=u.kilojoules_per_mole,
                     write_serialized_xml=False):
    """
    Compare energies between (pdb, psf, toppar) loaded via ParmEd and (pdb, ffxml) loaded by OpenMM ForceField

    Parameters
    ----------
    system_name : str
        Name of the test system
    pdb_filename : str
        Name of PDB file that should contain CRYST entry and PDB format compliant CONECT records for HETATM residues.
    psf_filename : str
        CHARMM PSF file
    ffxml_filenames : list of str
        List of OpenMM ffxml files
    toppar_filenames : list of CHARMM toppar filenames to load into CharmmParameterSet
        List of CHARMM toppar files
    box_vectors_filename : str, optional, default=None
        If specified, read box vectors from a file like step2.1_waterbox.prm
    system_kwargs : dict, optional, default=None
        Keyword arguments to pass to CharmmPsfFile.createSystem() and ForceField.CreateSystem() when constructing System objects for energy comparison
    tolerance : float, optional, default=1e-5
        Relative energy discrepancy tolerance
    units : simtk.unit.Unit
        Unit to use for energy comparison
    write_serialized_xml : bool, optional, default=False
        If True, will write out serialized System XML files for OpenMM systems to aid debugging.

    """

    is_periodic = False
    if (system_kwargs is not None) and ('nonbondedMethod'
                                        in system_kwargs) and (
                                            system_kwargs['nonbondedMethod']
                                            in [app.CutoffPeriodic, app.PME]):
        is_periodic = True

    # Load PDB file
    pdbfile = app.PDBFile(pdb_filename)

    # Read box vectors
    if box_vectors_filename:
        box_vectors = read_box_vectors(box_vectors_filename)
        pdbfile.topology.setPeriodicBoxVectors(box_vectors)
    else:
        box_vectors = pdbfile.topology.getPeriodicBoxVectors()

    # Load CHARMM system through OpenMM
    openmm_toppar = app.CharmmParameterSet(*toppar_filenames)
    openmm_psf = app.CharmmPsfFile(psf_filename)
    # Set box vectors
    if is_periodic:
        openmm_psf.setBox(box_vectors[0][0], box_vectors[1][1],
                          box_vectors[2][2])
    openmm_system = openmm_psf.createSystem(openmm_toppar, **system_kwargs)
    openmm_structure = openmm.load_topology(openmm_psf.topology,
                                            openmm_system,
                                            xyz=pdbfile.positions)
    #openmm_energies = openmm.energy_decomposition_system(openmm_structure, openmm_system, nrg=units)
    #print('OpenMM CHARMM loader energy components : %s' % str(openmm_energies))
    openmm_total_energy = compute_potential(openmm_system,
                                            pdbfile.positions) / units

    # Load CHARMM system through ParmEd
    parmed_toppar = CharmmParameterSet(*toppar_filenames)
    parmed_structure = CharmmPsfFile(psf_filename)
    #structure.load_parameters(toppar)
    parmed_structure.positions = pdbfile.positions
    # Set box vectors
    if is_periodic:
        parmed_structure.box = (box_vectors[0][0] / u.angstroms,
                                box_vectors[1][1] / u.angstroms,
                                box_vectors[2][2] / u.angstroms, 90, 90, 90)
    parmed_system = parmed_structure.createSystem(parmed_toppar,
                                                  **system_kwargs)
    #parmed_energies = openmm.energy_decomposition_system(parmed_structure, parmed_system, nrg=units)
    #print('ParmEd CHARMM loader energy components : %s' % str(parmed_energies))
    parmed_total_energy = compute_potential(parmed_system,
                                            pdbfile.positions) / units

    # Delete H-H bonds from waters and retreive updated topology and positions
    modeller = app.Modeller(openmm_psf.topology, pdbfile.positions)
    hhbonds = [
        b for b in modeller.topology.bonds()
        if b[0].element == app.element.hydrogen
        and b[1].element == app.element.hydrogen
    ]
    modeller.delete(hhbonds)
    ffxml_topology = modeller.topology

    # OpenMM system with ffxml
    ff = app.ForceField(*ffxml_filenames)
    ffxml_system = ff.createSystem(ffxml_topology, **system_kwargs)
    ffxml_structure = openmm.load_topology(ffxml_topology,
                                           ffxml_system,
                                           xyz=pdbfile.positions)
    #ffxml_energies = openmm.energy_decomposition_system(ffxml_structure, ffxml_system, nrg=units)
    #print('ffxml energy components : %s' % str(ffxml_energies))
    ffxml_total_energy = compute_potential(ffxml_system,
                                           pdbfile.positions) / units

    write_serialized_xml = True  # DEBUG
    if write_serialized_xml:
        print('Writing serialized XML files...')
        write_serialized_system(system_name + '.charmm.system.xml',
                                openmm_system)
        write_serialized_system(system_name + '.parmed.system.xml',
                                parmed_system)
        write_serialized_system(system_name + '.openmm.system.xml',
                                ffxml_system)

    print('-' * 100)
    print('')
    print('OpenMM CHARMM reader total energy: %14.3f' % openmm_total_energy)
    print('ParmEd CHARMM reader total energy: %14.3f' % parmed_total_energy)
    print('OPENMM ffxml total energy:         %14.3f' % ffxml_total_energy)
    print('TOTAL ERROR:                       %14.3f' %
          (ffxml_total_energy - openmm_total_energy))
    print('')

    print('-' * 100)

    # TODO : Automate comparison
    return

    # calc rel energies and assert
    rel_energies = []
    for i, j in zip(ffxml_energies, parmed_energies):
        if i[0] != j[0]:
            raise Exception('Mismatch in energy tuples naming.')
        if abs(i[1]) > NEARLYZERO:
            rel_energies.append((i[0], abs((i[1] - j[1]) / i[1])))
        else:
            if abs(j[1]) > NEARLYZERO:
                raise AssertionError(
                    'One of the CHARMM %s energies (%s) for %s is zero, '
                    'while the corresponding OpenMM energy is non-zero' %
                    (system_name, i[0], ffxml))
            rel_energies.append((i[0], 0))

    dihedrals_done = False
    for i in rel_energies:
        if i[0] != 'PeriodicTorsionForce':
            if i[1] > tolerance:
                raise AssertionError(
                    '%s energies (%s, %f) outside of allowed tolerance (%f) for %s'
                    % (system_name, i[0], i[1], tolerance, ffxml))
        else:
            if not dihedrals_done:
                if i[1] > tolerance:
                    raise AssertionError(
                        '%s energies (%s, %f) outside of allowed tolerance (%f) for %s'
                        % (system_name, i[0], i[1], tolerance, ffxml))
                dihedrals_done = True
            else:  #impropers
                if i[1] > improper_tolerance:
                    raise AssertionError(
                        '%s energies (%s-impropers, %f) outside of allowed tolerance (%f) for %s'
                        % (system_name, i[0], i[1], improper_tolerance, ffxml))

    # logging
    if not no_log:
        charmm_energies_log = dict()
        omm_energies_log = dict()
        rel_energies_log = dict()
        charmm_energies_log['ffxml_name'] = ffxml
        charmm_energies_log['test_system'] = system_name
        charmm_energies_log['data_type'] = 'CHARMM'
        charmm_energies_log['units'] = units
        omm_energies_log['ffxml_name'] = ffxml
        omm_energies_log['test_system'] = system_name
        omm_energies_log['data_type'] = 'OpenMM'
        omm_energies_log['units'] = units
        rel_energies_log['ffxml_name'] = ffxml
        rel_energies_log['test_system'] = system_name
        rel_energies_log['data_type'] = 'abs((CHARMM-OpenMM)/CHARMM)'
        dihedrals_done = False
        for item in amber_energies:
            if item[0] == 'PeriodicTorsionForce' and not dihedrals_done:
                charmm_energies_log['PeriodicTorsionForce_dihedrals'] = item[1]
                dihedrals_done = True
            elif item[0] == 'PeriodicTorsionForce' and dihedrals_done:
                charmm_energies_log['PeriodicTorsionForce_impropers'] = item[1]
            elif item[0] == 'CMMotionRemover':
                continue
            else:
                charmm_energies_log[item[0]] = item[1]
        dihedrals_done = False
        for item in omm_energies:
            if item[0] == 'PeriodicTorsionForce' and not dihedrals_done:
                omm_energies_log['PeriodicTorsionForce_dihedrals'] = item[1]
                dihedrals_done = True
            elif item[0] == 'PeriodicTorsionForce' and dihedrals_done:
                omm_energies_log['PeriodicTorsionForce_impropers'] = item[1]
            elif item[0] == 'CMMotionRemover':
                continue
            else:
                omm_energies_log[item[0]] = item[1]
        dihedrals_done = False
        for item in rel_energies:
            if item[0] == 'PeriodicTorsionForce' and not dihedrals_done:
                rel_energies_log['PeriodicTorsionForce_dihedrals'] = item[1]
                dihedrals_done = True
            elif item[0] == 'PeriodicTorsionForce' and dihedrals_done:
                rel_energies_log['PeriodicTorsionForce_impropers'] = item[1]
            elif item[0] == 'CMMotionRemover':
                continue
            else:
                rel_energies_log[item[0]] = item[1]

        logger.log(charmm_energies_log)
        logger.log(omm_energies_log)
        logger.log(rel_energies_log)
Exemplo n.º 18
0
M.xyzs[0] = pos
M.write('constrained.gro')

# Gromacs calculation
GMX_Energy, GMX_Force, Ecomps_GMX = Calculate_GMX('constrained.gro', 'topol.top', 'shot.mdp')
GMX_Force = GMX_Force.reshape(-1,3)

# Print Gromacs energy components
printcool_dictionary(Ecomps_GMX, title="GROMACS energy components")

# Parse the .mdp file to inform ParmEd
defines, sysargs, mdp_opts = interpret_mdp('shot.mdp')

GmxGro = parmed.gromacs.GromacsGroFile.parse('constrained.gro')
# CHARMM calculation
parm = CharmmParameterSet('fb15.prm', 'fb15.rtf')
psf = CharmmPsfFile('sys-full.psf')
crd = CharmmCrdFile('sys-full.crd')
parm.box = GmxGro.box
parm.positions = GmxGro.positions

IPython.embed()
CHARMM_Energy, CHARMM_Force, Ecomps_CHARMM = Calculate_CHARMM(parm, psf, crd, sysargs, defines)
CHARMM_Force = CHARMM_Force.reshape(-1,3)
# Print CHARMM energy components
printcool_dictionary(Ecomps_CHARMM, title="CHARMM energy components")

def compare_ecomps(in1, in2):
    groups = [([['Bond'], ['BOND']]),
              ([['Angle'], ['ANGLE']]),
              ([['Proper-Dih.', 'Improper-Dih.'], ['DIHED']]),
Exemplo n.º 19
0
import parmed as pm
from parmed.charmm import CharmmPsfFile, CharmmCrdFile, CharmmParameterSet


print('Loading CHARMM files...')
params = CharmmParameterSet('toppar/par_all36m_prot.prm', 'toppar/par_all36_lipid.prm')

gram = CharmmPsfFile('../../simulations/themis_data/1jnoetaohh3o2.psf')

for atom in gram.atoms:
    print(atom.name, atom.idx, atom.charge, atom.rmin, atom.epsilon)
Exemplo n.º 20
0
#!/usr/bin/env python
from __future__ import division, print_function
from collections import defaultdict

import sys

# OpenMM Imports
import simtk.openmm as mm
import simtk.openmm.app as app
import parmed as pmd
# ParmEd Imports
from parmed import load_file, unit as u
from parmed.charmm import CharmmParameterSet
from parmed.openmm import StateDataReporter, energy_decomposition_system
params = CharmmParameterSet('parmed_par_oplsaam.inp')
ala5_gas = load_file('GP.psf')
ala5_crds = load_file('plt.pdb')

# Create the OpenMM system
print('Creating OpenMM System')
system = ala5_gas.createSystem(params,
                               nonbondedMethod=app.NoCutoff,
                               nonbondedCutoff=1000.0 * u.angstroms)
# Create the integrator to do Langevin dynamics
integrator = mm.LangevinIntegrator(
    300 * u.kelvin,  # Temperature of heat bath
    1.0 / u.picoseconds,  # Friction coefficient
    2.0 * u.femtoseconds,  # Time step
)

# Define the platform to use; CUDA, OpenCL, CPU, or Reference. Or do not specify
Exemplo n.º 21
0
from __future__ import division, print_function

import sys

# OpenMM Imports
import simtk.openmm as mm
import simtk.openmm.app as app

# ParmEd Imports
from parmed import load_file, unit as u
from parmed.charmm import CharmmParameterSet
from parmed.openmm import StateDataReporter

# Load the CHARMM files
print('Loading CHARMM files...')
params = CharmmParameterSet('toppar/par_all36_prot.prm',
                            'toppar/toppar_water_ions.str')
ala2_solv = load_file('ala2_charmmgui.psf')
ala2_crds = load_file('ala2_charmmgui.crd')

# NOTE NOTE
# The parameter set we used here is the CHARMM 36 force field, but this is
# strictly an example. It is important that you use the most accurate (typically
# most up-to-date) force fields for your own simulation. See the CHARMM
# parameter web page for updates:
# http://mackerell.umaryland.edu/CHARMM_ff_params.html
# END NOTE

# Compute the box dimensions from the coordinates and set the box lengths (only
# orthorhombic boxes are currently supported in OpenMM)
coords = ala2_crds.positions
min_crds = [coords[0][0], coords[0][1], coords[0][2]]
import simtk.openmm as mm
from torsionfit import TorsionScanSet as ScanSet
import torsionfit.TorsionFitModel as Model
from torsionfit import sqlite_plus
from pymc import MCMC
from parmed.charmm import CharmmParameterSet

param_to_opt = [('CG331', 'CG321', 'CG321', 'CG331'),
                ('HGA3', 'CG331', 'CG321', 'HGA2'),
                ('HGA3', 'CG331', 'CG321', 'CG321'),
                ('HGA2', 'CG321', 'CG321', 'HGA2'),
                ('CG331', 'CG321', 'CG321', 'HGA2')]
param = CharmmParameterSet('../../../../data/charmm_ff/top_all36_cgenff.rtf',
                           '../../../../data/charmm_ff/par_all36_cgenff.prm')
structure = '../../../structure/butane.psf'
scan = '../../../torsion_scans/MP2_torsion_scan/'
# Print initial guess
print param.dihedral_types[param_to_opt[0]]

# Create a butane scan with torsions on (to compare for difference potential)
butane_scan = ScanSet.parse_psi4_out(scan, structure)
butane_scan.compute_energy(param)
optimized = butane_scan.remove_nonoptimized()
optimized.compute_energy(param)

# Turn off torsion
param.dihedral_types[('CG331', 'CG321', 'CG321', 'CG331')][1].phi_k = 0
param.dihedral_types[('CG331', 'CG321', 'CG321', 'CG331')][0].phi_k = 0
param.dihedral_types[('HGA3', 'CG331', 'CG321', 'HGA2')][0].phi_k = 0
param.dihedral_types[('HGA2', 'CG321', 'CG331', 'HGA3')][0].phi_k = 0
param.dihedral_types[('HGA3', 'CG331', 'CG321', 'CG321')][0].phi_k = 0
Exemplo n.º 23
0
from parmed.charmm import CharmmParameterSet
import parmed as pmd
import sys

if __name__ == "__main__":
    pfile = sys.argv[1]
    sfile = None
    if len(sys.argv) > 2:
        sfile = sys.argv[2]
    if sfile:
        psf = pmd.load_file(sfile)
        print(len(psf.atoms))
    #params = CharmmParameterSet('toph8.rtf', 'param3.prm')
    if sfile:
        params = CharmmParameterSet.from_structure(psf)
    else:
        params = CharmmParameterSet()
    print(len(psf.atoms))
    #params.read_parameter_file('../../../data/par_all27_prot_lipid_chiral.dat')
    params.read_parameter_file(pfile)
    print(params)
    print(params.atom_types)
    print('%.4f' % (params.atom_types['CD'].epsilon))
    print('%.4f' % (params.atom_types['CD'].rmin))
    print('%.4f' % (params.atom_types['NH3'].epsilon))
    print('%.4f' % (params.atom_types['NH3'].rmin))
    #print(params.bond_types)
    #print(params.angle_types)
    #print(params.dihedral_types)
Exemplo n.º 24
0
 def __init__(self, molecule, param_filepath):
     super(StructurePredictor, self).__init__()
     self.params = CharmmParameterSet(param_filepath)
     self.m = molecule
Exemplo n.º 25
0
from torsionfit.backends import sqlite_plus

import torsionfit.parameters as par
from pymc import MCMC
import pymc
from parmed.charmm import CharmmParameterSet
import unittest

try:
    from simtk.openmm import app
    import simtk.openmm as mm
    HAVE_OPENMM = True
except ImportError:
    HAVE_OPENMM = False

param = CharmmParameterSet(get_fn('top_all36_cgenff.rtf'),
                           get_fn('par_all36_cgenff.prm'))
structure = get_fn('butane.psf')
logfiles = get_fn('MP2_torsion_scan/')
frag = qmdb.parse_psi4_out(logfiles, structure)
frag = frag.remove_nonoptimized()
to_optimize = [('CG331', 'CG321', 'CG321', 'CG331')]
model_omm = TorsionFitModelOMM(param=param,
                               frags=frag,
                               param_to_opt=to_optimize,
                               init_random=False)


class TestFitModel(unittest.TestCase):
    """ Tests pymc model"""
    def test_pymc_model(self):
        """ Tests sampler """
Exemplo n.º 26
0
from torsionfit import sqlite_plus
from pymc import MCMC
from parmed.charmm import CharmmParameterSet
import glob
from pymc import MCMC

structure = 'pyrrol.psf'
scan = glob.glob('torsion-scan/*.log')

pyrrol_scan = ScanSet.parse_gauss(scan, structure)
pyrrol_opt = pyrrol_scan.extract_geom_opt()

# set up torsionfit model
param_to_optimize = [
    ('CG331', 'CG321', 'CG321', 'NG3C51'),
    ('CG321', 'CG321', 'NG3C51', 'CG2R51'),
    ('CG321', 'CG321', 'NG3C51', 'CG251O'),
    ('CG2D2', 'CG251O', 'NG3C51', 'CG321'),
]
param = CharmmParameterSet('../charmm_ff/top_all36_cgenff.rtf',
                           '../charmm_ff/par_all36_cgenff.prm', 'pyrrol.str')
model = Model.TorsionFitModelEliminatePhase(param,
                                            pyrrol_opt,
                                            decouple_n=True,
                                            sample_n5=True,
                                            param_to_opt=param_to_optimize)
db = sqlite_plus.load('pyrrol_4.db')
sampler = MCMC(model.pymc_parameters, db=db)
sampler.restore_sampler_state()
sampler.sample(100000)
Exemplo n.º 27
0
def convert_yaml(yaml_filename, ffxml_dir):
    # Read YAML
    data = yaml.safe_load(open(yaml_filename, 'r'))
    source_pack = data[0]['sourcePackage']
    source_pack_ver = data[0]['sourcePackageVersion']

    for entry in data[1:]:
        ffxml_filename = os.path.join(ffxml_dir, entry['Destination'])
        print('Generating %s' % ffxml_filename)
        charmm_references = entry['References']
        source_files = entry['Source']

        # files that should be excluded from conversion.
        exclude_files = set()
        if ('exclude' in source_files) and (source_files['exclude']
                                            is not None):
            exclude_files = set(source_files['exclude'])

        # charmm36 main top and par files
        charmm_files = list()
        if ('include' in source_files) and (source_files['include']
                                            is not None):
            charmm_files = source_files['include']

        # add stream files
        if ('stream' in source_files) and (source_files['stream'] is not None):
            for files in source_files['stream']:
                charmm_files.extend(glob.glob(files))

        # compile residue template names to exclude
        exclude_residues = list()
        if 'exclude_residues' in source_files:
            for resname in source_files['exclude_residues']:
                exclude_residues.append(resname)

        # exclude files from conversion, maintaining deterministic order
        for filename in exclude_files:
            try:
                charmm_files.remove(filename)
            except Exception as e:
                print(
                    'Specified excluded file "%s" does not appear in list of files'
                    % filename)

        provenance = OrderedDict()
        source = provenance['Source'] = []
        for fi in charmm_files:
            source.append(OrderedDict())
            source[-1]['Source'] = fi
            md5 = hashlib.md5()
            with open(fi, 'rb') as f:
                md5.update(f.read())
            md5 = md5.hexdigest()
            source[-1]['md5hash'] = md5
            source[-1]['sourcePackage'] = source_pack
            source[-1]['sourcePackageVersion'] = source_pack_ver

        references = provenance['Reference'] = []
        for ff in charmm_references:
            for cite in charmm_references[ff]:
                references.append(OrderedDict())
                if type(cite) is dict:
                    for key in cite.keys():
                        citation = cite[key]
                        references[-1]['Reference'] = citation
                        references[-1]['forcefield'] = ff
                        references[-1]['type'] = key
                else:
                    citation = cite
                    references[-1]['Reference'] = citation
                    references[-1]['forcefield'] = ff

        #generate recommended combination for charmm36
        if verbose: print('Loading CHARMM parameter sets %s...' % charmm_files)
        params = CharmmParameterSet(*charmm_files)

        if len(exclude_residues) > 0:
            if verbose: print('Excluding residues: %s' % exclude_residues)
            for resname in exclude_residues:
                del params.residues[resname]

        if verbose: print('Converting parameters to OpenMM...')
        params_omm = openmm.OpenMMParameterSet.from_parameterset(
            params, unique_atom_types=True)

        # Set override level
        if 'Override' in entry:
            override_level = int(entry['Override'])
            if verbose:
                print('Setting residues and patches to override level %d...' %
                      override_level)
            for name, residue in params_omm.residues.items():
                residue.override_level = override_level
            for name, patch in params_omm.patches.items():
                patch.override_level = override_level

        if verbose:
            print(
                'Writing parameter set and compatible patches. This may take several minutes...'
            )
        params_omm.write(ffxml_filename,
                         provenance=provenance,
                         charmm_imp=True,
                         separate_ljforce=True)

        # Try reading the forcefield back in to make sure it is valid
        if verbose: print('Verifying ffxml file integrity...')
        if 'TestInclude' in entry:
            ffxml_include = entry['TestInclude']
            forcefield = app.ForceField(ffxml_filename, *ffxml_include)
        else:
            forcefield = app.ForceField(ffxml_filename)

        if 'Test' in entry:
            for filename in entry['Test']:
                if verbose: print('Testing with %s ...' % filename)
                pdbfile = app.PDBFile(filename)
                system = forcefield.createSystem(pdbfile.topology)

        if verbose: print('Verified.')
Exemplo n.º 28
0
from __future__ import division, print_function

import sys

# OpenMM Imports
import simtk.openmm as mm
import simtk.openmm.app as app

# ParmEd Imports
from parmed.charmm import CharmmPsfFile, CharmmCrdFile, CharmmParameterSet
from parmed.openmm import StateDataReporter
from parmed import unit as u

# Load the CHARMM files
print('Loading CHARMM files...')
params = CharmmParameterSet('BNZ_2_PRD.prm')
ala5_gas = CharmmPsfFile('zero.psf')
ala5_crds = app.PDBFile('A2B_gas.pdb')
type_map = {
    'O': 'OT',
    'OH2': 'OT',
    'H1': 'HT',
    'H2': 'HT',
    'LP': 'LP',
    'OM': 'LP',
    'LP1': 'LP',
    'LP2': 'LP',
}

for nsites in [3, 4, 5]:
    pdb_filename = 'waterbox-{}-site.pdb'.format(nsites)
    psf_filename = 'waterbox-{}-site.psf'.format(nsites)
    str_filename = 'toppar_tip{}p.str'.format(nsites)
    pdb = pmd.load_file(pdb_filename)
    for atom in pdb.atoms:
        atom.type = type_map[atom.name]
    # Delete bonds to lone pairs
    indices_to_delete = list()
    for (index, bond) in enumerate(list(pdb.bonds)):
        if (bond.atom1.type == 'LP') or (bond.atom2.type == 'LP'):
            indices_to_delete.append(index)
    for index in indices_to_delete[-1:0:-1]:
        pdb.bonds[index].delete()
        del pdb.bonds[index]

    params = CharmmParameterSet(str_filename)
    PSFFile.write(pdb, psf_filename)
Exemplo n.º 30
0
from __future__ import division, print_function

import sys

# OpenMM Imports
import simtk.openmm as mm
import simtk.openmm.app as app

# ParmEd Imports
from parmed import load_file, unit as u
from parmed.charmm import CharmmParameterSet
from parmed.openmm import StateDataReporter

# Load the CHARMM files
print('Loading CHARMM files...')
params = CharmmParameterSet('toppar/par_all36_prot.prm')
ala5_gas = load_file('ala5_autopsf.psf')
ala5_crds = load_file('ala5_autopsf.pdb')

# NOTE NOTE
# The parameter set we used here is the CHARMM 36 force field, but this is
# strictly an example. It is important that you use the most accurate (typically
# most up-to-date) force fields for your own simulation. See the CHARMM
# parameter web page for updates:
# http://mackerell.umaryland.edu/CHARMM_ff_params.html
# END NOTE

# Create the OpenMM system
print('Creating OpenMM System')
system = ala5_gas.createSystem(
    params,
Exemplo n.º 31
0
#!/usr/bin/env python
from collections import defaultdict

import sys

# OpenMM Imports
import simtk.openmm as mm
from simtk.openmm import KcalPerKJ
import simtk.openmm.app as app
import parmed as pmd
# ParmEd Imports
from parmed import load_file, unit as u
from parmed.charmm import CharmmParameterSet
from parmed.openmm import StateDataReporter, energy_decomposition_system
params = CharmmParameterSet('QUBE_FF_openmm.par')
ala5_gas = load_file('new_ionized.psf')
ala5_crds = load_file('ionized.pdb')

system = ala5_gas.createSystem(params,
                               nonbondedMethod=app.NoCutoff,
                               nonbondedCutoff=500.0 * u.angstroms,
                               switchDistance=496.0 * u.angstroms)

#serializing the system
from simtk.openmm import XmlSerializer
serialized_system = XmlSerializer.serialize(system)
outfile = open('serialized_system.xml', 'w')
outfile.write(serialized_system)
outfile.close()

# Create the integrator to do Langevin dynamics