def test_no_container(self, ref): with tempdir.in_tempdir(): if ref.container_format: ref.writer('foo') else: with pytest.raises(TypeError): ref.writer('foo')
def test_write_no_args(self): with tempdir.in_tempdir(): self.u.atoms.write() files = glob('*') assert_equal(len(files), 1) name = path.splitext(path.basename(DCD))[0] assert_equal(files[0], "{}_0.pdb".format(name))
def test_AlignTraj_outfile_default(self, universe, reference): with tempdir.in_tempdir(): reference.trajectory[-1] x = align.AlignTraj(universe, reference) try: assert os.path.basename(x.filename) == 'rmsfit_adk_dims.dcd' finally: x._writer.close()
def test_xtc_striding(): """testing MDAnalysis.analysis.helanal xtc striding: Check for resolution of Issue #188.""" u = MDAnalysis.Universe(GRO, XTC) u.trajectory[1] with tempdir.in_tempdir(): assert_raises(FinishTimeException, MDAnalysis.analysis.helanal.helanal_trajectory, u, selection="name CA", finish=5)
def test_save(self, universe): with tempdir.in_tempdir(): ca = self._run_Contacts(universe) ca.save('testfile.npy') saved = np.genfromtxt('testfile.npy') assert_array_almost_equal(ca.timeseries, saved) # check the header was written correctly with open('testfile.npy', 'r') as fin: assert fin.readline().strip() == '# q1 analysis'
def test_get_writer(self, universe): with tempdir.in_tempdir(): self.outfile = 'test-trz-writer.trz' W = universe.trajectory.Writer(self.outfile) assert_equal(isinstance(W, mda.coordinates.TRZ.TRZWriter), True) assert_equal(W.n_atoms, universe.trajectory.n_atoms) try: os.unlink(self.outfile) except OSError: pass
def test_get_writer_2(self): with tempdir.in_tempdir(): self.outfile = 'test-trz-writer-1.trz' W = self.trz.Writer(self.outfile, n_atoms=100) assert_equal(isinstance(W, mda.coordinates.TRZ.TRZWriter), True) assert_equal(W.n_atoms, 100) try: os.unlink(self.outfile) except OSError: pass
def test_AlignTraj_outfile_default(self, universe, reference): # NOTE: Remove the line os.remove() with release 1.0, # when the default behavior of AlignTraj changes. with tempdir.in_tempdir(): reference.trajectory[-1] x = align.AlignTraj(universe, reference) try: assert os.path.basename(x.filename) == 'rmsfit_adk_dims.dcd' finally: x._writer.close() os.remove(x.filename)
def test_writer_trz_from_other(self, u): with tempdir.in_tempdir(): outfile = 'trz-writer-2.trz' W = mda.coordinates.TRZ.TRZWriter(outfile, n_atoms=len(u.atoms)) W.write(u.trajectory.ts) W.close() u2 = mda.Universe(two_water_gro, outfile) assert_almost_equal(u.atoms.positions, u2.atoms.positions, 3)
def setUpClass(cls): cls.universe = MDAnalysis.Universe(cls.filename) if not executable_not_found("hole"): with tempdir.in_tempdir(): H = HOLEtraj(cls.universe, start=cls.start, stop=cls.stop, raseed=31415) H.run() cls.H = H else: cls.H = None cls.frames = [ts.frame for ts in cls.universe.trajectory[cls.start:cls.stop]]
def test_writer_trz_from_other(self): with tempdir.in_tempdir(): outfile = 'trz-writer-2.trz' W = mda.coordinates.TRZ.TRZWriter(outfile, n_atoms=len(self.u.atoms)) W.write(self.u.trajectory.ts) W.close() u2 = mda.Universe(two_water_gro, outfile) assert_array_almost_equal(self.u.atoms.positions, u2.atoms.positions, 3)
def test_File_write(self): with tempdir.in_tempdir(): outfile = "lookingglas.txt" with open(outfile, "w") as obj: with util.NamedStream(obj, outfile, close=True) as ns: assert_equal(ns.name, outfile) assert_equal(str(ns), outfile) ns.writelines(self.text) with open(outfile) as fh: text = fh.readlines() assert_equal(len(text), len(self.text)) assert_equal("".join(text), "".join(self.text))
def test_conect_bonds_all(self): conect = self.conect assert_equal(len(conect.atoms), 1890) assert_equal(len(conect.bonds), 1922) with tempdir.in_tempdir(): try: outfile = 'pdb-connect-bonds.pdb' self.conect.atoms.write(outfile, bonds="all") u2 = mda.Universe(outfile, guess_bonds=True) finally: os.unlink(outfile) assert_equal(len(u2.atoms), 1890) assert_equal(len([b for b in u2.bonds if not b.is_guessed]), 1922)
def test_hole_module_fd_closure(self): """test open file descriptors are closed (MDAnalysisTests.analysis.test_hole.TestHoleModule): Issue 129""" # If Issue 129 isn't resolved, this function will produce an OSError on # the system, and cause many other tests to fail as well. # # Successful test takes ~10 s, failure ~2 s. # Hasten failure by setting "ulimit -n 64" (can't go too low because of open modules etc...) import resource # ----- temporary hack ----- # on Mac OS X (on Travis) we run out of open file descriptors # before even starting this test (see # https://github.com/MDAnalysis/mdanalysis/pull/901#issuecomment-231938093); # if this issue is solved by #363 then revert the following # hack: # import platform if platform.platform() == "Darwin": max_open_files = 512 else: max_open_files = 64 # # -------------------------- resource.setrlimit(resource.RLIMIT_NOFILE, (max_open_files, self.hard_max_open_files)) with tempdir.in_tempdir(): try: H = HOLEtraj(self.universe, cvect=[0, 1, 0], sample=20.0) finally: self._restore_rlimits() # pretty unlikely that the code will get through 2 rounds if the MDA # issue 129 isn't fixed, although this depends on the file descriptor # open limit for the machine in question try: for i in range(2): # will typically get an OSError for too many files being open after # about 2 seconds if issue 129 isn't resolved H.run() except OSError as err: if err.errno == errno.EMFILE: raise AssertionError( "HOLEtraj does not close file descriptors (Issue 129)") raise finally: # make sure to restore open file limit !! self._restore_rlimits()
def test_conect_bonds_conect(self): conect = self.conect assert_equal(len(conect.atoms), 1890) assert_equal(len(conect.bonds), 1922) with tempdir.in_tempdir(): try: outfile = 'test-pdb-hbonds.pdb' self.conect.atoms.write(outfile, bonds="conect") u1 = mda.Universe(outfile, guess_bonds=True) finally: os.unlink(outfile) assert_equal(len(u1.atoms), 1890) assert_equal(len(u1.bonds), 1922)
def test_rms_fit_trj_defaultfilename(self): filename = 'rmsfit_' + os.path.basename(self.universe.trajectory.filename) with tempdir.in_tempdir(): # Need to pretend to have the universe trajectory INSIDE the tempdir because # filename=None uses the full path self.universe.trajectory.filename = os.path.abspath( os.path.join( os.curdir, os.path.basename(self.universe.trajectory.filename))) #test filename=none and different selection align.rms_fit_trj(self.universe, self.reference, select="name CA", filename=None, verbose=False) assert_(os.path.exists(filename), "rms_fit_trj did not write to {}".format(filename))
def test_helanal_trajectory(reference=HELANAL_BENDING_MATRIX, outfile="helanal_bending_matrix.dat"): u = mda.Universe(PSF, DCD) with tempdir.in_tempdir(): # Helix 8: 161 - 187 http://www.rcsb.org/pdb/explore.do?structureId=4AKE MDAnalysis.analysis.helanal.helanal_trajectory(u, selection="name CA and resnum 161-187") bendingmatrix = read_bending_matrix(outfile) ref = read_bending_matrix(reference) assert_equal(sorted(bendingmatrix.keys()), sorted(ref.keys()), err_msg="different contents in bending matrix data file") for label in ref.keys(): assert_array_almost_equal(bendingmatrix[label], ref[label], err_msg="bending matrix stats for {0} mismatch".format(label))
def test_hole_module_fd_closure(self): """test open file descriptors are closed (MDAnalysisTests.analysis.test_hole.TestHoleModule): Issue 129""" # If Issue 129 isn't resolved, this function will produce an OSError on # the system, and cause many other tests to fail as well. # # Successful test takes ~10 s, failure ~2 s. # Hasten failure by setting "ulimit -n 64" (can't go too low because of open modules etc...) import resource # ----- temporary hack ----- # on Mac OS X (on Travis) we run out of open file descriptors # before even starting this test (see # https://github.com/MDAnalysis/mdanalysis/pull/901#issuecomment-231938093); # if this issue is solved by #363 then revert the following # hack: # import platform if platform.platform() == "Darwin": max_open_files = 512 else: max_open_files = 64 # # -------------------------- resource.setrlimit(resource.RLIMIT_NOFILE, (max_open_files, self.hard_max_open_files)) with tempdir.in_tempdir(): try: H = HOLEtraj(self.universe, cvect=[0, 1, 0], sample=20.0) finally: self._restore_rlimits() # pretty unlikely that the code will get through 2 rounds if the MDA # issue 129 isn't fixed, although this depends on the file descriptor # open limit for the machine in question try: for i in range(2): # will typically get an OSError for too many files being open after # about 2 seconds if issue 129 isn't resolved H.run() except OSError as err: if err.errno == errno.EMFILE: raise AssertionError("HOLEtraj does not close file descriptors (Issue 129)") raise finally: # make sure to restore open file limit !! self._restore_rlimits()
def check_density_from_Universe(self, atomselection, ref_meandensity, **kwargs): import MDAnalysis.analysis.density with tempdir.in_tempdir(): D = MDAnalysis.analysis.density.density_from_Universe( self.universe, atomselection=atomselection, delta=self.delta, **kwargs) assert_almost_equal(D.grid.mean(), ref_meandensity, err_msg="mean density does not match") D.export(self.outfile) D2 = MDAnalysis.analysis.density.Density(self.outfile) assert_almost_equal(D.grid, D2.grid, decimal=self.precision, err_msg="DX export failed: different grid sizes")
def setUpClass(cls): cls.universe = MDAnalysis.Universe(cls.filename) if not executable_not_found("hole"): with tempdir.in_tempdir(): H = HOLEtraj(cls.universe, start=cls.start, stop=cls.stop, raseed=31415) H.run() cls.H = H else: cls.H = None cls.frames = [ ts.frame for ts in cls.universe.trajectory[cls.start:cls.stop] ]
def test_save(self): hbond = HBAC(self.u, hydrogens=self.H, acceptors=self.O, donors=self.N, bond_type='continuous', sample_time=0.06, ) hbond.run() with tempdir.in_tempdir(): hbond.save_results('hbondout.npz') loaded = np.load('hbondout.npz') assert_('time' in loaded) assert_('results' in loaded)
def test_save(self, u, hydrogens, oxygens, nitrogens): hbond = HBAC( u, hydrogens=hydrogens, acceptors=oxygens, donors=nitrogens, bond_type='continuous', sample_time=0.06, ) hbond.run() with tempdir.in_tempdir(): hbond.save_results('hbondout.npz') loaded = np.load('hbondout.npz') assert 'time' in loaded assert 'results' in loaded
def test_File_write(self): with tempdir.in_tempdir(): outfile = "lookingglas.txt" try: obj = open(outfile, "w") ns = util.NamedStream(obj, outfile, close=True) ns.writelines(self.text) ns.close() text = open(outfile).readlines() assert_equal(ns.name, outfile) assert_equal(str(ns), outfile) assert_equal(len(text), len(self.text)) assert_equal("".join(text), "".join(self.text)) finally: ns.close() obj.close()
def test_save(self): hbond = HBAC( self.u, hydrogens=self.H, acceptors=self.O, donors=self.N, bond_type='continuous', sample_time=0.06, ) hbond.run() with tempdir.in_tempdir(): hbond.save_results('hbondout.npz') loaded = np.load('hbondout.npz') assert_('time' in loaded) assert_('results' in loaded)
def test_rms_fit_trj_defaultfilename(self): filename = 'rmsfit_' + os.path.basename( self.universe.trajectory.filename) with tempdir.in_tempdir(): # Need to pretend to have the universe trajectory INSIDE the tempdir because # filename=None uses the full path self.universe.trajectory.filename = os.path.abspath( os.path.join( os.curdir, os.path.basename(self.universe.trajectory.filename))) #test filename=none and different selection align.rms_fit_trj(self.universe, self.reference, select="name CA", filename=None, verbose=False) assert_(os.path.exists(filename), "rms_fit_trj did not write to {}".format(filename))
def test_AlignTraj_outfile_default_exists(self, universe, reference, tmpdir): reference.trajectory[-1] outfile = str(tmpdir.join('align_test.dcd')) align.AlignTraj(universe, reference, filename=outfile).run() fitted = mda.Universe(PSF, outfile) # ensure default file exists with mda.Writer(str(tmpdir.join("rmsfit_align_test.dcd")), n_atoms=fitted.atoms.n_atoms) as w: w.write(fitted.atoms) with tempdir.in_tempdir(): align.AlignTraj(fitted, reference) # we are careful now. The default does nothing with pytest.raises(IOError): align.AlignTraj(fitted, reference, force=False)
def test_hole_module_fd_closure(self): """MDAnalysis.analysis.hole: Issue 129: ensure low level file descriptors to PDB files used by Hole program are properly closed""" # If Issue 129 isn't resolved, this function will produce an OSError on # the system, and cause many other tests to fail as well. # # Successful test takes ~10 s, failure ~2 s. try: # Hasten failure by setting "ulimit -n 64" (can't go too low because of open modules etc...) import resource resource.setrlimit(resource.RLIMIT_NOFILE, (64, self.hard_max_open_files)) except ImportError: raise NotImplementedError( "Test cannot be run without the resource module.") with tempdir.in_tempdir(): try: # will need to have the 'hole' command available in the path H = HOLEtraj(self.universe, cvect=[0, 1, 0], sample=20.0) except OSError as err: if err.errno == errno.ENOENT: raise OSError(errno.ENOENT, "HOLE binary not found") raise finally: self._restore_rlimits() # pretty unlikely that the code will get through 2 rounds if the MDA # issue 129 isn't fixed, although this depends on the file descriptor # open limit for the machine in question try: for i in range(2): # will typically get an OSError for too many files being open after # about 2 seconds if issue 129 isn't resolved H.run() except OSError as err: if err.errno == errno.EMFILE: raise AssertionError( "HOLEtraj does not close file descriptors (Issue 129)") elif err.errno == errno.ENOENT: raise OSError(errno.ENOENT, "HOLE binary not found") raise finally: # make sure to restore open file limit !! self._restore_rlimits()
def test_hole_module_fd_closure(self): """MDAnalysis.analysis.hole: Issue 129: ensure low level file descriptors to PDB files used by Hole program are properly closed""" # If Issue 129 isn't resolved, this function will produce an OSError on # the system, and cause many other tests to fail as well. # # Successful test takes ~10 s, failure ~2 s. try: # Hasten failure by setting "ulimit -n 64" (can't go too low because of open modules etc...) import resource resource.setrlimit(resource.RLIMIT_NOFILE, (64, self.hard_max_open_files)) except ImportError: raise NotImplementedError("Test cannot be run without the resource module.") with tempdir.in_tempdir(): try: # will need to have the 'hole' command available in the path H = HOLEtraj(self.universe, cvect=[0, 1, 0], sample=20.0) except OSError as err: if err.errno == errno.ENOENT: raise OSError(errno.ENOENT, "HOLE binary not found") raise finally: self._restore_rlimits() # pretty unlikely that the code will get through 2 rounds if the MDA # issue 129 isn't fixed, although this depends on the file descriptor # open limit for the machine in question try: for i in range(2): # will typically get an OSError for too many files being open after # about 2 seconds if issue 129 isn't resolved H.run() except OSError as err: if err.errno == errno.EMFILE: raise AssertionError("HOLEtraj does not close file descriptors (Issue 129)") elif err.errno == errno.ENOENT: raise OSError(errno.ENOENT, "HOLE binary not found") raise finally: # make sure to restore open file limit !! self._restore_rlimits()
def test_get_writer_1(self, ref, reader): with tempdir.in_tempdir(): outfile = 'test-writer' + ref.ext with reader.Writer(outfile) as W: assert_equal(isinstance(W, ref.writer), True) assert_equal(W.n_atoms, reader.n_atoms)
def test_save(self): with tempdir.in_tempdir(): ca = self._run_Contacts() ca.save('testfile.npy') saved = np.genfromtxt('testfile.npy') assert_array_almost_equal(ca.timeseries, saved)
def test_bogus_kwarg_pdb(self): # test for resolution of Issue 877 with tempdir.in_tempdir(): with assert_raises(TypeError): self.u.atoms.write('dummy.pdb', bogus="what?")
def test_write_selection(self): with tempdir.in_tempdir(): self.u.atoms.write("test.vmd")
def test_write_coordinates(self): with tempdir.in_tempdir(): self.u.atoms.write("test.xtc")
def test_raises(self): with tempdir.in_tempdir(): self.u.atoms.write('useless.format123')
def test_no_container(self): with tempdir.in_tempdir(): if self.ref.container_format: self.ref.writer('foo') else: assert_raises(TypeError, self.ref.writer, 'foo')
def test_get_writer_2(self): with tempdir.in_tempdir(): self.outfile = 'test-writer' + self.ref.ext with self.reader.Writer(self.outfile, n_atoms=100) as W: assert_equal(isinstance(W, self.ref.writer), True) assert_equal(W.n_atoms, 100)