def test_scaling_unit_vectors(self): box = Box(lengths=u.unyt_array((2, 2, 2), u.nm), angles=u.degree*[40.0, 50.0, 60.0]) u_vectors = box.get_unit_vectors() scaled_u_vectors = (u_vectors.T * box.lengths).T scaled_vectors = box.get_vectors() assert_allclose_units(scaled_vectors, scaled_u_vectors, rtol=1e-5, atol=u.nm*1e-3) assert scaled_u_vectors.units == u.nm
def test_scaled_vectors(self): box = Box(lengths=u.unyt_array((2, 2, 2), u.nm), angles=u.degree*[40.0, 50.0, 60.0]) vectors = box.get_vectors() test_vectors = np.array([[1, 0, 0], [0.5, 0.86603, 0], [0.64278, 0.51344, 0.56852]]) test_vectors = (test_vectors.T * box.lengths).T assert_allclose_units(vectors, test_vectors, rtol=1e-5, atol=u.nm*1e-3) assert vectors.units == u.nm
def _get_box_coordinates(filename, unit_style, topology): """Function to parse box information """ with open(filename, 'r') as lammps_file: for line in lammps_file: if 'xlo' in line.split(): break x_line = line.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]) # Check if box is triclinic tilts = lammps_file.readline().split() if 'xy' in tilts: xy = float(tilts[0]) xz = float(tilts[1]) yz = float(tilts[2]) xhi = float(x_line[1]) - np.max([0.0, xy, xz, xy + xz]) xlo = float(x_line[0]) - np.min([0.0, xy, xz, xy + xz]) yhi = float(y_line[1]) - np.max([0.0, yz]) ylo = float(y_line[0]) - np.min([0.0, yz]) zhi = float(z_line[1]) zlo = float(z_line[0]) lx = xhi - xlo ly = yhi - ylo lz = zhi - zlo c = np.sqrt(lz**2 + xz**2 + yz**2) b = np.sqrt(ly**2 + xy**2) a = lx alpha = np.arccos((yz * ly + xy * xz) / (b * c)) beta = np.arccos(xz / c) gamma = np.arccos(xy / b) # Box Information lengths = u.unyt_array([a, b, c], get_units(unit_style)['distance']) angles = u.unyt_array([alpha, beta, gamma], u.radian) angles.to(get_units(unit_style)['angle']) topology.box = Box(lengths, angles) else: # Box Information lengths = u.unyt_array([x, y, z], get_units(unit_style)['distance']) topology.box = Box(lengths) return topology
def test_position_units(self, typed_ar_system): typed_ar_system.box = Box(lengths=[1,1,1]) n_topology_sites = len(typed_ar_system.sites) omm_top = to_openmm(typed_ar_system, openmm_object='modeller') assert isinstance(omm_top.positions.unit, type(simtk_unit.nanometer))
def from_mbuild_box(mb_box): """Convert an mBuild box to a GMSO box Assumes that the mBuild box dimensions are in nanometers Parameters ---------- mb_box : mbuild.Box mBuild box object to be converted to a gmso.core.Box object Returns: -------- box : gmso.core.Box """ # TODO: Unit tests if not isinstance(mb_box, mb.Box): raise ValueError('Argument mb_box is not an mBuild Box') if np.allclose(mb_box.lengths, [0, 0, 0]): warn('No box or boundingbox information detected, setting box to None') return None box = Box( lengths=np.asarray(mb_box.lengths) * u.nm, angles=np.asarray(mb_box.angles) * u.degree, ) return box
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_read_lammps_triclinic(self, typed_ar_system): typed_ar_system.box = Box(lengths=[1,1,1], angles=[60,90,120]) write_lammpsdata(typed_ar_system, filename='data.triclinic') read = read_lammpsdata('data.triclinic') assert u.array.allclose_units(read.box.lengths, u.unyt_array([1,1,1], u.nm)) assert u.array.allclose_units(read.box.angles, u.unyt_array([60, 90, 120], u.degree))
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 test_read_lammps_triclinic(self, typed_ar_system): typed_ar_system.box = Box(lengths=[1, 1, 1], angles=[60, 90, 120]) write_lammpsdata(typed_ar_system, filename="data.triclinic") read = read_lammpsdata("data.triclinic") assert_allclose_units( read.box.lengths, u.unyt_array([1, 1, 1], u.nm), rtol=1e-5, atol=1e-8, ) assert_allclose_units( read.box.angles, u.unyt_array([60, 90, 120], u.degree), rtol=1e-5, atol=1e-8, )
def test_init_lengths(self, lengths): box = Box(lengths=lengths) assert np.array_equal(box.lengths, lengths)
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 box(self): return Box(lengths=u.nm * np.ones(3))
def test_init_angles(self, lengths, angles): box = Box(lengths=lengths, angles=angles) assert np.array_equal(box.angles, angles)
def test_write_lammps_triclinic(self, topology_site): top = topology_site() top.box = Box(lengths=[1,1,1], angles=[60,90,120]) write_lammpsdata(top, filename='data.triclinic')
def test_build_2D_Box(self): with pytest.warns(UserWarning): Box(lengths=u.nm * [4, 4, 0])
def test_bad_lengths(self, lengths, angles): lengths *= u.nm with pytest.raises(ValueError): Box(lengths=lengths, angles=angles)
def test_write_lammps_triclinic(self, typed_ar_system): typed_ar_system.box = Box(lengths=[1,1,1], angles=[60,90,120]) write_lammpsdata(typed_ar_system, filename='data.triclinic')
def test_read_sites(self, filename=get_path('data.lammps')): read = read_lammpsdata(filename) assert read.box == Box(lengths=[1, 1, 1])
def test_angles_setter(self, lengths, angles): box = Box(lengths=lengths, angles=u.degree*np.ones(3)) angles *= u.degree box.angles = angles assert (box.angles == angles).all()
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
def test_setters_with_lists(self, lengths): box = Box(lengths=u.nm*np.ones(3)) lengths *= u.nm box.lengths = lengths assert (box.lengths == lengths).all()
def test_list_to_unyt_array(self): length = 5 * u.nm box = Box([length, length, length]) assert isinstance(box.lengths, u.unyt_array)
def test_unit_vectors(self): box = Box(lengths=u.nm*np.ones(3), angles=u.degree*[40.0, 50.0, 60.0]) vectors = box.get_unit_vectors() assert vectors.units.is_dimensionless