Exemple #1
0
def select_chain(molecule, chain_id):
    """
    Select a chain from an OpenEye molecule.

    Parameters
    ----------
    molecule: oechem.OEGraphMol
        An OpenEye molecule holding a molecular structure.
    chain_id: str
        Chain identifier.

    Returns
    -------
    selection: oechem.OEGraphMol
        An OpenEye molecule holding the selected chain.
    """
    # do not change input mol
    selection = molecule.CreateCopy()

    # delete other chains
    for atom in selection.GetAtoms():
        residue = oechem.OEAtomGetResidue(atom)
        if residue.GetChainID() != chain_id:
            selection.DeleteAtom(atom)

    return selection
Exemple #2
0
def select_chain(mol, chain_id):
    """
    Select a chain from an OEChem molecule.

    Parameters
    ----------
    mol: oechem.OEGraphMol
        An oechem.OEGraphMol object holding a molecular structure.

    chain_id: str
        Chain identifier.

    Returns
    -------
    selection: oechem.OEGraphMol
        An oechem.OEGraphMol object holding selected components.
    """
    # External libraries
    from openeye import oechem

    # do not change input mol
    selection = mol.CreateCopy()

    # delete other chains
    for atom in selection.GetAtoms():
        residue = oechem.OEAtomGetResidue(atom)
        if residue.GetChainID() != chain_id:
            selection.DeleteAtom(atom)

    return selection
Exemple #3
0
def select_ligand(mol, ligand_id):
    """
    Select all atoms from an OEChem molecule that are protein, water or are part of the specified ligand.

    Parameters
    ----------
    mol: oechem.OEGraphMol
        An oechem.OEGraphMol object holding a molecular structure.

    ligand_id: str
        Ligand identifier.

    Returns
    -------
    selection: oechem.OEGraphMol
        An oechem.OEGraphMol object holding selected components.
    """
    # External libraries
    from openeye import oechem

    # DocKin library
    from dockin.utils import protein_resnames

    # do not change input mol
    selection = mol.CreateCopy()

    allowed_resnames = protein_resnames + ['HOH', ligand_id]

    # delete other residues
    for atom in selection.GetAtoms():
        residue = oechem.OEAtomGetResidue(atom)
        if residue.GetName() not in allowed_resnames:
            selection.DeleteAtom(atom)

    return selection
Exemple #4
0
def select_altloc(molecule, altloc_id):
    """
    Select an alternate location from an OpenEye molecule.
    Parameters
    ----------
    molecule: oechem.OEGraphMol
        An OpenEye molecule holding a molecular structure.
    altloc_id: str
        Alternate location identifier.
    Returns
    -------
    selection: oechem.OEGraphMol
        An OpenEye molecule holding the selected alternate location.
    """
    # External libraries
    from openeye import oechem

    # do not change input mol
    selection = molecule.CreateCopy()

    allowed_altloc_ids = [" ", altloc_id]

    # delete other alternate location
    for atom in selection.GetAtoms():
        residue = oechem.OEAtomGetResidue(atom)
        if oechem.OEResidue.GetAlternateLocation(
                residue) not in allowed_altloc_ids:
            selection.DeleteAtom(atom)

    return selection
Exemple #5
0
    def getTargetAtoms(self, molecule, backbone_atoms, residue_list):
        """This function takes a OEGraphMol PDB structure and a list of residue numbers and
            generates a dictionary containing all the atom pointers and indicies for the
            non-backbone, atoms of those target residues, as well as a list of backbone atoms.
            Note: The atom indicies start at 0 and are thus -1 from the PDB file indicies"""

        # create and clear dictionary to store atoms that make up residue list
        qry_atoms = {}
        qry_atoms.clear()

        reslib = []

        #print('Searching residue list for atoms...')
        # loop through all the atoms in the PDB OEGraphMol structure
        for atom in molecule.GetAtoms():
            # check if the atom is in backbone
            if atom.GetIdx() not in backbone_atoms:
                # if heavy, find what residue it is associated with
                myres = oechem.OEAtomGetResidue(atom)
                # check if the residue number is amongst the list of residues
                if myres.GetResidueNumber() in residue_list and myres.GetName() != "HOH":
                    # store the atom location in a query atom dict keyed by its atom index
                    qry_atoms.update({atom : atom.GetIdx()})
                    #print('Found atom %s in residue number %i %s'%(atom,myres.GetResidueNumber(),myres.GetName()))
                    if myres not in reslib:
                        reslib.append(myres)

        return qry_atoms, backbone_atoms
Exemple #6
0
    def findHeavyRotBonds(self, pdb_OEMol, qry_atoms):
        '''This function takes in an OEGraphMol PDB structure as well as a dictionary of atom locations (keys)
            and atom indicies.  It loops over the query atoms and identifies any heavy bonds associated with each atom.
            It stores and returns the bond indicies (keys) and the two atom indicies for each bond in a dictionary
            **Note: atom indicies start at 0, so are offset by 1 compared to pdb)'''

        # create and clear dictionary to store bond and atom indicies that are rotatable + heavy
        rot_bonds = {}
        rot_bonds.clear()

        for atom in qry_atoms.keys():
            myres = oechem.OEAtomGetResidue(atom)
            for bond in atom.GetBonds():
                # retrieve the begnning and ending atoms
                begatom = bond.GetBgn()
                endatom = bond.GetEnd()
                # if begnnning and ending atoms are not Hydrogen, and the bond is rotatable
                if endatom.GetAtomicNum() >1 and begatom.GetAtomicNum() >1 and bond.IsRotor():
                    # if the bond has not been added to dictionary already..
                    # (as would happen if one of the atom pairs was previously looped over)
                    if bond not in rot_bonds:
                        #print('Bond number',bond, 'is rotatable, non-terminal, and contains only heavy atoms')
                        # store bond pointer (key) and atom indicies in dictionary if not already there
                        #rot_bonds.update({bond : {'AtomIdx_1' : bond.GetBgnIdx(), 'AtomIdx_2': bond.GetEndIdx()}})
                        rot_bonds.update({bond : myres.GetResidueNumber()})

        return rot_bonds
def main(argv=[__name__]):
    if len(argv) != 3:
        oechem.OEThrow.Usage("%s <molfile.pdb> <out.srf>" % argv[0])

    mol = oechem.OEGraphMol()
    ifs = oechem.oemolistream(argv[1])
    oechem.OEReadMolecule(ifs, mol)
    if not oechem.OEHasResidues(mol):
        oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)

    serials = {}
    for atom in mol.GetAtoms():
        res = oechem.OEAtomGetResidue(atom)
        serials[res.GetSerialNumber()] = atom

    outsurf = oespicoli.OESurface()
    center = oechem.OEFloatArray(3)
    for line in open(argv[1]):
        if line.startswith("ANISOU"):
            serno, factors = ParseFactors(line)
            if serno in serials:
                mol.GetCoords(serials[serno], center)
                surf = GetEllipsoidalSurface(center, factors)
                oespicoli.OEAddSurfaces(outsurf, surf)

    oespicoli.OEWriteSurface(argv[2], outsurf)
Exemple #8
0
def remove_non_protein(
    molecule: oechem.OEGraphMol,
    exceptions: Union[None, List[str]] = None,
    remove_water: bool = False,
) -> oechem.OEGraphMol:
    """
    Remove non-protein atoms from an OpenEye molecule.
    Parameters
    ----------
    molecule: oechem.OEGraphMol
        An OpenEye molecule holding a molecular structure.
    exceptions: None or list of str
        Exceptions that should not be removed.
    remove_water: bool
        If water should be removed.
    Returns
    -------
    selection: oechem.OEGraphMol
        An OpenEye molecule holding the filtered structure.
    """
    if exceptions is None:
        exceptions = []
    if remove_water is False:
        exceptions.append("HOH")

    # do not change input mol
    selection = molecule.CreateCopy()

    for atom in selection.GetAtoms():
        residue = oechem.OEAtomGetResidue(atom)
        if residue.IsHetAtom():
            if residue.GetName() not in exceptions:
                selection.DeleteAtom(atom)

    return selection
Exemple #9
0
 def _has_residue_number(atom, residue_numbers=real_termini):
     """Return True if atom matches any given residue number."""
     residue = oechem.OEAtomGetResidue(atom)
     return any([
         True if residue.GetResidueNumber() == residue_number else False
         for residue_number in residue_numbers
     ])
Exemple #10
0
def GetAverageBFactor(mol):

    sumbfactor = 0.0
    for atom in mol.GetAtoms():
        res = oechem.OEAtomGetResidue(atom)
        sumbfactor += res.GetBFactor()
    avgbfactor = sumbfactor / mol.NumAtoms()

    return avgbfactor
Exemple #11
0
def _OEFixBuiltLoopFragmentNumbers(protein):
    """
    Temporary fix, thanks to Jesper!
    """
    prev_fn = -1
    # Checking for CA atoms, since this will avoid messing with the caps and built sidechains,
    # since this is only a built loop problem
    builtPred = oespruce.OEIsModeledAtom()
    for atom in protein.GetAtoms(oechem.OEIsCAlpha()):
        res = oechem.OEAtomGetResidue(atom)
        fn = res.GetFragmentNumber()
        if builtPred(atom) and prev_fn != -1:
            for ra in oechem.OEGetResidueAtoms(atom):
                r = oechem.OEAtomGetResidue(ra)
                r.SetFragmentNumber(prev_fn)
                oechem.OEAtomSetResidue(ra, r)
        else:
            prev_fn = fn
def set_serial(molecule, chainid, first_serial):
    import oechem
    if not oechem.OEHasResidues(molecule):
        oechem.OEPerceiveResidues(molecule, oechem.OEPreserveResInfo_All)
    for atom in molecule.GetAtoms():
        residue = oechem.OEAtomGetResidue(atom)
        residue.SetExtChainID(chainid)
        serial_number = residue.GetSerialNumber()
        residue.SetSerialNumber(serial_number + first_serial)
Exemple #13
0
    def __iter__(self):
        max_idx = self.args.limit
        if max_idx is not None:
            max_idx = int(max_idx)
        count = 0
        self.config = config_from_env()
        in_orion = self.config is not None
        if not in_orion:
            with oechem.oemolistream(str(self.args.data_in)) as ifs:
                for mol in ifs.GetOEMols():
                    mol.SetData(oechem.OEGetTag('prefix'), self.opt['prefix'])
                    mol.SetData(oechem.OEGetTag('suffix'), self.opt['suffix'])

                    for at in mol.GetAtoms():
                        residue = oechem.OEAtomGetResidue(at)
                        residue.SetName(self.opt['type'])
                        oechem.OEAtomSetResidue(at, residue)

                    if self.opt['IDTag']:
                        mol.SetData(oechem.OEGetTag('IDTag'), 'l' + mol.GetTitle()[0:12] + '_' + str(count))
                    yield mol
                    count += 1
                    if max_idx is not None and count == max_idx:
                        break
        else:
            stream = StreamingDataset(self.args.data_in,
                                      input_format=self.args.download_format)
            for mol in stream:
                mol.SetData(oechem.OEGetTag('prefix'), self.opt['prefix'])
                mol.SetData(oechem.OEGetTag('suffix'), self.opt['suffix'])

                for at in mol.GetAtoms():
                    residue = oechem.OEAtomGetResidue(at)
                    residue.SetName(self.opt['type'])
                    oechem.OEAtomSetResidue(at, residue)

                if self.opt['IDTag']:
                    mol.SetData(oechem.OEGetTag('IDTag'), 'l' + mol.GetTitle()[0:12] + '_'+str(count))
                yield mol
                count += 1
                if max_idx is not None and count == max_idx:
                    break
Exemple #14
0
def PrintCloseContacts(prot, lig, maxgap):
    """print atoms in the protein within maxgap Angstroms of the ligand"""

    contacts = LigandProteinCloseContacts(prot, lig, maxgap)

    if len(contacts) > 0:
        print("%s: %d contacts within %.2fA" %
              (prot.GetTitle(), len(contacts), maxgap))
        for nbrs in contacts:
            pat = nbrs.GetBgn()
            lat = nbrs.GetEnd()
            rp = oechem.OEAtomGetResidue(pat)
            rl = oechem.OEAtomGetResidue(lat)
            print("%6.2fA:%5s %4s%s %s %s %4s%s:%5s %4s%s %s %s %4s%s" %
                  (math.sqrt(nbrs.GetDist2()), rp.GetSerialNumber(),
                   pat.GetName(), rp.GetAlternateLocation(), rp.GetName(),
                   rp.GetChainID(), rp.GetResidueNumber(), rp.GetInsertCode(),
                   rl.GetSerialNumber(), lat.GetName(),
                   rl.GetAlternateLocation(), rl.GetName(), rl.GetChainID(),
                   rl.GetResidueNumber(), rl.GetInsertCode()))
        print()
Exemple #15
0
def PrintResidues(mol):
    """list alternate location code and occupancy by group and residue"""
    if not oechem.OEHasResidues(mol):
        oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)

    alf = oechem.OEAltLocationFactory(mol)

    print("%s - %d alternate location groups:" %
          (mol.GetTitle(), alf.GetGroupCount()))

    for grp in alf.GetGroups():
        print("%d) %d alternate locations" %
              (grp.GetGroupID() + 1, grp.GetLocationCount()),
              end=" ")

        prev = oechem.OEResidue()
        prevCodes = ""
        sumOcc = []
        atNum = []

        for atom in alf.GetAltAtoms(grp):
            res = oechem.OEAtomGetResidue(atom)
            if not oechem.OESameResidue(res, prev):
                for i, code in enumerate(prevCodes):
                    print("%c(%.0f%c) " %
                          (code, (sumOcc[i] * 100.0) / atNum[i], "%"),
                          end=" ")
                print()
                prevCodes = ""
                sumOcc = []
                atNum = []

                print("\t%s%d%c chain '%c': " %
                      (res.GetName(), res.GetResidueNumber(),
                       res.GetInsertCode(), res.GetChainID()),
                      end=" ")
                prev = res

            code = res.GetAlternateLocation()
            whichCode = prevCodes.find(code)
            if whichCode < 0:
                prevCodes += code
                sumOcc.append(res.GetOccupancy())
                atNum.append(1)
            else:
                sumOcc[whichCode] += res.GetOccupancy()
                atNum[whichCode] += 1

        for i, code in enumerate(prevCodes):
            print("%c(%.0f%c) " % (code, (sumOcc[i] * 100.0) / atNum[i], "%"),
                  end=" ")
        print()
Exemple #16
0
def PrintLigandAtomInteractions(asite, atom):

    resnames = set()
    for inter in asite.GetInteractions(oechem.OEHasInteractionHint(atom)):
        profrag = inter.GetFragment(oechem.OEProteinInteractionHintComponent())
        if profrag is None:
            continue
        for patom in profrag.GetAtoms():
            residue = oechem.OEAtomGetResidue(patom)
            resnames.add(GetResidueName(residue))

    if len(resnames) != 0:
        print(atom, ":", " ".join(sorted(r for r in resnames)))
def LoopOverResAtoms(ims):
    for mol in ims.GetOEGraphMols():
        # @ <SNIPPET-PERCEIVE-RES>
        if not oechem.OEHasResidues(mol):
            oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)
        # @ </SNIPPET-PERCEIVE-RES>

        # @ <SNIPPET-RES-ATOMS-CORE>
        hv = oechem.OEHierView(mol)
        hres = hv.GetResidue("A", "LEU", 27)
        for atom in hres.GetAtoms():  # only this residue's atoms
            res = oechem.OEAtomGetResidue(atom)
            print(res.GetSerialNumber(), atom.GetName())
Exemple #18
0
def GetMinAndMaxBFactor(ligand, protein, maxdistance=4.0):

    minbfactor = float("inf")
    maxbfactor = float("-inf")

    # Ligand atoms
    for latom in ligand.GetAtoms(oechem.OEIsHeavy()):
        res = oechem.OEAtomGetResidue(latom)
        minbfactor = min(minbfactor, res.GetBFactor())
        maxbfactor = max(maxbfactor, res.GetBFactor())

    # Protein atoms close to ligand atoms
    nn = oechem.OENearestNbrs(protein, maxdistance)
    for latom in ligand.GetAtoms(oechem.OEIsHeavy()):
        for neigh in nn.GetNbrs(latom):
            ratom = neigh.GetBgn()
            res = oechem.OEAtomGetResidue(ratom)
            if ConsiderResidueAtom(ratom, res):
                minbfactor = min(minbfactor, res.GetBFactor())
                maxbfactor = max(maxbfactor, res.GetBFactor())

    return minbfactor, maxbfactor
def RamaCheck(mol):
    # @ <SNIPPET-RAMA-OUTLIER-CHECK>
    # Loop over the CA atoms in the protein
    for atom in mol.GetAtoms(oechem.OEIsCAlpha()):
        rama = oechem.OERamachandranAnalysis(atom)
        # Print out information about outliers for further analysis
        if rama.GetRamaCategory() == oechem.OERamaCategory_Outlier:
            res = oechem.OEAtomGetResidue(atom)
            print("Found: {}".format(oechem.OEGetRamachandranCategoryName(rama.GetRamaCategory())))
            print("  Residue: {} {} {}"
                  .format(res.GetName(), res.GetResidueNumber(), res.GetChainID()))
            ramatype = oechem.OEGetRamachandranTypeName(rama.GetRamaType())
            print("  Type: {}, Score: {}".format(ramatype, rama.GetRamaScore()))
Exemple #20
0
    def process(self, initialRecord, port):
        try:
            if not initialRecord.has_value(Fields.primary_molecule):
                raise ValueError("Missing Primary Molecule field")

            ligand = initialRecord.get_value(Fields.primary_molecule)

            # place the entire initial record as a sub-record, to be restored when conformer runs are gathered
            record = OERecord()
            record.set_value(Fields.ligInit_rec, initialRecord)

            if oechem.OECalculateMolecularWeight(ligand) > 1500.0:  # Units are in Dalton
                raise ValueError("[{}] The molecule {} seems to have a large molecular weight for a "
                                 "ligand: {:.2f} Da)".format(self.title,
                                                             ligand.GetTitle(),
                                                             oechem.OECalculateMolecularWeight(ligand)))

            # Removing Interaction Hint Container, Style and PDB Data
            oechem.OEDeleteInteractionsHintSerializationData(ligand)
            oechem.OEDeleteInteractionsHintSerializationIds(ligand)
            oechem.OEClearStyle(ligand)
            oechem.OEClearPDBData(ligand)

            # Ligand sanitation
            ligand = oeommutils.sanitizeOEMolecule(ligand)

            lig_title = ligand.GetTitle()

            if lig_title == "":
                lig_title = 'LIG'

            record.set_value(Fields.ligand_name, lig_title)

            for at in ligand.GetAtoms():
                residue = oechem.OEAtomGetResidue(at)
                residue.SetName(self.args.lig_res_name)
                oechem.OEAtomSetResidue(at, residue)

            record.set_value(Fields.primary_molecule, ligand)
            record.set_value(Fields.ligid, self.ligand_count)

            self.success.emit(record)
            self.ligand_count += 1
            self.max_runs += ligand.NumConfs()

        except Exception as e:

            print("Failed to complete", str(e), flush=True)
            self.opt['Logger'].info('Exception {} {}'.format(str(e), self.title))
            self.log.error(traceback.format_exc())
            self.failure.emit(initialRecord)
def run_create_mol2_pdb(**kwargs):

    nmol = kwargs['nmol']
    input_txt = kwargs['input']
    resname = kwargs['resname']
    density = kwargs['density']
    tries = kwargs['tries']

    # Disable Gromacs backup file creation
    os.environ['GMX_MAXBACKUP'] = "-1"

    smiles_string = open(input_txt).readlines()[0].strip()
    print("The following SMILES string will be converted: %s" % smiles_string)

    # create a new molecule
    oemol = oechem.OEGraphMol()
    # convert the SMILES string into a molecule
    if oechem.OESmilesToMol(oemol, smiles_string):
        # do something interesting with mol
        pass
    else:
        print("SMILES string was invalid!")

    # Add explicit
    oechem.OEAddExplicitHydrogens(oemol)

    # Generate a single conformer
    oemol = openmoltools.openeye.generate_conformers(oemol, max_confs=1)

    # Modify residue names
    oechem.OEPerceiveResidues(oemol, oechem.OEPreserveResInfo_All)
    for atom in oemol.GetAtoms():
        thisRes = oechem.OEAtomGetResidue(atom)
        thisRes.SetName(resname)

    # Write output files
    ofs = oechem.oemolostream()
    output_fnms = ['%s.mol2' % resname, '%s.pdb' % resname]
    for output_fnm in output_fnms:
        if not ofs.open(output_fnm):
            oechem.OEThrow.Fatal("Unable to create %s" % output_fnm)
        oechem.OEWriteMolecule(ofs, oemol)
        print("-=# Output #=- Created %s containing single molecule" %
              output_fnm)

    grams_per_mole = CalculateMolecularWeight(oemol)

    boxlen = CalculateBoxSize(nmol, grams_per_mole, density)
    GenerateBox('%s.pdb' % resname, '%s-box.pdb' % resname, boxlen, nmol,
                tries)
Exemple #22
0
def DropLigandFromProtein(prot, lig):
    """delete atoms from the protein w/same coords as the ligand
    as well as any waters"""

    approximatelyTheSame = 0.05
    nn = oechem.OENearestNbrs(prot, approximatelyTheSame)

    # mark ligand atoms for deletion
    bv = oechem.OEBitVector(prot.GetMaxAtomIdx())
    for nbrs in nn.GetNbrs(lig):
        r1 = oechem.OEAtomGetResidue(nbrs.GetBgn())
        r2 = oechem.OEAtomGetResidue(nbrs.GetEnd())
        if r1.GetModelNumber() == r2.GetModelNumber():
            bv.SetBitOn(nbrs.GetBgn().GetIdx())

    # mark waters for deletion too
    for atom in prot.GetAtoms():
        res = oechem.OEAtomGetResidue(atom)
        if oechem.OEGetResidueIndex(res) == oechem.OEResidueIndex_HOH:
            bv.SetBitOn(atom.GetIdx())

    pred = oechem.OEAtomIdxSelected(bv)
    for atom in prot.GetAtoms(pred):
        prot.DeleteAtom(atom)
def CalcResCounts(mol):
    if not oechem.OEHasResidues(mol):
        oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)
    resCt = 0
    hetCt = 0
    prevRes = oechem.OEResidue()
    for atom in mol.GetAtoms():
        thisRes = oechem.OEAtomGetResidue(atom)
        if not oechem.OESameResidue(prevRes, thisRes):
            resCt += 1
            if thisRes.IsHetAtom():
                hetCt += 1
            prevRes = thisRes
    print("Molecule: %s" % mol.GetTitle())
    print("Residues: %d (%d hets)" % (resCt, hetCt))
Exemple #24
0
def _OEFixWaterFragmentNumbers(solvent):
    """
    Temporary fix, thanks to Jesper!
    """
    fragment_counter = {}
    for atom in solvent.GetAtoms(oechem.OEIsWater()):
        res = oechem.OEAtomGetResidue(atom)
        if res.GetInsertCode() != " ":
            continue
        if res.GetFragmentNumber() not in fragment_counter:
            fragment_counter[res.GetFragmentNumber()] = 0
        fragment_counter[res.GetFragmentNumber()] += 1
    largest_solvent_fn_count = -1
    largest_solvent_fn = -1
    for fn in fragment_counter:
        if fragment_counter[fn] > largest_solvent_fn_count:
            largest_solvent_fn_count = fragment_counter[fn]
            largest_solvent_fn = fn
    if largest_solvent_fn < 0:
        return
    for atom in solvent.GetAtoms(oechem.OEIsWater(True)):
        res = oechem.OEAtomGetResidue(atom)
        res.SetFragmentNumber(largest_solvent_fn)
        oechem.OEAtomSetResidue(atom, res)
Exemple #25
0
    def RenderGlyph(self, disp, atom):
        adisp = disp.GetAtomDisplay(atom)
        if adisp is None or not adisp.IsVisible():
            return False

        res = oechem.OEAtomGetResidue(atom)
        bfactor = res.GetBFactor()
        color = self.colorg.GetColorAt(bfactor)

        pen = oedepict.OEPen(color, color, oedepict.OEFill_On, 1.0)
        radius = disp.GetScale() / 3.0

        layer = disp.GetLayer(oedepict.OELayerPosition_Below)
        oegrapheme.OEDrawCircle(layer, oegrapheme.OECircleStyle_Default,
                                adisp.GetCoords(), radius, pen)
        return True
Exemple #26
0
def main(argv=[__name__]):

    itf = oechem.OEInterface(InterfaceData)

    if not oechem.OEParseCommandLine(itf, argv):
        oechem.OEThrow.Fatal("Unable to interpret command line!")

    ims = oechem.oemolistream()
    ims.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_ALTLOC)

    inputFile = itf.GetString("-in")
    if not ims.open(inputFile):
        oechem.OEThrow.Fatal("Unable to open %s for reading." % inputFile)

    if not oechem.OEIs3DFormat(ims.GetFormat()):
        oechem.OEThrow.Fatal("%s is not in a 3D format." % inputFile)

    mol = oechem.OEGraphMol()
    if not oechem.OEReadMolecule(ims, mol):
        oechem.OEThrow.Fatal("Unable to read %s." % inputFile)

    if not oechem.OEHasResidues(mol):
        oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)

    alf = oechem.OEAltLocationFactory(mol)
    if alf.GetGroupCount() != 0:
        alf.MakePrimaryAltMol(mol)

    # in our example, we will select the first histidine
    selectedResidue = oechem.OEResidue()
    for atom in mol.GetAtoms():
        res = oechem.OEAtomGetResidue(atom)
        if oechem.OEGetResidueIndex(res) == oechem.OEResidueIndex_HIS:
            selectedResidue = res
            break

    # @ <SNIPPET-PLACE-HYDROGENS-PRED>
    # given predicate IsSameResidue, residue selectedResidue and molecule mol...
    opt = oechem.OEPlaceHydrogensOptions()
    opt.SetNoFlipPredicate(IsSameResidue(selectedResidue))

    if oechem.OEPlaceHydrogens(mol, opt):
        # selectedResidue will not be flipped...
        # @ </SNIPPET-PLACE-HYDROGENS-PRED>
        print("success")

    ims.close()
Exemple #27
0
def SetAverageBFactorOfNearbyProteinAtoms(ligand, protein, itag, maxdistance=4.0):

    nn = oechem.OENearestNbrs(protein, maxdistance)
    for latom in ligand.GetAtoms(oechem.OEIsHeavy()):
        sumbfactor = 0.0
        neighs = []
        for neigh in nn.GetNbrs(latom):
            ratom = neigh.GetBgn()
            res = oechem.OEAtomGetResidue(ratom)
            if ConsiderResidueAtom(ratom, res):
                sumbfactor += res.GetBFactor()
                neighs.append(ratom)

        avgbfactor = 0.0
        if len(neighs) > 0:
            avgbfactor = sumbfactor / len(neighs)
        latom.SetDoubleData(itag, avgbfactor)
def PrintLocations(mol, hideAtoms):
    """list alternate location codes and atom info (unless hideAtoms is True)"""
    if not oechem.OEHasResidues(mol):
        oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)

    alf = oechem.OEAltLocationFactory(mol)

    print("%s" % mol.GetTitle())

    print("grp-cnt=%d" % alf.GetGroupCount(), end=" ")
    if alf.GetGroupCount() > 0:
        print("{")
    else:
        print()

    for grp in alf.GetGroups():
        print(" grp=%d loc-cnt=%d grp-codes='%s'" %
              (grp.GetGroupID(), grp.GetLocationCount(),
               alf.GetLocationCodes(grp)))
        for loc in grp.GetLocations():
            print(" grp=%d loc=%d loc-codes='%s'" %
                  (loc.GetGroupID(), loc.GetLocationID(),
                   alf.GetLocationCodes(loc)),
                  end=" ")
            if not hideAtoms:
                print("[", end=" ")
            num_atoms = 0
            for atom in alf.GetAltAtoms(loc):
                num_atoms += 1
                if not hideAtoms:
                    res = oechem.OEAtomGetResidue(atom)
                    print("%s:%c:%s%d%c:c%cm%d;" %
                          (atom.GetName(), res.GetAlternateLocation(),
                           res.GetName(), res.GetResidueNumber(),
                           res.GetInsertCode(), res.GetChainID(),
                           res.GetModelNumber()),
                          end=" ")
            if not hideAtoms:
                print("]", end=" ")
            print(num_atoms)

    if alf.GetGroupCount() > 0:
        print("}")
def Rename(ims, oms):
    for mol in ims.GetOEGraphMols():
        # @ <SNIPPET-PERCEIVE-RES>
        if not oechem.OEHasResidues(mol):
            oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)
        # @ </SNIPPET-PERCEIVE-RES>
        # @ <SNIPPET-MSE-TO-MET-CORE>
        for atom in mol.GetAtoms():
            thisRes = oechem.OEAtomGetResidue(atom)
            if oechem.OEGetResidueIndex(thisRes) == oechem.OEResidueIndex_MSE:
                thisRes.SetName("MET")  # modify res properties
                thisRes.SetHetAtom(False)
                oechem.OEAtomSetResidue(atom, thisRes)  # store updated residue

                if atom.GetAtomicNum() == oechem.OEElemNo_Se:
                    atom.SetAtomicNum(
                        oechem.OEElemNo_S)  # fix atom type & name
                    atom.SetName(" SD ")
        # @ </SNIPPET-MSE-TO-MET-CORE>
        oechem.OEWriteMolecule(oms, mol)
Exemple #30
0
def resids_to_box(
        protein: oechem.OEMolBase,
        resids: List[int]) -> Tuple[float, float, float, float, float, float]:
    """
    Retrieve box dimensions of a list if residues.

    Parameters
    ----------
    protein: oechem.OEMolBase
        An OpenEye molecule holding a protein structure.
    resids: list of int
        A list of resids defining the residues of interest.

    Returns
    -------
    box_dimensions: tuple of float
        The box dimensions in the order of xmax, ymax, zmax, xmin, ymin, zmin.
    """

    coordinates = oechem.OEFloatArray(protein.NumAtoms() * 3)
    oechem.OEGetPackedCoords(protein, coordinates)

    x_coordinates = []
    y_coordinates = []
    z_coordinates = []
    for i, atom in enumerate(protein.GetAtoms()):
        if oechem.OEAtomGetResidue(atom).GetResidueNumber() in resids:
            x_coordinates.append(coordinates[i * 3])
            y_coordinates.append(coordinates[(i * 3) + 1])
            z_coordinates.append(coordinates[(i * 3) + 2])

    box_dimensions = (
        max(x_coordinates),
        max(y_coordinates),
        max(z_coordinates),
        min(x_coordinates),
        min(y_coordinates),
        min(z_coordinates),
    )

    return box_dimensions