Ejemplo n.º 1
0
def run_propka(options, pdb_path, tmp_path):
    """Run PROPKA software.

    Args:
        options:  list of PROPKA options
        pdb_path:  path to PDB file
        tmp_path:  path for working directory
    """
    options += [str(pdb_path)]
    args = loadOptions(options)
    try:
        _LOGGER.warning(
            "Working in tmpdir {0:s} because of PROPKA file output; "
            "need to fix this.".format(str(tmp_path)))
        cwd = Path.cwd()
        os.chdir(tmp_path)
        parameters = read_parameter_file(args.parameters, Parameters())
        molecule = MolecularContainer(parameters, args)
        molecule = read_molecule_file(str(pdb_path), molecule)
        molecule.calculate_pka()
        molecule.write_pka()
        if args.generate_propka_input:
            molecule.write_propka()
    finally:
        os.chdir(cwd)
Ejemplo n.º 2
0
def single(pdbfile, optargs=None):
    """Run a single PROPKA calculation using *pdbfile* as input.

    Commandline options can be passed as a **list** in *optargs*.

    Example
    -------
    Given an input file "protein.pdb", run the equivalent of ``propka3
    --mutation=N25R/N181D -v --pH=7.2 protein.pdb`` as::

       propka.run.single("protein.pdb",
                         optargs=["--mutation=N25R/N181D", "-v", "--pH=7.2"])


    .. todo::
       Test :func:`single`, not sure if it is correctly processing ``pdbfile``.

    """
    optargs = optargs if optargs is not None else []
    options = loadOptions(*optargs)
    pdbfile = options.filenames.pop(0)
    parameters = read_parameter_file(options.parameters, Parameters())
    if len(options.filenames) > 0:
        _LOGGER.warning("Ignoring filenames: {0:s}".format(options.filenames))
    my_molecule = MolecularContainer(parameters, options)
    my_molecule = read_molecule_file(pdbfile, my_molecule)
    my_molecule.calculate_pka()
    my_molecule.write_pka()
    if options.generate_propka_input:
        my_molecule.write_propka()
    return my_molecule
Ejemplo n.º 3
0
def main(optargs=None):
    """Read in structure files, calculate pKa values, and print pKa files."""
    # loading options, flags and arguments
    optargs = optargs if optargs is not None else []
    options = loadOptions(*optargs)
    pdbfiles = options.filenames
    parameters = read_parameter_file(options.parameters, Parameters())
    for pdbfile in pdbfiles:
        my_molecule = MolecularContainer(parameters, options)
        my_molecule = read_molecule_file(pdbfile, my_molecule)
        my_molecule.calculate_pka()
        my_molecule.write_pka()
        if options.generate_propka_input:
            my_molecule.write_propka()
Ejemplo n.º 4
0
def run_propka_stream(options, input_file, filename):
    """Run PROPKA software.

    Args:
        options:  list of PROPKA options
        input_file:  file-like PDB object
        filename: filename for the file-like PDB object
    """
    options += [filename]
    args = loadOptions(options)
    parameters = read_parameter_file(args.parameters, Parameters())
    molecule = MolecularContainer(parameters, args)
    molecule = read_molecule_file(filename, molecule, stream=input_file)
    molecule.calculate_pka()
    molecule.write_pka()
Ejemplo n.º 5
0
def main(optargs=None):
    """Read in structure files, calculate pKa values, and print pKa files.


    .. versionchanged:: 3.4.0
       Removed ability to write out PROPKA input files.
    """
    # loading options, flags and arguments
    logger = logging.getLogger("")
    stdout_handler = logging.StreamHandler(sys.stdout)
    stdout_handler.setFormatter(logging.Formatter("%(message)s"))
    logger.addHandler(stdout_handler)
    optargs = optargs if optargs is not None else []
    options = loadOptions(*optargs)
    pdbfiles = options.filenames
    parameters = read_parameter_file(options.parameters, Parameters())
    for pdbfile in pdbfiles:
        my_molecule = MolecularContainer(parameters, options)
        my_molecule = read_molecule_file(pdbfile, my_molecule)
        my_molecule.calculate_pka()
        my_molecule.write_pka()
Ejemplo n.º 6
0
def single(pdbfile, optargs=None):
    """Run a single PROPKA calculation using *pdbfile* as input.

    Commandline options can be passed as a **list** in *optargs*.

    .. rubric:: Example

    ::
       single("protein.pdb", optargs=["--mutation=N25R/N181D", "-v",
              "--pH=7.2"])
    """
    optargs = optargs if optargs is not None else []
    options = loadOptions(*optargs)
    pdbfile = options.filenames.pop(0)
    parameters = read_parameter_file(options.parameters, Parameters())
    if len(options.filenames) > 0:
        _LOGGER.warning("Ignoring filenames: {0:s}".format(options.filenames))
    my_molecule = MolecularContainer(parameters, options)
    my_molecule = read_molecule_file(pdbfile, my_molecule)
    my_molecule.calculate_pka()
    my_molecule.write_pka()
    if options.generate_propka_input:
        my_molecule.write_propka()
    return my_molecule
Ejemplo n.º 7
0
def protonate_propka(self, pH = 7.0):
    """
    Protonate a protein with PROPKA 3.1.

    :param pH: desired pH for protein protonation
    :type pH: float
    """

    import os
    import sys
    import  StringIO

    import propka.lib as plib
    import FESetup.propka.newmc as pmc

    PROT_RES = ('HIS', 'ASP', 'GLU')
    DEPROT_RES = ('LYS', 'CYS', 'ARG', 'TYR')

    # add PDB file name to options to avoid warning of missing file, also
    # set config file path to module path to find propka.cfg
    options, dummy = plib.loadOptions( ['--pH', pH, '-q', self.mol_file] )
    options.parameters = os.path.join(os.path.dirname(pmc.__file__),
                                      options.parameters)

    with CaptureOutput() as output:
        mol = pmc.Molecular_container_new(self.mol_file, options)
        pKas = mol.calculate_pka()

    logger.write('%s%s' % (output[0], output[1]) )

    protres = []

    for resName, resSeq, chainID, pKa in pKas:
        # NOTE: currently we ignore termini 'N+' and 'C-'
        if pH < pKa:
            if resName in PROT_RES:
                protres.append( (resName, resSeq, chainID) )
        else:
            if resName in DEPROT_RES:
                protres.append( (resName, resSeq, chainID) )

    logger.write('pH = %.2f' % pH)

    msg_res = set()

    with open(const.PROTONATED_PDB_FILE, 'w') as newfile:
        with open(self.mol_file, 'r') as pdbfile:
            for line in pdbfile:
                if line[:6] in ('ATOM  ', 'HETATM'):
                    resName = line[17:21].strip()
                    resSeq = int(line[22:26])
                    chainID = line[20:22].strip()

                    if (resName, resSeq, chainID) in protres:
                        msg_res.add( (resName, resSeq, chainID) )
                        newfile.write(line[:17] +
                                      '{:3s} '.format(self.PROT_MAP[resName]) +
                                      line[21:])
                    else:
                        newfile.write(line)

    for resName, resSeq, chainID in msg_res:
        logger.write('Changing %s %i %s to %s' %
                          (resName, resSeq, chainID, self.PROT_MAP[resName]) )

    self.mol_file = const.PROTONATED_PDB_FILE
Ejemplo n.º 8
0
def pdb2pqrTransform(filename, **kwargs):
    """
    A thin wrapper around PDB2PQR which protonates an input PDB file.

    Parameters
    ----------
    filename : str
        Name of input file.
    kwargs:
        Keyword arguments to be passed on to PDB2PQR. Supported arguments are:

        ph:
            The desired ph of the system (float).
        verbose:
            Whether all information is output to the logger.
        ph_calc_method:
            pKa calculation method (None, "propka","propka31","pdb2pka").
        ph_calc_options:
            optionParser like option object for propka30.
        neutraln:
            Make the N-terminus of this protein neutral
        neutralc:
            Make the C-terminus of this protein neutral
        assign_only:
            Only assign charges and radii - do not add atoms, debump, or optimize.
        drop_water:
            Remove water molecules from output.
        debump:
            When 1, debump heavy atoms (int).
        opt:
            When 1, run hydrogen optimization (int).
        include_old_header:
            Include most of the PDB header in output.
        holdlist:
            A list of residues not to be optimized, as [(resid, chain, icode)].

    Returns
    -------
    filename : str
        Absolute path to the protonated file.
    """

    default_kwargs = {
        'chain': True,
        'ff': 'amber',
        'ffout': 'amber',
        'verbose': True,
        'drop_water': True,
        'ph': 7,
        'ph_calc_method': 'propka31',
        'ph_calc_options': _lib.loadOptions('--quiet')[0]
    }

    default_kwargs = {**default_kwargs, **kwargs}

    _logging.basicConfig(stream=_sys.stdout)
    _logging.write = lambda msg: _logging.info(msg.strip()) \
        if msg.strip() else None
    with _redirect_stdout(_logging):
        pdb = _readPDB(open(filename))[0]
        pdb = _runPDB2PQR(pdb, **default_kwargs)

    filename_output = _os.path.splitext(filename)[0] + "_pdb2pqr.pdb"
    with open(filename_output, "w") as f:
        for line in pdb['lines']:
            f.write(line)

    return fixPdb2pqrPDB(filename_output, filename, filename_output)
Ejemplo n.º 9
0
def single(file, optargs: tuple = (), write_pka: bool = True):
    """Run a single PROPKA calculation using ``filename`` as input.

    Args:
        filename (str): name of input file. If filestream is not passed via
            ``stream``, should be a path to the file to be read.
        optargs (tuple): Optional, commandline options for propka. Extra files
            passed via ``optargs`` will be ignored, see Notes.
        stream : optional filestream handle. If ``None``, then ``filename``
            will be used as path to input file for reading.
        write_pka (bool): Controls if the pKa file should be writen to disk.

    Returns:
        :class:`~propka.molecular_container.MolecularContainer` object.

    Examples:
        Given an input file "protein.pdb", run the equivalent of ``propka3
        --mutation=N25R/N181D -v --pH=7.2 protein.pdb`` as::

            propka.run.single("protein.pdb", 
                optargs=["--mutation=N25R/N181D", "-v", "--pH=7.2"])

        By default, a pKa file will be written. However in some cases one may
        wish to not output this file and just have access to the
        :class:`~propka.molecular_container.MolecularContainer` object. If so,
        then pass ``False`` to ``write_pka``::

            mol = propka.run.single("protein.pdb", write_pka=False)

        In some cases, one may also want to pass a file-like (e.g.
        :class:`io.StringIO`) object instead of a file path as a string. In
        these cases the file-like object should be passed to the ``stream``
        argument and a string indicating the file type in the ``filename``
        argument; this string only has to look like a valid file name, it does
        not need to exist because the data are actually read from ``stream``.
        This approach is necessary because file-like objects do not usually
        have names, and propka uses the ``filename`` argument  to determine the
        input file type, and assigns the file name for the
        :class:`~propka.molecular_container.MolecularContainer` object::

            mol = propka.run.single('input.pdb', stream=string_io_file)

        In this case, a PDB file-like object was passed as `string_io_file`.
        The resultant pKa file will be written out as `input.pka`.

    Notes:
        * Only a single input structure file will be processed, defined by
          ``filename`` (and ``stream`` if passing a file-like object). Any
          additional files passed via the `-f` or `--file` flag to optargs will
          be ignored.


    .. seealso::

        :func:`propka.input.read_molecule_file`

    """
    # Deal with input optarg options
    optargs = tuple(optargs)
    optargs += (filename,)
    options = loadOptions(optargs)

    parameters = read_parameter_file(options.parameters, Parameters())

    # Only filename present should be the one passed via the arguments
    # Anything else will probably have been passed using optargs' `-f` flag.
    ignored_list = [i for i in options.filenames if i != filename]
    if ignored_list:
        _LOGGER.warning(f"Ignoring extra filenames passed: {ignored_list}")
    options.filenames = [filename]

    my_molecule = MolecularContainer(parameters, options)
    my_molecule = read_molecule_file(file, my_molecule)
    my_molecule.calculate_pka()

    # write outputs
    if options.generate_propka_input:
        my_molecule.write_propka()
    if write_pka:
        my_molecule.write_pka()

    return my_molecule