def test_add_box(self): top = Topology() box = Box(2 * u.nm * np.ones(3)) assert top.box is None top.box = box assert top.box is not None assert allclose(top.box.lengths, u.nm * 2 * np.ones(3))
def test_add_box(self): top = Topology() box = Box(2 * u.nm * np.ones(3)) assert top.box is None top.box = box assert top.box is not None assert_allclose_units( top.box.lengths, u.nm * 2 * np.ones(3), rtol=1e-5, atol=1e-8 )
def _topology(sites=1): top = Topology() top.box = Box(lengths=[1, 1, 1]) H = Hydrogen site1 = Site( name='site1', element=H, atom_type=AtomType(name="at1", mass=H.mass), ) for i in range(sites): top.add_site(site1) return top
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
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
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