rdkit.Dbase.DbReport

Package rdkit :: Package Dbase :: Module DbReport |
[hide private]
[frames] | no frames]

# Source Code for Module rdkit.Dbase.DbReport

      1  # $Id: DbReport.py 997 2009-02-25 06:12:43Z glandrum $
      2  #
      3  #  Copyright (C) 2003-2006  Rational Discovery LLC
      4  #
      5  #   @@ All Rights Reserved  @@
      6  #
      7  try:
      8    from reportlab import platypus
      9  except ImportError:
     10    import sys
     11    sys.stderr.write('ReportLab module could not be imported.  Db->PDF functionality not available')
     12    GetReportlabTable = None
     13    QuickReport = None
     14  else:
     15    from rdkit import Chem
     16    try:
     17      from pyRDkit.utils import chemdraw
     18    except ImportError:
     19      hasCDX=0
     20    else:
     21      hasCDX=1
     22    from rdkit.utils import cactvs
     23    from rdkit.Chem import rdDepictor
     24    from rdkit.Chem.Draw import DrawUtils
     25    from rdkit.Dbase.DbConnection import DbConnect
     26    from rdkit.Dbase import DbInfo
     27    from rdkit.Reports.PDFReport import PDFReport,ReportUtils
     28    import os,tempfile,sys
     29
     30 -  def GetReportlabTable(self,*args,**kwargs):
     31      """ this becomes a method of DbConnect  """
     32      dbRes = self.GetData(*args,**kwargs)
     33      rawD = [dbRes.GetColumnNames()]
     34      colTypes = dbRes.GetColumnTypes()
     35      binCols = []
     36      for i in range(len(colTypes)):
     37        if colTypes[i] in DbInfo.sqlBinTypes or colTypes[i]=='binary':
     38          binCols.append(i)
     39      nRows = 0
     40      for entry in dbRes:
     41        nRows += 1
     42        for col in binCols:
     43          entry = list(entry)
     44          entry[col] = 'N/A'
     45        rawD.append(entry)
     46        #if nRows >10: break
     47
     48      res = platypus.Table(rawD)
     49      return res
     50
     51    from reportlab.lib.units import inch
     52 -  class CDXImageTransformer(object):
     53 -    def __init__(self,smiCol,width=1,verbose=1,tempHandler=None):
     54        self.smiCol = smiCol
     55        if tempHandler is None:
     56          tempHandler = ReportUtils.TempFileHandler()
     57        self.tempHandler = tempHandler
     58        self.width = width*inch
     59        self.verbose=verbose
     60 -    def __call__(self,arg):
     61        res = list(arg)
     62        if self.verbose:
     63          print 'Render:',res[0]
     64        if hasCDX:
     65          smi = res[self.smiCol]
     66          tmpName = self.tempHandler.get('.jpg')
     67          try:
     68            img = chemdraw.SmilesToPilImage(smi)
     69            w,h = img.size
     70            aspect = float(h)/w
     71            img.save(tmpName)
     72            img = platypus.Image(tmpName)
     73            img.drawWidth = self.width
     74            img.drawHeight = aspect*self.width
     75            res[self.smiCol] = img
     76          except:
     77            import traceback
     78            traceback.print_exc()
     79            res[self.smiCol] = 'Failed'
     80        return res
     81
     82 -  class CactvsImageTransformer(object):
     83 -    def __init__(self,smiCol,width=1.,verbose=1,tempHandler=None):
     84        self.smiCol = smiCol
     85        if tempHandler is None:
     86          tempHandler = ReportUtils.TempFileHandler()
     87        self.tempHandler = tempHandler
     88        self.width = width*inch
     89        self.verbose=verbose
     90 -    def __call__(self,arg):
     91        res = list(arg)
     92        if self.verbose:
     93          sys.stderr.write('Render(%d): %s\n'%(self.smiCol,str(res[0])))
     94        smi = res[self.smiCol]
     95        tmpName = self.tempHandler.get('.gif')
     96        aspect = 1
     97        width = 300
     98        height = aspect*width
     99        ok = cactvs.SmilesToGif(smi,tmpName,(width,height))
    100        if ok:
    101          try:
    102            img = platypus.Image(tmpName)
    103            img.drawWidth = self.width
    104            img.drawHeight = aspect*self.width
    105          except:
    106            ok = 0
    107        if ok:
    108          res[self.smiCol] = img
    109        else:
    110          # FIX: maybe include smiles here in a Paragraph?
    111          res[self.smiCol] = 'Failed'
    112        return res
    113
    114
    115    from rdkit.sping.ReportLab.pidReportLab import RLCanvas as Canvas
    116    from rdkit.Chem.Draw.MolDrawing import MolDrawing
    117 -  class ReportLabImageTransformer(object):
    118 -    def __init__(self,smiCol,width=1.,verbose=1,tempHandler=None):
    119        self.smiCol = smiCol
    120        self.width = width*inch
    121        self.verbose=verbose
    122 -    def __call__(self,arg):
    123        res = list(arg)
    124        if self.verbose:
    125          sys.stderr.write('Render(%d): %s\n'%(self.smiCol,str(res[0])))
    126        smi = res[self.smiCol]
    127        aspect = 1
    128        width = self.width
    129        height = aspect*width
    130        try:
    131          mol = Chem.MolFromSmiles(smi)
    132          Chem.Kekulize(mol)
    133          canv = Canvas((width,height))
    134          drawing = MolDrawing()
    135          drawing.atomLabelMinFontSize=3
    136          drawing.minLabelPadding=(.5,.5)
    137          drawing.bondLineWidth=0.5
    138          if not mol.GetNumConformers():
    139            rdDepictor.Compute2DCoords(mol)
    140          drawing.AddMol(mol,canvas=canv)
    141          ok = True
    142        except:
    143          if self.verbose:
    144            import traceback
    145            traceback.print_exc()
    146          ok = False
    147
    148        if ok:
    149          res[self.smiCol] = canv.drawing
    150        else:
    151          # FIX: maybe include smiles here in a Paragraph?
    152          res[self.smiCol] = 'Failed'
    153        return res
    154
    155
    156 -  class RDImageTransformer(object):
    157 -    def __init__(self,smiCol,width=1.,verbose=1,tempHandler=None):
    158        self.smiCol = smiCol
    159        if tempHandler is None:
    160          tempHandler = ReportUtils.TempFileHandler()
    161        self.tempHandler = tempHandler
    162        self.width = width*inch
    163        self.verbose=verbose
    164 -    def __call__(self,arg):
    165        res = list(arg)
    166        if self.verbose:
    167          sys.stderr.write('Render(%d): %s\n'%(self.smiCol,str(res[0])))
    168        smi = res[self.smiCol]
    169        tmpName = self.tempHandler.get('.jpg')
    170        aspect = 1
    171        width = 300
    172        height = aspect*width
    173        ok = DrawUtils.SmilesToJpeg(smi,tmpName,size=(width,height))
    174        if ok:
    175          try:
    176            img = platypus.Image(tmpName)
    177            img.drawWidth = self.width
    178            img.drawHeight = aspect*self.width
    179          except:
    180            ok = 0
    181        if ok:
    182          res[self.smiCol] = img
    183        else:
    184          # FIX: maybe include smiles here in a Paragraph?
    185          res[self.smiCol] = 'Failed'
    186        return res
    187
    188 -  def QuickReport(conn,fileName,*args,**kwargs):
    189      from reportlab.lib import colors
    190      from reportlab.lib.styles import getSampleStyleSheet
    191      from reportlab.lib.units import inch
    192
    193      styles = getSampleStyleSheet()
    194      title = 'Db Report'
    195      if kwargs.has_key('title'):
    196        title = kwargs['title']
    197        del kwargs['title']
    198
    199      names = [x.upper() for x in conn.GetColumnNames()]
    200      try:
    201        smiCol = names.index('SMILES')
    202      except ValueError:
    203        try:
    204          smiCol = names.index('SMI')
    205        except ValueError:
    206          smiCol = -1
    207      if smiCol >-1:
    208        if hasCDX:
    209          tform = CDXImageTransformer(smiCol)
    210        elif 1:
    211          tform = ReportLabImageTransformer(smiCol)
    212        else:
    213          tform = CactvsImageTransformer(smiCol)
    214
    215      else:
    216        tform = None
    217      kwargs['transform'] = tform
    218      tbl = conn.GetReportlabTable(*args,**kwargs)
    219      tbl.setStyle(platypus.TableStyle([('GRID',(0,0),(-1,-1),1,colors.black),
    220                                        ('FONT',(0,0),(-1,-1),'Times-Roman',8),
    221                                        ]))
    222
    223
    224      if smiCol >-1 and tform:
    225        tbl._argW[smiCol] = tform.width*1.2
    226      elements = [tbl]
    227      reportTemplate = PDFReport()
    228      reportTemplate.pageHeader = title
    229
    230      doc = platypus.SimpleDocTemplate(fileName)
    231      doc.build(elements,onFirstPage=reportTemplate.onPage,
    232                onLaterPages=reportTemplate.onPage)
    233
    234    DbConnect.GetReportlabTable = GetReportlabTable
    235
    236  if __name__=='__main__':
    237    import sys
    238    dbName = sys.argv[1]
    239    tblName = sys.argv[2]
    240    fName = 'report.pdf'
    241    conn = DbConnect(dbName,tblName)
    242    QuickReport(conn,fName,where="where mol_id in ('1','100','104','107')")
    243