Appendix: Selected Examples in Python
These are full listings of programming examples that are excerpted or offered for download, elsewhere in this book.
Depict Toolkit
These examples illustrate use of the Depict tools to create molecule depictions in a variety of graphical file formats. See a guide to available examples in the Depict chapter.
Listing 1: Example of access atom display.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE OEDEPICT DOCUMENTATION
###############################################################
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc(N)cc(S(=O)(=O)O)c1")
oedepict.OEPrepareDepiction(mol)
width, height = 300, 200
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
disp = oedepict.OE2DMolDisplay(mol, opts)
pred = oechem.OEHasAtomicNum(oechem.OEElemNo_O)
for atom in mol.GetAtoms(pred):
adisp = disp.GetAtomDisplay(atom)
if adisp is not None and adisp.IsVisible():
# do something
pass
for adisp in disp.GetAtomDisplays(oechem.OEHasAtomicNum(oechem.OEElemNo_O)):
if adisp.IsVisible():
# do something
pass
Listing 2: Example of access bond display.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE OEDEPICT DOCUMENTATION
###############################################################
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc(N)cc(S(=O)(=O)O)c1")
oedepict.OEPrepareDepiction(mol)
width, height = 300, 200
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
disp = oedepict.OE2DMolDisplay(mol, opts)
pred = oechem.OEIsAromaticBond()
for bond in mol.GetBonds(pred):
bdisp = disp.GetBondDisplay(bond)
if bdisp is not None and bdisp.IsVisible():
# do something
pass
for bdisp in disp.GetBondDisplays(oechem.OEIsAromaticBond()):
if bdisp.IsVisible():
# do something
pass
Listing 3: Example of MDL query depiction.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
import sys
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <mdlquery> <imagefile>" % sys.argv[0])
ifs = oechem.oemolistream(sys.argv[1])
qmol = oechem.OEGraphMol()
oechem.OEReadMDLQueryFile(ifs, qmol)
oedepict.OEPrepareDepiction(qmol)
oedepict.OERenderMolecule(sys.argv[2], qmol)
Listing 4: Example of reaction depiction.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
import sys
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <mdlreaction> <imagefile>" % sys.argv[0])
ifs = oechem.oemolistream(sys.argv[1])
qmol = oechem.OEGraphMol()
oechem.OEReadMDLReactionQueryFile(ifs, qmol)
oedepict.OEPrepareDepiction(qmol)
oedepict.OERenderMolecule(sys.argv[2], qmol)
Listing 5: Example of reaction depiction with map indices.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
import sys
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <mdlreaction> <imagefile>" % sys.argv[0])
ifile = sys.argv[1]
ofile = sys.argv[2]
ifs = oechem.oemolistream(ifile)
qmol = oechem.OEGraphMol()
oechem.OEReadMDLReactionQueryFile(ifs, qmol)
oedepict.OEPrepareDepiction(qmol)
opts = oedepict.OE2DMolDisplayOptions()
opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomMapIdx())
disp = oedepict.OE2DMolDisplay(qmol, opts)
oedepict.OERenderMolecule(ofile, disp)
Listing 6: Example of line drawing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oedepict
width, height = 100, 100
# Create image
image = oedepict.OEImage(width, height)
# Draw line with default pen
bgn = oedepict.OE2DPoint(10.0, 10.0)
end = oedepict.OE2DPoint(90.0, 90.0)
image.DrawLine(bgn, end, oedepict.OEBlackPen)
# Write image to SVG file
oedepict.OEWriteImage("DrawLine.svg", image)
oedepict.OEWriteImage("DrawLine.png", image)
oedepict.OEWriteImage("DrawLine.pdf", image)
Listing 7: Example of object drawing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE OEDEPICT DOCUMENTATION
###############################################################
def DrawCubicBezier():
image = oedepict.OEImage(100, 100)
b = oedepict.OE2DPoint(20, 70)
e = oedepict.OE2DPoint(60, 70)
c1 = b + oedepict.OE2DPoint(50, -60)
c2 = e + oedepict.OE2DPoint(50, -60)
pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)
image.DrawCubicBezier(b, c1, c2, e, pen)
oedepict.OEWriteImage("DrawCubicBezier.png", image)
oedepict.OEWriteImage("DrawCubicBezier.pdf", image)
def DrawPath():
image = oedepict.OEImage(100, 100)
path = oedepict.OE2DPath(oedepict.OE2DPoint(20, 80))
path.AddLineSegment(oedepict.OE2DPoint(80, 80))
path.AddLineSegment(oedepict.OE2DPoint(80, 40))
path.AddCurveSegment(oedepict.OE2DPoint(80, 10), oedepict.OE2DPoint(20, 10),
oedepict.OE2DPoint(20, 40))
pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)
image.DrawPath(path, pen)
oedepict.OEWriteImage("DrawPath.png", image)
oedepict.OEWriteImage("DrawPath.pdf", image)
for p in path.GetPoints():
pos = p.GetPoint()
print(" %.1f %.1f %d" % (pos.GetX(), pos.GetY(), p.GetPointType()))
def DrawPolygon():
image = oedepict.OEImage(100, 100)
polygon = []
polygon.append(oedepict.OE2DPoint(20, 20))
polygon.append(oedepict.OE2DPoint(40, 40))
polygon.append(oedepict.OE2DPoint(60, 20))
polygon.append(oedepict.OE2DPoint(80, 40))
polygon.append(oedepict.OE2DPoint(80, 80))
polygon.append(oedepict.OE2DPoint(20, 80))
pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)
image.DrawPolygon(polygon, pen)
oedepict.OEWriteImage("DrawPolygon.png", image)
oedepict.OEWriteImage("DrawPolygon.pdf", image)
def DrawQuadraticBezier():
image = oedepict.OEImage(100, 100)
b = oedepict.OE2DPoint(20, 70)
e = oedepict.OE2DPoint(80, 70)
c = b + oedepict.OE2DPoint(30, -80)
pen = oedepict.OEPen(oechem.OELightGreen, oechem.OEBlack, oedepict.OEFill_On, 2.0)
image.DrawQuadraticBezier(b, c, e, pen)
oedepict.OEWriteImage("DrawQuadraticBezier.png", image)
oedepict.OEWriteImage("DrawQuadraticBezier.pdf", image)
DrawCubicBezier()
DrawPath()
DrawPolygon()
DrawQuadraticBezier()
Listing 8: Example of using highlighting class.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cncc2c1cc3c(cncc3)c2")
oedepict.OEPrepareDepiction(mol)
subs = oechem.OESubSearch("c1ncccc1")
disp = oedepict.OE2DMolDisplay(mol)
unique = True
for match in subs.Match(mol, unique):
oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OERed),
oedepict.OEHighlightStyle_Stick, match)
oedepict.OERenderMolecule("HighlightSimple.png", disp)
oedepict.OERenderMolecule("HighlightSimple.pdf", disp)
Listing 9: Example of using highlighting classes that correspond to the highlighting styles.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cncc2c1cc3c(cncc3)c2")
oedepict.OEPrepareDepiction(mol)
subs = oechem.OESubSearch("c1ncccc1")
opts = oedepict.OE2DMolDisplayOptions(240.0, 100.0, oedepict.OEScale_AutoScale)
opts.SetMargins(10.0)
disp = oedepict.OE2DMolDisplay(mol, opts)
stickWidthScale = 6.0
monochrome = True
highlight = oedepict.OEHighlightByStick(oechem.OEColor(oechem.OERed),
stickWidthScale, not monochrome)
unique = True
for match in subs.Match(mol, unique):
oedepict.OEAddHighlighting(disp, highlight, match)
oedepict.OERenderMolecule("HighlightStyle.png", disp)
oedepict.OERenderMolecule("HighlightStyle.pdf", disp)
Listing 10: Example of highlighting multiple matches one by one.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cncc2c1cc3c(cncc3)c2")
oedepict.OEPrepareDepiction(mol)
subs = oechem.OESubSearch("c1cc[c,n]cc1")
width, height = 350, 250
image = oedepict.OEImage(width, height)
rows, cols = 2, 2
grid = oedepict.OEImageGrid(image, rows, cols)
opts = oedepict.OE2DMolDisplayOptions(grid.GetCellWidth(), grid.GetCellHeight(),
oedepict.OEScale_AutoScale)
unique = True
for match, cell in zip(subs.Match(mol, unique), grid.GetCells()):
disp = oedepict.OE2DMolDisplay(mol, opts)
oedepict.OEAddHighlighting(disp, oechem.OEColor(oechem.OEPink),
oedepict.OEHighlightStyle_Color, match)
oedepict.OERenderMolecule(cell, disp)
oedepict.OEWriteImage("HighlightMulti.png", image)
oedepict.OEWriteImage("HighlightMulti.pdf", image)
Listing 11: Generating 2D coordinates.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Generates 2D coordinates
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
oedepict.OEConfigurePrepareDepictionOptions(itf,
oedepict.OEPrepareDepictionSetup_SuppressHydrogens |
oedepict.OEPrepareDepictionSetup_DepictOrientation)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
iname = itf.GetString("-in")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
ofs = oechem.oemolostream(".sdf")
if itf.HasString("-out"):
oname = itf.GetString("-out")
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
if not oechem.OEIs2DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output format for 2D coordinates")
if itf.HasString("-ringdict"):
rdfname = itf.GetString("-ringdict")
if not oechem.OEInit2DRingDictionary(rdfname):
oechem.OEThrow.Warning("Cannot use user-defined ring dictionary!")
popts = oedepict.OEPrepareDepictionOptions()
oedepict.OESetupPrepareDepictionOptions(popts, itf)
popts.SetClearCoords(True)
for mol in ifs.GetOEGraphMols():
oedepict.OEPrepareDepiction(mol, popts)
oechem.OEWriteMolecule(ofs, mol)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = """
!BRIEF [-in] <input> [-out] <output> [-ringdict] <rd file>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED false
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!PARAMETER -ringdict
!ALIAS -rd
!TYPE string
!REQUIRED false
!VISIBILITY simple
!BRIEF User-defined 2D ring dictionary
!DETAIL
2D ring dictionaries can be generated by the following OEChem examples:
C++ - createringdict.cpp
Python - createringdict.py
Java - CreateRingDict.java
C# - CreateRingDict.cs
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 12: Depicting substructure search match.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Depict a molecule and highlight the substructure specified by
# the given SMARTS pattern
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
oedepict.OEConfigureImageOptions(itf)
oedepict.OEConfigurePrepareDepictionOptions(itf)
oedepict.OEConfigure2DMolDisplayOptions(itf)
oedepict.OEConfigureHighlightParams(itf)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
iname = itf.GetString("-in")
oname = itf.GetString("-out")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredImageFile(ext):
oechem.OEThrow.Fatal("Unknown image type!")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Cannot read input file!")
smarts = itf.GetString("-smarts")
ss = oechem.OESubSearch()
if not ss.Init(smarts):
oechem.OEThrow.Fatal("Cannot parse smarts: %s" % smarts)
popts = oedepict.OEPrepareDepictionOptions()
oedepict.OESetupPrepareDepictionOptions(popts, itf)
oedepict.OEPrepareDepiction(mol, popts)
width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
dopts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
oedepict.OESetup2DMolDisplayOptions(dopts, itf)
dopts.SetMargins(10.0)
disp = oedepict.OE2DMolDisplay(mol, dopts)
hstyle = oedepict.OEGetHighlightStyle(itf)
hcolor = oedepict.OEGetHighlightColor(itf)
oechem.OEPrepareSearch(mol, ss)
unique = True
for match in ss.Match(mol, unique):
oedepict.OEAddHighlighting(disp, hcolor, hstyle, match)
oedepict.OERenderMolecule(ofs, ext, disp)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-in] <input> [-smarts] <smarts> [-out] <output image>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input filename
!END
!PARAMETER -smarts
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF SMARTS pattern
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 3
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 13: Aligning Molecule Based on MCS.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Aligns the fit molecule(s) based on their maximum common substructure
# with the reference molecule.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
rname = itf.GetString("-ref")
fname = itf.GetString("-fit")
oname = itf.GetString("-out")
rifs = oechem.oemolistream()
if not rifs.open(rname):
oechem.OEThrow.Fatal("Cannot open reference molecule file!")
refmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(rifs, refmol):
oechem.OEThrow.Fatal("Cannot read reference molecule!")
fifs = oechem.oemolistream()
if not fifs.open(fname):
oechem.OEThrow.Fatal("Cannot open align molecule file!")
ofs = oechem.oemolostream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
if not oechem.OEIs2DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output format for 2D coordinates")
oedepict.OEPrepareDepiction(refmol)
mcss = oechem.OEMCSSearch(oechem.OEMCSType_Approximate)
atomexpr = oechem.OEExprOpts_DefaultAtoms
bondexpr = oechem.OEExprOpts_DefaultBonds
mcss.Init(refmol, atomexpr, bondexpr)
mcss.SetMCSFunc(oechem.OEMCSMaxBondsCompleteCycles())
oechem.OEWriteConstMolecule(ofs, refmol)
for fitmol in fifs.GetOEGraphMols():
alignres = oedepict.OEPrepareAlignedDepiction(fitmol, mcss)
if alignres.IsValid():
oechem.OEThrow.Info("%s mcs size: %d" % (fitmol.GetTitle(), alignres.NumAtoms()))
oechem.OEWriteMolecule(ofs, fitmol)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-ref] <input> [-fit] <input> [-out] <output>
!CATEGORY "input/output options :"
!PARAMETER -ref
!ALIAS -r
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Ref filename
!END
!PARAMETER -fit
!ALIAS -f
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Align filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 3
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 14: Depicting MDL query.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Converts an MDL query structure into an image file.
# The output file format depends on its file extension.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
oedepict.OEConfigureImageOptions(itf)
oedepict.OEConfigure2DMolDisplayOptions(itf)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
iname = itf.GetString("-in")
oname = itf.GetString("-out")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredImageFile(ext):
oechem.OEThrow.Fatal("Unknown image type!")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
if ifs.GetFormat() != oechem.OEFormat_MDL:
oechem.OEThrow.Fatal("Input file is not an MDL query file")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
mol = oechem.OEGraphMol()
if not oechem.OEReadMDLQueryFile(ifs, mol):
oechem.OEThrow.Fatal("Cannot read mdl query input file!")
clearcoords, suppressH = False, False
oedepict.OEPrepareDepiction(mol, clearcoords, suppressH)
width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
oedepict.OESetup2DMolDisplayOptions(opts, itf)
disp = oedepict.OE2DMolDisplay(mol, opts)
oedepict.OERenderMolecule(ofs, ext, disp)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-in] <input> [-out] <output image>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 15: Converting an MDL reaction into an image file.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Converts an MDL reaction into an image file.
# The output file format is depends on its file extension.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface()
oechem.OEConfigure(itf, InterfaceData)
oedepict.OEConfigureImageOptions(itf)
oedepict.OEConfigure2DMolDisplayOptions(itf)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
iname = itf.GetString("-in")
oname = itf.GetString("-out")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredImageFile(ext):
oechem.OEThrow.Fatal("Unknown image type!")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
mol = oechem.OEGraphMol()
if not oechem.OEReadMDLReactionQueryFile(ifs, mol):
oechem.OEThrow.Fatal("Cannot read mdl reaction!")
clearcoords, suppressH = False, False
oedepict.OEPrepareDepiction(mol, clearcoords, suppressH)
width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
oedepict.OESetup2DMolDisplayOptions(opts, itf)
disp = oedepict.OE2DMolDisplay(mol, opts)
oedepict.OERenderMolecule(ofs, ext, disp)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-in] <input> [-out] <output image>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 16: Converting a single molecule into an image file.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Converts a molecule structure into an image file.
# The output file format depends on its file extension.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
oedepict.OEConfigureImageOptions(itf)
oedepict.OEConfigurePrepareDepictionOptions(itf)
oedepict.OEConfigure2DMolDisplayOptions(itf)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
iname = itf.GetString("-in")
oname = itf.GetString("-out")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredImageFile(ext):
oechem.OEThrow.Fatal("Unknown image type!")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Cannot read input file!")
if itf.HasString("-ringdict"):
rdfname = itf.GetString("-ringdict")
if not oechem.OEInit2DRingDictionary(rdfname):
oechem.OEThrow.Warning("Cannot use user-defined ring dictionary!")
popts = oedepict.OEPrepareDepictionOptions()
oedepict.OESetupPrepareDepictionOptions(popts, itf)
oedepict.OEPrepareDepiction(mol, popts)
width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
dopts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
oedepict.OESetup2DMolDisplayOptions(dopts, itf)
disp = oedepict.OE2DMolDisplay(mol, dopts)
oedepict.OERenderMolecule(ofs, ext, disp)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = """
!BRIEF [-in] <input> [-out] <output image> [-ringdict] <rd file>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!PARAMETER -ringdict
!ALIAS -rd
!TYPE string
!REQUIRED false
!VISIBILITY simple
!BRIEF User-defined 2D ring dictionary
!DETAIL
2D ring dictionaries can be generated by the following OEChem examples:
C++ - createringdict.cpp
Python - createringdict.py
Java - CreateRingDict.java
C# - CreateRingDict.cs
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 17: Depicting molecules in a grid.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Converts molecules into an image with grid layout.
# The output file format depends on its file extension.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface()
oechem.OEConfigure(itf, InterfaceData)
oedepict.OEConfigureImageWidth(itf, 400.0)
oedepict.OEConfigureImageHeight(itf, 400.0)
oedepict.OEConfigureImageGridParams(itf)
oedepict.OEConfigurePrepareDepictionOptions(itf)
oedepict.OEConfigure2DMolDisplayOptions(itf)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
oname = itf.GetString("-out")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredImageFile(ext):
oechem.OEThrow.Fatal("Unknown image type!")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
image = oedepict.OEImage(width, height)
rows = oedepict.OEGetImageGridNumRows(itf)
cols = oedepict.OEGetImageGridNumColumns(itf)
grid = oedepict.OEImageGrid(image, rows, cols)
popts = oedepict.OEPrepareDepictionOptions()
oedepict.OESetupPrepareDepictionOptions(popts, itf)
dopts = oedepict.OE2DMolDisplayOptions()
oedepict.OESetup2DMolDisplayOptions(dopts, itf)
dopts.SetDimensions(grid.GetCellWidth(), grid.GetCellHeight(), oedepict.OEScale_AutoScale)
celliter = grid.GetCells()
for iname in itf.GetStringList("-in"):
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Warning("Cannot open %s input file!" % iname)
continue
for mol in ifs.GetOEGraphMols():
if not celliter.IsValid():
break
oedepict.OEPrepareDepiction(mol, popts)
disp = oedepict.OE2DMolDisplay(mol, dopts)
oedepict.OERenderMolecule(celliter.Target(), disp)
celliter.Next()
oedepict.OEWriteImage(ofs, ext, image)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF -in <input1> [ <input2> .. ] -out <output image>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!LIST true
!REQUIRED true
!VISIBILITY simple
!BRIEF Input filename(s)
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 18: Convert molecular structures into a multipage :file:`PDF` image.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Converts molecules into a multi-page PDF document.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
oedepict.OEConfigureReportOptions(itf)
oedepict.OEConfigurePrepareDepictionOptions(itf)
oedepict.OEConfigure2DMolDisplayOptions(itf)
if not oechem.OEParseCommandLine(itf, argv):
return 1
iname = itf.GetString("-in")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
oname = itf.GetString("-out")
ext = oechem.OEGetFileExtension(oname)
if ext != "pdf":
oechem.OEThrow.Fatal("Output must be PDF format.")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
if itf.HasString("-ringdict"):
rdfname = itf.GetString("-ringdict")
if not oechem.OEInit2DRingDictionary(rdfname):
oechem.OEThrow.Warning("Cannot use user-defined ring dictionary!")
ropts = oedepict.OEReportOptions()
oedepict.OESetupReportOptions(ropts, itf)
ropts.SetFooterHeight(25.0)
report = oedepict.OEReport(ropts)
popts = oedepict.OEPrepareDepictionOptions()
oedepict.OESetupPrepareDepictionOptions(popts, itf)
dopts = oedepict.OE2DMolDisplayOptions()
oedepict.OESetup2DMolDisplayOptions(dopts, itf)
dopts.SetDimensions(report.GetCellWidth(), report.GetCellHeight(), oedepict.OEScale_AutoScale)
for mol in ifs.GetOEGraphMols():
cell = report.NewCell()
oedepict.OEPrepareDepiction(mol, popts)
disp = oedepict.OE2DMolDisplay(mol, dopts)
oedepict.OERenderMolecule(cell, disp)
font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Bold, 12,
oedepict.OEAlignment_Center, oechem.OEBlack)
for pagenum, footer in enumerate(report.GetFooters()):
text = "Page %d of %d" % (pagenum + 1, report.NumPages())
oedepict.OEDrawTextToCenter(footer, text, font)
oedepict.OEWriteReport(ofs, ext, report)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-in] <input> [-out] <output pdf> [-ringdict] <rd file>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!PARAMETER -ringdict
!ALIAS -rd
!TYPE string
!REQUIRED false
!VISIBILITY simple
!BRIEF User-defined 2D ring dictionary
!DETAIL
2D ring dictionaries can be generated by the following OEChem examples:
C++ - createringdict.cpp
Python - createringdict.py
Java - CreateRingDict.java
C# - CreateRingDict.cs
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 19: Generate a multipage PDF report of the 2D ring dictionary.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Converts a ring dictionary into a multi-page PDF document.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
oedepict.OEConfigureReportOptions(itf)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
ifname = itf.GetString("-ringdict")
ofname = itf.GetString("-out")
if not oechem.OEIsValid2DRingDictionary(ifname):
oechem.OEThrow.Fatal("Invalid ring dictionary file!")
ringdict = oechem.OE2DRingDictionary(ifname)
ropts = oedepict.OEReportOptions()
oedepict.OESetupReportOptions(ropts, itf)
oedepict.OEWrite2DRingDictionaryReport(ofname, ringdict, ropts)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = """
!BRIEF [-ringdict] <input ringdict> [-out] <output pdf>
!CATEGORY "input/output options :"
!PARAMETER -ringdict
!ALIAS -rd
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input ring dictionary filename
!DETAIL
2D ring dictionaries can be generated by the following OEChem examples:
C++ - createringdict.cpp
Python - createringdict.py
Java - CreateRingDict.java
C# - CreateRingDict.cs
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 20: Aligning molecules based on substructure search.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Aligns molecules to a smarts pattern
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
iname = itf.GetString("-in")
oname = itf.GetString("-out")
smarts = itf.GetString("-smarts")
qmol = oechem.OEQMol()
if not oechem.OEParseSmarts(qmol, smarts):
oechem.OEThrow.Fatal("Invalid SMARTS: %s" % smarts)
oechem.OEGenerate2DCoordinates(qmol)
ss = oechem.OESubSearch(qmol)
if not ss.IsValid():
oechem.OEThrow.Fatal("Unable to initialize substructure search!")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input molecule file!")
ofs = oechem.oemolostream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
if not oechem.OEIs2DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output format for 2D coordinates")
for mol in ifs.GetOEGraphMols():
oechem.OEPrepareSearch(mol, ss)
alignres = oedepict.OEPrepareAlignedDepiction(mol, ss)
if not alignres.IsValid():
oechem.OEThrow.Warning("Substructure is not found in input molecule!")
oedepict.OEPrepareDepiction(mol)
oechem.OEWriteMolecule(ofs, mol)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-in] <input> [-smarts] <smarts> [-out] <output>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Filename of input molecules
!END
!PARAMETER -smarts
!ALIAS -s
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF SMARTS for alignment match
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 3
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 21: Depicting MDL query substructure search hits.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Performs substructure search on a molecule using a MDL query and
# generates an image file depicting one match per molecule.
# The output file format depends on its file extension.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
oedepict.OEConfigureReportOptions(itf)
oedepict.OEConfigure2DMolDisplayOptions(itf)
oedepict.OEConfigureHighlightParams(itf)
if not oechem.OEParseCommandLine(itf, argv):
return 1
qname = itf.GetString("-query")
tname = itf.GetString("-target")
oname = itf.GetString("-out")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredMultiPageImageFile(ext):
oechem.OEThrow.Fatal("Unknown multipage image type!")
qfile = oechem.oemolistream()
if not qfile.open(qname):
oechem.OEThrow.Fatal("Cannot open mdl query file!")
if qfile.GetFormat() != oechem.OEFormat_MDL and qfile.GetFormat() != oechem.OEFormat_SDF:
oechem.OEThrow.Fatal("Query file has to be an MDL file!")
ifs = oechem.oemolistream()
if not ifs.open(tname):
oechem.OEThrow.Fatal("Cannot open target input file!")
depictquery = oechem.OEGraphMol()
if not oechem.OEReadMDLQueryFile(qfile, depictquery):
oechem.OEThrow.Fatal("Cannot read query molecule!")
oedepict.OEPrepareDepiction(depictquery)
queryopts = oechem.OEMDLQueryOpts_Default | oechem.OEMDLQueryOpts_SuppressExplicitH
qmol = oechem.OEQMol()
oechem.OEBuildMDLQueryExpressions(qmol, depictquery, queryopts)
ss = oechem.OESubSearch()
if not ss.Init(qmol):
oechem.OEThrow.Fatal("Cannot initialize substructure search!")
hstyle = oedepict.OEGetHighlightStyle(itf)
hcolor = oedepict.OEGetHighlightColor(itf)
align = itf.GetBool("-align")
ropts = oedepict.OEReportOptions()
oedepict.OESetupReportOptions(ropts, itf)
ropts.SetHeaderHeight(140.0)
report = oedepict.OEReport(ropts)
dopts = oedepict.OE2DMolDisplayOptions()
oedepict.OESetup2DMolDisplayOptions(dopts, itf)
cellwidth, cellheight = report.GetCellWidth(), report.GetCellHeight()
dopts.SetDimensions(cellwidth, cellheight, oedepict.OEScale_AutoScale)
unique = True
for mol in ifs.GetOEGraphMols():
oechem.OEPrepareSearch(mol, ss)
miter = ss.Match(mol, unique)
if not miter.IsValid():
continue # no match
alignres = oedepict.OEAlignmentResult(miter.Target())
if align:
alignres = oedepict.OEPrepareAlignedDepiction(mol, ss)
else:
oedepict.OEPrepareDepiction(mol)
cell = report.NewCell()
disp = oedepict.OE2DMolDisplay(mol, dopts)
if alignres.IsValid():
oedepict.OEAddHighlighting(disp, hcolor, hstyle, alignres)
oedepict.OERenderMolecule(cell, disp)
oedepict.OEDrawBorder(cell, oedepict.OELightGreyPen)
# render query structure in each header
headwidth, headheight = report.GetHeaderWidth(), report.GetHeaderHeight()
dopts.SetDimensions(headwidth, headheight, oedepict.OEScale_AutoScale)
disp = oedepict.OE2DMolDisplay(depictquery, dopts)
for header in report.GetHeaders():
oedepict.OERenderMolecule(header, disp)
oedepict.OEDrawBorder(header, oedepict.OELightGreyPen)
oedepict.OEWriteReport(oname, report)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-query] <input> [-target] <input> [-out] <output multipage image> [-align]
!CATEGORY "input/output options :"
!PARAMETER -query
!ALIAS -q
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input query filename
!END
!PARAMETER -target
!ALIAS -t
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Input target filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 3
!VISIBILITY simple
!BRIEF Output image filename
!END
!END
!CATEGORY "general options :"
!PARAMETER -align
!TYPE bool
!REQUIRED false
!DEFAULT false
!VISIBILITY simple
!BRIEF Align hits to query
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Docking Toolkit
Docking examples illustrate use of the Docking tools for docking and scoring molecules in the context of a protein active site. See the list in the Docking chapter for the set of examples.
Listing 1: Using the string I/O functions.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedocking
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <input receptor> <output receptor>" % argv[0])
receptor = oechem.OEGraphMol()
inputReceptorFilename = argv[1]
oedocking.OEReadReceptorFile(receptor, inputReceptorFilename)
outputReceptorFilename = argv[2]
oedocking.OEWriteReceptorFile(receptor, outputReceptorFilename)
bytes = oedocking.OEWriteReceptorToBytes(".oeb", receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, ".oeb", bytes)
print("SNIPPET-RECEPTOR-IO-3: .oeb status={} nbytes={}".format(status, len(bytes)))
bytes = oedocking.OEWriteReceptorToBytes(".oeb.gz", receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, ".oeb.gz", bytes)
print("SNIPPET-RECEPTOR-IO-4: .oeb.gz status={} nbytes={}".format(status, len(bytes)))
bytes = oedocking.OEWriteReceptorToBytes(".json", receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, ".json", bytes)
print("SNIPPET-RECEPTOR-IO-5: .json status={} nbytes={}".format(status, len(bytes)))
bytes = oedocking.OEWriteReceptorToBytes(".json.gz", receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, ".json.gz", bytes)
print("SNIPPET-RECEPTOR-IO-6: .json.gz status={} nbytes={}".format(status, len(bytes)))
gzip = False
bytes = oedocking.OEWriteReceptorToBytes(oechem.OEFormat_OEB,
oechem.OEGetDefaultOFlavor(oechem.OEFormat_OEB),
gzip, receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, oechem.OEFormat_OEB,
oechem.OEGetDefaultIFlavor(oechem.OEFormat_OEB),
gzip, bytes)
print("SNIPPET-RECEPTOR-IO-7: .oeb status={} nbytes={}".format(status, len(bytes)))
gzip = True
bytes = oedocking.OEWriteReceptorToBytes(oechem.OEFormat_OEB,
oechem.OEGetDefaultOFlavor(oechem.OEFormat_OEB),
gzip, receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, oechem.OEFormat_OEB,
oechem.OEGetDefaultIFlavor(oechem.OEFormat_OEB),
gzip, bytes)
print("SNIPPET-RECEPTOR-IO-8: .oeb.gz status={} nbytes={}".format(status, len(bytes)))
gzip = False
bytes = oedocking.OEWriteReceptorToBytes(oechem.OEFormat_JSON,
oechem.OEGetDefaultOFlavor(oechem.OEFormat_JSON),
gzip, receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, oechem.OEFormat_JSON,
oechem.OEGetDefaultIFlavor(oechem.OEFormat_JSON),
gzip, bytes)
print("SNIPPET-RECEPTOR-IO-9: .json status={} nbytes={}".format(status, len(bytes)))
gzip = True
bytes = oedocking.OEWriteReceptorToBytes(oechem.OEFormat_JSON,
oechem.OEGetDefaultOFlavor(oechem.OEFormat_JSON),
gzip, receptor)
receptorIO = oechem.OEGraphMol()
status = oedocking.OEReadReceptorFromBytes(receptorIO, oechem.OEFormat_JSON,
oechem.OEGetDefaultIFlavor(oechem.OEFormat_JSON),
gzip, bytes)
print("SNIPPET-RECEPTOR-IO-10: .json.gz status={} nbytes={}".format(status, len(bytes)))
if __name__ == "__main__":
sys.exit(main(sys.argv))
FastROCS Toolkit
FastROCS examples illustrate use of the FastROCS Toolkit to make extremely fast shape comparisons. See a full list of examples in the FastROCs chapter.
Listing 1: Full listing of CustomColorForceField.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
from openeye import oeshape
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
dbname = argv[1]
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
print("Opening database file %s ..." % dbname)
timer = oechem.OEWallTimer()
cff = oeshape.OEColorForceField()
cff.Init(oeshape.OEColorFFType_ImplicitMillsDeanNoRings)
cff.ClearInteractions()
cff.AddInteraction(
cff.GetType("donor"), cff.GetType("donor"), "gaussian", -1.0, range
)
cff.AddInteraction(
cff.GetType("acceptor"), cff.GetType("acceptor"), "gaussian", -1.0, range
)
dbase = oefastrocs.OEShapeDatabase(cff)
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifs):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
dots.Total()
print("%f seconds to load database" % timer.Elapsed())
opts = oefastrocs.OEShapeDatabaseOptions()
for qfname in argv[2:]:
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
ext = oechem.OEGetFileExtension(qfname)
base = qfname[:-(len(ext) + 1)]
# write out everthing to a similary named file
ofs = oechem.oemolostream()
ofname = base + "_results." + ext
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
print("Searching for %s" % qfname)
numhits = moldb.NumMols()
opts.SetLimit(numhits)
for score in dbase.GetSortedScores(query, opts):
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % ofname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 2: Full listing of OEShapeDatabaseOptions_SetUserStarts.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oefastrocs
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetInitialOrientation(oefastrocs.OEFastROCSOrientation_UserInertialStarts)
startsCoords = oechem.OEFloatVector()
startsCoords.append(float(1.45))
startsCoords.append(float(6.78))
startsCoords.append(float(-3.21))
opts.SetUserStarts(startsCoords, len(startsCoords) / 3)
coords = oechem.OEFloatVector(opts.GetNumStarts() * 3)
opts.GetUserStarts(coords)
Listing 3: Full listing of Tutorial1_InertialAtHeavyAtoms_Snippet.py
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
shapeOnlyDB = oefastrocs.OEShapeDatabase(oefastrocs.OEShapeDatabaseType_Shape)
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetLimit(5)
opts.SetInitialOrientation(oefastrocs.OEFastROCSOrientation_InertialAtHeavyAtoms)
qfs = oechem.oemolistream()
qfs.open(sys.argv[1])
query = oechem.OEGraphMol()
oechem.OEReadMolecule(qfs, query)
if opts.GetInitialOrientation() == oefastrocs.OEFastROCSOrientation_InertialAtHeavyAtoms:
numStarts = opts.GetNumHeavyAtomStarts(query)
oechem.OEThrow.Info("This example will use %u starts" % numStarts)
startsCoords = oechem.OEFloatVector()
xyz = query.GetCoords()[34]
for x in xyz:
startsCoords.append(x)
opts.SetInitialOrientation(oefastrocs.OEFastROCSOrientation_UserInertialStarts)
opts.SetUserStarts(oechem.OEFloatVector(startsCoords), int(len(startsCoords)/3))
if opts.GetInitialOrientation() == oefastrocs.OEFastROCSOrientation_UserInertialStarts:
numStarts = opts.GetNumUserStarts()
oechem.OEThrow.Info("This example will use %u starts" % numStarts)
oechem.OEThrow.Info("Opening database file %s ..." % sys.argv[2])
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
moldb.Open(sys.argv[2])
dbase.Open(moldb, oefastrocs.OEFastROCSOrientation_AsIs)
opts.SetInitialOrientation(oefastrocs.OEFastROCSOrientation_AsIs)
if opts.GetInitialOrientation() == oefastrocs.OEFastROCSOrientation_AsIs:
numStarts = opts.GetNumStarts()
numInertialStarts = opts.GetNumInertialStarts()
oechem.OEThrow.Info("This example will use %u starts & %u inertial starts"
% (numStarts, numInertialStarts))
opts.SetMaxOverlays(opts.GetNumInertialStarts() * opts.GetNumUserStarts())
opts.SetLimit(50)
opts.SetMaxConfs(5)
Listing 4: Shape Database Client Histogram.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from __future__ import unicode_literals
import os
import sys
import argparse
try:
from xmlrpclib import ServerProxy, Binary, Fault
except ImportError: # python 3
from xmlrpc.client import ServerProxy, Binary, Fault
class Pyasciigraph:
""" Copied from https://pypi.python.org/pypi/ascii_graph/0.2.1 """
def __init__(self, line_length=79, min_graph_length=50, separator_length=2):
"""Constructor of Pyasciigraph
:param int line_length: the max number of char on a line
if any line cannot be shorter,
it will go over this limit
:param int min_graph_length: the min number of char used by the graph
:param int separator_length: the length of field separator
"""
self.line_length = line_length
self.separator_length = separator_length
self.min_graph_length = min_graph_length
def _u(self, x):
if sys.version < '3':
import codecs
return codecs.unicode_escape_decode(x)[0]
else:
return x
def _get_maximum(self, data):
all_max = {}
all_max['value_max_length'] = 0
all_max['info_max_length'] = 0
all_max['max_value'] = 0
for (info, value) in data:
if value > all_max['max_value']:
all_max['max_value'] = value
if len(info) > all_max['info_max_length']:
all_max['info_max_length'] = len(info)
if len(str(value)) > all_max['value_max_length']:
all_max['value_max_length'] = len(str(value))
return all_max
def _gen_graph_string(self, value, max_value, graph_length, start_value):
number_of_square = 0
if max_value:
number_of_square = int(value * graph_length / max_value)
number_of_space = int(start_value - number_of_square)
return '#' * number_of_square + self._u(' ') * number_of_space
def _gen_info_string(self, info, start_info, line_length):
number_of_space = (line_length - start_info - len(info))
return info + self._u(' ') * number_of_space
def _gen_value_string(self, value, start_value, start_info):
number_space = start_info -\
start_value -\
len(str(value)) -\
self.separator_length
return ' ' * number_space +\
str(value) +\
' ' * self.separator_length
def _sanitize_string(self, string):
# get the type of a unicode string
unicode_type = type(self._u('t'))
input_type = type(string)
if input_type is str:
info = string
elif input_type is unicode_type:
info = string
elif input_type is int or input_type is float:
info = str(string)
return info
def _sanitize_data(self, data):
ret = []
for item in data:
ret.append((self._sanitize_string(item[0]), item[1]))
return ret
def graph(self, label, data, sort=0, with_value=True):
"""function generating the graph
:param string label: the label of the graph
:param iterable data: the data (list of tuple (info, value))
info must be "castable" to a unicode string
value must be an int or a float
:param int sort: flag sorted
0: not sorted (same order as given) (default)
1: increasing order
2: decreasing order
:param boolean with_value: flag printing value
True: print the numeric value (default)
False: don't print the numeric value
:rtype: a list of strings (each lines)
"""
result = []
san_data = self._sanitize_data(data)
san_label = self._sanitize_string(label)
if sort == 1:
san_data = sorted(san_data, key=lambda value: value[1], reverse=False)
elif sort == 2:
san_data = sorted(san_data, key=lambda value: value[1], reverse=True)
all_max = self._get_maximum(san_data)
real_line_length = max(self.line_length, len(label))
min_line_length = self.min_graph_length + 2 * self.separator_length +\
all_max['value_max_length'] + all_max['info_max_length']
if min_line_length < real_line_length:
# calcul of where to start info
start_info = self.line_length -\
all_max['info_max_length']
# calcul of where to start value
start_value = start_info -\
self.separator_length -\
all_max['value_max_length']
# calcul of where to end graph
graph_length = start_value -\
self.separator_length
else:
# calcul of where to start value
start_value = self.min_graph_length +\
self.separator_length
# calcul of where to start info
start_info = start_value +\
all_max['value_max_length'] +\
self.separator_length
# calcul of where to end graph
graph_length = self.min_graph_length
# calcul of the real line length
real_line_length = min_line_length
result.append(san_label)
result.append(self._u('#') * real_line_length)
for item in san_data:
info = item[0]
value = item[1]
graph_string = self._gen_graph_string(
value,
all_max['max_value'],
graph_length,
start_value
)
value_string = self._gen_value_string(
value,
start_value,
start_info
)
info_string = self._gen_info_string(
info,
start_info,
real_line_length
)
new_line = graph_string + value_string + info_string
result.append(new_line)
return result
def AddBin(bins, binSize, binIdx, curTotal):
lowerBound = binSize * binIdx
label = "%.2f" % lowerBound
bins.append((label, curTotal))
def GetGraphTitle(tversky, shapeOnly):
if not tversky and not shapeOnly:
return "FastROCS Tanimoto Combo Score Distribution"
if not tversky and shapeOnly:
return "FastROCS Tanimoto Shape Score Distribution"
if tversky and not shapeOnly:
return "FastROCS Tversky Combo Score Distribution"
if tversky and shapeOnly:
return "FastROCS Tversky Shape Score Distribution"
def PrintHistogram(hist, tversky=None, shapeOnly=None):
squashFactor = 10
if shapeOnly:
maxScore = 1.0
else:
maxScore = 2.0
binSize = maxScore/(len(hist) / squashFactor)
bins = []
curTotal = 0
binIdx = 0
for i, val in enumerate(hist):
if i != 0 and (i % squashFactor) == 0:
AddBin(bins, binSize, binIdx, curTotal)
curTotal = 0
binIdx += 1
curTotal += val
AddBin(bins, binSize, binIdx, curTotal)
graph = Pyasciigraph()
for line in graph.graph(GetGraphTitle(tversky, shapeOnly), bins):
print(line)
def GetFormatExtension(fname):
base, ext = os.path.splitext(fname.lower())
if ext == ".gz":
base, ext = os.path.splitext(base)
ext += ".gz"
return ext
def main(argv=[__name__]):
parser = argparse.ArgumentParser()
# positional arguments retaining backward compatibility
parser.add_argument('server:port', help='Server name and port number \
of database to search i.e. localhost:8080.')
parser.add_argument('query', help='File containing the query molecule to search \
(format not restricted to *.oeb).')
parser.add_argument('results', help='Output file to store results \
(format not restricted to *.oeb).')
parser.add_argument('nHits', nargs='?', type=int, default=100,
help='Number of hits to return (default=100).')
parser.add_argument('--tversky', action='store_true', default=argparse.SUPPRESS,
help='Switch to Tversky similarity scoring (default=Tanimoto).')
parser.add_argument('--shapeOnly', action='store_true', default=argparse.SUPPRESS,
help='Switch to shape-only scores (default=Combo).')
parser.add_argument('--alternativeStarts', default=argparse.SUPPRESS, nargs=1, dest='altStarts',
choices=('random', 'subrocs',
'inertialAtHeavyAtoms', 'inertialAtColorAtoms'),
help='Optimize using alternative starts. '
'To perform N random starts do \
"--alternativeStarts random N" (default N=10)')
known, remaining = (parser.parse_known_args())
dargs = vars(known)
qfname = dargs.pop('query')
numHits = dargs.pop('nHits')
startType = dargs.get('altStarts', None)
if startType:
dargs['altStarts'] = str(startType[0])
if len(remaining) == 1 and dargs['altStarts'] == 'random':
try:
numRands = int(remaining[0])
dargs['randStarts'] = numRands
except ValueError:
print("Invalid argument given. See --help menu for argument list")
sys.exit()
if len(remaining) > 1:
print("Too many arguments given. See --help menu for argument list")
sys.exit()
else:
if remaining:
print("Too many arguments given. See --help menu for argument list")
sys.exit()
try:
fh = open(qfname, 'rb')
except IOError:
sys.stderr.write("Unable to open '%s' for reading" % qfname)
return 1
iformat = GetFormatExtension(qfname)
ofname = dargs.pop('results')
oformat = GetFormatExtension(ofname)
s = ServerProxy("http://" + dargs.pop('server:port'))
data = Binary(fh.read())
try:
idx = s.SubmitQuery(data, numHits, iformat, oformat, dargs)
except Fault as e:
sys.stderr.write(str(e))
return 1
while True:
blocking = True
try:
current, total = s.QueryStatus(idx, blocking)
hist = s.QueryHistogram(idx)
except Fault as e:
print(str(e), file=sys.stderr)
return 1
if total == 0:
continue
PrintHistogram(hist, dargs.get('tversky', None), dargs.get('shapeOnly', None))
if total <= current:
break
results = s.QueryResults(idx)
# assuming the results come back as a string in the requested format
with open(ofname, 'wb') as output:
output.write(results.data)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 6: AsIs starts.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
import os
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage("%s <database.oeb> <queries> <hits.oeb>" % argv[0])
return 0
# check system
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
# read in database
dbname = argv[1]
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez", dbname)
print("Opening database file %s ..." % dbname)
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots, oefastrocs.OEFastROCSOrientation_AsIs):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
# customize search options
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetInitialOrientation(oefastrocs.OEFastROCSOrientation_AsIs)
opts.SetLimit(50)
opts.SetMaxConfs(5)
opts.SetMaxOverlays(opts.GetNumInertialStarts() * opts.GetNumStarts())
if opts.GetInitialOrientation() == oefastrocs.OEFastROCSOrientation_AsIs:
numStarts = opts.GetNumStarts()
numInertialStarts = opts.GetNumInertialStarts()
oechem.OEThrow.Info("This example will use %u starts & %u inertial starts"
% (numStarts, numInertialStarts))
qfname = argv[2]
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
# write out everthing to a similary named file
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[3])
oechem.OEWriteMolecule(ofs, query)
print("Searching for %s" % qfname)
for score in dbase.GetSortedScores(query, opts):
print("Score for mol %u(conf %u) %f shape %f color" % (
score.GetMolIdx(), score.GetConfIdx(),
score.GetShapeTanimoto(), score.GetColorTanimoto()))
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % argv[3])
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 7: Database searching with queries.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
from openeye import oeshape
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
dbname = argv[1]
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez" % dbname)
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
print("Opening database file %s ..." % dbname)
timer = oechem.OEWallTimer()
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifs):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
dots.Total()
print("%f seconds to load database" % timer.Elapsed())
for qfname in argv[2:]:
ext = oechem.OEGetFileExtension(qfname)
base = qfname[:-(len(ext) + 1)]
if ext == 'sq':
query = oeshape.OEShapeQuery()
if not oeshape.OEReadShapeQuery(qfname, query):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
ext = 'oeb'
else:
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
# write out everthing to a similary named file
ofs = oechem.oemolostream()
ofname = base + "_results." + ext
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
print("Searching for %s" % qfname)
numHits = moldb.NumMols()
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetLimit(numHits)
for score in dbase.GetSortedScores(query, opts):
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % ofname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 8: Database searching with every conformer of every query.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
import argparse
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
parser = argparse.ArgumentParser()
# positional arguments retaining backward compatibility
parser.add_argument('database',
help='File containing the database molecules to be search \
(format not restricted to *.oeb).')
parser.add_argument('query', default=[], nargs='+',
help='File containing the query molecule(s) to be search \
(format not restricted to *.oeb).')
parser.add_argument('--nHits', dest='nHits', type=int, default=100,
help='Number of hits to return (default = number of database mols).')
parser.add_argument('--cutoff', dest='cutoff', type=float, default=argparse.SUPPRESS,
help='Specify a cutoff criteria for scores.')
parser.add_argument('--tversky', dest='tversky', action='store_true', default=argparse.SUPPRESS,
help='Switch to Tversky similarity scoring (default = Tanimoto).')
args = parser.parse_args()
dbname = args.database
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez", dbname)
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
# set options
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetLimit(args.nHits)
print("Number of hits set to %u" % opts.GetLimit())
if hasattr(args, 'cutoff') is not False:
opts.SetCutoff(args.cutoff)
print("Cutoff set to %f" % args.cutoff)
if hasattr(args, 'tversky') is not False:
opts.SetSimFunc(args.tversky)
print("Tversky similarity scoring set.")
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
print("\nOpening database file %s ..." % dbname)
timer = oechem.OEWallTimer()
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifs):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
dots.Total()
print("%f seconds to load database\n" % timer.Elapsed())
for qfname in args.query:
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
mcmol = oechem.OEMol()
if not oechem.OEReadMolecule(qfs, mcmol):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
qfs.rewind()
ext = oechem.OEGetFileExtension(qfname)
qmolidx = 0
while oechem.OEReadMolecule(qfs, mcmol):
# write out to file name based on molecule title
ofs = oechem.oemolostream()
moltitle = mcmol.GetTitle()
if len(moltitle) == 0:
moltitle = str(qmolidx)
ofname = moltitle + "_results." + ext
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
print("Searching for %s of %s (%s conformers)" % (moltitle, qfname, mcmol.NumConfs()))
qconfidx = 0
for conf in mcmol.GetConfs():
for score in dbase.GetSortedScores(conf, opts):
dbmol = oechem.OEMol()
dbmolidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, dbmolidx):
print("Unable to retrieve molecule '%u' from the database" % dbmolidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "QueryConfidx", "%s" % qconfidx)
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
qconfidx += 1
print("%s conformers processed" % qconfidx)
print("Wrote results to %s\n" % ofname)
qmolidx += 1
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 9: Database searching with queries using Tversky similarity scoring.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
dbname = argv[1]
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez", dbname)
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
print("Opening database file %s ..." % dbname)
timer = oechem.OEWallTimer()
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifs):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
dots.Total()
print("%s seconds to load database" % timer.Elapsed())
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetSimFunc(oefastrocs.OEShapeSimFuncType_Tversky)
numHits = moldb.NumMols()
opts.SetLimit(numHits)
for qfname in argv[2:]:
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[1])
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % argv[1])
ext = oechem.OEGetFileExtension(qfname)
base = qfname[:-(len(ext) + 1)]
# write out everthing to a similary named file
ofs = oechem.oemolostream()
ofname = base + "_results." + ext
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
print("Searching for %s" % qfname)
for score in dbase.GetSortedScores(query, opts):
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTversky", "%.4f" % score.GetShapeTversky())
oechem.OESetSDData(mol, "ColorTversky", "%.4f" % score.GetColorTversky())
oechem.OESetSDData(mol, "TverskyCombo", "%.4f" % score.GetTverskyCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % ofname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 10: Optimize over color overlap in addition to shape overlap.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
dbname = argv[1]
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
print("Opening database file %s ..." % dbname)
timer = oechem.OEWallTimer()
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifs):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
dots.Total()
print("%f seconds to load database" % timer.Elapsed())
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetColorOptimization(True)
for qfname in argv[2:]:
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
ext = oechem.OEGetFileExtension(qfname)
base = qfname[:-(len(ext) + 1)]
# write out everthing to a similary named file
ofs = oechem.oemolostream()
ofname = base + "_results." + ext
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
print("Searching for %s" % qfname)
numhits = moldb.NumMols()
opts.SetLimit(numhits)
for score in dbase.GetSortedScores(query, opts):
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % ofname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 11: Cache custom color atoms onto molecules.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
# Cache custom color atoms onto a molecule to be used by FastROCS
import os
import sys
from openeye import oechem
from openeye import oeshape
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
COLOR_FORCE_FIELD = """#
TYPE negative
#
#
PATTERN negative [-]
PATTERN negative [OD1+0]-[!#7D3]~[OD1+0]
PATTERN negative [OD1+0]-[!#7D4](~[OD1+0])~[OD1+0]
#
#
INTERACTION negative negative attractive gaussian weight=1.0 radius=1.0
"""
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <input> <output>" % argv[0])
# input - preserve rotor-offset-compression
ifs = oechem.oemolistream()
ihand = ifs.GetBinaryIOHandler()
ihand.Clear()
oechem.OEInitHandler(ihand, oechem.OEBRotCompressOpts(), oechem.OEBRotCompressOpts())
ifname = argv[1]
if not ifs.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
# output
ofname = argv[2]
oformt = oechem.OEGetFileType(oechem.OEGetFileExtension(ofname))
if oformt != oechem.OEFormat_OEB:
oechem.OEThrow.Fatal("Output file format much be OEB")
ofs = oechem.oemolostream()
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open %s for writing" % ofname)
iss = oechem.oeisstream(COLOR_FORCE_FIELD)
cff = oeshape.OEColorForceField()
if not cff.Init(iss):
oechem.OEThrow.Fatal("Unable to initialize OEColorForceField")
dots = oechem.OEDots(10000, 200, "molecules")
for mol in ifs.GetOEMols():
oefastrocs.OEPrepareFastROCSMol(mol, cff)
oechem.OEWriteMolecule(ofs, mol)
dots.Update()
dots.Total()
ofs.close()
print("Indexing %s" % ofname)
if not oechem.OECreateMolDatabaseIdx(ofname):
oechem.OEThrow.Fatal("Failed to index %s" % argv[2])
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 12: Run FastROCS with the implicit Mills-Dean color force field, sans rings.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
from openeye import oeshape
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
dbname = argv[1]
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
print("Opening database file %s ..." % dbname)
timer = oechem.OEWallTimer()
cff = oeshape.OEColorForceField()
cff.Init(oeshape.OEColorFFType_ImplicitMillsDeanNoRings)
dbase = oefastrocs.OEShapeDatabase(cff)
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifs):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
dots.Total()
print("%f seconds to load database" % timer.Elapsed())
opts = oefastrocs.OEShapeDatabaseOptions()
for qfname in argv[2:]:
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
ext = oechem.OEGetFileExtension(qfname)
base = qfname[:-(len(ext) + 1)]
# write out everthing to a similary named file
ofs = oechem.oemolostream()
ofname = base + "_results." + ext
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
print("Searching for %s" % qfname)
numhits = moldb.NumMols()
opts.SetLimit(numhits)
for score in dbase.GetSortedScores(query, opts):
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % ofname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 13: Database searching with queries using the inertial at heavy atoms starting orientation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 4:
oechem.OEThrow.Usage("%s <database.oeb> <queries> <hits.oeb>" % argv[0])
return 0
# check system
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
# read in database
dbname = argv[1]
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez", dbname)
print("Opening database file %s ..." % dbname)
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
# customize search options
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetLimit(5)
opts.SetInitialOrientation(oefastrocs.OEFastROCSOrientation_InertialAtHeavyAtoms)
qfname = argv[2]
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
# write out everthing to a similary named file
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[3])
oechem.OEWriteMolecule(ofs, query)
if opts.GetInitialOrientation() == oefastrocs.OEFastROCSOrientation_InertialAtHeavyAtoms:
numStarts = opts.GetNumHeavyAtomStarts(query)
print("This example will use %u starts" % numStarts)
opts.SetMaxOverlays(opts.GetNumInertialStarts() * opts.GetNumHeavyAtomStarts(query))
print("Searching for %s" % qfname)
for score in dbase.GetSortedScores(query, opts):
print("Score for mol %u(conf %u) %f shape %f color" % (
score.GetMolIdx(), score.GetConfIdx(),
score.GetShapeTanimoto(), score.GetColorTanimoto()))
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % argv[3])
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 14: Turn on ROCS mode.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage("%s <database> [<queries> ... ]" % argv[0])
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
dbname = argv[1]
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
print("Opening database file %s ..." % dbname)
timer = oechem.OEWallTimer()
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifs):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
dots.Total()
print("%f seconds to load database" % timer.Elapsed())
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetFastROCSMode(oefastrocs.OEFastROCSMode_ROCS)
for qfname in argv[2:]:
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
ext = oechem.OEGetFileExtension(qfname)
base = qfname[:-(len(ext) + 1)]
# write out everthing to a similary named file
ofs = oechem.oemolostream()
ofname = base + "_results." + ext
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[4])
print("Searching for %s" % qfname)
numhits = moldb.NumMols()
opts.SetLimit(numhits)
for score in dbase.GetSortedScores(query, opts):
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % ofname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 15: Cluster database into shape clusters.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
# Shape clustering
import sys
import os
from openeye import oechem
from openeye import oeshape
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def GetScoreGetter(shapeOnly=False):
if shapeOnly:
return oefastrocs.OEShapeDatabaseScore.GetShapeTanimoto
return oefastrocs.OEShapeDatabaseScore.GetTanimotoCombo
class ShapeCluster:
def __init__(self, dbname, cutoff, shapeOnly):
self.cutoff = cutoff
# set up and options and database based upon shapeOnly
self.defaultOptions = oefastrocs.OEShapeDatabaseOptions()
dbtype = oefastrocs.OEShapeDatabaseType_Default
if shapeOnly:
dbtype = oefastrocs.OEShapeDatabaseType_Shape
self.defaultOptions.SetScoreType(dbtype)
self.shapedb = oefastrocs.OEShapeDatabase(dbtype)
self.dbmols = []
volumes = []
# read in database
ifs = oechem.oemolistream()
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
count = 0
for mol in ifs.GetOEGraphMols():
title = mol.GetTitle()
if not title:
title = "Untitled" + str(count)
mol.SetTitle(title)
count += 1
idx = self.shapedb.AddMol(oechem.OEMol(mol))
volume = oeshape.OEGetCachedSelfShape(mol)
if volume == 0.0:
volume = oeshape.OESelfShape(mol)
volumes.append((volume, idx))
dbmol = oechem.OEGraphMol(mol, oechem.OEMolBaseType_OEDBMol)
dbmol.Compress()
self.dbmols.append(dbmol)
numMols = len(volumes)
# find the molecule with the median volume as our first query
volumes.sort()
medianVolume, medianIdx = volumes[numMols // 2]
self.nextClusterHeadIdx = medianIdx
self.remainingMolecules = numMols
self.tanimotos = [0.0] * numMols
self.scoreGetter = GetScoreGetter(shapeOnly)
def HasRemainingMolecules(self):
return self.remainingMolecules != 0
def _removeMolecule(self, idx):
self.remainingMolecules -= 1
assert self.dbmols[idx] is not None
dbmol = self.dbmols[idx]
dbmol.UnCompress()
self.dbmols[idx] = None
assert self.tanimotos[idx] is not None
self.tanimotos[idx] = sys.float_info.max
return dbmol
def GetNextClusterHead(self):
assert self.nextClusterHeadIdx is not None
return self._removeMolecule(self.nextClusterHeadIdx)
def GetCluster(self, query):
options = oefastrocs.OEShapeDatabaseOptions(self.defaultOptions)
dots = oechem.OEDots(10000, 200, "molecules searched")
minTani = sys.float_info.max
minIdx = None
for score in self.shapedb.GetScores(query, options):
idx = score.GetMolIdx()
# check if already in a cluster
if self.dbmols[idx] is None:
continue
if self.cutoff < self.scoreGetter(score):
yield self._removeMolecule(idx), score
else:
self.tanimotos[idx] = max(self.tanimotos[idx], self.scoreGetter(score))
minTani, minIdx = min((minTani, minIdx), (self.tanimotos[idx], idx))
dots.Update()
dots.Total()
self.nextClusterHeadIdx = minIdx
InterfaceData = """\
!BRIEF [-shapeOnly] [-cutoff 0.75] [-dbase] <database> [-clusters] <clusters.oeb>
!PARAMETER -dbase
!TYPE string
!REQUIRED true
!BRIEF Input database to select from
!KEYLESS 1
!END
!PARAMETER -clusters
!TYPE string
!REQUIRED true
!BRIEF Output to write clusters to
!KEYLESS 2
!END
!PARAMETER -shapeOnly
!ALIAS -s
!TYPE bool
!DEFAULT false
!BRIEF Run FastROCS in shape only mode.
!END
!PARAMETER -cutoff
!ALIAS -c
!TYPE float
!DEFAULT 0.75
!BRIEF Number of random pairs to sample.
!END
"""
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
dbname = itf.GetString("-dbase")
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez", dbname)
cutoff = itf.GetFloat("-cutoff")
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-clusters")):
oechem.OEThrow.Fatal("Unable to open '%s'" % itf.GetString("-clusters"))
if ofs.GetFormat() != oechem.OEFormat_OEB:
oechem.OEThrow.Fatal("Output file must be OEB")
sdtag = "TanimotoComboFromHead"
if itf.GetBool("-shapeOnly"):
sdtag = "ShapeTanimotoFromHead"
getter = GetScoreGetter(itf.GetBool("-shapeOnly"))
cluster = ShapeCluster(dbname, cutoff, itf.GetBool("-shapeOnly"))
# do the clustering
while cluster.HasRemainingMolecules():
clusterHead = cluster.GetNextClusterHead()
print("Searching for neighbors of %s" % clusterHead.GetTitle())
for nbrMol, score in cluster.GetCluster(clusterHead):
oechem.OESetSDData(nbrMol, sdtag, "%.4f" % getter(score))
score.Transform(nbrMol)
clusterHead.AddData(nbrMol.GetTitle(), nbrMol)
oechem.OEWriteMolecule(ofs, clusterHead)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 16: Split database into chunks.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
# Split a multi-conformer database into N chunks keeping molecules
# with the same number of atoms in each chunk. Also caches other
# useful information onto the molecule to improve database load time.
import sys
import os
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) != 4:
oechem.OEThrow.Usage("%s <database> <prefix> <n_servers>" % argv[0])
# input - preserve rotor-offset-compression
ifs = oechem.oemolistream()
oechem.OEPreserveRotCompress(ifs)
ifname = argv[1]
if not ifs.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
# output
prefix = argv[2]
ext = oechem.OEGetFileExtension(prefix)
extstrt = len(prefix)
if ext:
extstrt = -(len(ext) + 1)
else:
ext = oechem.OEGetFileExtension(ifname)
base = prefix[:extstrt]
fmt = base + "_%i." + ext
nservers = int(argv[3])
outstrms = []
for i in range(1, nservers + 1):
ofs = oechem.oemolostream()
if not ofs.open(fmt % i):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
outstrms.append(ofs)
dots = oechem.OEDots(10000, 200, "molecules")
for mol in ifs.GetOEMols():
oefastrocs.OEPrepareFastROCSMol(mol)
nhvyatoms = oechem.OECount(mol, oechem.OEIsHeavy())
ofs = outstrms[nhvyatoms % nservers]
oechem.OEWriteMolecule(ofs, mol)
dots.Update()
dots.Total()
for strm in outstrms:
fname = strm.GetFileName()
strm.close()
oechem.OEThrow.Info("Indexing %s" % fname)
if not oechem.OECreateMolDatabaseIdx(fname):
oechem.OEThrow.Fatal("Failed to index %s" % fname)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 17: Send query to specified server.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
import argparse
try:
from xmlrpclib import ServerProxy, Binary, Fault
except ImportError: # python 3
from xmlrpc.client import ServerProxy, Binary, Fault
def GetFormatExtension(fname):
base, ext = os.path.splitext(fname.lower())
if ext == ".gz":
base, ext = os.path.splitext(base)
ext += ".gz"
return ext
def main(argv=[__name__]):
parser = argparse.ArgumentParser()
# positional arguments retaining backward compatibility
parser.add_argument('server:port', help='Server name and port number of database to search '
'i.e. localhost:8080.')
parser.add_argument('query', help='File containing the query molecule to search '
'(format not restricted to *.oeb).')
parser.add_argument('results',
help='Output file to store results (format not restricted to *.oeb).')
parser.add_argument('nHits', nargs='?', type=int, default=100,
help='Number of hits to return (default=100).')
parser.add_argument('--tversky', action='store_true', default=argparse.SUPPRESS,
help='Switch to Tversky similarity scoring (default=Tanimoto).')
parser.add_argument('--shapeOnly', action='store_true', default=argparse.SUPPRESS,
help='Switch to shape-only scores (default=Combo).')
parser.add_argument('--alternativeStarts', default=argparse.SUPPRESS, nargs=1, dest='altStarts',
choices=('random', 'subrocs',
'inertialAtHeavyAtoms', 'inertialAtColorAtoms'),
help='Optimize using alternative starts (default=inertial). '
'To perform N random starts do '
'"--alternativeStarts random N" (default N=10)')
known, remaining = (parser.parse_known_args())
dargs = vars(known)
qfname = dargs.pop('query')
numHits = dargs.pop('nHits')
startType = dargs.get('altStarts', None)
if startType:
dargs['altStarts'] = str(startType[0])
if len(remaining) == 1 and dargs['altStarts'] == 'random':
try:
numRands = int(remaining[0])
dargs['randStarts'] = numRands
except ValueError:
print("Invalid argument given. See --help menu for argument list")
sys.exit()
if len(remaining) > 1:
print("Too many arguments given. See --help menu for argument list")
sys.exit()
else:
if remaining:
print("Too many arguments given. See --help menu for argument list")
sys.exit()
try:
fh = open(qfname, 'rb')
except IOError:
sys.stderr.write("Unable to open '%s' for reading" % qfname)
return 1
iformat = GetFormatExtension(qfname)
ofname = dargs.pop('results')
oformat = GetFormatExtension(ofname)
s = ServerProxy("http://" + dargs.pop('server:port'))
data = Binary(fh.read())
try:
idx = s.SubmitQuery(data, numHits, iformat, oformat, dargs)
except Fault as e:
if "TypeError" in e.faultString:
# we're trying to run against an older server, may be able
# to still work if the formats ameniable.
if ((iformat == ".oeb" or iformat == ".sq") and oformat == ".oeb"):
idx = s.SubmitQuery(data, numHits)
else:
sys.stderr.write("%s is too new of a version to work with the server %s\n"
% (argv[0], argv[1]))
sys.stderr.write("Please upgrade your server to FastROCS version 1.4.0"
" or later to be able to use this client\n")
sys.stderr.write("This client will work with this version of the server "
"if the input file is either"
"'.oeb' or '.sq' and the output file is '.oeb'\n")
return 1
else:
sys.stderr.write(str(e))
return 1
first = False
while True:
blocking = True
try:
current, total = s.QueryStatus(idx, blocking)
except Fault as e:
print(str(e), file=sys.stderr)
return 1
if total == 0:
continue
if first:
print("%s/%s" % ("current", "total"))
first = False
print("%i/%i" % (current, total))
if total <= current:
break
results = s.QueryResults(idx)
# assuming the results come back as a string in the requested format
with open(ofname, 'wb') as output:
output.write(results.data)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 18: Run the FastROCS server.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
import os
import socket
try:
from SocketServer import ThreadingMixIn
except ImportError:
from socketserver import ThreadingMixIn
from threading import Thread
from threading import Lock
from threading import Condition
from threading import Event
from openeye import oechem
from openeye import oeshape
try:
from openeye import oefastrocs
except ImportError:
oechem.OEThrow.Fatal("This script is not available, "
"FastROCS is not supported on this platform.")
try:
from xmlrpclib import Binary
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
except ImportError: # python 3
from xmlrpc.client import Binary
from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
# very important that OEChem is in this mode since we are passing molecules between threads
oechem.OESetMemPoolMode(oechem.OEMemPoolMode_System)
class ReadWriteLock(object):
""" Basic locking primitive that allows multiple readers but only
a single writer at a time. Useful for synchronizing database
updates. Priority is given to pending writers. """
def __init__(self):
self.cond = Condition()
self.readers = 0
self.writers = 0
def AcquireReadLock(self):
self.cond.acquire()
try:
while self.writers:
self.cond.wait()
self.readers += 1
assert self.writers == 0
finally:
self.cond.notify_all()
self.cond.release()
def ReleaseReadLock(self):
self.cond.acquire()
assert self.readers > 0
try:
self.readers -= 1
finally:
self.cond.notify_all()
self.cond.release()
def AcquireWriteLock(self):
self.cond.acquire()
self.writers += 1
while self.readers:
self.cond.wait()
assert self.readers == 0
assert self.writers > 0
def ReleaseWriteLock(self):
assert self.readers == 0
assert self.writers > 0
self.writers -= 1
self.cond.notify_all()
self.cond.release()
class ShapeQueryThread(Thread):
""" A thread to run a query against a shape database """
def __init__(self, shapedb, querymolstr, nhits, iformat, oformat, errorLevel, **kwargs):
""" Create a new thread to perform a query. The query doesn't
execute until start is called.
shapedb - database to run the query against
See MCMolShapeDatabase.GetBestOverlays for a description of
the querymolstr and nhits arguments.
"""
Thread.__init__(self)
self.shapeOnly = kwargs.pop('shapeOnly', False)
self.tversky = kwargs.pop('tversky', False)
self.altStarts = kwargs.pop('altStarts', False)
self.randStarts = kwargs.pop('randStarts', False)
self.shapedb = shapedb
self.querymolstr = querymolstr
self.iformat = iformat
self.oformat = oformat
self.scoretype = GetDatabaseType(self.shapeOnly)
self.simFuncType = GetSimFuncType(self.tversky)
numHistBins = 200
if self.shapeOnly:
numHistBins = 100
self.tracer = oefastrocs.OEDBTracer(numHistBins)
self.options = oefastrocs.OEShapeDatabaseOptions()
self.options.SetTracer(self.tracer)
self.options.SetLimit(nhits)
self.options.SetScoreType(self.scoretype)
self.options.SetSimFunc(self.simFuncType)
if self.altStarts:
self.options.SetInitialOrientation(GetStartType(self.altStarts))
if self.randStarts:
self.options.SetNumRandomStarts(self.randStarts)
self.lock = Lock()
self.errorLevel = errorLevel
def run(self):
""" Perform the query """
# make sure the error level is set for this operating system thread
oechem.OEThrow.SetLevel(self.errorLevel)
try:
results = self.shapedb.GetBestOverlays(self.querymolstr,
self.options,
self.iformat,
self.oformat)
# since we are writing to the thread's dictionary this could
# race with the GetStatus method below
self.lock.acquire()
try:
self.results = results
if not results:
self.exception = RuntimeError("Query error, no results to return, "
"check the server log for more information")
finally:
self.lock.release()
except Exception as e:
self.lock.acquire()
try:
self.exception = e
finally:
self.lock.release()
def GetStatus(self, blocking):
""" Returns a tuple of (count, total). count is the number of
conformers already searched. total is the total number of
conformers that will be searched.
If blocking is True this method will not return until the
count has been changed (beware of deadlocks!). If blocking is
False the function will return immediately.
"""
self.lock.acquire()
try:
if hasattr(self, "exception"):
raise self.exception
return self.tracer.GetCounts(blocking), self.tracer.GetTotal()
finally:
self.lock.release()
def GetHistogram(self):
""" Returns a list of integers representing the histogram of
the molecule scores already scored.
"""
self.lock.acquire()
try:
if hasattr(self, "exception"):
raise self.exception
hist = self.tracer.GetHistogram()
scoretype = self.scoretype
finally:
self.lock.release()
frequencies = oechem.OEUIntVector()
hist.GetHistogram(frequencies, scoretype)
return list(frequencies)
def GetResults(self):
""" Return an OEB string containing the overlaid
confomers. This method should only be called after this thread
has been joined. """
if hasattr(self, "exception"):
raise self.exception
return self.results
class ShapeQueryThreadPool:
"""
Maintains a pool of threads querying the same MCMolShapeDatabase.
"""
def __init__(self, dbase):
""" Create a new thread pool to issues queries to dbase """
self.shapedb = dbase
self.queryidx = 0
self.threads = {}
self.lock = Lock()
self.errorLevel = oechem.OEThrow.GetLevel()
def SubmitQuery(self, querymolstr, nhits, iformat, oformat, kwargs):
""" Returns an index that can be passed to the QueryStatus and
QueryResults methods.
See MCMolShapeDatabase.GetBestOverlays for a description of
the querymolstr and nhits arguments.
"""
self.lock.acquire()
try:
idx = self.queryidx
self.queryidx += 1
self.threads[idx] = ShapeQueryThread(self.shapedb,
querymolstr,
nhits,
iformat,
oformat,
self.errorLevel,
**kwargs)
self.threads[idx].start()
finally:
self.lock.release()
return idx
def QueryStatus(self, idx, blocking):
""" Returns the status of the query indicated by idx. See
ShapeQueryThread.GetStatus for the description of the blocking
argument. """
self.lock.acquire()
try:
thrd = self.threads[idx]
finally:
self.lock.release()
return thrd.GetStatus(blocking)
def QueryHistogram(self, idx):
""" Returns the histogram of molecule scores already scored
for the query indicated by idx. """
self.lock.acquire()
try:
thrd = self.threads[idx]
finally:
self.lock.release()
return thrd.GetHistogram()
def QueryResults(self, idx):
""" Wait for the query associated with idx to complete and
then return the results as an OEB string. """
self.lock.acquire()
try:
thrd = self.threads[idx]
del self.threads[idx]
finally:
self.lock.release()
thrd.join()
return thrd.GetResults()
def SetLevel(self, level):
""" Set what level of information should be printed by the server. """
self.errorLevel = level
return True
class DatabaseLoaderThread(Thread):
""" A thread to read a database into memory. Special note, OEChem
must be placed in system allocation mode using
oechem.OESetMemPoolMode(oechem.OEMemPoolMode_System). This is because the
default OEChem memory caching scheme uses thread local storage,
but since this thread is temporary only for reading in molecules
that memory will be deallocated when this thread is terminated."""
def __init__(self, shapedb, moldb, dbname, loadedEvent):
"""
shapedb - the shapedb to add the molecules to
moldb - the OEMolDatabase object to use
dbname - the file name to open the OEMolDatabase on
loadedEvent - event to set once loading is finished
"""
Thread.__init__(self)
self.shapedb = shapedb
self.moldb = moldb
self.dbname = dbname
self.loadedEvent = loadedEvent
def run(self):
""" Open the database file and load it into the OEShapeDatabase """
timer = oechem.OEWallTimer()
sys.stderr.write("Opening database file %s ...\n" % self.dbname)
if not self.moldb.Open(self.dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % self.dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not self.shapedb.Open(self.moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % self.dbname)
dots.Total()
sys.stderr.write("%s seconds to load database\n" % timer.Elapsed())
self.loadedEvent.set()
def SetupStream(strm, format):
format = format.strip('.')
ftype = oechem.OEGetFileType(format)
if ftype == oechem.OEFormat_UNDEFINED:
raise ValueError("Unsupported file format sent to server '%s'" % format)
strm.SetFormat(ftype)
strm.Setgz(oechem.OEIsGZip(format))
return strm
OECOLOR_FORCEFIELDS = {
"ImplicitMillsDean": oeshape.OEColorFFType_ImplicitMillsDean,
"ImplicitMillsDeanNoRings": oeshape.OEColorFFType_ImplicitMillsDeanNoRings,
"ExplicitMillsDean": oeshape.OEColorFFType_ExplicitMillsDean,
"ExplicitMillsDeanNoRings": oeshape.OEColorFFType_ExplicitMillsDeanNoRings
}
def GetDatabaseType(shapeOnly):
if shapeOnly:
return oefastrocs.OEShapeDatabaseType_Shape
return oefastrocs.OEShapeDatabaseType_Default
def GetSimFuncType(simFuncType):
if simFuncType:
return oefastrocs.OEShapeSimFuncType_Tversky
return oefastrocs.OEShapeSimFuncType_Tanimoto
def GetStartType(altStarts):
if altStarts == 'random':
return oefastrocs.OEFastROCSOrientation_Random
if altStarts == 'inertialAtHeavyAtoms':
return oefastrocs.OEFastROCSOrientation_InertialAtHeavyAtoms
if altStarts == 'inertialAtColorAtoms':
return oefastrocs.OEFastROCSOrientation_InertialAtColorAtoms
if altStarts == 'subrocs':
return oefastrocs.OEFastROCSOrientation_Subrocs
return oefastrocs.OEFastROCSOrientation_Inertial
def GetAltStartsString(altStarts):
if altStarts == oefastrocs.OEFastROCSOrientation_Random:
return 'random'
if altStarts == oefastrocs.OEFastROCSOrientation_InertialAtHeavyAtoms:
return 'inertialAtHeavyAtoms'
if altStarts == oefastrocs.OEFastROCSOrientation_InertialAtColorAtoms:
return 'inertialAtColorAtoms'
if altStarts == oefastrocs.OEFastROCSOrientation_Subrocs:
return 'subrocs'
return 'inertial'
def GetShapeDatabaseArgs(itf):
shapeOnly = itf.GetBool("-shapeOnly")
if shapeOnly and itf.GetParameter("-chemff").GetHasValue():
oechem.OEThrow.Fatal("Unable to specify -shapeOnly and -chemff at the same time!")
chemff = itf.GetString("-chemff")
if not chemff.endswith(".cff"):
return (GetDatabaseType(shapeOnly), OECOLOR_FORCEFIELDS[chemff])
# given a .cff file, use that to construct a OEColorForceField
assert not shapeOnly
cff = oeshape.OEColorForceField()
if not cff.Init(chemff):
oechem.OEThrow.Fatal("Unable to read color force field from '%s'" % chemff)
return (cff,)
def ReadShapeQuery(querymolstr):
iss = oechem.oeisstream(querymolstr)
query = oeshape.OEShapeQueryPublic()
if not oeshape.OEReadShapeQuery(iss, query):
raise ValueError("Unable to read a shape query from the data string")
return query
class MCMolShapeDatabase:
""" Maintains a database of MCMols that can be queried by shape
similarity."""
def __init__(self, itf):
""" Create a MCMolShapeDatabase from the parameters specified by the OEInterface. """
self.rwlock = ReadWriteLock()
self.loadedEvent = Event()
self.dbname = itf.GetString("-dbase")
if oechem.OEIsGZip(self.dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped. "
"Preferred formats are .oeb, .sdf or .oez" % self.dbname)
self.moldb = oechem.OEMolDatabase()
self.dbtype = GetDatabaseType(itf.GetBool("-shapeOnly"))
self.shapedb = oefastrocs.OEShapeDatabase(*GetShapeDatabaseArgs(itf))
# this thread is daemonic so a KeyboardInterupt
# during the load will cancel the process
self.loaderThread = DatabaseLoaderThread(self.shapedb,
self.moldb,
self.dbname,
self.loadedEvent)
self.loaderThread.daemon = True
self.loaderThread.start()
def IsLoaded(self, blocking=False):
""" Return whether the server has finished loading. """
if blocking:
self.loadedEvent.wait()
# clean up the load waiter thread if it's still there
if self.loadedEvent.is_set() and self.loaderThread is not None:
self.rwlock.AcquireWriteLock()
try: # typical double checked locking
if self.loaderThread is not None:
self.loaderThread.join()
self.loaderThread = None
finally:
self.rwlock.ReleaseWriteLock()
return self.loadedEvent.is_set()
def GetBestOverlays(self, querymolstr, options, iformat, oformat):
""" Return a string of the format specified by 'oformat'
containing nhits overlaid confomers using querymolstr as the
query interpretted as iformat.
querymolstr - a string containing a molecule to use as the query
options - an instance of OEShapeDatabaseOptions
iformat - a string representing the file extension to parse the querymolstr as.
Note: old clients could be passing .sq files, so
iformat == '.oeb' will try to interpret the file as
a .sq file.
oformat - file format to write the results as
"""
timer = oechem.OEWallTimer()
# make sure to wait for the load to finish
blocking = True
loaded = self.IsLoaded(blocking)
assert loaded
if iformat.startswith(".sq"):
query = ReadShapeQuery(querymolstr)
else:
# read in query
qfs = oechem.oemolistream()
qfs = SetupStream(qfs, iformat)
if not qfs.openstring(querymolstr):
raise ValueError("Unable to open input molecule string")
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
if iformat == ".oeb": # could be an old client trying to send a .sq file.
query = ReadShapeQuery(querymolstr)
else:
raise ValueError("Unable to read a molecule from the string of format '%s'"
% iformat)
ofs = oechem.oemolostream()
ofs = SetupStream(ofs, oformat)
if not ofs.openstring():
raise ValueError("Unable to openstring for output")
# do we only want shape based results?
# this is a "Write" lock to be paranoid and not overload the GPU
self.rwlock.AcquireWriteLock()
try:
# do search
scores = self.shapedb.GetSortedScores(query, options)
sys.stderr.write("%f seconds to do search\n" % timer.Elapsed())
finally:
self.rwlock.ReleaseWriteLock()
timer.Start()
# write results
for score in scores:
mcmol = oechem.OEMol()
if not self.moldb.GetMolecule(mcmol, score.GetMolIdx()):
oechem.OEThrow.Warning("Can't retrieve molecule %i from the OEMolDatabase, "
"skipping..." % score.GetMolIdx())
continue
# remove hydrogens to make output smaller, this also
# ensures OEPrepareFastROCSMol will have the same output
oechem.OESuppressHydrogens(mcmol)
mol = oechem.OEGraphMol(mcmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OECopySDData(mol, mcmol)
if options.GetSimFunc() == oefastrocs.OEShapeSimFuncType_Tanimoto:
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
else:
oechem.OESetSDData(mol, "ShapeTversky", "%.4f" % score.GetShapeTversky())
oechem.OESetSDData(mol, "ColorTversky", "%.4f" % score.GetColorTversky())
oechem.OESetSDData(mol, "TverskyCombo", "%.4f" % score.GetTverskyCombo())
if options.GetInitialOrientation() != oefastrocs.OEFastROCSOrientation_Inertial:
oechem.OEAddSDData(mol, "Opt. Starting Pos.",
GetAltStartsString(options.GetInitialOrientation()))
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
output = ofs.GetString()
sys.stderr.write("%f seconds to write hitlist\n" % timer.Elapsed())
sys.stderr.flush()
ofs.close()
return output
def GetName(self):
self.rwlock.AcquireReadLock()
try:
return self.dbname
finally:
self.rwlock.ReleaseReadLock()
def SetName(self, name):
self.rwlock.AcquireWriteLock()
try:
self.dbname = name
finally:
self.rwlock.ReleaseWriteLock()
class ShapeQueryServer:
""" This object's methods are exposed via XMLRPC. """
def __init__(self, itf):
""" Initialize the server to serve queries on the database
named by dbname."""
self.shapedb = MCMolShapeDatabase(itf)
self.thdpool = ShapeQueryThreadPool(self.shapedb)
self.itf = itf
def IsLoaded(self, blocking=False):
""" Return whether the server has finished loading. """
return self.shapedb.IsLoaded(blocking)
def GetBestOverlays(self, querymolstr, nhits, iformat=".oeb", oformat=".oeb"):
""" A blocking call that only returns once the query is completed. """
results = self.shapedb.GetBestOverlays(querymolstr.data, nhits, iformat, oformat)
return Binary(results)
def SubmitQuery(self, querymolstr, nhits, iformat=".oeb", oformat=".oeb", kwargs=None):
""" Returns a index that can be used by QueryStatus and
QueryResults. This method will return immediately."""
if not kwargs:
kwargs = {}
if self.itf.GetBool("-shapeOnly"):
kwargs['shapeOnly'] = True
return self.thdpool.SubmitQuery(querymolstr.data, nhits, iformat, oformat, kwargs)
def QueryStatus(self, queryidx, blocking=False):
""" Return the status of the query specified by queryidx. See
ShapeQueryThread.GetStatus for a description of the blocking
argument and the return value."""
return self.thdpool.QueryStatus(queryidx, blocking)
def QueryHistogram(self, queryidx):
""" Return the current histogram of scores specified by
queryidx."""
return self.thdpool.QueryHistogram(queryidx)
def QueryResults(self, queryidx):
""" Wait for the query associated with idx to complete and
then return the results as an OEB string. """
results = self.thdpool.QueryResults(queryidx)
return Binary(results)
def GetVersion(self):
""" Returns what version of FastROCS this server is. """
return oefastrocs.OEFastROCSGetRelease()
def OEThrowSetLevel(self, level):
""" Set what level of information should be printed by the server. """
return self.thdpool.SetLevel(level)
def GetName(self):
""" The name of this database. By default this is the file name of the database used. """
return self.shapedb.GetName()
def SetName(self, name):
""" Set a custom database name for this server. """
self.shapedb.SetName(name)
return True
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
class AsyncXMLRPCServer(ThreadingMixIn, SimpleXMLRPCServer):
# if a shutdown request occurs through a signal force everything to terminate immediately
daemon_threads = True
allow_reuse_address = True
InterfaceData = """\
!BRIEF [-shapeOnly | -chemff <color forcefield>] [-hostname] [-dbase] database [[-port] 8080]
!PARAMETER -dbase
!TYPE string
!REQUIRED true
!BRIEF Input database to serve
!KEYLESS 1
!END
!PARAMETER -port
!TYPE int
!REQUIRED false
!BRIEF Port number to start the XML RPC server on
!DEFAULT 8080
!KEYLESS 2
!END
!PARAMETER -hostname
!TYPE string
!DEFAULT 0.0.0.0
!BRIEF Name of the server to bind to
!END
!PARAMETER -shapeOnly
!ALIAS -s
!TYPE bool
!DEFAULT false
!BRIEF Run FastROCS server in shape only mode, clients can also control this separately
!END
!PARAMETER -chemff
!TYPE string
!LEGAL_VALUE ImplicitMillsDean
!LEGAL_VALUE ImplicitMillsDeanNoRings
!LEGAL_VALUE ExplicitMillsDean
!LEGAL_VALUE ExplicitMillsDeanNoRings
!LEGAL_VALUE *.cff
!DEFAULT ImplicitMillsDean
!BRIEF Chemical force field. Either a constant or a filename.
!END
"""
def main(argv=[__name__]):
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Fatal("No supported GPU available to run FastROCS TK!")
itf = oechem.OEInterface(InterfaceData, argv)
# default hostname to bind is 0.0.0.0, to allow connections with
# any hostname
hostname = itf.GetString("-hostname")
# default port number is 8080
portnumber = itf.GetInt("-port")
# create server
server = AsyncXMLRPCServer((hostname, portnumber),
requestHandler=RequestHandler,
logRequests=False)
hostname, portnumber = server.socket.getsockname()
if hostname == "0.0.0.0":
hostname = socket.gethostname()
sys.stderr.write("Listening for ShapeDatabaseClient.py requests on %s:%i\n\n"
% (hostname, portnumber))
sys.stderr.write("Example: ShapeDatabaseClient.py %s:%i query.sdf hit.sdf\n\n"
% (hostname, portnumber))
# register the XMLRPC methods
server.register_introspection_functions()
server.register_instance(ShapeQueryServer(itf))
try:
# Run the server's main loop
server.serve_forever()
finally:
server.server_close()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 19: Returns whether the database has completed loading in server:port.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
import socket
try:
from xmlrpclib import ServerProxy
except ImportError: # python 3
from xmlrpc.client import ServerProxy
from time import sleep
from openeye import oechem
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
InterfaceData = """\
!BRIEF [-blocking] [-h] <server:port>
!PARAMETER -host
!ALIAS -h
!TYPE string
!REQUIRED true
!BRIEF The host to check to see if it is up yet
!KEYLESS 1
!END
!PARAMETER -blocking
!ALIAS -b
!TYPE bool
!DEFAULT false
!BRIEF If true the program will not exit until the database has finished loading.
!END
!PARAMETER -retries
!ALIAS -r
!TYPE int
!DEFAULT 10
!BRIEF Number of times to try connecting to the server.
!END
!PARAMETER -timeout
!ALIAS -t
!TYPE float
!DEFAULT 60.0
!BRIEF The time between retries is the timeout divided by the number of retries.
!END
"""
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
host = itf.GetString("-host")
s = ServerProxy("http://" + host)
blocking = itf.GetBool("-blocking")
retries = itf.GetInt("-retries")
if retries < 1:
oechem.OEThrow.Fatal("-retries must be greater than 0")
timeout = itf.GetFloat("-timeout")
if timeout <= 0.0:
oechem.OEThrow.Fatal("-timeout must be greater than 0.0")
waittime = timeout/retries
loaded = False
while retries:
try:
loaded = s.IsLoaded(blocking)
break
except socket.error:
retries -= 1
if retries:
print("Unable to connect to %s, retrying in %2.1f seconds" % (host, waittime))
sleep(waittime)
if not retries:
print("Was never able to connect to a server, exiting...")
return -1
if loaded:
loaded = "True"
else:
loaded = "False"
print(host, "IsLoaded =", loaded)
if loaded:
return 0
return 1
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 20: Adjust the verbosity of server running on server:port.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
try:
from xmlrpclib import ServerProxy
except ImportError: # python 3
from xmlrpc.client import ServerProxy
from openeye import oechem
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
InterfaceData = """\
!BRIEF (-debug|-verbose|-info|-warning|-error) [-h] <server:port>
!PARAMETER -host
!ALIAS -h
!TYPE string
!REQUIRED true
!BRIEF The host whose verbosity level will be changed
!KEYLESS 1
!END
!PARAMETER -debug
!ALIAS -d
!TYPE bool
!DEFAULT false
!BRIEF Debug error level
!END
!PARAMETER -verbose
!ALIAS -v
!TYPE bool
!DEFAULT false
!BRIEF Verbose error level
!END
!PARAMETER -info
!ALIAS -i
!TYPE bool
!DEFAULT false
!BRIEF Info error level
!END
!PARAMETER -warning
!ALIAS -w
!TYPE bool
!DEFAULT false
!BRIEF Warning error level
!END
!PARAMETER -error
!ALIAS -e
!TYPE bool
!DEFAULT false
!BRIEF Unrecoverable error level
!END
"""
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
levels = {"-debug": (oechem.OEErrorLevel_Debug, "oechem.OEErrorLevel_Debug"),
"-verbose": (oechem.OEErrorLevel_Verbose, "oechem.OEErrorLevel_Verbose"),
"-info": (oechem.OEErrorLevel_Info, "oechem.OEErrorLevel_Info"),
"-warning": (oechem.OEErrorLevel_Warning, "oechem.OEErrorLevel_Warning"),
"-error": (oechem.OEErrorLevel_Error, "oechem.OEErrorLevel_Error")}
onFlags = [key for key in levels if itf.GetBool(key)]
if not onFlags:
oechem.OEThrow.Fatal("Need specify exactly one error level: " +
"|".join(levels.keys()))
elif len(onFlags) > 1:
oechem.OEThrow.Fatal("This flags are mutually exclusive: " +
"|".join(onFlags))
level, name = levels[onFlags[0]]
s = ServerProxy("http://" + itf.GetString("-host"))
if s.OEThrowSetLevel(level):
print("oechem.OEThrow.SetLevel(" + name + ") successful")
else:
print("oechem.OEThrow.SetLevel(" + name + ") failed")
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 21: Prepare OEB file for faster load performance.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
# Cache as much as possible on the molecule to improve the performance
# of starting a server from scratch. Also cull to desired number of
# conformers if requested.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
InterfaceData = """\
!BRIEF [-maxConfs 10] [-storeFloat] [-in] <database.oeb> [-out] <database.oeb>
!PARAMETER -in
!TYPE string
!REQUIRED true
!BRIEF Input database to prep
!KEYLESS 1
!END
!PARAMETER -out
!TYPE string
!REQUIRED true
!BRIEF Output prepared database
!KEYLESS 2
!END
!PARAMETER -maxConfs
!ALIAS -mc
!TYPE int
!DEFAULT 10
!REQUIRED false
!BRIEF Maximum conformers per molecule
!END
!PARAMETER -storeFloat
!ALIAS -sf
!TYPE bool
!DEFAULT false
!REQUIRED false
!BRIEF Store as full float precision in output file else store as half float (default)
!END
"""
def TrimConformers(mol, maxConfs):
for i, conf in enumerate(mol.GetConfs()):
if i >= maxConfs:
mol.DeleteConf(conf)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
# input - preserve rotor-offset-compression
ifs = oechem.oemolistream()
oechem.OEPreserveRotCompress(ifs)
if not ifs.open(itf.GetString("-in")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-in"))
# output - use PRE-compress for smaller files (no need to .gz the file)
ofs = oechem.oemolostream()
oechem.OEPRECompress(ofs)
if not ofs.open(itf.GetString("-out")):
oechem.OEThrow.Fatal("Unable to open '%s' for writing" % itf.GetString("-out"))
if itf.GetString("-out").endswith('.gz'):
oechem.OEThrow.Fatal("Output file must not gzipped")
maxConfs = itf.GetInt("-maxConfs")
if maxConfs < 1:
oechem.OEThrow.Fatal("Illegal number of conformer requested %u", maxConfs)
dots = oechem.OEDots(10000, 200, "molecules")
for mol in ifs.GetOEMols():
if maxConfs is not None:
TrimConformers(mol, maxConfs)
oefastrocs.OEPrepareFastROCSMol(mol)
if not itf.GetBool("-storeFloat"):
halfMol = oechem.OEMol(mol, oechem.OEMCMolType_HalfFloatCartesian)
oechem.OEWriteMolecule(ofs, halfMol)
else:
oechem.OEWriteMolecule(ofs, mol)
dots.Update()
dots.Total()
ofs.close()
print("Indexing %s" % itf.GetString("-out"))
if not oechem.OECreateMolDatabaseIdx(itf.GetString("-out")):
oechem.OEThrow.Fatal("Failed to index %s" % itf.GetString("-out"))
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 22: Tie multiple servers to appear as a single server.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
import os
try:
from xmlrpclib import ServerProxy, Binary
from SimpleXMLRPCServer import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
except ImportError: # python 3
from xmlrpc.client import ServerProxy, Binary
from xmlrpc.server import SimpleXMLRPCServer, SimpleXMLRPCRequestHandler
from threading import Thread
from threading import Lock
from ShapeDatabaseServer import SetupStream
from openeye import oechem
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
class ShapeServer:
""" Encapsulates a single ShapeDatabase running on a remote
server."""
def __init__(self, servername, querydata, nhits, iformat, oformat, kwargs):
""" Create a ShapeServer specified by servername and submit
the querydata query for nhits. """
self.server = ServerProxy("http://" + servername)
self.queryidx = self.server.SubmitQuery(querydata, nhits, iformat, oformat, kwargs)
def QueryStatus(self, blocking):
""" Return the status of this server. """
current, total = self.server.QueryStatus(self.queryidx, blocking)
# only return once the tracer on the server has been initialized
while total == 0:
blocking = True
current, total = self.server.QueryStatus(self.queryidx, blocking)
return current, total
def QueryHistogram(self):
""" Return the histogram from this server. """
return self.server.QueryHistogram(self.queryidx)
def QueryResults(self):
""" Return the results of this server. """
return self.server.QueryResults(self.queryidx)
class ShapeServerPool:
""" Abstract a collection of ShapeServer to appear as a single
server."""
def __init__(self, servernames, querymolstr, nhits, iformat, oformat, kwargs):
""" Create a collection of ShapeServers as specified by
servernames. Launching querymolstr on each for nhits."""
self.nhits = nhits
self.oformat = oformat
thrdpool = LaunchFunctionThreadPool(ShapeServer)
for sname in servernames:
thrdpool.AddThread(sname, querymolstr, nhits, iformat, oformat, kwargs)
self.shapeservers = []
for server in thrdpool.GetResults():
self.shapeservers.append(server)
def QueryStatus(self, blocking):
""" Return the status of these servers. """
thrdpool = LaunchFunctionThreadPool(ShapeServer.QueryStatus)
for server in self.shapeservers:
thrdpool.AddThread(server, blocking)
current = 0
total = 0
for scur, stot in thrdpool.GetResults():
sys.stderr.write("%i/%i" % (scur, stot))
current += scur
total += stot
return current, total
def QueryHistogram(self):
""" Return the total histogram across all servers. """
thrdpool = LaunchFunctionThreadPool(ShapeServer.QueryHistogram)
for server in self.shapeservers:
thrdpool.AddThread(server)
totalHist = None
for hist in thrdpool.GetResults():
if totalHist is None:
totalHist = [0] * len(hist)
totalHist = [lhs + rhs for lhs, rhs in zip(totalHist, hist)]
return totalHist
def QueryResults(self):
""" Return the best nhits results of these servers. """
timer = oechem.OEWallTimer()
thrdpool = LaunchFunctionThreadPool(ShapeServer.QueryResults)
for server in self.shapeservers:
thrdpool.AddThread(server)
data = []
for oebdata in thrdpool.GetResults():
data.append(oebdata.data)
sys.stderr.write("%f seconds to get results back" % timer.Elapsed())
data = b"".join(data)
if not data:
sys.stderr.write("Possible query error, no data returned \
by any of the downstream servers")
return ""
timer.Start()
# read in from OEB strings
ifs = oechem.oemolistream()
ifs = SetupStream(ifs, self.oformat)
if not ifs.openstring(data):
sys.stderr.write("Unable to open OEB string from downstream server")
return ""
mols = [oechem.OEGraphMol(mol) for mol in ifs.GetOEGraphMols()]
def GetScoreToCmp(mol):
if oechem.OEHasSDData(mol, "ShapeTanimoto"):
# sort by shape tanimoto
if oechem.OEHasSDData(mol, "TanimotoCombo"):
return float(oechem.OEGetSDData(mol, "TanimotoCombo"))
return float(oechem.OEGetSDData(mol, "ShapeTanimoto"))
else:
# sort by shape tversky
if oechem.OEHasSDData(mol, "TverskyCombo"):
return float(oechem.OEGetSDData(mol, "TverskyCombo"))
return float(oechem.OEGetSDData(mol, "ShapeTversky"))
mols.sort(key=GetScoreToCmp)
mols.reverse()
# write back out to an OEB string
ofs = oechem.oemolostream()
ofs = SetupStream(ofs, self.oformat)
ofs.openstring()
nhits = self.nhits
if not nhits:
nhits = len(mols)
for mol in mols[:nhits]:
oechem.OEWriteMolecule(ofs, mol)
sys.stderr.write("%f seconds to collate hitlist" % timer.Elapsed())
return Binary(ofs.GetString())
class LaunchFunctionThread(Thread):
""" A thread to launch a function and be able to retrieve its
return value."""
def __init__(self, func, *args):
Thread.__init__(self)
self.func = func
self.args = args
def run(self):
try:
self.result = self.func(*self.args)
except Exception as e:
self.exception = e
def GetResult(self):
if hasattr(self, "exception"):
raise self.exception
return self.result
class LaunchFunctionThreadPool:
""" Given a function, launch it in several threads with a separate
argument list for each."""
def __init__(self, func):
""" Start a new thread pool to execute the function func. """
self.func = func
self.threads = []
def AddThread(self, *args):
""" Create and start another thread to run func on args. """
thrd = LaunchFunctionThread(self.func, *args)
thrd.start()
self.threads.append(thrd)
def GetResults(self):
""" Returns an iterable of the results of each thread in the
order they were added with AddThread."""
for thrd in self.threads:
thrd.join()
yield thrd.GetResult()
def ShapeServerIsLoaded(servername, blocking):
""" Helper function to determine whether a server is in the 'loaded' state. """
server = ServerProxy("http://" + servername)
return server.IsLoaded(blocking)
class ShapeServerProxy:
""" Proxy queries across multiple remote shape servers."""
def __init__(self, servernames):
""" Create a proxy """
self.servernames = servernames
self.queryidx = 0
self.activequeries = {}
self.lock = Lock()
def IsLoaded(self, blocking=False):
""" Return whether the servers have finished loading. """
thrdpool = LaunchFunctionThreadPool(ShapeServerIsLoaded)
for server in self.servernames:
thrdpool.AddThread(server, blocking)
areloaded = True
for result in thrdpool.GetResults():
areloaded = areloaded and result
return areloaded
def SubmitQuery(self, querymolstr, nhits, iformat=".oeb", oformat=".oeb", kwargs=None):
""" Submit a query to these shape servers. """
if not kwargs:
kwargs = {}
shapeservers = ShapeServerPool(self.servernames, querymolstr,
nhits, iformat, oformat, kwargs)
self.lock.acquire()
try:
idx = self.queryidx
self.queryidx += 1
self.activequeries[idx] = shapeservers
finally:
self.lock.release()
return idx
def QueryStatus(self, queryidx, blocking=False):
""" Return the status of the query specified by queryidx. """
self.lock.acquire()
try:
shapeservers = self.activequeries[queryidx]
finally:
self.lock.release()
return shapeservers.QueryStatus(blocking)
def QueryHistogram(self, queryidx):
""" Return the current histogram of scores specified by
queryidx."""
self.lock.acquire()
try:
shapeservers = self.activequeries[queryidx]
finally:
self.lock.release()
return shapeservers.QueryHistogram()
def QueryResults(self, queryidx):
""" Return the results of the query specified by queryidx. """
self.lock.acquire()
try:
shapeservers = self.activequeries.pop(queryidx)
finally:
self.lock.release()
return shapeservers.QueryResults()
# Restrict to a particular path.
class RequestHandler(SimpleXMLRPCRequestHandler):
rpc_paths = ('/RPC2',)
def main(argv=[__name__]):
if len(argv) < 2:
oechem.OEThrow.Usage("%s <server 1> <server 2> ... <server n> [portnumber=8080]" % argv[0])
# default port number is 8080
portnumber = 8080
try:
portnumber = int(argv[-1])
servernames = argv[1:-1]
except ValueError:
servernames = argv[1:]
# Create server, an empty string is used to allow connections with
# any hostname
server = SimpleXMLRPCServer(("", portnumber),
requestHandler=RequestHandler)
server.register_introspection_functions()
server.register_instance(ShapeServerProxy(servernames))
try:
# Run the server's main loop
server.serve_forever()
finally:
server.server_close()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 23: Calculate distance between all molecules in database with themselves.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
# Write out a csv file of the similarity matrix of a multi-conformer
# database. Note, all conformers will be compared to each other,
# however, only the best match will be reported between two molecules.
import sys
import os
import csv
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "openeye", "python")
sys.path.insert(0, os.path.realpath(oepy))
InterfaceData = """\
!BRIEF [-shapeOnly] [-dbase] <database> [-matrix] <clusters.csv>
!PARAMETER -dbase
!TYPE string
!REQUIRED true
!BRIEF Input database to select from
!KEYLESS 1
!END
!PARAMETER -matrix
!TYPE string
!REQUIRED true
!BRIEF csv file to write similarity matrix to
!KEYLESS 2
!END
!PARAMETER -shapeOnly
!ALIAS -s
!TYPE bool
!DEFAULT false
!BRIEF Run FastROCS in shape only mode.
!END
"""
def GetScoreGetter(shapeOnly=False):
if shapeOnly:
return oefastrocs.OEShapeDatabaseScore.GetShapeTanimoto
return
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
ifs = oechem.oemolistream()
dbname = itf.GetString("-dbase")
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez", dbname)
if not ifs.open(dbname):
oechem.OEThrow.Fatal("Unable to open %s for reading" % dbname)
colname = "TanimotoCombo"
getter = oefastrocs.OEShapeDatabaseScore.GetTanimotoCombo
dbtype = oefastrocs.OEShapeDatabaseType_Default
if itf.GetBool("-shapeOnly"):
colname = "ShapeTanimoto"
getter = oefastrocs.OEShapeDatabaseScore.GetShapeTanimoto
dbtype = oefastrocs.OEShapeDatabaseType_Shape
csvwriter = csv.writer(open(itf.GetString("-matrix"), 'w'))
csvwriter.writerow(["Title1", "Title2", colname])
shapedb = oefastrocs.OEShapeDatabase(dbtype)
options = oefastrocs.OEShapeDatabaseOptions()
options.SetScoreType(dbtype)
lmat = [[]]
titles = []
for mol in ifs.GetOEMols():
if titles:
bestscores = [0.0] * len(titles)
for conf in mol.GetConfs():
for score in shapedb.GetScores(conf, options):
midx = score.GetMolIdx()
bestscores[midx] = max(bestscores[midx], getter(score))
lmat.append(bestscores)
shapedb.AddMol(mol)
title = mol.GetTitle()
if not title:
title = str(len(titles) + 1)
titles.append(title)
# write csv file
csvwriter = csv.writer(open(itf.GetString("-matrix"), 'w'))
csvwriter.writerow(titles)
nrows = len(titles)
for i in range(nrows):
row = [i+1]
for j in range(nrows):
val = 2.0
if itf.GetBool("-shapeOnly"):
val = 1.0
if j > i:
val -= lmat[j][i]
elif j < i:
val -= lmat[i][j]
elif j == i:
val = 0.0
row.append("%.3f" % val)
csvwriter.writerow(row)
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 24: Database searching with queries using the user inertial starts orientation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem
from openeye import oefastrocs
oepy = os.path.join(os.path.dirname(__file__), "..", "python")
sys.path.insert(0, os.path.realpath(oepy))
def main(argv=[__name__]):
if len(argv) < 4:
oechem.OEThrow.Usage("%s <database> <queries> <hits.oeb>" % argv[0])
return 0
# check system
if not oefastrocs.OEFastROCSIsGPUReady():
oechem.OEThrow.Info("No supported GPU available!")
return 0
# read in database
dbname = argv[1]
if oechem.OEIsGZip(dbname):
oechem.OEThrow.Fatal("%s is an unsupported database file format as it is gzipped.\n"
"Preferred formats are .oeb, .sdf or .oez", dbname)
print("Opening database file %s ..." % dbname)
dbase = oefastrocs.OEShapeDatabase()
moldb = oechem.OEMolDatabase()
if not moldb.Open(dbname):
oechem.OEThrow.Fatal("Unable to open '%s'" % dbname)
dots = oechem.OEThreadedDots(10000, 200, "conformers")
if not dbase.Open(moldb, dots):
oechem.OEThrow.Fatal("Unable to initialize OEShapeDatabase on '%s'" % dbname)
# customize search options
opts = oefastrocs.OEShapeDatabaseOptions()
opts.SetInitialOrientation(oefastrocs.OEFastROCSOrientation_UserInertialStarts)
opts.SetLimit(5)
qfname = argv[2]
# read in query
qfs = oechem.oemolistream()
if not qfs.open(qfname):
oechem.OEThrow.Fatal("Unable to open '%s'" % qfname)
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(qfs, query):
oechem.OEThrow.Fatal("Unable to read query from '%s'" % qfname)
# write out everthing to a similary named file
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open '%s'" % argv[3])
oechem.OEWriteMolecule(ofs, query)
startsCoords = oechem.OEFloatVector()
atomIdx = 1
xyz = query.GetCoords()[atomIdx]
for x in xyz:
startsCoords.append(x)
if not len(startsCoords) % 3 == 0:
oechem.OEThrow.Fatal("Something went wrong whilst reading in user-starts coordinates")
opts.SetUserStarts(oechem.OEFloatVector(startsCoords), int(len(startsCoords)/3))
opts.SetMaxOverlays(opts.GetNumInertialStarts() * opts.GetNumUserStarts())
if opts.GetInitialOrientation() == oefastrocs.OEFastROCSOrientation_UserInertialStarts:
numStarts = opts.GetNumUserStarts()
print("This example will use %u starts" % numStarts)
print("Searching for %s" % qfname)
for score in dbase.GetSortedScores(query, opts):
print("Score for mol %u(conf %u) %f shape %f color" % (
score.GetMolIdx(), score.GetConfIdx(),
score.GetShapeTanimoto(), score.GetColorTanimoto()))
dbmol = oechem.OEMol()
molidx = score.GetMolIdx()
if not moldb.GetMolecule(dbmol, molidx):
print("Unable to retrieve molecule '%u' from the database" % molidx)
continue
mol = oechem.OEGraphMol(dbmol.GetConf(oechem.OEHasConfIdx(score.GetConfIdx())))
oechem.OESetSDData(mol, "ShapeTanimoto", "%.4f" % score.GetShapeTanimoto())
oechem.OESetSDData(mol, "ColorTanimoto", "%.4f" % score.GetColorTanimoto())
oechem.OESetSDData(mol, "TanimotoCombo", "%.4f" % score.GetTanimotoCombo())
score.Transform(mol)
oechem.OEWriteMolecule(ofs, mol)
print("Wrote results to %s" % argv[3])
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv))
Grapheme Toolkit
The Grapheme examples illustrate visualization of complex molecular interactions and properties in a clear and coherent 2D format that is the most natural to chemists. See a full list of exaxmples in the Grapheme chapter.
Listing 1: Full listing of ActiveSiteHighlight.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE OEGRAPHEME DOCUMENTATION
###############################################################
class Pred6MemAromAtom(oechem.OEUnaryAtomPred):
def __call__(self, atom):
return atom.IsAromatic() and oechem.OEAtomIsInAromaticRingSize(atom, 6)
class Pred6MemAromBond(oechem.OEUnaryBondPred):
def __call__(self, bond):
return bond.IsAromatic() and oechem.OEBondIsInAromaticRingSize(bond, 6)
def OEAddHighlighting_Predicate(adisp):
highlight = oedepict.OEHighlightByBallAndStick(oechem.OEBlueTint)
oegrapheme.OEAddLigandHighlighting(adisp, highlight, Pred6MemAromAtom())
oegrapheme.OEAddLigandHighlighting(adisp, highlight, Pred6MemAromBond())
def OEAddHighlighting_AtomAndBondPredicate(adisp):
highlight = oedepict.OEHighlightByColor(oechem.OEDarkGreen)
oegrapheme.OEAddLigandHighlighting(adisp, highlight, Pred6MemAromAtom(), Pred6MemAromBond())
def OEAddHighlighting_OEMatch(adisp):
ligand = adisp.GetDisplayedLigand()
subs = oechem.OESubSearch("a1aaaaa1")
colors = oechem.OEGetVividColors()
unique = True
for match, color in zip(subs.Match(ligand, unique), colors):
highlight = oedepict.OEHighlightByLasso(color)
highlight.SetConsiderAtomLabelBoundingBox(True)
oegrapheme.OEAddLigandHighlighting(adisp, highlight, match)
def OEAddHighlighting_OEAtomBondSet(adisp):
ligand = adisp.GetDisplayedLigand()
highlight = oedepict.OEHighlightByCogwheel(oechem.OEPinkTint)
highlight.SetInnerContour(False)
abset = oechem.OEAtomBondSet(ligand.GetAtoms(Pred6MemAromAtom()),
ligand.GetBonds(Pred6MemAromBond()))
oegrapheme.OEAddLigandHighlighting(adisp, highlight, abset)
def OEAddHighlighting_OEResidue(adisp):
for res, color in zip(adisp.GetDisplayedResidues(), oechem.OEGetLightColors()):
pen = oedepict.OEPen(color, color, oedepict.OEFill_On, 1.0)
oegrapheme.OEAddResidueHighlighting(adisp, pen, res)
def ImportMolecule(filename):
ifs = oechem.oemolistream()
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % filename)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % filename)
return mol
########################################################################
#
########################################################################
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <receptor> <ligand>" % sys.argv[0])
receptor = ImportMolecule(sys.argv[1])
ligand = ImportMolecule(sys.argv[2])
asite = oechem.OEInteractionHintContainer(receptor, ligand)
asite.SetTitle(ligand.GetTitle())
oechem.OEPerceiveInteractionHints(asite)
oegrapheme.OEPrepareActiveSiteDepiction(asite)
opts = oegrapheme.OE2DActiveSiteDisplayOptions(600, 400)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
OEAddHighlighting_Predicate(adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-Predicate.png", adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-Predicate.pdf", adisp)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
OEAddHighlighting_AtomAndBondPredicate(adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-AtomAndBondPredicate.png", adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-AtomAndBondPredicate.pdf", adisp)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
OEAddHighlighting_OEMatch(adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-OEMatch.png", adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-OEMatch.pdf", adisp)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
OEAddHighlighting_OEAtomBondSet(adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-OEAtomBondSet.png", adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-OEAtomBondSet.pdf", adisp)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
OEAddHighlighting_OEResidue(adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-OEResidue.png", adisp)
oegrapheme.OERenderActiveSite("OEAddHighlighting-ActiveSite-OEResidue.pdf", adisp)
Listing 2: Example of using a built-in atom annotation style
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc(N)cc(S(=O)(=O)O)c1")
oechem.OEAssignHybridization(mol)
oedepict.OEPrepareDepiction(mol)
opts = oedepict.OE2DMolDisplayOptions(350, 250, oedepict.OEScale_AutoScale)
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
disp = oedepict.OE2DMolDisplay(mol, opts)
sp2pen = oedepict.OEPen(oechem.OEWhite, oechem.OEBlueTint, oedepict.OEFill_Off, 1.5)
glyphSP2 = oegrapheme.OEAtomGlyphCircle(sp2pen, oegrapheme.OECircleStyle_Sun, 1.2)
oegrapheme.OEAddGlyph(disp, glyphSP2, oechem.OEIsAtomHybridization(oechem.OEHybridization_sp2))
sp3pen = oedepict.OEPen(oechem.OEWhite, oechem.OEPinkTint, oedepict.OEFill_Off, 1.5)
glyphSP3 = oegrapheme.OEAtomGlyphCircle(sp3pen, oegrapheme.OECircleStyle_Eyelash, 1.2)
oegrapheme.OEAddGlyph(disp, glyphSP3, oechem.OEIsAtomHybridization(oechem.OEHybridization_sp3))
oedepict.OERenderMolecule("AnnotateAtomPredicate.png", disp)
oedepict.OERenderMolecule("AnnotateAtomPredicate.pdf", disp)
Listing 3: Example of using a built-in bond annotation style
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc(NCC)cc(CS(=O)(=O)O)c1")
oedepict.OEPrepareDepiction(mol)
opts = oedepict.OE2DMolDisplayOptions(400, 250, oedepict.OEScale_AutoScale)
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
disp = oedepict.OE2DMolDisplay(mol, opts)
pen = oedepict.OEPen(oechem.OEDarkPurple, oechem.OEDarkPurple, oedepict.OEFill_Off, 2.0)
glyph = oegrapheme.OEBondGlyphArrow(pen, 0.5)
oegrapheme.OEAddGlyph(disp, glyph, oechem.OEIsRotor())
oedepict.OERenderMolecule("AnnotateBondPredicate.png", disp)
oedepict.OERenderMolecule("AnnotateBondPredicate.pdf", disp)
Listing 4: Example of user-defined annotation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
class ColorCharge(oegrapheme.OEAtomGlyphBase):
def __init__(self, cg):
oegrapheme.OEAtomGlyphBase.__init__(self)
self.colorg = cg
def RenderGlyph(self, disp, atom):
adisp = disp.GetAtomDisplay(atom)
if adisp is None or not adisp.IsVisible():
return False
charge = atom.GetPartialCharge()
if charge == 0.0:
return True
color = self.colorg.GetColorAt(charge)
pen = oedepict.OEPen()
pen.SetForeColor(oechem.OEColor(color))
color.SetA(100)
pen.SetBackColor(oechem.OEColor(color))
pen.SetFill(oedepict.OEFill_On)
radius = disp.GetScale() / 2.5
layer = disp.GetLayer(oedepict.OELayerPosition_Below)
oegrapheme.OEDrawCircle(layer, oegrapheme.OECircleStyle_Simpson,
adisp.GetCoords(), radius, pen)
return True
def CreateCopy(self):
return ColorCharge(self.colorg).__disown__()
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "Cc1cc(cc(c1[N+](=O)[O-])F)[N+]#C")
oechem.OEMMFFAtomTypes(mol)
oechem.OEMMFF94PartialCharges(mol)
oedepict.OEPrepareDepiction(mol)
opts = oedepict.OE2DMolDisplayOptions(350, 250, oedepict.OEScale_AutoScale)
opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
disp = oedepict.OE2DMolDisplay(mol, opts)
coloranion = oechem.OEColorStop(-1.0, oechem.OEColor(oechem.OEDarkRed))
colorcation = oechem.OEColorStop(+1.0, oechem.OEColor(oechem.OEDarkBlue))
colorg = oechem.OELinearColorGradient(coloranion, colorcation)
colorg.AddStop(oechem.OEColorStop(0.0, oechem.OEColor(oechem.OEWhite)))
colorcharge = ColorCharge(colorg)
oegrapheme.OEAddGlyph(disp, colorcharge, oechem.OEIsTrueAtom())
oedepict.OERenderMolecule("AnnotatePartialCharge.png", disp)
oedepict.OERenderMolecule("AnnotatePartialCharge.pdf", disp)
Listing 5: Full listing of bfactor2img.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Depicts the BFactor of a ligand and its environment
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
def main(argv=[__name__]):
itf = oechem.OEInterface()
oechem.OEConfigure(itf, InterfaceData)
oedepict.OEConfigureImageWidth(itf, 600.0)
oedepict.OEConfigureImageHeight(itf, 600.0)
oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
oechem.OEConfigureSplitMolComplexOptions(itf, oechem.OESplitMolComplexSetup_LigName)
if not oechem.OEParseCommandLine(itf, argv):
return 1
iname = itf.GetString("-complex")
oname = itf.GetString("-out")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredImageFile(ext):
oechem.OEThrow.Fatal("Unknown image type!")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
complexmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, complexmol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % iname)
if not oechem.OEHasResidues(complexmol):
oechem.OEPerceiveResidues(complexmol, oechem.OEPreserveResInfo_All)
# Separate ligand and protein
sopts = oechem.OESplitMolComplexOptions()
oechem.OESetupSplitMolComplexOptions(sopts, itf)
ligand = oechem.OEGraphMol()
protein = oechem.OEGraphMol()
water = oechem.OEGraphMol()
other = oechem.OEGraphMol()
oechem.OESplitMolComplex(ligand, protein, water, other, complexmol, sopts)
if ligand.NumAtoms() == 0:
oechem.OEThrow.Fatal("Cannot separate complex!")
# Calculate average BFactor of the whole complex
avgbfactor = GetAverageBFactor(complexmol)
# Calculate minimum and maximum BFactor of the ligand and its environment
minbfactor, maxbfactor = GetMinAndMaxBFactor(ligand, protein)
# Attach to each ligand atom the average BFactor of the nearby protein atoms
stag = "avg residue BFfactor"
itag = oechem.OEGetTag(stag)
SetAverageBFactorOfNearbyProteinAtoms(ligand, protein, itag)
oechem.OEThrow.Info("Average BFactor of the complex = %+.3f" % avgbfactor)
oechem.OEThrow.Info("Minimum BFactor of the ligand and its environment = %+.3f" % minbfactor)
oechem.OEThrow.Info("Maximum BFactor of the ligand and its environment = %+.3f" % maxbfactor)
# Create image
imagewidth, imageheight = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
image = oedepict.OEImage(imagewidth, imageheight)
mframe = oedepict.OEImageFrame(image, imagewidth,
imageheight * 0.90, oedepict.OE2DPoint(0.0, 0.0))
lframe = oedepict.OEImageFrame(image, imagewidth, imageheight * 0.10,
oedepict.OE2DPoint(0.0, imageheight * 0.90))
opts = oedepict.OE2DMolDisplayOptions(mframe.GetWidth(), mframe.GetHeight(),
oedepict.OEScale_AutoScale)
oedepict.OESetup2DMolDisplayOptions(opts, itf)
opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)
# Create BFactor color gradient
colorg = oechem.OELinearColorGradient()
colorg.AddStop(oechem.OEColorStop(0.0, oechem.OEDarkBlue))
colorg.AddStop(oechem.OEColorStop(10.0, oechem.OELightBlue))
colorg.AddStop(oechem.OEColorStop(25.0, oechem.OEYellowTint))
colorg.AddStop(oechem.OEColorStop(50.0, oechem.OERed))
colorg.AddStop(oechem.OEColorStop(100.0, oechem.OEDarkRose))
# Prepare ligand for depiction
oegrapheme.OEPrepareDepictionFrom3D(ligand)
arcfxn = BFactorArcFxn(colorg, itag)
for atom in ligand.GetAtoms():
oegrapheme.OESetSurfaceArcFxn(ligand, atom, arcfxn)
opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(ligand, opts))
# Render ligand and visualize BFactor
disp = oedepict.OE2DMolDisplay(ligand, opts)
colorbfactor = ColorLigandAtomByBFactor(colorg)
oegrapheme.OEAddGlyph(disp, colorbfactor, oechem.OEIsTrueAtom())
oegrapheme.OEDraw2DSurface(disp)
oedepict.OERenderMolecule(mframe, disp)
# Draw color gradient
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.SetColorStopPrecision(1)
opts.AddMarkedValue(avgbfactor)
opts.SetBoxRange(minbfactor, maxbfactor)
oegrapheme.OEDrawColorGradient(lframe, colorg, opts)
oedepict.OEWriteImage(oname, image)
return 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
def ConsiderResidueAtom(atom, res):
if atom.GetAtomicNum() == oechem.OEElemNo_H:
return False
if res.GetName() == "HOH":
return False
return True
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 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)
#############################################################################
#
#############################################################################
class BFactorArcFxn(oegrapheme.OESurfaceArcFxnBase):
def __init__(self, colorg, itag):
oegrapheme.OESurfaceArcFxnBase.__init__(self)
self.colorg = colorg
self.itag = itag
def __call__(self, image, arc):
adisp = arc.GetAtomDisplay()
if adisp is None or not adisp.IsVisible():
return False
atom = adisp.GetAtom()
if atom is None:
return False
avgresiduebfactor = atom.GetDoubleData(self.itag)
if avgresiduebfactor == 0.0:
return True
color = self.colorg.GetColorAt(avgresiduebfactor)
pen = oedepict.OEPen(color, color, oedepict.OEFill_Off, 5.0)
center = arc.GetCenter()
bAngle = arc.GetBgnAngle()
eAngle = arc.GetEndAngle()
radius = arc.GetRadius()
oegrapheme.OEDrawDefaultSurfaceArc(image, center, bAngle, eAngle, radius, pen)
return True
def CreateCopy(self):
return BFactorArcFxn(self.colorg, self.itag).__disown__()
#############################################################################
#
#############################################################################
class ColorLigandAtomByBFactor(oegrapheme.OEAtomGlyphBase):
def __init__(self, colorg):
oegrapheme.OEAtomGlyphBase.__init__(self)
self.colorg = colorg
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
def CreateCopy(self):
return ColorLigandAtomByBFactor(self.colorg).__disown__()
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-complex] <input> [-out] <output pdf>
!CATEGORY "input/output options :"
!PARAMETER -complex
!ALIAS -c
!TYPE string
!KEYLESS 1
!REQUIRED true
!VISIBILITY simple
!BRIEF Input filename of the protein complex
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 6: Full listing of complex2img.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Depicts the interactions of an active site
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
def main(argv=[__name__]):
itf = oechem.OEInterface()
oechem.OEConfigure(itf, InterfaceData)
oedepict.OEConfigureImageWidth(itf, 900.0)
oedepict.OEConfigureImageHeight(itf, 600.0)
oedepict.OEConfigure2DMolDisplayOptions(itf, oedepict.OE2DMolDisplaySetup_AromaticStyle)
oechem.OEConfigureSplitMolComplexOptions(itf, oechem.OESplitMolComplexSetup_LigName)
if not oechem.OEParseCommandLine(itf, argv):
return 1
iname = itf.GetString("-complex")
oname = itf.GetString("-out")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input file!")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredImageFile(ext):
oechem.OEThrow.Fatal("Unknown image type!")
ofs = oechem.oeofstream()
if not ofs.open(oname):
oechem.OEThrow.Fatal("Cannot open output file!")
complexmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, complexmol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % iname)
if not oechem.OEHasResidues(complexmol):
oechem.OEPerceiveResidues(complexmol, oechem.OEPreserveResInfo_All)
# Separate ligand and protein
sopts = oechem.OESplitMolComplexOptions()
oechem.OESetupSplitMolComplexOptions(sopts, itf)
ligand = oechem.OEGraphMol()
protein = oechem.OEGraphMol()
water = oechem.OEGraphMol()
other = oechem.OEGraphMol()
pfilter = sopts.GetProteinFilter()
wfilter = sopts.GetWaterFilter()
sopts.SetProteinFilter(oechem.OEOrRoleSet(pfilter, wfilter))
sopts.SetWaterFilter(oechem.OEMolComplexFilterFactory(
oechem.OEMolComplexFilterCategory_Nothing))
oechem.OESplitMolComplex(ligand, protein, water, other, complexmol, sopts)
if ligand.NumAtoms() == 0:
oechem.OEThrow.Fatal("Cannot separate complex!")
# Perceive interactions
asite = oechem.OEInteractionHintContainer(protein, ligand)
if not asite.IsValid():
oechem.OEThrow.Fatal("Cannot initialize active site!")
asite.SetTitle(ligand.GetTitle())
oechem.OEPerceiveInteractionHints(asite)
oegrapheme.OEPrepareActiveSiteDepiction(asite)
# Depict active site with interactions
width, height = oedepict.OEGetImageWidth(itf), oedepict.OEGetImageHeight(itf)
image = oedepict.OEImage(width, height)
cframe = oedepict.OEImageFrame(image, width * 0.80, height, oedepict.OE2DPoint(0.0, 0.0))
lframe = oedepict.OEImageFrame(image, width * 0.20, height,
oedepict.OE2DPoint(width * 0.80, 0.0))
opts = oegrapheme.OE2DActiveSiteDisplayOptions(cframe.GetWidth(), cframe.GetHeight())
oedepict.OESetup2DMolDisplayOptions(opts, itf)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
oegrapheme.OERenderActiveSite(cframe, adisp)
lopts = oegrapheme.OE2DActiveSiteLegendDisplayOptions(10, 1)
oegrapheme.OEDrawActiveSiteLegend(lframe, adisp, lopts)
oedepict.OEWriteImage(oname, image)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-complex] <input> [-out] <output image>
!CATEGORY "input/output options :"
!PARAMETER -complex
!ALIAS -c
!TYPE string
!KEYLESS 1
!REQUIRED true
!VISIBILITY simple
!BRIEF Input filename of the protein complex
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 7: Depicting partial charges using property map
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
def SetPartialCharge(mol, tagname):
oechem.OEMMFFAtomTypes(mol)
oechem.OEMMFF94PartialCharges(mol)
tag = oechem.OEGetTag(tagname)
for atom in mol.GetAtoms():
atom.SetData(tag, atom.GetPartialCharge())
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "Cc1cc(cc(c1[N+](=O)[O-])F)[N+]#C")
oedepict.OEPrepareDepiction(mol)
tagname = "PartialCharge"
SetPartialCharge(mol, tagname)
width, height = 450, 350
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(mol, opts))
disp = oedepict.OE2DMolDisplay(mol, opts)
propmap = oegrapheme.OE2DPropMap(opts.GetBackgroundColor())
propmap.SetNegativeColor(oechem.OEDarkRed)
propmap.SetPositiveColor(oechem.OEDarkBlue)
propmap.Render(disp, tagname)
oedepict.OERenderMolecule("Draw2DPropMapPartialCharge.png", disp)
oedepict.OERenderMolecule("Draw2DPropMapPartialCharge.pdf", disp)
Listing 8: Example of user-defined surface drawing
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
class AtomColorArcFxn(oegrapheme.OESurfaceArcFxnBase):
def __call__(self, image, arc):
adisp = arc.GetAtomDisplay()
if adisp is None or not adisp.IsVisible():
return False
color = adisp.GetLabelFont().GetColor()
pen = oedepict.OEPen(color, color, oedepict.OEFill_Off, 1.0)
center = arc.GetCenter()
radius = arc.GetRadius()
bgnAngle = arc.GetBgnAngle()
endAngle = arc.GetEndAngle()
oegrapheme.OEDrawEyelashSurfaceArc(image, center, bgnAngle, endAngle, radius, pen)
return True
def Draw2DSurface(image, mol):
oedepict.OEPrepareDepiction(mol)
opts = oedepict.OE2DMolDisplayOptions(image.GetWidth(), image.GetHeight(),
oedepict.OEScale_AutoScale)
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(mol, opts))
arcfxn = AtomColorArcFxn()
for atom in mol.GetAtoms():
oegrapheme.OESetSurfaceArcFxn(mol, atom, arcfxn)
disp = oedepict.OE2DMolDisplay(mol, opts)
oegrapheme.OEDraw2DSurface(disp)
oedepict.OERenderMolecule(image, disp)
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "OC(=O)c1cnc(c(Cl)c1)-c2ccccc2")
imagewidth, imageheight = 350.0, 250.0
image = oedepict.OEImage(imagewidth, imageheight)
Draw2DSurface(image, mol)
oedepict.OEWriteImage("Draw2DSurfaceUserDefined.png", image)
oedepict.OEWriteImage("Draw2DSurfaceUserDefined.pdf", image)
Listing 9: Example of drawing 2D surface with various radii
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
def DrawSurfaces(image, mol):
oechem.OEAssignCovalentRadii(mol)
minradius = oechem.OEGetCovalentRadius(oechem.OEElemNo_H)
radiusScales = oechem.OEDoubleVector(mol.GetMaxAtomIdx(), 0.0)
maxrscale = float("-inf")
for atom in mol.GetAtoms():
rscale = (atom.GetRadius() - minradius) + oegrapheme.OESurfaceArcScale_Minimum
radiusScales[atom.GetIdx()] = rscale
maxrscale = max(maxrscale, rscale)
opts = oedepict.OE2DMolDisplayOptions(image.GetWidth(), image.GetHeight(),
oedepict.OEScale_AutoScale)
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(mol, opts, maxrscale))
disp = oedepict.OE2DMolDisplay(mol, opts)
layer = disp.GetLayer(oedepict.OELayerPosition_Below)
penA = oedepict.OEPen(oechem.OELightGrey, oechem.OELightGrey, oedepict.OEFill_Off, 2.0,
oedepict.OEStipple_ShortDash)
arcfxnA = oegrapheme.OEDefaultArcFxn(penA)
for arc in oegrapheme.OEGet2DSurfaceArcs(disp, oegrapheme.OESurfaceArcScale_Minimum):
arcfxnA(layer, arc)
penB = oedepict.OEPen(oechem.OEGrey, oechem.OEGrey, oedepict.OEFill_Off, 2.0)
arcfxnB = oegrapheme.OEDefaultArcFxn(penB)
for arc in oegrapheme.OEGet2DSurfaceArcs(disp, radiusScales):
arcfxnB(layer, arc)
oedepict.OERenderMolecule(image, disp)
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc(sc1CCl)Br")
oedepict.OEPrepareDepiction(mol)
imagewidth, imageheight = 300.0, 240.0
image = oedepict.OEImage(imagewidth, imageheight)
DrawSurfaces(image, mol)
oedepict.OEWriteImage("Draw2DSurfaceVariousRadii.png", image)
oedepict.OEWriteImage("Draw2DSurfaceVariousRadii.pdf", image)
Listing 10: Full listing of DrawActiveSiteLegend.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE GRAPHEME DOCUMENTATION
###############################################################
def ImportMolecule(filename):
ifs = oechem.oemolistream()
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % filename)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % filename)
return mol
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <receptor> <ligand>" % sys.argv[0])
receptor = ImportMolecule(sys.argv[1])
ligand = ImportMolecule(sys.argv[2])
asite = oechem.OEInteractionHintContainer(receptor, ligand)
oechem.OEPerceiveInteractionHints(asite)
oegrapheme.OEPrepareActiveSiteDepiction(asite)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, oegrapheme.OE2DActiveSiteDisplayOptions(400, 400))
# initializing adisp OE2DActiveSiteDisplay object
rows, cols = 2, 4
opts = oegrapheme.OE2DActiveSiteLegendDisplayOptions(rows, cols)
image = oedepict.OEImage(600, 150)
oegrapheme.OEDrawActiveSiteLegend(image, adisp, opts)
oedepict.OEWriteImage("DrawActiveSiteLegend.png", image)
oedepict.OEWriteImage("DrawActiveSiteLegend.pdf", image)
Listing 11: Full listing of DrawColorForceFieldLegend.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oedepict
from openeye import oegrapheme
from openeye import oeshape
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE GRAPHEME DOCUMENTATION
###############################################################
cff = oeshape.OEColorForceField()
cff.Init(oeshape.OEColorFFType_ImplicitMillsDean)
cffdisp = oegrapheme.OEColorForceFieldDisplay(cff)
rows, cols = 2, 3
opts = oegrapheme.OEColorForceFieldLegendDisplayOptions(rows, cols)
image = oedepict.OEImage(450, 150)
oegrapheme.OEDrawColorForceFieldLegend(image, cffdisp, opts)
oedepict.OEWriteImage("DrawColorForceFieldLegend.png", image)
oedepict.OEWriteImage("DrawColorForceFieldLegend.pdf", image)
Listing 12: Full listing of DrawColorGradient.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
colorg = oechem.OELinearColorGradient(oechem.OEColorStop(0.0, oechem.OEYellow))
colorg.AddStop(oechem.OEColorStop(+1.0, oechem.OEOrange))
colorg.AddStop(oechem.OEColorStop(-1.0, oechem.OEGreen))
image = oedepict.OEImage(400, 100)
oegrapheme.OEDrawColorGradient(image, colorg)
oedepict.OEWriteImage("DrawColorGradient.png", image)
oedepict.OEWriteImage("DrawColorGradient.pdf", image)
Listing 13: Example of complex surface drawing
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
def ImportMolecule(filename):
ifs = oechem.oemolistream()
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % filename)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % filename)
oechem.OEAssignBondiVdWRadii(mol)
oechem.OESuppressHydrogens(mol)
return mol
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <receptor> <ligand>" % sys.argv[0])
receptor = ImportMolecule(sys.argv[1])
ligand = ImportMolecule(sys.argv[2])
oegrapheme.OEAddComplexSurfaceArcs(ligand, receptor)
oegrapheme.OEPrepareDepictionFrom3D(ligand)
width, height = 450, 350
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(ligand, opts))
disp = oedepict.OE2DMolDisplay(ligand, opts)
oegrapheme.OEDraw2DSurface(disp)
oedepict.OERenderMolecule("DrawComplexSurface.png", disp)
oedepict.OERenderMolecule("DrawComplexSurface.pdf", disp)
Listing 14:
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
def ImportMolecule(filename):
ifs = oechem.oemolistream()
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % filename)
mol = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, mol)
oechem.OEAssignBondiVdWRadii(mol)
oechem.OESuppressHydrogens(mol)
return mol
def DrawSurfaceArc(image, depth, arc, pen):
edgeAngle = 5.0
patternAngle = 5.0
minPatternWidthRatio = 0.05
maxPatternWidthRatio = 0.10 * depth
patternDirection = oegrapheme.OEPatternDirection_Outside
oegrapheme.OEDrawSunSurfaceArc(image, arc.GetCenter(), arc.GetBgnAngle(), arc.GetEndAngle(),
arc.GetRadius(), pen, edgeAngle,
patternDirection, patternAngle,
minPatternWidthRatio, maxPatternWidthRatio)
class SolventArcFxn(oegrapheme.OESurfaceArcFxnBase):
def __call__(self, image, arc):
pen = oedepict.OEPen(oechem.OELightGrey, oechem.OELightGrey)
pen.SetLineWidth(0.5)
oegrapheme.OEDrawDefaultSurfaceArc(image, arc.GetCenter(), arc.GetBgnAngle(),
arc.GetEndAngle(), arc.GetRadius(), pen)
return True
class BuriedArcFxn(oegrapheme.OESurfaceArcFxnBase):
def __call__(self, image, arc):
pen = oedepict.OEPen(oechem.OEGrey, oechem.OEGrey)
pen.SetLineWidth(2.0)
oegrapheme.OEDrawDefaultSurfaceArc(image, arc.GetCenter(), arc.GetBgnAngle(),
arc.GetEndAngle(), arc.GetRadius(), pen)
return True
class CavityArcFxn(oegrapheme.OEComplexSurfaceArcFxnBase):
def __call__(self, image, arc):
pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack)
pen.SetLineWidth(2.0)
DrawSurfaceArc(image, self.GetDepth(), arc, pen)
return True
class VoidArcFxn(oegrapheme.OEComplexSurfaceArcFxnBase):
def __call__(self, image, arc):
pen = oedepict.OEPen(oechem.OEDarkGrey, oechem.OEDarkGrey)
pen.SetLineWidth(2.0)
DrawSurfaceArc(image, self.GetDepth(), arc, pen)
return True
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <receptor> <ligand>" % sys.argv[0])
receptor = ImportMolecule(sys.argv[1])
ligand = ImportMolecule(sys.argv[2])
width, height = 450, 350
image = oedepict.OEImage(width, height)
sfxn = SolventArcFxn()
bfxn = BuriedArcFxn()
cfxn = CavityArcFxn()
vfxn = VoidArcFxn()
oegrapheme.OEAddComplexSurfaceArcs(ligand, receptor, sfxn, bfxn, cfxn, vfxn)
oegrapheme.OEPrepareDepictionFrom3D(ligand)
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(ligand, opts))
disp = oedepict.OE2DMolDisplay(ligand, opts)
oegrapheme.OEDraw2DSurface(disp)
oedepict.OERenderMolecule(image, disp)
oedepict.OERenderMolecule("DrawComplexSurfaceUserDefined.png", disp)
oedepict.OERenderMolecule("DrawComplexSurfaceUserDefined.pdf", disp)
Listing 15: Full listing of DrawIridium.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE GRAPHEME DOCUMENTATION
###############################################################
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <design unit>" % sys.argv[0])
filename = sys.argv[1]
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(filename, du):
oechem.OEThrow.Fatal("Cannot read design unit!")
image = oedepict.OEImage(250, 250)
oegrapheme.OEDrawIridiumData(image, du)
oedepict.OEDrawBorder(image, oedepict.OELightGreyPen)
oedepict.OEWriteImage("DrawIridiumData.svg", image)
oedepict.OEWriteImage("DrawIridiumData.pdf", image)
Listing 16: Example of drawing multiple 2D surfaces
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
def Draw2DSurface(disp, atompred, radius, color):
penA = oedepict.OEPen(color, color, oedepict.OEFill_Off, 2.0)
arcfxnA = oegrapheme.OEDefaultArcFxn(penA)
penB = oedepict.OEPen(oechem.OELightGrey, oechem.OELightGrey, oedepict.OEFill_Off, 2.0,
oedepict.OEStipple_ShortDash)
arcfxnB = oegrapheme.OEDefaultArcFxn(penB)
layer = disp.GetLayer(oedepict.OELayerPosition_Below)
for adisp in disp.GetAtomDisplays():
for arc in oegrapheme.OEGet2DSurfaceArcs(disp, adisp, radius):
if atompred(adisp.GetAtom()):
arcfxnA(layer, arc)
else:
arcfxnB(layer, arc)
def Draw2DSurfaces(image, mol):
oedepict.OEPrepareDepiction(mol)
opts = oedepict.OE2DMolDisplayOptions(image.GetWidth(), image.GetHeight(),
oedepict.OEScale_AutoScale)
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
opts.SetScale(oegrapheme.OEGetMoleculeSurfaceScale(mol, opts, 1.50))
disp = oedepict.OE2DMolDisplay(mol, opts)
Draw2DSurface(disp, oechem.OEHasAtomicNum(oechem.OEElemNo_C), 1.00, oechem.OEBlack)
Draw2DSurface(disp, oechem.OEHasAtomicNum(oechem.OEElemNo_N), 1.25, oechem.OEDarkBlue)
Draw2DSurface(disp, oechem.OEHasAtomicNum(oechem.OEElemNo_O), 1.50, oechem.OEDarkRed)
oedepict.OERenderMolecule(image, disp)
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc(N)ccc1O")
imagewidth, imageheight = 300.0, 260.0
image = oedepict.OEImage(imagewidth, imageheight)
Draw2DSurfaces(image, mol)
oedepict.OEWriteImage("DrawMultiple2DSurfaces.png", image)
oedepict.OEWriteImage("DrawMultiple2DSurfaces.pdf", image)
Listing 17: Full listing of DrawPeptide.py. :noindent:
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
ifs = oechem.oemolistream()
flavor = (oechem.OEIFlavor_Generic_Default | oechem.OEIFlavor_FASTA_EmbeddedSMILES)
ifs.SetFlavor(oechem.OEFormat_FASTA, flavor)
ifs.SetFormat(oechem.OEFormat_FASTA)
fasta = """>
FAVS[[R4]COCC(C(=O)O)Cc1ccccc1]"""
ifs.openstring(fasta)
mol = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, mol)
image = oedepict.OEImage(400, 250)
opts = oegrapheme.OEPeptideDisplayOptions()
opts.SetInteractive(True)
oegrapheme.OEDrawPeptide(image, mol, opts)
oedepict.OEWriteImage("DrawPeptide.svg", image)
oedepict.OEWriteImage("DrawPeptide.pdf", image)
Listing 18: Full listing of DrawResidues.py. :noindent:
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <pdb>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % sys.argv[1])
image = oedepict.OEImage(400, 250)
interactive = True
oegrapheme.OEDrawResidues(image, mol, interactive)
oedepict.OEWriteImage("DrawResidues.svg", image)
oedepict.OEWriteImage("DrawResidues.pdf", image)
Listing 19: Full listing of DrawROCSScores.py. :noindent:
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
image = oedepict.OEImage(200, 150)
scores = oechem.OEDoubleVector([0.75, 0.25, 0.50])
oegrapheme.OEDrawROCSScores(image, scores)
oedepict.OEWriteImage("DrawROCSScores.png", image)
oedepict.OEWriteImage("DrawROCSScores.pdf", image)
Listing 20: Full listing of OE2DPropMap_SetProperties.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE GRAPHEME DOCUMENTATION
###############################################################
def DepictPropMap(propmap, mol, tagname, basefilename):
width, height = 350, 250
opts = oedepict.OE2DMolDisplayOptions(width, height, oedepict.OEScale_AutoScale)
opts.SetTitleLocation(oedepict.OETitleLocation_Bottom)
opts.SetAtomColorStyle(oedepict.OEAtomColorStyle_WhiteMonochrome)
disp = oedepict.OE2DMolDisplay(mol, opts)
below = disp.GetLayer(oedepict.OELayerPosition_Below)
propmap.Render(below, disp, tagname)
oedepict.OERenderMolecule(basefilename + ".png", disp)
oedepict.OERenderMolecule(basefilename + ".pdf", disp)
def SetPartialCharge(mol, tagname):
oechem.OEMMFFAtomTypes(mol)
oechem.OEMMFF94PartialCharges(mol)
tag = oechem.OEGetTag(tagname)
for atom in mol.GetAtoms():
atom.SetData(tag, atom.GetPartialCharge())
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "Cc1cc(cc(c1[N+](=O)[O-])F)CC[N+]#C")
tagname = "PartialCharge"
SetPartialCharge(mol, tagname)
oedepict.OEPrepareDepiction(mol)
########################################################################
#
########################################################################
propmap = oegrapheme.OE2DPropMap()
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_Default")
propmap = oegrapheme.OE2DPropMap()
propmap.SetNegativeColor(oechem.OEDarkGreen)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetNegativeColor")
propmap = oegrapheme.OE2DPropMap()
propmap.SetMinValue(0.0)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetMinValue")
propmap = oegrapheme.OE2DPropMap()
propmap.SetPositiveColor(oechem.OEDarkGreen)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetPositiveColor")
propmap = oegrapheme.OE2DPropMap()
propmap.SetMaxValue(0.0)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetMaxValue")
propmap = oegrapheme.OE2DPropMap()
font = oedepict.OEFont()
font.SetStyle(oedepict.OEFontStyle_Bold)
font.SetColor(oechem.OEDarkBlue)
propmap.SetLegendFont(font)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetLegendFont")
propmap = oegrapheme.OE2DPropMap()
propmap.SetLegendFontScale(1.5)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetLegendFontScale")
propmap = oegrapheme.OE2DPropMap()
propmap.SetLegendLocation(oegrapheme.OELegendLocation_Left)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetLegendLocation")
propmap = oegrapheme.OE2DPropMap()
propmap.SetResolution(5)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetResolution")
propmap = oegrapheme.OE2DPropMap()
propmap.SetRadiusRatio(0.75)
DepictPropMap(propmap, mol, tagname, "OE2DPropMap_SetRadiusRatio")
Listing 21: Full listing of OEColorGradientDispOpts.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE GRAPHEME DOCUMENTATION
###############################################################
def DepictColorGradient(colorg, opts, basefilename):
width, height = 400, 100
image = oedepict.OEImage(width, height)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
oedepict.OEWriteImage(basefilename + ".png", image)
oedepict.OEWriteImage(basefilename + ".pdf", image)
########################################################################
#
########################################################################
width, height = 400, 100
image = oedepict.OEImage(width, height)
colorg = oechem.OELinearColorGradient(oechem.OEColorStop(0.0, oechem.OEYellow))
colorg.AddStop(oechem.OEColorStop(+1.0, oechem.OEOrange))
colorg.AddStop(oechem.OEColorStop(-1.0, oechem.OEGreen))
opts = oegrapheme.OEColorGradientDisplayOptions()
oegrapheme.OEDrawColorGradient(image, colorg)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_Default")
opts = oegrapheme.OEColorGradientDisplayOptions()
font = oedepict.OEFont()
font.SetColor(oechem.OEDarkGreen)
font.SetStyle(oedepict.OEFontStyle_Bold)
opts.SetColorStopLabelFont(font)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetColorStopLabelFont")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.SetColorStopLabelFontScale(0.5)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetColorStopLabelFontScale")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.SetColorStopPrecision(4)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetColorStopPrecision")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.SetColorStopVisibility(False)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetColorStopVisibility")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.SetBoxRange(-0.5, 0.5)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetBoxRange")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.SetBoxRange(-0.5, 0.5)
pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_On,
2.0, oedepict.OEStipple_ShortDash)
opts.SetBoxRangePen(pen)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetBoxRangePen")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.AddMarkedValue(0.20)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_AddMarkedValue")
opts = oegrapheme.OEColorGradientDisplayOptions()
markedvalues = oechem.OEDoubleVector([0.20, 0.70, 0.72])
opts.AddMarkedValues(markedvalues)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_AddMarkedValues")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.AddMarkedValue(0.0)
markedvalues = oechem.OEDoubleVector([0.5, 0.75])
opts.SetMarkedValues(markedvalues)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetMarkedValues")
opts = oegrapheme.OEColorGradientDisplayOptions()
markedvalues = oechem.OEDoubleVector([0.20, 0.70, 0.72])
opts.AddMarkedValues(markedvalues)
opts.SetMarkedValuePrecision(1)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetMarkedValuePrecision")
opts = oegrapheme.OEColorGradientDisplayOptions()
markedvalues = oechem.OEDoubleVector([0.20, 0.70, 0.72])
opts.AddMarkedValues(markedvalues)
pen = oedepict.OEPen(oechem.OEBlack, oechem.OEDarkGreen, oedepict.OEFill_On,
2.0, oedepict.OEStipple_ShortDash)
opts.SetMarkedValuePen(pen)
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_SetMarkedValuePen")
opts = oegrapheme.OEColorGradientDisplayOptions()
opts.AddLabel(oegrapheme.OEColorGradientLabel(-1.0, "dissimilar"))
opts.AddLabel(oegrapheme.OEColorGradientLabel(+1.0, "similar"))
oegrapheme.OEDrawColorGradient(image, colorg, opts)
DepictColorGradient(colorg, opts, "OEColorGradientDisplayOptions_AddLabel")
Listing 22: Full listing of OEPeptideDispOpts_SetOpts.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE OEDEPICT DOCUMENTATION
###############################################################
def DepictPeptide(opts, smiles, basefilename):
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, smiles)
oedepict.OEPrepareDepiction(mol)
image = oedepict.OEImage(400, 200)
oegrapheme.OEDrawPeptide(image, mol, opts)
oedepict.OEWriteImage(basefilename + ".svg", image)
oedepict.OEWriteImage(basefilename + ".pdf", image)
oedepict.OEWriteImage(basefilename + ".png", image)
smiles = "CCC(C)[C@H]1C(=O)N[C@@H](C(=O)N[C@H](C(=O)N[C@@H](C(=O)N[C@H](C(=O)NCCCC[C@@H]" \
"(C(=O)N[C@@H](C(=O)N1)CCCN)NC(=O)[C@H](C(C)CC)NC(=O)[C@@H](CCC(=O)O)NC(=O)[C@H]" \
"(CC(C)C)NC(=O)C2CSC(=N2)NC(C(C)CC)N)CC(=O)N)CC(=O)O)CC3=CN=C[NH]3)Cc4ccccc4 bacitracin"
opts = oegrapheme.OEPeptideDisplayOptions()
DepictPeptide(opts, smiles, "OEPeptideDisplayOptions_Default")
opts = oegrapheme.OEPeptideDisplayOptions()
opts.SetLabelStyle(oegrapheme.OEPeptideLabelStyle_SingleLetter)
DepictPeptide(opts, smiles, "OEPeptideDisplayOptions_SetLabelStyle")
opts = oegrapheme.OEPeptideDisplayOptions()
opts.SetInteractive(True)
DepictPeptide(opts, smiles, "OEPeptideDisplayOptions_SetInteractive")
opts = oegrapheme.OEPeptideDisplayOptions()
opts.SetInteractive(True)
opts.SetAminoAcidScale(0.75)
DepictPeptide(opts, smiles, "OEPeptideDisplayOptions_SetAminoAcidScale")
Listing 23: Full listing of RenderBFactorMap.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE GRAPHEME DOCUMENTATION
###############################################################
def ImportMolecule(filename):
ifs = oechem.oemolistream()
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % filename)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % filename)
return mol
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <receptor> <ligand>" % sys.argv[0])
protein = ImportMolecule(sys.argv[1])
ligand = ImportMolecule(sys.argv[2])
asite = oechem.OEInteractionHintContainer(protein, ligand)
oechem.OEPerceiveInteractionHints(asite)
oegrapheme.OEPrepareActiveSiteDepiction(asite)
image = oedepict.OEImage(800.0, 600.0)
opts = oegrapheme.OE2DActiveSiteDisplayOptions(image.GetWidth(), image.GetHeight())
opts.SetRenderInteractiveLegend(True)
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
oegrapheme.OERenderBFactorMap(image, adisp)
oedepict.OEWriteImage("RenderBFactorMap.svg", image)
oedepict.OEWriteImage("RenderBFactorMap.pdf", image)
# initialize OE2DActiveSiteDisplay
cgimage = oedepict.OEImage(300.0, 100.0)
oegrapheme.OEDrawBFactorMapLegend(cgimage, adisp)
oedepict.OEWriteImage("DrawBFactorMapLegend.png", cgimage)
oedepict.OEWriteImage("DrawBFactorMapLegend.pdf", cgimage)
Listing 24: Full listing of shapeoverlap2pdf.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Depicts shape and color overlap between a 3D reference structure and
# a sets of 3D fit molecules. The molecules have to be pre-aligned.
# The first molecule is expected be the reference.
#############################################################################
import sys
from openeye import oechem
from openeye import oedepict
from openeye import oegrapheme
from openeye import oeshape
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
if not oechem.OEParseCommandLine(itf, argv):
return 1
iname = itf.GetString("-in")
oname = itf.GetString("-out")
maxhits = itf.GetInt("-maxhits")
ext = oechem.OEGetFileExtension(oname)
if not oedepict.OEIsRegisteredMultiPageImageFile(ext):
oechem.OEThrow.Fatal("Unknown multipage image type!")
ifs = oechem.oemolistream()
if not ifs.open(iname):
oechem.OEThrow.Fatal("Cannot open input molecule file!")
refmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, refmol):
oechem.OEThrow.Fatal("Cannot read reference molecule!")
ropts = oedepict.OEReportOptions(3, 1)
ropts.SetHeaderHeight(40.0)
ropts.SetFooterHeight(20.0)
report = oedepict.OEReport(ropts)
cff = oeshape.OEColorForceField()
cff.Init(oeshape.OEColorFFType_ImplicitMillsDean)
cffdisplay = oegrapheme.OEColorForceFieldDisplay(cff)
qopts = GetShapeQueryDisplayOptions()
sopts = GetShapeOverlapDisplayOptions()
copts = GetColorOverlapDisplayOptions()
refdisp = oegrapheme.OEShapeQueryDisplay(refmol, cff, qopts)
dots = oechem.OEDots(100, 10, "shape overlaps")
for fitmol in ifs.GetOEGraphMols():
if maxhits > 0 and dots.GetCounts() >= maxhits:
break
dots.Update()
maincell = report.NewCell()
grid = oedepict.OEImageGrid(maincell, 1, 3)
grid.SetMargins(5.0)
grid.SetCellGap(5.0)
# TITLE + SCORE GRAPH + QUERY
cell = grid.GetCell(1, 1)
cellw, cellh = cell.GetWidth(), cell.GetHeight()
font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Bold, 10,
oedepict.OEAlignment_Left, oechem.OEBlack)
pos = oedepict.OE2DPoint(10.0, 10.0)
cell.DrawText(pos, fitmol.GetTitle(), font, cell.GetWidth())
rframe = oedepict.OEImageFrame(cell, cellw, cellh * 0.35,
oedepict.OE2DPoint(0.0, cellh * 0.10))
mframe = oedepict.OEImageFrame(cell, cellw, cellh * 0.50,
oedepict.OE2DPoint(0.0, cellh * 0.50))
RenderScoreRadial(rframe, fitmol)
oegrapheme.OERenderShapeQuery(mframe, refdisp)
font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Bold, 8,
oedepict.OEAlignment_Center, oechem.OEGrey)
pos = oedepict.OE2DPoint(20.0, 10.0)
mframe.DrawText(pos, "query", font)
oedepict.OEDrawCurvedBorder(mframe, oedepict.OELightGreyPen, 10.0)
odisp = oegrapheme.OEShapeOverlapDisplay(refdisp, fitmol, sopts, copts)
# SHAPE OVERLAP
cell = grid.GetCell(1, 2)
oegrapheme.OERenderShapeOverlap(cell, odisp)
RenderScore(cell, fitmol, "ROCS_ShapeTanimoto", "Shape Tanimoto")
# COLOR OVERLAP
cell = grid.GetCell(1, 3)
oegrapheme.OERenderColorOverlap(cell, odisp)
RenderScore(cell, fitmol, "ROCS_ColorTanimoto", "Color Tanimoto")
oedepict.OEDrawCurvedBorder(maincell, oedepict.OELightGreyPen, 10.0)
dots.Total()
cffopts = oegrapheme.OEColorForceFieldLegendDisplayOptions(1, 6)
for header in report.GetHeaders():
oegrapheme.OEDrawColorForceFieldLegend(header, cffdisplay, cffopts)
oedepict.OEDrawCurvedBorder(header, oedepict.OELightGreyPen, 10.0)
font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Default, 12,
oedepict.OEAlignment_Center, oechem.OEBlack)
for idx, footer in enumerate(report.GetFooters()):
oedepict.OEDrawTextToCenter(footer, "-" + str(idx + 1) + "-", font)
oedepict.OEWriteReport(oname, report)
return 0
def AddCommonDisplayOptions(opts):
opts.SetTitleLocation(oedepict.OETitleLocation_Hidden)
opts.SetAtomLabelFontScale(1.5)
pen = oedepict.OEPen(oechem.OEBlack, oechem.OEBlack, oedepict.OEFill_Off, 1.5)
opts.SetDefaultBondPen(pen)
def GetShapeQueryDisplayOptions():
qopts = oegrapheme.OEShapeQueryDisplayOptions()
AddCommonDisplayOptions(qopts)
arcpen = oedepict.OEPen(oedepict.OELightGreyPen)
qopts.SetSurfaceArcFxn(oegrapheme.OEDefaultArcFxn(arcpen))
qopts.SetDepictOrientation(oedepict.OEDepictOrientation_Square)
return qopts
def GetShapeOverlapDisplayOptions():
sopts = oegrapheme.OEShapeOverlapDisplayOptions()
AddCommonDisplayOptions(sopts)
arcpen = oedepict.OEPen(oechem.OEGrey, oechem.OEGrey, oedepict.OEFill_Off, 1.0, 0x1111)
sopts.SetQuerySurfaceArcFxn(oegrapheme.OEDefaultArcFxn(arcpen))
sopts.SetOverlapColor(oechem.OEColor(110, 110, 190))
return sopts
def GetColorOverlapDisplayOptions():
copts = oegrapheme.OEColorOverlapDisplayOptions()
AddCommonDisplayOptions(copts)
arcpen = oedepict.OEPen(oechem.OEGrey, oechem.OEGrey, oedepict.OEFill_Off, 1.0, 0x1111)
copts.SetQuerySurfaceArcFxn(oegrapheme.OEDefaultArcFxn(arcpen))
return copts
def GetScore(mol, sdtag):
if oechem.OEHasSDData(mol, sdtag):
return float(oechem.OEGetSDData(mol, sdtag))
return 0.0
def RenderScoreRadial(image, mol):
sscore = max(min(GetScore(mol, "ROCS_ShapeTanimoto"), 1.0), 0.00)
cscore = max(min(GetScore(mol, "ROCS_ColorTanimoto"), 1.0), 0.00)
if sscore > 0.0 or cscore > 0.0:
scores = oechem.OEDoubleVector([sscore, cscore])
oegrapheme.OEDrawROCSScores(image, scores)
def RenderScore(image, mol, sdtag, label):
score = GetScore(mol, sdtag)
if score == 0.0:
return
w, h = image.GetWidth(), image.GetHeight()
frame = oedepict.OEImageFrame(image, w, h * 0.10, oedepict.OE2DPoint(0.0, h * 0.90))
font = oedepict.OEFont(oedepict.OEFontFamily_Default, oedepict.OEFontStyle_Default, 9,
oedepict.OEAlignment_Center, oechem.OEBlack)
oedepict.OEDrawTextToCenter(frame, label + " = " + str(score), font)
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF [-in] <input> [-out] <output pdf>
!CATEGORY "input/output options:" 0
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input molecule filename
!DETAIL
The first molecule in the file is expected to be the reference
molecule
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output image filename
!END
!END
!CATEGORY "general options:" 1
!PARAMETER -maxhits
!ALIAS -mhits
!TYPE int
!REQUIRED false
!DEFAULT 0
!LEGAL_RANGE 0 500
!VISIBILITY simple
!BRIEF Maximum number of hits depicted
!DETAIL
The default of 0 means there is no limit.
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 25: Full listing of SVGMarkResidues.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegrapheme
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE GRAPHEME DOCUMENTATION
###############################################################
def ImportMolecule(filename):
ifs = oechem.oemolistream()
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % filename)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % filename)
return mol
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <receptor> <ligand>" % sys.argv[0])
protein = ImportMolecule(sys.argv[1])
ligand = ImportMolecule(sys.argv[2])
asite = oechem.OEInteractionHintContainer(protein, ligand)
oechem.OEPerceiveInteractionHints(asite)
oegrapheme.OEPrepareActiveSiteDepiction(asite)
opts = oegrapheme.OE2DActiveSiteDisplayOptions(800.0, 600.0)
opts.SetResidueSVGMarkupFunctor(oegrapheme.OEResidueSVGStandardMarkup())
adisp = oegrapheme.OE2DActiveSiteDisplay(asite, opts)
oegrapheme.OERenderActiveSite("SVGMarkResidues.svg", adisp)
Graphsim Toolkit
These examples illustrate use of the Graphsim Toolkit, provides a facility for encoding 2D molecular graph information into fingerprints. For a full list of examples, see the Graphsim chapter.
Listing 1:
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
import sys
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <queryfile> <targetfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
qmol = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, qmol)
qfp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(qfp, qmol, oegraphsim.OEFPType_Path)
if not ifs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[2])
fpdb = oegraphsim.OEFPDatabase(qfp.GetFPTypeBase())
for tmol in ifs.GetOEGraphMols():
fpdb.AddFP(tmol)
for score in fpdb.GetScores(qfp):
print("%.3f" % score.GetScore())
Listing 2:
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
import sys
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <queryfile> <targetfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
qmol = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, qmol)
qfp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(qfp, qmol, oegraphsim.OEFPType_Path)
if not ifs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[2])
fpdb = oegraphsim.OEFPDatabase(qfp.GetFPTypeBase())
for tmol in ifs.GetOEGraphMols():
if tmol.HasData("PATH_FP"):
tfp = tmol.GetData("PATH_FP")
fpdb.AddFP(tfp)
else:
oechem.OEThrow.Warning("Unable to access fingerprint for %s" % tmol.GetTitle())
fpdb.AddFP(tmol)
for score in fpdb.GetScores(qfp):
print("%.3f" % score.GetScore())
Listing 3: Full listing of FP2OEB.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegraphsim
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
ofs = oechem.oemolostream()
if not ofs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % sys.argv[2])
if ofs.GetFormat() != oechem.OEFormat_OEB:
oechem.OEThrow.Fatal("%s output file has to be an OEBinary file" % sys.argv[2])
fp = oegraphsim.OEFingerPrint()
for mol in ifs.GetOEGraphMols():
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_Path)
mol.SetData("PATH_FP", fp)
oechem.OEWriteMolecule(ofs, mol)
Listing 4: Full listing of FP2SDF.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegraphsim
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
ofs = oechem.oemolostream()
if not ofs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % sys.argv[2])
if ofs.GetFormat() != oechem.OEFormat_SDF:
oechem.OEThrow.Fatal("%s output file has to be an SDF file" % sys.argv[2])
fp = oegraphsim.OEFingerPrint()
for mol in ifs.GetOEGraphMols():
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_Circular)
fptypestr = fp.GetFPTypeBase().GetFPTypeString()
fphexdata = fp.ToHexString()
oechem.OESetSDData(mol, fptypestr, fphexdata)
oechem.OEWriteMolecule(ofs, mol)
Listing 5: Full listing of FPAtomTyping.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
def PrintTanimoto(molA, molB, atype, btype):
fpA = oegraphsim.OEFingerPrint()
fpB = oegraphsim.OEFingerPrint()
numbits = 2048
minb = 0
maxb = 5
oegraphsim.OEMakePathFP(fpA, molA, numbits, minb, maxb, atype, btype)
oegraphsim.OEMakePathFP(fpB, molB, numbits, minb, maxb, atype, btype)
print("Tanimoto(A,B) = %.3f" % oegraphsim.OETanimoto(fpA, fpB))
molA = oechem.OEGraphMol()
oechem.OESmilesToMol(molA, "Oc1c2c(cc(c1)CF)CCCC2")
molB = oechem.OEGraphMol()
oechem.OESmilesToMol(molB, "c1ccc2c(c1)c(cc(n2)CCl)N")
PrintTanimoto(molA, molB, oegraphsim.OEFPAtomType_DefaultAtom, oegraphsim.OEFPBondType_DefaultBond)
PrintTanimoto(molA, molB, oegraphsim.OEFPAtomType_DefaultAtom | oegraphsim.OEFPAtomType_EqAromatic,
oegraphsim.OEFPBondType_DefaultBond)
PrintTanimoto(molA, molB, oegraphsim.OEFPAtomType_Aromaticity, oegraphsim.OEFPBondType_DefaultBond)
PrintTanimoto(molA, molB, oegraphsim.OEFPAtomType_InRing, oegraphsim.OEFPBondType_InRing)
Listing 6: Full listing of FPBitString.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
def GetBitString(fp):
bitstring = ''
for b in range(0, fp.GetSize()):
if fp.IsBitOn(b):
bitstring += '1'
else:
bitstring += '0'
return bitstring
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccncc1")
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_MACCS166)
print(GetBitString(fp))
Listing 7: Full listing of FPCoverage.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CCNCC")
fptype = oegraphsim.OEGetFPType(oegraphsim.OEFPType_Path)
unique = True
for idx, abset in enumerate(oegraphsim.OEGetFPCoverage(mol, fptype, unique)):
print("%2d %s" % ((idx + 1), "".join([str(a) for a in abset.GetAtoms()])))
Listing 8: Full listing of FPData.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
tag = "FP_DATA"
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeLingoFP(fp, mol)
mol.SetData(tag, fp)
if mol.HasData(tag):
f = mol.GetData(tag)
if f.IsValid():
fptype = f.GetFPTypeBase().GetFPTypeString()
print("%s fingerprint with `%s` identifier" % (fptype, tag))
Listing 9: Full listing of FPOverlap.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
pmol = oechem.OEGraphMol()
oechem.OESmilesToMol(pmol, "c1cnc2c(c1)CC(CC2O)CF")
tmol = oechem.OEGraphMol()
oechem.OESmilesToMol(tmol, "c1cc2c(cc1)CC(CCl)CC2N")
fptype = oegraphsim.OEGetFPType("Tree,ver=2.0.0,size=4096,bonds=5-5,"
"atype=AtmNum|HvyDeg|EqHalo,btype=Order")
for idx, match in enumerate(oegraphsim.OEGetFPOverlap(pmol, tmol, fptype)):
ostring = "match %2d: " % (idx + 1)
for mpair in match.GetAtoms():
p = mpair.pattern
t = mpair.target
ostring += "%d%s-%d%s " % (p.GetIdx(), oechem.OEGetAtomicSymbol(p.GetAtomicNum()),
t.GetIdx(), oechem.OEGetAtomicSymbol(t.GetAtomicNum()))
print(ostring)
Listing 10: Full listing of FPPathLength.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
def PrintTanimoto(molA, molB, minb, maxb):
fpA = oegraphsim.OEFingerPrint()
fpB = oegraphsim.OEFingerPrint()
numbits = 2048
atype = oegraphsim.OEFPAtomType_DefaultPathAtom
btype = oegraphsim.OEFPBondType_DefaultPathBond
oegraphsim.OEMakePathFP(fpA, molA, numbits, minb, maxb, atype, btype)
oegraphsim.OEMakePathFP(fpB, molB, numbits, minb, maxb, atype, btype)
print("Tanimoto(A,B) = %.3f" % oegraphsim.OETanimoto(fpA, fpB))
molA = oechem.OEGraphMol()
oechem.OESmilesToMol(molA, "c1ccncc1")
molB = oechem.OEGraphMol()
oechem.OESmilesToMol(molB, "c1cc[nH]c1")
PrintTanimoto(molA, molB, 0, 3)
PrintTanimoto(molA, molB, 1, 3)
PrintTanimoto(molA, molB, 0, 4)
PrintTanimoto(molA, molB, 0, 5)
Listing 11: Full listing of FPPattern.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "NCC(=O)[O-]")
fptype = oegraphsim.OEGetFPType("Tree,ver=2.0.0,size=4096,bonds=0-4,"
"atype=AtmNum|Arom|FCharge|HvyDeg,btype=Order")
for idx, pattern in enumerate(oegraphsim.OEGetFPPatterns(mol, fptype)):
atomstr = " ".join([str(a) for a in pattern.GetAtoms()])
print("%2d %5d %50s %s" % ((idx + 1), pattern.GetBit(), pattern.GetSmarts(), atomstr))
Listing 12: Calculate Tanimoto similarity scores.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
molA = oechem.OEGraphMol()
oechem.OESmilesToMol(molA, "c1ccc2c(c1)c(c(oc2=O)OCCSC(=N)N)Cl")
fpA = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(fpA, molA, oegraphsim.OEFPType_MACCS166)
molB = oechem.OEGraphMol()
oechem.OESmilesToMol(molB, "COc1cc2ccc(cc2c(=O)o1)NC(=N)N")
fpB = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(fpB, molB, oegraphsim.OEFPType_MACCS166)
molC = oechem.OEGraphMol()
oechem.OESmilesToMol(molC, "COc1c(c2ccc(cc2c(=O)o1)NC(=N)N)Cl")
fpC = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(fpC, molC, oegraphsim.OEFPType_MACCS166)
print("Tanimoto(A,B) = %.3f" % oegraphsim.OETanimoto(fpA, fpB))
print("Tanimoto(A,C) = %.3f" % oegraphsim.OETanimoto(fpA, fpC))
print("Tanimoto(B,C) = %.3f" % oegraphsim.OETanimoto(fpB, fpC))
Listing 13: Full listing of MemSimSearch.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegraphsim
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <database>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Cannot open database molecule file!")
# load molecules
moldb = oechem.OEMolDatabase(ifs)
nrmols = moldb.GetMaxMolIdx()
# generate fingerprints
fpdb = oegraphsim.OEFPDatabase(oegraphsim.OEFPType_Path)
emptyfp = oegraphsim.OEFingerPrint()
emptyfp.SetFPTypeBase(fpdb.GetFPTypeBase())
mol = oechem.OEGraphMol()
for idx in range(0, nrmols):
if moldb.GetMolecule(mol, idx):
fpdb.AddFP(mol)
else:
fpdb.AddFP(emptyfp)
nrfps = fpdb.NumFingerPrints()
timer = oechem.OEWallTimer()
while True:
# read query SMILES from stdin
sys.stdout.write("Enter SMILES> ")
line = sys.stdin.readline()
line = line.rstrip()
if len(line) == 0:
sys.exit(0)
# parse query
query = oechem.OEGraphMol()
if not oechem.OESmilesToMol(query, line):
oechem.OEThrow.Warning("Invalid SMILES string")
continue
# calculate similarity scores
timer.Start()
scores = fpdb.GetSortedScores(query, 5)
oechem.OEThrow.Info("%5.2f seconds to search %i fingerprints" % (timer.Elapsed(), nrfps))
hit = oechem.OEGraphMol()
for si in scores:
if moldb.GetMolecule(hit, si.GetIdx()):
smi = oechem.OEMolToSmiles(hit)
oechem.OEThrow.Info("Tanimoto score %4.3f %s" % (si.GetScore(), smi))
Listing 14: Full listing of PathFPType.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fpA = oegraphsim.OEFingerPrint()
numbits = 1024
minbonds = 0
maxbonds = 5
oegraphsim.OEMakePathFP(fpA, mol, numbits, minbonds, maxbonds,
oegraphsim.OEFPAtomType_DefaultPathAtom,
oegraphsim.OEFPBondType_DefaultPathBond)
fpB = oegraphsim.OEFingerPrint()
numbits = 2048
oegraphsim.OEMakePathFP(fpB, mol, numbits, minbonds, maxbonds,
oegraphsim.OEFPAtomType_DefaultPathAtom,
oegraphsim.OEFPBondType_DefaultPathBond)
print("same fingerprint types = %r" % oegraphsim.OEIsSameFPType(fpA, fpB))
print(oegraphsim.OETanimoto(fpA, fpB))
Listing 15: Full listing of SDF2FP.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegraphsim
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <infile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
if ifs.GetFormat() != oechem.OEFormat_SDF:
oechem.OEThrow.Fatal("%s input file has to be an SDF file" % sys.argv[1])
molcounter = 0
fpcounter = 0
for mol in ifs.GetOEGraphMols():
molcounter += 1
for dp in oechem.OEGetSDDataPairs(mol):
if oegraphsim.OEIsValidFPTypeString(dp.GetTag()):
fpcounter += 1
fptypestr = dp.GetTag()
fphexdata = dp.GetValue()
fp = oegraphsim.OEFingerPrint()
fptype = oegraphsim.OEGetFPType(fptypestr)
fp.SetFPTypeBase(fptype)
fp.FromHexString(fphexdata)
print("Number of molecules = %d" % molcounter)
print("Number of fingerprints = %d" % fpcounter)
Listing 16: Full listing of SimCalcFromFile.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegraphsim
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <queryfile> <targetfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
qmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, qmol):
oechem.OEThrow.Fatal("Unable to read query molecule")
qfp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(qfp, qmol, oegraphsim.OEFPType_Path)
if not ifs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[2])
tfp = oegraphsim.OEFingerPrint()
for tmol in ifs.GetOEGraphMols():
oegraphsim.OEMakeFP(tfp, tmol, oegraphsim.OEFPType_Path)
print("%.3f" % oegraphsim.OETanimoto(qfp, tfp))
Listing 17: Full listing of SimCalcFromOEB.py.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegraphsim
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <queryfile> <targetfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
qmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, qmol):
oechem.OEThrow.Fatal("Unable to read query molecule")
qfp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(qfp, qmol, oegraphsim.OEFPType_Path)
if not ifs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[2])
tfp = oegraphsim.OEFingerPrint()
for tmol in ifs.GetOEGraphMols():
if tmol.HasData("PATH_FP"):
tfp = tmol.GetData("PATH_FP")
else:
oechem.OEThrow.Warning("Unable to access fingerprint for %s" % tmol.GetTitle())
oegraphsim.OEMakeFP(tfp, tmol, oegraphsim.OEFPType_Path)
print("%.3f" % oegraphsim.OETanimoto(qfp, tfp))
Listing 18: Generating fingerprint file for fast fingerprint search.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Generates binary fingerprint file for fast fingerprint search
#############################################################################
import sys
import os
from openeye import oechem
from openeye import oegraphsim
def main(argv=[__name__]):
itf = oechem.OEInterface()
oechem.OEConfigure(itf, InterfaceData)
oegraphsim.OEConfigureFingerPrint(itf, oegraphsim.OEGetFPType(oegraphsim.OEFPType_Tree))
if not oechem.OEParseCommandLine(itf, argv):
return 1
ifname = itf.GetString("-in")
ffname = itf.GetString("-fpdb")
if oechem.OEGetFileExtension(ffname) != "fpbin":
oechem.OEThrow.Fatal("Fingerprint database file should have '.fpbin' file extension!")
idxfname = oechem.OEGetMolDatabaseIdxFileName(ifname)
if not os.path.exists(idxfname):
if not oechem.OECreateMolDatabaseIdx(ifname):
oechem.OEThrow.Warning("Unable to create %s molecule index file" % idxfname)
oechem.OEThrow.Info("Using %s index molecule file" % idxfname)
moldb = oechem.OEMolDatabase()
if not moldb.Open(ifname):
oechem.OEThrow.Fatal("Cannot open molecule database file!")
nrmols = moldb.GetMaxMolIdx()
fptype = oegraphsim.OESetupFingerPrint(itf)
oechem.OEThrow.Info("Using fingerprint type %s" % fptype.GetFPTypeString())
opts = oegraphsim.OECreateFastFPDatabaseOptions(fptype)
opts.SetTracer(oechem.OEDots(100000, 1000, "fingerprints"))
oechem.OEThrow.Info("Generating fingerprints with %d threads" % opts.GetNumProcessors())
timer = oechem.OEWallTimer()
if not oegraphsim.OECreateFastFPDatabaseFile(ffname, ifname, opts):
oechem.OEThrow.Fatal("Cannot create fingerprint database file!")
oechem.OEThrow.Info("%5.2f secs to generate %d fingerprints" % (timer.Elapsed(), nrmols))
return 0
InterfaceData = """
!BRIEF [-in] <input> [-fpdbfname] <output>
!CATEGORY "input/output options"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input molecule filename
!END
!PARAMETER -fpdbfname
!ALIAS -fpdb
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output fingerprint database filename
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 19: Searching fast fingerprint database.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Searching fast fingerprint database
#############################################################################
import sys
from openeye import oechem
from openeye import oegraphsim
def main(argv=[__name__]):
itf = oechem.OEInterface()
oechem.OEConfigure(itf, InterfaceData)
defopts = oegraphsim.OEFPDatabaseOptions(10, oegraphsim.OESimMeasure_Tanimoto)
oegraphsim.OEConfigureFPDatabaseOptions(itf, defopts)
oegraphsim.OEConfigureFPDatabaseMemoryType(itf)
if not oechem.OEParseCommandLine(itf, argv):
return 0
qfname = itf.GetString("-query")
mfname = itf.GetString("-molfname")
ffname = itf.GetString("-fpdbfname")
ofname = itf.GetString("-out")
# initialize databases
timer = oechem.OEWallTimer()
timer.Start()
ifs = oechem.oemolistream()
if not ifs.open(qfname):
oechem.OEThrow.Fatal("Cannot open input file!")
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, query):
oechem.OEThrow.Fatal("Cannot read query molecule!")
moldb = oechem.OEMolDatabase()
if not moldb.Open(mfname):
oechem.OEThrow.Fatal("Cannot open molecule database!")
memtype = oegraphsim.OEGetFPDatabaseMemoryType(itf)
fpdb = oegraphsim.OEFastFPDatabase(ffname, memtype)
if not fpdb.IsValid():
oechem.OEThrow.Fatal("Cannot open fingerprint database!")
nrfps = fpdb.NumFingerPrints()
memtypestr = fpdb.GetMemoryTypeString()
ofs = oechem.oemolostream()
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Cannot open output file!")
if not oegraphsim.OEAreCompatibleDatabases(moldb, fpdb):
oechem.OEThrow.Fatal("Databases are not compatible!")
oechem.OEThrow.Info("%5.2f sec to initialize databases" % timer.Elapsed())
fptype = fpdb.GetFPTypeBase()
oechem.OEThrow.Info("Using fingerprint type %s" % fptype.GetFPTypeString())
opts = oegraphsim.OEFPDatabaseOptions()
oegraphsim.OESetupFPDatabaseOptions(opts, itf)
# search fingerprint database
timer.Start()
scores = fpdb.GetSortedScores(query, opts)
oechem.OEThrow.Info("%5.2f sec to search %d fingerprints %s"
% (timer.Elapsed(), nrfps, memtypestr))
timer.Start()
nrhits = 0
hit = oechem.OEGraphMol()
for si in scores:
if moldb.GetMolecule(hit, si.GetIdx()):
nrhits += 1
oechem.OESetSDData(hit, "Similarity score", "%.2f" % si.GetScore())
oechem.OEWriteMolecule(ofs, hit)
oechem.OEThrow.Info("%5.2f sec to write %d hits" % (timer.Elapsed(), nrhits))
return 0
InterfaceData = """
!BRIEF [-query] <molfile> [-molfname] <molfile> [-fpdbfname] <fpfile> [-out] <molfile>
!CATEGORY "input/output options"
!PARAMETER -query
!ALIAS -q
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input query filename
!END
!PARAMETER -molfname
!ALIAS -mol
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Input molecule filename
!END
!PARAMETER -fpdbfname
!ALIAS -fpdb
!TYPE string
!REQUIRED true
!KEYLESS 3
!VISIBILITY simple
!BRIEF Input fast fingerprint database filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 4
!VISIBILITY simple
!BRIEF Output molecule filename
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 20: Building and searching fingerprint database.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Searching fingerprint database
#############################################################################
import sys
from openeye import oechem
from openeye import oegraphsim
def main(argv=[__name__]):
itf = oechem.OEInterface()
oechem.OEConfigure(itf, InterfaceData)
defopts = oegraphsim.OEFPDatabaseOptions(10, oegraphsim.OESimMeasure_Tanimoto)
oegraphsim.OEConfigureFPDatabaseOptions(itf, defopts)
oegraphsim.OEConfigureFingerPrint(itf, oegraphsim.OEGetFPType(oegraphsim.OEFPType_Tree))
if not oechem.OEParseCommandLine(itf, argv):
return 0
qfname = itf.GetString("-query")
mfname = itf.GetString("-molfname")
ofname = itf.GetString("-out")
# initialize databases
timer = oechem.OEWallTimer()
timer.Start()
ifs = oechem.oemolistream()
if not ifs.open(qfname):
oechem.OEThrow.Fatal("Cannot open input file!")
query = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, query):
oechem.OEThrow.Fatal("Cannot read query molecule!")
moldb = oechem.OEMolDatabase()
if not moldb.Open(mfname):
oechem.OEThrow.Fatal("Cannot open molecule database!")
ofs = oechem.oemolostream()
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Cannot open output file!")
fptype = oegraphsim.OESetupFingerPrint(itf)
oechem.OEThrow.Info("Using fingerprint type %s" % fptype.GetFPTypeString())
fpdb = oegraphsim.OEFPDatabase(fptype)
emptyfp = oegraphsim.OEFingerPrint()
emptyfp.SetFPTypeBase(fptype)
nrmols = moldb.GetMaxMolIdx()
mol = oechem.OEGraphMol()
for idx in range(0, nrmols):
if moldb.GetMolecule(mol, idx):
fpdb.AddFP(mol)
else:
fpdb.AddFP(emptyfp)
nrfps = fpdb.NumFingerPrints()
oechem.OEThrow.Info("%5.2f sec to initialize databases" % timer.Elapsed())
opts = oegraphsim.OEFPDatabaseOptions()
oegraphsim.OESetupFPDatabaseOptions(opts, itf)
# search fingerprint database
timer.Start()
scores = fpdb.GetSortedScores(query, opts)
oechem.OEThrow.Info("%5.2f sec to search %d fingerprints" % (timer.Elapsed(), nrfps))
timer.Start()
hit = oechem.OEGraphMol()
for si in scores:
if moldb.GetMolecule(hit, si.GetIdx()):
oechem.OEWriteMolecule(ofs, hit)
oechem.OEThrow.Info("%5.2f sec to write %d hits" % (timer.Elapsed(), opts.GetLimit()))
return 0
InterfaceData = """
!BRIEF [-query] <molfile> [-molfname] <molfile> [-out] <molfile>
!CATEGORY "input/output options"
!PARAMETER -query
!ALIAS -q
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input query filename
!END
!PARAMETER -molfname
!ALIAS -mol
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Input molecule filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 3
!VISIBILITY simple
!BRIEF Output molecule filename
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 21: Calculate similarity scores.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
import sys
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <queryfile> <targetfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
qmol = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, qmol)
qfp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(qfp, qmol, oegraphsim.OEFPType_Path)
if not ifs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[2])
fpdb = oegraphsim.OEFPDatabase(qfp.GetFPTypeBase())
for tmol in ifs.GetOEGraphMols():
fpdb.AddFP(tmol)
print("Tanimoto scores:")
descending = True
fpdb.SetSimFunc(oegraphsim.OESimMeasure_Tanimoto, descending)
fpdb.SetCutoff(0.1)
for score in fpdb.GetScores(qfp, 0, 100):
print("%.3f" % score.GetScore())
fpdb.ClearCutoff()
print("Tversky scores:")
fpdb.SetSimFunc(oegraphsim.OETverskySim(0.9))
for score in fpdb.GetScores(qfp):
print("%.3f" % score.GetScore())
print("Dice scores:")
descending = True
fpdb.SetSimFunc(oegraphsim.OESimMeasure_Dice, not descending)
fpdb.SetCutoff(0.5)
for score in fpdb.GetScores(qfp, 100):
print("%.3f" % score.GetScore())
print("Cosine scores with option:")
opts = oegraphsim.OEFPDatabaseOptions()
opts.SetCutoff(0.3)
opts.SetSimFunc(oegraphsim.OESimMeasure_Cosine)
for score in fpdb.GetScores(qfp, opts):
print("%.3f" % score.GetScore())
print("Tanimoto sorted scores:")
fpdb.ClearCutoff() # default
descending = True
fpdb.SetSimFunc(oegraphsim.OESimMeasure_Tanimoto, descending) # default
for score in fpdb.GetSortedScores(qfp, 10):
print("%.3f" % score.GetScore())
print("Dice sorted scores:")
descending = True
fpdb.SetSimFunc(oegraphsim.OESimMeasure_Dice, descending)
fpdb.SetCutoff(0.5)
for score in fpdb.GetSortedScores(qfp, 0, 0, 100):
print("%.3f" % score.GetScore())
print("Manhattan sorted scores:")
descending = True
fpdb.SetSimFunc(oegraphsim.OESimMeasure_Manhattan, not descending)
fpdb.SetCutoff(0.3)
for score in fpdb.GetSortedScores(qfp, 5, 100):
print("%.3f" % score.GetScore())
print("Tversky sorted scores with options:")
opts = oegraphsim.OEFPDatabaseOptions()
opts.SetDescendingOrder(True)
opts.SetCutoff(0.3)
opts.SetSimFunc(oegraphsim.OESimMeasure_Tversky)
opts.SetTverskyCoeffs(0.9, 0.1)
opts.SetLimit(10)
for score in fpdb.GetSortedScores(qfp, opts):
print("%.3f" % score.GetScore())
Listing 22: Perform multithreaded similarity calculation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oegraphsim
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <molfname> <fpdbfname>" % sys.argv[0])
mfname = sys.argv[1]
ffname = sys.argv[2]
moldb = oechem.OEMolDatabase()
if not moldb.Open(mfname):
oechem.OEThrow.Fatal("Cannot open molecule database!")
memtype = oegraphsim.OEFastFPDatabaseMemoryType_InMemory
fpdb = oegraphsim.OEFastFPDatabase(ffname, memtype)
if not fpdb.IsValid():
oechem.OEThrow.Fatal("Cannot open fingerprint database!")
if not oegraphsim.OEAreCompatibleDatabases(moldb, fpdb):
oechem.OEThrow.Fatal("Databases are not compatible!")
query = oechem.OEGraphMol()
oechem.OESmilesToMol(query, "Cc1c(c2cc(ccc2n1C(=O)c3ccc(cc3)Cl)OC)CC(=O)O")
limit = 5
opts = oegraphsim.OEFPDatabaseOptions(limit, oegraphsim.OESimMeasure_Tanimoto)
nrbins = 5
result = oegraphsim.OESimSearchResult(nrbins)
status = fpdb.SortedSearch(result, query, opts)
print("Search status = {}".format(oegraphsim.OESimSearchStatusToName(status)))
print("Number of searched = {}".format(result.NumSearched()))
# print scores
for score in result.GetSortedScores():
print("{:.3f}".format(score.GetScore()))
# print histogram
hist = result.GetHistogram()
bounds = hist.GetBinBoundaries()
for idx, count in enumerate(hist.GetCounts()):
print("[{:.3f}-{:.3f}] = {}".format(bounds[idx], bounds[idx+1], count))
Listing 23: Print out string representation of a circular fingerprint.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oegraphsim
fptype = oegraphsim.OEGetFPType(oegraphsim.OEFPType_Circular)
print(fptype.GetFPTypeString())
Listing 24: Print out string representation of a path fingerprint.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oegraphsim
fptype = oegraphsim.OEGetFPType(oegraphsim.OEFPType_Path)
print(fptype.GetFPTypeString())
Listing 25: Print out string representation of a tree fingerprint.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oegraphsim
fptype = oegraphsim.OEGetFPType(oegraphsim.OEFPType_Tree)
print(fptype.GetFPTypeString())
Listing 26: simfunc.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
class SimpsonSimFunc(oegraphsim.OESimFuncBase):
def __call__(self, fpA, fpB):
onlyA, onlyB, bothAB, neitherAB = oechem.OEGetBitCounts(fpA, fpB)
if onlyA + onlyB == 0:
return 1.0
if bothAB == 0:
return 0.0
sim = float(bothAB)
sim /= min(float(onlyA + bothAB), float(onlyB + bothAB))
return sim
def GetSimTypeString(self):
return "Simpson"
def CreateCopy(self):
return SimpsonSimFunc().__disown__()
smiles = ["c1ccc2c(c1)c(c(oc2=O)OCCSC(=N)N)Cl",
"COc1cc2ccc(cc2c(=O)o1)NC(=N)N"]
fpdb = oegraphsim.OEFPDatabase(oegraphsim.OEFPType_Path)
fpdb.SetSimFunc(SimpsonSimFunc())
mol = oechem.OEGraphMol()
for smi in smiles:
mol.Clear()
oechem.OESmilesToMol(mol, smi)
fpdb.AddFP(mol)
query = oechem.OEGraphMol()
oechem.OESmilesToMol(query, "COc1c(c2ccc(cc2c(=O)o1)NC(=N)N)Cl")
for score in fpdb.GetScores(query):
print("%.3f" % score.GetScore())
Listing 27: makemaccsfp.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeMACCS166FP(fp, mol)
print(fp.GetFPTypeBase().GetFPTypeString())
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_MACCS166)
print(fp.GetFPTypeBase().GetFPTypeString())
Listing 28: makelingofp.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeLingoFP(fp, mol)
print(fp.GetFPTypeBase().GetFPTypeString())
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_Lingo)
print(fp.GetFPTypeBase().GetFPTypeString())
Listing 29: MakeCircularFP.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeCircularFP(fp, mol)
print(fp.GetFPTypeBase().GetFPTypeString())
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_Circular)
print(fp.GetFPTypeBase().GetFPTypeString())
numbits = 1024
minradius = 0
maxradius = 3
oegraphsim.OEMakeCircularFP(fp, mol, numbits, minradius, maxradius,
oegraphsim.OEFPAtomType_DefaultCircularAtom,
oegraphsim.OEFPBondType_DefaultCircularBond)
print(fp.GetFPTypeBase().GetFPTypeString())
Listing 30: Make a path fingerprint.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakePathFP(fp, mol)
print(fp.GetFPTypeBase().GetFPTypeString())
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_Path)
print(fp.GetFPTypeBase().GetFPTypeString())
numbits = 1024
minbonds = 0
maxbonds = 5
oegraphsim.OEMakePathFP(fp, mol, numbits, minbonds, maxbonds,
oegraphsim.OEFPAtomType_DefaultPathAtom,
oegraphsim.OEFPBondType_DefaultPathBond)
print(fp.GetFPTypeBase().GetFPTypeString())
Listing 31: Fingerprint types.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
fpA = oegraphsim.OEFingerPrint()
fpB = oegraphsim.OEFingerPrint()
if not fpA.IsValid():
print("uninitialized fingerprint")
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
oegraphsim.OEMakeFP(fpA, mol, oegraphsim.OEFPType_Path)
oegraphsim.OEMakeFP(fpB, mol, oegraphsim.OEFPType_Lingo)
if oegraphsim.OEIsFPType(fpA, oegraphsim.OEFPType_Lingo):
print("Lingo")
if oegraphsim.OEIsFPType(fpA, oegraphsim.OEFPType_Path):
print("Path")
if oegraphsim.OEIsSameFPType(fpA, fpB):
print("same fingerprint types")
else:
print("different fingerprint types")
Listing 32: Compare fingerprint objects.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fpA = oegraphsim.OEFingerPrint()
fpB = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(fpA, mol, oegraphsim.OEFPType_Path)
oegraphsim.OEMakeFP(fpB, mol, oegraphsim.OEFPType_Path)
if fpA == fpB:
print("same fingerprints")
else:
print("different fingerprints")
Listing 33: Return string representation of fingerprint type.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_Path)
print(fp.GetFPTypeBase().GetFPTypeString())
fp = oegraphsim.OEFingerPrint()
oegraphsim.OEMakeFP(fp, mol, oegraphsim.OEFPType_Path)
print(fp.GetFPTypeBase().GetFPVersionString())
Listing 34: Yule similarity measures.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oegraphsim
molA = oechem.OEGraphMol()
oechem.OESmilesToMol(molA, "c1ccc2c(c1)c(c(oc2=O)OCCSC(=N)N)Cl")
fpA = oegraphsim.OEFingerPrint()
molB = oechem.OEGraphMol()
oechem.OESmilesToMol(molB, "COc1cc2ccc(cc2c(=O)o1)NC(=N)N")
fpB = oegraphsim.OEFingerPrint()
molC = oechem.OEGraphMol()
oechem.OESmilesToMol(molC, "COc1c(c2ccc(cc2c(=O)o1)NC(=N)N)Cl")
fpC = oegraphsim.OEFingerPrint()
def CalculateYule(fpA, fpB):
onlyA, onlyB, bothAB, neitherAB = oechem.OEGetBitCounts(fpA, fpB)
yule = float(bothAB * neitherAB - onlyA * onlyB)
yule /= float(bothAB * neitherAB + onlyA * onlyB)
return yule
oegraphsim.OEMakeFP(fpA, molA, oegraphsim.OEFPType_Path)
oegraphsim.OEMakeFP(fpB, molB, oegraphsim.OEFPType_Path)
oegraphsim.OEMakeFP(fpC, molC, oegraphsim.OEFPType_Path)
print("Yule(A,B) = %.3f" % CalculateYule(fpA, fpB))
print("Yule(A,C) = %.3f" % CalculateYule(fpA, fpC))
print("Yule(B,C) = %.3f" % CalculateYule(fpB, fpC))
Listing 35: Fingerprint parameters.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oegraphsim
fptype = oegraphsim.OEGetFPType(oegraphsim.OEFPType_Path)
prms = oegraphsim.OEFPTypeParams(fptype.GetFPTypeString())
print("version = %s" % oegraphsim.OEGetFingerPrintVersionString(prms.GetVersion()))
print("number of bits = %d" % prms.GetNumBits())
print("min bonds = %d" % prms.GetMinDistance())
print("max bonds = %d" % prms.GetMaxDistance())
print("atom types = %s" % oegraphsim.OEGetFPAtomType(prms.GetAtomTypes()))
print("bond types = %s" % oegraphsim.OEGetFPBondType(prms.GetBondTypes()))
MedChem Toolkit
These examples illustrate use of the MedChem toolkit, which provides facilities for fragmentation-based analysis. For a full list of examples, see the MedChem chapter.
Listing 1: Example of molecule fragmentation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oemedchem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "COc1ccc(cc1)CC(=O)N")
for frag in oemedchem.OEGetRingChainFragments(mol):
fragatompred = oechem.OEIsAtomMember(frag.GetAtoms())
fragbondpred = oechem.OEIsBondMember(frag.GetBonds())
fragment = oechem.OEGraphMol()
adjustHCount = True
oechem.OESubsetMol(fragment, mol, fragatompred, fragbondpred, adjustHCount)
print(oechem.OEMolToSmiles(fragment))
Listing 2: Example of molecule fragmentation with annotations.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oemedchem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CCOc1ccc(cc1)CC(OC)c2ccccc2CC(=O)N")
adjustHCount = True
for frag in oemedchem.OEGetBemisMurcko(mol):
fragment = oechem.OEGraphMol()
oechem.OESubsetMol(fragment, mol, frag, adjustHCount)
print(".".join(r.GetName() for r in frag.GetRoles()), oechem.OEMolToSmiles(fragment))
Listing 3: Example of custom molecule fragmentation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oemedchem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CCc1nc(nc(n1)OC)NC(CC(=O)N)NS(=O)(=O)c2ccccc2CC(=O)N")
subsearch = oechem.OESubSearch()
subsearch.Init("[#6]-CC(=O)N")
options = oemedchem.OEBemisMurckoOptions()
options.SetSubstituentSearch(subsearch)
adjustHCount = True
for frag in oemedchem.OEGetBemisMurcko(mol, options):
fragment = oechem.OEGraphMol()
oechem.OESubsetMol(fragment, mol, frag, adjustHCount)
print(".".join(r.GetName() for r in frag.GetRoles()), oechem.OEMolToSmiles(fragment))
Listing 4: Example of custom molecule fragmentation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oemedchem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CCc1nc(nc(n1)OC)NC(=O)NS(=O)(=O)c2ccccc2OC")
options = oemedchem.OEBemisMurckoOptions()
options.SetUnsaturatedHeteroBonds(True)
adjustHCount = True
for frag in oemedchem.OEGetBemisMurcko(mol, options):
fragment = oechem.OEGraphMol()
oechem.OESubsetMol(fragment, mol, frag, adjustHCount)
print(".".join(r.GetName() for r in frag.GetRoles()), oechem.OEMolToSmiles(fragment))
MolProp Toolkit
These examples illustrate use of the MolProp toolkit, which provides a customizable framework for molecular property calculation geared toward enabling rapid database filtering. For a full list of examples, see the MolProp chapter.
Listing 1: Example of retrieving individual atom contributions to PSA.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oemolprop
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <molfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % sys.argv[1])
atomPSA = oechem.OEFloatArray(mol.GetMaxAtomIdx())
psa = oemolprop.OEGet2dPSA(mol, atomPSA)
print("PSA =", psa)
for atom in mol.GetAtoms():
idx = atom.GetIdx()
print(idx, atomPSA[idx])
Listing 2: Example of retrieving individual atom contributions to XLogP
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oemolprop
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <molfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % sys.argv[1])
atomXLogP = oechem.OEFloatArray(mol.GetMaxAtomIdx())
result = oemolprop.OEGetXLogPResult(mol, atomXLogP)
if (result.IsValid()):
print("XLogP =", result.GetValue())
for atom in mol.GetAtoms():
idx = atom.GetIdx()
print(idx, atomXLogP[idx])
else:
print("XLogP failed for molecule")
OEChem Toolkit
These selected examples illustrate use of the OEChem toolkit, which is a powerful programming library for chemistry and cheminformatics. For a full list of examples, also see the OEChem chapter.
Listing 1: Alternate location factory groups
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
def PrintAltGroupInfo(mol):
if not oechem.OEHasResidues(mol):
oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)
alf = oechem.OEAltLocationFactory(mol) # create factory for mol
print("%s\t(%s groups)" % (mol.GetTitle(), alf.GetGroupCount()))
for grp in alf.GetGroups():
print("\t%s locs:%s" % (grp.GetLocationCount(), alf.GetLocationCodes(grp)))
def main(argv=[__name__]):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <mol-infile>" % argv[0])
ims = oechem.oemolistream()
if not ims.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
# need this flavor to read alt loc atoms
ims.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_ALTLOC)
ims.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEIFlavor_MMCIF_ALTLOC)
for mol in ims.GetOEGraphMols():
PrintAltGroupInfo(mol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 2: Aromaticity perception with various models
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
def PerceiveAromaticity(mol, modelname, aromodel):
oechem.OEAssignAromaticFlags(mol, aromodel)
cansmi = oechem.OECreateCanSmiString(mol)
print(modelname, ":", cansmi)
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ncncc1c2cocc2-c3[nH]ccc(=O)c3")
PerceiveAromaticity(mol, "OEAroModelOpenEye ", oechem.OEAroModel_OpenEye)
PerceiveAromaticity(mol, "OEAroModelDaylight", oechem.OEAroModel_Daylight)
PerceiveAromaticity(mol, "OEAroModelTripos ", oechem.OEAroModel_Tripos)
PerceiveAromaticity(mol, "OEAroModelMMFF ", oechem.OEAroModel_MMFF)
PerceiveAromaticity(mol, "OEAroModelMDL ", oechem.OEAroModel_MDL)
Listing 3: Substructure search with atom mappings
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1C")
# create a substructure search object
ss = oechem.OESubSearch("c1ccccc1")
oechem.OEPrepareSearch(mol, ss)
# loop over matches
for count, match in enumerate(ss.Match(mol)):
print("Match", count + 1, ":", end=" ")
print("pattern atoms:", end=" ")
for ma in match.GetAtoms():
print(ma.pattern.GetIdx(), end=" ")
print("target atoms:", end=" ")
for ma in match.GetAtoms():
print(ma.target.GetIdx(), end=" ")
print()
Listing 4: Combining predefined atom predicates
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cnc(O)cc1CCCBr")
print("Number of chain atoms =", end=" ")
print(oechem.OECount(mol, oechem.OENotAtom(oechem.OEAtomIsInRing())))
print("Number of aromatic nitrogens =", end=" ")
print(oechem.OECount(mol, oechem.OEAndAtom(oechem.OEIsNitrogen(), oechem.OEIsAromaticAtom())))
print("Number of non-carbons =", end=" ")
print(oechem.OECount(mol, oechem.OENotAtom(oechem.OEHasAtomicNum(oechem.OEElemNo_C))))
print("Number of nitrogen and oxygen atoms =", end=" ")
print(oechem.OECount(mol, oechem.OEOrAtom(oechem.OEHasAtomicNum(oechem.OEElemNo_N),
oechem.OEHasAtomicNum(oechem.OEElemNo_O))))
Listing 5: Combining predefined bond predicates
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "N#CCC1CCNC=C1")
print("Number of non-rotatable bonds =", end=" ")
print(oechem.OECount(mol, oechem.OENotBond(oechem.OEIsRotor())))
print("Number of ring double bonds =", end=" ")
print(oechem.OECount(mol, oechem.OEAndBond(oechem.OEBondIsInRing(), oechem.OEHasOrder(2))))
print("Number of double or triple bonds =", end=" ")
print(oechem.OECount(mol, oechem.OEOrBond(oechem.OEHasOrder(2), oechem.OEHasOrder(3))))
Listing 6: Clearing aromaticity
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OEParseSmiles(mol, "n1ccncc1")
print("Canonical smiles :", oechem.OECreateCanSmiString(mol))
oechem.OEClearAromaticFlags(mol)
oechem.OEKekulize(mol)
print("Kekule smiles :", oechem.OECreateCanSmiString(mol))
Listing 7: Looping over hierarchical components
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
def CalcResCounts(mol):
hv = oechem.OEHierView(mol)
chainCt = 0
fragCt = 0
resCt = 0
watCt = 0
for chain in hv.GetChains():
chainCt += 1
for frag in chain.GetFragments():
fragCt += 1
for hres in frag.GetResidues():
resCt += 1
if (oechem.OEGetResidueIndex(hres.GetOEResidue()) ==
oechem.OEResidueIndex_HOH):
watCt += 1
print("Molecule : %s" % mol.GetTitle())
print("Chains : %d" % chainCt)
print("Fragments: %d" % fragCt)
print("Residues : %d (%d waters)" % (resCt, watCt))
def main(argv=[__name__]):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <mol-infile>" % argv[0])
ims = oechem.oemolistream()
if not ims.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
for mol in ims.GetOEGraphMols():
if not oechem.OEHasResidues(mol):
oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)
CalcResCounts(mol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 10: Retrieving a subset of a file
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
if len(sys.argv) != 5:
oechem.OEThrow.Usage("%s <input> <output> <offset> <limit>" % sys.argv[0])
moldb = oechem.OEMolDatabase()
if not moldb.Open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s" % sys.argv[1])
if moldb.GetFormat() != oechem.OEGetFileType(oechem.OEGetFileExtension(sys.argv[2])):
oechem.OEThrow.Fatal("Output format does not match input format: %s != %s" %
(oechem.OEGetFileExtension(sys.argv[1]),
oechem.OEGetFileExtension(sys.argv[2])))
ofs = oechem.oemolostream()
if not ofs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % sys.argv[2])
offset = int(sys.argv[3])
limit = int(sys.argv[4])
maxIdx = offset + limit
for idx in range(offset, maxIdx):
moldb.WriteMolecule(ofs, idx)
Listing 11: Extract molecules by title
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
if len(sys.argv) != 4:
oechem.OEThrow.Usage("%s <input> <output> <title>" % sys.argv[0])
moldb = oechem.OEMolDatabase()
if not moldb.Open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s" % sys.argv[1])
if moldb.GetFormat() != oechem.OEGetFileType(oechem.OEGetFileExtension(sys.argv[2])):
oechem.OEThrow.Fatal("Output format does not match input format: %s != %s" %
(oechem.OEGetFileExtension(sys.argv[1]),
oechem.OEGetFileExtension(sys.argv[2])))
ofs = oechem.oemolostream()
if not ofs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % sys.argv[2])
title = sys.argv[3]
for idx in range(moldb.GetMaxMolIdx()):
if moldb.GetTitle(idx) == title:
moldb.WriteMolecule(ofs, idx)
Listing 12: SD data manipulation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
def DumpSDData(mol):
print("SD data of", mol.GetTitle())
# loop over SD data
for dp in oechem.OEGetSDDataPairs(mol):
print(dp.GetTag(), ':', dp.GetValue())
print()
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
mol.SetTitle("benzene")
# set some tagged data
oechem.OESetSDData(mol, "color", "brown")
oechem.OESetSDData(mol, oechem.OESDDataPair("size", "small"))
DumpSDData(mol)
# check for existence of data, then delete it
if oechem.OEHasSDData(mol, "size"):
oechem.OEDeleteSDData(mol, "size")
DumpSDData(mol)
# add additional color data
oechem.OEAddSDData(mol, "color", "black")
DumpSDData(mol)
# remove all SD data
oechem.OEClearSDData(mol)
DumpSDData(mol)
Listing 13: Using Threaded Input and Output
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
ss = oechem.OESubSearch(sys.argv[1])
ifs = oechem.oemolithread(sys.argv[2])
ofs = oechem.oemolothread(sys.argv[3])
for mol in ifs.GetOEGraphMols():
oechem.OEPrepareSearch(mol, ss)
if ss.SingleMatch(mol):
oechem.OEWriteMolecule(ofs, mol)
Listing 14: Using multiple threads to read and write to molthreads
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from threading import Thread
import sys
ss = oechem.OESubSearch(sys.argv[1])
ifs = oechem.oemolithread(sys.argv[2])
ofs = oechem.oemolothread(sys.argv[3])
class MultiCoreMolFind(Thread):
def run(self):
for mol in ifs.GetOEGraphMols():
oechem.OEPrepareSearch(mol, ss)
if ss.SingleMatch(mol):
oechem.OEWriteMolecule(ofs, mol)
thrds = []
for i in range(oechem.OEGetNumProcessors()):
thrd = MultiCoreMolFind()
thrd.start()
thrds.append(thrd)
for thrd in thrds:
thrd.join()
Listing 15: Setting mutexed memory pool mode
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from threading import Thread
try:
from queue import Queue
except ImportError:
from Queue import Queue
import sys
ss = oechem.OESubSearch(sys.argv[1])
ifs = oechem.oemolithread(sys.argv[2])
ofs = oechem.oemolothread(sys.argv[3])
iqueue = Queue(1024)
oqueue = Queue(1024)
class ParseThread(Thread):
def run(self):
mol = oechem.OEGraphMol()
while oechem.OEReadMolecule(ifs, mol):
iqueue.put(mol, block=True)
mol = oechem.OEGraphMol()
# signal SearchThread to die
iqueue.put(None, block=True)
class SearchThread(Thread):
def run(self):
mol = iqueue.get(block=True)
while mol is not None:
oechem.OEPrepareSearch(mol, ss)
if ss.SingleMatch(mol):
oqueue.put(mol, block=True)
mol = iqueue.get(block=True)
# signal main thread to die
oqueue.put(None, block=True)
pthrd = ParseThread()
pthrd.start()
sthrd = SearchThread()
sthrd.start()
# main thread will handle output
mol = oqueue.get(block=True)
while mol is not None:
oechem.OEWriteMolecule(ofs, mol)
mol = oqueue.get(block=True)
Listing 16: PDB data manipulation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <pdbfile>" % sys.argv[0])
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s" % sys.argv[1])
# need to set input flavor to ensure PDB data is stored on molecule
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_SpruceDefault)
ifs.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEIFlavor_MMCIF_SpruceDefault)
mol = oechem.OEGraphMol()
while oechem.OEReadMolecule(ifs, mol):
if oechem.OEHasPDBData(mol, "COMPND"):
print("COMPND:")
print(oechem.OEGetPDBData(mol, "COMPND"))
if oechem.OEHasPDBData(mol, "HELIX "):
print("HELIX:")
print(oechem.OEGetPDBData(mol, "HELIX "))
if oechem.OEHasPDBData(mol, "SSBOND"):
print("SSBOND:")
for dp in oechem.OEGetPDBDataPairs(mol):
if dp.GetTag() == "SSBOND":
print(dp.GetValue())
Listing 17: Simple substructure search example
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1C")
# create a substructure search object
ss = oechem.OESubSearch("c1ccccc1")
oechem.OEPrepareSearch(mol, ss)
if ss.SingleMatch(mol):
print("benzene matches toluene")
else:
print("benzene does not match toluene")
Listing 18: Extracting molecules based upon a substructure
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
ss = oechem.OESubSearch(sys.argv[1])
ifs = oechem.oemolistream(sys.argv[2])
ofs = oechem.oemolostream(sys.argv[3])
for mol in ifs.GetOEGraphMols():
oechem.OEPrepareSearch(mol, ss)
if ss.SingleMatch(mol):
oechem.OEWriteMolecule(ofs, mol)
Listing 19: Substructures match for query molecule
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
qmol = oechem.OEGraphMol()
oechem.OESmilesToMol(qmol, "c1ccccc1")
# create a substructure search object
itag = oechem.OEGetTag("__orig_idx")
for ai in qmol.GetAtoms():
ai.SetData(itag, ai.GetIdx())
ss = oechem.OESubSearch(qmol, oechem.OEExprOpts_DefaultAtoms, oechem.OEExprOpts_DefaultBonds)
tmol = oechem.OEGraphMol()
oechem.OESmilesToMol(tmol, "Cc1ccccc1")
oechem.OEPrepareSearch(tmol, ss)
for mi in ss.Match(tmol, True):
match = oechem.OEMatch()
for apairi in mi.GetAtoms():
pidx = apairi.pattern.GetData(itag)
pattern = qmol.GetAtom(oechem.OEHasAtomIdx(pidx))
match.AddPair(pattern, apairi.target)
Listing 20: Using functor callbacks
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
def CountAtoms(mol, pred):
counts = 0
for atom in mol.GetAtoms():
if pred(atom):
counts += 1
return counts
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2")
print("Number of oxygen atoms =", CountAtoms(mol, oechem.OEIsOxygen()))
Listing 21: Using predefined atom functors
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2")
print("Number of heavy atoms =", oechem.OECount(mol, oechem.OEIsHeavy()))
print("Number of ring atoms =", oechem.OECount(mol, oechem.OEAtomIsInRing()))
Listing 22: Using predefined bond functors
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC(=O)Nc1c[nH]cc1")
print("Number of ring bonds =", oechem.OECount(mol, oechem.OEBondIsInRing()))
print("Number of rotor bonds =", oechem.OECount(mol, oechem.OEIsRotor()))
Listing 23: Functor substructure-based matching
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C1(Cl)C(N)C(F)OC1C(=O)NCCCN")
NonAmideNitrogenPred = oechem.OEMatchAtom("[N;!$(NC=O)]")
print("Number of non-amide nitrogen =", oechem.OECount(mol, NonAmideNitrogenPred))
FiveMemberedRingOxygenPred = oechem.OEMatchAtom("[O;r5]")
print("Number of 5-membered ring oxygen =", oechem.OECount(mol, FiveMemberedRingOxygenPred))
CarbonAttachedToHalogenPred = oechem.OEMatchAtom("[#6][Cl,Br,F]")
print("Number of carbon attached to halogen =", oechem.OECount(mol, CarbonAttachedToHalogenPred))
Listing 24: Ring system extraction
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2")
nrrings, rings = oechem.OEDetermineRingSystems(mol)
pred = oechem.OEPartPredAtom(rings)
print("Number of rings =", nrrings)
for r in range(1, nrrings + 1):
pred.SelectPart(r)
ringmol = oechem.OEGraphMol()
oechem.OESubsetMol(ringmol, mol, pred, True)
print(r, "->", oechem.OEMolToSmiles(ringmol))
Listing 25: Ring system extraction
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2")
submol = oechem.OEGraphMol()
oechem.OESubsetMol(submol, mol, oechem.OEAtomIsInRing(), True)
print(oechem.OEMolToSmiles(submol))
Listing 26: Example of attaching a molecule as generic data
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1ccccc1O")
frag = oechem.OEGraphMol()
oechem.OESubsetMol(frag, mol, oechem.OEIsCarbon())
mol.SetData("just_carbon", frag)
justCarbon = mol.GetData("just_carbon")
Listing 27: Example of using generic data
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
def CalculateMoleculeWeight(mol):
mol.SetData("MolWeight", oechem.OECalculateMolecularWeight(mol))
def PrintMoleculeWeight(mol):
tag = oechem.OEGetTag("MolWeight")
if mol.HasData(tag):
print("molecule weight =", mol.GetData(tag))
else:
print("molecule weight is not calculated!")
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C1CCCC(C(=O)O)C1")
CalculateMoleculeWeight(mol)
PrintMoleculeWeight(mol)
Listing 28: Example of attaching generic data to atoms
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
IsDonorAtom = oechem.OEMatchAtom("[!H0;#7,#8]")
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1c(Cl)cncc1C(=O)O")
for atom in mol.GetAtoms():
atom.SetData("isdonor", IsDonorAtom(atom))
class IsDonorAtomPred(oechem.OEUnaryAtomPred):
def __call__(self, atom):
return atom.GetData("isdonor")
print("Donor atoms:", end=" ")
for atom in mol.GetAtoms(IsDonorAtomPred()):
print(atom.GetIdx(), oechem.OEGetAtomicSymbol(atom.GetAtomicNum()), end=" ")
print()
Listing 29: Getting started with OEInterface command line parsing
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!PARAMETER -b
!TYPE bool
!BRIEF A boolean parameter
!END
!PARAMETER -i
!TYPE int
!BRIEF An integer parameter
!END
!PARAMETER -f
!TYPE float
!BRIEF A float parameter
!END
!PARAMETER -str
!TYPE string
!BRIEF A string parameter
!END
"""
itf = oechem.OEInterface(InterfaceData, sys.argv)
print("-b =", itf.GetBool("-b"))
print("-i =", itf.GetInt("-i"))
print("-f =", itf.GetFloat("-f"))
print("-str =", itf.GetString("-str"))
Listing 30: Retrieving the Nth molecule in a file
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
if len(sys.argv) != 4:
oechem.OEThrow.Usage("%s <input> <output> <index>" % sys.argv[0])
moldb = oechem.OEMolDatabase()
if not moldb.Open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % sys.argv[1])
ofs = oechem.oemolostream()
if not ofs.open(sys.argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % sys.argv[2])
idx = int(sys.argv[3])
mol = oechem.OEMol()
if not moldb.GetMolecule(mol, idx):
oechem.OEThrow.Fatal("Unable to read a molecule from index %u" % idx)
oechem.OEWriteMolecule(ofs, mol)
Listing 31: Example of using molecule parameter
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!PARAMETER -mol
!TYPE OEGraphMol
!BRIEF Molecule file
!REQUIRED true
!KEYLESS 1
!END
"""
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
mol = itf.GetOEGraphMol("-mol")
print("Number of heavy atoms in molecule = %d" % oechem.OECount(mol, oechem.OEIsHeavy()))
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 32: Aromatic ring system identification
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C(O)(=O)c1cccc2c1[nH]c(C3CCCc4c3cccc4)c2")
nraromsystems, parts = oechem.OEDetermineAromaticRingSystems(mol)
print("Aliphatic atoms:", end=" ")
for atom in mol.GetAtoms():
if parts[atom.GetIdx()] == 0:
print(atom.GetIdx(), end=" ")
print()
print("Number of aromatic ring systems =", nraromsystems)
for ringidx in range(1, nraromsystems + 1):
print(ringidx, ". aromatic ring system:", end=" ")
for atom in mol.GetAtoms():
if parts[atom.GetIdx()] == ringidx:
print(atom.GetIdx(), end=" ")
print()
Listing 33: Accessing atom stereo information
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "[H][C@]1(NC[C@@H](CC1CO[C@H]2CC[C@@H](CC2)O)N)[H]")
for atom in mol.GetAtoms():
chiral = atom.IsChiral()
stereo = oechem.OEAtomStereo_Undefined
if atom.HasStereoSpecified(oechem.OEAtomStereo_Tetrahedral):
v = []
for nbr in atom.GetAtoms():
v.append(nbr)
stereo = atom.GetStereo(v, oechem.OEAtomStereo_Tetrahedral)
if chiral or stereo != oechem.OEAtomStereo_Undefined:
print("Atom:", atom.GetIdx(), "chiral=", chiral, "stereo=", end=" ")
if stereo == oechem.OEAtomStereo_RightHanded:
print("right handed")
elif stereo == oechem.OEAtomStereo_LeftHanded:
print("left handed")
else:
print("undefined")
Listing 34: Accessing bond stereo information
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C\\C=C\\C=C/C=CC")
for bond in mol.GetBonds():
if bond.HasStereoSpecified(oechem.OEBondStereo_CisTrans):
for atomB in bond.GetBgn().GetAtoms():
if atomB == bond.GetEnd():
continue
for atomE in bond.GetEnd().GetAtoms():
if atomE == bond.GetBgn():
continue
v = []
v.append(atomB)
v.append(atomE)
stereo = bond.GetStereo(v, oechem.OEBondStereo_CisTrans)
print("Atoms:", atomB.GetIdx(), "and", atomE.GetIdx(), "are", end=" ")
if stereo == oechem.OEBondStereo_Cis:
print("cis")
elif stereo == oechem.OEBondStereo_Trans:
print("trans")
Listing 35: Perceiving CIP atom stereo information
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "N[C@@H]1N[C@@H](O)CC(O)C1.C2[C@@H](O)CC[C@@H](O)C2")
for atom in mol.GetAtoms():
cip = oechem.OEPerceiveCIPStereo(mol, atom)
if atom.HasStereoSpecified():
print("atom %d is" % atom.GetIdx(), end=" ")
if cip == oechem.OECIPAtomStereo_S:
print('S')
if cip == oechem.OECIPAtomStereo_R:
print('R')
if cip == oechem.OECIPAtomStereo_NotStereo:
print('not a CIP stereo center')
if cip == oechem.OECIPAtomStereo_UnspecStereo:
print("atom %d is" % atom.GetIdx(), end=" ")
print('a CIP stereo center without specified stereochemistry')
Listing 36: Perceiving CIP bond stereo information
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C\\C(C)=C(\\C)C.O\\C(C)=C(\\C)O.O\\C(C)=C(\\O)C.CC(O)=C(O)C")
for bond in mol.GetBonds():
if bond.GetOrder() == 2:
cip = oechem.OEPerceiveCIPStereo(mol, bond)
print("bond %d is" % bond.GetIdx(), end=" ")
if bond.HasStereoSpecified():
if cip == oechem.OECIPBondStereo_E:
print('E')
if cip == oechem.OECIPBondStereo_Z:
print('Z')
if cip == oechem.OECIPBondStereo_NotStereo:
print('not a CIP stereo center')
if cip == oechem.OECIPBondStereo_UnspecStereo:
print('a CIP stereo center without specified stereochemistry')
Listing 37: Constructing a scalar grid
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oegrid
grid = oegrid.OEScalarGrid(64, 64, 64, 0.0, 0.0, 0.0, 0.5)
Listing 38: Setting atom stereo information
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "[H][C@]1(NC[C@@H](CC1CO[C@H]2CC[C@@H](CC2)O)N)[H]")
for atom in mol.GetAtoms():
if atom.IsChiral() and not atom.HasStereoSpecified(oechem.OEAtomStereo_Tetrahedral):
v = []
for neigh in atom.GetAtoms():
v.append(neigh)
atom.SetStereo(v, oechem.OEAtomStereo_Tetra, oechem.OEAtomStereo_Left)
print(oechem.OEMolToSmiles(mol))
Listing 39: Setting bond stereo information
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "C\\C=C\\C=C/C=CC")
for bond in mol.GetBonds():
if bond.GetOrder() == 2 and not bond.HasStereoSpecified(oechem.OEBondStereo_CisTrans):
v = []
for neigh in bond.GetBgn().GetAtoms():
if neigh != bond.GetEnd():
v.append(neigh)
break
for neigh in bond.GetEnd().GetAtoms():
if neigh != bond.GetBgn():
v.append(neigh)
break
bond.SetStereo(v, oechem.OEBondStereo_CisTrans, oechem.OEBondStereo_Trans)
print(oechem.OEMolToSmiles(mol))
Listing 40: Accessing OEResidue properties
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
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))
def main(argv=[__name__]):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <mol-infile>" % argv[0])
ims = oechem.oemolistream()
if not ims.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
for mol in ims.GetOEGraphMols():
CalcResCounts(mol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 41: User defined atom predicate
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
class PredAliphaticNitrogen(oechem.OEUnaryAtomPred):
def __call__(self, atom):
return atom.IsNitrogen() and not atom.IsAromatic()
def CreateCopy(self):
# __disown__ is required to allow C++ to take ownership of this
# object and its memory
return PredAliphaticNitrogen().__disown__()
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2")
print("Number of aliphatic N atoms =", end=" ")
print(oechem.OECount(mol, PredAliphaticNitrogen()))
Listing 42: User defined atom predicate with state
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
class PredAtomicNumList(oechem.OEUnaryAtomPred):
def __init__(self, alist):
oechem.OEUnaryAtomPred.__init__(self)
self.atomiclist = alist
def __call__(self, atom):
return (atom.GetAtomicNum() in self.atomiclist)
def CreateCopy(self):
# __disown__ is required to allow C++ to take ownership of this
# object and its memory
return PredAtomicNumList(self.atomiclist).__disown__()
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "c1cc[nH]c1CC2COCNC2")
alist = [oechem.OEElemNo_O, oechem.OEElemNo_N]
print("Number of oxygen or nitrogen atoms =", end=" ")
print(oechem.OECount(mol, PredAtomicNumList(alist)))
Listing 43: User defined bond predicate
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
class PredHasDoubleBondO(oechem.OEUnaryAtomPred):
def __call__(self, atom):
for bond in atom.GetBonds():
if bond.GetOrder() == 2 and bond.GetNbr(atom).IsOxygen():
return True
return False
def CreateCopy(self):
# __disown__ is required to allow C++ to take ownership of this
# object and its memory
return PredHasDoubleBondO().__disown__()
class PredAmideBond(oechem.OEUnaryBondPred):
def __call__(self, bond):
if bond.GetOrder() != 1:
return False
atomB = bond.GetBgn()
atomE = bond.GetEnd()
pred = PredHasDoubleBondO()
if atomB.IsCarbon() and atomE.IsNitrogen() and pred(atomB):
return True
if atomB.IsNitrogen() and atomE.IsCarbon() and pred(atomE):
return True
return False
def CreateCopy(self):
# __disown__ is required to allow C++ to take ownership of this
# object and its memory
return PredAmideBond().__disown__()
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "CC(=O)Nc1c[nH]cc1")
print("Number of amide bonds =", oechem.OECount(mol, PredAmideBond()))
Listing 44: Setting a default value for a parameter
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!PARAMETER -b
!TYPE bool
!DEFAULT false
!BRIEF An boolean parameter
!END
!PARAMETER -i
!TYPE int
!DEFAULT 2
!BRIEF An integer parameter
!END
!PARAMETER -f
!TYPE float
!DEFAULT 0.5
!BRIEF A float parameter
!END
!PARAMETER -str
!TYPE string
!DEFAULT foo
!BRIEF A string parameter
!END
"""
itf = oechem.OEInterface(InterfaceData, sys.argv)
print("-b =", itf.GetBool("-b"))
print("-i =", itf.GetInt("-i"))
print("-f =", itf.GetFloat("-f"))
print("-str =", itf.GetString("-str"))
Listing 45: Testing for parameter existence with the Has method
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!PARAMETER -b
!TYPE bool
!BRIEF An boolean parameter
!END
!PARAMETER -i
!TYPE int
!BRIEF An integer parameter
!END
!PARAMETER -f
!TYPE float
!BRIEF A float parameter
!END
!PARAMETER -str
!TYPE string
!BRIEF A string parameter
!END
"""
itf = oechem.OEInterface(InterfaceData, sys.argv)
if itf.HasBool("-b"):
print("-b =", itf.GetBool("-b"))
if itf.HasInt("-i"):
print("-i =", itf.GetInt("-i"))
if itf.HasFloat("-f"):
print("-f =", itf.GetFloat("-f"))
if itf.HasString("-str"):
print("-str =", itf.GetString("-str"))
Listing 46: A program to concatenate any number of molecules together
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!BRIEF UsingOEInterfaceHelp.py [-d <delimiter>] [-o] <output> [-i] <input1> <input2> ...
!PARAMETER -delim
!ALIAS -d
!TYPE string
!SIMPLE true
!DEFAULT _
!BRIEF Title delimiter
!DETAIL
This is the value given to the OEChem function OEAddMols to
separate the titles of the input molecules in the output.
!END
!PARAMETER -output
!ALIAS -o
!TYPE string
!SIMPLE true
!REQUIRED true
!KEYLESS 1
!BRIEF The output file
!DETAIL
The molecule file to output to, can be any file format
OEChem supports.
!END
!PARAMETER -inputs
!ALIAS -i
!TYPE string
!SIMPLE true
!REQUIRED true
!LIST true
!KEYLESS 2
!BRIEF The input files
!DETAIL
A list of molecule files to add together. Note, only the
first molecule from every file will be added.
!END
"""
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
outmol = oechem.OEGraphMol()
for fname in itf.GetStringList("-inputs"):
ims = oechem.oemolistream(fname)
inmol = oechem.OEGraphMol()
oechem.OEReadMolecule(ims, inmol)
oechem.OEAddMols(outmol, inmol, itf.GetString("-delim"))
oms = oechem.oemolostream(itf.GetString("-output"))
oechem.OEWriteMolecule(oms, outmol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 47: Specifying keyless input and output file parameters
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!PARAMETER -i
!TYPE string
!KEYLESS 1
!BRIEF Input file name
!END
!PARAMETER -o
!TYPE string
!KEYLESS 2
!BRIEF Output file name
!END
"""
itf = oechem.OEInterface(InterfaceData, sys.argv)
print("Input file name =", itf.GetString("-i"))
print("Output file name =", itf.GetString("-o"))
Listing 48: Specifying that a parameter is a list of values
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!PARAMETER -strs
!TYPE string
!LIST true
!BRIEF Some string parameters
!END
"""
itf = oechem.OEInterface(InterfaceData, sys.argv)
print("-strs =", end=" ")
for param in itf.GetStringList("-strs"):
print(param)
print(" ", end=" ")
Listing 49: Requiring all parameters to be specified.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
import sys
InterfaceData = """
!PARAMETER -b
!TYPE bool
!REQUIRED true
!BRIEF An boolean parameter
!END
!PARAMETER -i
!TYPE int
!REQUIRED true
!BRIEF An integer parameter
!END
!PARAMETER -f
!TYPE float
!REQUIRED true
!BRIEF A float parameter
!END
!PARAMETER -str
!TYPE string
!REQUIRED true
!BRIEF A string parameter
!END
"""
itf = oechem.OEInterface(InterfaceData, sys.argv)
print("-b =", itf.GetBool("-b"))
print("-i =", itf.GetInt("-i"))
print("-f =", itf.GetFloat("-f"))
print("-str =", itf.GetString("-str"))
Listing 50: Writing out SD data as CSV
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
ofs = oechem.oemolostream()
ofs.SetFormat(oechem.OEFormat_CSV)
mol = oechem.OEGraphMol()
oechem.OESmilesToMol(mol, "O")
mol.SetTitle("water")
oechem.OESetSDData(mol, "phases", "gas,liquid,solid")
oechem.OESetSDData(mol, "uses", "bathing\nwater guns\ntea|earl grey|hot")
oechem.OEWriteMolecule(ofs, mol)
Listing 51: Print anisotropic B-factors.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Output anisotropic B factor information
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
verbose = itf.GetBool("-verbose")
ifname = itf.GetString("-input")
ims = oechem.oemolistream()
if not ims.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifname)
ims.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_Default | oechem.OEIFlavor_PDB_DATA)
for mol in ims.GetOEMols():
if verbose:
if not oechem.OEHasResidues(mol):
oechem.OEPerceiveResidues(mol, oechem.OEPreserveResInfo_All)
for atom in mol.GetAtoms():
res = oechem.OEAtomGetResidue(atom)
uij = oechem.OEAnisoUij()
if oechem.OEGetAnisou(uij, atom):
oechem.OEThrow.Info("%s %s%c %s%d%c %c (u11=%5d, u22=%5d, u33=%5d, \
u12=%5d, u13=%5d, u23=%5d)" %
(mol.GetTitle(),
atom.GetName(),
res.GetAlternateLocation(),
res.GetName(),
res.GetResidueNumber(),
res.GetInsertCode(),
res.GetChainID(),
uij.GetU11(),
uij.GetU22(),
uij.GetU33(),
uij.GetU12(),
uij.GetU13(),
uij.GetU23()))
else:
oechem.OEThrow.Info("%s %s%c %s%d%c %c -no-anisou-" % (mol.GetTitle(),
atom.GetName(),
res.GetAlternateLocation(),
res.GetName(),
res.GetResidueNumber(),
res.GetInsertCode(),
res.GetChainID()))
oechem.OEThrow.Info("%s %d atoms with anisou data (out of %d)" % (mol.GetTitle(),
oechem.OECount(mol, oechem.OEHasAnisou()),
mol.NumAtoms()))
return 0
InterfaceData = """\
!BRIEF [-v] [-i] <mol file>
!CATEGORY "input options"
!PARAMETER -input
!ALIAS -i
!TYPE string
!REQUIRED true
!BRIEF input mol file name
!KEYLESS 1
!END
!END
!CATEGORY "options"
!PARAMETER -verbose
!ALIAS -v
!TYPE bool
!DEFAULT false
!BRIEF verbose
!END
!END
"""
#############################################################################
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 52: Append 2D ring dictionary.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Appends rings to an existing 2D rings dictionary
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
ifname = itf.GetString("-in")
irdfname = itf.GetString("-inringdict")
ordfname = itf.GetString("-outringdict")
ifs = oechem.oemolistream()
if not ifs.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading!" % ifname)
if not oechem.OEIs2DFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input file format for 2D coordinates!")
if not oechem.OEIsValid2DRingDictionary(irdfname):
oechem.OEThrow.Fatal("Invalid ring dirctinary file!")
ringdict = oechem.OE2DRingDictionary(irdfname)
nrrings = ringdict.NumRings()
dots = oechem.OEDots(10000, 100, "molecules")
for mol in ifs.GetOEGraphMols():
dots.Update()
ringdict.AddRings(mol)
dots.Total()
nrnewrings = ringdict.NumRings() - nrrings
oechem.OEThrow.Info("%d new ring templates have been added!" % nrnewrings)
oechem.OEWrite2DRingDictionary(ordfname, ringdict)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = """
!BRIEF [-in] <input> [-inringdict] <input ringdict> [-outringdict] <output ringdict>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input 2D molecule filename
!END
!PARAMETER -inringdict
!ALIAS -ird
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Input ring dictionary OEB filename
!DETAIL
2D ring dictionaries can be generated by the following OEChem examples:
C++ - createringdict.cpp
Python - createringdict.py
Java - CreateRingDict.java
C# - CreateRingDict.cs
!END
!PARAMETER -outringdict
!ALIAS -ord
!TYPE string
!REQUIRED true
!KEYLESS 3
!VISIBILITY simple
!BRIEF Output ring dictionary OEB filename
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 53: Use a SMIRKS specification to perform individual reaction transformations on single molecules.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Apply a transformation
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
opts = oechem.OEUniMolecularRxnOptions()
opts.SetStrictSmirks(itf.GetBool("-strict"))
opts.SetClearCoordinates(itf.GetBool("-clearcoords"))
opts.SetValidateKekule(itf.GetBool("-validkek"))
opts.SetMaxMatches(itf.GetInt("-max"))
altered = itf.GetString("-alteredtag")
opts.SetAlteredTag("")
if altered:
opts.SetAlteredTag(altered)
fixval = itf.GetString("-fixval")
if fixval.upper() == "EXPLICIT" or fixval.upper() == "NONE":
opts.SetFixValence(oechem.OEUniMolecularRxnFixValence_Explicit)
elif fixval.upper() == "ALTERED":
opts.SetFixValence(oechem.OEUniMolecularRxnFixValence_Altered)
elif fixval.upper() == "ALL":
opts.SetFixValence(oechem.OEUniMolecularRxnFixValence_All)
else:
oechem.Error("Unknown fix valence request: {}".format(fixval))
xform = itf.GetString("-smirks")
xformname = None
if " " in xform:
xform, xformname = xform.split(" ")[:2]
qrxn = oechem.OEQMol()
if not oechem.OEParseSmirks(qrxn, xform):
oechem.Fatal("SMIRKS parse error: {}".format(xform))
umr = oechem.OEUniMolecularRxn()
if not umr.Init(xform, opts):
oechem.Fatal("Error initializing OEUniMolecularRxn: {}".format(xform))
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-in")):
oechem.OEThrow.Fatal(
"Unable to open {} for reading".format(itf.GetString("-in"))
)
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-out")):
oechem.OEThrow.Fatal(
"Unable to open {} for writing".format(itf.GetString("-out"))
)
outfails = None
if itf.HasString("-noxform"):
print('noform=[{}]'.format(itf.GetString("-noxform")))
outfails = oechem.oemolostream()
if not outfails.open(itf.GetString("-noxform")):
oechem.OEThrow.Fatal(
"Unable to open failure file {} for writing".format(itf.GetString("-noxform"))
)
all2output = itf.GetBool("-passfail")
asrxn = itf.GetBool("-asrxn")
outmol = oechem.OEGraphMol()
for mol in ifs.GetOEGraphMols():
title = mol.GetTitle()
insmi = oechem.OEMolToSmiles(mol)
status = umr(mol)
if status or all2output:
if not asrxn:
if status and xformname:
mol.SetTitle("{}({})".format(xformname, mol.GetTitle()))
if (
oechem.OEWriteMolecule(ofs, mol)
!= oechem.OEWriteMolReturnCode_Success
):
oechem.Fatal(
"Error writing molecule: {}".format(oechem.OEMolToSmiles(mol))
)
else:
if not status:
outmol = mol
else:
oechem.OESmilesToMol(
outmol, "{}>>{}".format(insmi, oechem.OEMolToSmiles(mol))
)
if xformname:
outmol.SetTitle("{}({})".format(xformname, title))
else:
outmol.SetTitle(title)
if (
oechem.OEWriteMolecule(ofs, outmol)
!= oechem.OEWriteMolReturnCode_Success
):
oechem.Fatal(
"Error writing molecule: {}".format(
oechem.OEMolToSmiles(outmol)
)
)
elif outfails and not status:
if (
oechem.OEWriteMolecule(outfails, mol)
!= oechem.OEWriteMolReturnCode_Success
):
oechem.Fatal(
"Error writing molecule: {}".format(oechem.OEMolToSmiles(mol))
)
return 0
InterfaceData = """
!BRIEF -smirks SMIRKS -in <input> -out <output>
!CATEGORY I/O
!PARAMETER -smirks 1
!ALIAS -xform
!TYPE string
!REQUIRED true
!BRIEF Transformation SMIRKS
!KEYLESS 1
!END
!PARAMETER -in 2
!ALIAS -i
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 2
!END
!PARAMETER -out 3
!ALIAS -o
!ALIAS -success
!TYPE string
!REQUIRED true
!BRIEF Output file name
!KEYLESS 3
!END
!PARAMETER -noxform 4
!ALIAS -failure
!TYPE string
!REQUIRED false
!BRIEF Output file name for untransformed structures
!END
!END
!CATEGORY Options
!PARAMETER -strict 1
!ALIAS -strictsmirks
!TYPE bool
!REQUIRED false
!DEFAULT true
!BRIEF requested strict flag which controls the interpretation of the transformation SMIRKS (true:Daylight convention, false:OpenEye convention)
!END
!PARAMETER -clearcoords 2
!TYPE bool
!REQUIRED false
!DEFAULT true
!BRIEF whether to clear coordinates for transformed products
!END
!PARAMETER -validkek 3
!ALIAS -validkekule
!TYPE bool
!REQUIRED false
!DEFAULT true
!BRIEF whether the transformation validates the Kekule form of the transformed products
!END
!PARAMETER -fixval 4
!TYPE string
!REQUIRED false
!DEFAULT Explicit
!BRIEF type of valence correction to apply to the transformed products: Explicit(None), Altered, All
!END
!PARAMETER -max 5
!ALIAS -maxxforms
!TYPE int
!REQUIRED false
!DEFAULT 10
!BRIEF maximum number of transformation to apply to each processed molecule
!END
!PARAMETER -alteredtag 6
!TYPE string
!REQUIRED false
!DEFAULT None
!BRIEF A generic data tag to mark altered atom information from transformed products
!END
!PARAMETER -passfail 7
!TYPE bool
!REQUIRED false
!DEFAULT false
!BRIEF If true, include untransformed structures in -out
!END
!PARAMETER -asrxn 8
!TYPE bool
!REQUIRED false
!DEFAULT false
!BRIEF If true, output the transformation as a reaction
!END
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 54: Use a SMIRKS specification to perform individual reaction transformations on each input molecule.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Apply a transformation
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
opts = oechem.OEUniMolecularRxnOptions()
opts.SetStrictSmirks(itf.GetBool("-strict"))
opts.SetClearCoordinates(itf.GetBool("-clearcoords"))
opts.SetValidateKekule(itf.GetBool("-validkek"))
opts.SetMaxMatches(itf.GetInt("-max"))
altered = itf.GetString("-alteredtag")
opts.SetAlteredTag("")
if altered:
opts.SetAlteredTag(altered)
fixval = itf.GetString("-fixval")
if fixval.upper() == "EXPLICIT" or fixval.upper() == "NONE":
opts.SetFixValence(oechem.OEUniMolecularRxnFixValence_Explicit)
elif fixval.upper() == "ALTERED":
opts.SetFixValence(oechem.OEUniMolecularRxnFixValence_Altered)
elif fixval.upper() == "ALL":
opts.SetFixValence(oechem.OEUniMolecularRxnFixValence_All)
else:
oechem.Error("Unknown fix valence request: {}".format(fixval))
xform = itf.GetString("-smirks")
xformname = None
if " " in xform:
xform, xformname = xform.split(" ")[:2]
qrxn = oechem.OEQMol()
if not oechem.OEParseSmirks(qrxn, xform):
oechem.Fatal("SMIRKS parse error: {}".format(xform))
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-in")):
oechem.OEThrow.Fatal(
"Unable to open {} for reading".format(itf.GetString("-in"))
)
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-out")):
oechem.OEThrow.Fatal(
"Unable to open {} for writing".format(itf.GetString("-out"))
)
outfails = None
if itf.HasString("-noxform"):
print('noform=[{}]'.format(itf.GetString("-noxform")))
outfails = oechem.oemolostream()
if not outfails.open(itf.GetString("-noxform")):
oechem.OEThrow.Fatal(
"Unable to open failure file {} for writing".format(itf.GetString("-noxform"))
)
all2output = itf.GetBool("-passfail")
asrxn = itf.GetBool("-asrxn")
outxfmmol = oechem.OEGraphMol()
for mol in ifs.GetOEGraphMols():
title = mol.GetTitle()
insmi = oechem.OEMolToSmiles(mol)
nxforms = 0
for xfmmol in oechem.OEGetUniMolecularRxnIter(mol, qrxn, opts):
nxforms += 1
if not asrxn:
if xformname:
xfmmol.SetTitle("{}:{}({})".format(nxforms, xformname, mol.GetTitle()))
if (
oechem.OEWriteMolecule(ofs, xfmmol)
!= oechem.OEWriteMolReturnCode_Success
):
oechem.Fatal(
"Error writing molecule: {}".format(oechem.OEMolToSmiles(xfmmol))
)
else:
oechem.OESmilesToMol(
outxfmmol, "{}>>{}".format(insmi, oechem.OEMolToSmiles(xfmmol))
)
if xformname:
outxfmmol.SetTitle("{}:{}({})".format(nxforms, xformname, title))
else:
outxfmmol.SetTitle(title)
if (
oechem.OEWriteMolecule(ofs, outxfmmol)
!= oechem.OEWriteMolReturnCode_Success
):
oechem.Fatal(
"Error writing molecule: {}".format(
oechem.OEMolToSmiles(outxfmmol)
)
)
if not nxforms:
if all2output:
if (
oechem.OEWriteMolecule(ofs, mol)
!= oechem.OEWriteMolReturnCode_Success
):
oechem.Fatal(
"Error writing untransformed molecule: {}".format(oechem.OEMolToSmiles(xfmmol))
)
elif outfails:
if (
oechem.OEWriteMolecule(outfails, mol)
!= oechem.OEWriteMolReturnCode_Success
):
oechem.Fatal(
"Error writing untransformed molecule: {}".format(oechem.OEMolToSmiles(mol))
)
return 0
InterfaceData = """
!BRIEF -smirks SMIRKS -in <input> -out <output>
!CATEGORY I/O
!PARAMETER -smirks 1
!ALIAS -xform
!TYPE string
!REQUIRED true
!BRIEF Transformation SMIRKS
!KEYLESS 1
!END
!PARAMETER -in 2
!ALIAS -i
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 2
!END
!PARAMETER -out 3
!ALIAS -o
!ALIAS -success
!TYPE string
!REQUIRED true
!BRIEF Output file name
!KEYLESS 3
!END
!PARAMETER -noxform 4
!ALIAS -fails
!ALIAS -failures
!TYPE string
!REQUIRED false
!BRIEF Output file name for untransformed structures
!END
!END
!CATEGORY Options
!PARAMETER -strict 1
!ALIAS -strictsmirks
!TYPE bool
!REQUIRED false
!DEFAULT true
!BRIEF requested strict flag which controls the interpretation of the transformation SMIRKS (true:Daylight convention, false:OpenEye convention)
!END
!PARAMETER -clearcoords 2
!TYPE bool
!REQUIRED false
!DEFAULT true
!BRIEF whether to clear coordinates for transformed products
!END
!PARAMETER -validkek 3
!ALIAS -validkekule
!TYPE bool
!REQUIRED false
!DEFAULT true
!BRIEF whether the transformation validates the Kekule form of the transformed products
!END
!PARAMETER -fixval 4
!TYPE string
!REQUIRED false
!DEFAULT Explicit
!BRIEF type of valence correction to apply to the transformed products: Explicit(None), Altered, All
!END
!PARAMETER -max 5
!ALIAS -maxxforms
!TYPE int
!REQUIRED false
!DEFAULT 10
!BRIEF maximum number of transformation to apply to each processed molecule
!END
!PARAMETER -alteredtag 6
!TYPE string
!REQUIRED false
!DEFAULT None
!BRIEF A generic data tag to mark altered atom information from transformed products
!END
!PARAMETER -passfail 7
!TYPE bool
!REQUIRED false
!DEFAULT false
!BRIEF If true, include untransformed structures in -out
!END
!PARAMETER -asrxn 8
!TYPE bool
!REQUIRED false
!DEFAULT false
!BRIEF If true, output the transformation as a reaction
!END
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 55: Setting up an OE3DMolStyle on a molecule.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
for mol in ifs.GetOEMols():
molSty = oechem.OE3DMolStyle()
protCol = oechem.OEMolStyleColorer(oechem.OEAtomColorScheme_Residue)
atomCol = oechem.OEMolStyleColorer(oechem.OEAtomColorScheme_Element, oechem.OEWhite)
atomCol.AddColor(6, oechem.OEGreen)
atomCol.AddColor(7, oechem.OERed)
atomCol.AddColor(8, oechem.OEBlue)
molSty.SetAtomColorer(atomCol)
molSty.SetProteinColorer(protCol)
molSty.SetProteinStyle(oechem.OEProteinStyle_Ribbons)
molSty.SetAtomLabelType(oechem.OEAtomLabelScheme_Element)
molSty.SetAtomStyle(oechem.OEAtomStyle_BallAndStick)
molSty.SetHydrogenVisibility(oechem.OEHydrogenVisibility_Polar)
molSty.SetInteractionStyle(oechem.OEInteractionStyle_IntermolecularHBonds)
oechem.OESetStyle(mol, molSty)
if not oechem.OEHasStyle(mol):
oechem.OEThrow.Fatal("OE3DMolStyle was not applied to the OEMol")
oechem.OEWriteMolecule(ofs, mol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 56: OE3DMolStyle focused on B-Factor styling.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
for mol in ifs.GetOEMols():
molSty = oechem.OE3DMolStyle()
molCol = oechem.OEMolStyleColorer(oechem.OEAtomColorScheme_BFactor)
molSty.SetAtomColorer(molCol)
molSty.SetProteinColorer(molCol)
molSty.SetProteinStyle(oechem.OEProteinStyle_Ribbons)
molSty.SetAtomLabelType(oechem.OEAtomLabelScheme_BFactor)
oechem.OESetStyle(mol, molSty)
if not oechem.OEHasStyle(mol):
oechem.OEThrow.Fatal("OE3DMolStyle was not applied to the OEMol")
oechem.OEWriteMolecule(ofs, mol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 57: Generate canonical SMILES.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Generate canonical smiles of various flavors
#############################################################################
import sys
from openeye import oechem
#############################################################################
# To create unique Kekule smiles, must reperceive bond orders from
# scratch to avoid arbitrary non-deterministic variations, e.g.,
# CC1=C(O)C=CC=C1 vs. CC1=CC=CC=C1O
# This is why oechem.OESMILESFlag_Kekule is not sufficient and not used.
#############################################################################
def CanSmi(mol, isomeric, kekule):
oechem.OEFindRingAtomsAndBonds(mol)
oechem.OEAssignAromaticFlags(mol, oechem.OEAroModel_OpenEye)
smiflag = oechem.OESMILESFlag_Canonical
if isomeric:
smiflag |= oechem.OESMILESFlag_ISOMERIC
if kekule:
for bond in mol.GetBonds(oechem.OEIsAromaticBond()):
bond.SetIntType(5)
oechem.OECanonicalOrderAtoms(mol)
oechem.OECanonicalOrderBonds(mol)
oechem.OEClearAromaticFlags(mol)
oechem.OEKekulize(mol)
smi = oechem.OECreateSmiString(mol, smiflag)
return smi
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
isomeric = itf.GetBool("-isomeric")
kekule = itf.GetBool("-kekule")
from3d = itf.GetBool("-from3d")
if from3d:
isomeric = True
ifs = oechem.oemolistream()
ifile = itf.GetString("-i")
if not ifs.open(ifile):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifile)
if itf.HasString("-o"):
ofile = itf.GetString("-o")
try:
ofs = open(ofile, 'w')
except Exception:
oechem.OEThrow.Fatal("Unable to open %s for writing" % ofile)
else:
ofs = sys.stdout
mol = oechem.OEGraphMol()
while oechem.OEReadMolecule(ifs, mol):
if from3d:
oechem.OE3DToInternalStereo(mol)
smi = CanSmi(mol, isomeric, kekule)
if mol.GetTitle():
smi += (" %s" % mol.GetTitle())
ofs.write("%s\n" % smi)
InterfaceData = """\
!BRIEF [options] [-i] <input> [[-o] <output>]
!PARAMETER -i
!ALIAS -in
!TYPE string
!REQUIRED true
!BRIEF input file name
!KEYLESS 1
!END
!PARAMETER -o
!ALIAS -out
!TYPE string
!BRIEF output file name
!KEYLESS 2
!END
!PARAMETER -isomeric
!TYPE bool
!DEFAULT false
!BRIEF generate isomeric smiles
!END
!PARAMETER -from3d
!TYPE bool
!DEFAULT false
!BRIEF perceive stereo from 3D coords
!END
!PARAMETER -kekule
!TYPE bool
!DEFAULT false
!BRIEF generate kekule form
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 58: Concatenating molecules.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# This program concatenates molecules into one file.
# It can be useful for generating ROCS queries or reattach ligands to an
# protein structure
#############################################################################
import sys
from openeye import oechem
def CatMols(infnames, outfname):
omol = oechem.OEGraphMol()
for fname in infnames:
ifs = oechem.oemolistream()
if ifs.open(fname):
for imol in ifs.GetOEGraphMols():
oechem.OEAddMols(omol, imol)
else:
oechem.OEThrow.Fatal("Unable to open %s for reading" % fname)
ofs = oechem.oemolostream()
if not ofs.open(outfname):
oechem.OEThrow.Fatal("Unable to open %s for writing" % outfname)
oechem.OEWriteMolecule(ofs, omol)
Interface = """
!BRIEF -i <infile1> [<infile2>...] -o <outfile>
!PARAMETER -i
!ALIAS -in
!TYPE string
!LIST true
!REQUIRED true
!BRIEF input file name(s)
!END
!PARAMETER -o
!ALIAS -out
!TYPE string
!REQUIRED true
!BRIEF output file name
!END
"""
def main(argv=[__name__]):
itf = oechem.OEInterface(Interface, argv)
CatMols(itf.GetStringList("-i"), itf.GetString("-o"))
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 59: Creating an OECIFData Object.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
import os
from openeye import oechem
def main(argv=sys.argv):
if len(argv) != 2:
oechem.OEThrow.Usage("%s 5nev.cif" % argv[0])
filename = argv[1]
filebase = os.path.basename(filename)
filebase, extension = os.path.splitext(filebase)
if filebase.split(".")[0].upper() != "5NEV" or extension != ".cif":
oechem.OEThrow.Usage("%s must be the 5nev cif file" % argv[1])
ifs = oechem.oemolistream()
ifs.open(filename)
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
cifData = oechem.OECIFData(mol)
print(cifData.GetNumCategories()) # 81
cifCategory = cifData.GetCategory("_audit_conform.")
print(cifCategory.GetCategoryName()) # "_audit_conform."
# Getting Data
for attribute in cifData.GetAttributes("_audit_author."):
print(attribute) # name, pdbx_ordinal, identifier_ORCID
for attributeValue in cifData.GetAttributeValues("_audit_author.", "name"):
print(attributeValue) # Various author Names
print(cifData.GetAttributeValues("_audit_author.", "name")[0]) # Coxon, C.R.
print(cifData.GetAttributeValues("_audit_author.", "name", raw=True)[0]) # 'Coxon, C.R.'
# Setting, Adding and Deleting Data
# Pair Data
cifData.SetData("_pdbx_audit_revision_details.", "details", "No details")
cifData.AddData("_database_2.", "details")
# Loop Data
cifData.SetData("_entity_name_com.", "name", 0, "No Cell Division Protein Kinase 2,p33 protein kinase")
cifData.AddRow("_audit_author.", ["Doe J.", "19", "0000-0000-0867-5309"])
# Deleting a Category
cifData.DeleteCategory("_pdbx_poly_seq_scheme.")
print(cifData.GetNumCategories()) # 80
# Saving
oechem.OESetMMCIFData(mol, cifData)
# Modifying the Molecule
mol.SetTitle("mod5NEV")
for atom in mol.GetAtoms():
res = oechem.OEAtomGetResidue(atom)
if oechem.OEGetResidueIndex(res) == oechem.OEResidueIndex_HOH:
continue
if res.GetExtChainID() == "A" and res.GetEntityID() == "1":
res.SetExtChainID("Z")
res.SetSubChainID("Z")
res.SetEntityID("9")
oechem.OEAtomSetResidue(atom, res)
# Update header with molecule changes
copts = oechem.OECIFOptions()
copts.SetPerceiveEntity(True)
copts.SetPerceiveStruct(True)
cifData.Update(mol, copts)
print(cifData.GetAttributeValue("_entry.", "id")) # mod5NEV
struct_asym_id_idx = cifData.GetAttributeIndex("_struct_asym.", "id")
struct_asym_entity_id_idx = cifData.GetAttributeIndex("_struct_asym.", "entity_id")
struct_asym_row = cifData.GetRow("_struct_asym.", 9)
print(struct_asym_row[struct_asym_id_idx]) # "Z"
print(struct_asym_row[struct_asym_entity_id_idx]) # "9"
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 60: Align molecules by clique match.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Align two compounds based on the clique match
#############################################################################
import sys
from openeye import oechem
def CliqueAlign(refmol, fitmol, ofs):
cs = oechem.OECliqueSearch(refmol, oechem.OEExprOpts_DefaultAtoms,
oechem.OEExprOpts_DefaultBonds)
cs.SetSaveRange(5)
cs.SetMinAtoms(6)
for mi in cs.Match(fitmol):
rmat = oechem.OEDoubleArray(9)
trans = oechem.OEDoubleArray(3)
overlay = True
oechem.OERMSD(cs.GetPattern(), fitmol, mi, overlay, rmat, trans)
oechem.OERotate(fitmol, rmat)
oechem.OETranslate(fitmol, trans)
oechem.OEWriteMolecule(ofs, fitmol)
def main(argv=[__name__]):
if len(argv) != 4:
oechem.OEThrow.Usage("%s <refmol> <fitmol> <outfile>" % argv[0])
reffs = oechem.oemolistream()
if not reffs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
if not oechem.OEIs3DFormat(reffs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
refmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(reffs, refmol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % argv[1])
if not refmol.GetDimension() == 3:
oechem.OEThrow.Fatal("%s doesn't have 3D coordinates" % refmol.GetTitle())
fitfs = oechem.oemolistream()
if not fitfs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
if not oechem.OEIs3DFormat(fitfs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
if not oechem.OEIs3DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates")
oechem.OEWriteConstMolecule(ofs, refmol)
oechem.OESuppressHydrogens(refmol)
for fitmol in fitfs.GetOEGraphMols():
if not fitmol.GetDimension() == 3:
oechem.OEThrow.Warning("%s doesn't have 3D coordinates" % fitmol.GetTitle())
continue
CliqueAlign(refmol, fitmol, ofs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 61: Convert molecules.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Program to convert from one molecule format to another
#############################################################################
import sys
from openeye import oechem
def main(argv=sys.argv):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
for mol in ifs.GetOEMols():
oechem.OEWriteMolecule(ofs, mol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 62: Create 2D ring dictionary.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Creates a new 2D ring dictionary
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
ifname = itf.GetString("-in")
ofname = itf.GetString("-ringdict")
ifs = oechem.oemolistream()
if not ifs.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading!" % ifname)
if not oechem.OEIs2DFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input file format for 2D coordinates!")
ofs = oechem.oemolostream()
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open %s for writing!" % ofname)
if ofs.GetFormat() != oechem.OEFormat_OEB:
oechem.OEThrow.Fatal("Output file has to be OEB format!")
opts = oechem.OE2DRingDictionaryCreatorOptions()
opts.SetRetainExistingBuiltInTemplates(itf.GetBool('-retain-built-in'))
ringdict = oechem.OE2DRingDictionary(opts)
dots = oechem.OEDots(10000, 100, "molecules")
for mol in ifs.GetOEGraphMols():
dots.Update()
ringdict.AddRings(mol)
nrrings = ringdict.NumRings()
oechem.OEThrow.Info("%d ring template(s) have been extracted!" % nrrings)
if nrrings != 0:
oechem.OEWrite2DRingDictionary(ofname, ringdict)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = """
!BRIEF [-in] <input> [-ringdict] <output ringdict>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input 2D molecule filename
!END
!PARAMETER -ringdict
!ALIAS -rd
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output ring dictionary OEB filename
!END
!END
!CATEGORY "ring dictionary options :"
!PARAMETER -retain-built-in
!TYPE bool
!REQUIRED false
!DEFAULT false
!VISIBILITY simple
!BRIEF Ignore ring template if built-in exists
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 63: Adding CSV data as SD tags.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Merge a CSV file of data/properties, key on compound name in first column
# and use column titles as keys. All data is read/written as strings
#############################################################################
import sys
import csv
from openeye import oechem
def CSV2SDF(csvfile, ifs, ofs):
reader = csv.reader(csvfile, delimiter=',')
propnames = next(reader)
values = {}
for row in reader:
title = row[0]
if title == "":
oechem.OEThrow.Warning("Skipping entry with no title")
continue
value = row[1:]
values[title] = value
for mol in ifs.GetOEGraphMols():
if mol.GetTitle() in values:
count = 0
for v in values[mol.GetTitle()]:
count += 1
if v == "":
continue
else:
oechem.OESetSDData(mol, propnames[count], v)
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
if len(argv) != 4:
oechem.OEThrow.Usage("%s <csvfile> <infile> <outsdfile>" % argv[0])
try:
csvfile = open(argv[1])
except Exception:
oechem.OEThrow.Fatal("Unable to open %s csv for reading" % argv[1])
ifs = oechem.oemolistream()
if not ifs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
if ofs.GetFormat() not in [oechem.OEFormat_SDF, oechem.OEFormat_OEB]:
oechem.OEThrow.Fatal("Only works for sdf or oeb output files")
CSV2SDF(csvfile, ifs, ofs)
csvfile.close()
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 64: Print dots.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Show dots when piping example programs
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) < 3 or len(argv) > 4:
oechem.OEThrow.Usage("%s <infile> <outfile> [interval, default = 100]" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
dots = oechem.OEDots(100, 10, "molecules")
if len(argv) == 4:
i = int(argv[3])
dots.SetBigStep(i)
dots.SetSmallStep(i / 10)
for mol in ifs.GetOEMols():
oechem.OEWriteMolecule(ofs, mol)
dots.Update()
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 65: Extract 2D ring templates.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Extracts ring templates for 2D coordinate generation
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
ifname = itf.GetString("-in")
ofname = itf.GetString("-out")
ifs = oechem.oemolistream()
if not ifs.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifname)
if not oechem.OEIs2DFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 2D coordinates")
ofs = oechem.oemolostream()
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open %s for writing" % ofname)
if not oechem.OEIs2DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output format: unable to write 2D coordinates")
nrrings = 0
for mol in ifs.GetOEGraphMols():
for ring in oechem.OEExtractRingTemplates(mol):
nrrings += 1
oechem.OEWriteMolecule(ofs, ring)
oechem.OEThrow.Info("%d number of ring templates extracted" % nrrings)
InterfaceData = """
!BRIEF [-i] <input> [-o] <output>
!PARAMETER -i
!ALIAS -in
!TYPE string
!REQUIRED true
!BRIEF input file name
!KEYLESS 1
!END
!PARAMETER -o
!ALIAS -out
!TYPE string
!REQUIRED true
!BRIEF output file name
!KEYLESS 2
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 66: Extract molecule scaffolds.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Extract the ring scaffold of a molecule
#############################################################################
from openeye import oechem
try:
set()
except NameError:
from sets import Set as set
import sys
def TraverseForRing(visited, atom):
visited.add(atom.GetIdx())
for nbor in atom.GetAtoms():
if nbor.GetIdx() not in visited:
if nbor.IsInRing():
return True
if TraverseForRing(visited, nbor):
return True
return False
def DepthFirstSearchForRing(root, nbor):
visited = set()
visited.add(root.GetIdx())
return TraverseForRing(visited, nbor)
class IsInScaffold(oechem.OEUnaryAtomPred):
def __call__(self, atom):
if atom.IsInRing():
return True
count = 0
for nbor in atom.GetAtoms():
if DepthFirstSearchForRing(atom, nbor):
count += 1
return count > 1
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
exo_dbl_bonds = itf.GetBool("-exo")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-o"))
for src in ifs.GetOEMols():
dst = oechem.OEMol()
pred = IsInScaffold()
if exo_dbl_bonds:
pred = oechem.OEOrAtom(pred, oechem.OEIsNonRingAtomDoubleBondedToRing())
adjustHcount = True
oechem.OESubsetMol(dst, src, pred, adjustHcount)
if dst.IsValid():
oechem.OEWriteMolecule(ofs, dst)
InterfaceData = """
!BRIEF [-exo] [-i] <input> [-o] <scaffolds>
!PARAMETER -i
!ALIAS -in
!TYPE string
!REQUIRED true
!BRIEF input file name
!KEYLESS 1
!END
!PARAMETER -o
!ALIAS -out
!TYPE string
!REQUIRED true
!BRIEF output file name
!KEYLESS 2
!END
!PARAMETER -exo
!TYPE bool
!DEFAULT true
!BRIEF Exclude double bonds exo to ring in scaffold
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 67: Generate 2D coordinates with user-defined ring templates.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Generates 2D coordinates using user-defined ring templates
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
ifname = itf.GetString("-in")
ofname = itf.GetString("-out")
ifs = oechem.oemolistream()
if not ifs.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading!" % ifname)
ofs = oechem.oemolostream()
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open %s for writing!" % ofname)
if not oechem.OEIs2DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output file format for 2D coordinates!")
if itf.HasString("-ringdict"):
rdfname = itf.GetString("-ringdict")
if not oechem.OEIsValid2DRingDictionary(rdfname):
oechem.OEThrow.Warning("Invalid 2D ring dictionary file!")
else:
oechem.OEInit2DRingDictionary(rdfname)
for mol in ifs.GetOEGraphMols():
oechem.OEGenerate2DCoordinates(mol)
oechem.OEWriteMolecule(ofs, mol)
return 0
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = """
!BRIEF [-in] <input> [-out] <output> [-ringdict] <ringdict file>
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!KEYLESS 1
!VISIBILITY simple
!BRIEF Input filename
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED true
!KEYLESS 2
!VISIBILITY simple
!BRIEF Output filename
!END
!PARAMETER -ringdict
!ALIAS -rd
!TYPE string
!REQUIRED false
!VISIBILITY simple
!BRIEF Ring dictionary file
!DETAIL
2D ring dictionaries can be generated by the following OEChem examples:
C++ - createringdict.cpp
Python - createringdict.py
Java - CreateRingDict.java
C# - CreateRingDict.cs
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 68: Get molecule titles.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Output all molecule titles
#############################################################################
import sys
from openeye import oechem
def GenerateList(ifs, ofs):
for mol in ifs.GetOEMols():
title = mol.GetTitle()
if len(title) == 0:
title = "untitled"
ofs.write('%s\n' % title)
def main(argv=[__name__]):
if not (2 <= len(argv) <= 3):
oechem.OEThrow.Usage("%s <infile> [<outfile>]" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oeofstream()
if len(argv) == 3:
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
else:
ofs = sys.stdout
GenerateList(ifs, ofs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 69: Library generation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Perform library generation with SMIRKS
#############################################################################
import sys
from openeye import oechem
def LibGen(libgen, ofs, unique, isomeric):
smiflag = oechem.OESMILESFlag_DEFAULT # Canonical|AtomMaps|Rgroup
if isomeric:
smiflag |= oechem.OESMILESFlag_ISOMERIC
# access products
uniqproducts = []
for mol in libgen.GetProducts():
smiles = oechem.OECreateSmiString(mol, smiflag)
if not unique or smiles not in uniqproducts:
uniqproducts.append(smiles)
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
if not itf.HasString("-smirks") and not itf.HasString("-rxn"):
oechem.OEThrow.Fatal("Please provide SMIRKS string or MDL reaction file")
if itf.HasString("-smirks") and itf.HasString("-rxn"):
oechem.OEThrow.Fatal("Please provide only SMIRKS string or MDL reaction file")
reaction = oechem.OEQMol()
if itf.HasString("-smirks"):
smirks = itf.GetString("-smirks")
if not oechem.OEParseSmirks(reaction, smirks):
oechem.OEThrow.Fatal("Unable to parse SMIRKS: %s" % smirks)
else:
rxn = itf.GetString("-rxn")
rfile = oechem.oemolistream(rxn)
opt = oechem.OEMDLQueryOpts_ReactionQuery | oechem.OEMDLQueryOpts_SuppressExplicitH
if not oechem.OEReadMDLReactionQueryFile(rfile, reaction, opt):
oechem.OEThrow.Fatal("Unable to read reaction file: %s" % rxn)
relax = itf.GetBool("-relax")
unique = itf.GetBool("-unique")
implicitH = itf.GetBool("-implicitH")
valcorrect = itf.GetBool("-valence")
isomeric = itf.GetBool("-isomeric")
libgen = oechem.OELibraryGen()
if not libgen.Init(reaction, not relax):
oechem.OEThrow.Fatal("failed to initialize library generator")
libgen.SetValenceCorrection(valcorrect)
libgen.SetExplicitHydrogens(not implicitH)
libgen.SetClearCoordinates(True)
ofs = oechem.oemolostream(".smi")
if itf.HasString("-product"):
ofs.open(itf.GetString("-product"))
nrReacts = 0
while itf.HasString("-reactants", nrReacts):
fileName = itf.GetString("-reactants", nrReacts)
if nrReacts >= libgen.NumReactants():
oechem.OEThrow.Fatal("Number of reactant files exceeds number of \
reactants specified in reaction")
ifs = oechem.oemolistream()
if not ifs.open(fileName):
oechem.OEThrow.Fatal("Unable to read %s reactant file" % fileName)
for mol in ifs.GetOEGraphMols():
libgen.AddStartingMaterial(mol, nrReacts, unique)
nrReacts += 1
if nrReacts != libgen.NumReactants():
oechem.OEThrow.Fatal("Reactions requires %d reactant files!" % libgen.NumReactants())
LibGen(libgen, ofs, unique, isomeric)
InterfaceData = """
!BRIEF [options] [-smirks <string> | -rxn <rfile>] -reactants <infile> [-product <outfile>]
!CATEGORY "input/output options"
!PARAMETER -smirks
!ALIAS -s
!TYPE string
!VISIBILITY simple
!BRIEF SMIRKS reaction string
!END
!PARAMETER -rxn
!TYPE string
!VISIBILITY simple
!BRIEF MDL reaction file
!END
!PARAMETER -reactants
!ALIAS -r
!TYPE string
!LIST true
!REQUIRED true
!VISIBILITY simple
!BRIEF list of input reactant filenames
!END
!PARAMETER -product
!ALIAS -p
!TYPE string
!REQUIRED false
!VISIBILITY simple
!BRIEF output product filename
!END
!END
!CATEGORY "OELibraryGen options"
!PARAMETER -relax
!TYPE bool
!REQUIRED false
!DEFAULT false
!VISIBILITY simple
!BRIEF unmapped atoms on reactant side are not deleted during reaction
!END
!PARAMETER -implicitH
!TYPE bool
!REQUIRED false
!DEFAULT false
!VISIBILITY simple
!BRIEF reaction will be performed using implicit hydrogens
!END
!PARAMETER -valence
!TYPE bool
!REQUIRED false
!DEFAULT false
!VISIBILITY simple
!BRIEF automatic valence correction will be applied
!END
!END
!CATEGORY "product smiles generation options"
!PARAMETER -unique
!TYPE bool
!REQUIRED false
!DEFAULT false
!VISIBILITY simple
!BRIEF only unique product canonical smiles will be written
!END
!PARAMETER -isomeric
!TYPE bool
!REQUIRED false
!DEFAULT false
!VISIBILITY simple
!BRIEF include atom and bond stereochemistry in product smiles string
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 70: Generate database for fast substructure search.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Generates database for fast substructure search.
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line.")
ifname = itf.GetString("-in")
ofname = itf.GetString("-out")
stype = itf.GetString("-stype")
sort = itf.GetBool("-sort")
keeptitle = itf.GetBool("-keep-title")
nrthreads = itf.GetUnsignedInt("-nrthreads")
screentype = None
if stype == "Molecule":
screentype = oechem.OEGetSubSearchScreenType(oechem.OESubSearchScreenType_Molecule)
elif stype == "MDL":
screentype = oechem.OEGetSubSearchScreenType(oechem.OESubSearchScreenType_MDL)
elif stype == "SMARTS":
screentype = oechem.OEGetSubSearchScreenType(oechem.OESubSearchScreenType_SMARTS)
if screentype is None:
oechem.OEThrow.Fatal("stype %s is not supported" % stype)
opts = oechem.OECreateSubSearchDatabaseOptions(screentype)
opts.SetSortByBitCounts(sort)
opts.SetKeepTitle(keeptitle)
opts.SetNumProcessors(nrthreads)
screenstr = screentype.GetName()
infomsg = "Using %d processor(s) to generate database with '%s'"
oechem.OEThrow.Info(infomsg % (opts.GetNumProcessors(), screenstr))
tracer = oechem.OEConsoleProgressTracer()
if not oechem.OECreateSubSearchDatabaseFile(ofname, ifname, opts, tracer):
oechem.OEThrow.Fatal("Substructure search database can not be generated!")
return 0
#############################################################################
InterfaceData = """\
!BRIEF [options] -in <input> -out <output> -stype <screentype>
!CATEGORY "input/output options"
!PARAMETER -in 1
!ALIAS -i
!TYPE string
!REQUIRED true
!VISIBILITY simple
!BRIEF Input molecule filename
!END
!PARAMETER -out 2
!ALIAS -o
!TYPE string
!REQUIRED true
!VISIBILITY simple
!BRIEF Output substructure database filename
!END
!END
!CATEGORY "other options"
!PARAMETER -screentype
!ALIAS -stype
!TYPE string
!REQUIRED true
!LEGAL_VALUE Molecule
!LEGAL_VALUE MDL
!LEGAL_VALUE SMARTS
!BRIEF Screen type generated
!END
!PARAMETER -nrthreads
!TYPE unsigned
!DEFAULT 0
!BRIEF Number of processors used (zero means all available)
!DETAIL
!END
!PARAMETER -sort
!TYPE bool
!DEFAULT true
!BRIEF Whether to sort the molecules based on their screen bit counts.
!DETAIL
Generating sorted databases can be slower, but searching them will
be faster.
!END
!PARAMETER -keep-title
!TYPE bool
!DEFAULT true
!BRIEF Whether to keep the title of the molecule as unique identifier
!DETAIL
If false, then a 16 character long unique identifier will be generated
for each molecule as a new title.
!END
!END
"""
#############################################################################
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 71: Align molecules by maximum common substructure.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Align two compounds based on the maximum common substructure
#############################################################################
import sys
from openeye import oechem
def MCSAlign(refmol, fitmol, ofs):
atomexpr = oechem.OEExprOpts_AtomicNumber | oechem.OEExprOpts_Aromaticity
bondexpr = 0
mcss = oechem.OEMCSSearch(oechem.OEMCSType_Exhaustive)
mcss.Init(refmol, atomexpr, bondexpr)
mcss.SetMCSFunc(oechem.OEMCSMaxBondsCompleteCycles())
rmat = oechem.OEDoubleArray(9)
trans = oechem.OEDoubleArray(3)
unique = True
overlay = True
for match in mcss.Match(fitmol, unique):
rms = oechem.OERMSD(mcss.GetPattern(), fitmol, match, overlay, rmat, trans)
if rms < 0.0:
oechem.OEThrow.Warning("RMS overlay failure")
continue
oechem.OERotate(fitmol, rmat)
oechem.OETranslate(fitmol, trans)
oechem.OEWriteMolecule(ofs, fitmol)
def main(argv=[__name__]):
if len(argv) != 4:
oechem.OEThrow.Usage("%s <refmol> <fitmol> <outfile>" % argv[0])
reffs = oechem.oemolistream()
if not reffs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
if not oechem.OEIs3DFormat(reffs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
refmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(reffs, refmol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % argv[1])
if not refmol.GetDimension() == 3:
oechem.OEThrow.Fatal("%s doesn't have 3D coordinates" % refmol.GetTitle())
fitfs = oechem.oemolistream()
if not fitfs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
if not oechem.OEIs3DFormat(fitfs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
if not oechem.OEIs3DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates")
oechem.OEWriteConstMolecule(ofs, refmol)
oechem.OESuppressHydrogens(refmol)
for fitmol in fitfs.GetOEGraphMols():
if not fitmol.GetDimension() == 3:
oechem.OEThrow.Warning("%s doesn't have 3D coordinates" % fitmol.GetTitle())
continue
MCSAlign(refmol, fitmol, ofs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 72: Find minimum path in a molecule.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Find the minimum path length between 2 smarts patterns
# or the path length between 2 named atoms
#############################################################################
import sys
from openeye import oechem
def AtomPathLength(ifs, ofs, itf, atm1, atm2):
for mol in ifs.GetOEGraphMols():
oechem.OETriposAtomNames(mol)
a1 = None
a2 = None
for atm in mol.GetAtoms():
if atm.GetName() == atm1:
a1 = atm
if atm.GetName() == atm2:
a2 = atm
if a1 is not None and a2 is not None:
break
if a1 is None or a2 is None:
oechem.OEThrow.Warning("Failed to find atoms %s and %s in molecule" % (atm1, atm2))
continue
pathlen = oechem.OEGetPathLength(a1, a2)
if itf.GetBool("-verbose") or not itf.HasString("-o"):
print("Path length: %s in %s" % (pathlen, oechem.OEMolToSmiles(mol)))
spath = oechem.OEShortestPath(a1, a2)
spathmol = oechem.OEGraphMol()
adjustHCount = True
oechem.OESubsetMol(spathmol, mol, oechem.OEIsAtomMember(spath), adjustHCount)
spathsmiles = oechem.OEMolToSmiles(spathmol)
if itf.HasString("-o"):
oechem.OEWriteMolecule(ofs, spathmol)
elif itf.GetBool("-verbose"):
print(spathsmiles)
def SmartsPathLength(ifs, ofs, itf, ss1, ss2):
for mol in ifs.GetOEGraphMols():
oechem.OEPrepareSearch(mol, ss1)
oechem.OEPrepareSearch(mol, ss2)
if not (ss1.SingleMatch(mol) and ss2.SingleMatch(mol)):
oechem.OEThrow.Warning("Unable to find SMARTS matches in %s, skipping" % mol.GetTitle())
continue
unique = True
allminlen = sys.maxsize
for match1 in ss1.Match(mol, unique):
for match2 in ss2.Match(mol, unique):
minlen = sys.maxsize
for atom1 in match1.GetTargetAtoms():
for atom2 in match2.GetTargetAtoms():
pathlen = oechem.OEGetPathLength(atom1, atom2)
if minlen > pathlen:
minlen = pathlen
atompairs = []
atompairs.append([atom1, atom2])
elif minlen == pathlen:
atompairs.append([atom1, atom2])
if minlen < allminlen:
allminlen = minlen
allatompairs = atompairs[:]
elif minlen == allminlen:
allatompairs += atompairs[:]
if itf.GetBool("-verbose") or not itf.HasString("-o"):
print("Shortest path length: %s in %s" % (allminlen, oechem.OEMolToSmiles(mol)))
spathlist = set()
for satom1, satom2, in allatompairs:
spath = oechem.OEShortestPath(satom1, satom2)
spathmol = oechem.OEGraphMol()
oechem.OESubsetMol(spathmol, mol, oechem.OEIsAtomMember(spath))
spathsmiles = oechem.OEMolToSmiles(spathmol)
if spathsmiles in spathlist:
continue
spathlist.add(spathsmiles)
if itf.HasString("-o"):
oechem.OEWriteMolecule(ofs, spathmol)
elif itf.GetBool("-verbose"):
print(spathsmiles)
return
def main(argv=[__name__]):
itf = oechem.OEInterface(Interface, argv)
if not ((itf.HasString("-smarts1") and itf.HasString("-smarts2")) ^
(itf.HasString("-atom1") and itf.HasString("-atom2"))):
oechem.OEThrow.Fatal("-smarts1 and -smarts2 or -atom1 and -atom2 must be set")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" %
itf.GetString("-i").rstrip())
ofs = oechem.oemolostream()
if itf.HasString("-o"):
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-o"))
if itf.HasString("-smarts1") and itf.HasString("-smarts2"):
ss1 = oechem.OESubSearch()
smarts1 = itf.GetString("-smarts1")
if not ss1.Init(smarts1):
oechem.OEThrow.Fatal("Unable to parse SMARTS1: %s" % smarts1.rstrip())
ss2 = oechem.OESubSearch()
smarts2 = itf.GetString("-smarts2")
if not ss2.Init(smarts2):
oechem.OEThrow.Fatal("Unable to parse SMARTS2: %s" % smarts2.rstrip())
SmartsPathLength(ifs, ofs, itf, ss1, ss2)
else:
atom1 = itf.GetString("-atom1")
atom2 = itf.GetString("-atom2")
AtomPathLength(ifs, ofs, itf, atom1, atom2)
Interface = """
!BRIEF -i <input> [-o <output>] -smarts1 <smarts> -smarts2 <smarts> | -atom1 <name> -atom2 <name>
!PARAMETER -i
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 1
!END
!PARAMETER -o
!TYPE string
!REQUIRED false
!BRIEF Output file name
!KEYLESS 2
!END
!PARAMETER -smarts1
!TYPE string
!BRIEF Smarts pattern to identify 1st atom
!END
!PARAMETER -smarts2
!TYPE string
!BRIEF Smarts pattern to identify 2nd atom
!END
!PARAMETER -atom1
!TYPE string
!BRIEF Name of 1st atom
!END
!PARAMETER -atom2
!TYPE string
!BRIEF Name of 2nd atom
!END
!PARAMETER -verbose
!TYPE bool
!REQUIRED false
!DEFAULT false
!BRIEF Print verbose output
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 73: Split molecule file.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Split molecule file into N chunks or chunks of size N
#############################################################################
import os
import sys
from openeye import oechem
def NewOutputStream(outbase, ext, chunk):
newname = outbase + ('_%07d' % chunk) + ext
ofs = oechem.oemolostream()
if not ofs.open(newname):
oechem.OEThrow.Fatal("Unable to open %s for writing" % newname)
return ofs
def SplitNParts(ifs, nparts, countconfs, outbase, ext):
# first read entire file to determine number of molecules
molconfcount = 0
for mol in ifs.GetOEMols():
if countconfs:
molconfcount += mol.NumConfs()
else:
molconfcount += 1
ifs.rewind()
chunksize, lft = divmod(molconfcount, nparts)
if lft != 0:
chunksize += 1
chunk = 1
count = 0
ofs = NewOutputStream(outbase, ext, chunk)
for mol in ifs.GetOEMols():
if countconfs:
count += mol.NumConfs()
else:
count += 1
if count > chunksize:
if chunk == lft:
chunksize -= 1
ofs.close()
chunk += 1
count = 1
ofs = NewOutputStream(outbase, ext, chunk)
oechem.OEWriteMolecule(ofs, mol)
def SplitChunk(ifs, chunksize, countconfs, outbase, ext):
chunk = 1
ofs = NewOutputStream(outbase, ext, chunk)
count = 0
for mol in ifs.GetOEMols():
if count >= chunksize:
ofs.close()
count = 0
chunk += 1
ofs = NewOutputStream(outbase, ext, chunk)
if countconfs:
count += mol.NumConfs()
else:
count += 1
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
if not (itf.HasInt("-num") ^ itf.HasInt("-size")):
oechem.OEThrow.Fatal("Number of chunks (-num) or the size of each chunk "
"(-size) must be specified and are mutually exclusive.")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
if (ifs.GetFormat() != oechem.OEFormat_OEB):
ifs.SetConfTest(oechem.OEIsomericConfTest(False))
elif itf.GetBool("-rotcompress"):
oechem.OEPreserveRotCompress(ifs) # only for OEB
outbase, ext = os.path.splitext(itf.GetString("-o"))
if ext == '':
oechem.OEThrow.Fatal("Failed to find file extension")
if ext == '.gz':
outbase, ext = os.path.splitext(outbase)
ext = ext + '.gz'
countconfs = itf.GetBool("-confs")
if itf.HasInt("-num"):
nparts = itf.GetInt("-num")
SplitNParts(ifs, nparts, countconfs, outbase, ext)
else:
chunksize = itf.GetInt("-size")
SplitChunk(ifs, chunksize, countconfs, outbase, ext)
#############################################################################
InterfaceData = """\
!BRIEF -num|-size [-i] <input> [-o] <output>
!PARAMETER -i 1
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 1
!END
!PARAMETER -o 2
!TYPE string
!REQUIRED true
!BRIEF Output file name
!KEYLESS 2
!END
!PARAMETER -num 3
!TYPE int
!BRIEF The number of chunks
!END
!PARAMETER -size 4
!TYPE int
!BRIEF The size of each chunk
!END
!PARAMETER -confs 5
!TYPE bool
!DEFAULT true
!BRIEF Split by number of conformers not molecules
!END
!PARAMETER -rotcompress 6
!TYPE bool
!DEFAULT false
!BRIEF Preserve rotor compression
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 74: Counting molecules.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Counts molecule (and conformers) in input files
#############################################################################
import sys
from openeye import oechem
def PrintConfInfo(nconfs, nmols):
print("Total # of conformers: ", nconfs)
avg = 0
if nmols:
avg = float(nconfs) / nmols
print("Average # of conformers:", avg)
def MolCount(ifs, fname, conffrag):
nummols = 0
numconfs = 0
for mol in ifs.GetOEMols():
nummols += 1
if conffrag:
numconfs += mol.NumConfs()
print("%s contains %d molecule(s)." % (fname, nummols))
if conffrag:
PrintConfInfo(numconfs, nummols)
print("-----------------------------------------------------------")
return nummols, numconfs
def main(argv=[__name__]):
itf = oechem.OEInterface(Interface, argv)
conffrag = itf.GetBool("-conf")
confomega = itf.GetBool("-confomega")
totmols = 0
totconfs = 0
for fname in itf.GetStringList("-i"):
ifs = oechem.oemolistream()
if not ifs.open(fname):
oechem.OEThrow.Warning("Unable to open %s for reading" % fname)
continue
if confomega:
conffrag = True
ifs.SetConfTest(oechem.OEOmegaConfTest(False))
nummol, numconfs = MolCount(ifs, fname, conffrag)
totmols += nummol
totconfs += numconfs
print("===========================================================")
print("Total %d molecules" % totmols)
if conffrag:
PrintConfInfo(totconfs, totmols)
Interface = """
!BRIEF [-conf | -confomega] [-i] <infile1> [<infile2>...]
!PARAMETER -i
!ALIAS -in
!TYPE string
!LIST true
!REQUIRED true
!BRIEF Input file name(s)
!KEYLESS 1
!END
!PARAMETER -conf
!ALIAS -c
!TYPE bool
!DEFAULT false
!BRIEF Count conformers
!END
!PARAMETER -confomega
!TYPE bool
!DEFAULT false
!BRIEF Count Omega conformers
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 75: Extract molecules by title.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Extract compound(s) from a file based on molecule title
#############################################################################
import sys
try:
set()
except NameError:
from sets import Set as set
from openeye import oechem
def MolExtract(ifs, ofs, nameset):
for mol in ifs.GetOEMols():
title = mol.GetTitle()
if title in nameset:
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
haslist = itf.HasString("-list")
hastitle = itf.HasString("-title")
if not (haslist ^ hastitle):
oechem.OEThrow.Usage("Must give either -list or -title")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-o"))
# collect names
nameset = set()
if itf.HasString("-list"):
try:
lfs = open(itf.GetString("-list"))
except IOError:
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-list"))
for name in lfs.readlines():
name = name.strip()
nameset.add(name)
elif itf.HasString("-title"):
nameset.add(itf.GetString("-title"))
if len(nameset) == 0:
oechem.OEThrow.Fatal("No titles requested")
MolExtract(ifs, ofs, nameset)
InterfaceData = """\
!BRIEF -title title | -list <moltitles.file> [-i] <input> [-o] <output>
!PARAMETER -i
!ALIAS -in
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 1
!END
!PARAMETER -o
!ALIAS -out
!TYPE string
!REQUIRED true
!BRIEF Output file name
!KEYLESS 2
!END
!PARAMETER -title
!ALIAS -t
!TYPE string
!BRIEF Single mol title to extract
!END
!PARAMETER -list
!ALIAS -l
!TYPE string
!BRIEF List file of mol titles to extract
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 76: Perform substructure searches.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Perform substructure search on molecule file
#############################################################################
import sys
from openeye import oechem
def SubSearch(itf, ss, ifs, ofs):
reverseflag = itf.GetBool("-r")
countflag = itf.GetBool("-c")
count = 0
for mol in ifs.GetOEGraphMols():
oechem.OEPrepareSearch(mol, ss)
if ss.SingleMatch(mol) != reverseflag:
if countflag:
count += 1
else:
oechem.OEWriteMolecule(ofs, mol)
if countflag:
print("%d matching molecules\n" % (count), end=" ")
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
if not (itf.GetBool("-c") ^ itf.HasString("-o")):
oechem.OEThrow.Fatal("Counting (-c) or output (-o) must be \
specified and are mutually exclusive.")
ifs = oechem.oemolistream()
filename = itf.GetString("-i")
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % filename)
ofs = oechem.oemolostream()
if not itf.GetBool("-c"):
filename = itf.GetString("-o")
if not ofs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for writing" % filename)
smarts = itf.GetString("-p")
ss = oechem.OESubSearch()
if not ss.Init(smarts):
oechem.OEThrow.Fatal("Unable to parse SMARTS: %s" % smarts)
SubSearch(itf, ss, ifs, ofs)
InterfaceData = """
!BRIEF [-r][-c] -p smarts [-i] <input> [[-o] <output>]
!PARAMETER -i 1
!ALIAS -in
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 1
!END
!PARAMETER -p 2
!TYPE string
!REQUIRED true
!BRIEF SMARTS pattern, quote for safety
!END
!PARAMETER -o 3
!ALIAS -out
!TYPE string
!BRIEF Output file name
!KEYLESS 2
!END
!PARAMETER -r 4
!ALIAS -v
!TYPE bool
!DEFAULT false
!BRIEF Reverse logic, not matched
!END
!PARAMETER -c 5
!TYPE bool
!DEFAULT false
!BRIEF Just output count of number matched
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 77: Print simple molecule information.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Output some basic molecule properties
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
print("Title MolWt NumAtoms NumHeavyAtoms NumRingAtoms NumRotors NumConfs")
for mol in ifs.GetOEMols():
title = mol.GetTitle()
if not title:
title = "Untitled"
print("%s %.3f %d %d %d %d %d" % (title,
oechem.OECalculateMolecularWeight(mol),
mol.NumAtoms(),
oechem.OECount(mol, oechem.OEIsHeavy()),
oechem.OECount(mol, oechem.OEAtomIsInRing()),
oechem.OECount(mol, oechem.OEIsRotor()),
mol.NumConfs()))
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 78: Print OEChem and file format information.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Print toolkit release date platform and build information. Also print out
# all formats supported by OEChem and whether they are readable or writable
#############################################################################
import os
import sys
import openeye
from openeye import oechem
def GetYesNo(ok):
if ok:
return "yes"
return "no"
def PrintFormats():
print("code| ext | description |read? |write?")
print("----+---------------+------------------------------------------+------+------")
for numformat in range(1, oechem.OEFormat_MAXFORMAT):
extension = oechem.OEGetFormatExtension(numformat)
description = oechem.OEGetFormatString(numformat)
readable = GetYesNo(oechem.OEIsReadable(numformat))
writeable = GetYesNo(oechem.OEIsWriteable(numformat))
print(' %2d | %-13s | %-40s | %-4s | %-4s'
% (numformat, extension, description, readable, writeable))
print("----+---------------+------------------------------------------+------+------")
def ShowExamples():
parent = os.path.abspath(os.path.dirname(openeye.__file__))
print()
print("Examples:", os.path.join(parent, 'examples'))
print("Doc Examples:", os.path.join(parent, 'docexamples'))
print()
def main(argv=sys.argv):
print("Installed OEChem version: %s platform: %s built: %s release name: %s" %
(oechem.OEChemGetRelease(), oechem.OEChemGetPlatform(),
oechem.OEChemGetVersion(), oechem.OEToolkitsGetRelease()))
ShowExamples()
PrintFormats()
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 79: Define parameters.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
class MyOptions(oechem.OEOptions):
def __init__(self):
oechem.OEOptions.__init__(self, "MyOption")
param1 = oechem.OEDoubleParameter("-value", 10.0)
param1.AddLegalRange("20.0", "-20.0")
param1.SetBrief("Brief description of parameter value")
self.AddParameter(param1)
pass
def main(argv=[__name__]):
opts = MyOptions()
oechem.OEConfigureOpts(opts, argv, True)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 80: Splitting multicomponent molecules.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Writes each component of a molecule as a separate molecule
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % argv[0])
ifs = oechem.oemolistream()
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_Default ^ oechem.OEIFlavor_PDB_DATA)
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
for mol in ifs.GetOEGraphMols():
numparts, partlist = oechem.OEDetermineComponents(mol)
pred = oechem.OEPartPredAtom(partlist)
for i in range(1, numparts + 1):
pred.SelectPart(i)
partmol = oechem.OEGraphMol()
oechem.OESubsetMol(partmol, mol, pred)
oechem.OEWriteMolecule(ofs, partmol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 81: Print molecule atom names.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Print out atom names
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
for mol in ifs.GetOEMols():
oechem.OETriposAtomNames(mol)
for atm in mol.GetAtoms():
print(atm.GetName())
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 82: Randomize molecules of atom.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Demonstrates how to randomly reorder atoms and bonds of a molecule
#############################################################################
import sys
from openeye import oechem
def OrderMolecules(ifs, ofs):
for mol in ifs.GetOEGraphMols():
oechem.OEScrambleMolecule(mol)
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
OrderMolecules(ifs, ofs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 83: Extract random molecule subset.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Randomly reorder molecules and optionally obtain a random subset
#############################################################################
import sys
from random import Random
from openeye import oechem
def LoadDatabase(ifs, mlist, count):
for pos, mol in enumerate(ifs.GetOEMols()):
newmol = oechem.OEMol(mol, oechem.OEMCMolType_OEDBMCMol)
newmol.Compress()
mlist.append(newmol)
if pos + 1 == count:
break
def WriteDatabase(ofs, mlist, size):
for mol in mlist[:size]:
mol.UnCompress()
oechem.OEWriteMolecule(ofs, mol)
mol.Clear()
def RandomizePercent(ifs, ofs, percent, rand):
mlist = []
LoadDatabase(ifs, mlist, 0)
rand.shuffle(mlist)
size = len(mlist)
size = int(percent * 0.01 * size)
if size < 1:
size = 1
WriteDatabase(ofs, mlist, size)
def Randomize(ifs, ofs, rand):
wholedb = 100
RandomizePercent(ifs, ofs, wholedb, rand)
def RandomizeN(ifs, ofs, count, rand):
mlist = []
LoadDatabase(ifs, mlist, count)
for pos, mol in enumerate(ifs.GetOEMols()):
if float(count / float(count + pos + 1)) > rand.random():
idx = int(float(count) * rand.random())
newmol = oechem.OEMol(mol, oechem.OEMCMolType_OEDBMCMol)
newmol.Compress()
mlist[idx] = newmol
rand.shuffle(mlist)
WriteDatabase(ofs, mlist, count)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
if itf.HasFloat("-p") and itf.HasInt("-n"):
oechem.OEThrow.Usage("Give only one option, -p or -n")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
ofs = oechem.oemolostream(".ism")
if itf.HasString("-o"):
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-o"))
if itf.HasInt("-seed"):
rand = Random(itf.GetInt("-seed"))
else:
rand = Random()
if itf.HasInt("-n"):
RandomizeN(ifs, ofs, itf.GetInt("-n"), rand)
elif itf.HasFloat("-p"):
RandomizePercent(ifs, ofs, itf.GetFloat("-p"), rand)
else:
Randomize(ifs, ofs, rand)
InterfaceData = """
!BRIEF [-seed <int>] [-n <number>] [-p <percent>] [-i] <input> [-o] <output>
!PARAMETER -i
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 1
!END
!PARAMETER -o
!TYPE string
!REQUIRED false
!BRIEF Output file name
!KEYLESS 2
!END
!PARAMETER -p
!TYPE float
!REQUIRED false
!BRIEF Percentage of output molecules
!END
!PARAMETER -n
!TYPE int
!REQUIRED false
!BRIEF Number of output molecules
!END
!PARAMETER -seed
!TYPE int
!REQUIRED false
!BRIEF Integer value for random seed, default is system time
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 84: Extract rings.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#######################################################################
# Extracting rings/ring systems from input molecules
#######################################################################
import sys
from openeye import oechem
def RingSubSet(ifs, ofs, exo):
for mol in ifs.GetOEGraphMols():
submol = oechem.OEGraphMol()
adjustHcount = True
if exo:
isinring = oechem.OEAtomIsInRing()
isexo = oechem.OEIsNonRingAtomDoubleBondedToRing()
includeexo = oechem.OEOrAtom(isinring, isexo)
oechem.OESubsetMol(submol, mol, includeexo, adjustHcount)
else:
oechem.OESubsetMol(submol, mol, oechem.OEAtomIsInRing(), adjustHcount)
submol.SetTitle(mol.GetTitle() + "_rings")
if submol.NumAtoms() != 0:
oechem.OEWriteMolecule(ofs, submol)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
exo_dbl_bonds = itf.GetBool("-exo")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
ofs = oechem.oemolostream(".ism")
if itf.HasString("-o"):
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-o"))
RingSubSet(ifs, ofs, exo_dbl_bonds)
InterfaceData = """
!BRIEF [-exo] [-i] <infile> [[-o] <outfile>]
!PARAMETER -i
!ALIAS -in
!TYPE string
!REQUIRED true
!BRIEF input file name
!KEYLESS 1
!END
!PARAMETER -o
!ALIAS -out
!TYPE string
!REQUIRED false
!BRIEF output file name
!KEYLESS 2
!END
!PARAMETER -exo
!TYPE bool
!DEFAULT true
!BRIEF Include non-ring atoms double bonded to a ring
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 85: Align multiconformer molecules.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Performing RMSD calculation between a 3D reference molecule and
# multi-conformation molecules
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
if not itf.GetBool("-verbose"):
oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Warning)
rfname = itf.GetString("-ref")
ifname = itf.GetString("-in")
automorph = itf.GetBool("-automorph")
heavy = itf.GetBool("-heavyonly")
overlay = itf.GetBool("-overlay")
ifs = oechem.oemolistream()
if not ifs.open(rfname):
oechem.OEThrow.Fatal("Unable to open %s for reading" % rfname)
rmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, rmol):
oechem.OEThrow.Fatal("Unable to read reference molecule")
ifs = oechem.oemolistream()
if not ifs.open(ifname):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifname)
ofs = oechem.oemolostream()
if itf.HasString("-out"):
ofname = itf.GetString("-out")
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Unable to open %s for writing" % ofname)
if not overlay:
oechem.OEThrow.Warning("Output is the same as input when overlay is false")
for mol in ifs.GetOEMols():
oechem.OEThrow.Info(mol.GetTitle())
rmsds = oechem.OEDoubleArray(mol.GetMaxConfIdx())
rmtx = oechem.OEDoubleArray(9 * mol.GetMaxConfIdx())
tmtx = oechem.OEDoubleArray(3 * mol.GetMaxConfIdx())
# perform RMSD for all confomers
oechem.OERMSD(rmol, mol, rmsds, automorph, heavy, overlay, rmtx, tmtx)
for conf in mol.GetConfs():
cidx = conf.GetIdx()
oechem.OEThrow.Info("Conformer %i : rmsd = %f" % (cidx, rmsds[cidx]))
if itf.GetBool("-overlay"):
oechem.OERotate(conf, rmtx[cidx * 9: cidx * 9 + 9])
oechem.OETranslate(conf, tmtx[cidx * 3: cidx * 3 + 3])
if itf.HasString("-out"):
oechem.OEWriteMolecule(ofs, mol)
return 0
#############################################################################
InterfaceData = """\
!BRIEF [options] [-ref <mol file>] [-in <mol file>] [-out <mol file>]
!CATEGORY "input/output options"
!PARAMETER -ref
!TYPE string
!REQUIRED true
!BRIEF input reference mol file name
!KEYLESS 1
!END
!PARAMETER -in
!ALIAS -i
!TYPE string
!REQUIRED true
!BRIEF input mol file name
!KEYLESS 2
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!REQUIRED false
!BRIEF output file name, this implies that -overlay should be true
!KEYLESS 3
!END
!END
!CATEGORY "options"
!PARAMETER -automorph
!TYPE bool
!DEFAULT true
!BRIEF assign best atom association
!DETAIL
If false, atoms are associated by order.
If true, graph isomorphism is determined with symmetry perception.
!END
!PARAMETER -overlay
!TYPE bool
!DEFAULT true
!BRIEF Minimize to the smallest RMSD
!END
!PARAMETER -heavyonly
!TYPE bool
!DEFAULT true
!BRIEF Ignore hydrogens for RMSD calculation
!END
!PARAMETER -verbose
!ALIAS -v
!TYPE bool
!DEFAULT false
!BRIEF verbose
!END
!END
"""
#############################################################################
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 86: Print rotor count distribution.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Counts the number of rotatable bonds in the input compound file and
# outputs the maximum number of rotamers and the rotomer distribution
#############################################################################
import sys
from openeye import oechem
def CountRotors(ifs):
rotcounts = []
for mol in ifs.GetOEMols():
nrots = oechem.OECount(mol, oechem.OEIsRotor())
while nrots >= len(rotcounts):
rotcounts.append(0)
rotcounts[nrots] += 1
print("Max rotors:", len(rotcounts) - 1)
print("Rotorcount distribution:")
for rots, numrot in enumerate(rotcounts):
print("\t%d:\t%d" % (rots, numrot))
def main(argv=[__name__]):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
CountRotors(ifs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 87: Exporting SD data to a CSV file.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Extract properties from SD file and save as CSV
#############################################################################
import sys
from openeye import oechem
def SDF2CSV(ifs, csv):
taglist = []
# read through once to find all unique tags
for mol in ifs.GetOEGraphMols():
for dp in oechem.OEGetSDDataPairs(mol):
if dp.GetTag() not in taglist:
taglist.append(dp.GetTag())
ifs.rewind()
# print out column labels
header = "Title"
for tag in taglist:
header += ",%s" % tag
header += '\n'
csv.write(header)
# build csv file
for mol in ifs.GetOEGraphMols():
line = [mol.GetTitle()]
for tag in taglist:
if oechem.OEHasSDData(mol, tag):
value = oechem.OEGetSDData(mol, tag)
else:
value = ''
line.append(',')
line.append(value)
csv.write(''.join(line))
csv.write('\n')
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <csvfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
if ifs.GetFormat() not in [oechem.OEFormat_SDF, oechem.OEFormat_OEB]:
oechem.OEThrow.Fatal("Only works for sdf or oeb input files")
csv = oechem.oeofstream()
if not csv.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
SDF2CSV(ifs, csv)
if __name__ == '__main__':
sys.exit(main(sys.argv))
Listing 88: Filter molecules by SD data.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Filter molecules by SD data
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
if not (itf.HasDouble("-min") or itf.HasDouble("-max")):
oechem.OEThrow.Fatal("Please set a filter value with -min or -max")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
if not oechem.OEIsSDDataFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Only works for input file formats that support SD data (sdf,oeb,csv)")
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-i"))
if not oechem.OEIsSDDataFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Only works for output file formats that support SD data \
(sdf,oeb,csv)")
tag = itf.GetString("-tag")
minval = float("-inf")
if itf.HasDouble("-min"):
minval = itf.GetDouble("-min")
maxval = float("inf")
if itf.HasDouble("-max"):
maxval = itf.GetDouble("-max")
for mol in ifs.GetOEGraphMols():
if not oechem.OEHasSDData(mol, tag):
oechem.OEThrow.Warning(
"Unable to find %s tag on %s" % (tag, mol.GetTitle()))
continue
value = oechem.OEGetSDData(mol, tag)
try:
tagvalue = float(value)
except ValueError:
oechem.OEThrow.Warning("Failed to convert (%s) to a number in %s" %
(value, mol.GetTitle()))
continue
if tagvalue < minval:
continue
if tagvalue > maxval:
continue
oechem.OEWriteMolecule(ofs, mol)
InterfaceData = """
!BRIEF -i <input> -o <output> -tag <name> [-min <num>] [-max <num>]
!PARAMETER -i
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 1
!END
!PARAMETER -o
!TYPE string
!REQUIRED true
!BRIEF Output file name
!KEYLESS 2
!END
!PARAMETER -tag
!TYPE string
!REQUIRED true
!BRIEF SD tag
!END
!PARAMETER -min
!TYPE double
!REQUIRED false
!BRIEF minimum value of SD tag
!END
!PARAMETER -max
!TYPE double
!REQUIRED false
!BRIEF maximum value of SD tag
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 89: Modifying SD tags.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Modifies the SD data of a set of input molecules by clearing all tags,
# defining which tags to keep or defining which tags to remove
#############################################################################
import sys
from openeye import oechem
def ClearProps(ifs, ofs):
for mol in ifs.GetOEGraphMols():
oechem.OEClearSDData(mol)
oechem.OEWriteMolecule(ofs, mol)
def KeepProps(proplist, ifs, ofs):
for mol in ifs.GetOEGraphMols():
for dp in oechem.OEGetSDDataPairs(mol):
if dp.GetTag() not in proplist:
oechem.OEDeleteSDData(mol, dp.GetTag())
oechem.OEWriteMolecule(ofs, mol)
def RemoveProps(proplist, ifs, ofs):
for mol in ifs.GetOEGraphMols():
for tag in proplist:
oechem.OEDeleteSDData(mol, tag)
oechem.OEWriteMolecule(ofs, mol)
def ModProps(itf, ifs, ofs):
proplist = []
if itf.HasString("-keep"):
for prop in itf.GetStringList("-keep"):
proplist.append(prop)
KeepProps(proplist, ifs, ofs)
elif itf.HasString("-remove"):
for prop in itf.GetStringList("-remove"):
proplist.append(prop)
RemoveProps(proplist, ifs, ofs)
elif itf.GetBool("-clearAll"):
ClearProps(ifs, ofs)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
haskeep = itf.HasString("-keep")
hasremove = itf.HasString("-remove")
hasclear = itf.GetBool("-clearAll")
numoption = 0
for hasoption in [haskeep, hasremove, hasclear]:
if hasoption:
numoption += 1
if numoption != 1:
oechem.OEThrow.Usage("Need to pick one from -keep, -remove, or -clearAll")
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
if not oechem.OEIsSDDataFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Only works for input file formats that support SD data (sdf,oeb,csv)")
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-o"))
if not oechem.OEIsSDDataFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Only works for output file formats that support SD data \
(sdf,oeb,csv)")
ModProps(itf, ifs, ofs)
InterfaceData = """
!BRIEF [-remove] <prop1 prop2...> [-keep] <prop1 prop2...> [-clearAll] -i <input> -o <output>
!PARAMETER -i
!ALIAS -in
!TYPE string
!REQUIRED true
!BRIEF Input file name
!END
!PARAMETER -o
!ALIAS -out
!TYPE string
!REQUIRED true
!BRIEF Output file name
!END
!PARAMETER -keep
!ALIAS -k
!TYPE string
!LIST true
!BRIEF SD tags to be kept
!END
!PARAMETER -remove
!ALIAS -r
!TYPE string
!LIST true
!BRIEF SD tags to be removed
!END
!PARAMETER -clearAll
!ALIAS -c
!TYPE bool
!DEFAULT false
!BRIEF Removes all SD tags
!END
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 90: Renaming molecules by SD field.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Rename SDF molecules by specified field
#############################################################################
import sys
from openeye import oechem
def Rename(ifs, ofs, fieldname):
for mol in ifs.GetOEGraphMols():
if oechem.OEHasSDData(mol, fieldname):
mol.SetTitle(oechem.OEGetSDData(mol, fieldname))
else:
title = mol.GetTitle()
oechem.OEThrow.Warning("Renaming of molecule %s failed; no field %s" %
(title, fieldname))
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
if len(argv) != 4:
oechem.OEThrow.Usage("%s <fieldname> <infile> <outfile>" % argv[0])
fieldname = argv[1]
ifs = oechem.oemolistream()
if not ifs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
if not oechem.OEIsSDDataFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Only works for input file formats that support SD data (sdf,oeb,csv)")
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
Rename(ifs, ofs, fieldname)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 91: Perform SMARTS search on substructure database file.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Performs SMARTS search on substructure database file
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line.")
# check parameters
c = itf.GetBool("-count")
t = itf.GetBool("-titles")
o = itf.HasString("-out")
if not((c and not t and not o) or (not c and t and not o) or (not c and not t and o)):
oechem.OEThrow.Fatal("Counting (-c) or outputting titles (-t) or molecules (-o) "
"must be specified and are mutually exclusive.")
ofs = oechem.oemolostream()
if itf.HasString("-out"):
ofname = itf.GetString("-out")
if not ofs.open(ofname):
oechem.OEThrow.Fatal("Cannot open output file!")
dbfname = itf.GetString("-db")
smarts = itf.GetString("-smarts")
nrthreads = itf.GetUnsignedInt("-nrthreads")
maxmatches = itf.GetUnsignedInt("-maxmatches")
# initialize query
qmol = oechem.OEQMol()
if not oechem.OEParseSmarts(qmol, smarts):
oechem.OEThrow.Fatal("Unable to parse SMARTS pattern: %s" % smarts)
# initialize substructure search database
screentype = oechem.OEGetSubSearchScreenType(oechem.OESubSearchScreenType_SMARTS)
if not oechem.OEIsValidSubSearchDatabase(dbfname, screentype):
oechem.OEThrow.Fatal("Invalid SMARTS substructure search database file!")
ssdb = oechem.OESubSearchDatabase(oechem.OESubSearchDatabaseType_Default, nrthreads)
tracer = oechem.OEConsoleProgressTracer()
if not ssdb.Open(dbfname, tracer):
oechem.OEThrow.Fatal("Substructure search database can not be initialized!")
screenstr = screentype.GetName()
infomsg = "Using %d processor(s) to search database with '%s'"
oechem.OEThrow.Info(infomsg % (ssdb.NumProcessors(), screenstr))
# search database
if itf.GetBool("-count"):
oechem.OEThrow.Info("Number of hits: %d" % ssdb.NumMatches(qmol))
else:
query = oechem.OESubSearchQuery(qmol, maxmatches)
result = oechem.OESubSearchResult()
status = ssdb.Search(result, query)
print("Search status = ", oechem.OESubSearchStatusToName(status))
print("Number of targets = ", result.NumTargets())
print("Number of screened = ", result.NumScreened())
print("Number of searched = ", result.NumSearched())
print("Number of total matches = ", result.NumTotalMatches())
print("Number of kept matches = ", result.NumMatches())
if itf.GetBool("-titles"):
print("Matches:")
for index in result.GetMatchIndices():
print(ssdb.GetTitle(index))
elif itf.HasString("-out"):
mol = oechem.OEGraphMol()
for index in result.GetMatchIndices():
if ssdb.GetMolecule(mol, index):
oechem.OEWriteMolecule(ofs, mol)
return 0
#############################################################################
InterfaceData = """\
!BRIEF [options] -db <database> -s <smarts> -nrthreads <unsigned int>
!CATEGORY "input/output options"
!PARAMETER -database 1
!ALIAS -db
!TYPE string
!REQUIRED true
!VISIBILITY simple
!BRIEF Input substructure search database filename
!END
!PARAMETER -smarts 2
!ALIAS -s
!TYPE string
!REQUIRED true
!BRIEF SMARTS pattern, quote for safety
!END
!END
!CATEGORY "search types"
!PARAMETER -count
!ALIAS -c
!TYPE bool
!DEFAULT false
!BRIEF Output count of number matched
!END
!PARAMETER -titles
!ALIAS -t
!TYPE bool
!DEFAULT false
!BRIEF Output title of matches
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!BRIEF Output molecule filename of matches
!END
!END
!CATEGORY "other options"
!PARAMETER -nrthreads
!TYPE unsigned
!REQUIRED true
!DEFAULT 1
!BRIEF Number of processors used (zero means all available)
!END
!PARAMETER -maxmatches
!ALIAS -max
!TYPE unsigned
!DEFAULT 1000
!BRIEF The maximum number of matches returned in case of parameters (-titles) and (-out)
!END
!END
"""
#############################################################################
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 92: Setting mmCIF Chemical Component Header.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Simple superimposition of a fit protein on to a reference protein
#############################################################################
import sys
import os
from openeye import oechem
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage(f"{argv[0]} <input CIF> <reference cif oeb> <output CIF>") # noqa
file1 = os.path.basename(argv[1])
_, ext1 = os.path.splitext(argv[1])
if ext1 != '.cif':
oechem.OEThrow.Usage(f"Input file {argv[1]} should be a CIF file.")
file2 = os.path.basename(argv[2])
_, ext3 = os.path.splitext(argv[3])
if ext3 != '.cif':
oechem.OEThrow.Usage(f"Output file {argv[3]} should be a CIF file.")
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
mol = oechem.OEMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % argv[1])
ifs = oechem.oemolistream()
if not ifs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
rmol = oechem.OEMol()
if not oechem.OEReadMolecule(ifs, rmol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % argv[2])
if not oechem.OEHasResidues(mol) or not oechem.OEHasResidues(rmol):
oechem.OEThrow.Fatal("Input molecule(s) do not contain any residues.")
cifData = oechem.OECIFData(mol)
opts = oechem.OECIFOptions()
opts.SetPerceiveChemComp(True)
if not cifData.Update(mol, opts):
oechem.OEThrow.Warning("Molecule missing header information and could not update.")
if not cifData.SetMMCIFChemCompData(mol, rmol, False):
oechem.OEThrow.Fatal(f"Could not apply reference molecule {file2} to _chem_comp header in {file1}.")
oechem.OESetMMCIFData(mol, cifData)
ofs = oechem.oemolostream(argv[3])
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
oechem.OEWriteMolecule(ofs, mol)
ofs.close()
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 93: Filter molecules by weight or heavy atom count.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Filter out molecules by their molecular weight or heavy atom count
#############################################################################
import sys
from openeye import oechem
def IsBetween(min, max, val):
if min <= val <= max:
return True
return False
def IsMoleculeInHeavyAtomCountRange(min, max, mol):
count = oechem.OECount(mol, oechem.OEIsHeavy())
return IsBetween(min, max, count)
def IsMoleculeInMolWtRange(min, max, mol):
molwt = oechem.OECalculateMolecularWeight(mol)
return IsBetween(min, max, molwt)
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData, argv)
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-i")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-i"))
ofs = oechem.oemolostream(".ism")
if itf.HasString("-o"):
if not ofs.open(itf.GetString("-o")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-o"))
minhac = float("-inf")
if itf.HasInt("-minhac"):
minhac = itf.GetInt("-minhac")
maxhac = float("inf")
if itf.HasInt("-maxhac"):
maxhac = itf.GetInt("-maxhac")
minwt = float("-inf")
if itf.HasDouble("-minwt"):
minwt = itf.GetDouble("-minwt")
maxwt = float("inf")
if itf.HasDouble("-maxwt"):
maxwt = itf.GetDouble("-maxwt")
for mol in ifs.GetOEMols():
if not IsMoleculeInHeavyAtomCountRange(minhac, maxhac, mol):
continue
if not IsMoleculeInMolWtRange(minwt, maxwt, mol):
continue
oechem.OEWriteMolecule(ofs, mol)
InterfaceData = """
!BRIEF [-minhac <num>] [-maxhac <num>] [-minwt <num>] [-maxwt <num>] [-i] <input> [[-o] <output>]
!PARAMETER -i
!TYPE string
!REQUIRED true
!BRIEF Input file name
!KEYLESS 1
!END
!PARAMETER -o
!TYPE string
!REQUIRED false
!BRIEF Output file name
!KEYLESS 2
!END
!PARAMETER -minhac
!TYPE int
!REQUIRED false
!BRIEF minimum heavy atom count
!END
!PARAMETER -maxhac
!TYPE int
!REQUIRED false
!BRIEF maximum heavy atom count
!END
!PARAMETER -minwt
!TYPE double
!REQUIRED false
!BRIEF minimum molecular weight
!END
!PARAMETER -maxwt
!TYPE double
!REQUIRED false
!BRIEF maximum molecular weight
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 94: Align molecules by SMARTS match.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Align two compounds based on smarts match
#############################################################################
import sys
from openeye import oechem
def SmartsAlign(refmol, fitmol, ss, ofs):
unique = True
for match1 in ss.Match(refmol, unique):
for match2 in ss.Match(fitmol, unique):
match = oechem.OEMatch()
for mp1, mp2 in zip(match1.GetAtoms(), match2.GetAtoms()):
match.AddPair(mp1.target, mp2.target)
overlay = True
rmat = oechem.OEDoubleArray(9)
trans = oechem.OEDoubleArray(3)
oechem.OERMSD(refmol, fitmol, match, overlay, rmat, trans)
oechem.OERotate(fitmol, rmat)
oechem.OETranslate(fitmol, trans)
oechem.OEWriteConstMolecule(ofs, fitmol)
def main(argv=[__name__]):
if len(argv) != 5:
oechem.OEThrow.Usage("%s <refmol> <fitmol> <outfile> <smarts>" % argv[0])
reffs = oechem.oemolistream()
if not reffs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
if not oechem.OEIs3DFormat(reffs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
refmol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(reffs, refmol):
oechem.OEThrow.Fatal("Unable to read molecule in %s" % argv[1])
if not refmol.GetDimension() == 3:
oechem.OEThrow.Fatal("%s doesn't have 3D coordinates" % refmol.GetTitle())
fitfs = oechem.oemolistream()
if not fitfs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
if not oechem.OEIs3DFormat(fitfs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
if not oechem.OEIs3DFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Invalid output format: need 3D coordinates")
oechem.OEWriteConstMolecule(ofs, refmol)
ss = oechem.OESubSearch()
if not ss.Init(argv[4]):
oechem.OEThrow.Fatal("Unable to parse SMARTS: %s" % argv[4])
oechem.OEPrepareSearch(refmol, ss)
if not ss.SingleMatch(refmol):
oechem.OEThrow.Fatal("SMARTS fails to match refmol")
for fitmol in fitfs.GetOEGraphMols():
if not fitmol.GetDimension() == 3:
oechem.OEThrow.Warning("%s doesn't have 3D coordinates" % fitmol.GetTitle())
continue
oechem.OEPrepareSearch(fitmol, ss)
if not ss.SingleMatch(fitmol):
oechem.OEThrow.Warning("SMARTS fails to match fitmol %s" % fitmol.GetTitle())
continue
SmartsAlign(refmol, fitmol, ss, ofs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 95: Strip salts.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Remove salts and/or remove all but the largest molecule
#############################################################################
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
for mol in ifs.GetOEMols():
oechem.OEDeleteEverythingExceptTheFirstLargestComponent(mol)
oechem.OEWriteMolecule(ofs, mol)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 96: OE3DMolStyle hierarchy between molecule, conformers, and atoms.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
for mol in ifs.GetOEMols():
mol.NewConf(mol)
mol.NewConf(mol)
molSty = oechem.OE3DMolStyle()
molSty.SetAtomStyle(oechem.OEAtomStyle_Wireframe)
molSty.SetAtomColorer(oechem.OEMolStyleColorer(oechem.OEBlue))
molSty.SetSurfaceColorer(oechem.OEMolStyleColorer(oechem.OEYellow))
molSty.SetHydrogenVisibility(oechem.OEHydrogenVisibility_Off)
molSty.SetSurfaceType(oechem.OESurfaceType_Molecular)
confSty = oechem.OE3DMolStyle()
confSty.SetAtomStyle(oechem.OEAtomStyle_CPK)
confSty.SetHydrogenVisibility(oechem.OEHydrogenVisibility_Polar)
atomSty = oechem.OE3DMolStyle()
atomSty.SetAtomStyle(oechem.OEAtomStyle_Stick)
atomSty.SetAtomColorer(oechem.OEMolStyleColorer(oechem.OEWhite))
atomSty.SetSurfaceType(oechem.OESurfaceType_Off)
atomSty2 = oechem.OE3DMolStyle()
atomSty2.SetAtomColorer(oechem.OEMolStyleColorer(oechem.OEPink))
oechem.OESetStyle(mol, molSty)
molConf1 = mol.GetConf(oechem.OEHasConfIdx(0))
oechem.OESetStyle(molConf1, confSty)
molAtom1 = mol.GetAtom(oechem.OEHasAtomIdx(0))
oechem.OESetStyle(molAtom1, atomSty)
molAtom2 = mol.GetAtom(oechem.OEHasAtomIdx(1))
oechem.OESetStyle(molAtom2, atomSty2)
if not oechem.OEHasStyle(mol):
oechem.OEThrow.Fatal("OE3DMolStyle was not applied to the OEMol")
oechem.OEWriteMolecule(ofs, mol)
# for conf in mol.GetConfs():
# tempConfSty = oechem.OE3DMolStyle()
# tempConfSty = oechem.OEGetStyle(conf)
# print(tempConfSty.GetString())
# for atom in mol.GetAtoms():
# tempAtomSty = oechem.OE3DMolStyle()
# tempAtomSty = oechem.OEGetStyle(atom)
# print(tempAtomSty.GetString())
# tempMolSty = oechem.OE3DMolStyle()
# tempMolSty = oechem.OEGetStyle(mol)
# print(tempMolSty.GetString())
if __name__ == "__main__":
sys.exit(main(sys.argv))
#This is a complicated example of adding multiple OE3DMolStyles to the connfomer, atoms, and molecule
#The mol will have a style that includes: Wireframe, blue, yellow molecular surface, no hydrogens
#The first conf will have a style that indludes: CPK, blue, yellow molecular surface, polar hydrogens
#The second conf will have the same style of the mol
#The first atom on the first conf will have a style that includes: Stick, white, no surface, polar hydrogens
#The first atom on the second conf will have a style that includes: Stick, white, no surface, no hydrogens
#The second atom on the first conf will have a style that includes: CPK, pink, blue molecular surface, polar H
#This shows the hierarchy of how the stle moves from mol to conf to atom
#The top level is always the mol, but the style in a conf will take priority
#The atom will have the style from the mol and conf, but if a OE3DMolStyle is added to an atom then it will take priority
Listing 97: Performing a reaction.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Perform reactions on the given compounds
#############################################################################
import sys
from openeye import oechem
def UniMolRxn(ifs, ofs, umr):
for mol in ifs.GetOEGraphMols():
if umr(mol):
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
if not (3 <= len(argv) <= 4):
oechem.OEThrow.Usage("%s SMIRKS <infile> [<outfile>]" % argv[0])
qmol = oechem.OEQMol()
if not oechem.OEParseSmirks(qmol, argv[1]):
oechem.OEThrow.Fatal("Unable to parse SMIRKS: %s" % argv[1])
umr = oechem.OEUniMolecularRxn()
if not umr.Init(qmol):
oechem.OEThrow.Fatal("Failed to initialize reaction with %s SMIRKS" % argv[1])
umr.SetClearCoordinates(True)
ifs = oechem.oemolistream()
if not ifs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
ofs = oechem.oemolostream(".ism")
if len(argv) == 4:
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
UniMolRxn(ifs, ofs, umr)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 98: Write out unique molecules (InChi).
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Read molecules and write out the unique ones. Two molecules are considered
# identical if their InChIs are identical.
#############################################################################
import sys
from openeye import oechem
def UniqInChI(ifs, ofs):
inchis = {}
for mol in ifs.GetOEMols():
inchi = oechem.OECreateInChI(mol)
if inchi not in inchis:
inchis[inchi] = True
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
UniqInChI(ifs, ofs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 99: Write out unique molecules (canonical SMILES).
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Read molecules and write out the unique ones. Two molecules are considered
# identical if their canonical isomeric smiles are identical.
#############################################################################
import sys
from openeye import oechem
def UniqMol(ifs, ofs):
smiles = {}
for mol in ifs.GetOEMols():
smi = oechem.OEMolToSmiles(mol)
if smi not in smiles:
smiles[smi] = True
oechem.OEWriteMolecule(ofs, mol)
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <infile> <outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
UniqMol(ifs, ofs)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Omega Toolkit
These selected examples illustrate use of the Omega toolkit, which generates conformations of molecules. For a guide to programming examples, see the Omega chapter.
Listing 1: Example of adding a new torsion rule.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeomega
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <outfile>" % sys.argv[0])
mol = oechem.OEMol()
oechem.OESmilesToMol(mol, "O=COC")
ofs = oechem.oemolostream()
if not ofs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % sys.argv[1])
omegaOpts = oeomega.OEOmegaOptions()
omega = oeomega.OEOmega(omegaOpts)
torlib = oeomega.OETorLib()
# Adding the torsion rule "[O:1]=[C:2]-[O:3][CH3:4] 90" as a string
# This takes precedent over previous rule
rule = "[O:1]=[C:2]-[O:3][CH3:4] 90"
if not torlib.AddTorsionRule(rule):
oechem.OEThrow.Fatal("Failed to add torsion rule: %s" % rule)
omegaOpts.SetTorLib(torlib)
omega.SetOptions(omegaOpts)
if omega(mol):
oechem.OEWriteMolecule(ofs, mol)
# Adding torsion rule "[O:1]=[C:2]-[O:3][CH3:4] 45" as a query
# molecule. This takes precedent over default rule
qmol = oechem.OEQMol()
oechem.OEParseSmarts(qmol, "[O:1]=[C:2]-[O:3][CH3:4]")
degrees = oechem.OEIntVector([45])
if not torlib.AddTorsionRule(qmol, degrees):
oechem.OEThrow.Fatal("Failed to add torsion rule")
omegaOpts.SetTorLib(torlib)
omega.SetOptions(omegaOpts)
if omega(mol):
oechem.OEWriteMolecule(ofs, mol)
Listing 2: Example of turning off GPU-Omega and changing parameters.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oeff
from openeye import oeomega
mol = oechem.OEMol()
oechem.OESmilesToMol(mol, "C1CCCCC1N(=O)CCS")
omegaOpts = oeomega.OEOmegaOptions()
omegaOpts.GetTorDriveOptions().SetUseGPU(False)
omega = oeomega.OEOmega(omegaOpts)
omega(mol)
omegaOpts = oeomega.OEOmegaOptions(oeomega.OEOmegaSampling_Dense)
if oeomega.OEOmegaIsGPUReady():
omegaOpts.GetTorDriveOptions().SetForceField(oeff.OEMMFFSheffieldFFType_MMFF94Smod_NOESTAT)
omegaOpts.GetMolBuilderOptions().SetSampleHydrogens(False)
omega = oeomega.OEOmega(omegaOpts)
omega(mol)
Quacpac Toolkit
These selected examples illustrate use of the Quacpac toolkit, which includes pKa and tautomer enumeration in order to get correct protonation states, partial charges using multiple models that cover a range of speed and accuracy, and electrostatic potential map construction and storage. For a guide to programming examples, see the Quacpac chapter.
Listing 1: Assigning partial charges.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oequacpac
def AssignChargesByName(mol, name):
if name == "noop":
return oequacpac.OEAssignCharges(mol, oequacpac.OEChargeEngineNoOp())
elif name == "mmff" or name == "mmff94":
return oequacpac.OEAssignCharges(mol, oequacpac.OEMMFF94Charges())
elif name == "am1bcc":
return oequacpac.OEAssignCharges(mol, oequacpac.OEAM1BCCCharges())
elif name == "am1bccnosymspt":
optimize = True
symmetrize = True
return oequacpac.OEAssignCharges(mol,
oequacpac.OEAM1BCCCharges(not optimize, not symmetrize))
elif name == "amber" or name == "amberff94":
return oequacpac.OEAssignCharges(mol, oequacpac.OEAmberFF94Charges())
elif name == "am1bccelf10":
return oequacpac.OEAssignCharges(mol, oequacpac.OEAM1BCCELF10Charges())
return False
def main(argv=[__name__]):
itf = oechem.OEInterface(InterfaceData)
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to interpret command line!")
ifs = oechem.oemolistream()
inputFile = itf.GetString("-in")
if not ifs.open(inputFile):
oechem.OEThrow.Fatal("Unable to open %s for reading" % inputFile)
ofs = oechem.oemolostream()
outFile = itf.GetString("-out")
if not ofs.open(outFile):
oechem.OEThrow.Fatal("Unable to open %s for writing" % outFile)
chargeName = itf.GetString("-method")
mol = oechem.OEMol()
while oechem.OEReadMolecule(ifs, mol):
if not AssignChargesByName(mol, chargeName):
oechem.OEThrow.Warning("Unable to assign %s charges to mol %s"
% (chargeName, mol.GetTitle()))
oechem.OEWriteMolecule(ofs, mol)
ifs.close()
ofs.close()
#############################################################################
# INTERFACE
#############################################################################
InterfaceData = '''
!BRIEF AssignCharges.py [-options] <inmol> [<outmol>]
!CATEGORY "input/output options :"
!PARAMETER -in
!ALIAS -i
!TYPE string
!BRIEF Input molecule
!VISIBILITY simple
!REQUIRED true
!KEYLESS 1
!END
!PARAMETER -out
!ALIAS -o
!TYPE string
!DEFAULT oeassigncharges.oeb.gz
!BRIEF Output molecule (usually an oeb)
!VISIBILITY simple
!REQUIRED false
!KEYLESS 2
!END
!END
!CATEGORY "Charging options :"
!PARAMETER -method
!TYPE string
!LEGAL_VALUE noop
!LEGAL_VALUE mmff
!LEGAL_VALUE mmff94
!LEGAL_VALUE am1bcc
!LEGAL_VALUE am1bccnosymspt
!LEGAL_VALUE amber
!LEGAL_VALUE amberff94
!LEGAL_VALUE am1bccelf10
!DEFAULT mmff94
!BRIEF which set of charges to apply
!SIMPLE true
!REQUIRED false
!END
!END
'''
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 2: Applying charges to an OpenEye design unit.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# This program demonstrates how to apply charges to an OEDesignUnit.
#############################################################################
import sys
from openeye import oechem
from openeye import oequacpac
def main(argv=[__name__]):
opts = oechem.OESimpleAppOptions("applycharges_du", oechem.OEFileStringType_DU,
oechem.OEFileStringType_DU)
if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
return 0
ifs = oechem.oeifstream()
if not ifs.open(opts.GetInFile()):
oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
ofs = oechem.oeofstream()
if not ofs.open(opts.GetOutFile()):
oechem.OEThrow.Fatal("Unable to open %s for writing" % opts.GetOutFile())
du = oechem.OEDesignUnit()
while oechem.OEReadDesignUnit(ifs, du):
charge_engine = oequacpac.OEDesignUnitCharges()
if charge_engine.ApplyCharges(du):
oechem.OEWriteDesignUnit(ofs, du)
else:
oechem.OEThrow.Warning("%s: %s" % (du.GetTitle(), "Failed to assign charges"))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 3: Applying charges to an OpenEye design unit.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oequacpac
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <mol-infile> <mol-outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
logfs = oechem.oeofstream("enumerateionizationstatesatneutralph.log")
# oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Verbose)
# oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Info)
oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Warning)
oechem.OEThrow.SetOutputStream(logfs)
mol = oechem.OEGraphMol()
while oechem.OEReadMolecule(ifs, mol):
title = mol.GetTitle()
opts = oequacpac.OEMultistatepKaModelOptions()
# opts.SetMaxNumMicrostates(128)
multistatepka = oequacpac.OEMultistatepKaModel(mol, opts)
if (multistatepka.GenerateMicrostates()):
for a in multistatepka.GetMicrostates():
a.SetTitle(title)
oechem.OEWriteMolecule(ofs, a)
ofs.flush()
else:
msg = ("No microstates are generated for molecule: %s"
% title)
oechem.OEThrow.Warning(msg)
oechem.OEWriteMolecule(ofs, mol)
ofs.flush()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 4: A fast informatics technique using tautomer enumeration.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oequacpac
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <mol-infile> <mol-outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
tautomerOptions = oequacpac.OETautomerOptions()
pKaNorm = True
for mol in ifs.GetOEGraphMols():
for tautomer in oequacpac.OEGetReasonableTautomers(mol, tautomerOptions, pKaNorm):
oechem.OEWriteMolecule(ofs, tautomer)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 5: Set a single dominant ionization state of a molecule at pH 7.4.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oequacpac
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <mol-infile> <mol-outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
mol = oechem.OEGraphMol()
while oechem.OEReadMolecule(ifs, mol):
if oequacpac.OESetNeutralpHModel(mol):
oechem.OEWriteMolecule(ofs, mol)
else:
msg = ("Unable to set a neutral pH model for molecule: %s"
% mol.GetTile())
oechem.OEThrow.Warning(msg)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 6: Set a favorable ionization state assuming pH 7.4.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oequacpac
def main(argv=[__name__]):
if len(argv) != 3:
oechem.OEThrow.Usage("%s <mol-infile> <mol-outfile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
ofs = oechem.oemolostream()
if not ofs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[2])
for mol in ifs.GetOEGraphMols():
oequacpac.OEGetReasonableProtomer(mol)
oechem.OEWriteMolecule(ofs, mol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 7: Obtain the Wiberg bond orders from an AM1 calculation.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oequacpac
def main(argv=[__name__]):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream(sys.argv[1])
am1 = oequacpac.OEAM1()
results = oequacpac.OEAM1Results()
for mol in ifs.GetOEMols():
for conf in mol.GetConfs():
print("molecule: ", mol.GetTitle(), "conformer:", conf.GetIdx())
if am1.CalcAM1(results, mol):
nbonds = 0
for bond in mol.GetBonds(oechem.OEIsRotor()):
nbonds += 1
print(results.GetBondOrder(bond.GetBgnIdx(), bond.GetEndIdx()))
print("Rotatable bonds: ", nbonds)
if __name__ == "__main__":
import sys
sys.exit(main(sys.argv))
Saiph Toolkit
The Saiph toolkit provides facilities for converting data to different formats without changing the meaning of the data. See the Saiph chapter for a guide to programming examples.
Shape Toolkit
The Shape toolkit facilitates the calculation of molecular descriptors for shape (steric multipoles), volume overlap between molecules, and spatial similarity of chemical groups (color force field), as well as the optimization of the latter two quantities. See the Shape TK chapter for a guide to programming examples.
SiteHopper Toolkit
The Shape toolkit facilitates rapid comparison of protein binding sites. See the SiteHopper chapter for a guide to programming examples.
Spicoli Toolkit
The Spicoli toolkit facilitates creating, manipulating, and analyzing surfaces of many types. Programming examples are presented and excerpted with specific features, for example, OEMakeConnectedSurfaceCliques.
Listing 1: CalculateTriangleAreas.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oespicoli
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <input>" % sys.argv[0])
ims = oechem.oemolistream()
if not ims.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s" % sys.argv[1])
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ims, mol):
oechem.OEThrow.Fatal("Unable to read a molecule")
oechem.OEAssignBondiVdWRadii(mol)
surf = oespicoli.OESurface()
oespicoli.OEMakeMolecularSurface(surf, mol)
areas = oechem.OEFloatArray(surf.GetNumTriangles())
oespicoli.OECalculateTriangleAreas(surf, areas)
atomareas = [0.0] * mol.GetMaxAtomIdx()
for i in range(surf.GetNumTriangles()):
tri = surf.GetTriangle(i)
a1 = surf.GetAtomsElement(tri[0])
a2 = surf.GetAtomsElement(tri[1])
a3 = surf.GetAtomsElement(tri[2])
atomareas[a1] += areas[i]/3.0
atomareas[a2] += areas[i]/3.0
atomareas[a3] += areas[i]/3.0
for atom in mol.GetAtoms():
print("atom %d area = %2.4f" % (atom.GetIdx(), atomareas[atom.GetIdx()]))
Listing 2: MakeConnectedSurfaceCliques.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oespicoli
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <input>" % sys.argv[0])
ims = oechem.oemolistream()
if not ims.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s" % sys.argv[1])
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ims, mol):
oechem.OEThrow.Fatal("Unable to read a molecule")
oechem.OEAssignBondiVdWRadii(mol)
surf = oespicoli.OESurface()
oespicoli.OEMakeMolecularSurface(surf, mol)
nclqs = oespicoli.OEMakeConnectedSurfaceCliques(surf)
areas = []
for i in range(1, nclqs+1):
areas.append((oespicoli.OESurfaceCliqueArea(surf, i), i))
maxarea, maxclq = max(areas)
oespicoli.OESurfaceCropToClique(surf, maxclq)
print(maxarea)
print(oespicoli.OESurfaceArea(surf))
Listing 3: AttachSurface.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oespicoli
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <input>" % sys.argv[0])
ims = oechem.oemolistream()
if not ims.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s" % sys.argv[1])
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ims, mol):
oechem.OEThrow.Fatal("Unable to read a molecule")
oechem.OEAssignBondiVdWRadii(mol)
surf = oespicoli.OESurface()
oespicoli.OEMakeMolecularSurface(surf, mol)
mol.SetData("surface", surf)
ofs = oechem.oemolostream("foo.oeb")
oechem.OEWriteMolecule(ofs, mol)
ofs.close()
ifs = oechem.oemolistream("foo.oeb")
oechem.OEReadMolecule(ifs, mol)
msrf = mol.GetData("surface")
Listing 4: SurfaceDataAccess.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
from openeye import oespicoli
surf = oespicoli.OESurface()
coords = oechem.OEFloatArray(surf.GetNumVertices() * 3)
surf.GetVertices(coords)
for i in range(surf.GetNumVertices()):
vert = surf.GetVertex(i)
coords = oechem.OEUIntArray(surf.GetNumTriangles() * 3)
surf.GetTriangles(coords)
for i in range(surf.GetNumTriangles()):
tri = surf.GetTriangle(i)
Spruce Toolkit
The Spruce toolkit facilitates preparing biomolecules (that is, proteins and nucleic acids) for modeling tasks. See the Spruce chapter for a guide to programming examples. Examples listed here are provided for download in the Spruce chapter.
Listing 1: du2mmcif.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
import os
from openeye import oechem
from openeye import oegrid
from openeye import oespruce
def main(argv=sys.argv):
if len(argv) > 2:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream()
ifile = argv[1]
ofile = os.path.basename(ifile)[:-5] + ".cif"
ofs = oechem.oemolostream(ofile)
ofs.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEOFlavor_MMCIF_Default)
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(ifile, du):
oechem.OEThrow.Fatal("Cannot read design unit!")
complex = oechem.OEGraphMol()
du.GetComponents(complex, oechem.OEDesignUnitComponents_All ^ oechem.OEDesignUnitComponents_PackingResidues)
du.GetPDBMetaData(complex)
oechem.OEWriteMolecule(ofs, complex)
ofs.close()
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 2: add_receptor_obj_to_du.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem, oedocking
COMBINED_DESIGNUNIT_CONSTANTS = {
"All":oechem.OEDesignUnitComponents_All,
"TargetComplex":oechem.OEDesignUnitComponents_TargetComplex,
"TargetComplexNoSolvent":oechem.OEDesignUnitComponents_TargetComplexNoSolvent,
"Default":oechem.OEDesignUnitComponents_Default,
"ListComponents":oechem.OEDesignUnitComponents_ListComponents,
"MacroMolComponents":oechem.OEDesignUnitComponents_MacroMolComponents,
"MolComponents":oechem.OEDesignUnitComponents_MolComponents,
}
def make_receptor_with_custom_mask_and_predicate(du, receptor_out, mask, pred_str):
"""
Inputs:
du (str): The file containing OEDesignUnit (.oedu)
receptor_out (str): Path for the output receptor file
pred (str): Pipe separated string of residues to create subset.
If no predicate is provided, the entirety of an included
component will be part of the receptor mask.
mask(OEDesignUnitComponent): Specifies the component of the design unit
that is to be used as as receptor mask.
"""
opts = oedocking.OEMakeReceptorOptions()
# Add target predicate to create OESubSetDesignUnit
opts.SetTargetPred(pred_str)
target_mask = mask
opts.SetTargetMask(target_mask)
if oedocking.OEMakeReceptor(du, opts):
oechem.OEThrow.Info(f"Successfully created receptor: {receptor_out}")
return True
oechem.OEThrow.Warning(f"{du.GetTitle()} failed to make receptor")
return False
def get_target_component_mask(component_string):
if component_string in COMBINED_DESIGNUNIT_CONSTANTS:
return COMBINED_DESIGNUNIT_CONSTANTS[component_string]
component_id = oechem.OEGetDesignUnitComponentID(component_string)
if component_id == 0:
oechem.Throw.Fatal(f"{component_string} is not a OEDesignUnit Component")
return component_id
def main(argv=[__name__]):
"""
Add solvent or cofactor atoms/molecules to a receptor docking grid.
"""
itf = oechem.OEInterface(InterfaceData, argv)
infile = itf.GetString("-du")
receptor_out = itf.GetString("-out")
target_mask = itf.GetString("-mask")
pred_str = itf.GetString("-pred")
if not os.path.exists(infile):
oechem.OEThrow.Fatal(f"{infile} does not exist.")
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(infile, du):
oechem.OEThrow.Fatal("Cannot read design unit!")
if not oechem.OEIsWriteableDesignUnit(receptor_out):
oechem.OEThrow.Fatal(f"Can not write design unit to {receptor_out}")
target_mask = target_mask.split(",")
if len(target_mask) == 0:
processed_mask = oechem.OEDesignUnitComponents_TargetComplexNoSolvent
elif len(target_mask) == 1:
processed_mask = get_target_component_mask(target_mask[0].strip())
else:
processed_mask = get_target_component_mask(target_mask[0].strip())
for component_string in target_mask[1:]:
print("hit it")
processed_mask = processed_mask | get_target_component_mask(component_string.strip())
success = make_receptor_with_custom_mask_and_predicate(du, receptor_out, processed_mask, pred_str)
if success:
oechem.OEWriteDesignUnit(receptor_out, du)
InterfaceData = """
!BRIEF [To run] python add_receptor_obj_to_du.py -du <oedu>
!PARAMETER -du
!TYPE string
!REQUIRED true
!BRIEF Input OEDesignUnit file.
!DETAIL
Input OEDesignUnit (.oedu) file containing the prepared protein structure.
!END
!PARAMETER -out
!TYPE string
!REQUIRED false
!DEFAULT receptor_out.oedu
!BRIEF Output receptor file.
!DETAIL
Output receptor file (.oedu).
!END
!PARAMETER -mask
!TYPE string
!REQUIRED false
!DEFAULT TargetComplexNoSolvent
!BRIEF Mask string containing the component names for the receptor mask. Components should be separated by string.
!DETAIL
Mask string containing the component names for the receptor mask. Components should be separated by string.
Example: "protein,ligand,cofactors". Options to choose from: protein, nucleic, ligand, cofactors, solvent,
metals, counter_ions, lipids, packing_residues, excipients, suagrs, polymers, post_translational, other_proteins,
other_nucleics, other_ligands, other_cofactors, undefined, All, TargetComplex, TargetComplexNoSolvent, Default,
ListComponents, MacroMolComponents, and MolComponents.
!END
!PARAMETER -pred
!TYPE string
!REQUIRED false
!BRIEF Predicate string containing residue IDs, solvent or cofactor molecules to create a subset
!DETAIL
Predicate string containing solvent and cofactor molecules with their residue IDs. Accepted format is,
"MN:508: :D:1:|HOH:435: :D:1:"
where, if needed, empty space is filled with alt loc.
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 3: extract_biounits_ref.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Simple superimposition of a fit protein on to a reference protein
#############################################################################
import sys
import os
from openeye import oechem
from openeye import oespruce
import tempfile
def ReadProteinMol(pdb_file, mol):
ifs = oechem.oemolistream()
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_SpruceDefault)
ifs.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEIFlavor_MMCIF_SpruceDefault)
if not ifs.open(pdb_file):
oechem.OEThrow.Fatal("Unable to open %s for reading." % pdb_file)
temp_mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, temp_mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s." % pdb_file)
ifs.close()
fact = oechem.OEAltLocationFactory(temp_mol)
mol.Clear()
fact.MakePrimaryAltMol(mol)
return (mol)
def main(argv=[__name__]):
if len(argv) not in [3, 5, 6]:
oechem.OEThrow.Usage("%s <extract protein PDB> <reference protein PDB> [min score] [superpose] [nowrite]" % argv[0]) # noqa
do_write = True
if len(argv) == 6:
if argv[5] != "nowrite":
oechem.OEThrow.Warning("%s is not a valid option.\n" % argv[5])
sys.exit(1)
else:
do_write = False
opts = oespruce.OEBioUnitExtractionOptions()
if len(argv) >= 5:
opts.SetMinScore(int(argv[3]))
opts.SetSuperpose(bool(argv[4]))
extract_prot_file = argv[1]
extract_prot = oechem.OEGraphMol()
extract_success = ReadProteinMol(extract_prot_file, extract_prot)
if not extract_success:
oechem.OEThrow.Fatal("Unable to extract protein(s) from PDB file.")
ref_prot_file = argv[2]
ref_prot = oechem.OEGraphMol()
ref_success = ReadProteinMol(ref_prot_file, ref_prot)
if not ref_success:
oechem.OEThrow.Fatal("Unable to reference protein(s) from PDB file.")
biounits = oespruce.OEExtractBioUnits(extract_prot, ref_prot, opts)
if do_write:
pdb_ext = ".pdb"
str_pos = extract_prot_file.find(pdb_ext)
base_name = extract_prot_file[0:str_pos]
temp_dir = tempfile.mkdtemp()
for i, biounit in enumerate(biounits):
output_biounit_file = os.path.join(temp_dir, base_name + "_BU_{}.oeb.gz".format(i)) # noqa
print("Writing biounit {} to {}".format(i, output_biounit_file))
ofs = oechem.oemolostream(output_biounit_file)
oechem.OEWriteMolecule(ofs, biounit)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 4: extract_biounits_remarks.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Simple superimposition of a fit protein on to a reference protein
#############################################################################
import sys
import os
from openeye import oechem
from openeye import oespruce
import tempfile
def ReadProteinMol(pdb_file, mol):
ifs = oechem.oemolistream()
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_SpruceDefault)
ifs.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEIFlavor_MMCIF_SpruceDefault)
if not ifs.open(pdb_file):
oechem.OEThrow.Fatal("Unable to open %s for reading." % pdb_file)
temp_mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, temp_mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s." % pdb_file)
ifs.close()
fact = oechem.OEAltLocationFactory(temp_mol)
mol.Clear()
fact.MakePrimaryAltMol(mol)
return (mol)
def main(argv=[__name__]):
if len(argv) not in [2, 4, 5]:
oechem.OEThrow.Usage("%s <extract protein PDB> [max atoms] [prefer author] [nowrite]" % argv[0]) # noqa
do_write = True
if len(argv) == 5:
if argv[4] != "nowrite":
oechem.OEThrow.Warning("%s is not a valid option.\n" % argv[4])
sys.exit(1)
else:
do_write = False
opts = oespruce.OEBioUnitExtractionOptions()
if len(argv) >= 4:
opts.SetMaxAtoms(int(argv[2]))
opts.SetPreferAuthorRecord(bool(argv[3]))
extract_prot_file = argv[1]
extract_prot = oechem.OEGraphMol()
extract_success = ReadProteinMol(extract_prot_file, extract_prot)
if not extract_success:
oechem.OEThrow.Fatal("Unable to read protein(s) from PDB file.")
biounits = oespruce.OEExtractBioUnits(extract_prot, opts)
if do_write:
pdb_ext = ".pdb"
str_pos = extract_prot_file.find(pdb_ext)
base_name = extract_prot_file[0:str_pos]
temp_dir = tempfile.mkdtemp()
for i, biounit in enumerate(biounits):
output_biounit_file = os.path.join(temp_dir, base_name + "_BU_{}.oeb.gz".format(i)) # noqa
print("Writing biounit {} to {}".format(i, output_biounit_file))
ofs = oechem.oemolostream(output_biounit_file)
oechem.OEWriteMolecule(ofs, biounit)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 5: findpockets.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################################################
# This program demonstrates how to find pockets and some of its properties from a protein or DesignUnit file.
#############################################################################################################
import sys
from openeye import oechem
from openeye import oespruce
def readProteinMol(ifilename):
if oechem.OEGetFileExtension(ifilename) == 'oedu':
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(ifilename, du):
oechem.OEThrow.Fatal("Unable to open %s for reading OEDesignUnit" % ifilename)
return du
else:
ifs = oechem.oemolistream()
if not ifs.open(ifilename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifilename)
mol = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, mol)
return mol
def main(argv=None):
if argv is None:
argv = [__name__]
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <protein or DesignUnit input file>" % argv[0])
mol = readProteinMol(sys.argv[1])
pockets = oespruce.OEFindPockets(mol)
print("pockets count: %s" % len(list(pockets)))
pockets.ToFirst()
pocket_cntr = 0
for pocket in pockets:
pocket_cntr += 1
pocket_residues = pocket.GetResidues()
print("pocket_%s Residues count: " % pocket_cntr, len(list(pocket_residues)))
pocket_residues.ToFirst()
print("pocket_%s Residues: " % pocket_cntr)
for res in pocket_residues:
print(res)
print("pocket_%s Surface Area: " % pocket_cntr, pocket.GetSurfaceArea())
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 6: make_apo_design_units.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Script to prepare proteins into design units
#############################################################################
import sys
import os
from openeye import oechem
from openeye import oegrid
from openeye import oespruce
def main(argv=sys.argv):
if len(argv) < 3 or len(argv) > 5:
oechem.OEThrow.Usage(
"%s <infile> <site_residue> [<mtzfile>] [<loopdbfile>]" % argv[0]
)
ifs = oechem.oemolistream()
ifile = argv[1]
if not ifs.open(ifile):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifile)
site_residue = argv[2]
include_loop = False
include_ed = False
if len(argv) > 3:
if len(argv) == 5 or (len(argv) == 4 and "mtz" in argv[3]):
edfile = argv[3]
ed = oegrid.OESkewGrid()
if not oegrid.OEReadMTZ(edfile, ed, oegrid.OEMTZMapType_Fwt):
oechem.OEThrow.Fatal(
"Unable to read electron density file %s" % edfile
) # noqa
include_ed = True
if len(argv) == 5:
loopfile = argv[4]
include_loop = True
elif len(argv) == 4 and "mtz" not in argv[3]:
loopfile = argv[3]
include_loop = True
if ifs.GetFormat() not in [oechem.OEFormat_PDB, oechem.OEFormat_CIF]:
oechem.OEThrow.Fatal("Only works for .pdb or .cif input files")
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_SpruceDefault)
ifs.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEIFlavor_MMCIF_SpruceDefault)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % ifile)
metadata = oespruce.OEStructureMetadata()
opts = oespruce.OEMakeDesignUnitOptions()
opts.GetPrepOptions().GetBuildOptions().GetLoopBuilderOptions().SetBuildTails(False)
if include_loop:
opts.GetPrepOptions().GetBuildOptions().GetLoopBuilderOptions().SetLoopDBFilename(
loopfile
)
if include_ed:
design_units = oespruce.OEMakeDesignUnits(mol, ed, metadata, opts, site_residue)
else:
design_units = oespruce.OEMakeDesignUnits(mol, metadata, opts, site_residue)
base_name = os.path.basename(ifile)[:-4] + "_DU_{}.oedu"
for i, design_unit in enumerate(design_units):
oechem.OEWriteDesignUnit(base_name.format(i), design_unit)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 7: make_design_unit_using_metadata.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
'''
This script prepares an MD or docking-ready design unit with receptor from an input PDB or mmCIF file.
Input parameters:
Required:
-in: The input PDB or mmCIF file
-site_residue: Defines a binding site residue for pocket detection (Required for apo structures only)
Optional:
-map: Input mtz file containing the electron density map
-loop_db: Input loop_db file for loop modeling
-generate_tautomers: generate and use tautomers in the hydrogen network optimization
-prefix: String to prepend to all output DU files
-metadata: Input metadata JSON file
-allow_filter_error: Run spruce prep even when structure fails spruce filter
-verbose: boolean flag to trigger verbose logging
Usage examples:
python spruce_prep.py -in 3fly.cif
python spruce_prep.py -in 3fly.pdb -metadata 3fly_metadata.json -generate_tautomers false
python spruce_prep.py -in 3fly.pdb -map 3fly.mtz -verbose true -prefix 3FLY -loop_db my_loop_db.loop_db
python spruce_prep.py -3p2q.pdb -site_residue 'HIS: 76: :A'
'''
import sys
from openeye import oechem
from openeye import oegrid
from openeye import oespruce
from openeye import oedocking
InterfaceData = '''
!PARAMETER -in
!TYPE string
!REQUIRED true
!BRIEF Input PDB/CIF file name
!END
!PARAMETER -site_residue
!TYPE string
!REQUIRED false
!BRIEF Site residue specification to indentify binding site (ex: 'HIS:42: :A')
!END
!PARAMETER -prefix
!TYPE string
!REQUIRED false
!BRIEF prefix to append to all output DU file names
!END
!PARAMETER -map
!TYPE string
!REQUIRED false
!LEGAL_VALUE *.mtz
!BRIEF Input electron density file
!END
!PARAMETER -loop_db
!TYPE string
!REQUIRED false
!LEGAL_VALUE *.loop_db
!BRIEF Input database for loop modeling
!END
!PARAMETER -generate_tautomers
!TYPE bool
!REQUIRED false
!DEFAULT true
!BRIEF Option to generate and use tautomers in the hydrogen network optimization (optional)
!END
!PARAMETER -metadata
!TYPE string
!REQUIRED false
!LEGAL_VALUE *.json
!BRIEF Input structure metadata json file
!END
!PARAMETER -allow_filter_error
!TYPE bool
!REQUIRED false
!DEFAULT false
!BRIEF Option to allow running spruce prep even when structure fails spruce filter.
!END
!PARAMETER -verbose
!TYPE bool
!REQUIRED false
!DEFAULT false
!BRIEF Boolean flag to trigger verbose logging
!END
'''
def main(argv=sys.argv):
itf = oechem.OEInterface(InterfaceData, argv)
# read input parameters
ifile = itf.GetString('-in')
include_ed = False
if itf.HasString('-map'):
mapfile = itf.GetString('-map')
include_ed = True
include_loop = False
if itf.HasString('-loopdb'):
loopfile = itf.GetString('-loopdb')
include_loop = True
site_residue_specified = False
if itf.HasString('-site_residue'):
site_residue = itf.GetString('-site_residue')
site_residue_specified = True
has_prefix = False
if itf.HasString('-prefix'):
prefix = itf.GetString('-prefix')
has_prefix = True
if itf.GetBool('-verbose'):
oechem.OEThrow.SetLevel(oechem.OEErrorLevel_Verbose)
has_metadata = False
if itf.HasString('-metadata'):
metadata_json_name = itf.GetString('-metadata')
with open(metadata_json_name, "r") as f:
metadata_json = f.read()
has_metadata = True
allow_filter_error = itf.GetBool('-allow_filter_error')
generate_tautomers = itf.GetBool('-generate_tautomers')
# read PDB or CIF input file
ifs = oechem.oemolistream()
if not ifs.open(ifile):
oechem.OEThrow.Fatal(f'Unable to open {ifile} for reading')
if ifs.GetFormat() not in [oechem.OEFormat_PDB, oechem.OEFormat_CIF]:
oechem.OEThrow.Fatal('Input file must be .pdb or .cif')
ifs.SetFlavor(oechem.OEFormat_PDB,
oechem.OEIFlavor_PDB_Default |
oechem.OEIFlavor_PDB_DATA |
oechem.OEIFlavor_PDB_ALTLOC)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal(f'Unable to read molecule from {ifile}')
# read mtz file if included
ed = oegrid.OESkewGrid()
if include_ed:
if not oegrid.OEReadMTZ(mapfile, ed, oegrid.OEMTZMapType_Fwt):
oechem.OEThrow.Fatal(f'Unable to read electron density file {mapfile}')
makedu_opts = oespruce.OEMakeDesignUnitOptions()
makedu_opts.GetSplitOptions().SetAlternateLocationHandling(oespruce.OEAlternateLocationOption_Combinatorial)
makedu_opts.GetSplitOptions().SetMinLigAtoms(8)
makedu_opts.GetSplitOptions().SetMaxLigAtoms(200)
makedu_opts.GetSplitOptions().SetMaxLigResidues(20)
makedu_opts.GetPrepOptions().GetEnumerateSitesOptions().SetEnumerateCofactorSites(False)
makedu_opts.GetPrepOptions().GetEnumerateSitesOptions().SetCollapseNonSiteAlts(False)
# read metadata file if provided
metadata = oespruce.OEStructureMetadata()
if has_metadata:
oespruce.OEStructureMetadataFromJson(metadata, metadata_json)
# set loop database if included
if include_loop:
makedu_opts.GetPrepOptions().GetBuildOptions().GetLoopBuilderOptions().SetLoopDBFilename(loopfile)
# set tautomer generation flag
makedu_opts.GetPrepOptions().GetProtonateOptions().SetGenerateTautomers(generate_tautomers)
# run Spruce filter
filter_opts = oespruce.OESpruceFilterOptions()
filter = oespruce.OESpruceFilter(filter_opts, makedu_opts)
ret_filter = filter.StandardizeAndFilter(mol, ed, metadata)
if ret_filter !=oespruce.OESpruceFilterIssueCodes_Success:
oechem.OEThrow.Warning(f'This structure fails spruce filter due to: ')
oechem.OEThrow.Warning(filter.GetMessages())
if not allow_filter_error:
oechem.OEThrow.Fatal('This structure fails spruce filter')
# make the DUs
if site_residue_specified:
# use site residue
if include_ed:
design_units = oespruce.OEMakeDesignUnits(mol, ed, metadata, makedu_opts, site_residue)
else:
design_units = oespruce.OEMakeDesignUnits(mol, metadata, makedu_opts, site_residue)
else:
# assume structure has bound ligand
if include_ed:
design_units = oespruce.OEMakeDesignUnits(mol, ed, metadata, makedu_opts)
else:
design_units = oespruce.OEMakeDesignUnits(mol, metadata, makedu_opts)
# validate the DUs
validator = oespruce.OEValidateDesignUnit()
for i, design_unit in enumerate(design_units):
ret_validator = validator.Validate(design_unit, metadata)
if ret_validator != oespruce.OEDesignUnitIssueCodes_Success:
oechem.OEThrow.Warning(f'Design unit {design_unit.GetTitle()} did not pass the DU validator.')
oechem.OEThrow.Warning(validator.GetMessages())
# make the receptor
ropts = oedocking.OEMakeReceptorOptions()
if not oedocking.OEMakeReceptor(design_unit, ropts):
oechem.OEThrow.Warning(f'Unable to generate receptor for design unit {design_unit.GetTitle()}')
# write the DU
print(design_unit.GetTitle())
basename = f'{design_unit.GetTitle()}'.replace('(', '_').replace(')', '_').replace(' > ', 'DU_').replace(' ', '_').replace('/', '-')[:-1]
if has_prefix:
ofile = f'{prefix}_{basename}.oedu'
else:
ofile = f'{basename}.oedu'
if not oechem.OEWriteDesignUnit(ofile, design_unit):
oechem.OEThrow.Warning(f'Unable to write design unit {design_unit.GetTitle()}')
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 8: make_design_units.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Script to prepare proteins into design units
#############################################################################
import sys
import os
from openeye import oechem
from openeye import oegrid
from openeye import oespruce
def main(argv=sys.argv):
if len(argv) < 2 or len(argv) > 4:
oechem.OEThrow.Usage("%s <infile> [<mtzfile>] [<loopdbfile>]" % argv[0])
ifs = oechem.oemolistream()
ifile = argv[1]
if not ifs.open(ifile):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifile)
include_loop = False
include_ed = False
ed = oegrid.OESkewGrid()
if len(argv) > 2:
if len(argv) == 4 or (len(argv) == 3 and "mtz" in argv[2]):
edfile = argv[2]
if not oegrid.OEReadMTZ(edfile, ed, oegrid.OEMTZMapType_Fwt):
oechem.OEThrow.Fatal(
"Unable to read electron density file %s" % edfile
) # noqa
include_ed = True
if len(argv) == 4:
loopfile = argv[3]
include_loop = True
elif len(argv) == 3 and "mtz" not in argv[2]:
loopfile = argv[2]
include_loop = True
if ifs.GetFormat() not in [oechem.OEFormat_PDB, oechem.OEFormat_CIF]:
oechem.OEThrow.Fatal("Only works for .pdb or .cif input files")
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_SpruceDefault)
ifs.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEIFlavor_MMCIF_SpruceDefault)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % ifile)
allow_filter_errors = False
metadata = oespruce.OEStructureMetadata()
filter_opts = oespruce.OESpruceFilterOptions()
makedu_opts = oespruce.OEMakeDesignUnitOptions()
makedu_opts.GetPrepOptions().GetBuildOptions().GetLoopBuilderOptions().SetBuildTails(False)
if include_loop:
makedu_opts.GetPrepOptions().GetBuildOptions().GetLoopBuilderOptions().SetLoopDBFilename(
loopfile
)
filter = oespruce.OESpruceFilter(filter_opts, makedu_opts)
ret_filter = filter.StandardizeAndFilter(mol, ed, metadata)
if ret_filter !=oespruce.OESpruceFilterIssueCodes_Success:
oechem.OEThrow.Warning("This structure fails spruce filter due to: ")
oechem.OEThrow.Warning(filter.GetMessages())
if not allow_filter_errors:
oechem.OEThrow.Fatal("This structure fails spruce filter")
if include_ed:
design_units = oespruce.OEMakeDesignUnits(mol, ed, metadata, makedu_opts)
else:
design_units = oespruce.OEMakeDesignUnits(mol, metadata, makedu_opts)
validator = oespruce.OEValidateDesignUnit()
base_name = os.path.basename(ifile)[:-4] + "_DU_{}.oedu"
for i, design_unit in enumerate(design_units):
ret_validator = validator.Validate(design_unit,metadata)
if ret_validator != oespruce.OEDesignUnitIssueCodes_Success:
oechem.OEThrow.Warning("This generated DU did not pass DU validator.")
oechem.OEThrow.Warning(validator.GetMessages())
oechem.OEWriteDesignUnit(base_name.format(i), design_unit)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 9: fasta_to_structmeta.py full listing.
#!/usr/bin/env python
# (C) 2024 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oespruce
def main(argv=sys.argv):
if len(sys.argv) != 4:
oechem.OEThrow.Usage("%s <FASTA> <ChainIDs> <output>" % sys.argv[0])
fasta_input = sys.argv[1]
ifs = oechem.oemolistream()
ifs.open(fasta_input)
fastaMol = oechem.OEGraphMol()
json = oechem.oeout
if not json.open(sys.argv[3]):
oechem.OEThrow.Fatal(f'Unable to open {oname} for writing')
StructMeta = oespruce.OEStructureMetadata()
SeqMeta = oespruce.OESequenceMetadata()
seq_list = []
chainID = ""
chainIDs = sys.argv[2].split(',')
i = 0
while oechem.OEReadFASTAFile(ifs, fastaMol):
for res in oechem.OEGetResidues(fastaMol):
seq_list.append(res.GetName())
SeqMeta.SetChainID(chainIDs[i])
SeqMeta.SetSequence("-".join(seq_list))
StructMeta.AddSequenceMetadata(SeqMeta)
i += 1
if i > len(chainIDs):
oechem.OEThrow.Fatal('More sequences are in the fasta file than the ChainIDs provided,')
json.write(oespruce.OEStructureMetadataToJson(StructMeta))
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 10: superpose.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
#############################################################################
# Simple superimposition of a fit protein on to a reference protein
#############################################################################
import sys
import os
from openeye import oechem
from openeye import oespruce
import tempfile
def ReadProteinMol(ifilename):
if oechem.OEIsReadableDesignUnit(ifilename):
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(ifilename, du):
oechem.OEThrow.Fatal("Unable to open %s for reading OEDesignUnit" % ifilename)
return du
else:
ifs = oechem.oemolistream()
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_SpruceDefault)
ifs.SetFlavor(oechem.OEFormat_MMCIF, oechem.OEIFlavor_MMCIF_SpruceDefault)
if not ifs.open(ifilename):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ifilename)
mol = oechem.OEGraphMol()
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read molecule from %s" % ifilename)
return mol
def ReadSiteResidues(in_file):
site_residues = []
with open(in_file, "r") as f:
lines = f.read().splitlines()
for line in lines:
if line.strip() == "":
continue
site_residues.append(line)
return site_residues
def main(argv=[__name__]):
if len(argv) < 3:
oechem.OEThrow.Usage(f"{argv[0]} <reference protein PDB> <fit protein PDB> [global|ddm|weighted|sse|site] [site-residue file] [nowrite]") # noqa
inp_method = "global"
if len(argv) > 3:
inp_method = argv[3]
site_file = None
do_write = True
if inp_method == "site":
if len(argv) > 4:
site_file = argv[4]
else:
oechem.OEThrow.Warning(f"A text file containing site residues must be provided for using the SiteSequence method\n")
sys.exit(1)
if not os.path.isfile(site_file):
oechem.OEThrow.Warning(f"File not found: {site_file}\n")
sys.exit(1)
nowrite_argidx = 5
else:
nowrite_argidx = 4
if len(argv) > nowrite_argidx:
if argv[nowrite_argidx] != "nowrite":
oechem.OEThrow.Warning(f"{argv[nowrite_argidx]} is not a valid option.\n")
sys.exit(1)
else:
do_write = False
ref_prot_file = argv[1]
fit_prot_file = argv[2]
ref_prot = ReadProteinMol(ref_prot_file)
fit_prot = ReadProteinMol(fit_prot_file)
method = oespruce.OEGetSuperposeMethodFromName(inp_method)
if method == oespruce.OESuperposeMethod_Undefined:
oechem.OEThrow.Warning(f"{inp_method} superposition method is not supported.\n")
sys.exit(1)
opts = oespruce.OESuperposeOptions(method)
print(f"Superposing {fit_prot_file} to {ref_prot_file} using {oespruce.OEGetSuperposeMethodName(method)}.\n")
results = oespruce.OESuperposeResults()
superposition = oespruce.OESuperpose(opts)
if opts.GetMethod() == oespruce.OESuperposeMethod_Site and not isinstance(ref_prot, oechem.OEDesignUnit):
site_residues = ReadSiteResidues(site_file)
superposition.SetupRef(ref_prot, site_residues)
else:
superposition.SetupRef(ref_prot)
superposition.Superpose(results, fit_prot)
rmsd = results.GetRMSD()
seqscore = results.GetSeqScore()
tanimoto = results.GetTanimoto()
results.Transform(fit_prot)
if opts.GetMethod() == oespruce.OESuperposeMethod_SSE:
print(f"Tanimoto: {tanimoto:4.2f}\n")
else:
print(f"RMSD: {rmsd:4.2f} Angstroms.")
print(f"SeqScore: {seqscore:d}.\n")
if do_write:
temp_dir = tempfile.mkdtemp()
if isinstance(fit_prot, oechem.OEDesignUnit):
str_pos = fit_prot_file.find(".oedu")
base_name = fit_prot_file[0:str_pos]
output_fit_file = os.path.join(temp_dir, base_name + "_sp.oedu")
ofs = oechem.oeofstream(output_fit_file)
oechem.OEWriteDesignUnit(ofs, fit_prot)
else:
str_pos = fit_prot_file.find(".pdb")
base_name = fit_prot_file[0:str_pos]
output_fit_file = os.path.join(temp_dir, base_name + "_sp.oeb.gz")
ofs = oechem.oemolostream(output_fit_file)
oechem.OEWriteMolecule(ofs, fit_prot)
print(f"Superimposed fit protein was written to {output_fit_file}.\n")
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 11: validate_design_unit.py full listing.
#!/usr/bin/env python
# (C) 2025 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import os
import sys
from openeye import oechem, oespruce
def main(argv=[__name__]):
if len(sys.argv) < 2:
print("Input needed:\npython validate_designunit.py <input.oedu>")
sys.exit(1)
ifilename = sys.argv[1]
if not os.path.exists(ifilename):
oechem.OEThrow.Fatal(f"{ifilename} does not exist.")
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(ifilename, du):
oechem.OEThrow.Fatal("Cannot read design unit!")
validator = oespruce.OEValidateDesignUnit()
issue_code = validator.Validate(du)
if issue_code == oespruce.OEDesignUnitIssueCodes_Success:
print(f"Validation successful for '{ifilename}")
else:
print(f"Validation raised the following warning(s) for '{ifilename}")
print(validator.GetMessages())
if __name__ == "__main__":
sys.exit(main(sys.argv))
Szmap Toolkit
The Szmap toolkit provides simple access to SZMAP functionality, for calculating solvent thermodynamic properties near molecular surfaces. For a guide to programming examples, see the Szmap chapter.
Listing 1: Generate Szmap points and probe orientations at ligand atoms.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
# generate szmap points and probe orientations at ligand atoms
import sys
from openeye import oechem
from openeye import oeszmap
InterfaceData = """
!BRIEF SzmapBestOrientations.py [-prob #.#] [-du] <designunitfile> [-o] <molfile>
!PARAMETER -du
!TYPE string
!BRIEF Input designunit
!REQUIRED true
!KEYLESS 1
!END
!PARAMETER -o
!TYPE string
!BRIEF Output file for points and probes molecules
!REQUIRED true
!KEYLESS 2
!END
!PARAMETER -prob
!TYPE double
!DEFAULT 0.5
!BRIEF Cutoff for cumulative probability of probes
!REQUIRED false
!END
"""
def GenerateSzmapProbes(oms, cumulativeProb, lig, prot):
"""
generate multiconf probes and data-rich points at ligand coords
@rtype : None
@param oms: output mol stream for points and probes
@param cumulativeProb: cumulative probability for cutoff of point set
@param lig: mol defining coordinates for szmap calcs
@param prot: context mol for szmap calcs (must have charges and radii)
"""
sz = oeszmap.OESzmapEngine(prot)
rslt = oeszmap.OESzmapResults()
points = oechem.OEGraphMol()
points.SetTitle("points %s" % lig.GetTitle())
probes = oechem.OEMol()
coord = oechem.OEFloatArray(3)
for i, atom in enumerate(lig.GetAtoms()):
lig.GetCoords(atom, coord)
if not oeszmap.OEIsClashing(sz, coord):
oeszmap.OECalcSzmapResults(rslt, sz, coord)
rslt.PlaceNewAtom(points)
clear = False
rslt.PlaceProbeSet(probes, cumulativeProb, clear)
name = oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_NeutralDiffDeltaG)
nddG = rslt.GetEnsembleValue(oeszmap.OEEnsemble_NeutralDiffDeltaG)
print("%2d (%7.3f, %7.3f, %7.3f): %s = %.3f"
% (i, coord[0], coord[1], coord[2], name, nddG))
else:
print("%2d (%7.3f, %7.3f, %7.3f): CLASH"
% (i, coord[0], coord[1], coord[2]))
oechem.OEWriteMolecule(oms, points)
oechem.OEWriteMolecule(oms, probes)
def main(argv=(__name__)):
"""
the protein should have charges and radii but the ligand need not
"""
itf = oechem.OEInterface()
if not oechem.OEConfigure(itf, InterfaceData):
oechem.OEThrow.Fatal("Problem configuring OEInterface!")
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to parse command line")
duFile = itf.GetString("-du")
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(duFile, du):
oechem.OEThrow.Fatal("Unable to open %s for reading" % duFile)
if not du.HasLigand():
oechem.OEThrow.Fatal("Input designunit %s does not have a ligand bound" % du.GetTitle())
lig = oechem.OEGraphMol()
du.GetLigand(lig)
prot = oechem.OEGraphMol()
du.GetComponents(prot, oechem.OEDesignUnitComponents_Protein)
outputFile = itf.GetString("-o")
if not oechem.OEIsWriteable(outputFile):
oechem.OEThrow.Fatal("Invalid file extension for output %s" % outputFile)
oms = oechem.oemolostream()
if not oms.open(outputFile):
oechem.OEThrow.Fatal("Unable to open %s for writing" % outputFile)
GenerateSzmapProbes(oms, itf.GetDouble("-prob"), lig, prot)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 2: Example of Szmap calculations.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszmap
InterfaceData = """
!BRIEF SzmapCalcs.py [-prob #.#] [-p] <molfile> [-l] <molfile> [-o] <molfile>
!PARAMETER -p
!TYPE string
!BRIEF Input protein (or other) context mol
!REQUIRED true
!KEYLESS 1
!END
!PARAMETER -l
!TYPE string
!BRIEF Input ligand coordinates for calculations
!REQUIRED true
!KEYLESS 2
!END
!PARAMETER -o
!TYPE string
!BRIEF Output file for points and probes molecules
!REQUIRED true
!KEYLESS 3
!END
!PARAMETER -prob
!TYPE double
!DEFAULT 0.5
!BRIEF Cutoff for cumulative probability of probes
!REQUIRED false
!END
"""
def RunSzmap(lig, prot):
"""
run szmap at ligand coordinates in the protein context
@rtype : None
@param lig: mol defining coordinates for szmap calcs
@param prot: context mol for szmap calcs (must have charges and radii)
"""
opt = oeszmap.OESzmapEngineOptions()
mol = oechem.OEGraphMol()
opt.GetProbeMol(mol)
print("probe mol smiles: %s" % oechem.OEMolToSmiles(mol))
opt.SetProbe(360)
print("norient = %d" % opt.NumOrientations())
opt.SetProbe(24).SetMaskCutoff(999.99)
print("norient = %d" % opt.NumOrientations())
print("cutoff = %.3f" % opt.GetMaskCutoff())
opt.SetMaskCutoff(0.0) # reset cutoff
print("cutoff = %.3f" % opt.GetMaskCutoff())
p = opt.GetProbe()
print("probe nconf = %d" % p.NumConfs())
sz = oeszmap.OESzmapEngine(prot, opt)
opt = sz.GetOptions()
print("norient= %d" % opt.NumOrientations())
print("name = %s" % opt.GetProbeName())
print("cutoff = %.3f" % opt.GetMaskCutoff())
mol = sz.GetContext()
print("context mol: %s" % mol.GetTitle())
print("probe smiles: %s" % oechem.OEMolToSmiles(opt.GetProbe()))
coord = oechem.OEFloatArray(3)
rslt = oeszmap.OESzmapResults()
for atom in lig.GetAtoms():
lig.GetCoords(atom, coord)
name = oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_NeutralDiffDeltaG)
print("ensemble name: %s" % name)
longName = True
name = oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_NeutralDiffDeltaG, longName)
nddg = oeszmap.OECalcSzmapValue(sz, coord)
print("ensemble name: %s, value: %.3f" % (name, nddg))
name = oeszmap.OEGetComponentName(oeszmap.OEComponent_Interaction)
print("component name: %s" % name)
if not oeszmap.OEIsClashing(sz, coord):
oeszmap.OECalcSzmapResults(rslt, sz, coord)
nddg = rslt.GetEnsembleValue(oeszmap.OEEnsemble_NeutralDiffDeltaG)
if not oeszmap.OEIsClashing(sz, coord):
oeszmap.OECalcSzmapResults(rslt, sz, coord)
# ...
print("result norient = %d" % rslt.NumOrientations())
nddg = rslt.GetEnsembleValue(oeszmap.OEEnsemble_NeutralDiffDeltaG)
print("nddG = %.3f" % nddg)
print("vdw = %.3f" % rslt.GetEnsembleValue(oeszmap.OEEnsemble_VDW))
coulomb = rslt.GetComponent(oeszmap.OEComponent_Interaction)
print("interaction:")
print(" ".join("%.3f" % c for c in coulomb))
order = rslt.GetProbabilityOrder()
print("conf with greatest prob = %d" % order[0])
prob = rslt.GetProbabilities()
print("greatest prob = %.3f" % prob[order[0]])
vdw = oechem.OEDoubleArray(rslt.NumOrientations())
rslt.GetComponent(vdw, oeszmap.OEComponent_VDW)
print("vdw greatest prob = %.3f" % vdw[order[0]])
point = oechem.OEFloatArray(3)
rslt.GetCoords(point)
print("calc point: (%.3f, %.3f, %.3f)" % (point[0], point[1], point[2]))
mcmol = oechem.OEMol()
rslt.PlaceProbeSet(mcmol)
probCutoff = 0.5
rslt.PlaceProbeSet(mcmol, probCutoff)
print("nconf to yield 50pct = %d" % mcmol.NumConfs())
clear = False
cumulativeProb = rslt.PlaceProbeSet(mcmol, 10, clear)
print("best 10 cumulative prob = %.3f" % cumulativeProb)
amol = oechem.OEGraphMol()
atom = rslt.PlaceNewAtom(amol)
print("vdw = %s" % atom.GetData("vdw"))
pmol = oechem.OEGraphMol()
rslt.PlaceProbeMol(pmol, order[0])
def GetSzmapEnergies(lig, prot):
"""
run szmap at ligand coordinates in the protein context
@rtype : None
@param lig: mol defining coordinates for szmap calcs
@param prot: context mol for szmap calcs (must have charges and radii)
"""
print("num\tatom\t%s\t%s\t%s\t%s\t%s"
% (oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_NeutralDiffDeltaG),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_PSolv),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_WSolv),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_VDW),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_OrderParam)))
coord = oechem.OEFloatArray(3)
sz = oeszmap.OESzmapEngine(prot)
rslt = oeszmap.OESzmapResults()
for i, atom in enumerate(lig.GetAtoms()):
lig.GetCoords(atom, coord)
if not oeszmap.OEIsClashing(sz, coord):
oeszmap.OECalcSzmapResults(rslt, sz, coord)
print("%2d\t%s\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f"
% (i, atom.GetName(),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_NeutralDiffDeltaG),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_PSolv),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_WSolv),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_VDW),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_OrderParam)))
else:
print("%2d\t%s CLASH" % (i, atom.GetName()))
def GenerateSzmapProbes(oms, cumulativeProb, lig, prot):
"""
generate multiconf probes and data-rich points at ligand coords
@rtype : None
@param oms: output mol stream for points and probes
@param cumulativeProb: cumulative probability for cutoff of point set
@param lig: mol defining coordinates for szmap calcs
@param prot: context mol for szmap calcs (must have charges and radii)
"""
coord = oechem.OEFloatArray(3)
sz = oeszmap.OESzmapEngine(prot)
rslt = oeszmap.OESzmapResults()
points = oechem.OEGraphMol()
points.SetTitle("points %s" % lig.GetTitle())
probes = oechem.OEMol()
for i, atom in enumerate(lig.GetAtoms()):
lig.GetCoords(atom, coord)
if not oeszmap.OEIsClashing(sz, coord):
oeszmap.OECalcSzmapResults(rslt, sz, coord)
rslt.PlaceNewAtom(points)
clear = False
rslt.PlaceProbeSet(probes, cumulativeProb, clear)
oechem.OEWriteMolecule(oms, points)
oechem.OEWriteMolecule(oms, probes)
def main(argv=(__name__)):
"""
the protein should have charges and radii but the ligand need not
"""
itf = oechem.OEInterface()
if not oechem.OEConfigure(itf, InterfaceData):
oechem.OEThrow.Fatal("Problem configuring OEInterface!")
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to parse command line")
ligFile = itf.GetString("-l")
ims = oechem.oemolistream()
if not ims.open(ligFile):
oechem.OEThrow.Fatal("Unable to open %s for reading" % ligFile)
lig = oechem.OEGraphMol()
oechem.OEReadMolecule(ims, lig)
contextFile = itf.GetString("-p")
ims = oechem.oemolistream()
if not ims.open(contextFile):
oechem.OEThrow.Fatal("Unable to open %s for reading" % contextFile)
prot = oechem.OEGraphMol()
oechem.OEReadMolecule(ims, prot)
RunSzmap(lig, prot)
GetSzmapEnergies(lig, prot)
outputFile = itf.GetString("-o")
oms = oechem.oemolostream()
if not oms.open(outputFile):
oechem.OEThrow.Fatal("Unable to open %s for writing" % outputFile)
GenerateSzmapProbes(oms, itf.GetDouble("-prob"), lig, prot)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 3: Analyze binding site energies.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
# analyze binding site energies with szmaptk
import sys
from openeye import oechem
from openeye import oeszmap
InterfaceData = """
!BRIEF SzmapEnergies.py [-high_res] [-du] <designunitfile>
!PARAMETER -du
!TYPE string
!BRIEF Input designunit
!REQUIRED true
!KEYLESS 1
!END
!PARAMETER -high_res
!TYPE bool
!DEFAULT false
!BRIEF If true, increase the number of rotations to 360
!REQUIRED false
!END
"""
def GetSzmapEnergies(lig, prot, highRes):
"""
run szmap at ligand coordinates in the protein context
@rtype : None
@param lig: mol defining coordinates for szmap calcs
@param prot: context mol for szmap calcs (must have charges and radii)
@param highRes: if true, use 360 rotations rather than the default of 60
"""
opt = oeszmap.OESzmapEngineOptions()
if highRes:
opt.SetProbe(360)
sz = oeszmap.OESzmapEngine(prot, opt)
coord = oechem.OEFloatArray(3)
rslt = oeszmap.OESzmapResults()
print("num\tatom\t%s\t%s\t%s\t%s\t%s"
% (oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_NeutralDiffDeltaG),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_PSolv),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_WSolv),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_VDW),
oeszmap.OEGetEnsembleName(oeszmap.OEEnsemble_OrderParam)))
for i, atom in enumerate(lig.GetAtoms()):
lig.GetCoords(atom, coord)
if not oeszmap.OEIsClashing(sz, coord):
oeszmap.OECalcSzmapResults(rslt, sz, coord)
print("%2d\t%s\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f"
% (i, atom.GetName(),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_NeutralDiffDeltaG),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_PSolv),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_WSolv),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_VDW),
rslt.GetEnsembleValue(oeszmap.OEEnsemble_OrderParam)))
else:
print("%2d\t%s CLASH" % (i, atom.GetName()))
def main(argv=(__name__)):
"""
the protein should have charges and radii but the ligand need not
"""
itf = oechem.OEInterface()
if not oechem.OEConfigure(itf, InterfaceData):
oechem.OEThrow.Fatal("Problem configuring OEInterface!")
if not oechem.OEParseCommandLine(itf, argv):
oechem.OEThrow.Fatal("Unable to parse command line")
duFile = itf.GetString("-du")
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(duFile, du):
oechem.OEThrow.Fatal("Unable to open %s for reading" % duFile)
if not du.HasLigand():
oechem.OEThrow.Fatal("Input designunit %s does not have a ligand bound" % du.GetTitle())
lig = oechem.OEGraphMol()
du.GetLigand(lig)
prot = oechem.OEGraphMol()
du.GetComponents(prot, oechem.OEDesignUnitComponents_Protein)
highRes = itf.GetBool("-high_res")
GetSzmapEnergies(lig, prot, highRes)
if __name__ == "__main__":
sys.exit(main(sys.argv))
Szybki Toolkit
The Szybki toolkit provides facilities for force-field-based optimization and thermodynamic property estimation of small molecule ligands or protein-ligand complexes with small molecule ligands. For a guide to programming examples, see the Szybki chapter.
Listing 1: Simple Ligand in a Vacuum.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args=[__name__]):
if len(args) != 3:
oechem.OEThrow.Usage("%s <molfile> <outfile>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OESzybkiOptions()
sz = oeszybki.OESzybki(opts)
results = oeszybki.OESzybkiResults()
if not sz(mol, results):
return 1
oechem.OEWriteMolecule(ofs, mol)
results.Print(oechem.oeout)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 2: Simple Ligand in a Vacuum Using SMIRNOFF.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args=[__name__]):
if len(args) != 3:
oechem.OEThrow.Usage("%s <molfile> <outfile>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OESzybkiOptions()
opts.GetGeneralOptions().SetForceFieldType(oeszybki.OEForceFieldType_SMIRNOFF99FROSST)
sz = oeszybki.OESzybki(opts)
results = oeszybki.OESzybkiResults()
if not sz(mol, results):
return 1
oechem.OEWriteMolecule(ofs, mol)
results.Print(oechem.oeout)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 3: Optimization of a Set of Ligands.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
itf = oechem.OEInterface()
if not SetupInterface(argv, itf):
return 1
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-in")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-in"))
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-out")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-out"))
logfile = oechem.oeout
if itf.HasString("-log"):
if not logfile.open(itf.GetString("-log")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-log"))
# Szybki options
opts = oeszybki.OESzybkiOptions()
# select run type
if itf.GetBool("-t"):
opts.SetRunType(oeszybki.OERunType_TorsionsOpt)
if itf.GetBool("-n"):
opts.SetRunType(oeszybki.OERunType_SinglePoint)
# apply solvent model
if itf.GetBool("-s"):
opts.GetSolventOptions().SetSolventModel(oeszybki.OESolventModel_Sheffield)
# remove attractive VdW forces
if itf.GetBool("-a"):
opts.GetGeneralOptions().SetRemoveAttractiveVdWForces(True)
# Szybki object
sz = oeszybki.OESzybki(opts)
# fix atoms
if itf.HasString("-f"):
if not sz.FixAtoms(itf.GetString("-f")):
oechem.OEThrow.Warning("Failed to fix atoms for %s" % itf.GetString("-f"))
# process molecules
mol = oechem.OEMol()
while oechem.OEReadMolecule(ifs, mol):
logfile.write("\nMolecule %s\n" % mol.GetTitle())
no_res = True
for results in sz(mol):
results.Print(logfile)
no_res = False
if no_res:
oechem.OEThrow.Warning("No results processing molecule: %s" % mol.GetTitle())
continue
else:
oechem.OEWriteMolecule(ofs, mol)
return 0
InterfaceData = """
!PARAMETER -in
!TYPE string
!REQUIRED true
!BRIEF Input molecule file name.
!END
!PARAMETER -out
!TYPE string
!REQUIRED true
!BRIEF Output molecule file name.
!END
!PARAMETER -log
!TYPE string
!REQUIRED false
!BRIEF Log file name. Defaults to standard out.
!END
!PARAMETER -s
!TYPE bool
!DEFAULT false
!REQUIRED false
!BRIEF Optimization in solution.
!END
!PARAMETER -t
!TYPE bool
!DEFAULT false
!REQUIRED false
!BRIEF Optimization of torsions.
!END
!PARAMETER -n
!TYPE bool
!DEFAULT false
!REQUIRED false
!BRIEF Single point calculation.
!END
!PARAMETER -a
!TYPE bool
!DEFAULT false
!REQUIRED false
!BRIEF No attractive VdW forces.
!END
!PARAMETER -f
!TYPE string
!REQUIRED false
!BRIEF SMARTS pattern of fixed atoms.
!END
"""
def SetupInterface(argv, itf):
oechem.OEConfigure(itf, InterfaceData)
if oechem.OECheckHelp(itf, argv):
return False
if not oechem.OEParseCommandLine(itf, argv):
return False
if not oechem.OEIsReadable(oechem.OEGetFileType(
oechem.OEGetFileExtension(itf.GetString("-in")))):
oechem.OEThrow.Warning("%s is not a readable input file" % itf.GetString("-in"))
return False
if not oechem.OEIsWriteable(oechem.OEGetFileType(
oechem.OEGetFileExtension(itf.GetString("-out")))):
oechem.OEThrow.Warning("%s is not a writable output file" % itf.GetString("-out"))
return False
return True
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 4: Optimization of a Single Ligand with the Newton-Raphson Method.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s input_molecule output_molecule" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OESzybkiOptions()
opts.GetOptOptions().SetOptimizerType(oeszybki.OEOptType_NEWTON)
opts.GetSolventOptions().SetSolventModel(oeszybki.OESolventModel_Sheffield)
sz = oeszybki.OESzybki(opts)
res = oeszybki.OESzybkiResults()
if (sz(mol, res)):
oechem.OEWriteMolecule(ofs, mol)
res.Print(oechem.oeout)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 5: Optimization of All Conformers of a Ligand.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oequacpac
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s input_molecule output_molecule" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
opts = oeszybki.OESzybkiOptions()
opts.GetOptOptions().SetOptimizerType(oeszybki.OEOptType_NEWTON)
opts.GetGeneralOptions().SetForceFieldType(oeszybki.OEForceFieldType_MMFF94S)
opts.GetSolventOptions().SetSolventModel(oeszybki.OESolventModel_Sheffield)
opts.GetSolventOptions().SetChargeEngine(oequacpac.OEChargeEngineNoOp())
sz = oeszybki.OESzybki(opts)
res = oeszybki.OESzybkiResults()
for mol in ifs.GetOEMols():
for conf in mol.GetConfs():
if sz(conf, res):
oechem.OESetSDData(conf, oechem.OESDDataPair('Total_energy', "%0.4f"
% res.GetTotalEnergy()))
oechem.OEWriteMolecule(ofs, mol)
ifs.close()
ofs.close()
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 6: Optimization of a Single Bound Ligand.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
if len(argv) != 4:
oechem.OEThrow.Usage("%s <molfile> <protein> <outfile>" % argv[0])
lfs = oechem.oemolistream()
if not lfs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
pfs = oechem.oemolistream()
if not pfs.open(argv[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[2])
ofs = oechem.oemolostream()
if not ofs.open(argv[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % argv[3])
mol = oechem.OEGraphMol()
oechem.OEReadMolecule(lfs, mol)
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(pfs, protein)
opts = oeszybki.OESzybkiOptions()
sz = oeszybki.OESzybki(opts)
sz.SetProtein(protein)
res = oeszybki.OESzybkiResults()
if not sz(mol, res):
return 1
oechem.OEWriteMolecule(ofs, mol)
res.Print(oechem.oeout)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 7: Optimization of a Set of Bound Ligands in a Rigid Receptor.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
itf = oechem.OEInterface(Interface, argv)
lfs = oechem.oemolistream()
if not lfs.open(itf.GetString("-in")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-in"))
pfs = oechem.oemolistream()
if not pfs.open(itf.GetString("-p")):
oechem.OEThrow.Fatal("Unable to open %s for reading", itf.GetString("-p"))
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-out")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-out"))
logfile = oechem.oeout
if itf.HasString("-log"):
if not logfile.open(itf.GetString("-log")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-log"))
# Szybki options
opts = oeszybki.OESzybkiOptions()
# select optimization type
if(itf.GetBool("-t")):
opts.SetRunType(oeszybki.OERunType_TorsionsOpt)
else:
opts.SetRunType(oeszybki.OERunType_CartesiansOpt)
# select protein-electrostatic model
emodel = itf.GetString("-e")
elecModel = oeszybki.OEProteinElectrostatics_NoElectrostatics
if emodel == "VdW":
elecModel = oeszybki.OEProteinElectrostatics_NoElectrostatics
elif emodel == "PB":
elecModel = oeszybki.OEProteinElectrostatics_GridPB
elif emodel == "Coulomb":
elecModel = oeszybki.OEProteinElectrostatics_GridCoulomb
elif emodel == "ExactCoulomb":
elecModel = oeszybki.OEProteinElectrostatics_ExactCoulomb
opts.GetProteinOptions().SetExactVdWProteinLigand(True)
opts.GetOptOptions().SetMaxIter(1000)
opts.GetOptOptions().SetGradTolerance(1e-6)
opts.GetProteinOptions().SetProteinElectrostaticModel(elecModel)
# Szybki object
sz = oeszybki.OESzybki(opts)
# read and setup protein
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(pfs, protein)
sz.SetProtein(protein)
# save or load grid potential
if(emodel == "PB" or emodel == "Coulomb"):
if(itf.HasString("-s")):
sz.SavePotentialGrid(itf.GetString("-s"))
if(itf.HasString("-l")):
sz.LoadPotentialGrid(itf.GetString("-l"))
# process molecules
for mol in lfs.GetOEMols():
logfile.write("\nMolecule %s\n" % mol.GetTitle())
no_res = True
for res in sz(mol):
res.Print(logfile)
no_res = False
if no_res:
oechem.OEThrow.Warning("No results processing molecule: %s" % mol.GetTitle())
continue
else:
oechem.OEWriteMolecule(ofs, mol)
return 0
Interface = """
!PARAMETER -in
!TYPE string
!REQUIRED true
!BRIEF Input molecule file name.
!END
!PARAMETER -p
!TYPE string
!REQUIRED true
!BRIEF Input protein file name.
!END
!PARAMETER -out
!TYPE string
!REQUIRED true
!BRIEF Output molecule file name.
!END
!PARAMETER -log
!TYPE string
!REQUIRED false
!BRIEF Log file name. Defaults to standard out.
!END
!PARAMETER -e
!TYPE string
!DEFAULT VdW
!LEGAL_VALUE VdW
!LEGAL_VALUE PB
!LEGAL_VALUE Coulomb
!LEGAL_VALUE ExactCoulomb
!BRIEF Protein ligand electrostatic model.
!END
!PARAMETER -t
!TYPE bool
!DEFAULT false
!REQUIRED false
!BRIEF Torsions added to the optimized variables.
!END
!PARAMETER -l
!TYPE string
!REQUIRED false
!BRIEF File name of the potential grid to be read.
!END
!PARAMETER -s
!TYPE string
!REQUIRED false
!BRIEF File name of the potential grid to be saved.
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 8: Optimization of a Set of Bound Ligands in a Partially Flexible Receptor.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
itf = oechem.OEInterface(Interface, argv)
lfs = oechem.oemolistream()
if not lfs.open(itf.GetString("-in")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-in"))
pfs = oechem.oemolistream()
if not pfs.open(itf.GetString("-p")):
oechem.OEThrow.Fatal("Unable to open %s for reading", itf.GetString("-p"))
olfs = oechem.oemolostream()
if not olfs.open(itf.GetString("-out")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-out"))
opfs = oechem.oemolostream()
if itf.HasString("-s"):
if not opfs.open(itf.GetString("-s")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-s"))
logfile = oechem.oeout
if itf.HasString("-log"):
if not logfile.open(itf.GetString("-log")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-log"))
# Szybki options
opts = oeszybki.OESzybkiOptions()
# select optimization type
opt = itf.GetString("-opt")
if opt == "Cartesian":
opts.SetRunType(oeszybki.OERunType_CartesiansOpt)
if opt == "Torsion":
opts.SetRunType(oeszybki.OERunType_TorsionsOpt)
if opt == "SolidBody":
opts.SetRunType(oeszybki.OERunType_SolidBodyOpt)
# select protein-electrostatic model
emodel = itf.GetString("-e")
elecModel = oeszybki.OEProteinElectrostatics_NoElectrostatics
if emodel == "VdW":
elecModel = oeszybki.OEProteinElectrostatics_NoElectrostatics
elif emodel == "PB":
elecModel = oeszybki.OEProteinElectrostatics_GridPB
elif emodel == "Coulomb":
elecModel = oeszybki.OEProteinElectrostatics_GridCoulomb
elif emodel == "ExactCoulomb":
elecModel = oeszybki.OEProteinElectrostatics_ExactCoulomb
opts.GetProteinOptions().SetProteinElectrostaticModel(elecModel)
# use smooth potential and tight convergence
if (emodel == "VdW" or emodel == "ExactCoulomb"):
opts.GetProteinOptions().SetExactVdWProteinLigand(True)
opts.GetOptOptions().SetMaxIter(1000)
opts.GetOptOptions().SetGradTolerance(1e-6)
# protein flexibility
opts.GetProteinOptions().SetProteinFlexibilityType(oeszybki.OEProtFlex_SideChains)
opts.GetProteinOptions().SetProteinFlexibilityRange(itf.GetDouble("-d"))
# Szybki object
sz = oeszybki.OESzybki(opts)
# read and setup protein
protein = oechem.OEGraphMol()
oprotein = oechem.OEGraphMol() # optimized protein
oechem.OEReadMolecule(pfs, protein)
sz.SetProtein(protein)
# process molecules
for mol in lfs.GetOEMols():
logfile.write("\nMolecule %s\n" % mol.GetTitle())
for res in sz(mol):
res.Print(logfile)
oechem.OEWriteMolecule(olfs, mol)
if itf.HasString("-s"):
sz.GetProtein(oprotein)
oechem.OEWriteMolecule(opfs, oprotein)
return 0
Interface = """
!BRIEF -in input_molecule -p protein -out output_molecule
!PARAMETER -in
!TYPE string
!REQUIRED true
!BRIEF Input molecule file name.
!END
!PARAMETER -p
!TYPE string
!REQUIRED true
!BRIEF Input protein file name.
!END
!PARAMETER -out
!TYPE string
!REQUIRED true
!BRIEF Output molecule file name.
!END
!PARAMETER -log
!TYPE string
!REQUIRED false
!BRIEF Log file name. Defaults to standard out.
!END
!PARAMETER -e
!TYPE string
!DEFAULT VdW
!LEGAL_VALUE VdW
!LEGAL_VALUE PB
!LEGAL_VALUE Coulomb
!LEGAL_VALUE ExactCoulomb
!BRIEF Protein ligand electrostatic model.
!END
!PARAMETER -opt
!TYPE string
!DEFAULT Cartesian
!LEGAL_VALUE Cartesian
!LEGAL_VALUE Torsion
!LEGAL_VALUE SolidBody
!BRIEF Optimization method
!END
!PARAMETER -d
!TYPE double
!DEFAULT 5.0
!BRIEF Distance criteria from protein side-chains flexibility.
!END
!PARAMETER -s
!TYPE string
!REQUIRED false
!BRIEF File name the partially optimized protein will be saved.
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 9: Optimization of a Bound Ligand in a Partially Flexible Receptor.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
itf = oechem.OEInterface(Interface, argv)
ifs = oechem.oemolistream()
if not ifs.open(itf.GetString("-in")):
oechem.OEThrow.Fatal("Unable to open %s for reading" % itf.GetString("-in"))
pfs = oechem.oemolistream()
if not pfs.open(itf.GetString("-protein")):
oechem.OEThrow.Fatal("Unable to open %s for reading", itf.GetString("-protein"))
ofs = oechem.oemolostream()
if not ofs.open(itf.GetString("-outl")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-outl"))
opfs = oechem.oemolostream()
if not opfs.open(itf.GetString("-outp")):
oechem.OEThrow.Fatal("Unable to open %s for writing" % itf.GetString("-outp"))
ligand = oechem.OEGraphMol()
oechem.OEReadMolecule(ifs, ligand)
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(pfs, protein)
# Szybki options
opts = oeszybki.OESzybkiOptions()
opts.SetRunType(oeszybki.OERunType_CartesiansOpt)
opts.GetOptOptions().SetMaxIter(2000)
opts.GetOptOptions().SetGradTolerance(1e-6)
opts.GetGeneralOptions().SetForceFieldType(oeszybki.OEForceFieldType_MMFF94S)
opts.GetProteinOptions().SetProteinFlexibilityType(oeszybki.OEProtFlex_SideChainsList)
opts.GetProteinOptions().SetProteinElectrostaticModel(
oeszybki.OEProteinElectrostatics_ExactCoulomb)
res_num = []
for res in itf.GetStringList('-residues'):
intres = None
try:
intres = int(res)
except ValueError:
print('Illegal residue value: {}'.format(res))
if intres is None:
continue
res_num.append(intres)
for i in res_num:
for atom in protein.GetAtoms():
residue = oechem.OEAtomGetResidue(atom)
if(residue.GetResidueNumber() == i):
opts.AddFlexibleResidue(residue)
break
sz = oeszybki.OESzybki(opts)
sz.SetProtein(protein)
result = oeszybki.OESzybkiResults()
sz(ligand, result)
sz.GetProtein(protein)
oechem.OEWriteMolecule(opfs, protein)
oechem.OEWriteMolecule(ofs, ligand)
return 0
Interface = """
!BRIEF -in ligand -protein protein -outl output_ligand -outp output_protein -residues r1 r2 ... rn
!PARAMETER -in
!TYPE string
!REQUIRED true
!BRIEF Input ligand file name.
!END
!PARAMETER -protein
!TYPE string
!REQUIRED true
!BRIEF Input protein file name.
!END
!PARAMETER -outl
!TYPE string
!REQUIRED true
!BRIEF Output ligand file name.
!END
!PARAMETER -outp
!TYPE string
!REQUIRED true
!BRIEF Output protein file name.
!END
!PARAMETER -residues
!TYPE string
!LIST true
!REQUIRED true
!BRIEF List of residues numbers to be optimized along with the ligand
!END
"""
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 10: Estimation of PB Binding for a Set of Ligands.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 4:
oechem.OEThrow.Usage("%s ligand_file protein_file output_file (SDF or OEB)" % args[0])
lfs = oechem.oemolistream()
if not lfs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
pfs = oechem.oemolistream()
if not pfs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[2])
ofs = oechem.oemolostream()
if not ofs.open(args[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[3])
if not oechem.OEIsSDDataFormat(ofs.GetFormat()):
oechem.OEThrow.Fatal("Output file does not support SD data used by this example")
# Szybki options for VdW-Coulomb calculations
optsC = oeszybki.OESzybkiOptions()
optsC.GetProteinOptions().SetProteinElectrostaticModel(
oeszybki.OEProteinElectrostatics_ExactCoulomb)
optsC.SetRunType(oeszybki.OERunType_CartesiansOpt)
# Szybki options for PB calculations
optsPB = oeszybki.OESzybkiOptions()
optsPB.GetProteinOptions().SetProteinElectrostaticModel(
oeszybki.OEProteinElectrostatics_SolventPBForces)
optsPB.SetRunType(oeszybki.OERunType_SinglePoint)
# Szybki objects
szC = oeszybki.OESzybki(optsC)
szPB = oeszybki.OESzybki(optsPB)
# read and setup protein
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(pfs, protein)
szC.SetProtein(protein)
szPB.SetProtein(protein)
terms = set([oeszybki.OEPotentialTerms_ProteinLigandInteraction,
oeszybki.OEPotentialTerms_VdWProteinLigand,
oeszybki.OEPotentialTerms_CoulombProteinLigand,
oeszybki.OEPotentialTerms_ProteinDesolvation,
oeszybki.OEPotentialTerms_LigandDesolvation,
oeszybki.OEPotentialTerms_SolventScreening])
# process molecules
for mol in lfs.GetOEMols():
# optimize mol
if not list(szC(mol)):
oechem.OEThrow.Warning("No results processing molecule: %s" % mol.GetTitle())
continue
# do single point with better electrostatics
for conf, results in zip(mol.GetConfs(), szPB(mol)):
for i in terms:
strEnergy = ("%9.4f" % results.GetEnergyTerm(i))
oechem.OEAddSDData(conf, oeszybki.OEGetEnergyTermName(i), strEnergy)
oechem.OEWriteMolecule(ofs, mol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 11: Optimization of a Bound Ligand Using Newton-Raphson Method.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 4:
oechem.OEThrow.Usage("%s protein input_ligand output_ligand" % args[0])
pfs = oechem.oemolistream()
if not pfs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
lfs = oechem.oemolistream()
if not lfs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[2])
ofs = oechem.oemolostream()
if not ofs.open(args[3]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[3])
mol = oechem.OEGraphMol()
protein = oechem.OEGraphMol()
oechem.OEReadMolecule(lfs, mol)
oechem.OEReadMolecule(pfs, protein)
opts = oeszybki.OESzybkiOptions()
opts.GetOptOptions().SetOptimizerType(oeszybki.OEOptType_NEWTON)
opts.GetProteinOptions().SetProteinElectrostaticModel(
oeszybki.OEProteinElectrostatics_ExactCoulomb)
opts.GetProteinOptions().SetProteinFlexibilityType(oeszybki.OEProtFlex_Residues)
opts.GetProteinOptions().SetProteinFlexibilityRange(2.0)
sz = oeszybki.OESzybki(opts)
sz.SetProtein(protein)
res = oeszybki.OESzybkiResults()
if (sz(mol, res)):
oechem.OEWriteMolecule(ofs, mol)
res.Print(oechem.oeout)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 12: Optimization of Ligand in a Rigid Active Site.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
szOpts = oeszybki.OEProteinLigandOptOptions()
opts = oechem.OERefInputAppOptions(szOpts, "OptimizeLigandInDU", oechem.OEFileStringType_Mol3D,
oechem.OEFileStringType_Mol3D, oechem.OEFileStringType_DU, "-du")
if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
return 0
szOpts.UpdateValues(opts)
ifs = oechem.oemolistream()
if not ifs.open(opts.GetInFile()):
oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
rfs = oechem.oeifstream()
if not rfs.open(opts.GetRefFile()):
oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetRefFile())
ofs = oechem.oemolostream()
if not ofs.open(opts.GetOutFile()):
oechem.OEThrow.Fatal("Unable to open %s for writing" % opts.GetOutFile())
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(rfs, du):
oechem.OEThrow.Fatal("Failed to read design unit")
optimizer = oeszybki.OEFixedProteinLigandOptimizer(szOpts)
optimizer.SetProtein(du, oechem.OEDesignUnitComponents_Protein)
for mol in ifs.GetOEMols():
oechem.OEThrow.Info("Title: %s" % mol.GetTitle())
conf = 0
for res in optimizer.Optimize(mol):
conf += 1
if res.GetReturnCode() == oeszybki.OESzybkiReturnCode_Success:
oechem.OEThrow.Info("Conformer: %d" % conf)
initEne = res.GetInitialEnergies()
oechem.OEThrow.Info("Initial energies:")
oechem.OEThrow.Info(" Ligand: %0.2f" % initEne.GetLigandEnergy())
oechem.OEThrow.Info(" Intermolecular: %0.2f" % initEne.GetInterEnergy())
oechem.OEThrow.Info(" Total: %0.2f" % initEne.GetTotalEnergy())
finalEne = res.GetFinalEnergies()
oechem.OEThrow.Info("Final energies:")
oechem.OEThrow.Info(" Ligand: %0.2f" % finalEne.GetLigandEnergy())
oechem.OEThrow.Info(" Intermolecular: %0.2f" % finalEne.GetInterEnergy())
oechem.OEThrow.Info(" Total: %0.2f" % finalEne.GetTotalEnergy())
oechem.OEThrow.Info("Ligand Strain: %0.2f" % res.GetLigandLocalStrain())
else:
oechem.OEThrow.Warning("Failed: %s" % oeszybki.OEGetSzybkiError(res.GetReturnCode()))
oechem.OEWriteMolecule(ofs, mol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 13: Optimization of Ligand in a Partially Flexible Active Site.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
class MyOptions(oechem.OEOptions):
def __init__(self):
oechem.OEOptions.__init__(self, "MyOption")
self._optOpts = oeszybki.OEProteinLigandOptOptions()
self._flexOpts = oeszybki.OEProteinFlexOptions()
self.AddOption(self._optOpts)
self.AddOption(self._flexOpts)
pass
def CreateCopy(self):
return self
def GetOptOptions(self):
return self._optOpts
def GetFlexOptions(self):
return self._flexOpts
def main(argv=[__name__]):
myOpts = MyOptions()
opts = oechem.OESimpleAppOptions(myOpts, "OptimizeDU", oechem.OEFileStringType_DU, oechem.OEFileStringType_DU)
if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
return 0
optOpts = myOpts.GetOptOptions()
flexOpts = myOpts.GetFlexOptions()
optOpts.UpdateValues(opts)
flexOpts.UpdateValues(opts)
ifs = oechem.oeifstream()
if not ifs.open(opts.GetInFile()):
oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
ofs = oechem.oeofstream()
if not ofs.open(opts.GetOutFile()):
oechem.OEThrow.Fatal("Unable to open %s for writing" % opts.GetOutFile())
optimizer = oeszybki.OEFlexProteinLigandOptimizer(optOpts)
du = oechem.OEDesignUnit()
while oechem.OEReadDesignUnit(ifs, du):
oechem.OEThrow.Info("Title: %s" % du.GetTitle())
res = oeszybki.OEProteinLigandOptResults()
proteinMask = oechem.OEDesignUnitComponents_Protein
retCode = optimizer.Optimize(res, du, proteinMask, oechem.OEDesignUnitComponents_Ligand, flexOpts)
if retCode == oeszybki.OESzybkiReturnCode_Success:
initEne = res.GetInitialEnergies()
oechem.OEThrow.Info("Initial energies:")
oechem.OEThrow.Info(" Ligand: %0.2f" % initEne.GetLigandEnergy())
oechem.OEThrow.Info(" Flexible Protein: %0.2f" % initEne.GetHostEnergy())
oechem.OEThrow.Info(" Intermolecular: %0.2f" % initEne.GetInterEnergy())
oechem.OEThrow.Info(" Total: %0.2f" % initEne.GetTotalEnergy())
finalEne = res.GetFinalEnergies()
oechem.OEThrow.Info("Final energies:")
oechem.OEThrow.Info(" Ligand: %0.2f" % finalEne.GetLigandEnergy())
oechem.OEThrow.Info(" Flexible Protein: %0.2f" % finalEne.GetHostEnergy())
oechem.OEThrow.Info(" Intermolecular: %0.2f" % finalEne.GetInterEnergy())
oechem.OEThrow.Info(" Total: %0.2f" % finalEne.GetTotalEnergy())
oechem.OEThrow.Info("Ligand Strain: %0.2f" % res.GetLigandLocalStrain())
oechem.OEWriteDesignUnit(ofs, du)
else:
oechem.OEThrow.Warning("%s: %s" % (du.GetTitle(), oeszybki.OEGetSzybkiError(retCode)))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 14: Ligand Entropy.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
szOpts = oeszybki.OELigandEntropyOptions()
opts = oechem.OESimpleAppOptions(szOpts, "LigandEntropy", oechem.OEFileStringType_Mol3D)
if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
return 0
szOpts.UpdateValues(opts)
ifs = oechem.oemolistream()
if not ifs.open(opts.GetInFile()):
oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
for mol in ifs.GetOEMols():
oechem.OEThrow.Info("Title: %s" % mol.GetTitle())
res = oeszybki.OEEntropyResults()
ret_code = oeszybki.OELigandEntropy(res, mol, szOpts)
if ret_code == oeszybki.OESzybkiReturnCode_Success:
oechem.OEThrow.Info(" Configurational Entropy: %0.2f" % res.GetConfigurationalEntropy())
oechem.OEThrow.Info(" Solvation Entropy: %0.2f" % res.GetSolvationEntropy())
oechem.OEThrow.Info(" Total Entropy: %0.2f" % res.GetTotalEntropy())
else:
oechem.OEThrow.Warning("Failed: %s" % oeszybki.OEGetSzybkiError(ret_code))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 15: Estimation of Bound Ligand Entropy
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(argv=[__name__]):
szOpts = oeszybki.OEBoundEntropyOptions()
opts = oechem.OERefInputAppOptions(szOpts, "BoundEntropy", oechem.OEFileStringType_Mol3D,
oechem.OEFileStringType_DU, "-du")
if oechem.OEConfigureOpts(opts, argv, False) == oechem.OEOptsConfigureStatus_Help:
return 0
szOpts.UpdateValues(opts)
ifs = oechem.oemolistream()
if not ifs.open(opts.GetInFile()):
oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetInFile())
rfs = oechem.oeifstream()
if not rfs.open(opts.GetRefFile()):
oechem.OEThrow.Fatal("Unable to open %s for reading" % opts.GetRefFile())
du = oechem.OEDesignUnit()
if not oechem.OEReadDesignUnit(rfs, du):
oechem.OEThrow.Fatal("Failed to read design unit")
for mol in ifs.GetOEMols():
oechem.OEThrow.Info("Title: %s" % mol.GetTitle())
res = oeszybki.OEEntropyResults()
ret_code = oeszybki.OEBoundLigandEntropy(res, du, oechem.OEDesignUnitComponents_Protein, mol, szOpts)
if ret_code == oeszybki.OESzybkiReturnCode_Success:
oechem.OEThrow.Info(" Configurational Entropy: %0.2f" % res.GetConfigurationalEntropy())
oechem.OEThrow.Info(" Solvation Entropy: %0.2f" % res.GetSolvationEntropy())
oechem.OEThrow.Info(" Total Entropy: %0.2f" % res.GetTotalEntropy())
else:
oechem.OEThrow.Warning("Failed: %s" % oeszybki.OEGetSzybkiError(ret_code))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 16: Solvation Free Energy Estimation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s <input> <output>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OEFreeFormSolvOptions()
opts.SetIonicState(oeszybki.OEFreeFormIonicState_Uncharged)
res = oeszybki.OEFreeFormSolvResults()
omol = oechem.OEGraphMol()
if not oeszybki.OEEstimateSolvFreeEnergy(res, omol, mol, opts):
oechem.OEThrow.Error("Failed to calculate solvation free energy for molecule %s" %
mol.GetTitle())
solvenergy = res.GetSolvationFreeEnergy()
oechem.OEThrow.Info("Solvation free energy for compound %s is %6.2f kcal/mol" %
(mol.GetTitle(), solvenergy))
oechem.OEWriteMolecule(ofs, omol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 17: Simple Free Energy Estimation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s <input> <output>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OEFreeFormConfOptions()
ffconf = oeszybki.OEFreeFormConf(opts)
omol = oechem.OEMol(mol)
if not (ffconf.EstimateFreeEnergies(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Failed to estimate conformational free energies")
res = oeszybki.OEFreeFormConfResults(omol)
oechem.OEThrow.Info("Number of unique conformations: %d" % res.GetNumUniqueConfs())
oechem.OEThrow.Info("Conf. Delta_G Vibrational_Entropy")
oechem.OEThrow.Info(" [kcal/mol] [J/(mol K)]")
for r in res.GetResultsForConformations():
oechem.OEThrow.Info("%2d %10.2f %14.2f" % (r.GetConfIdx(), r.GetDeltaG(),
r.GetVibrationalEntropy()))
oechem.OEWriteMolecule(ofs, omol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 18: Simple Restriction Energy Estimation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s <input> <output>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OEFreeFormConfOptions()
ffconf = oeszybki.OEFreeFormConf(opts)
omol = oechem.OEMol(mol)
rmol = oechem.OEMol(mol)
if not (ffconf.EstimateFreeEnergies(omol, rmol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Failed to estimate conformational free energies")
res = oeszybki.OEFreeFormConfResults(omol)
oechem.OEThrow.Info("Number of unique conformations: %d" % res.GetNumUniqueConfs())
oechem.OEThrow.Info("Conf. Delta_G Vibrational_Entropy")
oechem.OEThrow.Info(" [kcal/mol] [J/(mol K)]")
for r in res.GetResultsForConformations():
oechem.OEThrow.Info("%2d %10.2f %14.2f" % (r.GetConfIdx(), r.GetDeltaG(),
r.GetVibrationalEntropy()))
rstrRes = oeszybki.OERestrictionEnergyResult(rmol)
oechem.OEThrow.Info("Global strain: %d" % rstrRes.GetGlobalStrain())
oechem.OEThrow.Info("Local strain: %d" % rstrRes.GetLocalStrain())
oechem.OEWriteMolecule(ofs, omol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 19: Advanced Free Energy Estimation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s <input> <output>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OEFreeFormConfOptions()
ffconf = oeszybki.OEFreeFormConfAdvanced(opts)
# Make a copy of our MCMol. We will execute the FreeFormConf commands on
# the copied molecule so that our original molecule stays intact.
omol = oechem.OEMol(mol)
# Prepare a comprehensive ensemble of molecule conformers. This will
# generate a comprehensive set of conformers, assign solvent charges on the molecule
# and check that the ensemble is otherwise ready for FreeFormConf calculations.
if not (ffconf.PrepareEnsemble(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Failed to prepare ensemble for FreeFormConf calculations")
# Perform loose optimization of the ensemble conformers. We will remove
# duplicates based on the loose optimization, to reduce the time needed for
# tighter, more stricter optimization
if not (ffconf.PreOptimizeEnsemble(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Pre-optimization of the ensembles failed")
# Remove duplicates from the pre-optimized ensemble
if not (ffconf.RemoveDuplicates(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Duplicate removal from the ensembles failed")
# Perform the desired optimization. This uses a stricter convergence
# criteria in the default settings.
if not (ffconf.Optimize(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Optimization of the ensembles failed")
# Remove duplicates to obtain the set of minimum energy conformers
if not (ffconf.RemoveDuplicates(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Duplicate removal from the ensembles failed")
# Perform FreeFormConf free energy calculations. When all the above steps
# have already been performed on the ensemble, this energy calculation
# step is fast.
if not (ffconf.EstimateEnergies(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Estimation of FreeFormConf energies failed")
# Gather results of calculation into a results object for ease of viewing, etc.
res = oeszybki.OEFreeFormConfResults(omol)
oechem.OEThrow.Info("Number of unique conformations: %d" % res.GetNumUniqueConfs())
oechem.OEThrow.Info("Conf. Delta_G Vibrational_Entropy")
oechem.OEThrow.Info(" [kcal/mol] [J/(mol K)]")
for r in res.GetResultsForConformations():
oechem.OEThrow.Info("%2d %10.2f %14.2f" % (r.GetConfIdx(), r.GetDeltaG(),
r.GetVibrationalEntropy()))
oechem.OEWriteMolecule(ofs, omol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 20: Advanced Restriction Energy Estimation
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s <input> <output>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OEFreeFormConfOptions()
ffconf = oeszybki.OEFreeFormConfAdvanced(opts)
# Make a copy of our MCMol. We will execute the FreeFormConf commands on
# the copied molecule so that our original molecule stays intact.
omol = oechem.OEMol(mol)
# Make further copies of our original molecule. The copied molecule(s) would be used
# as source on which retriction energies would be calculated
rmol = oechem.OEMol(mol)
fmol = oechem.OEMol(mol)
# Prepare a comprehensive ensemble of molecule conformers. For calculation
# of restriction energies we want to make sure that all the corresponding free
# conformers are also part of the comprehensive ensemble. This will also
# assign solvent charges on the molecule and check that the ensemble is
# otherwise ready for FreeFormConf calculations. The resulting `fmol`
# contains the correspondig free conformers.
if not (ffconf.PrepareEnsemble(omol, rmol, fmol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Failed to prepare ensemble for FreeFormConf calculations")
# Perform loose optimization of the ensemble conformers. We will remove
# duplicates based on the loose optimization, to reduce the time needed for
# tighter, more stricter optimization
if not (ffconf.PreOptimizeEnsemble(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Pre-optimization of the ensembles failed")
# Remove duplicates from the pre-optimized ensemble
if not (ffconf.RemoveDuplicates(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Duplicate removal from the ensembles failed")
# Perform the desired optimization. This uses a stricter convergence
# criteria in the default settings.
if not (ffconf.Optimize(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Optimization of the ensembles failed")
# Remove duplicates to obtain the set of minimum energy conformers
if not (ffconf.RemoveDuplicates(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Duplicate removal from the ensembles failed")
# Perform FreeFormConf free energy calculations. When all the above steps
# have already been performed on the ensemble, this energy calculation
# step is fast.
if not (ffconf.EstimateEnergies(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Estimation of FreeFormConf energies failed")
# Gather results of calculation into a results object for ease of viewing, etc.
res = oeszybki.OEFreeFormConfResults(omol)
oechem.OEThrow.Info("Number of unique conformations: %d" % res.GetNumUniqueConfs())
oechem.OEThrow.Info("Conf. Delta_G Vibrational_Entropy")
oechem.OEThrow.Info(" [kcal/mol] [J/(mol K)]")
for r in res.GetResultsForConformations():
oechem.OEThrow.Info("%2d %10.2f %14.2f" % (r.GetConfIdx(), r.GetDeltaG(),
r.GetVibrationalEntropy()))
# Identify the corresponding conformer(s) to the free minimized conformer(s).
# If identified, the corresponding (Conf)Free energy information is also
# copied to the free conformers
if not (ffconf.IdentifyConformer(fmol, omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Identification of free conformer(s) failed")
# Estimate restriction energies. Since both restricted and free conformer
# energy components are already available, this operation is fast.
if not (ffconf.EstimateRestrictionEnergy(fmol, rmol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Restriction energy estimation failed")
# Gather restriction energies into a results object for ease of viewing, etc.
rstrRes = oeszybki.OERestrictionEnergyResult(fmol)
oechem.OEThrow.Info("Global strain: %f" % rstrRes.GetGlobalStrain())
oechem.OEThrow.Info("Local strain: %f" % rstrRes.GetLocalStrain())
# Optionally it is desired to perform a restrained optimization of the
# restricted conformer(s) to brush out any energy differences due to
# force field constaints or the sources of coonformer coordinates. Note: The
# high level EstimateFreeEnergy method does not perform this opertion.
if not (ffconf.OptimizeRestraint(rmol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Restraint optimization of the conformer(s) failed")
# Estimate restriction energies on this optimized conformers.
# Since both restricted and free conformer energy components
# are already available, this operation is fast.
if not (ffconf.EstimateRestrictionEnergy(fmol, rmol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Restriction energy estimation failed")
# Gather restriction energies into a results object for ease of viewing, etc.
rstrRes = oeszybki.OERestrictionEnergyResult(fmol)
oechem.OEThrow.Info("Global strain: %f" % rstrRes.GetGlobalStrain())
oechem.OEThrow.Info("Local strain: %f" % rstrRes.GetLocalStrain())
oechem.OEWriteMolecule(ofs, omol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 21: Finding Similar Conformers
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
def main(args):
if len(args) != 3:
oechem.OEThrow.Usage("%s <input> <output>" % args[0])
ifs = oechem.oemolistream()
if not ifs.open(args[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % args[1])
ofs = oechem.oemolostream()
if not ofs.open(args[2]):
oechem.OEThrow.Fatal("Unable to open %s for writing" % args[2])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
opts = oeszybki.OEFreeFormConfOptions()
ffconf = oeszybki.OEFreeFormConf(opts)
# Estimate free energies to ontain the minimum energy conformers
omol = oechem.OEMol(mol)
if not (ffconf.EstimateFreeEnergies(omol) == oeszybki.OEFreeFormReturnCode_Success):
oechem.OEThrow.Error("Failed to estimate conformational free energies")
# Find similar conformers to the ones we started with, from the
# pool of minimum energy conformers
fmol = oechem.OEMol(mol)
for conf in mol.GetConfs():
ffconf.FindSimilarConfs(fmol, omol, conf, oechem.OESimilarByRMSD(0.05))
oechem.OEWriteMolecule(ofs, fmol)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
Listing 22: Perform torsion scan for all torsions in the input molecule
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oeszybki
###############################################################
# USED TO GENERATE CODE SNIPPETS FOR THE SZYBKI DOCUMENTATION
###############################################################
def main(argv=sys.argv):
if len(argv) != 2:
oechem.OEThrow.Usage("%s <infile>" % argv[0])
ifs = oechem.oemolistream()
if not ifs.open(argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading" % argv[1])
mol = oechem.OEMol()
oechem.OEReadMolecule(ifs, mol)
outmol = oechem.OEMol()
opts = oeszybki.OETorsionScanOptions()
opts.SetDelta(30.0)
opts.SetForceFieldType(oeszybki.OEForceFieldType_MMFF94)
opts.SetSolvationType(oeszybki.OESolventModel_NoSolv)
for tor in oechem.OEGetTorsions(mol):
print("Torsion: %d %d %d %d" %
(tor.a.GetIdx(), tor.b.GetIdx(), tor.c.GetIdx(), tor.d.GetIdx()))
for res in oeszybki.OETorsionScan(outmol, mol, tor, opts):
print("%.2f %.2f" % (res.GetAngle(), res.GetEnergy()))
if __name__ == "__main__":
sys.exit(main(sys.argv))
Zap Toolkit
The Zap toolkit Zap TK produces Poisson-Boltzmann electrostatic potentials and, from them, biologically interesting properties including solvent transfer energies, binding energies, pKa shifts, solvent forces, electrostatic descriptors, surface potentials, and effective dielectric constants. Programming examples are dispersed among the descriptions of parts of the toolkits and in the overall chapter The Way of Zap. Full listings are provided here for examples that are presented as incomplete snippets in the Zap chapters.
Listing 1: OEBind.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oezap
def ReadMolecule(filename):
mol = oechem.OEGraphMol()
ifs = oechem.oemolistream()
if not ifs.open(filename):
oechem.OEThrow.Fatal("Unable to open %s for reading", filename)
if not oechem.OEIs3DFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
if not oechem.OEReadMolecule(ifs, mol):
oechem.OEThrow.Fatal("Unable to read a molecule from %s", filename)
return mol
if len(sys.argv) != 3:
oechem.OEThrow.Usage("%s <protein> <ligand>" % sys.argv[0])
protein = ReadMolecule(sys.argv[1])
ligand = ReadMolecule(sys.argv[2])
bind = oezap.OEBind()
bind.SetProtein(protein)
results = oezap.OEBindResults()
bind.Bind(ligand, results)
results.Print(oechem.OEThrow)
bind = oezap.OEBind()
bind.GetZap().SetGridSpacing(0.6)
Listing 2: OEArea_GetArea.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
import sys
from openeye import oechem
from openeye import oezap
if len(sys.argv) != 2:
oechem.OEThrow.Usage("%s <molfile>" % sys.argv[0])
mol = oechem.OEGraphMol()
ifs = oechem.oemolistream()
if not ifs.open(sys.argv[1]):
oechem.OEThrow.Fatal("Unable to open %s for reading", sys.argv[1])
if not oechem.OEIs3DFormat(ifs.GetFormat()):
oechem.OEThrow.Fatal("Invalid input format: need 3D coordinates")
oechem.OEReadMolecule(ifs, mol)
oechem.OEAssignBondiVdWRadii(mol)
oechem.OEMMFFAtomTypes(mol)
oechem.OEMMFF94PartialCharges(mol)
area = oezap.OEArea()
a = area.GetArea(mol)
print("Molecule area =", a)
atomArea = oechem.OEFloatArray(mol.GetMaxAtomIdx())
area = oezap.OEArea()
area.GetArea(mol, atomArea)
for atom in mol.GetAtoms():
idx = atom.GetIdx()
print(idx, atomArea[idx])
area = oezap.OEArea()
for res in oechem.OEGetResidues(mol):
print (area.GetArea(mol, res))
atomArea = oechem.OEFloatArray(mol.GetMaxAtomIdx())
area = oezap.OEArea()
area.GetArea(mol, atomArea)
for res in oechem.OEGetResidues(mol):
print (area.GetArea(mol, atomArea, res))
Listing 3: DelPhiFlavor.py full listing.
#!/usr/bin/env python
# (C) 2022 Cadence Design Systems, Inc. (Cadence)
# All rights reserved.
# TERMS FOR USE OF SAMPLE CODE The software below ("Sample Code") is
# provided to current licensees or subscribers of Cadence products or
# SaaS offerings (each a "Customer").
# Customer is hereby permitted to use, copy, and modify the Sample Code,
# subject to these terms. Cadence claims no rights to Customer's
# modifications. Modification of Sample Code is at Customer's sole and
# exclusive risk. Sample Code may require Customer to have a then
# current license or subscription to the applicable Cadence offering.
# THE SAMPLE CODE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT
# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall Cadence be
# liable for any damages or liability in connection with the Sample Code
# or its use.
from openeye import oechem
ifs = oechem.oemolistream()
ifs.SetFlavor(oechem.OEFormat_PDB, oechem.OEIFlavor_PDB_Default | oechem.OEIFlavor_PDB_DELPHI)