コード例 #1
0
ファイル: ucer2.py プロジェクト: tcmoore3/mbuild
 def __init__(self):
     """Returns a CER NS C24 with the head-to-tail vector pointing in +z.
     """
     super(UCer2, self).__init__(name='ucer2')
     mb.load('ucer2.pdb', compound=self, relative_to_module=self.__module__)
     mb.coordinate_transform.z_axis_transform(self, 
             new_origin=self[2], point_on_z_axis=self[58])
コード例 #2
0
ファイル: chol.py プロジェクト: tcmoore3/mbuild
 def __init__(self):
     """Returns a CHOL with the head-to-tail vector pointing in +z.
     """
     super(Chol, self).__init__(name='chol')
     mb.load('chol.pdb', compound=self, relative_to_module=self.__module__)
     mb.coordinate_transform.z_axis_transform(self, 
             new_origin=self[2], point_on_z_axis=self[63])
コード例 #3
0
ファイル: ch3.py プロジェクト: ctk3b/mbuild
    def __init__(self):
        super(CH3, self).__init__()

        mb.load('ch3.pdb', compound=self, relative_to_module=self.__module__)
        self.translate(-self[0].pos)  # Move carbon to origin.

        self.add(mb.Port(anchor=self[0]), 'up')
        self['up'].translate([0, -0.07, 0])
コード例 #4
0
ファイル: chol.py プロジェクト: tcmoore3/mbuild
 def __init__(self):
     """Returns a CG CHOL with the head-to-tail vector pointing in -z.
     """
     super(Chol, self).__init__()
     mb.load('chol.hoomdxml', compound=self, relative_to_module=self.__module__)
     xx = list(self.particles())
     mb.coordinate_transform.z_axis_transform(self,
             new_origin=xx[0], point_on_z_axis=xx[6])
     self.rotate(np.pi, [1, 0, 0])
コード例 #5
0
ファイル: ecer2.py プロジェクト: tcmoore3/mbuild
 def __init__(self):
     """Returns a CG eCER2 with the head-to-tail vector pointing in -z.
     """
     super(ECer2, self).__init__()
     mb.load('ecer2.hoomdxml', compound=self, relative_to_module=self.__module__)
     self.periodicity = [0, 0, 0]
     xx = list(self.particles())
     mb.coordinate_transform.z_axis_transform(self,
             new_origin=xx[6], point_on_z_axis=xx[11])
     self.rotate(np.pi, [1, 0, 0])
コード例 #6
0
ファイル: ffac16.py プロジェクト: tcmoore3/mbuild
 def __init__(self):
     """Returns a CG FFA C16 with the head-to-tail vector pointing in -z.
     """
     super(FFAC16, self).__init__()
     mb.load('ffac16.hoomdxml', compound=self, relative_to_module=self.__module__)
     self.periodicity = [0, 0, 0]
     xx = list(self.particles())
     mb.coordinate_transform.z_axis_transform(self,
             new_origin=xx[5], point_on_z_axis=xx[0])
     self.spin(np.pi, [1, 0, 0])
コード例 #7
0
ファイル: ch2.py プロジェクト: hainm/mbuild
    def __init__(self):
        super(CH2, self).__init__()

        mb.load('ch2.pdb', compound=self, relative_to_module=self.__module__)
        mb.translate(self, -self[0].pos)  # Move carbon to origin.

        self.add(mb.Port(anchor=self[0]), 'up')
        mb.translate(self['up'], [0, 0.07, 0])

        self.add(mb.Port(anchor=self[0]), 'down')
        mb.translate(self['down'], [0, -0.07, 0])
コード例 #8
0
ファイル: peg.py プロジェクト: ctk3b/mbuild
    def __init__(self):
        super(PegMonomer, self).__init__()

        mb.load('peg_monomer.pdb', compound=self, relative_to_module=self.__module__)
        self.translate(-self[0].pos)

        self.add(mb.Port(anchor=self[0]), 'down')
        self['down'].translate([0, -0.07, 0])

        self.add(mb.Port(anchor=self[6]), 'up')
        self['up'].translate([0, 0.073, 0])
コード例 #9
0
    def __init__(self):
        super(PegMonomer, self).__init__()

        mb.load('peg_monomer.pdb', compound=self, relative_to_module=self.__module__)
        mb.translate(self, -self.C[0])

        self.add(mb.Port(anchor=self.C[0]), 'down')
        mb.translate(self.down, [0, -0.07, 0])


        self.add(mb.Port(anchor=self.O[0]), 'up')
        mb.translate(self.up, [0, 0.364, 0])
コード例 #10
0
ファイル: ester.py プロジェクト: TengyuMaVandy/mbuild
    def __init__(self):
        super(Ester, self).__init__()

        mb.load('ester.pdb', compound=self, relative_to_module=self.__module__)
        mb.translate(self, -self[0].pos)

        self.add(mb.Port(anchor=self[2]), 'up')
        mb.rotate_around_z(self['up'], np.pi / 2)
        mb.translate_to(self['up'], self[2].pos + np.array([0.07, 0, 0]))

        self.add(mb.Port(anchor=self[0]), 'down')
        mb.rotate_around_z(self['down'], np.pi / 2)
        mb.translate(self['down'], np.array([-0.07, 0, 0]))
コード例 #11
0
ファイル: ester.py プロジェクト: ctk3b/mbuild
    def __init__(self):
        super(Ester, self).__init__()

        mb.load('ester.pdb', compound=self, relative_to_module=self.__module__)
        self.translate(-self[0].pos)

        self.add(mb.Port(anchor=self[2]), 'up')
        self['up'].spin(np.pi / 2, [0, 0, 1])
        self['up'].translate_to(np.array([0.07, 0, 0]))

        self.add(mb.Port(anchor=self[0]), 'down')
        self['down'].spin(np.pi / 2, [0, 0, 1])
        self['down'].translate(np.array([-0.07, 0, 0]))
コード例 #12
0
    def __init__(self):
        super(Carbonyl, self).__init__()

        mb.load('carbonyl.pdb',
                compound=self,
                relative_to_module=self.__module__)
        self.translate(-self[0].pos)  # Move carbon to origin.

        self.add(
            mb.Port(anchor=self[0], orientation=[1, 0, 0], separation=0.075),
            'right')

        self.add(
            mb.Port(anchor=self[0], orientation=[-1, 0, 0], separation=0.075),
            'left')
コード例 #13
0
ファイル: test_compound.py プロジェクト: tcmoore3/mbuild
 def test_save_box(self, ch3):
     extensions = ['.mol2', '.pdb', '.hoomdxml', '.gro']
     box_attributes = ['mins', 'maxs', 'lengths']
     custom_box = mb.Box([.8, .8, .8])
     for ext in extensions:
         outfile_padded = 'padded_methyl' + ext
         outfile_custom = 'custom_methyl' + ext
         ch3.save(filename=outfile_padded, box=None, overwrite=True)
         ch3.save(filename=outfile_custom, box=custom_box, overwrite=True)
         padded_ch3 = mb.load(outfile_padded)
         custom_ch3 = mb.load(outfile_custom)
         for attr in box_attributes:
             pad_attr = getattr(padded_ch3.boundingbox, attr)
             custom_attr = getattr(custom_ch3.boundingbox, attr)
             assert np.array_equal(pad_attr, custom_attr)
コード例 #14
0
ファイル: generate.py プロジェクト: matty-jones/rhaco
 def __init__(self, template, stoichiometry_dict):
     # Call the mb.Compound initialisation
     super().__init__()
     # Load the unit cell
     mb.load(os.path.join(PDB_LIBRARY, template), compound=self)
     # Replacable atoms in the matrix are assigned as type `X'
     # Note: In both Py2 and Py3, subsequent calls to keys() and values()
     # with no intervening modifications will directly correspond
     # \cite{PyDocumentation}
     atom_types, atom_probs, _ = calculate_probabilities(stoichiometry_dict)
     for particle in self.particles():
         if particle.name == 'X':
             # `Randomly' select an atom type based on the biases given in
             # stoichiometry_dict
             particle.name = np.random.choice(atom_types, p=atom_probs)
コード例 #15
0
ファイル: SOL.py プロジェクト: uppittu11/McCabeGroup
 def __init__(self, use_atom_name=True):
     super(SOL, self).__init__()
     if use_atom_name:
         mb.load('SOL_new.mol2',
                 compound=self,
                 relative_to_module=self.__module__,
                 infer_hierarchy=False)
     else:
         mb.load('SOL.mol2',
                 compound=self,
                 relative_to_module=self.__module__,
                 infer_hierarchy=False)
     self.children[0].charge = -0.834
     self.children[1].charge = 0.417
     self.children[2].charge = 0.417
コード例 #16
0
    def __init__(self):
        super(Betacristobalite, self).__init__()

        mb.load('beta-cristobalite-expanded.mol2', compound=self,
                relative_to_module=self.__module__)
        self.periodicity = np.array([5.3888, 4.6669, 0.0])

        count = 0
        for particle in self.particles():
            if particle.name.startswith('O') and particle.pos[2] > 1.0:
                count += 1
                port = mb.Port(anchor=particle)
                mb.rotate_around_x(port, np.pi/2)
                mb.translate(port, particle.pos + np.array([0, 0, .1]))
                self.add(port, 'port_{}'.format(count))
コード例 #17
0
    def __init__(self):
        super(Isopropylbenzene, self).__init__()

        mb.load('isopropylbenzene.pdb',
                compound=self,
                relative_to_module=self.__module__)
        # pop off bottom hydrogen on benzene ring
        direction = self[18].xyz - self[6].xyz
        self.remove(self[18])

        # add port anchored to newly hydrogen-less carbon in benzene ring
        self.add(
            mb.Port(anchor=self[6],
                    orientation=direction.tolist()[0],
                    separation=0.07), 'down')
コード例 #18
0
ファイル: silane.py プロジェクト: sallai/mbuild
    def __init__(self, ):
        super(Silane, self).__init__()
        mb.load('silane.pdb', compound=self, relative_to_module=self.__module__)

        # Transform the coordinate system such that the silicon atom is at the
        # origin and the oxygen atoms are on the x axis.
        mb.x_axis_transform(self, new_origin=self[0], point_on_x_axis=self[1])

        # Add bottom port.
        self.add(mb.Port(anchor=self[0]), 'down')
        mb.translate(self['down'], np.array([0, -.07, 0]))

        # Add top port.
        self.add(mb.Port(anchor=self[0]), 'up')
        mb.translate(self['up'], np.array([0, .07, 0]))
コード例 #19
0
ファイル: silane.py プロジェクト: ctk3b/mbuild
    def __init__(self, ):
        super(Silane, self).__init__()
        mb.load('silane.pdb', compound=self, relative_to_module=self.__module__)

        # Transform the coordinate system such that the silicon atom is at the
        # origin and the oxygen atoms are on the x axis.
        mb.x_axis_transform(self, new_origin=self[0], point_on_x_axis=self[1])

        # Add bottom port.
        self.add(mb.Port(anchor=self[0]), 'down')
        self['down'].translate(np.array([0, -.07, 0]))

        # Add top port.
        self.add(mb.Port(anchor=self[0]), 'up')
        self['up'].translate(np.array([0, .07, 0]))
コード例 #20
0
ファイル: cer2_18.py プロジェクト: uppittu11/lipids
 def __init__(self):
     """Returns a CG uCER2 with the head-to-tail vector pointing in -z.
     """
     super(Cer2_18, self).__init__()
     mb.load('cer2-18.hoomdxml', compound=self, relative_to_module=self.__module__)
     self.periodicity = [0, 0, 0]
     xx = list(self.particles())
     mb.coordinate_transform.z_axis_transform(self,
             new_origin=xx[9], point_on_z_axis=xx[14])
     self.translate([-self.center[0], -self.center[1], 0])  # center in xy plane
     self.masses = [0.403639, 0.584458, 0.584458, 0.584458,
               0.584458, 0.584458, 0.597575, 0.556458, 0.556458, 0.584458,
               0.584458, 0.584458, 0.598458, 0.236214, 0.236214]
     self.mass = np.sum(self.masses)
     self.rotate(np.pi, [1, 0, 0])
コード例 #21
0
ファイル: test_compound.py プロジェクト: whitehml/mbuild
 def test_save_box(self, ch3):
     extensions = ['.mol2', '.pdb', '.hoomdxml', '.gro']
     box_attributes = ['mins', 'maxs', 'lengths']
     custom_box = mb.Box([.8, .8, .8])
     for ext in extensions:
         outfile_padded = 'padded_methyl' + ext
         outfile_custom = 'custom_methyl' + ext
         ch3.save(filename=outfile_padded, box=None, overwrite=True)
         ch3.save(filename=outfile_custom, box=custom_box, overwrite=True)
         padded_ch3 = mb.load(outfile_padded)
         custom_ch3 = mb.load(outfile_custom)
         for attr in box_attributes:
             pad_attr = getattr(padded_ch3.boundingbox, attr)
             custom_attr = getattr(custom_ch3.boundingbox, attr)
             assert np.array_equal(pad_attr, custom_attr)
コード例 #22
0
    def test_non_zero_charge(self):
        import mbuild as mb

        compound = mb.load("C1=CC=C2C(=C1)C(C3=CC=CC=C3O2)C(=O)O", smiles=True)
        oplsaa = Forcefield(name="oplsaa")
        with pytest.warns(UserWarning):
            oplsaa.apply(compound, assert_dihedral_params=False)
コード例 #23
0
    def test_comb_rule(self, mixing_rule):
        import mbuild as mb

        mol2 = mb.load(get_fn("ethane.mol2"))
        oplsaa = Forcefield(name="oplsaa")
        ethane = oplsaa.apply(mol2, combining_rule=mixing_rule)
        assert ethane.combining_rule == mixing_rule
コード例 #24
0
def get_info(inputfile, frame=-1, show_bonds=False):
    """Get dictionary of information about inputfile.

    `info` is a dictionary containing the number of particles, the particle
    types in the system, a typeid for each particle, particle positions, the
    number of bonds, the particle indices which are bonded, and the box
    information. These quantities follow GSD format

    Parameters
    ----------
    inputfile: path
        Path to file to get info from.
    frame: int
        If trajectory, frame to get info from.
    show_bonds: bool
        Whether to show the bonds in the scene.

    Returns
    -------
    dict
    """
    name, extension = os.path.splitext(inputfile)
    if extension == ".gsd":
        # info contains N, types, typeids, positions, N_bonds, bonds, box
        info = get_gsd_info(inputfile, frame, show_bonds)
    else:
        comp = mb.load(inputfile)
        # info contains N, types, typeids, positions, N_bonds, bonds, box
        info = get_comp_info(comp, show_bonds)
    return info
コード例 #25
0
ファイル: test_forcefield.py プロジェクト: uppittu11/foyer
def test_topology_precedence():
    """Test to see if topology precedence is properly adhered to.

    This test uses a force field file where bond, angle, and dihedral
    parameters are present with different counts of `type` definitions.
    It checks that:
        1. The parameters with the higher number of `type` definitions
           are assigned (because they are given the highest precedence)
        2. That if multiple definitions exist with the same number of
           `type` definitions, that the convention from OpenMM is followed
           whereby the definitions that occurs earliest in the XML is
           assigned.
    """
    import mbuild as mb
    ethane = mb.load(get_fn('ethane.mol2'))
    ff = Forcefield(forcefield_files=get_fn('ethane-topo-precedence.xml'))
    typed_ethane = ff.apply(ethane)

    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.15]) == 6
    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.6]) == 1
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 120.321]) == 6
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 97.403]) == 6
    assert len([rb for rb in typed_ethane.rb_torsions
                if round(rb.type.c0, 3) == 0.287]) == 9
コード例 #26
0
def run_nvt(**custom_args):

    # Use mBuild to create a methane molecule
    methane = mbuild.load("C", smiles=True)

    # Create an empty mbuild.Box
    box = mbuild.Box(lengths=[3.0, 3.0, 3.0])

    # Load force field
    oplsaa = foyer.forcefields.load_OPLSAA()

    # Use foyer to apply force field to methane
    methane_ff = oplsaa.apply(methane)

    # Create box and species list
    box_list = [box]
    species_list = [methane_ff]

    # Use Cassandra to insert some initial number of methane molecules
    mols_to_add = [[50]]

    # Define the System
    system = mc.System(box_list, species_list, mols_to_add=mols_to_add)
    # Define the MoveSet
    moveset = mc.MoveSet("nvt", species_list)

    # Run a simulation at 300 K for 10000 MC moves
    mc.run(
        system=system,
        moveset=moveset,
        run_type="equilibration",
        run_length=10000,
        temperature=300.0 * u.K,
        **custom_args,
    )
コード例 #27
0
def _get_water():
    cache_dir = resource_filename('bulk_water', 'lib')
    filename = 'water.mol2'
    water = mb.load(os.path.join(cache_dir, filename))
    water.name = 'SOL'

    return water
コード例 #28
0
    def test_rb_torsions_vs_foyer(self, ethanol_with_rb_torsions):
        # Given that these force constants are copied from Foyer's OPLS-AA file,
        # compare to processing through the current MoSDeF pipeline
        import foyer
        import mbuild

        comp = mbuild.load("CC", smiles=True)
        comp.xyz = ethanol_with_rb_torsions.positions.m_as(unit.nanometer)
        ff = foyer.Forcefield(name="oplsaa")
        from_foyer = ff.apply(comp)
        from_foyer.box = [40, 40, 40, 90, 90, 90]
        from_foyer.save("from_foyer.top")
        from_foyer.save("from_foyer.gro")

        rb_torsion_energy_from_foyer = _run_gmx_energy(
            top_file="from_foyer.top",
            gro_file="from_foyer.gro",
            mdp_file=_get_mdp_file("default"),
        ).energies["Torsion"]

        # GROMACS vs. OpenMM was already compared, so just use one
        omm = get_gromacs_energies(ethanol_with_rb_torsions, decimal=3).energies[
            "Torsion"
        ]

        assert (omm - rb_torsion_energy_from_foyer).m_as(kj_mol) < 1e-6
コード例 #29
0
    def test_gmso_backend_lj_site_type(self):
        pmd_silica_surface = mb.load(
            filename_or_object=get_fn("beta-cristobalite-expanded.mol2"),
            backend="parmed",
        )
        gmso_silica_surface = mb.load(
            filename_or_object=get_fn("beta-cristobalite-expanded.mol2"),
            backend="gmso",
            site_type="lj",
        )

        assert pmd_silica_surface.n_particles == gmso_silica_surface.n_particles
        assert pmd_silica_surface.n_bonds == gmso_silica_surface.n_bonds

        for particle in gmso_silica_surface:
            assert particle.element is None
コード例 #30
0
ファイル: base_test.py プロジェクト: plin1112/mbuild
    def benzene_from_parts(self):
        ch = mb.load(get_fn('ch.mol2'))
        ch.name = 'CH'
        mb.translate(ch, -ch[0].pos)
        ch.add(mb.Port(anchor=ch[0]), 'a')
        mb.translate(ch['a'], [0, 0.07, 0])
        mb.rotate_around_z(ch['a'], 120.0 * (np.pi / 180.0))

        ch.add(mb.Port(anchor=ch[0]), 'b')
        mb.translate(ch['b'], [0, 0.07, 0])
        mb.rotate_around_z(ch['b'], -120.0 * (np.pi / 180.0))

        benzene = mb.Compound(name='Benzene')
        benzene.add(ch)
        current = ch

        for _ in range(5):
            ch_new = mb.clone(ch)
            mb.force_overlap(move_this=ch_new,
                             from_positions=ch_new['a'],
                             to_positions=current['b'])
            current = ch_new
            benzene.add(ch_new)

        carbons = [p for p in benzene.particles_by_name('C')]
        benzene.add_bond((carbons[0], carbons[-1]))

        return benzene
コード例 #31
0
    def test_singleterm_charmm(self):
        from foyer import Forcefield

        from mbuild.formats.lammpsdata import write_lammpsdata

        cmpd = mb.load(get_fn("charmm_dihedral.mol2"))
        for i in cmpd.particles():
            i.name = "_{}".format(i.name)
        structure = cmpd.to_parmed(
            box=cmpd.get_boundingbox(),
            residues=set([p.parent.name for p in cmpd.particles()]),
        )
        ff = Forcefield(
            forcefield_files=[get_fn("charmm_truncated_singleterm.xml")])
        structure = ff.apply(structure, assert_dihedral_params=False)
        write_lammpsdata(structure, "charmm_dihedral_singleterm.lammps")
        out_lammps = open("charmm_dihedral_singleterm.lammps", "r").readlines()
        found_dihedrals = False
        for i, line in enumerate(out_lammps):
            if "Dihedral Coeffs" in line:
                assert "# charmm" in line
                assert "#k, n, phi, weight" in out_lammps[i + 1]
                assert len(out_lammps[i + 2].split("#")[0].split()) == 5
                assert float(
                    out_lammps[i + 2].split("#")[0].split()[4]) == float("1.0")
                found_dihedrals = True
            else:
                pass
        assert found_dihedrals
コード例 #32
0
 def test_load_with_top(self, ethane):
     ethane.save(filename='ethane.xyz')
     ethane.save(filename='ethane.mol2')
     ethane_in = mb.load('ethane.xyz', top='ethane.mol2')
     assert len(ethane_in.children) == 8
     assert ethane_in.n_bonds == 7
     assert set([child.name for child in ethane_in.children]) == {'C', 'H'}
コード例 #33
0
ファイル: base_test.py プロジェクト: ramanishsingh/mbuild
    def benzene_from_parts(self):
        ch = mb.load(get_fn('ch.mol2'))
        ch.name = 'CH'
        ch.translate(-ch[0].pos)       
        ch.add(mb.Port(anchor=ch[0], separation=0.07), 'a')
        ch['a'].rotate(120.0 * (np.pi/180.0), around=np.asarray([0, 0, 1]))
        ch.add(mb.Port(anchor=ch[0], separation=0.07), 'b')
        ch['b'].rotate(-120.0 * (np.pi/180.0), around=np.asarray([0, 0, 1]))
        ch_copy = mb.clone(ch)

        benzene = mb.Compound(name='Benzene')
        benzene.add(ch)
        current = ch

        for _ in range(5):
            ch_new = mb.clone(ch_copy)
            mb.force_overlap(move_this=ch_new,
                             from_positions=ch_new['a'],
                             to_positions=current['b'])
            current = ch_new
            benzene.add(ch_new)

        carbons = [p for p in benzene.particles_by_name('C')]
        benzene.add_bond((carbons[0],carbons[-1]))

        return benzene
コード例 #34
0
    def test_gaff(self, smiles):
        import foyer
        import mbuild as mb
        # These tests are smiles strings
        cmpd = mb.load(smiles, smiles=True)
        ff = commpare.identify_forcefields()['GAFF']
        structure = ff.apply(cmpd)
        # Enlarge box to avoid cutoff issues
        bbox = cmpd.boundingbox
        bbox.lengths *= 10
        if any(bbox.lengths < 10):
            bbox.lengths = [100, 100, 100]

        structure.box = [
            bbox.lengths[0], bbox.lengths[1], bbox.lengths[2], 90, 90, 90
        ]
        energies = commpare.spawn_engine_simulations(structure,
                                                     hoomd_kwargs={
                                                         'ref_distance': 10,
                                                         'ref_energy':
                                                         1 / 4.184
                                                     })
        print(smiles)
        print(energies)
        print('=' * 20)
コード例 #35
0
def run_gcmc_restricted():

    # Use mbuild to create molecules
    methane = mbuild.load("C", smiles=True)

    # Create an empty mbuild.Box
    box = mbuild.Box(lengths=[5.0, 5.0, 5.0])

    # Load forcefields
    oplsaa = foyer.forcefields.load_OPLSAA()

    # Use foyer to apply forcefields
    methane_ff = oplsaa.apply(methane)

    # Create box and species list
    box_list = [box]
    species_list = [methane_ff]

    mols_to_add = [[10]]

    system = mc.System(box_list, species_list, mols_to_add=mols_to_add)
    moves = mc.Moves("gcmc", species_list)

    # Specify restricted insertions
    moves.add_restricted_insertions(species_list, [["sphere"]], [[20]])

    mc.run(
        system=system,
        moves=moves,
        run_type="equilibration",
        run_length=100,
        temperature=300.0,
        chemical_potentials=[-35.0],
        prop_freq=10,
    )
コード例 #36
0
    def test_allow_empty_def(self):
        import mbuild as mb

        ethane = mb.load(get_fn("ethane.mol2"))
        with pytest.warns(ValidationWarning):
            ff = Forcefield(forcefield_files=get_fn("empty_def.xml"))
        ff.apply(ethane)
コード例 #37
0
    def test_write_refs_multiple(self, requests_mock):
        import mbuild as mb

        register_mock_request(
            mocker=requests_mock,
            url="http://api.crossref.org/",
            path="works/10.1021/ja9621760/transform/application/x-bibtex",
            headers={"accept": "application/x-bibtex"},
            text=RESPONSE_BIB_ETHANE_JA962170,
        )
        register_mock_request(
            mocker=requests_mock,
            url="http://api.crossref.org/",
            path="works/10.1021/jp0484579/transform/application/x-bibtex",
            headers={"accept": "application/x-bibtex"},
            text=RESPONSE_BIB_ETHANE_JP0484579,
        )
        mol2 = mb.load(get_fn("ethane.mol2"))
        oplsaa = Forcefield(forcefield_files=get_fn("refs-multi.xml"))
        ethane = oplsaa.apply(mol2, references_file="ethane-multi.bib")
        assert os.path.isfile("ethane-multi.bib")
        with open(get_fn("ethane-multi.bib")) as file1:
            with open("ethane-multi.bib") as file2:
                diff = list(
                    difflib.unified_diff(file1.readlines(),
                                         file2.readlines(),
                                         n=0))
        assert not diff
コード例 #38
0
    def test_overrides_space(self):
        import mbuild as mb

        ethane = mb.load(get_fn("ethane.mol2"))
        ff = Forcefield(forcefield_files=get_fn("overrides-space.xml"))
        typed_ethane = ff.apply(ethane)
        assert typed_ethane.atoms[0].type == "CT3"
コード例 #39
0
    def test_save_forcefield_with_same_struct(self):
        from foyer import Forcefield

        from mbuild.formats.lammpsdata import write_lammpsdata

        system = mb.load("C1(=CC=CC=C1)F", smiles=True)

        ff = Forcefield(forcefield_files=[get_fn("gaff_test.xml")])
        struc = ff.apply(
            system,
            assert_angle_params=False,
            assert_dihedral_params=False,
            assert_improper_params=False,
        )
        write_lammpsdata(struc,
                         "charmm_improper.lammps",
                         zero_dihedral_weighting_factor=True)
        for i in range(3):
            xyz = struc.coordinates
            xyz = xyz + np.array([1, 1, 1])
            struc.coordinates = xyz
            write_lammpsdata(
                struc,
                f"charmm_improper{i}.lammps",
                zero_dihedral_weighting_factor=True,
            )
コード例 #40
0
ファイル: peg.py プロジェクト: zijiewu3/mbuild
    def __init__(self):
        super(PegMonomer, self).__init__()

        mb.load(
            "peg_monomer.pdb",
            compound=self,
            relative_to_module=self.__module__,
            infer_hierarchy=False,
        )
        self.translate(-self[0].pos)

        self.add(mb.Port(anchor=self[0]), "down")
        self["down"].translate([0, -0.07, 0])

        self.add(mb.Port(anchor=self[6]), "up")
        self["up"].translate([0, 0.073, 0])
コード例 #41
0
ファイル: base_test.py プロジェクト: ctk3b/mbuild
    def benzene_from_parts(self):
        ch = mb.load(get_fn('ch.mol2'))
        ch.name = 'CH'
        mb.translate(ch, -ch[0].pos)       
        ch.add(mb.Port(anchor=ch[0]), 'a')
        mb.translate(ch['a'], [0, 0.07, 0]) 
        mb.rotate_around_z(ch['a'], 120.0 * (np.pi/180.0))

        ch.add(mb.Port(anchor=ch[0]), 'b')
        mb.translate(ch['b'], [0, 0.07, 0]) 
        mb.rotate_around_z(ch['b'], -120.0 * (np.pi/180.0))

        benzene = mb.Compound(name='Benzene')
        benzene.add(ch)
        current = ch

        for _ in range(5):
            ch_new = mb.clone(ch)
            mb.force_overlap(move_this=ch_new,
                             from_positions=ch_new['a'],
                             to_positions=current['b'])
            current = ch_new
            benzene.add(ch_new)

        carbons = [p for p in benzene.particles_by_name('C')]
        benzene.add_bond((carbons[0],carbons[-1]))

        return benzene
コード例 #42
0
    def test_save_charmm(self):
        from foyer import Forcefield

        cmpd = mb.load(get_fn("charmm_dihedral.mol2"))
        for i in cmpd.particles():
            i.name = "_{}".format(i.name)
        structure = cmpd.to_parmed(
            box=cmpd.get_boundingbox(),
            residues=set([p.parent.name for p in cmpd.particles()]),
        )
        ff = Forcefield(forcefield_files=[get_fn("charmm_truncated.xml")])
        structure = ff.apply(structure, assert_dihedral_params=False)
        write_lammpsdata(structure, "charmm_dihedral.lammps")
        out_lammps = open("charmm_dihedral.lammps", "r").readlines()
        found_angles = False
        found_dihedrals = False
        for i, line in enumerate(out_lammps):
            if "Angle Coeffs" in line:
                assert "# charmm" in line
                assert (
                    "#\tk(kcal/mol/rad^2)\t\ttheteq(deg)\tk(kcal/mol/angstrom^2)\treq(angstrom)\n"
                    in out_lammps[i + 1])
                assert len(out_lammps[i + 2].split("#")[0].split()) == 5
                found_angles = True
            elif "Dihedral Coeffs" in line:
                assert "# charmm" in line
                assert "#k, n, phi, weight" in out_lammps[i + 1]
                assert len(out_lammps[i + 2].split("#")[0].split()) == 5
                found_dihedrals = True
            else:
                pass
        assert found_angles
        assert found_dihedrals
コード例 #43
0
ファイル: test_compound.py プロジェクト: joaander/mbuild
    def test_reload(self):
        # Create a compound and write it to file.
        p3ht1 = mb.load('CCCCCCC1=C(SC(=C1)C)C', smiles=True)
        p3ht1.save("p3ht1.pdb")

        # Create another compound, rotate it and write it to file.
        p3ht2 = mb.load('CCCCCCC1=C(SC(=C1)C)C', smiles=True)
        mb.rotate(p3ht2, np.pi / 2, [0, 0, 1])
        p3ht2.save("p3ht2.pdb")

        # Load p3ht2.pdb into p3ht1, modifying the atom positions of p3ht1.
        p3ht1.update_coordinates("p3ht2.pdb")
        p3ht1.save("modified_p3ht1.pdb")

        assert p3ht1.n_particles == 33
        assert p3ht1.n_bonds == 33
コード例 #44
0
ファイル: test_forcefield.py プロジェクト: iModels/foyer
def test_topology_precedence():
    """Test to see if topology precedence is properly adhered to.

    This test uses a force field file where bond, angle, and dihedral
    parameters are present with different counts of `type` definitions.
    It checks that:
        1. The parameters with the higher number of `type` definitions
           are assigned (because they are given the highest precedence)
        2. That if multiple definitions exist with the same number of
           `type` definitions, that the convention from OpenMM is followed
           whereby the definitions that occurs earliest in the XML is
           assigned.
    """
    ethane = mb.load(get_fn('ethane.mol2'))
    ff = Forcefield(forcefield_files=get_fn('ethane-topo-precedence.xml'))
    typed_ethane = ff.apply(ethane)

    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.15]) == 6
    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.6]) == 1
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 120.321]) == 6
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 97.403]) == 6
    assert len([rb for rb in typed_ethane.rb_torsions
                if round(rb.type.c0, 3) == 0.287]) == 9
コード例 #45
0
 def test_save(self):
     methyl = mb.load(get_fn('methyl.pdb'))
     extensions = ['.xyz', '.pdb', '.mol2']
     for ext in extensions:
         outfile = 'methyl_out' + ext
         methyl.save(filename=outfile)
         assert os.path.exists(outfile)
コード例 #46
0
ファイル: edit_xml.py プロジェクト: CalCraven/OPLSAA_Mods
def Compare_Standard_Mol(test_molecule_path,test_forcefield_path):
    molecule=mb.load(test_molecule_path)
    parmed_structure = molecule.to_parmed()
    opls = foyer.Forcefield(forcefield_files=[test_forcefield_path])
    typed_molecule = opls.apply(parmed_structure)
    filepath=os.path.join("./test_molecules/test_molecule_comp.top")
    typed_molecule.save(filepath,overwrite=True)
    originalfilepath=os.path.join(test_molecule_path[:-4]+'top')
    count=0
    total=0
    halt=0
    with open(filepath,'r') as openfile:
        with open(originalfilepath,'r') as compfile:
            comp_lines=compfile.readlines()[17:]
            lines=openfile.readlines()[17:]
            #print(len(comp_lines),len(lines))
            for i,line in enumerate(lines):
                #print(line)
                if line == '[ bonds ]\n':
                    halt = 1
                if line == '[ pairs ]\n':
                    halt = 0
                if not(halt):
                    total+=1
                    if line == comp_lines[i]:
                        count+=1

    if count/total==1.0:
        print(test_molecule_path[:-5] +' Passed')
    else:
        print(test_molecule_path[:-5] +' Failed')
コード例 #47
0
ファイル: betacristobalite.py プロジェクト: ctk3b/mbuild
    def __init__(self):
        super(Betacristobalite, self).__init__()

        mb.load('beta-cristobalite-expanded.mol2', compound=self,
                relative_to_module=self.__module__)
        self.periodicity = np.array([5.3888, 4.6669, 0.0])

        count = 0
        for particle in self.particles():
            if particle.name.startswith('O') and particle.pos[2] > 1.0:
                count += 1
                port = mb.Port(anchor=particle, orientation=[0, 0, 1], 
                               separation=0.1)
                self.add(port, 'port_{}'.format(count))
                particle.name = 'O'  # Strip numbers required in .mol2 files.
            elif particle.name.startswith('Si'):
                particle.name = 'Si'
コード例 #48
0
ファイル: test_forcefield.py プロジェクト: iModels/foyer
def test_missing_topo_params(ff_filename, kwargs):
    """Test that the user is notified if not all topology parameters are found."""
    ethane = mb.load(get_fn('ethane.mol2'))
    oplsaa_with_typo = Forcefield(forcefield_files=get_fn(ff_filename))
    with pytest.raises(Exception):
        ethane = oplsaa_with_typo.apply(ethane)
    with pytest.warns(UserWarning):
        ethane = oplsaa_with_typo.apply(ethane, **kwargs)
コード例 #49
0
ファイル: test_hoomdxml.py プロジェクト: iModels/mbuild
 def test_box_dimensions(self, benzene):
     n_benzenes = 10
     filled = mb.fill_box(benzene,
                          n_compounds=n_benzenes,
                          box=[0, 0, 0, 4, 4, 4])
     filled.save(filename='benzene.hoomdxml')
     for atom in mb.load('benzene.hoomdxml'):
         assert atom.pos.max() < 20
         assert atom.pos.min() > -20
コード例 #50
0
ファイル: initiator.py プロジェクト: TengyuMaVandy/mbuild
    def __init__(self):
        super(Initiator, self).__init__()

        # Look for data file in same directory as this python module.
        mb.load('initiator.pdb', compound=self, relative_to_module=self.__module__)

        # Transform the coordinate system such that the two carbon atoms
        # that are part of the backbone are on the y axis, C_1 at the origin.
        mb.y_axis_transform(self, new_origin=self[0], point_on_y_axis=self[21])

        # Add bottom port
        self.add(mb.Port(anchor=self[0]), 'down')
        # Place the port.
        mb.translate(self['down'], self[0].pos + np.array([0.0, -0.07, 0.0]))

        # Add top port.
        self.add(mb.Port(anchor=self[21]), 'up')
        # Place the port.
        mb.translate(self['up'], self[21].pos + np.array([0.0, 0.07, 0.0]))
コード例 #51
0
ファイル: bilayer.py プロジェクト: hainm/mbuild
def main():
    from mbuild.utils.io import get_fn
    from mbuild.lib.moieties import H2O

    water = H2O()
    ecerns = mb.load(get_fn('ecer2.pdb'))

    chol = mb.load(get_fn('cg-chol.pdb'))
    # Orient along the z-direction.
    mb.rotate_around_x(chol, -135.0*np.pi/180)
    mb.rotate_around_y(chol, -45.0*np.pi/180)

    lipids = [(ecerns, 0.5), (chol, 0.5)]

    bilayer = Bilayer(lipids, n_lipids_x=15, n_lipids_y=15, area_per_lipid=1.4,
                      solvent=water, ref_atoms=[1, 6],  spacing_z=0.7,
                      solvent_per_lipid=20, mirror=False)

    bilayer.save(filename='bilayer.pdb')
    return bilayer
コード例 #52
0
ファイル: test_forcefield.py プロジェクト: iModels/foyer
def test_write_refs_multiple():
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(forcefield_files=get_fn('refs-multi.xml'))
    ethane = oplsaa.apply(mol2, references_file='ethane-multi.bib')
    assert os.path.isfile('ethane-multi.bib')
    with open(get_fn('ethane-multi.bib')) as file1:
        with open('ethane-multi.bib') as file2:
            diff = list(difflib.unified_diff(file1.readlines(),
                                             file2.readlines(),
                                             n=0))
    assert not diff
コード例 #53
0
ファイル: amorphous_silica.py プロジェクト: ctk3b/mbuild
    def __init__(self, surface_roughness=1.0):
        super(AmorphousSilica, self).__init__()

        if surface_roughness == 1.0:
            # TODO: description of how this surface was generated/citation
            mb.load('amorphous_silica_sr1.0.pdb', compound=self,
                    relative_to_module=self.__module__)
            self.periodicity = np.array([5.4366, 4.7082, 0.0])
        else:
            raise ValueError('Amorphous silica input file with surface '
                             'roughness of {0:.1f} does not exist. If you have '
                             'this structure, please submit a pull request to'
                             'add it! '.format(surface_roughness))
        count = 0
        for particle in self.particles():
            if particle.name == 'OB':
                count += 1
                port = mb.Port(anchor=particle, orientation=[0, 0, 1],
                               separation=0.1)
                self.add(port, 'port_{}'.format(count))
コード例 #54
0
ファイル: test_forcefield.py プロジェクト: sallai/foyer
def test_from_mbuild():
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(name='oplsaa')
    ethane = oplsaa.apply(mol2)

    assert sum((1 for at in ethane.atoms if at.type == 'opls_135')) == 2
    assert sum((1 for at in ethane.atoms if at.type == 'opls_140')) == 6
    assert len(ethane.bonds) == 7
    assert all(x.type for x in ethane.bonds)
    assert len(ethane.angles) == 12
    assert all(x.type for x in ethane.angles)
    assert len(ethane.rb_torsions) == 9
    assert all(x.type for x in ethane.dihedrals)
コード例 #55
0
ファイル: base_test.py プロジェクト: ctk3b/mbuild
    def rigid_ch(self):
        ch = mb.load(get_fn('ch.mol2'))
        ch.name = 'CH'
        ch.label_rigid_bodies()
        mb.translate(ch, -ch[0].pos)    
        ch.add(mb.Port(anchor=ch[0]), 'a')
        mb.translate(ch['a'], [0, 0.07, 0]) 
        mb.rotate_around_z(ch['a'], 120.0 * (np.pi/180.0))

        ch.add(mb.Port(anchor=ch[0]), 'b')
        mb.translate(ch['b'], [0, 0.07, 0]) 
        mb.rotate_around_z(ch['b'], -120.0 * (np.pi/180.0))
        return ch
コード例 #56
0
ファイル: test_forcefield.py プロジェクト: iModels/foyer
def test_from_mbuild_customtype():
    mol2 = mb.load(get_fn('ethane_customtype.pdb'))
    customtype_ff = Forcefield(forcefield_files=get_fn('validate_customtypes.xml'))
    ethane = customtype_ff.apply(mol2)

    assert sum((1 for at in ethane.atoms if at.type == 'C3')) == 2
    assert sum((1 for at in ethane.atoms if at.type == 'Hb')) == 6
    assert len(ethane.bonds) == 7
    assert all(x.type for x in ethane.bonds)
    assert len(ethane.angles) == 12
    assert all(x.type for x in ethane.angles)
    assert len(ethane.rb_torsions) == 9
    assert all(x.type for x in ethane.dihedrals)
コード例 #57
0
ファイル: mpc.py プロジェクト: hainm/mbuild
    def __init__(self, alpha=0):
        super(MPC, self).__init__()

        # Look for data file in same directory as this python module.
        mb.load('mpc.pdb', compound=self, relative_to_module=self.__module__)

        # Transform the coordinate system of mpc such that the two carbon atoms
        # that are part of the backbone are on the y axis, c_backbone at the origin.
        C_top = self[37]
        # this can be achieved with the following alternative syntax:
        # C_top = self.labels["atom[37]"]
        # C_top = self.labels["atom"][37]
        C_bottom = self[1]

        mb.y_axis_transform(self, new_origin=C_top, point_on_y_axis=C_bottom)

        # Add top port.
        self.add(mb.Port(anchor=C_top), label='up')
        mb.translate(self['up'], C_top.pos - (C_top.pos - C_bottom.pos)*1.50)

        # Add bottom port
        self.add(mb.Port(anchor=C_bottom), 'down')
        mb.rotate_around_y(self['down'], alpha)
        mb.translate(self['down'], C_bottom.pos - (C_bottom.pos - C_top.pos)*1.50)
コード例 #58
0
ファイル: test_mol2file.py プロジェクト: TengyuMaVandy/mbuild
 def test_save(self):
     methyl = mb.load(get_fn('methyl.mol2'))
     methyl.save(filename='methyl_out.mol2')
コード例 #59
0
ファイル: test_mol2file.py プロジェクト: TengyuMaVandy/mbuild
 def test_load_and_create(self):
     mb.load(get_fn('methyl.mol2'))