def depict_smiles(smiles): """ OEChem and OEDepict image generation """ # Image to draw on image = OEImage(400, 400) # Process SMILES mol = OEGraphMol() parsed = OESmilesToMol(mol, str(unquote(smiles))) if parsed: # Create image of molecule newtitle = [] for c in mol.GetTitle(): newtitle.append(choice(ALL_EMOJI)) mol.SetTitle(("".join(newtitle)).encode("UTF-8")) OEPrepareDepiction(mol) disp = OE2DMolDisplay(mol) for adisp in disp.GetAtomDisplays(): adisp.SetLabel(choice(ALL_EMOJI).encode("UTF-8")) OERenderMolecule(image, disp) else: # Create error image font = OEFont(OEFontFamily_Helvetica, OEFontStyle_Default, 20, OEAlignment_Center, OERed) image.DrawText(OE2DPoint(image.GetWidth()/2.0, image.GetHeight()/2.0), 'Your SMILES is not valid', font) img_content = OEWriteImageToString('svg', image) return Response(img_content, mimetype='image/svg+xml')
def Match(self, mol, flg=True): # Find all the hetero-aromatic atoms hetero_atoms = [atom for atom in mol.GetAtoms(_is_hetereo_aromatic)] if len(hetero_atoms) < 2: # The caller just needs an iterable return hetero_atoms # There are at least two hetero-aromatic atoms. # Are there multiple ring systems? num_aromatic_systems, parts = OEDetermineAromaticRingSystems(mol) assert num_aromatic_systems >= 1 # Are there hetero-atoms in different systems? atom_components = set(parts[atom.GetIdx()] for atom in hetero_atoms) if len(atom_components) > 1: return (1, 2) # The answer now is "at least one". But are there two? # All of the hetero-aromatic atoms are in the same ring system # This is the best answer I could think of, and it only works # with the OEChem toolkit: remove one of the bonds, re-find # the rings, and see if there's still an aromatic hetero-atom. hetero_atom = hetero_atoms[0] for bond in hetero_atom.GetBonds(OEIsAromaticBond()): newmol = OEGraphMol(mol) newmol_bond = newmol.GetBond(OEHasBondIdx(bond.GetIdx())) newmol.DeleteBond(newmol_bond) OEFindRingAtomsAndBonds(newmol) for atom in mol.GetAtoms(_is_hetereo_aromatic): return (1, 2) return (1, )
def rebuild_c_terminal(complex: oechem.OEGraphMol) -> oechem.OEGraphMol: # Delete and rebuild C-terminal residue because Spruce causes issues with this # See: 6m2n 6lze pred = oechem.OEIsCTerminalAtom() for atom in complex.GetAtoms(): if pred(atom): for nbor in atom.GetAtoms(): if oechem.OEGetPDBAtomIndex(nbor) == oechem.OEPDBAtomName_O: complex.DeleteAtom(nbor) return complex
def importSmiles(self, smiles): """ Contruct a OEGraphMol using the input descriptor. """ self.__oeMol = OEGraphMol() if OEParseSmiles(self.__oeMol, smiles): OEFindRingAtomsAndBonds(self.__oeMol) OEPerceiveChiral(self.__oeMol) return True # return False
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
def superpose_proteins(reference_protein: oechem.OEGraphMol, fit_protein: oechem.OEGraphMol) -> oechem.OEGraphMol: """ Superpose a protein structure onto a reference protein. Parameters ---------- reference_protein: oechem.OEGraphMol An OpenEye molecule holding a protein structure which will be used as reference during superposition. fit_protein: oechem.OEGraphMol An OpenEye molecule holding a protein structure which will be superposed onto the reference protein. Returns ------- superposed_protein: oechem.OEGraphMol An OpenEye molecule holding the superposed protein structure. """ # do not modify input superposed_protein = fit_protein.CreateCopy() # set superposition method options = oespruce.OESuperpositionOptions() options.SetSuperpositionType(oespruce.OESuperpositionType_Global) # perform superposition superposition = oespruce.OEStructuralSuperposition(reference_protein, superposed_protein, options) superposition.Transform(superposed_protein) return superposed_protein
def test_sanitizeSMILES(): """ Test SMILES sanitization. """ smiles_list = [ 'CC', 'CCC', '[H][C@]1(NC[C@@H](CC1CO[C@H]2CC[C@@H](CC2)O)N)[H]' ] sanitized_smiles_list = sanitizeSMILES(smiles_list, mode='drop') if len(sanitized_smiles_list) != 2: raise Exception( "Molecules with undefined stereochemistry are not being properly dropped (size=%d)." % len(sanitized_smiles_list)) sanitized_smiles_list = sanitizeSMILES(smiles_list, mode='expand') if len(sanitized_smiles_list) != 4: raise Exception( "Molecules with undefined stereochemistry are not being properly expanded (size=%d)." % len(sanitized_smiles_list)) # Check that all molecules can be round-tripped. from openeye.oechem import OEGraphMol, OESmilesToMol, OECreateIsoSmiString for smiles in sanitized_smiles_list: molecule = OEGraphMol() OESmilesToMol(molecule, smiles) isosmiles = OECreateIsoSmiString(molecule) if (smiles != isosmiles): raise Exception( "Molecule '%s' was not properly round-tripped (result was '%s')" % (smiles, isosmiles))
def setOeMol(self, inpOeMol, ccId): """ Load this object with an existing oeMOL() """ self.__clear() self.__oeMol = OEMol(inpOeMol) self.__ccId = ccId self.getElementCounts()
def get_atoms(molecule: oechem.OEGraphMol, match_string: str, atom_name: str) -> List[oechem.OEAtomBase]: atoms = [] pred = oechem.OEAtomMatchResidue(match_string) for atom in molecule.GetAtoms(pred): if atom.GetName().strip() == atom_name: atoms.append(atom) return atoms
def resids_to_box( protein: oechem.OEGraphMol, resids: List[int] ) -> Tuple[float, float, float, float, float, float]: """ Retrieve box dimensions of a list if residues. Parameters ---------- protein: oechem.OEGraphMol 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
def clashing_atoms(molecule1: oechem.OEGraphMol, molecule2: oechem.OEGraphMol) -> bool: """ Evaluates if the atoms of two molecules are clashing. Parameters ---------- molecule1: oechem.OEGraphMol An OpenEye molecule. molecule2: oechem.OEGraphMol An OpenEye molecule. Returns ------- : bool If any atoms of two molecules are clashing """ import math oechem.OEAssignCovalentRadii(molecule1) oechem.OEAssignCovalentRadii(molecule2) coordinates1_list = [ molecule1.GetCoords()[x] for x in sorted(molecule1.GetCoords().keys()) ] coordinates2_list = [ molecule2.GetCoords()[x] for x in sorted(molecule2.GetCoords().keys()) ] for atom1, coordinates1 in zip(molecule1.GetAtoms(), coordinates1_list): for atom2, coordinates2 in zip(molecule2.GetAtoms(), coordinates2_list): clash_threshold = atom1.GetRadius() + atom2.GetRadius() distance = math.sqrt( sum((coordinate1 - coordinate2)**2.0 for coordinate1, coordinate2 in zip( coordinates1, coordinates2))) if distance <= clash_threshold: return True return False
def test_single_match(self): matcher = openeye_patterns.NumFragments(10) self.assertEqual(matcher.SingleMatch(OEGraphMol()), 0) self.assertEqual(matcher.SingleMatch(parse_smiles("C")), 1) self.assertEqual(matcher.SingleMatch(parse_smiles("C.C")), 1)
def parse_smiles(smiles): mol = OEGraphMol() OEParseSmiles(mol, smiles) return mol
def oe_canonicalize(smiles): """Canonicalize smiles using OpenEye.""" mol = OEGraphMol() OEParseSmiles(mol, smiles) return OECreateCanSmiString(mol)
OE2DMolDisplay, OE2DMolDisplayOptions, OEAddHighlighting, OEGetMoleculeScale, OEHighlightStyle_BallAndStick, OEImage, OEImageGrid, OEPrepareAlignedDepiction, OEPrepareDepiction, OERenderMolecule, OEScale_AutoScale, OETitleLocation_Hidden, OEWriteImage, ) refmol = OEGraphMol() OEParseSmiles(refmol, "c1cc(c2cc(cnc2c1)CCCO)C(=O)CCO") OEPrepareDepiction(refmol) fitmol = OEGraphMol() OEParseSmiles(fitmol, "c1cc2ccc(cc2c(c1)C(=O)O)CCO") OEPrepareDepiction(fitmol) mcss = OEMCSSearch(OEMCSType_Approximate) atomexpr = OEExprOpts_DefaultAtoms bondexpr = OEExprOpts_DefaultBonds mcss.Init(refmol, atomexpr, bondexpr) mcss.SetMCSFunc(OEMCSMaxBondsCompleteCycles()) image = OEImage(400, 200)
def __build3D(self, coordType="model", setTitle=True): """ Build OE molecule using 3D coordinates and OE stereo perception. """ self.__clear() # self.__oeMol=OEGraphMol() self.__oeMol = OEMol() # if setTitle: self.__oeMol.SetTitle(self.__ccId) aL = [] # Atom index dictionary aD = {} i = 1 atomIt = PdbxChemCompAtomIt(self.__dcChemCompAtom, self.__verbose, self.__lfh) for ccAt in atomIt: atName = ccAt.getName() aD[atName] = i i += 1 atNo = ccAt.getAtNo() if atNo not in self.__eD: self.__eD[atNo] = 1 else: self.__eD[atNo] += 1 atType = ccAt.getType() fc = ccAt.getFormalCharge() chFlag = ccAt.isChiral() # arFlag = ccAt.isAromatic() isotope = ccAt.getIsotope() leavingAtom = ccAt.getLeavingAtomFlag() oeAt = self.__oeMol.NewAtom(atNo) oeAt.SetName(atName) oeAt.SetFormalCharge(fc) oeAt.SetStringData("pdbx_leaving_atom_flag", leavingAtom) oeAt.SetChiral(chFlag) oeAt.SetIsotope(isotope) # oeAt.SetAromatic(arFlag) # if chFlag: # st=ccAt.getCIPStereo() # if st == 'S' or st == 'R': # oeAt.SetStringData("StereoInfo",st) # if (self.__debug): # self.__lfh.write("Atom - %s type %s atno %d isotope %d fc %d chFlag %r\n" % (atName,atType,atNo,isotope,fc,chFlag)) if ((coordType == 'model') and ccAt.hasModelCoordinates()): cTup = ccAt.getModelCoordinates() # if (self.__verbose): # self.__lfh.write("CC %s Atom - %s cTup %r\n" % (self.__ccId,atName,cTup)) self.__oeMol.SetCoords(oeAt, cTup) elif ((coordType == 'ideal') and ccAt.hasIdealCoordinates()): cTup = ccAt.getIdealCoordinates() self.__oeMol.SetCoords(oeAt, cTup) else: pass if (self.__debug): self.__lfh.write( "Atom - %s type %s atno %d isotope %d fc %d (xyz) %r\n" % (atName, atType, atNo, isotope, fc, cTup)) aL.append(oeAt) bondIt = PdbxChemCompBondIt(self.__dcChemCompBond, self.__verbose, self.__lfh) for ccBnd in bondIt: (at1, at2) = ccBnd.getBond() iat1 = aD[at1] - 1 iat2 = aD[at2] - 1 iType = ccBnd.getIntegerType() # arFlag = ccBnd.isAromatic() # noqa: F841 pylint: disable=unused-variable if (self.__debug): self.__lfh.write(" %s %d -- %s %d (%d)\n" % (at1, iat1, at2, iat2, iType)) oeBnd = self.__oeMol.NewBond(aL[iat1], aL[iat2], iType) # noqa: F841 pylint: disable=unused-variable # oeBnd.SetAromatic(arFlag) # if arFlag: # oeBnd.SetIntType(5) # st=ccBnd.getStereo() # if st == 'E' or st =='Z': # oeBnd.SetStringData("StereoInfo",st) # # run standard perceptions -- # self.__oeMol.SetDimension(3) OE3DToInternalStereo(self.__oeMol) OEFindRingAtomsAndBonds(self.__oeMol) # Other aromatic models: OEAroModelMDL or OEAroModelDaylight OEAssignAromaticFlags(self.__oeMol, OEAroModelOpenEye) self.updateCIPStereoOE()
def save_profile_as_sd(mol: oechem.OEGraphMol): oechem.OEDeleteSDData(mol, TOTAL_STRAIN_TAG) oechem.OESetSDData(mol, TOTAL_STRAIN_TAG, '') # place holder oechem.OEDeleteSDData(mol, NUM_TORSION_PROFILES_TAG) oechem.OESetSDData(mol, NUM_TORSION_PROFILES_TAG, '') oechem.OEDeleteSDData(mol, NUM_LOW_CONFIDENCE_TORSIONS_TAG) oechem.OESetSDData(mol, NUM_LOW_CONFIDENCE_TORSIONS_TAG, '') strain_arr = np.zeros(1) strain_arr_high_conf_preds = np.zeros(1) num_torsion_profiles = 0 num_low_confidence_torsions = 0 can_torsions = get_canonical_torsions(mol) for num, can_torsion in enumerate(can_torsions): bond = mol.GetBond(can_torsion.b, can_torsion.c) if bond is not None and bond.HasData(ENERGY_PROFILE_TAG): num_torsion_profiles += 1 bond_strains = bond.GetData(STRAIN_TAG) profile_offset = bond.GetData(PROFILE_OFFSET_TAG) if profile_offset < OFFSET_THRESHOLD and ( not bond.HasData(SKIP_TORSION_TAG)): strain_arr_high_conf_preds += np.array(bond_strains) strain_arr += np.array(bond_strains) offset = bond.GetData(PROFILE_OFFSET_TAG) profile_str = bond.GetData(ENERGY_PROFILE_TAG) pred_confidence_value = HIGH_PREDICTION_CONFIDENCE_TAG if offset > OFFSET_THRESHOLD or bond.HasData(SKIP_TORSION_TAG): profile_str = 'LOW CONFIDENCE - ' + profile_str pred_confidence_value = LOW_PREDICTION_CONFIDENCE_TAG num_low_confidence_torsions += 1 #tor_atoms_str = bond.GetData(TORSION_ATOMS_FRAGMENT_TAG) #tor_atoms_str_list = tor_atoms_str.split(':') #a_idx, b_idx, c_idx, d_idx = list(map(int, tor_atoms_str_list[0].split())) tor_atoms_str1 = bond.GetData(TORSION_ATOMS_FRAGMENT_TAG) ca, cb, cc, cd = list(map(int, tor_atoms_str1.split())) apStr = "{}:{}:{}:{}".format(ca + 1, cb + 1, cc + 1, cd + 1) atom_ca = mol.GetAtom(oechem.OEHasAtomIdx(ca)) atom_cb = mol.GetAtom(oechem.OEHasAtomIdx(cb)) atom_cc = mol.GetAtom(oechem.OEHasAtomIdx(cc)) atom_cd = mol.GetAtom(oechem.OEHasAtomIdx(cd)) angle_float = oechem.OEGetTorsion(mol, atom_ca, atom_cb, atom_cc, atom_cd) * oechem.Rad2Deg sd_tag1 = 'TORSION_%s_ATOMS' % (num + 1) sd_tag2 = 'TORSION_%d_TORSIONNET_%s' % (num + 1, ENERGY_PROFILE_TAG) sd_tag3 = 'TORSION_%d_TORSIONNET_PRED_CONFIDENCE' % (num + 1) sd_tag4 = 'TORSION_%d_TORSIONNET_PROFILE_OFFSET' % (num + 1) oechem.OEDeleteSDData(mol, sd_tag1) oechem.OEDeleteSDData(mol, sd_tag2) oechem.OEDeleteSDData(mol, sd_tag3) oechem.OEDeleteSDData(mol, sd_tag4) oechem.OESetSDData(mol, sd_tag1, apStr) oechem.OESetSDData(mol, sd_tag2, profile_str) sd_tag6 = 'TORSION_%d_%s' % ((num + 1), STRAIN_TAG) oechem.OEDeleteSDData(mol, sd_tag6) oechem.OESetSDData(mol, sd_tag6, '%.1f' % bond_strains) angle = '%.1f' % angle_float sd_tag5 = 'TORSION_%d_ANGLE' % (num + 1) oechem.OEDeleteSDData(mol, sd_tag5) oechem.OESetSDData(mol, sd_tag5, angle) oechem.OESetSDData(mol, sd_tag3, pred_confidence_value) oechem.OESetSDData(mol, sd_tag4, '%.2f' % offset) strain_str = '%.1f' % strain_arr_high_conf_preds[0] oechem.OESetSDData(mol, TOTAL_STRAIN_TAG, strain_str) oechem.OESetSDData(mol, NUM_TORSION_PROFILES_TAG, str(num_torsion_profiles)) oechem.OESetSDData(mol, NUM_LOW_CONFIDENCE_TORSIONS_TAG, str(num_low_confidence_torsions)) reorder_sd_props(mol) return mol
import math from openeye import oechem, oedepict, oegrapheme from openeye.oechem import OEBlack, OEGraphMol, OEReadMolecule, OEWhite from openeye.oedepict import OE2DMolDisplay # Constants RGRP_IDX = 1 WEDGE_WIDTH = 30 RADIUS_BASE = 40 START_ANGLE = 5 SEGMENT_LABEL_SCALE_FACTOR = 1.3 ifs = oechem.oemolistream() ifs.open("rgrouppie.mol") mol = OEGraphMol() OEReadMolecule(ifs, mol) ###################################### oedepict.OEPrepareDepiction(mol) mdisp = OE2DMolDisplay(mol) # Get display coordinates of the R group atom r_coords = None for atom in mol.GetAtoms(): if atom.GetMapIdx() == 1: r_coords = mdisp.GetAtomDisplay(atom).GetCoords() # Create base image image = oedepict.OEImage(300, 300)
def __build2D(self, setTitle=True): """ Build molecule using existing assignments of chemical information in the CC definition. """ self.__clear() self.__oeMol = OEGraphMol() if setTitle: self.__oeMol.SetTitle(self.__ccId) aL = [] i = 1 # Atom index dictionary aD = {} atomIt = PdbxChemCompAtomIt(self.__dcChemCompAtom, self.__verbose, self.__lfh) for ccAt in atomIt: atName = ccAt.getName() aD[atName] = i i += 1 atNo = ccAt.getAtNo() if atNo not in self.__eD: self.__eD[atNo] = 1 else: self.__eD[atNo] += 1 atType = ccAt.getType() fc = ccAt.getFormalCharge() chFlag = ccAt.isChiral() arFlag = ccAt.isAromatic() isotope = ccAt.getIsotope() leavingAtom = ccAt.getLeavingAtomFlag() oeAt = self.__oeMol.NewAtom(atNo) oeAt.SetName(atName) oeAt.SetFormalCharge(fc) oeAt.SetStringData("pdbx_leaving_atom_flag", leavingAtom) oeAt.SetChiral(chFlag) oeAt.SetIsotope(isotope) oeAt.SetAromatic(arFlag) if chFlag: st = ccAt.getCIPStereo() if st == 'S' or st == 'R': oeAt.SetStringData("StereoInfo", st) if (self.__debug): self.__lfh.write( "Atom - %s type %s atno %d isotope %d fc %d chFlag %r\n" % (atName, atType, atNo, isotope, fc, chFlag)) aL.append(oeAt) bondIt = PdbxChemCompBondIt(self.__dcChemCompBond, self.__verbose, self.__lfh) for ccBnd in bondIt: (at1, at2) = ccBnd.getBond() iat1 = aD[at1] - 1 iat2 = aD[at2] - 1 iType = ccBnd.getIntegerType() arFlag = ccBnd.isAromatic() if (self.__debug): self.__lfh.write(" %s %d -- %s %d (%d)\n" % (at1, iat1, at2, iat2, iType)) oeBnd = self.__oeMol.NewBond(aL[iat1], aL[iat2], iType) oeBnd.SetAromatic(arFlag) if arFlag: oeBnd.SetIntType(5) st = ccBnd.getStereo() if st == 'E' or st == 'Z': oeBnd.SetStringData("StereoInfo", st) # # run standard perceptions -- OEFindRingAtomsAndBonds(self.__oeMol) OEPerceiveChiral(self.__oeMol) for oeAt in self.__oeMol.GetAtoms(): st = oeAt.GetStringData("StereoInfo") if st == 'R': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_R) elif st == 'S': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_S) for oeBnd in self.__oeMol.GetBonds(): st = oeBnd.GetStringData("StereoInfo") if st == 'E': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_E) elif st == 'Z': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_Z) if (self.__debug): for ii, atm in enumerate(self.__oeMol.GetAtoms()): self.__lfh.write("OeBuildMol.build2d - atom %d %s\n" % (ii, atm.GetName()))
def importFile(self, filePath, type='2D'): # pylint: disable=redefined-builtin """ Contruct a OEGraphMol using the content of the input file. The input file must have a file extension recognized by the OE toolkit (e.g. .sdf) """ ifs = oemolistream() if not ifs.open(filePath): return False # # self.__oeMol = OEGraphMol() self.__oeMol = OEMol() OEReadMolecule(ifs, self.__oeMol) # OETriposAtomNames(self.__oeMol) if type == '2D': # run standard perceptions -- OEFindRingAtomsAndBonds(self.__oeMol) OEPerceiveChiral(self.__oeMol) for oeAt in self.__oeMol.GetAtoms(): st = oeAt.GetStringData("StereoInfo") if st == 'R': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_R) elif st == 'S': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_S) for oeBnd in self.__oeMol.GetBonds(): st = oeBnd.GetStringData("StereoInfo") if st == 'E': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_E) elif st == 'Z': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_Z) elif type == '3D': # run standard perceptions -- # self.__oeMol.SetDimension(3) OE3DToInternalStereo(self.__oeMol) OEFindRingAtomsAndBonds(self.__oeMol) # Other aromatic models: OEAroModelMDL or OEAroModelDaylight OEAssignAromaticFlags(self.__oeMol, OEAroModelOpenEye) self.updateCIPStereoOE() OEAddExplicitHydrogens(self.__oeMol) self.__molXyzL = [] aC = {} for ii, atm in enumerate(self.__oeMol.GetAtoms()): iAtNum = atm.GetAtomicNum() if iAtNum in aC: aC[iAtNum] += 1 else: aC[iAtNum] = 1 # Less than idea - should have an API atName = PdbxChemCompConstants._periodicTable[iAtNum - 1] + str( aC[iAtNum]) # pylint: disable=protected-access atm.SetName(atName) # xyzL = OEFloatArray(3) self.__oeMol.GetCoords(atm, xyzL) self.__molXyzL.append( (ii, atm.GetIdx(), atm.GetAtomicNum(), atm.GetName(), atm.GetType(), xyzL[0], xyzL[1], xyzL[2])) return True
class OeBuildMol(object): ''' Utility methods for constructing OEGraphMols from chemical component definition objects. ''' def __init__(self, verbose=True, log=sys.stderr): self.__verbose = verbose self.__debug = False self.__lfh = log # # File system path to the chemical component dictionary definitions in (CVS checkout organization) # # Internal storage for current OE molecule self.__oeMol = None # # Component identifier # self.__ccId = None # # dictionary of element counts eD[atno]=count self.__eD = {} # # Source data categories objects from chemical component definitions. self.__dcChemCompAtom = None self.__dcChemCompBond = None # self.__molXyzL = [] def setDebug(self, flag): self.__debug = flag def setChemCompPath(self, ccPath): try: myReader = IoAdapter(self.__verbose, self.__lfh) cL = myReader.readFile(ccPath) self.__ccId = cL[0].getName() self.__dcChemCompAtom = cL[0].getObj("chem_comp_atom") self.__dcChemCompBond = cL[0].getObj("chem_comp_bond") return self.__ccId except Exception as e: self.__lfh.write("OeBuildMol(setChemCompPath) Fails for %s %s\n" % (ccPath, str(e))) traceback.print_exc(file=self.__lfh) return None def setOeMol(self, inpOeMol, ccId): """ Load this object with an existing oeMOL() """ self.__clear() self.__oeMol = OEMol(inpOeMol) self.__ccId = ccId self.getElementCounts() def set(self, ccId, dcChemCompAtom=None, dcChemCompBond=None): """ Assign source data categories - """ self.__ccId = ccId self.__dcChemCompAtom = dcChemCompAtom self.__dcChemCompBond = dcChemCompBond def __clear(self): self.__oeMol = None self.__eD = {} def serialize(self): """ Create a string representing the content of the current OE molecule. This serialization uses the OE internal binary format. """ oms = oemolostream() oms.SetFormat(OEFormat_OEB) oms.openstring() OEWriteMolecule(oms, self.__oeMol) if (self.__debug): self.__lfh.write("OeBuildMol(Serialize) SMILES %s\n" % OECreateCanSmiString(self.__oeMol)) self.__lfh.write("OeBuildMol(Serialize) atoms = %d\n" % self.__oeMol.NumAtoms()) return oms.GetString() def deserialize(self, oeS): """ Reconstruct an OE molecule from the input string serialization (OE binary). The deserialized molecule is used to initialize the internal OE molecule within this object. Returns True for success or False otherwise. """ self.__clear() ims = oemolistream() ims.SetFormat(OEFormat_OEB) ims.openstring(oeS) nmol = 0 mList = [] # for mol in ims.GetOEGraphMols(): for mol in ims.GetOEMols(): if (self.__debug): self.__lfh.write("OeBuildMol(deserialize) SMILES %s\n" % OECreateCanSmiString(mol)) self.__lfh.write("OeBuildMol(deserialize) title %s\n" % mol.GetTitle()) self.__lfh.write("OeBuildMol(deserialize) atoms %d\n" % mol.NumAtoms()) # mList.append(OEGraphMol(mol)) mList.append(OEMol(mol)) nmol += 1 # if nmol >= 1: self.__oeMol = mList[0] self.__ccId = self.__oeMol.GetTitle() # if (self.__debug): self.__lfh.write("OeBuildMol(deserialize) mols %d\n" % nmol) self.__lfh.write("OeBuildMol(deserialize) id %s\n" % self.__ccId) self.__lfh.write("OeBuildMol(deserialize) atoms %d\n" % self.__oeMol.NumAtoms()) return True else: return False def simpleAtomNames(self): """ """ for atom in self.__oeMol.GetAtoms(): atom.SetIntType(atom.GetAtomicNum()) atom.SetType(OEGetAtomicSymbol(atom.GetAtomicNum())) OETriposAtomNames(self.__oeMol) def getElementCounts(self): """ Get the dictionary of element counts (eg. eD[iAtNo]=iCount). """ if len(self.__eD) == 0: # calculate from current oeMol try: self.__eD = {} for atom in self.__oeMol.GetAtoms(): atNo = atom.GetAtomicNum() if atNo not in self.__eD: self.__eD[atNo] = 1 else: self.__eD[atNo] += 1 except: # noqa: E722 pylint: disable=bare-except pass return self.__eD def build3D(self, coordType="model", setTitle=True): try: self.__build3D(coordType=coordType, setTitle=setTitle) return True except Exception as e: self.__lfh.write("OeBuildMol(build3D) Failing %s\n" % str(e)) traceback.print_exc(file=self.__lfh) return False def __build3D(self, coordType="model", setTitle=True): """ Build OE molecule using 3D coordinates and OE stereo perception. """ self.__clear() # self.__oeMol=OEGraphMol() self.__oeMol = OEMol() # if setTitle: self.__oeMol.SetTitle(self.__ccId) aL = [] # Atom index dictionary aD = {} i = 1 atomIt = PdbxChemCompAtomIt(self.__dcChemCompAtom, self.__verbose, self.__lfh) for ccAt in atomIt: atName = ccAt.getName() aD[atName] = i i += 1 atNo = ccAt.getAtNo() if atNo not in self.__eD: self.__eD[atNo] = 1 else: self.__eD[atNo] += 1 atType = ccAt.getType() fc = ccAt.getFormalCharge() chFlag = ccAt.isChiral() # arFlag = ccAt.isAromatic() isotope = ccAt.getIsotope() leavingAtom = ccAt.getLeavingAtomFlag() oeAt = self.__oeMol.NewAtom(atNo) oeAt.SetName(atName) oeAt.SetFormalCharge(fc) oeAt.SetStringData("pdbx_leaving_atom_flag", leavingAtom) oeAt.SetChiral(chFlag) oeAt.SetIsotope(isotope) # oeAt.SetAromatic(arFlag) # if chFlag: # st=ccAt.getCIPStereo() # if st == 'S' or st == 'R': # oeAt.SetStringData("StereoInfo",st) # if (self.__debug): # self.__lfh.write("Atom - %s type %s atno %d isotope %d fc %d chFlag %r\n" % (atName,atType,atNo,isotope,fc,chFlag)) if ((coordType == 'model') and ccAt.hasModelCoordinates()): cTup = ccAt.getModelCoordinates() # if (self.__verbose): # self.__lfh.write("CC %s Atom - %s cTup %r\n" % (self.__ccId,atName,cTup)) self.__oeMol.SetCoords(oeAt, cTup) elif ((coordType == 'ideal') and ccAt.hasIdealCoordinates()): cTup = ccAt.getIdealCoordinates() self.__oeMol.SetCoords(oeAt, cTup) else: pass if (self.__debug): self.__lfh.write( "Atom - %s type %s atno %d isotope %d fc %d (xyz) %r\n" % (atName, atType, atNo, isotope, fc, cTup)) aL.append(oeAt) bondIt = PdbxChemCompBondIt(self.__dcChemCompBond, self.__verbose, self.__lfh) for ccBnd in bondIt: (at1, at2) = ccBnd.getBond() iat1 = aD[at1] - 1 iat2 = aD[at2] - 1 iType = ccBnd.getIntegerType() # arFlag = ccBnd.isAromatic() # noqa: F841 pylint: disable=unused-variable if (self.__debug): self.__lfh.write(" %s %d -- %s %d (%d)\n" % (at1, iat1, at2, iat2, iType)) oeBnd = self.__oeMol.NewBond(aL[iat1], aL[iat2], iType) # noqa: F841 pylint: disable=unused-variable # oeBnd.SetAromatic(arFlag) # if arFlag: # oeBnd.SetIntType(5) # st=ccBnd.getStereo() # if st == 'E' or st =='Z': # oeBnd.SetStringData("StereoInfo",st) # # run standard perceptions -- # self.__oeMol.SetDimension(3) OE3DToInternalStereo(self.__oeMol) OEFindRingAtomsAndBonds(self.__oeMol) # Other aromatic models: OEAroModelMDL or OEAroModelDaylight OEAssignAromaticFlags(self.__oeMol, OEAroModelOpenEye) self.updateCIPStereoOE() def updatePerceptions3D(self): self.__oeMol.SetDimension(3) OE3DToInternalStereo(self.__oeMol) OEFindRingAtomsAndBonds(self.__oeMol) # Other aromatic models: OEAroModelMDL or OEAroModelDaylight OEAssignAromaticFlags(self.__oeMol, OEAroModelOpenEye) self.updateCIPStereoOE() def updateCIPStereoOE(self): """ OE perception of CIP stereo - """ for atom in self.__oeMol.GetAtoms(): OEPerceiveCIPStereo(self.__oeMol, atom) for bond in self.__oeMol.GetBonds(): if (bond.GetOrder() == 2): OEPerceiveCIPStereo(self.__oeMol, bond) def build2D(self, setTitle=True): # pylint: disable=unused-argument try: self.__build2D(setTitle=True) return True except: # noqa: E722 pylint: disable=bare-except return False def __build2D(self, setTitle=True): """ Build molecule using existing assignments of chemical information in the CC definition. """ self.__clear() self.__oeMol = OEGraphMol() if setTitle: self.__oeMol.SetTitle(self.__ccId) aL = [] i = 1 # Atom index dictionary aD = {} atomIt = PdbxChemCompAtomIt(self.__dcChemCompAtom, self.__verbose, self.__lfh) for ccAt in atomIt: atName = ccAt.getName() aD[atName] = i i += 1 atNo = ccAt.getAtNo() if atNo not in self.__eD: self.__eD[atNo] = 1 else: self.__eD[atNo] += 1 atType = ccAt.getType() fc = ccAt.getFormalCharge() chFlag = ccAt.isChiral() arFlag = ccAt.isAromatic() isotope = ccAt.getIsotope() leavingAtom = ccAt.getLeavingAtomFlag() oeAt = self.__oeMol.NewAtom(atNo) oeAt.SetName(atName) oeAt.SetFormalCharge(fc) oeAt.SetStringData("pdbx_leaving_atom_flag", leavingAtom) oeAt.SetChiral(chFlag) oeAt.SetIsotope(isotope) oeAt.SetAromatic(arFlag) if chFlag: st = ccAt.getCIPStereo() if st == 'S' or st == 'R': oeAt.SetStringData("StereoInfo", st) if (self.__debug): self.__lfh.write( "Atom - %s type %s atno %d isotope %d fc %d chFlag %r\n" % (atName, atType, atNo, isotope, fc, chFlag)) aL.append(oeAt) bondIt = PdbxChemCompBondIt(self.__dcChemCompBond, self.__verbose, self.__lfh) for ccBnd in bondIt: (at1, at2) = ccBnd.getBond() iat1 = aD[at1] - 1 iat2 = aD[at2] - 1 iType = ccBnd.getIntegerType() arFlag = ccBnd.isAromatic() if (self.__debug): self.__lfh.write(" %s %d -- %s %d (%d)\n" % (at1, iat1, at2, iat2, iType)) oeBnd = self.__oeMol.NewBond(aL[iat1], aL[iat2], iType) oeBnd.SetAromatic(arFlag) if arFlag: oeBnd.SetIntType(5) st = ccBnd.getStereo() if st == 'E' or st == 'Z': oeBnd.SetStringData("StereoInfo", st) # # run standard perceptions -- OEFindRingAtomsAndBonds(self.__oeMol) OEPerceiveChiral(self.__oeMol) for oeAt in self.__oeMol.GetAtoms(): st = oeAt.GetStringData("StereoInfo") if st == 'R': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_R) elif st == 'S': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_S) for oeBnd in self.__oeMol.GetBonds(): st = oeBnd.GetStringData("StereoInfo") if st == 'E': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_E) elif st == 'Z': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_Z) if (self.__debug): for ii, atm in enumerate(self.__oeMol.GetAtoms()): self.__lfh.write("OeBuildMol.build2d - atom %d %s\n" % (ii, atm.GetName())) def importFile(self, filePath, type='2D'): # pylint: disable=redefined-builtin """ Contruct a OEGraphMol using the content of the input file. The input file must have a file extension recognized by the OE toolkit (e.g. .sdf) """ ifs = oemolistream() if not ifs.open(filePath): return False # # self.__oeMol = OEGraphMol() self.__oeMol = OEMol() OEReadMolecule(ifs, self.__oeMol) # OETriposAtomNames(self.__oeMol) if type == '2D': # run standard perceptions -- OEFindRingAtomsAndBonds(self.__oeMol) OEPerceiveChiral(self.__oeMol) for oeAt in self.__oeMol.GetAtoms(): st = oeAt.GetStringData("StereoInfo") if st == 'R': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_R) elif st == 'S': OESetCIPStereo(self.__oeMol, oeAt, OECIPAtomStereo_S) for oeBnd in self.__oeMol.GetBonds(): st = oeBnd.GetStringData("StereoInfo") if st == 'E': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_E) elif st == 'Z': OESetCIPStereo(self.__oeMol, oeBnd, OECIPBondStereo_Z) elif type == '3D': # run standard perceptions -- # self.__oeMol.SetDimension(3) OE3DToInternalStereo(self.__oeMol) OEFindRingAtomsAndBonds(self.__oeMol) # Other aromatic models: OEAroModelMDL or OEAroModelDaylight OEAssignAromaticFlags(self.__oeMol, OEAroModelOpenEye) self.updateCIPStereoOE() OEAddExplicitHydrogens(self.__oeMol) self.__molXyzL = [] aC = {} for ii, atm in enumerate(self.__oeMol.GetAtoms()): iAtNum = atm.GetAtomicNum() if iAtNum in aC: aC[iAtNum] += 1 else: aC[iAtNum] = 1 # Less than idea - should have an API atName = PdbxChemCompConstants._periodicTable[iAtNum - 1] + str( aC[iAtNum]) # pylint: disable=protected-access atm.SetName(atName) # xyzL = OEFloatArray(3) self.__oeMol.GetCoords(atm, xyzL) self.__molXyzL.append( (ii, atm.GetIdx(), atm.GetAtomicNum(), atm.GetName(), atm.GetType(), xyzL[0], xyzL[1], xyzL[2])) return True def importSmiles(self, smiles): """ Contruct a OEGraphMol using the input descriptor. """ self.__oeMol = OEGraphMol() if OEParseSmiles(self.__oeMol, smiles): OEFindRingAtomsAndBonds(self.__oeMol) OEPerceiveChiral(self.__oeMol) return True # return False def getGraphMolSuppressH(self): """ Return the current constructed OE molecule with hydrogens suppressed. """ # OESuppressHydrogens(self.__oeMol, retainPolar=False,retainStereo=True,retainIsotope=True) OESuppressHydrogens(self.__oeMol) return self.__oeMol def getMol(self): """ Return the current constructed OE molecule. """ return OEMol(self.__oeMol) def getCanSMILES(self): """ Return the cannonical SMILES string derived from the current OD molecule. """ return OECreateCanSmiString(self.__oeMol) def getIsoSMILES(self): """ Return the cannonical stereo SMILES string derived from the current OE molecule. """ return OECreateIsoSmiString(self.__oeMol) def getFormula(self): """ Return the Hill order formulat derived from the current OE molecule. """ return OEMolecularFormula(self.__oeMol) def getInChIKey(self): """ Return the InChI key derived from the current OE molecule. """ return OECreateInChIKey(self.__oeMol) def getInChI(self): """ Return the InChI string derived from the current OE molecule. """ return OECreateInChI(self.__oeMol) def getTitle(self): """ Return the title assigned to the current OE molecule """ return self.__oeMol.GetTitle() def getCcId(self): """ Return the CC id of this object - """ return self.__ccId def getCoords(self): """ Return coordinate list if a 3D molecule is built -- otherwise an empty list -- """ return self.__molXyzL
def strip_hydrogens(complex: oechem.OEGraphMol) -> oechem.OEGraphMol: for atom in complex.GetAtoms(): if atom.GetAtomicNum() > 1: oechem.OESuppressHydrogens(atom) return complex
def mutate_structure(target_structure: oechem.OEGraphMol, template_sequence: str) -> oechem.OEGraphMol: """ Mutate a protein structure according to an amino acid sequence. Parameters ---------- target_structure: oechem.OEGraphMol An OpenEye molecule holding a protein structure to mutate. template_sequence: str A template one letter amino acid sequence, which defines the sequence the target structure should be mutated to. Protein residues not matching a template sequence will be either mutated or deleted. Returns ------- mutated_structure: oechem.OEGraphMol An OpenEye molecule holding the mutated protein structure. """ from Bio import pairwise2 # the hierarchy view is more stable if reinitialized after each change # https://docs.eyesopen.com/toolkits/python/oechemtk/biopolymers.html#a-hierarchy-view finished = False while not finished: altered = False # align template and target sequences target_sequence = get_sequence(target_structure) template_sequence_aligned, target_sequence_aligned = pairwise2.align.globalxs( template_sequence, target_sequence, -10, 0)[0][:2] logging.debug(f"Template sequence:\n{template_sequence}") logging.debug(f"Target sequence:\n{target_sequence}") hierview = oechem.OEHierView(target_structure) structure_residues = hierview.GetResidues() # adjust target structure to match template sequence for template_sequence_residue, target_sequence_residue in zip( template_sequence_aligned, target_sequence_aligned): if template_sequence_residue == "-": # delete any non protein residue from target structure structure_residue = structure_residues.next() if target_sequence_residue != "X": # delete for atom in structure_residue.GetAtoms(): target_structure.DeleteAtom(atom) # break loop and reinitialize altered = True break else: # compare amino acids if target_sequence_residue != "-": structure_residue = structure_residues.next() if target_sequence_residue not in [ "X", template_sequence_residue ]: # mutate structure_residue = structure_residue.GetOEResidue() three_letter_code = oechem.OEGetResidueName( oechem.OEGetResidueIndexFromCode( template_sequence_residue)) oespruce.OEMutateResidue(target_structure, structure_residue, three_letter_code) # break loop and reinitialize altered = True break # leave while loop if no changes were introduced if not altered: finished = True # OEMutateResidue doesn't build sidechains and doesn't add hydrogens automatically oespruce.OEBuildSidechains(target_structure) oechem.OEPlaceHydrogens(target_structure) # update residue information oechem.OEPerceiveResidues(target_structure, oechem.OEPreserveResInfo_All) return target_structure
def DebugWeb(environ, start_response): request = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ) templateDict = {} templateDict["importChemDB"] = "" templateDict["importOEChem"] = "" templateDict["importPsycoPg"] = "" if "importChemDB" in request: templateDict["importChemDB"] = "checked" if "importOEChem" in request: templateDict["importOEChem"] = "checked" if "importPsycoPg" in request: templateDict["importPsycoPg"] = "checked" html =\ """ <html> <body> <form action="DebugWeb.py" method=get name="debugForm"> <input type=text name="smiles"> <A HREF="Draw structure" onClick="popup = window.open('../JMEPopupWeb.py?parentForm=debugForm&smilesField=smiles&smiles='+ document.forms[0].smiles.value +'&JMEPopupWeb=True','jmePopup','resizable=yes,width=400,height=400'); popup.focus(); return false;"><IMG SRC="../../resource/edit.gif" STYLE="width: 19; height: 17; border: 0" alt="Draw structure"></A> <br> <textarea name="testArea"></textarea> <A HREF="Draw structure" onClick="popup = window.open('../JMEPopupWeb.py?parentForm=debugForm&smilesField=testArea','jmePopup','resizable=yes,width=400,height=400'); popup.focus(); return false;"><IMG SRC="../../resource/edit.gif" STYLE="width: 19; height: 17; border: 0" alt="Draw structure"></A> <br> <select multiple name="testMulti" size=4> <option>A <option>B <option>C <option>D <option>E <option>F <option>G </select><br> <input type=text name="repeater" value="joe"><br> <input type=text name="repeater" disabled value="blah"><br> <input type=text name="repeater" value="mama"><br> Import: <ul> <li><input type=checkbox name="importChemDB" value="checked" %(importChemDB)s> Misc ChemDB Module (requires web server PYTHONPATH to be set to CHEM's parent directory) <li><input type=checkbox name="importOEChem" value="checked" %(importOEChem)s> OEChem (requires OEChem installation and web server OE_LICENSE to be set to license file name and location) <li><input type=checkbox name="importPsycoPg" value="checked" %(importPsycoPg)s> PsycoPg </ul> <input type=file name="testFile"><br> <input type=submit name="JMEPopupWeb"><br> </form> """ % templateDict # Test if external imports work: if "importChemDB" in request: import CHEM.Common.Env html += "<i>Successfully imported a CHEM module</i><br>" if "importOEChem" in request: from openeye.oechem import OEGraphMol mol = OEGraphMol() html += "<i>Successfully imported a OEChem module</i><br>" if "importPsycoPg" in request: import psycopg2 html += "<i>Successfully imported psycopg2 module</i><br>" html += "Request Parameters" html += "<table border=1>" html += "<tr><th>Key</th><th>Value</th><th>Filename and Type</th></tr>" for key in list(request.keys()): field = request[key] if not isinstance(field, list): field = [field] # Convert to list of size 1 for item in field: html += "<tr><td>%s</td><td><pre>%s</pre></td><td>%s<br><br>%s</td></tr>" % ( key, item.value, item.filename, item.type) html += "</table>" html += "Paths (PYTHONPATH)" html += "<ul>" for path in sys.path: html += "<li>" + path + "</li>" html += "</ul>\n" #cgi.test() html += "<b>Request</b><br>" html += str(request) html += "<br><b>Environment Variables</b>" html += "<table border=1>" html += "<tr><th>Key</th><th>Value</th></tr>" keyList = list(os.environ.keys()) keyList.sort() for key in keyList: html += "<tr><td>%s</td><td>%s</td></tr>" % (key, os.environ[key]) html += "</table>" html += "</body>" html += "</html>" status = '200 OK' response_headers = [('Content-type', 'text/html'), ('Content-Length', str(len(html)))] start_response(status, response_headers) return html
def sanitizeSMILES(smiles_list, mode='drop', verbose=False): """ Sanitize set of SMILES strings by ensuring all are canonical isomeric SMILES. Duplicates are also removed. Parameters ---------- smiles_list : iterable of str The set of SMILES strings to sanitize. mode : str, optional, default='drop' When a SMILES string that does not correspond to canonical isomeric SMILES is found, select the action to be performed. 'exception' : raise an `Exception` 'drop' : drop the SMILES string 'expand' : expand all stereocenters into multiple molecules verbose : bool, optional, default=False If True, print verbose output. Returns ------- sanitized_smiles_list : list of str Sanitized list of canonical isomeric SMILES strings. Examples -------- Sanitize a simple list. >>> smiles_list = ['CC', 'CCC', '[H][C@]1(NC[C@@H](CC1CO[C@H]2CC[C@@H](CC2)O)N)[H]'] Throw an exception if undefined stereochemistry is present. >>> sanitized_smiles_list = sanitizeSMILES(smiles_list, mode='exception') Traceback (most recent call last): ... Exception: Molecule '[H][C@]1(NC[C@@H](CC1CO[C@H]2CC[C@@H](CC2)O)N)[H]' has undefined stereocenters Drop molecules iwth undefined stereochemistry. >>> sanitized_smiles_list = sanitizeSMILES(smiles_list, mode='drop') >>> len(sanitized_smiles_list) 2 Expand molecules iwth undefined stereochemistry. >>> sanitized_smiles_list = sanitizeSMILES(smiles_list, mode='expand') >>> len(sanitized_smiles_list) 4 """ from openeye import oechem from openeye.oechem import OEGraphMol, OESmilesToMol, OECreateIsoSmiString from perses.tests.utils import has_undefined_stereocenters, enumerate_undefined_stereocenters sanitized_smiles_set = set() OESMILES_OPTIONS = oechem.OESMILESFlag_DEFAULT | oechem.OESMILESFlag_ISOMERIC | oechem.OESMILESFlag_Hydrogens ## IVY for smiles in smiles_list: molecule = OEGraphMol() OESmilesToMol(molecule, smiles) oechem.OEAddExplicitHydrogens(molecule) if verbose: molecule.SetTitle(smiles) oechem.OETriposAtomNames(molecule) if has_undefined_stereocenters(molecule, verbose=verbose): if mode == 'drop': if verbose: print("Dropping '%s' due to undefined stereocenters." % smiles) continue elif mode == 'exception': raise Exception("Molecule '%s' has undefined stereocenters" % smiles) elif mode == 'expand': if verbose: print('Expanding stereochemistry:') print('original: %s', smiles) molecules = enumerate_undefined_stereocenters(molecule, verbose=verbose) for molecule in molecules: smiles_string = oechem.OECreateSmiString(molecule, OESMILES_OPTIONS) ## IVY sanitized_smiles_set.add(smiles_string) ## IVY if verbose: print('expanded: %s', smiles_string) else: # Convert to OpenEye's canonical isomeric SMILES. smiles_string = oechem.OECreateSmiString(molecule, OESMILES_OPTIONS) ## IVY sanitized_smiles_set.add(smiles_string) ## IVY sanitized_smiles_list = list(sanitized_smiles_set) return sanitized_smiles_list
#!/usr/bin/env python from openeye.oechem import OEGraphMol, OEReadMolecule, OEWriteMolecule, oemolistream, oemolostream ifs = oemolistream('imidazole/imidazole-epik-charged.mol2') ofs = oemolostream('imidazol.pdb') mol = OEGraphMol() while OEReadMolecule(ifs, mol): OEWriteMolecule(ofs, mol)