示例#1
0
def add_missing(param_list, param, sample_n5=False):
    """
    Update param set with missing multiplicities. The modifications are in place.

    Parameters
    ----------
    param_list : list of tuples
        list of parameters to add missing. Format (A, B, C, D)
    param : parmed.charmm.CharmmParameterSet
        parameter set to add missing parameters.
    sample_n5 : bool
        Flag if multiplicity of 5 should be added. Default False.
    """
    multiplicities = [1, 2, 3, 4, 6]
    if sample_n5:
        multiplicities = [1, 2, 3, 4, 5, 6]
    if type(param_list) is not list:
        param_list = [param_list]
    for p in param_list:
        reverse = tuple(reversed(p))
        per = []
        for i in range(len(param.dihedral_types[p])):
            per.append(param.dihedral_types[p][i].per)
            per.append(param.dihedral_types[reverse][i].per)
        for j in multiplicities:
            if j not in per:
                param.dihedral_types[p].append(DihedralType(0, j, 0))
                param.dihedral_types[reverse].append(DihedralType(0, j, 0))
示例#2
0
    def test_vectorToParams(self):
        from parmed.parameters import ParameterSet
        from parmed.topologyobjects import DihedralTypeList, DihedralType

        params = ParameterSet()
        dihlist = DihedralTypeList()
        for i in range(6):
            dihtype = DihedralType(float(i) + 10, i + 1, float(i) + 20)
            dihlist.append(dihtype)
        params.dihedral_types[('x', 'x', 'x', 'x')] = dihlist

        self.df.dihedrals = [[0, 1, 2, 3]]
        self.df.parameters = params
        self.df._dihedral_atomtypes = [('x', 'x', 'x', 'x')]
        vector = np.array([30, 31, 32, 33, 34, 35, 40, 41, 42, 43, 44, 45, 50])

        new_params = self.df._vectorToParams(vector)

        self.assertFalse(params is new_params)
        self.assertEqual(len(new_params.dihedral_types[('x', 'x', 'x', 'x')]),
                         6)
        for i, param in enumerate(new_params.dihedral_types[('x', 'x', 'x',
                                                             'x')]):
            self.assertEqual(param.phi_k, i + 30)
            self.assertEqual(param.per, i + 1)
            self.assertAlmostEqual(np.deg2rad(param.phase), i + 40)
示例#3
0
    def test_paramsToVector(self):
        from parmed.parameters import ParameterSet
        from parmed.topologyobjects import DihedralTypeList, DihedralType

        params = ParameterSet()
        dihlist = DihedralTypeList()
        for i in range(6):
            dihtype = DihedralType(float(i) + 10, i + 1, float(i) + 20)
            dihlist.append(dihtype)
        params.dihedral_types[('x', 'x', 'x', 'x')] = dihlist

        self.df.dihedrals = [
            (0, 0, 0, 0),
        ]
        self.df._dihedral_atomtypes = [('x', 'x', 'x', 'x')]
        vector = self.df._paramsToVector(params)
        self.assertListEqual(list(vector), [
            10, 11, 12, 13, 14, 15,
            np.deg2rad(20),
            np.deg2rad(21),
            np.deg2rad(22),
            np.deg2rad(23),
            np.deg2rad(24),
            np.deg2rad(25), 0.
        ])
示例#4
0
    def from_dih_params(filename=None, dih_params=None, rj=False, continuous=False, n_increments=13, sample_phase=False):
        """

        Parameters
        ----------
        filename : str
            name of file with serialized dihedral parameters
        rj : bool
            Flag if using reversible jump. Default it True
        continuous : bool
            Flag if sampling continuous phase. Default is False
        n_increments : int
            incermentation of torsion drive
        sample_phase : bool
            Flag if sampling phase. Default is False (K is allowed to go negative when sample_phase is False)

        Returns
        -------
        ToyModel with true and initial value from saved file.

        """
        if filename is None and dih_params is None:
            msg = 'You must provide either an npy file or a numpy array with true and initial values for the toy model'
            raise Exception(msg)
        if filename is not None:
            dih_params = np.load(filename)
        dih_tlist_true = DihedralTypeList()
        dih_tlist_init = DihedralTypeList()

        true = dih_params[0]
        init = dih_params[1]

        for dih in true:
            if not np.isnan(dih[0]):
                dih_tlist_true.append(DihedralType(per=dih[0], phi_k=dih[1], phase=dih[2]))

        for dih in init:
            if not np.isnan(dih[0]):
                dih_tlist_init.append(DihedralType(per=dih[0], phi_k=dih[1], phase=dih[2]))

        return ToyModel(true_value=dih_tlist_true, initial_value=dih_tlist_init, rj=rj, continuous=continuous,
                        n_increments=n_increments, sample_phase=sample_phase)
示例#5
0
 def _process_improper_line(self, line):
     rematch = _impropre.match(line)
     if not rematch:
         raise ParameterError('Could not understand IMPROPER line '
                                 '[%s]' % line)
     a1, a2, a3, a4, k, phi, per = rematch.groups()
     a1 = a1.strip(); a2 = a2.strip();
     a3 = a3.strip(); a4 = a4.strip()
     # Pre-sort the improper types, assuming atom3 is the central atom (which
     # it must be in Amber parameter files!!!!)
     a1, a2, a4 = sorted([a1, a2, a4])
     key = (a1, a2, a3, a4)
     self.improper_periodic_types[key] = \
             DihedralType(float(k), float(per), float(phi))
示例#6
0
    def test_paramsToVector(self):
        from parmed.parameters import ParameterSet
        from parmed.topologyobjects import DihedralTypeList, DihedralType

        params = ParameterSet()
        dihlist = DihedralTypeList()
        for i in range(6):
            dihtype = DihedralType(float(i)+10, i+1, float(i)+20)
            dihlist.append(dihtype)
        params.dihedral_types[('x', 'x', 'x', 'x')] = dihlist

        self.df.dihedrals = [(0, 0, 0, 0),]
        vector = self.df._paramsToVector(params, [('x', 'x', 'x', 'x'),])
        self.assertListEqual(list(vector), [10., 11., 12., 13., 14., 15., 20., 21., 22., 23., 24., 25., 0.])
示例#7
0
def _process_dihedral(struct, force):
    """ Adds periodic torsions to the structure """
    typemap = dict()
    for ii in range(force.getNumTorsions()):
        i, j, k, l, per, phase, phi_k = force.getTorsionParameters(ii)
        ai, aj = struct.atoms[i], struct.atoms[j]
        ak, al = struct.atoms[k], struct.atoms[l]
        key = (per, phase._value, phi_k._value)
        if key in typemap:
            dihed_type = typemap[key]
        else:
            dihed_type = DihedralType(phi_k, per, phase)
            typemap[key] = dihed_type
            struct.dihedral_types.append(dihed_type)
        improper = (ai in ak.bond_partners and aj in ak.bond_partners
                    and al in ak.bond_partners)
        struct.dihedrals.append(
            Dihedral(ai, aj, ak, al, improper=improper, type=dihed_type))
    struct.dihedral_types.claim()
示例#8
0
    def test_vectorToParams(self):
        from parmed.parameters import ParameterSet
        from parmed.topologyobjects import DihedralTypeList, DihedralType

        params = ParameterSet()
        dihlist = DihedralTypeList()
        for i in range(6):
            dihtype = DihedralType(float(i)+10, i+1, float(i)+20)
            dihlist.append(dihtype)
        params.dihedral_types[('x', 'x', 'x', 'x')] = dihlist

        self.df.dihedrals = [[0, 1, 2, 3]]
        vector = np.array([30., 31., 32., 33., 34., 35., 40., 41., 42., 43., 44., 45., 50.])
        self.df._vectorToParams(params, [('x', 'x', 'x', 'x'),], vector)

        self.assertEqual(len(params.dihedral_types[('x', 'x', 'x', 'x')]), 6)
        for i, param in enumerate(params.dihedral_types[('x', 'x', 'x', 'x')]):
            self.assertEqual(param.phi_k, i+30)
            self.assertEqual(param.per, i+1)
            self.assertEqual(param.phase, i+40)
示例#9
0
    def _randomize_dih_param(self, return_dih=False):
        """
        generates random dihedral parameters

        """
        dih_tlist = DihedralTypeList()
        multiplicities = [1, 2, 3, 4, 6]
        terms = np.random.randint(1, 5+1)
        np.random.shuffle(multiplicities)
        for i in range(terms):
            k = np.random.uniform(0.0, 20.0)
            n = multiplicities[i]
            phase = np.random.randint(0, 1+1)
            if phase == 1:
                phase = 180
            dih_tlist.append(DihedralType(k, n, phase, 1.00, 1.00))
        self._param.dihedral_types[self._dih_type] = dih_tlist
        if return_dih:
            _dih_tlist = copy.deepcopy(dih_tlist)
            return _dih_tlist
示例#10
0
def createMultitermDihedralTypes(parameters, nterms=6, scee=1.2, scnb=2):
    from parmed.topologyobjects import DihedralTypeList, DihedralType
    from copy import deepcopy

    parameters = deepcopy(parameters)

    for key, val in parameters.dihedral_types.items():
        dihlist = DihedralTypeList()
        for i in range(1, nterms + 1):
            found = False
            for d in val:  # Check if this term already exists in the parameters.
                if d.per == i:
                    dihlist.append(d)
                    found = True
                    break
            if not found:  # Else create an unparametrized term
                dihtype = DihedralType(0, i, 0, scee=scee, scnb=scnb)
                dihlist.append(dihtype)
        parameters.dihedral_types[key] = dihlist

    return parameters
示例#11
0
文件: utils.py 项目: ctk3b/ParmEd
def create_random_structure(parametrized, novalence=False):
    """ Create a random Structure with random attributes

    Parameters
    ----------
    parametrized : bool
        If True, add at least two of all kinds of parameters to the
        generated random structure. If False, just fill in the atoms and
        residues and some random valence terms, but no "types"
    novalence : bool, optional
        If True, no valence terms will be added. Default is False. This is
        set to False if parametrized is True
    """
    from parmed.topologyobjects import (
        Atom, Bond, AtomType, BondType, AngleType, DihedralType, ImproperType,
        CmapType, OutOfPlaneBendType, StretchBendType, TorsionTorsionType,
        AmoebaNonbondedExceptionType, Angle, UreyBradley, Dihedral, Improper,
        Cmap, TrigonalAngle, OutOfPlaneBend, StretchBend, PiTorsion,
        TorsionTorsion, AcceptorDonor, Group, ChiralFrame, MultipoleFrame,
        NonbondedException, RBTorsionType)
    from parmed import structure
    from copy import copy
    if parametrized: novalence = False
    # Generate random atom and parameter types
    atom_types = [
        AtomType(''.join(random.sample(uppercase, 3)), i,
                 random.random() * 16 + 1, random.randint(1, 8))
        for i in range(random.randint(8, 20))
    ]
    bond_types = [
        BondType(random.random() * 2,
                 random.random() * 100) for i in range(random.randint(10, 20))
    ]
    angle_types = [
        AngleType(random.random() * 50,
                  random.random() * 120) for i in range(random.randint(10, 20))
    ]
    dihed_types = [
        DihedralType(random.random() * 10, random.randint(1, 6),
                     random.choice([0, 180]))
        for i in range(random.randint(10, 20))
    ]
    rb_types = [RBTorsionType(*[random.random() * 10 for i in range(6)])]
    imp_types = [
        ImproperType(random.random() * 100, random.choice([0, 180]))
        for i in range(random.randint(10, 20))
    ]
    cmap_types = [
        CmapType(24, [random.random() * 5 for i in range(24 * 24)])
        for i in range(random.randint(5, 10))
    ]
    oop_types = [
        OutOfPlaneBendType(random.random() * 100)
        for i in range(random.randint(10, 20))
    ]
    strbnd_types = [
        StretchBendType(random.random() * 10,
                        random.random() * 10,
                        random.random() * 2,
                        random.random() * 2,
                        random.random() * 120)
        for i in range(random.randint(10, 20))
    ]
    ang1, ang2 = list(range(-180, 180, 36)), list(range(-180, 180, 18))
    tortor_types = [
        TorsionTorsionType((10, 20), ang1[:], ang2[:],
                           [random.random() * 10 for j in range(200)])
        for i in range(random.randint(5, 10))
    ]
    for typ in atom_types:
        typ.set_lj_params(random.random() * 2, random.random() * 2)

    struct = structure.Structure()
    # Add atoms in residues
    for res in range(random.randint(20, 30)):
        resname = ''.join(random.sample(uppercase, 3))
        resid = res + 1
        for i in range(random.randint(10, 25)):
            name = ''.join(random.sample(uppercase, 4))
            if parametrized:
                typ = random.choice(atom_types)
                type = str(typ)
                mass = typ.mass
                atomic_number = typ.atomic_number
            else:
                type = ''.join(random.sample(uppercase, 3))
                mass = random.random() * 16 + 1
                atomic_number = random.randint(1, 8)
            charge = random.random() * 2 - 1
            solvent_radius = random.random() * 2
            screen = random.random() * 2
            atom = Atom(atomic_number=atomic_number,
                        type=type,
                        charge=charge,
                        mass=mass,
                        solvent_radius=solvent_radius,
                        screen=screen,
                        name=name)
            if parametrized:
                atom.atom_type = typ
            struct.add_atom(atom, resname, resid)
    if novalence:
        return struct
    # Possibly add parameter type lists
    if parametrized:
        struct.bond_types.extend([copy(x) for x in bond_types])
        struct.bond_types.claim()
        struct.angle_types.extend([copy(x) for x in angle_types])
        struct.angle_types.claim()
        struct.dihedral_types.extend([copy(x) for x in dihed_types])
        struct.dihedral_types.claim()
        struct.rb_torsion_types.extend([copy(x) for x in rb_types])
        struct.rb_torsion_types.claim()
        struct.urey_bradley_types.extend([copy(x) for x in bond_types])
        struct.urey_bradley_types.claim()
        struct.improper_types.extend([copy(x) for x in imp_types])
        struct.improper_types.claim()
        struct.cmap_types.extend([copy(x) for x in cmap_types])
        struct.cmap_types.claim()
        struct.trigonal_angle_types.extend([copy(x) for x in angle_types])
        struct.trigonal_angle_types.claim()
        struct.out_of_plane_bend_types.extend([copy(x) for x in oop_types])
        struct.out_of_plane_bend_types.claim()
        struct.pi_torsion_types.extend([copy(x) for x in dihed_types])
        struct.pi_torsion_types.claim()
        struct.stretch_bend_types.extend([copy(x) for x in strbnd_types])
        struct.stretch_bend_types.claim()
        struct.torsion_torsion_types.extend([copy(x) for x in tortor_types])
        struct.torsion_torsion_types.claim()
        struct.adjust_types.extend([
            AmoebaNonbondedExceptionType(0.5, 0.5, 0.6, 0.6, 0.7)
            for i in range(random.randint(10, 20))
        ])
        struct.adjust_types.claim()
    # Add valence terms with optional
    for i in range(random.randint(40, 50)):
        struct.bonds.append(Bond(*random.sample(struct.atoms, 2)))
        if parametrized:
            struct.bonds[-1].type = random.choice(struct.bond_types)
    for i in range(random.randint(35, 45)):
        struct.angles.append(Angle(*random.sample(struct.atoms, 3)))
        if parametrized:
            struct.angles[-1].type = random.choice(struct.angle_types)
    for i in range(random.randint(35, 45)):
        struct.urey_bradleys.append(
            UreyBradley(*random.sample(struct.atoms, 2)))
        if parametrized:
            struct.urey_bradleys[-1].type = random.choice(
                struct.urey_bradley_types)
    for i in range(random.randint(30, 40)):
        struct.dihedrals.append(
            Dihedral(*random.sample(struct.atoms, 4),
                     improper=random.choice([True, False])))
        if parametrized:
            struct.dihedrals[-1].type = random.choice(struct.dihedral_types)
    for i in range(random.randint(30, 40)):
        struct.rb_torsions.append(Dihedral(*random.sample(struct.atoms, 4)))
        if parametrized:
            struct.rb_torsions[-1].type = random.choice(
                struct.rb_torsion_types)
    for i in range(random.randint(10, 20)):
        struct.impropers.append(Improper(*random.sample(struct.atoms, 4)))
        if parametrized:
            struct.impropers[-1].type = random.choice(struct.improper_types)
    for i in range(random.randint(25, 35)):
        struct.cmaps.append(Cmap(*random.sample(struct.atoms, 5)))
        if parametrized:
            struct.cmaps[-1].type = random.choice(struct.cmap_types)
    for i in range(random.randint(30, 40)):
        struct.trigonal_angles.append(
            TrigonalAngle(*random.sample(struct.atoms, 4)))
        if parametrized:
            struct.trigonal_angles[-1].type = random.choice(
                struct.trigonal_angle_types)
    for i in range(random.randint(30, 40)):
        struct.out_of_plane_bends.append(
            OutOfPlaneBend(*random.sample(struct.atoms, 4)))
        if parametrized:
            struct.out_of_plane_bends[-1].type = random.choice(
                struct.out_of_plane_bend_types)
    for i in range(random.randint(30, 40)):
        struct.stretch_bends.append(
            StretchBend(*random.sample(struct.atoms, 3)))
        if parametrized:
            struct.stretch_bends[-1].type = random.choice(
                struct.stretch_bend_types)
    for i in range(random.randint(20, 30)):
        struct.pi_torsions.append(PiTorsion(*random.sample(struct.atoms, 6)))
        if parametrized:
            struct.pi_torsions[-1].type = random.choice(
                struct.pi_torsion_types)
    for i in range(random.randint(10, 20)):
        struct.torsion_torsions.append(
            TorsionTorsion(*random.sample(struct.atoms, 5)))
        if parametrized:
            struct.torsion_torsions[-1].type = random.choice(
                struct.torsion_torsion_types)
    # Now use some lesser-used features
    for i in range(random.randint(5, 10)):
        struct.acceptors.append(AcceptorDonor(*random.sample(struct.atoms, 2)))
        struct.donors.append(AcceptorDonor(*random.sample(struct.atoms, 2)))
        struct.groups.append(Group(random.choice(struct.atoms), 2, 0))
        struct.chiral_frames.append(
            ChiralFrame(*random.sample(struct.atoms, 2),
                        chirality=random.choice([-1, 1])))
        struct.multipole_frames.append(
            MultipoleFrame(random.choice(struct.atoms), 0, 1, 2, 3))
    for i in range(random.randint(20, 30)):
        struct.adjusts.append(
            NonbondedException(*random.sample(struct.atoms, 2)))
        if parametrized:
            struct.adjusts[-1].type = random.choice(struct.adjust_types)
    struct.prune_empty_terms()
    struct.unchange()
    struct.update_dihedral_exclusions()
    return struct
示例#12
0
    def _process_dihedral_line(self, line, finished_diheds, last_key):
        """ Processes a dihedral line, possibly part of a multi-term dihedral

        Parameters
        ----------
        line : str
            Line of the file that contains a dihedral term
        finished_diheds : dict
            Dictionary of dihedral parameters whose final term has been read in
            already (which means additional terms will overwrite, not add)
        last_key : str or None
            If not None, this is the key for the last dihedral type that should
            be implied if the atom types are missing. Atom types seem to only be
            required for the first term in a multi-term torsion definition

        Returns
        -------
        key or None
            If a negative periodicity indicates another term is coming, the
            current key is returned so it can be passed as key to the next
            _process_dihedral_call
        """
        rematch = _dihedre.match(line)
        if not rematch and last_key is None:
            raise ParameterError('Could not understand DIHEDRAL line '
                                 '[%s]' % line)
        elif not rematch:
            rematch = _dihed2re.match(line)
            if not rematch:
                raise ParameterError('Could not understand DIHEDRAL line '
                                     '[%s]' % line)
            div, k, phi, per = rematch.groups()
            key = last_key
            rkey = tuple(reversed(key))
            assert key in finished_diheds
            if finished_diheds[key]:
                raise AssertionError('Cannot have an implied torsion that '
                                     'has already finished!')
        else:
            a1, a2, a3, a4, div, k, phi, per = rematch.groups()
            a1, a2, a3, a4 =  a1.strip(), a2.strip(), a3.strip(), a4.strip()
            key = (a1, a2, a3, a4)
            rkey = (a4, a3, a2, a1)
            if last_key is not None and (last_key != key and last_key != rkey):
                warnings.warn('Expecting next term in dihedral %r, got '
                              'definition for dihedral %r' % (last_key, key),
                              ParameterWarning)
        scee = [float(x) for x in _sceere.findall(line)] or [1.2]
        scnb = [float(x) for x in _scnbre.findall(line)] or [2.0]
        per = float(per)
        typ = DihedralType(float(k)/float(div), abs(per), float(phi),
                           scee[0], scnb[0])
        if finished_diheds[key]:
            # This dihedral is already finished its definition, which means
            # we go ahead and add a new one to override it
            typs = DihedralTypeList()
            typs.append(typ)
            self.dihedral_types[key] = self.dihedral_types[rkey] = typs
        else:
            self.dihedral_types[key].append(typ)
        finished_diheds[key] = finished_diheds[rkey] = per >= 0
        if per < 0:
            return key
示例#13
0
min_n = max(equil_t[:, 0])
# draw indices randomly to
idx_1 = np.random.randint(min_n, len(db.trace(torsion_k)[:]), 200)
idx_2 = np.random.randint(min_n, len(db.trace(torsion_k)[:]), 200)
#samples_with_replacement = [[data[i] for i in index] for index in idx]

# Add missing parameters
multiplicities = [1, 2, 3, 4, 5, 6]
p = ('CG331', 'CG321', 'CG321', 'CG331')
per = []
for i in range(len(param_1.dihedral_types[p])):
    per.append(param_1.dihedral_types[p][i].per)
for j in multiplicities:
    if j not in per:
        param_1.dihedral_types[p].append(DihedralType(0, j, 0))
        param_2.dihedral_types[p].append(DihedralType(0, j, 0))

# Set phase to 0
param_1.dihedral_types[p][1].phase = 0.0
param_2.dihedral_types[p][1].phase = 0.0

# Create 2 systems tied to the 2 different parameter sets for solvated and vacuum
# parameterize without deep copy parameters

pdb_solvate = app.PDBFile('../structure/butane_solvated.pdb')

coords = pdb_solvate.positions
min_crds = [coords[0][0], coords[0][1], coords[0][2]]
max_crds = [coords[0][0], coords[0][1], coords[0][2]]
示例#14
0
equil_t = 8443
# draw indices randomly to
idx = np.random.randint(equil_t,
                        len(db.trace('{}_1_K'.format(param_to_opt[0]))[:]),
                        200)

# Add missing parameters
multiplicities = [1, 2, 3, 4, 5, 6]
for t in param_to_opt:
    p = tuple(t.split('_'))
    per = []
    for i in range(len(param.dihedral_types[p])):
        per.append(param.dihedral_types[p][i].per)
    for j in multiplicities:
        if j not in per:
            param.dihedral_types[p].append(DihedralType(0, j, 0))

# parameterize without deep copy parameters
psf_solvate = database['solvated']['structure']
psf_solvate.load_parameters(param, copy_parameters=False)
system_solvate = psf_solvate.createSystem(nonbondedMethod=app.PME,
                                          constraints=app.HBonds,
                                          nonbondedCutoff=12.0 * u.angstroms,
                                          switchDistance=10.0 * u.angstroms)
database['solvated']['system'] = system_solvate

# create openmm system in vacuum
psf_vacuum = database['vacuum']['structure']
psf_vacuum.load_parameters(param, copy_parameters=False)
system_vacuum = psf_vacuum.createSystem(nonbondedMethod=app.NoCutoff,
                                        constraints=app.HBonds,