Пример #1
0
    def ethane(self):
        mytop = Topology()
        c1 = Atom(name='C1')
        h11 = Atom(name='H11')
        h12 = Atom(name='H12')
        h13 = Atom(name='H13')

        c2 = Atom(name='C2')
        h21 = Atom(name='H21')
        h22 = Atom(name='H22')
        h23 = Atom(name='H23')

        c1h11 = Bond(connection_members=[c1, h11])
        c1h12 = Bond(connection_members=[c1, h12])
        c1h13 = Bond(connection_members=[c1, h13])

        c2h21 = Bond(connection_members=[c2, h21])
        c2h22 = Bond(connection_members=[c2, h22])
        c2h23 = Bond(connection_members=[c2, h23])

        c1c2 = Bond(connection_members=[c1, c2])

        mytop.add_connection(c1h11, update_types=False)
        mytop.add_connection(c1h12, update_types=False)
        mytop.add_connection(c1h13, update_types=False)

        mytop.add_connection(c2h21, update_types=False)
        mytop.add_connection(c2h22, update_types=False)
        mytop.add_connection(c2h23, update_types=False)

        mytop.add_connection(c1c2, update_types=False)
        mytop.update_topology()

        return mytop
Пример #2
0
 def test_with_1000_atom_types(self):
     top = Topology()
     for i in range(1000):
         site = Site()
         atom_type = AtomType()
         site.atom_type = atom_type
         top.add_site(site, update_types=False)
     top.update_topology()
     assert len(top.atom_types) == 1
     assert top.n_sites == 1000
Пример #3
0
    def test_add_duplicate_connected_atom(self):
        top = Topology()
        atom1 = Atom(name="AtomA")
        atom2 = Atom(name="AtomB")
        bond = Bond(connection_members=[atom1, atom2])
        bond_eq = Bond(connection_members=[atom1, atom2])

        top.add_connection(bond)
        top.add_connection(bond_eq)
        top.update_topology()
        assert top.n_connections == 1
Пример #4
0
 def test_topology_atom_type_changes(self):
     top = Topology()
     for i in range(100):
         site = Site(name='site{}'.format(i))
         atom_type = AtomType(name='atom_type{}'.format(i % 10))
         site.atom_type = atom_type
         top.add_site(site, update_types=False)
     top.update_topology()
     assert len(top.atom_types) == 10
     top.sites[0].atom_type.name = 'atom_type_changed'
     assert id(top.sites[0].atom_type) == id(top.sites[10].atom_type)
     assert top.sites[10].atom_type.name == 'atom_type_changed'
     assert top.is_typed()
Пример #5
0
    def test_top_update(self):
        top = Topology()
        top.update_topology()
        assert top.n_sites == 0
        assert len(top.atom_types) == 0
        assert len(top.atom_type_expressions) == 0
        assert top.n_connections == 0
        assert len(top.connection_types) == 0
        assert len(top.connection_type_expressions) == 0

        atomtype = AtomType()
        site1 = Site(name='site1', atom_type=atomtype)
        top.add_site(site1)
        site2 = Site(name='site2', atom_type=atomtype)
        top.add_site(site2)

        assert top.n_sites == 2
        assert len(top.atom_types) == 1
        assert len(top.atom_type_expressions) == 1
        assert top.n_connections == 0
        assert len(top.connection_types) == 0
        assert len(top.connection_type_expressions) == 0


        ctype = BondType()
        connection_12 = Bond(connection_members=[site1, site2],
                             connection_type=ctype)
        top.add_connection(connection_12)

        assert top.n_sites == 2
        assert len(top.atom_types) == 1
        assert len(top.atom_type_expressions) == 1
        assert top.n_connections == 1
        assert len(top.connection_types) == 1
        assert len(top.connection_type_expressions) == 1

        site1.atom_type = AtomType(expression='sigma*epsilon')
        assert top.n_sites == 2
        assert len(top.atom_types) == 1
        assert len(top.atom_type_expressions) == 1
        assert top.n_connections == 1
        assert len(top.connection_types) == 1
        assert len(top.connection_type_expressions) == 1
        top.update_atom_types()
        assert top.n_sites == 2
        assert len(top.atom_types) == 2
        assert len(top.atom_type_expressions) == 2
        assert top.n_connections == 1
        assert len(top.connection_types) == 1
        assert len(top.connection_type_expressions) == 1
Пример #6
0
    def test_top_update(self):
        top = Topology()
        top.update_topology()
        assert top.n_sites == 0
        assert len(top.atom_types) == 0
        assert len(top.atom_type_expressions) == 0
        assert top.n_connections == 0
        assert len(top.connection_types) == 0
        assert len(top.connection_type_expressions) == 0

        atomtype = AtomType()
        atom1 = Atom(name='atom1', atom_type=atomtype)
        top.add_site(atom1)
        atom2 = Atom(name='atom2', atom_type=atomtype)
        top.add_site(atom2)

        assert top.n_sites == 2
        assert len(top.atom_types) == 1
        assert len(top.atom_type_expressions) == 1
        assert top.n_connections == 0
        assert len(top.connection_types) == 0
        assert len(top.connection_type_expressions) == 0

        ctype = BondType()
        connection_12 = Bond(connection_members=[atom1, atom2],
                             bond_type=ctype)
        top.add_connection(connection_12)

        assert top.n_sites == 2
        assert len(top.atom_types) == 1
        assert len(top.atom_type_expressions) == 1
        assert top.n_connections == 1
        assert len(top.connection_types) == 1
        assert len(top.connection_type_expressions) == 1

        atom1.atom_type = AtomType(expression='sigma*epsilon*r')
        assert top.n_sites == 2
        assert len(top.atom_types) == 1
        assert len(top.atom_type_expressions) == 1
        assert top.n_connections == 1
        assert len(top.connection_types) == 1
        assert len(top.connection_type_expressions) == 1
        top.update_atom_types()
        assert top.n_sites == 2
        assert len(top.atom_types) == 2
        assert len(top.atom_type_expressions) == 2
        assert top.n_connections == 1
        assert len(top.connection_types) == 1
        assert len(top.connection_type_expressions) == 1
Пример #7
0
def read_xyz(filename):
    """Reader for xyz file format.

    Read in an xyz file at the given path and return a Topology object.

    Parameters
    ----------
    filename : str
        Path to .xyz file that need to be read.

    Return
    ------
    top : topology.Topology
        Topology object
    """
    top = Topology()

    with open(filename, "r") as xyz_file:
        n_atoms = int(xyz_file.readline())
        xyz_file.readline()
        coords = np.zeros(shape=(n_atoms, 3)) * u.nanometer
        for row, _ in enumerate(coords):
            line = xyz_file.readline().split()
            if not line:
                msg = (
                    "Incorrect number of lines in input file. Based on the "
                    "number in the first line of the file, {} rows of atoms "
                    "were expected, but at least one fewer was found."
                )
                raise ValueError(msg.format(n_atoms))
            tmp = np.array(line[1:4], dtype=np.float) * u.angstrom
            coords[row] = tmp.in_units(u.nanometer)
            site = Atom(name=line[0], position=coords[row])
            top.add_site(site)
        top.update_topology()

        # Verify we have read the last line by ensuring the next line in blank
        line = xyz_file.readline().split()
        if line:
            msg = (
                "Incorrect number of lines in input file. Based on the "
                "number in the first line of the file, {} rows of atoms "
                "were expected, but at least one more was found."
            )
            raise ValueError(msg.format(n_atoms))

    return top
Пример #8
0
    def methane(self):
        mytop = Topology()
        c = Atom(name='c')
        h1 = Atom(name='h1')
        h2 = Atom(name='h2')
        h3 = Atom(name='h3')
        h4 = Atom(name='h4')
        ch1 = Bond(connection_members=[c, h1])
        ch2 = Bond(connection_members=[c, h2])
        ch3 = Bond(connection_members=[c, h3])
        ch4 = Bond(connection_members=[c, h4])
        mytop.add_site(c, update_types=False)
        mytop.add_site(h1, update_types=False)
        mytop.add_site(h2, update_types=False)
        mytop.add_site(h3, update_types=False)
        mytop.add_site(h4, update_types=False)
        mytop.add_connection(ch1, update_types=False)
        mytop.add_connection(ch2, update_types=False)
        mytop.add_connection(ch3, update_types=False)
        mytop.add_connection(ch4, update_types=False)
        mytop.update_topology()

        return mytop
Пример #9
0
def from_mbuild(compound, box=None, search_method=element_by_symbol):
    """Convert an mbuild.Compound to a gmso.Topology

    This conversion makes the following assumptions about the inputted
    `Compound`:
        * All positional and box dimension values in compound are in nanometers

        * If the `Compound` has 4 or more levels of hierarchy, these are\
            compressed to 3 levels of hierarchy in the resulting `Topology`. The\
            top level `Compound` becomes the `Topology`, the second level\
            Compounds become `SubTopologies`, and each particle becomes a `Site`,\
            which are added to their corresponding `SubTopologies`.\

        * Furthermore, `Sites` that do not belong to a sub-`Compound` are\
            added to a single-`Site` `SubTopology`.

        * The box dimension are extracted from `compound.periodicity`. If the\
            `compound.periodicity` is `None`, the box lengths are the lengths of\
            the bounding box + a 0.5 nm buffer.

        * Only `Bonds` are added for each bond in the `Compound`. If `Angles`\
        and `Dihedrals` are desired in the resulting `Topology`, they must be\
        added separately from this function.


    Parameters
    ----------
    compound : mbuild.Compound
        mbuild.Compound instance that need to be converted
    box : mbuild.Box, optional, default=None
        Box information to be loaded to a gmso.Topology
    search_method : function, optional, default=element_by_symbol
        Searching method used to assign element from periodic table to
        particle site.
        The information specified in the `search_method` argument is extracted
        from each `Particle`'s `name` attribute.
        Valid functions are element_by_symbol, element_by_name,
        element_by_atomic_number, and element_by_mass, which can be imported
        from `gmso.core.element'


    Returns
    -------
    top : gmso.Topology

    """

    msg = ("Argument compound is not an mbuild.Compound")
    assert isinstance(compound, mb.Compound), msg

    top = Topology()
    top.typed = False

    # Keep the name if it is not the default mBuild Compound name
    if compound.name != mb.Compound().name:
        top.name = compound.name

    site_map = dict()
    for child in compound.children:
        if len(child.children) == 0:
            continue
        else:
            subtop = SubTopology(name=child.name)
            top.add_subtopology(subtop)
            for particle in child.particles():
                pos = particle.xyz[0] * u.nanometer
                ele = search_method(particle.name)
                site = Site(name=particle.name, position=pos, element=ele)
                site_map[particle] = site
                subtop.add_site(site)
    top.update_topology()

    for particle in compound.particles():
        already_added_site = site_map.get(particle, None)
        if already_added_site:
            continue

        pos = particle.xyz[0] * u.nanometer
        ele = search_method(particle.name)
        site = Site(name=particle.name, position=pos, element=ele)
        site_map[particle] = site

        # If the top has subtopologies, then place this particle into
        # a single-site subtopology -- ensures that all sites are in the
        # same level of hierarchy.
        if len(top.subtops) > 0:
            subtop = SubTopology(name=particle.name)
            top.add_subtopology(subtop)
            subtop.add_site(site)
        else:
            top.add_site(site)

    for b1, b2 in compound.bonds():
        new_bond = Bond(connection_members=[site_map[b1], site_map[b2]],
                        connection_type=None)
        top.add_connection(new_bond)
    top.update_topology()

    if box:
        top.box = from_mbuild_box(box)
    # Assumes 2-D systems are not supported in mBuild
    # if compound.periodicity is None and not box:
    else:
        if np.allclose(compound.periodicity, np.zeros(3)):
            box = from_mbuild_box(compound.boundingbox)
            if box:
                box.lengths += [0.5, 0.5, 0.5] * u.nm
            top.box = box
        else:
            top.box = Box(lengths=compound.periodicity)

    return top
Пример #10
0
def read_gro(filename):
    """Provided a filepath to a gro file, generate a topology.

    The Gromos87 (gro) format is a common plain text structure file used
    commonly with the GROMACS simulation engine.  This file contains the
    simulation box parameters, number of atoms, the residue and atom number for
    each atom, as well as their positions and velocities (velocity is
    optional).  This method will receive a filepath representation either as a
    string, or a file object and return a `topology`.

    Parameters
    ----------
    filename : str or file object
        The path to the gro file either as a string, or a file object that
        points to the gro file.

    Returns
    -------
    gmso.core.topology
        A `topology` object containing site information


    Notes
    -----
    Gro files do not specify connections between atoms, the returned topology
    will not have connections between sites either.

    Currently this implementation does not support a gro file with more than 1
    frame.

    All residues and resid information from the gro file are currently lost
    when converting to `topology`.

    """

    top = Topology()

    with open(filename, 'r') as gro_file:
        top.name = str(gro_file.readline().strip())
        n_atoms = int(gro_file.readline())
        coords = u.nm * np.zeros(shape=(n_atoms, 3))
        for row, _ in enumerate(coords):
            line = gro_file.readline()
            if not line:
                msg = (
                    'Incorrect number of lines in .gro file. Based on the '
                    'number in the second line of the file, {} rows of'
                    'atoms were expected, but at least one fewer was found.')
                raise ValueError(msg.format(n_atoms))
            resid = int(line[:5])
            res_name = line[5:10]
            atom_name = line[10:15]
            atom_id = int(line[15:20])
            coords[row] = u.nm * np.array([
                float(line[20:28]),
                float(line[28:36]),
                float(line[36:44]),
            ])
            site = Atom(name=atom_name, position=coords[row])
            top.add_site(site, update_types=False)
        top.update_topology()

        # Box information
        line = gro_file.readline().split()
        top.box = Box(u.nm * np.array([float(val) for val in line[:3]]))

        # Verify we have read the last line by ensuring the next line in blank
        line = gro_file.readline()
        if line:
            msg = ('Incorrect number of lines in input file. Based on the '
                   'number in the second line of the file, {} rows of atoms '
                   'were expected, but at least one more was found.')
            raise ValueError(msg.format(n_atoms))

    return top
Пример #11
0
def read_lammpsdata(filename, atom_style='full'):
    top = Topology()
    # The idea is to get the number of types to read in
    with open(filename, 'r') as lammps_file:
        for i, line in enumerate(lammps_file):
            if 'xlo' in line.split():
                break
    typelines = open(filename, 'r').readlines()[2:i]
    # TODO: Rewrite the logic to read in all type information
    for line in typelines:
        if 'atoms' in line:
            n_atoms = int(line.split()[0])
        elif 'bonds' in line:
            n_bonds = int(line.split()[0])
        elif 'angles' in line:
            n_angles = int(line.split()[0])
        elif 'dihedrals' in line:
            n_dihedrals = int(line.split()[0])
        elif 'impropers' in line:
            n_impropers = int(line.split()[0])
        elif 'atom' in line:
            n_atomtypes = int(line.split()[0])
        elif 'bond' in line:
            n_bondtypes = int(line.split()[0])
        elif 'angle' in line:
            n_angletypes = int(line.split()[0])
        elif 'dihedral' in line:
            n_dihedraltypes = int(line.split()[0])

    with open(filename, 'r') as lammps_file:
        top.name = str(lammps_file.readline().strip())
        lammps_file.readline()
        for j in range(
                i -
                2):  # looping through to skip through all of the type lines
            lammps_file.readline()
        x_line = lammps_file.readline().split()
        y_line = lammps_file.readline().split()
        z_line = lammps_file.readline().split()

        x = float(x_line[1]) - float(x_line[0])
        y = float(y_line[1]) - float(y_line[0])
        z = float(z_line[1]) - float(z_line[0])

        # Box Information
        lengths = u.unyt_array([x, y, z], u.angstrom)
        top.box = Box(lengths)

    coords = u.angstrom * np.zeros(shape=(n_atoms, 3))
    unique_types = _get_masses(filename, n_atomtypes)
    charge_dict, coords_dict, type_dict = _get_atoms(filename, n_atoms, coords)
    sigma_dict, epsilon_dict = _get_pairs(filename, n_atomtypes)

    for k, v in type_dict.items():
        atomtype = AtomType(name=k,
                            mass=unique_types[k],
                            charge=charge_dict[k],
                            parameters={
                                'sigma': sigma_dict[k],
                                'epsilon': epsilon_dict[k]
                            })
        for i in range(v):
            site = Site(
                name="atom{}".format(i),  # probably change
                position=coords_dict[k][i],
                atom_type=atomtype)
            top.add_site(site, update_types=False)

            print('{}:{}'.format(k, i))
    top.update_topology()

    return top
Пример #12
0
def read_lammpsdata(filename,
                    atom_style="full",
                    unit_style="real",
                    potential="lj"):
    """Read in a lammps data file as a GMSO topology.

    Parameters
    ----------
    filename : str
        LAMMPS data file
    atom_style : str, optional, default='full'
        Inferred atom style defined by LAMMPS
    potential: str, optional, default='lj'
        Potential type defined in data file

    Returns
    -------
    top : GMSO Topology
        A GMSO Topology object

    Notes
    -----
    See http://lammps.sandia.gov/doc/2001/data_format.html for a full description of the LAMMPS data format.

    This is a work in progress, as only several atom styles, potential styles, and unit styes are currently supported.

    Currently supporting the following atom styles: 'full'

    Currently supporting the following unit styles: 'real'

    Currently supporting the following potential styles: 'lj'

    Proper dihedrals can be read in but is currently not tested.

    Currently not supporting improper dihedrals.

    """
    # TODO: Add argument to ask if user wants to infer bond type
    top = Topology()

    # Validate 'atom_style'
    if atom_style not in ["full"]:
        raise ValueError(
            'Atom Style "{}" is invalid or is not currently supported'.format(
                atom_style))

    # Validate 'unit_style'
    if unit_style not in ["real"]:
        raiseValueError(
            'Unit Style "{}" is invalid or is not currently supported'.format(
                unit_style))

    # Parse box information
    _get_box_coordinates(filename, unit_style, top)
    # Parse atom type information
    top, type_list = _get_ff_information(filename, unit_style, top)
    # Parse atom information
    _get_atoms(filename, top, unit_style, type_list)
    # Parse connection (bonds, angles, dihedrals) information
    # TODO: Add more atom styles
    if atom_style in ["full"]:
        _get_connection(filename, top, unit_style, connection_type="bond")
        _get_connection(filename, top, unit_style, connection_type="angle")

    top.update_topology()

    return top