Пример #1
0
    def save(self, fname, format=None, overwrite=False, **kwargs):
        """
        Saves the current ResidueTemplate in the requested file format.
        Supported formats can be specified explicitly or determined by file-name
        extension. The following formats are supported, with the recognized
        suffix shown in parentheses:

            - MOL2 (.mol2)
            - MOL3 (.mol3)
            - OFF (.lib/.off)
            - PDB (.pdb)
            - PQR (.pqr)

        Parameters
        ----------
        fname : str
            Name of the file to save. If ``format`` is ``None`` (see below), the
            file type will be determined based on the filename extension. If the
            type cannot be determined, a ValueError is raised.
        format : str, optional
            The case-insensitive keyword specifying what type of file ``fname``
            should be saved as. If ``None`` (default), the file type will be
            determined from filename extension of ``fname``
        overwrite : bool, optional
            If True, allow the target file to be overwritten. Otherwise, an
            IOError is raised if the file exists. Default is False
        kwargs : keyword-arguments
            Remaining arguments are passed on to the file writing routines that
            are called by this function

        Raises
        ------
        ValueError if either filename extension or ``format`` are not recognized
        TypeError if the structure cannot be converted to the desired format for
        whatever reason
        """
        from parmed.amber.offlib import AmberOFFLibrary
        from parmed.formats.mol2 import Mol2File

        extmap = {".mol2": "MOL2", ".mol3": "MOL3", ".off": "OFFLIB", ".lib": "OFFLIB", ".pdb": "PDB", ".pqr": "PQR"}
        if format is not None:
            format = format.upper()
        else:
            base, ext = os.path.splitext(fname)
            if ext in (".bz2", ".gz"):
                ext = os.path.splitext(base)[1]
            if ext in extmap:
                format = extmap[ext]
            else:
                raise ValueError("Could not determine file type of %s" % fname)
        if format == "MOL2":
            Mol2File.write(self, fname, mol3=False, **kwargs)
        elif format == "MOL3":
            Mol2File.write(self, fname, mol3=True, **kwargs)
        elif format in ("OFFLIB", "OFF"):
            AmberOFFLibrary.write({self.name: self}, fname, **kwargs)
        elif format in ("PDB", "PQR"):
            self.to_structure().save(fname, format=format, overwrite=overwrite, **kwargs)
        else:
            raise ValueError("Unrecognized format for ResidueTemplate save")
Пример #2
0
    def save(self, fname, format=None, **kwargs):
        """
        Saves the current ResidueTemplateContainer in the requested file format.
        Supported formats can be specified explicitly or determined by file-name
        extension. The following formats are supported, with the recognized
        suffix and ``format`` keyword shown in parentheses:

            - MOL2 (.mol2)
            - MOL3 (.mol3)
            - OFF (.lib/.off)

        Parameters
        ----------
        fname : str
            Name of the file to save. If ``format`` is ``None`` (see below), the
            file type will be determined based on the filename extension. If the
            type cannot be determined, a ValueError is raised.
        format : str, optional
            The case-insensitive keyword specifying what type of file ``fname``
            should be saved as. If ``None`` (default), the file type will be
            determined from filename extension of ``fname``
        kwargs : keyword-arguments
            Remaining arguments are passed on to the file writing routines that
            are called by this function

        Raises
        ------
        ValueError if either filename extension or ``format`` are not recognized
        TypeError if the structure cannot be converted to the desired format for
        whatever reason

        Notes
        -----
        Mol2 and Mol3 files are saved as concatenated multiple @<MOLECULE>s. By
        contrast, ``Structure.save`` will save a single @<MOLECULE> mol2 file
        with multiple residues if the mol2 format is requested.
        """
        from parmed.amber.offlib import AmberOFFLibrary
        from parmed.formats.mol2 import Mol2File

        extmap = {".mol2": "MOL2", ".mol3": "MOL3", ".off": "OFFLIB", ".lib": "OFFLIB"}
        if format is not None:
            format = format.upper()
        else:
            base, ext = os.path.splitext(fname)
            if ext in (".bz2", ".gz"):
                ext = os.path.splitext(base)[1]
            if ext in extmap:
                format = extmap[ext]
            else:
                raise ValueError("Could not determine file type of %s" % fname)
        if format == "MOL2":
            Mol2File.write(self, fname, mol3=False, split=True, **kwargs)
        elif format == "MOL3":
            Mol2File.write(self, fname, mol3=True, split=True, **kwargs)
        elif format in ("OFFLIB", "OFF"):
            AmberOFFLibrary.write(self.to_library(), fname, **kwargs)
        else:
            raise ValueError("Unrecognized format for ResidueTemplate save")
Пример #3
0
    def save(self, fname, format=None, **kwargs):
        """
        Saves the current ResidueTemplate in the requested file format.
        Supported formats can be specified explicitly or determined by file-name
        extension. The following formats are supported, with the recognized
        suffix and ``format`` keyword shown in parentheses:

            - MOL2 (.mol2)
            - MOL3 (.mol3)
            - OFF (.lib/.off)

        Parameters
        ----------
        fname : str
            Name of the file to save. If ``format`` is ``None`` (see below), the
            file type will be determined based on the filename extension. If the
            type cannot be determined, a ValueError is raised.
        format : str, optional
            The case-insensitive keyword specifying what type of file ``fname``
            should be saved as. If ``None`` (default), the file type will be
            determined from filename extension of ``fname``
        kwargs : keyword-arguments
            Remaining arguments are passed on to the file writing routines that
            are called by this function

        Raises
        ------
        ValueError if either filename extension or ``format`` are not recognized
        TypeError if the structure cannot be converted to the desired format for
        whatever reason
        """
        from parmed.modeller.offlib import AmberOFFLibrary
        from parmed.formats.mol2 import Mol2File
        extmap = {
                '.mol2' : 'MOL2',
                '.mol3' : 'MOL3',
                '.off' : 'OFFLIB',
                '.lib' : 'OFFLIB',
        }
        if format is not None:
            format = format.upper()
        else:
            base, ext = os.path.splitext(fname)
            if ext in ('.bz2', '.gz'):
                ext = os.path.splitext(base)[1]
            if ext in extmap:
                format = extmap[ext]
            else:
                raise ValueError('Could not determine file type of %s' % fname)
        if format == 'MOL2':
            Mol2File.write(self, fname, mol3=False, **kwargs)
        elif format == 'MOL3':
            Mol2File.write(self, fname, mol3=True, **kwargs)
        elif format in ('OFFLIB', 'OFF'):
            AmberOFFLibrary.write({self.name : self}, fname, **kwargs)
        else:
            raise ValueError('Unrecognized format for ResidueTemplate save')
Пример #4
0
    def save(self, fname, format=None, **kwargs):
        """
        Saves the current ResidueTemplateContainer in the requested file format.
        Supported formats can be specified explicitly or determined by file-name
        extension. The following formats are supported, with the recognized
        suffix and ``format`` keyword shown in parentheses:

            - MOL2 (.mol2)
            - MOL3 (.mol3)
            - OFF (.lib/.off)

        Parameters
        ----------
        fname : str
            Name of the file to save. If ``format`` is ``None`` (see below), the
            file type will be determined based on the filename extension. If the
            type cannot be determined, a ValueError is raised.
        format : str, optional
            The case-insensitive keyword specifying what type of file ``fname``
            should be saved as. If ``None`` (default), the file type will be
            determined from filename extension of ``fname``
        kwargs : keyword-arguments
            Remaining arguments are passed on to the file writing routines that
            are called by this function

        Raises
        ------
        ValueError if either filename extension or ``format`` are not recognized
        TypeError if the structure cannot be converted to the desired format for
        whatever reason

        Notes
        -----
        Mol2 and Mol3 files are saved as concatenated multiple @<MOLECULE>s. By
        contrast, ``Structure.save`` will save a single @<MOLECULE> mol2 file
        with multiple residues if the mol2 format is requested.
        """
        from parmed.amber.offlib import AmberOFFLibrary
        from parmed.formats.mol2 import Mol2File
        extmap = {
            '.mol2': 'MOL2',
            '.mol3': 'MOL3',
            '.off': 'OFFLIB',
            '.lib': 'OFFLIB',
        }
        if format is not None:
            format = format.upper()
        else:
            base, ext = os.path.splitext(fname)
            if ext in ('.bz2', '.gz'):
                ext = os.path.splitext(base)[1]
            if ext in extmap:
                format = extmap[ext]
            else:
                raise ValueError('Could not determine file type of %s' % fname)
        if format == 'MOL2':
            Mol2File.write(self, fname, mol3=False, split=True, **kwargs)
        elif format == 'MOL3':
            Mol2File.write(self, fname, mol3=True, split=True, **kwargs)
        elif format in ('OFFLIB', 'OFF'):
            AmberOFFLibrary.write(self.to_library(), fname, **kwargs)
        else:
            raise ValueError('Unrecognized format for ResidueTemplate save')
Пример #5
0
    def save(self, fname, format=None, overwrite=False, **kwargs):
        """
        Saves the current ResidueTemplate in the requested file format.
        Supported formats can be specified explicitly or determined by file-name
        extension. The following formats are supported, with the recognized
        suffix shown in parentheses:

            - MOL2 (.mol2)
            - MOL3 (.mol3)
            - OFF (.lib/.off)
            - PDB (.pdb)
            - PQR (.pqr)

        Parameters
        ----------
        fname : str
            Name of the file to save. If ``format`` is ``None`` (see below), the
            file type will be determined based on the filename extension. If the
            type cannot be determined, a ValueError is raised.
        format : str, optional
            The case-insensitive keyword specifying what type of file ``fname``
            should be saved as. If ``None`` (default), the file type will be
            determined from filename extension of ``fname``
        overwrite : bool, optional
            If True, allow the target file to be overwritten. Otherwise, an
            IOError is raised if the file exists. Default is False
        kwargs : keyword-arguments
            Remaining arguments are passed on to the file writing routines that
            are called by this function

        Raises
        ------
        ValueError if either filename extension or ``format`` are not recognized
        TypeError if the structure cannot be converted to the desired format for
        whatever reason
        """
        from parmed.amber.offlib import AmberOFFLibrary
        from parmed.formats.mol2 import Mol2File
        extmap = {
            '.mol2': 'MOL2',
            '.mol3': 'MOL3',
            '.off': 'OFFLIB',
            '.lib': 'OFFLIB',
            '.pdb': 'PDB',
            '.pqr': 'PQR',
        }
        if format is not None:
            format = format.upper()
        else:
            base, ext = os.path.splitext(fname)
            if ext in ('.bz2', '.gz'):
                ext = os.path.splitext(base)[1]
            if ext in extmap:
                format = extmap[ext]
            else:
                raise ValueError('Could not determine file type of %s' % fname)
        if format == 'MOL2':
            Mol2File.write(self, fname, mol3=False, **kwargs)
        elif format == 'MOL3':
            Mol2File.write(self, fname, mol3=True, **kwargs)
        elif format in ('OFFLIB', 'OFF'):
            AmberOFFLibrary.write({self.name: self}, fname, **kwargs)
        elif format in ('PDB', 'PQR'):
            self.to_structure().save(fname,
                                     format=format,
                                     overwrite=overwrite,
                                     **kwargs)
        else:
            raise ValueError('Unrecognized format for ResidueTemplate save')
Пример #6
0
    def from_leaprc(cls, fname, search_oldff=False):
        """ Load a parameter set from a leaprc file

        Parameters
        ----------
        fname : str or file-like
            Name of the file or open file-object from which a leaprc-style file
            will be read

        search_oldff : bool, optional, default=False
            If True, search the oldff directories in the main Amber leap
            folders. Default is False

        Notes
        -----
        This does not read all parts of a leaprc file -- only those pertinent to
        defining force field information. For instance, the following sections
        and commands are processed:

        - addAtomTypes
        - loadAmberParams
        - loadOFF
        - loadMol2
        - loadMol3
        """
        params = cls()
        if isinstance(fname, string_types):
            f = genopen(fname, 'r')
            own_handle = True
        else:
            f = fname
            own_handle = False
        # To make parsing easier, and because leaprc files are usually quite
        # short, I'll read the whole file into memory
        def joinlines(lines):
            newlines = []
            composite = []
            for line in lines:
                if line.endswith('\\\n'):
                    composite.append(line[:-2])
                    continue
                else:
                    composite.append(line)
                newlines.append(''.join(composite))
                composite = []
            if composite:
                newlines.append(''.join(composite))
            return newlines
        lines = joinlines(map(lambda line:
                    line if '#' not in line else line[:line.index('#')], f))
        text = ''.join(lines)
        if own_handle: f.close()
        lowertext = text.lower() # commands are case-insensitive
        # Now process the parameter files
        def process_fname(fname):
            if fname[0] in ('"', "'"):
                fname = fname[1:-1]
            fname = fname.replace('_BSTOKEN_', r'\ ').replace(r'\ ', ' ')
            return fname
        for line in lines:
            line = line.replace(r'\ ', '_BSTOKEN_')
            if _loadparamsre.findall(line):
                fname = process_fname(_loadparamsre.findall(line)[0])
                params.load_parameters(_find_amber_file(fname, search_oldff))
            elif _loadoffre.findall(line):
                fname = process_fname(_loadoffre.findall(line)[0])
                params.residues.update(
                    AmberOFFLibrary.parse(_find_amber_file(fname, search_oldff))
                )
            elif _loadmol2re.findall(line):
                (resname, fname), = _loadmol2re.findall(line)
                residue = Mol2File.parse(_find_amber_file(fname, search_oldff))
                if isinstance(residue, ResidueTemplateContainer):
                    warnings.warn('Multi-residue mol2 files not supported by '
                                  'tleap. Loading anyway using names in mol2',
                                  AmberWarning)
                    for res in residue:
                        params.residues[res.name] = res
                else:
                    params.residues[resname] = residue
        # Now process the addAtomTypes
        try:
            idx = lowertext.index('addatomtypes')
        except ValueError:
            # Does not exist in this file
            atom_types_str = ''
        else:
            i = idx + len('addatomtypes')
            while i < len(text) and text[i] != '{':
                if text[i] not in '\r\n\t ':
                    raise ParameterError('Unsupported addAtomTypes syntax in '
                                         'leaprc file')
                i += 1
            if i == len(text):
                raise ParameterError('Unsupported addAtomTypes syntax in '
                                     'leaprc file')
            # We are at our first brace
            chars = []
            nopen = 1
            i += 1
            while i < len(text):
                char = text[i]
                if char == '{':
                    nopen += 1
                elif char == '}':
                    nopen -= 1
                    if nopen == 0: break
                elif char == '\n':
                    char = ' '
                chars.append(char)
                i += 1
            atom_types_str = ''.join(chars).strip()
        for _, name, symb, hyb in _atomtypere.findall(atom_types_str):
            if symb not in AtomicNum:
                raise ParameterError('%s is not a recognized element' % symb)
            if name in params.atom_types:
                params.atom_types[name].atomic_number = AtomicNum[symb]
        return params