Beispiel #1
0
 def testMol2FileWithNoTypeNames(self):
     """ Tests writing a Mol2 without types uses names instead """
     struct = read_PDB(get_fn('2koc.pdb'))
     output = StringIO()
     formats.Mol2File.write(struct, output)
     output.seek(0)
     mol2 = formats.Mol2File.parse(output, structure=True)
Beispiel #2
0
 def testPdbWriteXtal(self):
     """ Test PDB file writing from a Xtal structure """
     pdbfile = read_PDB(self.pdb)
     self._check4lzt(pdbfile)
     output = StringIO()
     pdbfile.write_pdb(output, renumber=False)
     output.seek(0)
     pdbfile2 = read_PDB(output)
     self._check4lzt(pdbfile2, check_meta=False)
     self._compareInputOutputPDBs(pdbfile, pdbfile2)
     output = reset_stringio(output)
     write_PDB(pdbfile, output)
     output.seek(0)
     pdbfile3 = read_PDB(output)
     self._check4lzt(pdbfile3, check_meta=False)
     self._compareInputOutputPDBs(pdbfile, pdbfile3, True)
     # Now check that renumbering is done correctly. 4lzt skips residues 130
     # through 200
     for res1, res2 in zip(pdbfile.residues, pdbfile3.residues):
         if res1.idx < 129:
             self.assertEqual(res1.number, res2.number)
         elif res1.idx < 135:
             self.assertEqual(res1.number, res2.number + 71)
         else:
             # Some residue numbers are skipped in the water numbering
             self.assertGreaterEqual(res1.number, res2.number + 71 + 794)
Beispiel #3
0
 def testCopyingDefaults(self):
     """ Tests that copying GromacsTopologyFile copies Defaults too """
     parm = load_file(get_fn('159.top'))
     newfile = StringIO()
     copy.copy(parm).write(newfile)
     newfile.seek(0)
     newparm = GromacsTopologyFile(newfile)
     self.assertEqual(parm.defaults, newparm.defaults)
Beispiel #4
0
 def testGetitemDefaults(self):
     """ Tests that GromacsTopologyFile[] sets Defaults correctly """
     parm = load_file(get_fn('159.top'))
     newfile = StringIO()
     parm[0,:].write(newfile)
     newfile.seek(0)
     newparm = GromacsTopologyFile(newfile)
     self.assertEqual(parm.defaults, newparm.defaults)
 def test_pp_regex(self):
     """ Tests CPreProcessor processing with whitespace """
     f = StringIO("#      define MY_DEFINE Something\nMY_DEFINE")
     self.assertEqual(CPreProcessor(f).read().strip(), "Something")
     f = StringIO("#       ifdef      MY_VAR    \nMY_VAR\n#endif\n"
                  "#\t\tdefine MY_VAR       NoSpaces    \n"
                  "#       ifdef      MY_VAR    \nMY_VAR\n#endif")
     f.seek(0)
     self.assertEqual(CPreProcessor(f).read().strip(), 'NoSpaces')
 def test_ifndef(self):
     """ Tests CPreProcessor #ifndef/#else#endif preprocessing """
     f = StringIO('#ifndef MY_DEFINE\nMY_DEFINE is not set\n'
                  '#else\nPPVAR is set to MY_DEFINE\n#endif\n')
     pp = CPreProcessor(f)  # no defines
     self.assertEqual(pp.read().strip(), 'MY_DEFINE is not set')
     f.seek(0)
     pp = CPreProcessor(f, defines=dict(MY_DEFINE='SUCCESS'))
     self.assertEqual(pp.read().strip(), 'PPVAR is set to SUCCESS')
 def test_missing_include(self):
     """ Tests CPreProcessor controllable behavior of missing #includes """
     warnings.filterwarnings('error', category=PreProcessorWarning)
     f = StringIO("#include \"nofile.h\"\n")
     pp = CPreProcessor(f)
     self.assertRaises(PreProcessorError, lambda: pp.read())
     f.seek(0)
     pp = CPreProcessor(f, notfound_fatal=False)
     self.assertRaises(PreProcessorWarning, lambda: pp.read())
 def test_ifndef(self):
     """ Tests CPreProcessor #ifndef/#else#endif preprocessing """
     f = StringIO('#ifndef MY_DEFINE\nMY_DEFINE is not set\n'
                  '#else\nPPVAR is set to MY_DEFINE\n#endif\n')
     pp = CPreProcessor(f) # no defines
     self.assertEqual(pp.read().strip(), 'MY_DEFINE is not set')
     f.seek(0)
     pp = CPreProcessor(f, defines=dict(MY_DEFINE='SUCCESS'))
     self.assertEqual(pp.read().strip(), 'PPVAR is set to SUCCESS')
 def test_pp_regex(self):
     """ Tests CPreProcessor processing with whitespace """
     f = StringIO("#      define MY_DEFINE Something\nMY_DEFINE")
     self.assertEqual(CPreProcessor(f).read().strip(), "Something")
     f = StringIO("#       ifdef      MY_VAR    \nMY_VAR\n#endif\n"
                  "#\t\tdefine MY_VAR       NoSpaces    \n"
                  "#       ifdef      MY_VAR    \nMY_VAR\n#endif")
     f.seek(0)
     self.assertEqual(CPreProcessor(f).read().strip(), 'NoSpaces')
Beispiel #10
0
 def test_missing_include(self):
     """ Tests CPreProcessor controllable behavior of missing #includes """
     warnings.filterwarnings('error', category=PreProcessorWarning)
     f = StringIO("#include \"nofile.h\"\n")
     pp = CPreProcessor(f)
     self.assertRaises(PreProcessorError, lambda: pp.read())
     f.seek(0)
     pp = CPreProcessor(f, notfound_fatal=False)
     self.assertRaises(PreProcessorWarning, lambda: pp.read())
Beispiel #11
0
 def testCIFModels(self):
     """ Test CIF parsing/writing NMR structure with 20 models (2koc) """
     cif = download_CIF('2koc')
     self.assertEqual(cif.get_coordinates('all').shape, (20, 451, 3))
     self.assertEqual(len(cif.atoms), 451)
     output = StringIO()
     write_CIF(cif, output)
     output.seek(0)
     pdbfile2 = read_CIF(output)
     self.assertEqual(len(pdbfile2.atoms), 451)
     self.assertEqual(pdbfile2.get_coordinates('all').shape, (20, 451, 3))
Beispiel #12
0
 def testPdbWriteModels(self):
     """ Test PDB file writing from NMR structure with models """
     pdbfile = read_PDB(self.models)
     self.assertEqual(pdbfile.get_coordinates('all').shape, (20, 451, 3))
     self.assertEqual(len(pdbfile.atoms), 451)
     output = StringIO()
     write_PDB(pdbfile, output)
     output.seek(0)
     pdbfile2 = read_PDB(output)
     self.assertEqual(len(pdbfile2.atoms), 451)
     self.assertEqual(pdbfile2.get_coordinates('all').shape, (20, 451, 3))
     self._compareInputOutputPDBs(pdbfile, pdbfile2)
Beispiel #13
0
 def testPdbWriteSimple(self):
     """ Test PDB file writing on a very simple input structure """
     pdbfile = read_PDB(self.simple)
     self.assertEqual(len(pdbfile.atoms), 33)
     self.assertEqual(len(pdbfile.residues), 3)
     output = StringIO()
     pdbfile.write_pdb(output)
     output.seek(0)
     pdbfile2 = read_PDB(output)
     self.assertEqual(len(pdbfile2.atoms), 33)
     self.assertEqual(len(pdbfile2.residues), 3)
     self._compareInputOutputPDBs(pdbfile, pdbfile2)
Beispiel #14
0
 def test_not_write_residues_with_same_templhash(self):
     """Test that no identical residues are written to XML, using the
        templhasher function."""
     # TODO add testing for multiatomic residues when support for those added
     params = openmm.OpenMMParameterSet.from_parameterset(
         pmd.amber.AmberParameterSet(get_fn('atomic_ions.lib')))
     new_residues = OrderedDict()
     for name in ('K', 'K+', 'NA', 'Na+', 'CL', 'Cl-'):
         new_residues[name] = params.residues[name]
     params.residues = new_residues
     ffxml = StringIO()
     params.write(ffxml)
     ffxml.seek(0)
     self.assertEqual(len(ffxml.readlines()), 16)
Beispiel #15
0
    def test_write_xml_parameters_amber_write_unused(self):
        """Test the write_unused argument in writing XML files"""
        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.amber.AmberParameterSet(
                get_fn('amino12.lib'),
                os.path.join(get_fn('parm'), 'parm10.dat'),
                os.path.join(get_fn('parm'), 'frcmod.ff14SB')))
        ffxml = StringIO()
        params.write(ffxml)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 2178)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 1646)

        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.amber.AmberParameterSet(
                get_fn('atomic_ions.lib'),
                os.path.join(get_fn('parm'), 'frcmod.ionsjc_tip3p')))
        ffxml = StringIO()
        warnings.filterwarnings('ignore', category=exceptions.ParameterWarning)
        params.write(ffxml)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 222)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 57)
    def test_write_xml_parameters_amber_write_unused(self):
        """Test the write_unused argument in writing XML files"""
        params = openmm.OpenMMParameterSet.from_parameterset(
                pmd.amber.AmberParameterSet(get_fn('amino12.lib'),
                os.path.join(get_fn('parm'), 'parm10.dat'),
                os.path.join(get_fn('parm'), 'frcmod.ff14SB'))
        )
        ffxml = StringIO()
        params.write(ffxml)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 2178)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 1646)

        params = openmm.OpenMMParameterSet.from_parameterset(
                  pmd.amber.AmberParameterSet(get_fn('atomic_ions.lib'),
                  os.path.join(get_fn('parm'), 'frcmod.ionsjc_tip3p'))
        )
        ffxml = StringIO()
        warnings.filterwarnings('ignore', category=exceptions.ParameterWarning)
        params.write(ffxml)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 222)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 57)
 def test_not_write_residues_with_same_templhash(self):
     """Test that no identical residues are written to XML, using the
        templhasher function."""
     # TODO add testing for multiatomic residues when support for those added
     params = openmm.OpenMMParameterSet.from_parameterset(
              pmd.amber.AmberParameterSet(get_fn('atomic_ions.lib'))
              )
     new_residues = OrderedDict()
     for name in ('K', 'K+', 'NA', 'Na+', 'CL', 'Cl-'):
         new_residues[name] = params.residues[name]
     params.residues = new_residues
     ffxml = StringIO()
     params.write(ffxml)
     ffxml.seek(0)
     self.assertEqual(len(ffxml.readlines()), 16)
Beispiel #18
0
 def test_if1_if0(self):
     """ Tests CPreProcessor use of #if 1 and #if 0 to serve as comments """
     f = StringIO('#if 1\n#ifdef MY_DEFINE\nPPVAR is set to MY_DEFINE\n'
                  '#else\nMY_DEFINE is not set\n#endif\n#endif\n')
     pp = CPreProcessor(f) # no defines
     self.assertEqual(pp.read().strip(), 'MY_DEFINE is not set')
     f.seek(0)
     pp = CPreProcessor(f, defines=dict(MY_DEFINE='SUCCESS'))
     self.assertEqual(pp.read().strip(), 'PPVAR is set to SUCCESS')
     f = StringIO('#if 0\n#ifdef MY_DEFINE\nPPVAR is set to MY_DEFINE\n'
                  '#else\nMY_DEFINE is not set\n#endif\n#endif\n')
     pp = CPreProcessor(f) # no defines
     self.assertFalse(pp.read().strip())
     f.seek(0)
     pp = CPreProcessor(f, defines=dict(MY_DEFINE='SUCCESS'))
     self.assertFalse(pp.read().strip())
 def test_if1_if0(self):
     """ Tests CPreProcessor use of #if 1 and #if 0 to serve as comments """
     f = StringIO('#if 1\n#ifdef MY_DEFINE\nPPVAR is set to MY_DEFINE\n'
                  '#else\nMY_DEFINE is not set\n#endif\n#endif\n')
     pp = CPreProcessor(f)  # no defines
     self.assertEqual(pp.read().strip(), 'MY_DEFINE is not set')
     f.seek(0)
     pp = CPreProcessor(f, defines=dict(MY_DEFINE='SUCCESS'))
     self.assertEqual(pp.read().strip(), 'PPVAR is set to SUCCESS')
     f = StringIO('#if 0\n#ifdef MY_DEFINE\nPPVAR is set to MY_DEFINE\n'
                  '#else\nMY_DEFINE is not set\n#endif\n#endif\n')
     pp = CPreProcessor(f)  # no defines
     self.assertFalse(pp.read().strip())
     f.seek(0)
     pp = CPreProcessor(f, defines=dict(MY_DEFINE='SUCCESS'))
     self.assertFalse(pp.read().strip())
Beispiel #20
0
 def test_write_xml_parameters_amber_write_unused(self):
     """ Test writing XML parameters loaded from part of the ff14SB forcefield
     files, using the write_unused argument"""
     params = openmm.OpenMMParameterSet.from_parameterset(
         pmd.amber.AmberParameterSet(
             get_fn('amino12.lib'),
             os.path.join(get_fn('parm'), 'parm10.dat'),
             os.path.join(get_fn('parm'), 'frcmod.ff14SB')))
     ffxml = StringIO()
     params.write(ffxml)
     ffxml.seek(0)
     self.assertEqual(len(ffxml.readlines()), 2178)
     ffxml = StringIO()
     params.write(ffxml, write_unused=False)
     ffxml.seek(0)
     self.assertEqual(len(ffxml.readlines()), 1646)
Beispiel #21
0
 def testAnisouWrite(self):
     """ Tests that write_PDB properly writes ANISOU records """
     def check_aniso(pdbfile):
         aniso1 = [2066, 1204, 1269, 44, 126, 191]
         aniso2 = [2090, 1182, 921, 46, 64, 60]
         aniso3 = [3057, 3932, 5304, 126, -937, -661]
         self.assertEqual(len(aniso1), len(pdbfile.atoms[0].anisou))
         for x, y in zip(aniso1, pdbfile.atoms[0].anisou):
             self.assertEqual(x/10000, y)
         self.assertEqual(len(aniso2), len(pdbfile.atoms[1].anisou))
         for x, y in zip(aniso2, pdbfile.atoms[1].anisou):
             self.assertEqual(x/10000, y)
         self.assertEqual(len(aniso3), len(pdbfile.atoms[-1].anisou))
         for x, y in zip(aniso3, pdbfile.atoms[-1].anisou):
             self.assertEqual(x/10000, y)
     pdbfile = read_PDB(self.pdb)
     check_aniso(pdbfile)
     output = StringIO()
     pdbfile.write_pdb(output)
     output.seek(0)
     pdbfile2 = read_PDB(output)
     # Should have no anisou records, since by default they are not written
     for atom in pdbfile2.atoms:
         self.assertIs(atom.anisou, None)
     output = reset_stringio(output)
     pdbfile.write_pdb(output, renumber=False, write_anisou=True)
     output.seek(0)
     # This one should have anisou records
     pdbfile3 = read_PDB(output)
     self._compareInputOutputPDBs(pdbfile, pdbfile3)
     for a1, a2 in zip(pdbfile.atoms, pdbfile3.atoms):
         if has_numpy():
             self.assertEqual(a1.anisou.shape, a2.anisou.shape)
         else:
             self.assertEqual(len(a1.anisou), len(a2.anisou))
         for x, y in zip(a1.anisou, a2.anisou):
             self.assertAlmostEqual(x, y, delta=1e-4)
         self.assertEqual(len(a1.other_locations), len(a2.other_locations))
         for key in sorted(a1.other_locations.keys()):
             oa1 = a1.other_locations[key]
             oa2 = a2.other_locations[key]
             if has_numpy():
                 self.assertEqual(oa1.anisou.shape, oa2.anisou.shape)
             else:
                 self.assertEqual(len(oa1.anisou), len(oa2.anisou))
             for x, y in zip(oa1.anisou, oa2.anisou):
                 self.assertAlmostEqual(x, y, delta=1e-4)
Beispiel #22
0
 def test_override_level(self):
     """Test correct support for the override_level attribute of
        ResidueTemplates and correct writing to XML tag"""
     params = openmm.OpenMMParameterSet.from_parameterset(
         pmd.amber.AmberParameterSet(get_fn('atomic_ions.lib')))
     new_residues = OrderedDict()
     new_residues['K'] = params.residues['K']
     new_residues['NA'] = params.residues['NA']
     new_residues['K'].override_level = 1
     params.residues = new_residues
     ffxml = StringIO()
     params.write(ffxml)
     ffxml.seek(0)
     output_lines = ffxml.readlines()
     control_line1 = '  <Residue name="K" override="1">\n'
     control_line2 = '  <Residue name="NA">\n'
     self.assertEqual(output_lines[5], control_line1)
     self.assertEqual(output_lines[8], control_line2)
Beispiel #23
0
 def test_write_xml_parameters_amber_write_unused(self):
     """ Test writing XML parameters loaded from part of the ff14SB forcefield
     files, using the write_unused argument"""
     params = openmm.OpenMMParameterSet.from_parameterset(
         pmd.amber.AmberParameterSet(
             get_fn("amino12.lib"),
             os.path.join(get_fn("parm"), "parm10.dat"),
             os.path.join(get_fn("parm"), "frcmod.ff14SB"),
         )
     )
     ffxml = StringIO()
     params.write(ffxml)
     ffxml.seek(0)
     self.assertEqual(len(ffxml.readlines()), 2178)
     ffxml = StringIO()
     params.write(ffxml, write_unused=False)
     ffxml.seek(0)
     self.assertEqual(len(ffxml.readlines()), 1646)
Beispiel #24
0
    def parse(filename):
        """
        Parses XML file and returns deserialized object. The return value
        depends on the serialized object, summarized below

            - System : returns simtk.openmm.System
            - State : returns simtk.openmm.State
            - Integrator : returns simtk.openmm.Integrator subclass
            - ForceField : returns simtk.openmm.app.ForceField

        Parameters
        ----------
        filename : str or file-like
            The file name or file object containing the XML-serialized object

        Returns
        -------
        obj : System, State, Integrator, or ForceField
            The deserialized object

        Notes
        -----
        OpenMM requires the entire contents of this file read into memory. As a
        result, this function may require a significant amount of memory.
        """
        if isinstance(filename, string_types):
            with closing(genopen(filename, 'r')) as f:
                contents = f.read()
        else:
            contents = f.read()
        # ForceField is not handled by XmlSerializer
        if '<ForceField' in contents:
            obj = StringIO()
            obj.write(contents)
            obj.seek(0)
            return app.ForceField(obj)

        obj = mm.XmlSerializer.deserialize(contents)
        if isinstance(obj, (mm.System, mm.Integrator)):
            return obj
        elif isinstance(obj, mm.State):
            return _OpenMMStateContents(obj)
        return 
 def test_define(self):
     """ Tests CPreProcessor #define preprocessing """
     f = StringIO('#ifdef MY_DEFINE\nPPVAR is set to MY_DEFINE\n'
                  '#else\nMY_DEFINE is not set\n#endif\n'
                  '#define MY_DEFINE SUCCESS\n#ifdef MY_DEFINE\n'
                  'PPVAR is set to MY_DEFINE\n#else\nMY_DEFINE is not set\n'
                  '#endif\n')
     pp = CPreProcessor(f)
     self.assertEqual(pp.read().strip(),
                      'MY_DEFINE is not set\nPPVAR is set to SUCCESS')
     warnings.filterwarnings('error', category=PreProcessorWarning)
     f = StringIO('#define MYVAR something\nMYVAR\n#define MYVAR '
                  'something_else\nMYVAR')
     with CPreProcessor(f) as pp:
         self.assertRaises(PreProcessorWarning, pp.read)
     warnings.filterwarnings('ignore', category=PreProcessorWarning)
     f.seek(0)
     with CPreProcessor(f) as pp:
         self.assertEqual(pp.read().strip(), 'something\nsomething_else')
 def test_overload_level(self):
     """Test correct support for the overload_level attribute of
        ResidueTemplates and correct writing to XML tag"""
     params = openmm.OpenMMParameterSet.from_parameterset(
              pmd.amber.AmberParameterSet(get_fn('atomic_ions.lib'))
              )
     new_residues = OrderedDict()
     new_residues['K'] = params.residues['K']
     new_residues['NA'] = params.residues['NA']
     new_residues['K'].overload_level = 1
     params.residues = new_residues
     ffxml = StringIO()
     params.write(ffxml)
     ffxml.seek(0)
     output_lines = ffxml.readlines()
     control_line1 = '  <Residue name="K" overload="1">\n'
     control_line2 = '  <Residue name="NA">\n'
     self.assertEqual(output_lines[5], control_line1)
     self.assertEqual(output_lines[8], control_line2)
 def test_define(self):
     """ Tests CPreProcessor #define preprocessing """
     f = StringIO('#ifdef MY_DEFINE\nPPVAR is set to MY_DEFINE\n'
                  '#else\nMY_DEFINE is not set\n#endif\n'
                  '#define MY_DEFINE SUCCESS\n#ifdef MY_DEFINE\n'
                  'PPVAR is set to MY_DEFINE\n#else\nMY_DEFINE is not set\n'
                  '#endif\n')
     pp = CPreProcessor(f)
     self.assertEqual(pp.read().strip(),
                      'MY_DEFINE is not set\nPPVAR is set to SUCCESS')
     warnings.filterwarnings('error', category=PreProcessorWarning)
     f = StringIO('#define MYVAR something\nMYVAR\n#define MYVAR '
                  'something_else\nMYVAR')
     with CPreProcessor(f) as pp:
         self.assertRaises(PreProcessorWarning, pp.read)
     warnings.filterwarnings('ignore', category=PreProcessorWarning)
     f.seek(0)
     with CPreProcessor(f) as pp:
         self.assertEqual(pp.read().strip(), 'something\nsomething_else')
Beispiel #28
0
    def parse(filename):
        """
        Parses XML file and returns deserialized object. The return value
        depends on the serialized object, summarized below

            - System : returns simtk.openmm.System
            - State : returns simtk.openmm.State
            - Integrator : returns simtk.openmm.Integrator subclass
            - ForceField : returns simtk.openmm.app.ForceField

        Parameters
        ----------
        filename : str or file-like
            The file name or file object containing the XML-serialized object

        Returns
        -------
        obj : System, State, Integrator, or ForceField
            The deserialized object

        Notes
        -----
        OpenMM requires the entire contents of this file read into memory. As a
        result, this function may require a significant amount of memory.
        """
        import simtk.openmm as mm
        from simtk.openmm import app
        if isinstance(filename, string_types):
            with closing(genopen(filename, 'r')) as f:
                contents = f.read()
        else:
            contents = filename.read()
        # ForceField is not handled by XmlSerializer
        if '<ForceField' in contents:
            obj = StringIO()
            obj.write(contents)
            obj.seek(0)
            return app.ForceField(obj)

        obj = mm.XmlSerializer.deserialize(contents)
        if isinstance(obj, mm.State):
            return _OpenMMStateContents(obj)
        return obj
Beispiel #29
0
    def test_nested_ifs(self):
        """ Tests CPreProcessor nested #ifdef and #if """
        f = StringIO("""
#ifdef MY_VAR
line 1
#   if 1
line 2
#   endif /* 1 */
#else /* ! MY_VAR */
#   if 0
line 3
#   else /* ! 0 */
line 4
#   endif /* 0 */
#endif /* MY_VAR */
""")
        pp = CPreProcessor(f)
        self.assertEqual(pp.read().strip(), "line 4")
        f.seek(0)
        pp = CPreProcessor(f, defines=dict(MY_VAR=1))
        self.assertEqual(pp.read().strip(), "line 1\nline 2")
Beispiel #30
0
 def testPdbWriteAltlocOptions(self):
     """ Test PDB file writing with different altloc options """
     pdbfile = read_PDB(self.pdb)
     self._check4lzt(pdbfile)
     output = StringIO()
     pdbfile.write_pdb(output, renumber=False, altlocs='all')
     output.seek(0)
     pdbfile2 = read_PDB(output)
     self._check4lzt(pdbfile2, check_meta=False)
     self._compareInputOutputPDBs(pdbfile, pdbfile2)
     # Check that 'first' option works
     output = reset_stringio(output)
     pdbfile.write_pdb(output, renumber=False, altlocs='first')
     output.seek(0)
     pdbfile3 = read_PDB(output)
     self._check4lzt(pdbfile3, check_meta=False, has_altloc=False)
     self._compareInputOutputPDBs(pdbfile, pdbfile3, altloc_option='first')
     # Check that the 'occupancy' option works
     output = reset_stringio(output)
     write_PDB(pdbfile, output, renumber=False, altlocs='occupancy')
     output.seek(0)
     pdbfile4 = read_PDB(output)
     self._check4lzt(pdbfile4, check_meta=False, has_altloc=False)
     self._compareInputOutputPDBs(pdbfile, pdbfile4, altloc_option='occupancy')
     # Double-check 'first' vs. 'occupancy'. Residue 85 (SER) has a conformer
     # A that has an occupancy of 0.37 and conformer B with occupancy 0.63
     self.assertEqual(pdbfile3.residues[84][4].xx, -4.162)
     self.assertEqual(pdbfile4.residues[84][4].xx, -4.157)
Beispiel #31
0
 def testMol2MultiWrite(self):
     """
     Tests writing mol2 file of multi residues from ResidueTemplateContainer
     """
     mol2 = formats.Mol2File.parse(get_fn('test_multi.mol2'))
     formats.Mol2File.write(mol2, get_fn('test_multi.mol2', written=True))
     formats.Mol2File.write(mol2, get_fn('test_multi_sep.mol2', written=True),
                            split=True)
     self.assertTrue(diff_files(get_saved_fn('test_multi.mol2'),
                                get_fn('test_multi.mol2', written=True)))
     self.assertTrue(diff_files(get_saved_fn('test_multi_sep.mol2'),
                                get_fn('test_multi_sep.mol2', written=True)))
     mol22 = formats.Mol2File.parse(get_fn('test_multi_sep.mol2', written=True))
     self.assertEqual(len(mol2), len(mol22))
     self.assertEqual([r.name for r in mol2], [r.name for r in mol22])
     for r1, r2 in zip(mol2, mol22):
         self.assertEqual(len(r1.bonds), len(r2.bonds))
         self.assertEqual(len(r1.atoms), len(r2.atoms))
         self.assertFalse(r1.head is None and r1.tail is None)
         self.assertTrue(r2.head is None and r2.tail is None)
     f = StringIO()
     formats.Mol2File.write(mol2, f, mol3=True, split=True)
     f.seek(0)
     mol3 = formats.Mol2File.parse(f)
     self.assertEqual(len(mol2), len(mol3))
     self.assertEqual([r.name for r in mol2], [r.name for r in mol3])
     for r1, r2 in zip(mol2, mol3):
         self.assertEqual(len(r1.bonds), len(r2.bonds))
         self.assertEqual(len(r1.atoms), len(r2.atoms))
         self.assertFalse(r1.head is None and r1.tail is None)
         self.assertFalse(r2.head is None and r2.tail is None)
         if r1.head is None:
             self.assertIs(r2.head, None)
         else:
             self.assertEqual(r1.head.name, r2.head.name)
         if r1.tail is None:
             self.assertIs(r2.tail, None)
         else:
             self.assertEqual(r1.tail.name, r2.tail.name)
    def test_gromacs_file(self):
        """ Test GromacsFile helper class """
        f = StringIO('This is the first line \\\n  this is still the first line'
                     '\nThis is the second line')
        gf = GromacsFile(f)
        self.assertEqual(gf.readline(), 'This is the first line    this is '
                         'still the first line\n')
        self.assertEqual(gf.readline(), 'This is the second line')
        self.assertEqual(gf.readline(), '')
        f.seek(0)
        lines = [line for line in gf]
        self.assertEqual(lines[0], 'This is the first line    this is '
                         'still the first line\n')
        self.assertEqual(lines[1], 'This is the second line')

        # Try with comments now
        f = StringIO('This is the first line \\\n  this is still the first line'
                     ' ; and this is a comment\nThis is the second line ; and '
                     'this is also a comment')
        gf = GromacsFile(f)
        self.assertEqual(gf.readline(), 'This is the first line    this is still'
                         ' the first line \n')
        self.assertEqual(gf.readline(), 'This is the second line \n')
        f.seek(0)
        lines = [line for line in gf]
        self.assertEqual(lines[0], 'This is the first line    this is still'
                         ' the first line \n')
        self.assertEqual(lines[1], 'This is the second line \n')
        f.seek(0)
        lines = gf.readlines()
        self.assertEqual(lines[0], 'This is the first line    this is still'
                         ' the first line \n')
        self.assertEqual(lines[1], 'This is the second line \n')
        f.seek(0)
        self.assertEqual(gf.read(), 'This is the first line    this is still'
                         ' the first line \nThis is the second line \n')

        # Error handling
        self.assertRaises(IOError, lambda:
                GromacsFile('some_file that does_not exist'))
    def test_nested_ifs(self):
        """ Tests CPreProcessor nested #ifdef and #if """
        f = StringIO("""
#ifdef MY_VAR
line 1
#   if 1
line 2
#   endif /* 1 */
#else /* ! MY_VAR */
#   if 0
line 3
#   else /* ! 0 */
line 4
#   endif /* 0 */
#endif /* MY_VAR */
""")
        pp = CPreProcessor(f)
        self.assertEqual(pp.read().strip(), "line 4")
        f.seek(0)
        pp = CPreProcessor(f, defines=dict(MY_VAR=1))
        self.assertEqual(pp.read().strip(), "line 1\nline 2")
        f = StringIO("""
#ifdef MY_VAR
#   ifndef MY_VAR_2
MY_VAR defined... MY_VAR_2 not
#   else
MY_VAR defined... MY_VAR_2 also
#   endif
#endif
""")
        pp = CPreProcessor(f)
        self.assertEqual(pp.read().strip(), '')
        f.seek(0)
        pp = CPreProcessor(f, defines=dict(MY_VAR=1))
        self.assertEqual(pp.read().strip(), '1 defined... MY_VAR_2 not')
        f.seek(0)
        pp = CPreProcessor(f, defines=dict(MY_VAR=1, MY_VAR_2=2))
        self.assertEqual(pp.read().strip(), '1 defined... 2 also')
    def test_nested_ifs(self):
        """ Tests CPreProcessor nested #ifdef and #if """
        f = StringIO("""
#ifdef MY_VAR
line 1
#   if 1
line 2
#   endif /* 1 */
#else /* ! MY_VAR */
#   if 0
line 3
#   else /* ! 0 */
line 4
#   endif /* 0 */
#endif /* MY_VAR */
""")
        pp = CPreProcessor(f)
        self.assertEqual(pp.read().strip(), "line 4")
        f.seek(0)
        pp = CPreProcessor(f, defines=dict(MY_VAR=1))
        self.assertEqual(pp.read().strip(), "line 1\nline 2")
        f = StringIO("""
#ifdef MY_VAR
#   ifndef MY_VAR_2
MY_VAR defined... MY_VAR_2 not
#   else
MY_VAR defined... MY_VAR_2 also
#   endif
#endif
""")
        pp = CPreProcessor(f)
        self.assertEqual(pp.read().strip(), '')
        f.seek(0)
        pp = CPreProcessor(f, defines=dict(MY_VAR=1))
        self.assertEqual(pp.read().strip(), '1 defined... MY_VAR_2 not')
        f.seek(0)
        pp = CPreProcessor(f, defines=dict(MY_VAR=1, MY_VAR_2=2))
        self.assertEqual(pp.read().strip(), '1 defined... 2 also')
Beispiel #35
0
    def testWriteCIF(self):
        """ Test CIF writing capabilities """
        cif = read_CIF(self.lzt)
        written = get_fn('test.cif', written=True)
        cif.write_cif(written, renumber=False, write_anisou=True)
        cif2 = read_CIF(written)
        # cif and cif2 should have equivalent atom properties (basically,
        # everything should be the same except the metadata)
        self.assertEqual(len(cif.atoms), len(cif2.atoms))
        self.assertEqual(len(cif.residues), len(cif2.residues))

        # Check residue properties
        for res1, res2 in zip(cif.residues, cif2.residues):
            self.assertEqual(len(res1), len(res2))
            self.assertEqual(res1.name, res2.name)
            self.assertEqual(res1.chain, res2.chain)
            self.assertEqual(res1.insertion_code, res2.insertion_code)
            self.assertEqual(res1.number, res2.number)

        # Check atom properties
        for a1, a2 in zip(cif.atoms, cif2.atoms):
            self.assertEqual(a1.name, a2.name)
            self.assertEqual(a1.number, a2.number)
            self.assertEqual(a1.element, a2.element)
            self.assertEqual(a1.altloc, a2.altloc)
            self.assertEqual(a1.xx, a2.xx)
            self.assertEqual(a1.xy, a2.xy)
            self.assertEqual(a1.xz, a2.xz)
            self.assertEqual(len(a1.anisou), 6)
            self.assertEqual(len(a2.anisou), 6)
            for x, y in zip(a1.anisou, a2.anisou):
                self.assertEqual(x, y)

        # Check box
        self.assertEqual(len(cif.box), len(cif2.box))
        for x, y in zip(cif.box, cif2.box):
            self.assertEqual(x, y)

        # Now check CIF writing without anisotropic B-factors and with
        # renumbering
        io = StringIO()
        cif.write_cif(io)
        io.seek(0)
        cif3 = read_CIF(io)
        # cif and cif3 should have equivalent atom properties (basically,
        # everything should be the same except the metadata)
        self.assertEqual(len(cif.atoms), len(cif3.atoms))
        self.assertEqual(len(cif.residues), len(cif3.residues))

        # Check residue properties
        i = 1
        for res1, res2 in zip(cif.residues, cif3.residues):
            self.assertEqual(len(res1), len(res2))
            self.assertEqual(res1.name, res2.name)
            self.assertEqual(res1.chain, res2.chain)
            self.assertEqual(res1.insertion_code, res2.insertion_code)
            self.assertEqual(res2.number, i)
            i += 1

        # Check atom properties
        i = 1
        for a1, a2 in zip(cif.atoms, cif3.atoms):
            self.assertEqual(a1.name, a2.name)
            self.assertEqual(a2.number, i)
            self.assertEqual(a1.element, a2.element)
            self.assertEqual(a1.altloc, a2.altloc)
            self.assertEqual(a1.xx, a2.xx)
            self.assertEqual(a1.xy, a2.xy)
            self.assertEqual(a1.xz, a2.xz)
            self.assertIs(a2.anisou, None)
            i += 1 + len(a2.other_locations)

        # Check box
        self.assertEqual(len(cif.box), len(cif3.box))
        for x, y in zip(cif.box, cif3.box):
            self.assertEqual(x, y)