class TestCustomReaders(object): """ Can pass a reader as kwarg on Universe creation """ @dec.skipif(parser_not_found('TRZ'), 'TRZ parser not available. Are you using python 3?') def test_custom_reader(self): # check that reader passing works u = mda.Universe(TRZ_psf, TRZ, format=MDAnalysis.coordinates.TRZ.TRZReader) assert_equal(len(u.atoms), 8184) def test_custom_reader_singleframe(self): T = MDAnalysis.topology.GROParser.GROParser R = MDAnalysis.coordinates.GRO.GROReader u = mda.Universe(two_water_gro, two_water_gro, topology_format=T, format=R) assert_equal(len(u.atoms), 6) def test_custom_reader_singleframe_2(self): # Same as before, but only one argument to Universe T = MDAnalysis.topology.GROParser.GROParser R = MDAnalysis.coordinates.GRO.GROReader u = mda.Universe(two_water_gro, topology_format=T, format=R) assert_equal(len(u.atoms), 6) @dec.skipif(parser_not_found('TRZ'), 'TRZ parser not available. Are you using python 3?') def test_custom_parser(self): # topology reader passing works u = mda.Universe( TRZ_psf, TRZ, topology_format=MDAnalysis.topology.PSFParser.PSFParser) assert_equal(len(u.atoms), 8184) @dec.skipif(parser_not_found('TRZ'), 'TRZ parser not available. Are you using python 3?') def test_custom_both(self): # use custom for both u = mda.Universe( TRZ_psf, TRZ, format=MDAnalysis.coordinates.TRZ.TRZReader, topology_format=MDAnalysis.topology.PSFParser.PSFParser) assert_equal(len(u.atoms), 8184)
class TestSelectionErrors(object): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.u = mda.Universe(PSF, DCD) def tearDown(self): del self.u def selection_fail(self, selstr): assert_raises(SelectionError, self.u.select_atoms, selstr) def test_expected_errors(self): for selstr in [ 'name and H', # string selection 'name )', 'resid abcd', # range selection 'resid 1-', 'prop chicken == tasty', 'prop chicken <= 7.4', 'prop mass ^^ 12.0', 'same this as resid 1', # same selection 'same resid resname mass 5.0', # same / expect 'name H and', # check all tokens used 'naem H', # unkonwn (misplet) opertaor 'resid and name C', # rangesel not finding vals 'resnum ', 'bynum or protein', 'prop mass < 4.0 hello', # unused token 'prop mass > 10. and group this', # missing group 'prop mass > 10. and fullgroup this', # missing fullgroup ]: yield self.selection_fail, selstr
class _SelectionWriter(TestCase): filename = None max_number = 357 # to keep fixtures smallish, only select CAs up to number 357 @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.universe = MDAnalysis.Universe(PSF, DCD) stream = StringIO() self.namedfile = NamedStream(stream, self.filename) def tearDown(self): del self.universe del self.namedfile def _selection(self): return self.universe.select_atoms( "protein and name CA and bynum 1-{0}".format(self.max_number)) def _write(self, **kwargs): g = self._selection() g.write(self.namedfile, **kwargs) return g def _write_selection(self, **kwargs): g = self._selection() g.write_selection(self.namedfile, **kwargs) return g
class TestAtomGroupTimestep(object): """Tests the AtomGroup.ts attribute (partial timestep)""" @dec.skipif(parser_not_found('TRZ'), 'TRZ parser not available. Are you using python 3?') def setUp(self): self.universe = mda.Universe(TRZ_psf, TRZ) self.prec = 6 def tearDown(self): del self.universe del self.prec def test_partial_timestep(self): ag = self.universe.select_atoms('name Ca') idx = ag.indices assert_equal(len(ag.ts._pos), len(ag)) for ts in self.universe.trajectory[0:20:5]: assert_array_almost_equal( ts.positions[idx], ag.ts.positions, self.prec, err_msg="Partial timestep coordinates wrong") assert_array_almost_equal( ts.velocities[idx], ag.ts.velocities, self.prec, err_msg="Partial timestep coordinates wrong")
class TestOrthogonalDistanceSelections(BaseDistanceSelection): @dec.skipif(parser_not_found('TRZ'), 'TRZ parser not available. Are you using python 3?') def setUp(self): self.u = mda.Universe(TRZ_psf, TRZ) def tearDown(self): del self.u def _check_cyzone(self, meth, periodic): sel = Parser.parse('cyzone 5 4 -4 resid 2', self.u.atoms) sel.periodic = periodic result = sel.apply(self.u.atoms) other = self.u.select_atoms('resid 2') pos = other.center_of_geometry() vecs = self.u.atoms.positions - pos if periodic: box = self.u.dimensions[:3] vecs -= box * np.rint(vecs / box) mask = (vecs[:, 2] > -4) & (vecs[:, 2] < 4) radii = vecs[:, 0]**2 + vecs[:, 1]**2 mask &= radii < 5**2 ref = set(self.u.atoms[mask].indices) assert_(ref == set(result.indices)) def test_cyzone(self): for meth, periodic in self.methods[1:]: yield self._check_cyzone, meth, periodic
class TestLAMMPSDCD(BaseTimestepInterfaceTest): @dec.skipif(parser_not_found('LAMMPS'), 'LAMMPS parser not available. Are you using python 3?') def setUp(self): u = self.u = mda.Universe(LAMMPSdata2, LAMMPSdcd2, format='LAMMPS', topology_format='DATA', timeunit='fs') self.ts = u.trajectory.ts
class _TestSelfDistanceArrayDCD(TestCase): backend = None @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.universe = MDAnalysis.Universe(PSF, DCD) self.trajectory = self.universe.trajectory self.ca = self.universe.select_atoms('name CA') # see comments above on precision self.prec = 5 def tearDown(self): del self.universe del self.trajectory del self.ca def test_simple(self): U = self.universe self.trajectory.rewind() x0 = U.atoms.coordinates(copy=True) d = MDAnalysis.lib.distances.self_distance_array(x0, backend=self.backend) N = 3341 * (3341 - 1) / 2 assert_equal(d.shape, (N,), "wrong shape (should be (Natoms*(Natoms-1)/2,))") assert_almost_equal(d.min(), 0.92905562402529318, self.prec, err_msg="wrong minimum distance value") assert_almost_equal(d.max(), 52.4702570624190590, self.prec, err_msg="wrong maximum distance value") def test_outarray(self): U = self.universe self.trajectory.rewind() x0 = U.atoms.coordinates(copy=True) natoms = len(U.atoms) N = natoms * (natoms - 1) / 2 d = np.zeros((N,), np.float64) MDAnalysis.lib.distances.self_distance_array(x0, result=d, backend=self.backend) assert_equal(d.shape, (N,), "wrong shape (should be (Natoms*(Natoms-1)/2,))") assert_almost_equal(d.min(), 0.92905562402529318, self.prec, err_msg="wrong minimum distance value") assert_almost_equal(d.max(), 52.4702570624190590, self.prec, err_msg="wrong maximum distance value") def test_periodic(self): # boring with the current dcd as that has no PBC U = self.universe self.trajectory.rewind() x0 = U.atoms.coordinates(copy=True) natoms = len(U.atoms) N = natoms * (natoms - 1) / 2 d = MDAnalysis.lib.distances.self_distance_array(x0, box=U.coord.dimensions, backend=self.backend) assert_equal(d.shape, (N,), "wrong shape (should be (Natoms*(Natoms-1)/2,))") assert_almost_equal(d.min(), 0.92905562402529318, self.prec, err_msg="wrong minimum distance value with PBC") assert_almost_equal(d.max(), 52.4702570624190590, self.prec, err_msg="wrong maximum distance value with PBC")
class TestWaterdynamics(TestCase): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.universe = MDAnalysis.Universe(waterPSF, waterDCD) self.selection1 = "byres name OH2" self.selection2 = self.selection1 self.selection3 = "byres name P1" def test_HydrogenBondLifetimes(self): hbl = MDAnalysis.analysis.waterdynamics.HydrogenBondLifetimes( self.universe, self.selection1, self.selection2, 0, 5, 3) hbl.run(verbose=False) assert_equal(round(hbl.timeseries[2][1], 5), 0.75) def test_WaterOrientationalRelaxation(self): wor = MDAnalysis.analysis.waterdynamics.WaterOrientationalRelaxation( self.universe, self.selection1, 0, 5, 2) wor.run(verbose=False) assert_equal(round(wor.timeseries[1][2], 5), 0.35887) def test_WaterOrientationalRelaxation_zeroMolecules(self): wor_zero = MDAnalysis.analysis.waterdynamics.WaterOrientationalRelaxation( self.universe, self.selection3, 0, 5, 2) wor_zero.run(verbose=False) assert_equal(wor_zero.timeseries[1], (0.0, 0.0, 0.0)) def test_AngularDistribution(self): ad = MDAnalysis.analysis.waterdynamics.AngularDistribution( self.universe, self.selection1, 40) ad.run(verbose=False) assert_equal(str(ad.graph[0][39]), str("0.951172947884 0.48313682125")) def test_MeanSquareDisplacement(self): msd = MDAnalysis.analysis.waterdynamics.MeanSquareDisplacement( self.universe, self.selection1, 0, 10, 2) msd.run(verbose=False) assert_equal(round(msd.timeseries[1], 5), 0.03984) def test_MeanSquareDisplacement_zeroMolecules(self): msd_zero = MDAnalysis.analysis.waterdynamics.MeanSquareDisplacement( self.universe, self.selection3, 0, 10, 2) msd_zero.run(verbose=False) assert_equal(msd_zero.timeseries[1], 0.0) def test_SurvivalProbability(self): sp = MDAnalysis.analysis.waterdynamics.SurvivalProbability( self.universe, self.selection1, 0, 6, 3) sp.run(verbose=False) assert_equal(round(sp.timeseries[1], 5), 1.0) def test_SurvivalProbability_zeroMolecules(self): sp_zero = MDAnalysis.analysis.waterdynamics.SurvivalProbability( self.universe, self.selection3, 0, 6, 3) sp_zero.run(verbose=False) assert_equal(sp_zero.timeseries[1], 0.0)
class _Test_apply_PBC(TestCase): backend = None def setUp(self): self.prec = 6 def tearDown(self): del self.prec @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def test_ortho_PBC(self): from MDAnalysis.lib.distances import apply_PBC U = MDAnalysis.Universe(PSF, DCD) atoms = U.atoms.coordinates() box1 = np.array([2.5, 2.5, 3.5], dtype=np.float32) box2 = np.array([2.5, 2.5, 3.5, 90., 90., 90.], dtype=np.float32) cyth1 = apply_PBC(atoms, box1, backend=self.backend) cyth2 = apply_PBC(atoms, box2, backend=self.backend) reference = atoms - np.floor(atoms / box1) * box1 assert_almost_equal(cyth1, reference, self.prec, err_msg="Ortho apply_PBC #1 failed comparison with np") assert_almost_equal(cyth2, reference, self.prec, err_msg="Ortho apply_PBC #2 failed comparison with np") def test_tric_PBC(self): from MDAnalysis.lib.distances import apply_PBC U = MDAnalysis.Universe(TRIC) atoms = U.atoms.coordinates() box1 = U.dimensions box2 = MDAnalysis.coordinates.core.triclinic_vectors(box1) #print box2 #print box2.shape def numpy_PBC(coords, box): coords -= np.array([box[2] * val for val in np.floor(coords[:, 2] / box[2][2])]) coords -= np.array([box[1] * val for val in np.floor(coords[:, 1] / box[1][1])]) coords -= np.array([box[0] * val for val in np.floor(coords[:, 0] / box[0][0])]) return coords cyth1 = apply_PBC(atoms, box1, backend=self.backend) cyth2 = apply_PBC(atoms, box2, backend=self.backend) reference = numpy_PBC(atoms, box2) assert_almost_equal(cyth1, reference, self.prec, err_msg="Triclinic apply_PBC failed comparison with np") assert_almost_equal(cyth2, reference, self.prec, err_msg="Trlclinic apply_PBC failed comparison with np")
class TestSegmentGroup(object): # Legacy tests from before 363 @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): """Set up the standard AdK system in implicit solvent.""" self.universe = mda.Universe(PSF, DCD) self.g = self.universe.atoms.segments def test_newSegmentGroup(self): """test that slicing a SegmentGroup returns a new SegmentGroup (Issue 135)""" g = self.universe.atoms.segments newg = g[:] assert_(isinstance(newg, mda.core.groups.SegmentGroup)) assert_equal(len(newg), len(g)) def test_n_atoms(self): assert_equal(self.g.n_atoms, 3341) def test_n_residues(self): assert_equal(self.g.n_residues, 214) def test_resids_dim(self): assert_equal(len(self.g.resids), len(self.g)) for seg, resids in zip(self.g, self.g.resids): assert_(len(resids) == len(seg.residues)) assert_equal(seg.residues.resids, resids) def test_resnums_dim(self): assert_equal(len(self.g.resnums), len(self.g)) for seg, resnums in zip(self.g, self.g.resnums): assert_(len(resnums) == len(seg.residues)) assert_equal(seg.residues.resnums, resnums) def test_segids_dim(self): assert_equal(len(self.g.segids), len(self.g)) def test_set_segids(self): s = self.universe.select_atoms('all').segments s.segids = 'ADK' assert_equal(self.universe.segments.segids, ['ADK'], err_msg="failed to set_segid on segments") def test_set_segid_updates_self(self): g = self.universe.select_atoms("resid 10:18").segments g.segids = 'ADK' assert_equal( g.segids, ['ADK'], err_msg="old selection was not changed in place after set_segid") def test_atom_order(self): assert_equal(self.universe.segments.atoms.indices, sorted(self.universe.segments.atoms.indices))
class TestMergeTopology(object): """Test that Merge correct does topology""" @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.u = MDAnalysis.Universe(PSF, DCD) self.u2 = MDAnalysis.Universe(merge_protein) def tearDown(self): del self.u del self.u2 def test_merge_with_topology(self): ag1 = self.u.atoms[:20] ag2 = self.u.atoms[100:110] u2 = MDAnalysis.Merge(ag1, ag2) assert_(len(u2.atoms) == 30) assert_(len(u2.atoms.bonds) == 28) assert_(len(u2.atoms.angles) == 47) assert_(len(u2.atoms.dihedrals) == 53) assert_(len(u2.atoms.impropers) == 1) # All these bonds are in the merged Universe assert_(len(ag1[0].bonds) == len(u2.atoms[0].bonds)) # One of these bonds isn't in the merged Universe assert_(len(ag2[0].bonds) -1 == len(u2.atoms[20].bonds)) def test_merge_with_topology_from_different_universes(self): u3 = MDAnalysis.Merge(self.u.atoms[:110], self.u2.atoms) # merge_protein doesn't contain bond topology, so merged universe # shouldn't have one either print(u3.atoms.bonds) # PDB reader yields empty Bonds group, which means bonds from # PSF/DCD survive the merge #assert_(not hasattr(u3.atoms, 'bonds') or len(u3.atoms.bonds) == 0) assert_(not hasattr(u3.atoms, 'angles') or len(u3.atoms.bonds) == 0) assert_(not hasattr(u3.atoms, 'dihedrals') or len(u3.atoms.bonds) == 0) assert_(not hasattr(u3.atoms, 'impropers') or len(u3.atoms.bonds) == 0) def test_merge_without_topology(self): # This shouldn't have topology as we merged single atoms u2 = MDAnalysis.Merge(self.u.atoms[0:1], self.u.atoms[10:11]) assert_(len(u2.atoms) == 2) assert_(len(u2.atoms.bonds) == 0) assert_(len(u2.atoms.angles) == 0) assert_(len(u2.atoms.dihedrals) == 0) assert_(len(u2.atoms.impropers) == 0)
class _SelectionWriter(TestCase): filename = None max_number = 357 # to keep fixtures smallish, only select CAs up to number 357 @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.universe = MDAnalysis.Universe(PSF, DCD) stream = StringIO() self.namedfile = NamedStream(stream, self.filename) def tearDown(self): del self.universe del self.namedfile def _selection(self): return self.universe.select_atoms( "protein and name CA and bynum 1-{0}".format(self.max_number)) def _write(self, **kwargs): g = self._selection() g.write(self.namedfile, **kwargs) return g def _write_selection(self, **kwargs): g = self._selection() g.write(self.namedfile, **kwargs) return g def _write_with(self, **kwargs): g = self._selection() with self.writer(self.namedfile, **kwargs) as outfile: outfile.write(g) return g def test_write_bad_mode(self): with self.assertRaises(ValueError): self._write(name=self.ref_name, mode='a+') def test_write(self): self._write(name=self.ref_name) self._assert_selectionstring() def test_writeselection(self): self._write_selection(name=self.ref_name) self._assert_selectionstring() def test_write_with(self): self._write_with(name=self.ref_name) self._assert_selectionstring()
class TestAnalysisBase(object): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): # has 98 frames self.u = mda.Universe(PSF, DCD) def tearDown(self): del self.u def test_default(self): an = FrameAnalysis(self.u.trajectory).run() assert_equal(an.n_frames, len(self.u.trajectory)) assert_equal(an.frames, list(range(len(self.u.trajectory)))) def test_start(self): an = FrameAnalysis(self.u.trajectory, start=20).run() assert_equal(an.n_frames, len(self.u.trajectory) - 20) assert_equal(an.frames, list(range(20, len(self.u.trajectory)))) def test_stop(self): an = FrameAnalysis(self.u.trajectory, stop=20).run() assert_equal(an.n_frames, 20) assert_equal(an.frames, list(range(20))) def test_step(self): an = FrameAnalysis(self.u.trajectory, step=20).run() assert_equal(an.n_frames, 5) assert_equal(an.frames, list(range(98))[::20]) def test_verbose(self): a = FrameAnalysis(self.u.trajectory, verbose=True) assert_(a._verbose) assert_(not a._quiet) @raises(NotImplementedError) def test_incomplete_defined_analysis(self): IncompleteAnalysis(self.u.trajectory).run() def test_old_api(self): OldAPIAnalysis(self.u.trajectory).run() def test_start_stop_step_conversion(self): an = FrameAnalysis(self.u.trajectory) assert_equal(an.start, 0) assert_equal(an.stop, self.u.trajectory.n_frames) assert_equal(an.step, 1)
class TestPSAnalysis(TestCase): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.tmpdir = tempdir.TempDir() self.iu1 = np.triu_indices(3, k=1) self.universe1 = MDAnalysis.Universe(PSF, DCD) self.universe2 = MDAnalysis.Universe(PSF, DCD2) self.universe_rev = MDAnalysis.Universe(PSF, DCD) self.universes = [self.universe1, self.universe2, self.universe_rev] self.psa = MDAnalysis.analysis.psa.PSAnalysis(self.universes, \ path_select='name CA', \ targetdir=self.tmpdir.name) self.psa.generate_paths(align=True) self.psa.paths[-1] = self.psa.paths[-1][:: -1, :, :] # reverse third path self._run() def _run(self): self.psa.run(metric='hausdorff') self.hausd_matrix = self.psa.get_pairwise_distances() self.psa.run(metric='discrete_frechet') self.frech_matrix = self.psa.get_pairwise_distances() self.hausd_dists = self.hausd_matrix[self.iu1] self.frech_dists = self.frech_matrix[self.iu1] def tearDown(self): del self.universe1 del self.universe2 del self.universe_rev del self.psa del self.tmpdir def test_hausdorff_bound(self): err_msg = "Some Frechet distances are smaller than corresponding " \ + "Hausdorff distances" assert_array_less(self.hausd_dists, self.frech_dists, err_msg) def test_reversal_hausdorff(self): err_msg = "Hausdorff distances changed after path reversal" assert_array_almost_equal(self.hausd_matrix[1,2], \ self.hausd_matrix[0,1], \ decimal=3, err_msg=err_msg) def test_reversal_frechet(self): err_msg = "Frechet distances did not increase after path reversal" assert_(self.frech_matrix[1, 2] >= self.frech_matrix[0, 1], err_msg)
class MemoryReference(BaseReference): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def __init__(self): super(MemoryReference, self).__init__() self.topology = PSF self.trajectory = DCD self.universe = mda.Universe(PSF, DCD) self.n_atoms = self.universe.trajectory.n_atoms self.n_frames = self.universe.trajectory.n_frames self.dt = self.universe.trajectory.ts.dt self.dimensions = self.universe.trajectory.ts.dimensions self.totaltime = self.universe.trajectory.totaltime self.volume = self.universe.trajectory.ts.volume self.first_frame = Timestep(self.n_atoms) self.first_frame.positions = np.array(self.universe.trajectory[0]) self.first_frame.frame = 0 self.first_frame.time = self.first_frame.frame * self.dt self.second_frame = Timestep(self.n_atoms) self.second_frame.positions = np.array(self.universe.trajectory[1]) self.second_frame.frame = 1 self.second_frame.time = self.second_frame.frame * self.dt self.last_frame = Timestep(self.n_atoms) self.last_frame.positions = \ np.array(self.universe.trajectory[self.n_frames - 1]) self.last_frame.frame = self.n_frames - 1 self.last_frame.time = self.last_frame.frame * self.dt self.jump_to_frame = self.first_frame.copy() self.jump_to_frame.positions = np.array(self.universe.trajectory[3]) self.jump_to_frame.frame = 3 self.jump_to_frame.time = self.jump_to_frame.frame * self.dt def reader(self, trajectory): return mda.Universe(self.topology, trajectory, in_memory=True).trajectory def iter_ts(self, i): ts = self.universe.trajectory[i] return ts
class TestContactAnalysis1(TestCase): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.universe = MDAnalysis.Universe(PSF, DCD) self.trajectory = self.universe.trajectory def tearDown(self): del self.universe del self.trajectory def _run_ContactAnalysis1(self, **runkwargs): sel_basic = "(resname ARG or resname LYS) and (name NH* or name NZ)" sel_acidic = "(resname ASP or resname GLU) and (name OE* or name OD*)" acidic = self.universe.select_atoms(sel_acidic) basic = self.universe.select_atoms(sel_basic) outfile = 'qsalt.dat' CA1 = MDAnalysis.analysis.contacts.ContactAnalysis1( self.universe, selection=(sel_acidic, sel_basic), refgroup=(acidic, basic), radius=6.0, outfile=outfile) kwargs = runkwargs.copy() kwargs['force'] = True CA1.run(**kwargs) return CA1 def test_startframe(self): """test_startframe: TestContactAnalysis1: start frame set to 0 (resolution of Issue #624)""" with tempdir.in_tempdir(): CA1 = self._run_ContactAnalysis1() self.assertEqual(CA1.timeseries.shape[1], self.universe.trajectory.n_frames) def test_end_zero(self): """test_end_zero: TestContactAnalysis1: stop frame 0 is not ignored""" with tempdir.in_tempdir(): CA1 = self._run_ContactAnalysis1(stop=0) self.assertEqual(len(CA1.timeseries), 0) def test_slicing(self): start, stop, step = 10, 30, 5 with tempdir.in_tempdir(): CA1 = self._run_ContactAnalysis1(start=start, stop=stop, step=step) frames = np.arange(self.universe.trajectory.n_frames)[start:stop:step] self.assertEqual(CA1.timeseries.shape[1], len(frames))
class TestBondedSelection(object): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.u = mda.Universe(PSF, DCD) def tearDown(self): del self.u def test_bonded_1(self): ag = self.u.select_atoms('type 2 and bonded name N') assert_(len(ag) == 3) def test_nobonds_warns(self): self.u.bonds = TopologyGroup([]) assert_warns(UserWarning, self.u.select_atoms, 'type 2 and bonded name N')
class TestChainReaderFormats(TestCase): """Test of ChainReader with explicit formats (Issue 76).""" @attr('issue') def test_set_all_format_tuples(self): universe = mda.Universe(GRO, [(PDB, 'pdb'), (XTC, 'xtc'), (TRR, 'trr')]) assert_equal(universe.trajectory.n_frames, 21) @attr('issue') @dec.skipif(parser_not_found('DCD'), 'DCD parset not available. Are you using python 3?') def test_set_one_format_tuple(self): universe = mda.Universe(PSF, [(PDB_small, 'pdb'), DCD]) assert_equal(universe.trajectory.n_frames, 99) @attr('issue') def test_set_all_formats(self): universe = mda.Universe(PSF, [PDB_small, PDB_closed], format='pdb') assert_equal(universe.trajectory.n_frames, 2)
class TestChainReaderCommonDt(TestCase): @dec.skipif(parser_not_found('DCD'), 'DCD parset not available. Are you using python 3?') def setUp(self): self.common_dt = 100.0 self.universe = mda.Universe(PSF, [DCD, CRD, DCD, CRD, DCD, CRD, CRD], dt=self.common_dt) self.trajectory = self.universe.trajectory self.prec = 3 def test_time(self): # We test this for the beginning, middle and end of the trajectory. for frame_n in (0, self.trajectory.n_frames // 2, -1): self.trajectory[frame_n] assert_almost_equal(self.trajectory.time, self.trajectory.frame*self.common_dt, 5, err_msg="Wrong time for frame {0:d}".format(frame_n) )
class TestBaseTimestep(BaseTimestepTest): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def test_other_timestep(self): # use a subclass to base.Timestep to check it works ts1 = mda.coordinates.base.Timestep(10) ts1.positions = self._get_pos() # can't do TRR Timestep here as it always has vels and forces # so isn't actually equal to a position only timestep for otherTS in [mda.coordinates.DCD.Timestep, mda.coordinates.TRJ.Timestep, mda.coordinates.DMS.Timestep, mda.coordinates.GRO.Timestep, mda.coordinates.TRZ.Timestep, ]: ts2 = otherTS(10) ts2.positions = self._get_pos() yield (self._check_ts_equal, ts1, ts2, "Failed on {0}".format(otherTS))
class TestResidue(object): # Legacy tests from before 363 @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.universe = mda.Universe(PSF, DCD) self.res = self.universe.residues[100] def test_type(self): assert_(isinstance(self.res, mda.core.groups.Residue)) assert_equal(self.res.resname, "ILE") assert_equal(self.res.resid, 101) def test_index(self): atom = self.res.atoms[2] assert_(isinstance(atom, mda.core.groups.Atom)) assert_equal(atom.name, "CA") assert_equal(atom.index, 1522) assert_equal(atom.resid, 101) def test_atom_order(self): assert_equal(self.res.atoms.indices, sorted(self.res.atoms.indices))
class TestMergeTopology(object): """Test that Merge correct does topology""" @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.u = MDAnalysis.Universe(PSF, DCD) def tearDown(self): del self.u def test_merge_with_topology(self): ag1 = self.u.atoms[:20] ag2 = self.u.atoms[100:110] u2 = MDAnalysis.Merge(ag1, ag2) assert_(len(u2.atoms) == 30) assert_(len(u2.bonds) == 28) assert_(len(u2.angles) == 47) assert_(len(u2.dihedrals) == 53) assert_(len(u2.impropers) == 1) # All these bonds are in the merged Universe assert_(len(ag1[0].bonds) == len(u2.atoms[0].bonds)) # One of these bonds isn't in the merged Universe assert_(len(ag2[0].bonds) -1 == len(u2.atoms[20].bonds)) def test_merge_without_topology(self): # This shouldn't have topology as we merged single atoms ag1 = AtomGroup([self.u.atoms[1]]) ag2 = AtomGroup([self.u.atoms[10]]) u2 = MDAnalysis.Merge(ag1, ag2) assert_(len(u2.atoms) == 2) assert_(len(u2.bonds) == 0) assert_(len(u2.angles) == 0) assert_(len(u2.dihedrals) == 0) assert_(len(u2.impropers) == 0)
class TestBondedSelection(object): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.u = mda.Universe(PSF, DCD) def tearDown(self): del self.u def test_bonded_1(self): ag = self.u.select_atoms('type 2 and bonded name N') assert_(len(ag) == 3) @staticmethod def test_nobonds_warns(): u = make_Universe(('names', )) # empty bond topology attr batt = mda.core.topologyattrs.Bonds([]) u.add_TopologyAttr(batt) assert_warns(UserWarning, u.select_atoms, 'bonded name AAA')
class TestAnalysisBase(object): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): # has 98 frames self.u = mda.Universe(PSF, DCD) def tearDown(self): del self.u def test_default(self): an = FrameAnalysis(self.u.trajectory) assert_(an.nframes == len(self.u.trajectory)) an.run() assert_(an.frames == list(range(len(self.u.trajectory)))) def test_start(self): an = FrameAnalysis(self.u.trajectory, start=20) assert_(an.nframes == len(self.u.trajectory) - 20) an.run() assert_(an.frames == list(range(20, len(self.u.trajectory)))) def test_stop(self): an = FrameAnalysis(self.u.trajectory, stop=20) assert_(an.nframes == 20) an.run() assert_(an.frames == list(range(20))) def test_step(self): an = FrameAnalysis(self.u.trajectory, step=20) assert_(an.nframes == 5) an.run() assert_(an.frames == list(range(98))[::20])
class TestWrap(object): @dec.skipif(parser_not_found('TRZ'), 'TRZ parser not available. Are you using python 3?') def setUp(self): self.u = mda.Universe(TRZ_psf, TRZ) self.ag = self.u.atoms[:100] def tearDown(self): del self.u del self.ag def test_wrap_comp_fail(self): assert_raises(ValueError, self.ag.wrap, compound='strawberries') def test_wrap_cent_fail(self): assert_raises(ValueError, self.ag.wrap, compound='residues', center='avacado') def test_wrap_box_fail(self): assert_raises(ValueError, self.ag.wrap, box=np.array([0, 1])) def _in_box(self, coords): """Check that a set of coordinates are 0.0 <= r <= box""" box = self.u.dimensions[:3] return (coords >= 0.0).all() and (coords <= box).all() def test_wrap_atoms(self): ag = self.u.atoms[100:200] ag.wrap(compound='atoms') assert_equal(self._in_box(ag.positions), True) def test_wrap_group(self): ag = self.u.atoms[:100] ag.wrap(compound='group') cen = ag.center_of_mass() assert_equal(self._in_box(cen), True) def test_wrap_residues(self): ag = self.u.atoms[300:400] ag.wrap(compound='residues') cen = np.vstack([r.atoms.center_of_mass() for r in ag.residues]) assert_equal(self._in_box(cen), True) def test_wrap_segments(self): ag = self.u.atoms[1000:1200] ag.wrap(compound='segments') cen = np.vstack([s.atoms.center_of_mass() for s in ag.segments]) assert_equal(self._in_box(cen), True) def test_wrap_fragments(self): ag = self.u.atoms[:250] ag.wrap(compound='fragments') cen = np.vstack([f.center_of_mass() for f in ag.fragments]) assert_equal(self._in_box(cen), True)
def test_contact_matrix(): d = np.arange(5) radius = np.ones(5) * 2.5 out = contacts.contact_matrix(d, radius) assert_array_equal(out, [True, True, True, False, False]) # check in-place update out = np.empty(out.shape) contacts.contact_matrix(d, radius, out=out) assert_array_equal(out, [True, True, True, False, False]) @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def test_new_selection(): u = mda.Universe(PSF, DCD) selections = ('all', ) sel = contacts._new_selections(u, selections, -1)[0] u.trajectory[-1] assert_array_equal(sel.positions, u.atoms.positions) def soft_cut(ref, u, selA, selB, radius=4.5, beta=5.0, lambda_constant=1.8): """ Reference implementation for testing """ # reference groups A and B from selection strings refA, refB = ref.select_atoms(selA), ref.select_atoms(selB)
class TestSelectionsCHARMM(object): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): """Set up the standard AdK system in implicit solvent. Geometry here is orthogonal """ self.universe = MDAnalysis.Universe(PSF, DCD) def tearDown(self): self.universe.trajectory.close() del self.universe def test_segid(self): sel = self.universe.select_atoms('segid 4AKE') assert_equal(sel.n_atoms, 3341, "failed to select segment 4AKE") assert_array_equal( sorted(sel.indices), sorted(self.universe.s4AKE.atoms.indices), "selected segment 4AKE is not the same as auto-generated segment s4AKE" ) def test_protein(self): sel = self.universe.select_atoms('protein') assert_equal(sel.n_atoms, 3341, "failed to select protein") assert_array_equal( sorted(sel.indices), sorted(self.universe.s4AKE.atoms.indices), "selected protein is not the same as auto-generated protein segment s4AKE" ) def test_backbone(self): sel = self.universe.select_atoms('backbone') assert_equal(sel.n_atoms, 855) def test_resid_single(self): sel = self.universe.select_atoms('resid 100') assert_equal(sel.n_atoms, 7) assert_equal(sel.residues.resnames, ['GLY']) def test_resid_range(self): sel = self.universe.select_atoms('resid 100:105') assert_equal(sel.n_atoms, 89) assert_equal(sel.residues.resnames, ['GLY', 'ILE', 'ASN', 'VAL', 'ASP', 'TYR']) def test_selgroup(self): sel = self.universe.select_atoms('not resid 100') sel2 = self.universe.select_atoms('not group notr100', notr100=sel) assert_equal(sel2.n_atoms, 7) assert_equal(sel2.residues.resnames, ['GLY']) def test_fullselgroup(self): sel1 = self.universe.select_atoms('resid 101') sel2 = self.universe.select_atoms('resid 100') sel3 = sel1.select_atoms('fullgroup r100', r100=sel2) assert_equal(sel2.n_atoms, 7) assert_equal(sel2.residues.resnames, ['GLY']) # resnum selections are boring here because we haven't really a mechanism yet # to assign the canonical PDB resnums def test_resnum_single(self): sel = self.universe.select_atoms('resnum 100') assert_equal(sel.n_atoms, 7) assert_equal(sel.residues.resids, [100]) assert_equal(sel.residues.resnames, ['GLY']) def test_resnum_range(self): sel = self.universe.select_atoms('resnum 100:105') assert_equal(sel.n_atoms, 89) assert_equal(sel.residues.resids, range(100, 106)) assert_equal(sel.residues.resnames, ['GLY', 'ILE', 'ASN', 'VAL', 'ASP', 'TYR']) def test_resname(self): sel = self.universe.select_atoms('resname LEU') assert_equal(sel.n_atoms, 304, "Failed to find all 'resname LEU' atoms.") assert_equal(sel.n_residues, 16, "Failed to find all 'resname LEU' residues.") assert_array_equal( sorted(sel.indices), sorted(self.universe.s4AKE.LEU.atoms.indices), "selected 'resname LEU' atoms are not the same as auto-generated s4AKE.LEU" ) def test_name(self): sel = self.universe.select_atoms('name CA') assert_equal(sel.n_atoms, 214) def test_atom(self): sel = self.universe.select_atoms('atom 4AKE 100 CA') assert_equal(len(sel), 1) assert_equal(sel.resnames, ['GLY']) assert_array_almost_equal( sel.positions, np.array([[20.38685226, -3.44224262, -5.92158318]], dtype=np.float32)) def test_atom_empty(self): sel = self.universe.select_atoms('atom 4AKE 100 XX') # Does not exist assert_equal(len(sel), 0) def test_type(self): sel = self.universe.select_atoms("type 1") assert_equal(len(sel), 253) def test_and(self): sel = self.universe.select_atoms('resname GLY and resid 100') assert_equal(len(sel), 7) def test_or(self): sel = self.universe.select_atoms('resname LYS or resname ARG') assert_equal(sel.n_residues, 31) def test_not(self): sel = self.universe.select_atoms('not backbone') assert_equal(len(sel), 2486) def test_around(self): sel = self.universe.select_atoms('around 4.0 bynum 1943') assert_equal(len(sel), 32) def test_sphlayer(self): sel = self.universe.select_atoms('sphlayer 4.0 6.0 bynum 1281') assert_equal(len(sel), 66) def test_sphzone(self): sel = self.universe.select_atoms('sphzone 6.0 bynum 1281') assert_equal(len(sel), 86) def test_cylayer(self): sel = self.universe.select_atoms('cylayer 4.0 6.0 10 -10 bynum 1281') assert_equal(len(sel), 88) def test_cyzone(self): sel = self.universe.select_atoms('cyzone 6.0 10 -10 bynum 1281') assert_equal(len(sel), 166) def test_point(self): ag = self.universe.select_atoms('point 5.0 5.0 5.0 3.5') d = distance_array(np.array([[5.0, 5.0, 5.0]], dtype=np.float32), self.universe.atoms.positions, box=self.universe.dimensions) idx = np.where(d < 3.5)[1] assert_equal(set(ag.indices), set(idx)) def test_prop(self): sel = self.universe.select_atoms('prop y <= 16') sel2 = self.universe.select_atoms('prop abs z < 8') assert_equal(len(sel), 3194) assert_equal(len(sel2), 2001) def test_bynum(self): "Tests the bynum selection, also from AtomGroup instances (Issue 275)" sel = self.universe.select_atoms('bynum 5') assert_equal(sel[0].index, 4) sel = self.universe.select_atoms('bynum 1:10') assert_equal(len(sel), 10) assert_equal(sel[0].index, 0) assert_equal(sel[-1].index, 9) subsel = sel.select_atoms('bynum 5') assert_equal(subsel[0].index, 4) subsel = sel.select_atoms('bynum 2:5') assert_equal(len(subsel), 4) assert_equal(subsel[0].index, 1) assert_equal(subsel[-1].index, 4) def test_byres(self): sel = self.universe.select_atoms('byres bynum 0:5') assert_equal(len(sel), len(self.universe.residues[0].atoms)) def test_same_resname(self): """Test the 'same ... as' construct (Issue 217)""" sel = self.universe.select_atoms( "same resname as resid 10 or resid 11") assert_equal(len(sel), 331, ("Found a wrong number of atoms with same resname as " "resids 10 or 11")) target_resids = np.array([ 7, 8, 10, 11, 12, 14, 17, 25, 32, 37, 38, 42, 46, 49, 55, 56, 66, 73, 80, 85, 93, 95, 99, 100, 122, 127, 130, 144, 150, 176, 180, 186, 188, 189, 194, 198, 203, 207, 214 ]) assert_array_equal(sel.residues.resids, target_resids, ("Found wrong residues with same resname as " "resids 10 or 11")) def test_same_segment(self): """Test the 'same ... as' construct (Issue 217)""" SNew_A = self.universe.add_Segment(segid='A') SNew_B = self.universe.add_Segment(segid='B') SNew_C = self.universe.add_Segment(segid='C') self.universe.residues[:100].segments = SNew_A self.universe.residues[100:150].segments = SNew_B self.universe.residues[150:].segments = SNew_C target_resids = np.arange(100) + 1 sel = self.universe.select_atoms("same segment as resid 10") assert_equal( len(sel), 1520, "Found a wrong number of atoms in the same segment of resid 10") assert_array_equal( sel.residues.resids, target_resids, "Found wrong residues in the same segment of resid 10") target_resids = np.arange(100, 150) + 1 sel = self.universe.select_atoms("same segment as resid 110") assert_equal( len(sel), 797, "Found a wrong number of atoms in the same segment of resid 110") assert_array_equal( sel.residues.resids, target_resids, "Found wrong residues in the same segment of resid 110") target_resids = np.arange(150, self.universe.atoms.n_residues) + 1 sel = self.universe.select_atoms("same segment as resid 160") assert_equal( len(sel), 1024, "Found a wrong number of atoms in the same segment of resid 160") assert_array_equal( sel.residues.resids, target_resids, "Found wrong residues in the same segment of resid 160") def test_empty_same(self): ag = self.universe.select_atoms('resname MET') # No GLY, so 'as resname GLY' is empty ag2 = ag.select_atoms('same mass as resname GLY') assert_(len(ag2) == 0) def test_empty_selection(self): """Test that empty selection can be processed (see Issue 12)""" # no Trp in AdK assert_equal(len(self.universe.select_atoms('resname TRP')), 0) def test_parenthesized_expression(self): sel = self.universe.select_atoms( '( name CA or name CB ) and resname LEU') assert_equal(len(sel), 32) def test_no_space_around_parentheses(self): """Test that no space is needed around parentheses (Issue 43).""" # note: will currently be ERROR because it throws a ParseError sel = self.universe.select_atoms( '(name CA or name CB) and resname LEU') assert_equal(len(sel), 32) # TODO: # test for checking ordering and multiple comma-separated selections def test_concatenated_selection(self): E151 = self.universe.s4AKE.atoms.select_atoms('resid 151') # note that this is not quite phi... HN should be C of prec. residue phi151 = E151.atoms.select_atoms('name HN', 'name N', 'name CA', 'name CB') assert_equal(len(phi151), 4) assert_equal(phi151[0].name, 'HN', "wrong ordering in selection, should be HN-N-CA-CB") def test_global(self): """Test the `global` modifier keyword (Issue 268)""" ag = self.universe.select_atoms("resname LYS and name NZ") # Lys amines within 4 angstrom of the backbone. ag1 = self.universe.select_atoms( "resname LYS and name NZ and around 4 backbone") ag2 = ag.select_atoms("around 4 global backbone") assert_array_equal(ag2.indices, ag1.indices)
class TestAtomGroup(object): """Tests of AtomGroup; selections are tested separately. These are from before the big topology rework (aka #363) but are still valid. There is likely lots of duplication between here and other tests. """ @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): """Set up the standard AdK system in implicit solvent.""" self.universe = mda.Universe(PSF, DCD) self.ag = self.universe.atoms # prototypical AtomGroup self.dih_prec = 2 def test_getitem_int(self): assert_equal(self.universe.atoms[0].ix, self.universe.atoms.ix[0]) def test_getitem_slice(self): assert_array_equal(self.universe.atoms[0:4].ix, self.universe.atoms.ix[:4]) def test_getitem_slice2(self): assert_equal(self.universe.atoms[0:8:2].ix, self.universe.atoms.ix[0:8:2]) def test_getitem_str(self): ag1 = self.universe.atoms['HT1'] # select_atoms always returns an AtomGroup even if single result ag2 = self.universe.select_atoms('name HT1')[0] assert_equal(ag1, ag2) def test_getitem_IE(self): d = {'A': 1} assert_raises(IndexError, self.universe.atoms.__getitem__, d) def test_bad_make(self): assert_raises(TypeError, mda.core.groups.AtomGroup, ['these', 'are', 'not', 'atoms']) def test_n_atoms(self): assert_equal(self.ag.n_atoms, 3341) def test_n_residues(self): assert_equal(self.ag.n_residues, 214) def test_n_segments(self): assert_equal(self.ag.n_segments, 1) def test_resids_dim(self): assert_equal(len(self.ag.resids), len(self.ag)) def test_resnums_dim(self): assert_equal(len(self.ag.resnums), len(self.ag)) def test_segids_dim(self): assert_equal(len(self.ag.segids), len(self.ag)) def test_len(self): """testing that len(atomgroup) == atomgroup.n_atoms""" assert_equal(len(self.ag), self.ag.n_atoms, "len and n_atoms disagree") def test_center_of_geometry(self): assert_array_almost_equal( self.ag.center_of_geometry(), np.array([-0.04223963, 0.0141824, -0.03505163], dtype=np.float32)) def test_center_of_mass(self): assert_array_almost_equal( self.ag.center_of_mass(), np.array([-0.01094035, 0.05727601, -0.12885778])) def test_coordinates(self): assert_array_almost_equal( self.ag.positions[1000:2000:200], np.array([[3.94543672, -12.4060812, -7.26820087], [13.21632767, 5.879035, -14.67914867], [12.07735443, -9.00604534, 4.09301519], [11.35541916, 7.0690732, -0.32511973], [-13.26763439, 4.90658951, 10.6880455]], dtype=np.float32)) def test_principal_axes(self): assert_array_almost_equal( self.ag.principal_axes(), np.array([ [1.53389276e-03, 4.41386224e-02, 9.99024239e-01], [1.20986911e-02, 9.98951474e-01, -4.41539838e-02], [-9.99925632e-01, 1.21546132e-02, 9.98264877e-04], ])) def test_total_charge(self): assert_almost_equal(self.ag.total_charge(), -4.0, decimal=4) def test_total_mass(self): assert_almost_equal(self.ag.total_mass(), 23582.043) def test_indices_ndarray(self): assert_equal(isinstance(self.ag.indices, np.ndarray), True) def test_indices(self): assert_array_equal(self.ag.indices[:5], np.array([0, 1, 2, 3, 4])) def test_resids_ndarray(self): assert_equal(isinstance(self.ag.resids, np.ndarray), True) def test_resids(self): assert_array_equal(self.ag.residues.resids, np.arange(1, 215)) def test_resnums_ndarray(self): assert_equal(isinstance(self.ag.residues.resnums, np.ndarray), True) def test_resnums(self): assert_array_equal(self.ag.residues.resnums, np.arange(1, 215)) def test_resnames_ndarray(self): assert_equal(isinstance(self.ag.residues.resnames, np.ndarray), True) def test_resnames(self): resnames = self.ag.residues.resnames assert_array_equal(resnames[0:3], np.array(["MET", "ARG", "ILE"])) def test_names_ndarray(self): assert_equal(isinstance(self.ag.names, np.ndarray), True) def test_names(self): names = self.ag.names assert_array_equal(names[0:3], np.array(["N", "HT1", "HT2"])) def test_segids_ndarray(self): assert_equal(isinstance(self.ag.segids, np.ndarray), True) def test_segids(self): segids = self.ag.segids assert_array_equal(segids[0], np.array(["4AKE"])) def test_masses_ndarray(self): assert_equal(isinstance(self.ag.masses, np.ndarray), True) def test_masses(self): masses = self.ag.masses assert_array_equal(masses[0:3], np.array([14.007, 1.008, 1.008])) def test_charges_ndarray(self): assert_equal(isinstance(self.ag.charges, np.ndarray), True) def test_charges(self): assert_array_almost_equal(self.ag.charges[1000:2000:200], np.array([-0.09, 0.09, -0.47, 0.51, 0.09])) def test_bad_add_AG(self): def bad_add(): return self.ag + [1, 2, 3] assert_raises(TypeError, bad_add) def test_bool_false(self): # Issue #304 ag = self.universe.atoms[[]] assert_equal(bool(ag), False) def test_bool_true(self): # Issue #304 ag = self.universe.atoms[:3] assert_equal(bool(ag), True) def test_repr(self): # Should make sure that the user facing info stays as expected assert_equal(repr(self.ag), "<AtomGroup with 3341 atoms>") def test_set_resnum_single(self): ag = self.universe.atoms[:3] ag.residues.resnums = 5 for at in ag: assert_equal(at.resnum, 5) assert_equal(all(ag.resnums == 5), True) def test_set_resname_single(self): ag = self.universe.atoms[:3] new = 'abc' ag.residues.resnames = new for at in ag: assert_equal(at.resname, new) assert_equal(all(ag.resnames == new), True) def test_packintobox_badshape(self): ag = self.universe.atoms[:10] box = np.zeros(9, dtype=np.float32).reshape(3, 3) assert_raises(ValueError, ag.pack_into_box, box=box) def test_packintobox_noshape(self): ag = self.universe.atoms[:10] assert_raises(ValueError, ag.pack_into_box) def test_packintobox(self): """test AtomGroup.pack_into_box(): Tests application of periodic boundary conditions on coordinates Reference system doesn't have dimensions, so an arbitrary box is imposed on the system """ u = self.universe u.trajectory.rewind() # just to make sure... ag = u.atoms[1000:2000:200] # Provide arbitrary box ag.pack_into_box(box=np.array([5., 5., 5.], dtype=np.float32)) assert_array_almost_equal( ag.positions, np.array([[3.94543672, 2.5939188, 2.73179913], [3.21632767, 0.879035, 0.32085133], [2.07735443, 0.99395466, 4.09301519], [1.35541916, 2.0690732, 4.67488003], [1.73236561, 4.90658951, 0.6880455]], dtype=np.float32)) def test_residues(self): u = self.universe assert_equal( u.residues[100].atoms.ix, u.select_atoms('resname ILE and resid 101').atoms.ix, "Direct selection from residue group does not match " "expected I101.") def test_segments(self): u = self.universe assert_equal(len(u.segments.s4AKE.atoms), len(u.select_atoms('segid 4AKE').atoms), "Direct selection of segment 4AKE from segments failed.") def test_index_integer(self): u = self.universe a = u.atoms[100] assert_(isinstance(a, mda.core.groups.Atom), "integer index did not return Atom") def test_index_slice(self): u = self.universe a = u.atoms[100:200:10] assert_(isinstance(a, mda.core.groups.AtomGroup), "slice index did not return AtomGroup") def test_index_slice_empty(self): u = self.universe assert_array_equal(u.atoms[0:0], [], "making an empty AtomGroup failed") def test_index_advancedslice(self): u = self.universe aslice = [0, 10, 20, -1, 10] ag = u.atoms[aslice] assert_(isinstance(ag, mda.core.groups.AtomGroup), "advanced slicing does not produce a AtomGroup") assert_equal(ag[1], ag[-1], "advanced slicing does not preserve order") def test_boolean_indexing(self): # index an array with a sequence of bools # issue #282 sel = np.array([True, False, True]) ag = self.universe.atoms[10:13] ag2 = ag[sel] assert_equal(len(ag2), 2) for at in [ag[0], ag[2]]: assert_equal(at in ag2, True) def test_boolean_indexing_2(self): # index an array with a sequence of bools # issue #282 sel = [True, False, True] ag = self.universe.atoms[10:13] ag2 = ag[sel] assert_equal(len(ag2), 2) for at in [ag[0], ag[2]]: assert_equal(at in ag2, True) def test_bool_IE(self): # indexing with empty list doesn't run foul of bool check sel = [] ag = self.universe.atoms[10:30] ag2 = ag[sel] assert_equal(len(ag2), 0) def test_dihedral_ValueError(self): """test that AtomGroup.dihedral() raises ValueError if not exactly 4 atoms given""" nodih = self.universe.select_atoms("resid 3:10") assert_raises(ValueError, getattr, nodih, 'dihedral') nodih = self.universe.select_atoms("resid 3:5") assert_raises(ValueError, getattr, nodih, 'dihedral') def test_improper(self): u = self.universe u.trajectory.rewind() # just to make sure... peptbond = u.select_atoms("atom 4AKE 20 C", "atom 4AKE 21 CA", "atom 4AKE 21 N", "atom 4AKE 21 HN") assert_almost_equal( peptbond.improper.value(), 168.52952575683594, self.dih_prec, "Peptide bond improper dihedral for M21 " "calculated wrongly.") def test_dihedral_equals_improper(self): u = self.universe u.trajectory.rewind() # just to make sure... peptbond = u.select_atoms("atom 4AKE 20 C", "atom 4AKE 21 CA", "atom 4AKE 21 N", "atom 4AKE 21 HN") assert_equal( peptbond.improper.value(), peptbond.dihedral.value(), "improper() and proper dihedral() give different results") def test_bond(self): self.universe.trajectory.rewind() # just to make sure... sel2 = self.universe.s4AKE.r98.atoms.select_atoms( "name OE1", "name OE2") assert_almost_equal(sel2.bond.value(), 2.1210737228393555, 3, "distance of Glu98 OE1--OE2 wrong") def test_bond_pbc(self): self.universe.trajectory.rewind() sel2 = self.universe.s4AKE.r98.atoms.select_atoms( "name OE1", "name OE2") assert_almost_equal(sel2.bond.value(pbc=True), 2.1210737228393555, 3, "distance of Glu98 OE1--OE2 wrong") def test_bond_ValueError(self): ag = self.universe.atoms[:4] assert_raises(ValueError, getattr, ag, 'bond') def test_angle(self): self.universe.trajectory.rewind() # just to make sure... sel3 = self.universe.s4AKE.r98.atoms.select_atoms( "name OE1", "name CD", "name OE2") assert_almost_equal(sel3.angle.value(), 117.46187591552734, 3, "angle of Glu98 OE1-CD-OE2 wrong") def test_angle_ValueError(self): ag = self.universe.atoms[:2] assert_raises(ValueError, getattr, ag, 'angle') def test_shape_parameter(self): s = self.universe.s4AKE.atoms.shape_parameter() assert_almost_equal(s, 0.00240753939086033, 6) def test_asphericity(self): a = self.universe.s4AKE.atoms.asphericity() assert_almost_equal(a, 0.020227504542775828, 6) def test_positions(self): ag = self.universe.select_atoms("bynum 12:42") pos = ag.positions + 3.14 ag.positions = pos # should work assert_almost_equal(ag.positions, pos, err_msg="failed to update atoms 12:42 position " "to new position") def set_badarr(pos=pos): # create wrong size array badarr = np.random.random((pos.shape[0] - 1, pos.shape[1] - 1)) ag.positions = badarr assert_raises(ValueError, set_badarr) def test_set_names(self): ag = self.universe.atoms[:2] names = ['One', 'Two'] ag.names = names for a, b in zip(ag, names): assert_equal(a.name, b) @attr("issue") def test_nonexistent_instantselector_raises_AttributeError(self): def access_nonexistent_instantselector(): self.universe.atoms.NO_SUCH_ATOM assert_raises(AttributeError, access_nonexistent_instantselector) def test_atom_order(self): assert_equal(self.universe.atoms.indices, sorted(self.universe.atoms.indices))
class TestPBCFlag(object): @dec.skipif(parser_not_found('TRZ'), 'TRZ parser not available. Are you using python 3?') def setUp(self): self.prec = 3 self.universe = mda.Universe(TRZ_psf, TRZ) self.ref_noPBC = { 'COG': np.array([4.23789883, 0.62429816, 2.43123484], dtype=np.float32), 'COM': np.array([4.1673783, 0.70507009, 2.21175832]), 'ROG': 119.30368949900134, 'Shape': 0.6690026954813445, 'Asph': 0.5305456387833748, 'MOI': np.array([[152117.06620921, 55149.54042136, -26630.46034023], [55149.54042136, 72869.64061494, 21998.1778074], [-26630.46034023, 21998.1778074, 162388.70002471]]), 'BBox': np.array([[-75.74159241, -144.86634827, -94.47974396], [95.83090973, 115.11561584, 88.09812927]], dtype=np.float32), 'BSph': (173.40482, np.array([4.23789883, 0.62429816, 2.43123484], dtype=np.float32)), 'PAxes': np.array([[-0.78787867, -0.26771575, 0.55459488], [0.40611024, 0.45112859, 0.7947059], [0.46294889, -0.85135849, 0.24671249]]) } self.ref_PBC = { 'COG': np.array([26.82960892, 31.5592289, 30.98238945], dtype=np.float32), 'COM': np.array([26.67781143, 31.2104336, 31.19796289]), 'ROG': 27.713008969174918, 'Shape': 0.0017390512580463542, 'Asph': 0.020601215358731016, 'MOI': np.array([[7333.79167791, -211.8997285, -721.50785456], [-211.8997285, 7059.07470427, -91.32156884], [-721.50785456, -91.32156884, 6509.31735029]]), 'BBox': np.array([[1.45964116e-01, 1.85623169e-02, 4.31785583e-02], [5.53314018e+01, 5.54227829e+01, 5.54158211e+01]], dtype=np.float32), 'BSph': (47.923367, np.array([26.82960892, 31.5592289, 30.98238945], dtype=np.float32)), 'PAxes': np.array([[-0.85911708, 0.19258726, 0.4741603], [-0.07520116, -0.96394227, 0.25526473], [-0.50622389, -0.18364489, -0.84262206]]) } self.ag = self.universe.residues[0:3] def tearDown(self): mda.core.flags['use_pbc'] = False del self.universe del self.ref_noPBC del self.ref_PBC del self.ag def test_flag(self): # Test default setting of flag assert_equal(mda.core.flags['use_pbc'], False) def test_default(self): # Test regular behaviour assert_almost_equal(self.ag.center_of_geometry(), self.ref_noPBC['COG'], self.prec) assert_almost_equal(self.ag.center_of_mass(), self.ref_noPBC['COM'], self.prec) assert_almost_equal(self.ag.radius_of_gyration(), self.ref_noPBC['ROG'], self.prec) assert_almost_equal(self.ag.shape_parameter(), self.ref_noPBC['Shape'], self.prec) assert_almost_equal(self.ag.asphericity(), self.ref_noPBC['Asph'], self.prec) assert_almost_equal(self.ag.moment_of_inertia(), self.ref_noPBC['MOI'], self.prec) assert_almost_equal(self.ag.bbox(), self.ref_noPBC['BBox'], self.prec) assert_almost_equal(self.ag.bsphere()[0], self.ref_noPBC['BSph'][0], self.prec) assert_almost_equal(self.ag.bsphere()[1], self.ref_noPBC['BSph'][1], self.prec) assert_almost_equal(self.ag.principal_axes(), self.ref_noPBC['PAxes'], self.prec) def test_pbcflag(self): # Test using ag method flag assert_almost_equal(self.ag.center_of_geometry(pbc=True), self.ref_PBC['COG'], self.prec) assert_almost_equal(self.ag.center_of_mass(pbc=True), self.ref_PBC['COM'], self.prec) assert_almost_equal(self.ag.radius_of_gyration(pbc=True), self.ref_PBC['ROG'], self.prec) assert_almost_equal(self.ag.shape_parameter(pbc=True), self.ref_PBC['Shape'], self.prec) assert_almost_equal(self.ag.asphericity(pbc=True), self.ref_PBC['Asph'], self.prec) assert_almost_equal(self.ag.moment_of_inertia(pbc=True), self.ref_PBC['MOI'], self.prec) assert_almost_equal(self.ag.bbox(pbc=True), self.ref_PBC['BBox'], self.prec) assert_almost_equal( self.ag.bsphere(pbc=True)[0], self.ref_PBC['BSph'][0], self.prec) assert_almost_equal( self.ag.bsphere(pbc=True)[1], self.ref_PBC['BSph'][1], self.prec) assert_almost_equal(self.ag.principal_axes(pbc=True), self.ref_PBC['PAxes'], self.prec) def test_usepbc_flag(self): # Test using the core.flags flag mda.core.flags['use_pbc'] = True assert_almost_equal(self.ag.center_of_geometry(), self.ref_PBC['COG'], self.prec) assert_almost_equal(self.ag.center_of_mass(), self.ref_PBC['COM'], self.prec) assert_almost_equal(self.ag.radius_of_gyration(), self.ref_PBC['ROG'], self.prec) assert_almost_equal(self.ag.shape_parameter(), self.ref_PBC['Shape'], self.prec) assert_almost_equal(self.ag.asphericity(), self.ref_PBC['Asph'], self.prec) assert_almost_equal(self.ag.moment_of_inertia(), self.ref_PBC['MOI'], self.prec) assert_almost_equal(self.ag.bbox(), self.ref_PBC['BBox'], self.prec) assert_almost_equal(self.ag.bsphere()[0], self.ref_PBC['BSph'][0], self.prec) assert_almost_equal(self.ag.bsphere()[1], self.ref_PBC['BSph'][1], self.prec) assert_almost_equal(self.ag.principal_axes(), self.ref_PBC['PAxes'], self.prec) mda.core.flags['use_pbc'] = False def test_override_flag(self): # Test using the core.flags flag, then overriding mda.core.flags['use_pbc'] = True assert_almost_equal(self.ag.center_of_geometry(pbc=False), self.ref_noPBC['COG'], self.prec) assert_almost_equal(self.ag.center_of_mass(pbc=False), self.ref_noPBC['COM'], self.prec) assert_almost_equal(self.ag.radius_of_gyration(pbc=False), self.ref_noPBC['ROG'], self.prec) assert_almost_equal(self.ag.shape_parameter(pbc=False), self.ref_noPBC['Shape'], self.prec) assert_almost_equal(self.ag.asphericity(pbc=False), self.ref_noPBC['Asph'], self.prec) assert_almost_equal(self.ag.moment_of_inertia(pbc=False), self.ref_noPBC['MOI'], self.prec) assert_almost_equal(self.ag.bbox(pbc=False), self.ref_noPBC['BBox'], self.prec) assert_almost_equal( self.ag.bsphere(pbc=False)[0], self.ref_noPBC['BSph'][0], self.prec) assert_almost_equal( self.ag.bsphere(pbc=False)[1], self.ref_noPBC['BSph'][1], self.prec) assert_almost_equal(self.ag.principal_axes(pbc=False), self.ref_noPBC['PAxes'], self.prec) mda.core.flags['use_pbc'] = False
class TestDihedralSelections(object): @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def setUp(self): self.universe = mda.Universe(PSF, DCD) self.dih_prec = 2 def tearDown(self): del self.universe del self.dih_prec def test_phi_selection(self): phisel = self.universe.s4AKE.r10.phi_selection() assert_equal(phisel.names, ['C', 'N', 'CA', 'C']) assert_equal(phisel.residues.resids, [9, 10]) assert_equal(phisel.residues.resnames, ['PRO', 'GLY']) def test_psi_selection(self): psisel = self.universe.s4AKE.r10.psi_selection() assert_equal(psisel.names, ['N', 'CA', 'C', 'N']) assert_equal(psisel.residues.resids, [10, 11]) assert_equal(psisel.residues.resnames, ['GLY', 'ALA']) def test_omega_selection(self): osel = self.universe.s4AKE.r8.omega_selection() assert_equal(osel.names, ['CA', 'C', 'N', 'CA']) assert_equal(osel.residues.resids, [8, 9]) assert_equal(osel.residues.resnames, ['ALA', 'PRO']) def test_chi1_selection(self): sel = self.universe.s4AKE.r13.chi1_selection() # LYS assert_equal(sel.names, ['N', 'CA', 'CB', 'CG']) assert_equal(sel.residues.resids, [13]) assert_equal(sel.residues.resnames, ['LYS']) def test_phi_sel_fail(self): sel = self.universe.residues[0].phi_selection() assert_equal(sel, None) def test_psi_sel_fail(self): sel = self.universe.residues[-1].psi_selection() assert_equal(sel, None) def test_omega_sel_fail(self): sel = self.universe.residues[-1].omega_selection() assert_equal(sel, None) def test_ch1_sel_fail(self): sel = self.universe.s4AKE.r8.chi1_selection() assert_equal(sel, None) # ALA def test_dihedral_phi(self): u = self.universe phisel = u.s4AKE.r10.phi_selection() assert_almost_equal(phisel.dihedral.value(), -168.57384, self.dih_prec) def test_dihedral_psi(self): u = self.universe psisel = u.s4AKE.r10.psi_selection() assert_almost_equal(psisel.dihedral.value(), -30.064838, self.dih_prec) def test_dihedral_omega(self): u = self.universe osel = u.s4AKE.r8.omega_selection() assert_almost_equal(osel.dihedral.value(), -179.93439, self.dih_prec) def test_dihedral_chi1(self): u = self.universe sel = u.s4AKE.r13.chi1_selection() # LYS assert_almost_equal(sel.dihedral.value(), -58.428127, self.dih_prec)
class TestAtomGroupProperties(object): """Test working with the properties of Atoms via AtomGroups Check that: - getting properties from AG matches the Atom values - setting properties from AG changes the Atom - setting the property on Atom changes AG """ @staticmethod def get_new(att_type): """Return enough values to change the small g""" if att_type == 'string': return ['A', 'B', 'C', 'D', 'E', 'F'] elif att_type == 'float': return np.array([0.001, 0.002, 0.003, 0.005, 0.012, 0.025], dtype=np.float32) elif att_type == 'int': return [4, 6, 8, 1, 5, 4] def _check_ag_matches_atom(self, att, atts, ag): """Checking Atomgroup property matches Atoms""" # Check that accessing via AtomGroup is identical to doing # a list comprehension over AG ref = [getattr(atom, att) for atom in ag] assert_equal( ref, getattr(ag, atts), err_msg="AtomGroup doesn't match Atoms for property: {0}".format( att)) def _change_atom_check_ag(self, att, atts, vals, ag): """Changing Atom, checking AtomGroup matches this""" # Set attributes via Atoms for atom, val in zip(ag, vals): setattr(atom, att, val) # Check that AtomGroup returns new values other = getattr(ag, atts) assert_equal( vals, other, err_msg= "Change to Atoms not reflected in AtomGroup for property: {0}". format(att)) @dec.skipif(parser_not_found('DCD'), 'DCD parser not available. Are you using python 3?') def test_attributes(self): u = make_Universe( ('names', 'resids', 'segids', 'types', 'altLocs', 'charges', 'masses', 'radii', 'bfactors', 'occupancies')) u.atoms.occupancies = 1.0 master = u.atoms idx = [0, 1, 4, 7, 11, 14] ag = master[idx] for att, atts, att_type in (('name', 'names', 'string'), ('type', 'types', 'string'), ('altLoc', 'altLocs', 'string'), ('charge', 'charges', 'float'), ('mass', 'masses', 'float'), ('radius', 'radii', 'float'), ('bfactor', 'bfactors', 'float'), ('occupancy', 'occupancies', 'float')): vals = self.get_new(att_type) yield self._check_ag_matches_atom, att, atts, ag yield self._change_atom_check_ag, att, atts, vals, ag