ó
a#nSc           @   sŸ  d  Z  d d l m Z d d l m Z d d l m Z d d l m Z d d l Z yÞ d d l	 Z
 e
 j j j d ƒ Z e d d	 k r¥ e e d
 ƒ d k  r¥ d Z
 nŠ d e
 j j j k rÍ e
 j d d ƒ n  d e
 j j j k rõ e
 j d d ƒ n  d e
 j j j k re
 j d d ƒ n  e
 j j j j Z Wn e k
 rKZ d Z
 n Xd „  Z d d „ Z d „  Z d d l m Z y d d l m Z d „  Z  Wn e! k
 r³d „  Z  n Xd „  Z" e" e j# _$ d d „ Z% d „  Z& e% e j# _' d „  Z( e) d „ Z* d d e+ d „ Z, d d  d! „ Z- d" d# d e+ d$ „ Z. d d% l m/ Z/ e/ j/ ƒ  Z0 d d& „ Z1 d d' d( „ Z2 d d d) „ Z3 d d* l4 m5 Z5 d d+ l m6 Z6 d d, e+ d- „ Z7 d d. l m8 Z8 d/ „  Z9 d d, d0 „ Z: e; d1 k r›d d l< Z< e
 d k r	e< j= d2 IJq›e
 j j j d ƒ Z e d d	 k rTe e d
 ƒ d k  rTe< j= d3 IJq›d d l> Z> e> j? d4 e> j@ e> jA ƒ \ ZB ZC eB r›e< jD eB ƒ q›n  d S(5   sL  
Importing pandasTools enables several features that allow for using RDKit molecules as columns of a Pandas dataframe.
If the dataframe is containing a molecule format in a column (e.g. smiles), like in this example:
>>> from rdkit.Chem import PandasTools
>>> import pandas as pd
>>> import os
>>> from rdkit import RDConfig
>>> antibiotics = pd.DataFrame(columns=['Name','Smiles'])
>>> antibiotics = antibiotics.append({'Smiles':'CC1(C(N2C(S1)C(C2=O)NC(=O)CC3=CC=CC=C3)C(=O)O)C','Name':'Penicilline G'}, ignore_index=True)#Penicilline G
>>> antibiotics = antibiotics.append({'Smiles':'CC1(C2CC3C(C(=O)C(=C(C3(C(=O)C2=C(C4=C1C=CC=C4O)O)O)O)C(=O)N)N(C)C)O','Name':'Tetracycline'}, ignore_index=True)#Tetracycline
>>> antibiotics = antibiotics.append({'Smiles':'CC1(C(N2C(S1)C(C2=O)NC(=O)C(C3=CC=CC=C3)N)C(=O)O)C','Name':'Ampicilline'}, ignore_index=True)#Ampicilline
>>> print [str(x) for x in  antibiotics.columns]
['Name', 'Smiles']
>>> print antibiotics
            Name                                             Smiles
0  Penicilline G    CC1(C(N2C(S1)C(C2=O)NC(=O)CC3=CC=CC=C3)C(=O)O)C
1   Tetracycline  CC1(C2CC3C(C(=O)C(=C(C3(C(=O)C2=C(C4=C1C=CC=C4...
2  Ampicilline  CC1(C(N2C(S1)C(C2=O)NC(=O)C(C3=CC=CC=C3)N)C(=O...

a new column can be created holding the respective RDKit molecule objects. The fingerprint can be included to accelerate substructure searches on the dataframe.

>>> PandasTools.AddMoleculeColumnToFrame(antibiotics,'Smiles','Molecule',includeFingerprints=True)
>>> print [str(x) for x in  antibiotics.columns]
['Name', 'Smiles', 'Molecule']

A substructure filter can be applied on the dataframe using the RDKit molecule column, because the ">=" operator has been modified to work as a substructure check.
Such the antibiotics containing the beta-lactam ring "C1C(=O)NC1" can be obtained by

>>> beta_lactam = Chem.MolFromSmiles('C1C(=O)NC1')
>>> beta_lactam_antibiotics = antibiotics[antibiotics['Molecule'] >= beta_lactam]
>>> print beta_lactam_antibiotics[['Name','Smiles']]
            Name                                             Smiles
0  Penicilline G    CC1(C(N2C(S1)C(C2=O)NC(=O)CC3=CC=CC=C3)C(=O)O)C
2  Ampicilline  CC1(C(N2C(S1)C(C2=O)NC(=O)C(C3=CC=CC=C3)N)C(=O...


It is also possible to load an SDF file can be load into a dataframe.

>>> sdfFile = os.path.join(RDConfig.RDDataDir,'NCI/first_200.props.sdf')
>>> frame = PandasTools.LoadSDF(sdfFile,smilesName='SMILES',molColName='Molecule',includeFingerprints=True)
>>> frame.info # doctest: +SKIP
<bound method DataFrame.info of <class 'pandas.core.frame.DataFrame'>
Int64Index: 200 entries, 0 to 199
Data columns:
AMW                       200  non-null values
CLOGP                     200  non-null values
CP                        200  non-null values
CR                        200  non-null values
DAYLIGHT.FPG              200  non-null values
DAYLIGHT_CLOGP            200  non-null values
FP                        200  non-null values
ID                        200  non-null values
ISM                       200  non-null values
LIPINSKI_VIOLATIONS       200  non-null values
NUM_HACCEPTORS            200  non-null values
NUM_HDONORS               200  non-null values
NUM_HETEROATOMS           200  non-null values
NUM_LIPINSKIHACCEPTORS    200  non-null values
NUM_LIPINSKIHDONORS       200  non-null values
NUM_RINGS                 200  non-null values
NUM_ROTATABLEBONDS        200  non-null values
P1                        30  non-null values
SMILES                    200  non-null values
Molecule                  200  non-null values
dtypes: object(20)>

In order to support rendering the molecules as images in the HTML export of the dataframe, the __str__ method is monkey-patched to return a base64 encoded PNG:
>>> molX = Chem.MolFromSmiles('Fc1cNc2ccccc12')
>>> print molX # doctest: +SKIP
<img src="data:image/png;base64,..." alt="Mol"/>
This can be reverted using the ChangeMoleculeRendering method
>>> ChangeMoleculeRendering(renderer='String')
>>> print molX # doctest: +SKIP
<rdkit.Chem.rdchem.Mol object at 0x10d179440>
>>> ChangeMoleculeRendering(renderer='PNG')
>>> print molX # doctest: +SKIP
<img src="data:image/png;base64,..." alt="Mol"/>
iÿÿÿÿ(   t   Chem(   t   Draw(   t	   b64encode(   t   StringIONt   .i    t   0i   i
   s   display.widthi Êš;s   display.heights   display.max_colwidthc      "   K   s’   t  j j j |  d d d d d d d d d t d t d d d	 d d
 d d d d t d d d d d t d d d t ƒ} | j ƒ  | j j	 ƒ  } | S(   sf   
  Patched default escaping of HTML control characters to allow molecule image rendering dataframes
  t   buft   columnst	   col_spacet   colSpacet   headert   indext   na_rept   NaNt
   formatterst   float_formatt   sparsifyt   index_namest   justifyt   force_unicodet	   bold_rowst   classest   escapeN(
   t   pdt   coret   formatt   DataFrameFormattert   Nonet   Truet   Falset   to_htmlR   t   getvalue(   t   selft   kwargst	   formattert   html(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   patchPandasHTMLreprh   s    6!
i   c         C   s8   |  |  } t  j t | ƒ | _ t  j t | ƒ | _ | S(   s;   Ensure inheritance of patched to_html in "head" subframe
  (   t   typest
   MethodTypeR$   R   t   patchPandasHeadMethodt   head(   R    t   nt   df(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR'   s   s    
c         C   s®   d d l  } t ƒ  } |  j | d d ƒt | j ƒ  ƒ } | j d t | ƒ d ƒ | j d t | ƒ d ƒ t | ƒ d | j d	 ƒ k rª | j d	 t | ƒ d ƒ n  | S(
   s4   displayhook function for PIL Images, rendered as PNGiÿÿÿÿNR   t   PNGs   display.max_columnsiè  s   display.max_rowsid   s   display.max_colwidth(   t   pandasR   t   saveR   R   t
   set_optiont   lent
   get_option(   t   xR   t   siot   s(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt
   _get_image{   s    	(   t   DataStructs(   t   pyAvalonToolsc         C   s   t  j |  d | d t  j ƒS(   Nt   isQueryt   bitFlags(   R6   t   GetAvalonFPt   avalonSSSBits(   R1   t   y(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   <lambda>‹   s    c         C   s   t  j |  d d ƒS(   Nt   fpSizei   (   R    t   PatternFingerprint(   R1   R;   (    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR<   �   s    c         C   s{   |  d k s | d k r t St |  d ƒ rn t | d ƒ sO t | t ƒ | _ n  t j | j |  j ƒ sn t Sn  |  j | ƒ S(   s!  Allows for substructure check using the >= operator (X has substructure Y -> X >= Y) by
  monkey-patching the __ge__ function 
  This has the effect that the pandas/numpy rowfilter can be used for substructure filtering (filtered = dframe[dframe['RDKitColumn'] >= SubstructureMolecule])
  t   _substructfpN(	   R   R   t   hasattrt   _fingerprinterR   R?   R5   t   AllProbeBitsMatcht   HasSubstructMatch(   R1   R;   (    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   _molge�   s     c         C   s   d t  t j |  ƒ ƒ S(   s4   returns the molecules as base64 encoded PNG image
  s/   <img src="data:image/png;base64,%s" alt="Mol"/>(   R4   R   t
   MolToImage(   R1   t   renderer(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   PrintAsBase64PNGStringž   s    c         C   s   t  |  j ƒ  ƒ S(   N(   t   strt   __repr__(   R1   (    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   PrintDefaultMolRep£   s    c         C   s4   t  j |  ƒ } | d k	 r0 t | t ƒ | _ n  | S(   sf   Precomputes fingerprints and stores results in molecule objects to accelerate substructure matching
  N(   R    t   MolFromSmilesR   RA   R   R?   (   t   smit   m(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   _MolPlusFingerprintFromSmiles©   s    c         C   s1   |  r t  t j j j _ n t t j j j _ d S(   sA  Changes the default dataframe rendering to not escape HTML characters, thus allowing rendered images in all dataframes.
  IMPORTANT: THIS IS A GLOBAL CHANGE THAT WILL AFFECT TO COMPLETE PYTHON SESSION. If you want to change the rendering only 
  for a single dataframe use the "ChangeMoleculeRendering" method instead.
  N(   R$   R   R   t   framet	   DataFrameR   t   defPandasRendering(   t   images(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   RenderImagesInAllDataFrames±   s    t   Smilest   ROMolc            s^   | s+ |  j  ‡  f d †  d d ƒ|  | <n" |  j  ‡  f d †  d d ƒ|  | <t d t ƒ d S(   s  Converts the molecules contains in "smilesCol" to RDKit molecules and appends them to the dataframe "frame" using the specified column name.
  If desired, a fingerprint can be computed and stored with the molecule objects to accelerate substructure matching
  c            s   t  j |  ˆ  ƒ S(   N(   R    RK   (   R1   (   t	   smilesCol(    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR<   Á   s    t   axisi   c            s   t  |  ˆ  ƒ S(   N(   RN   (   R1   (   RV   (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR<   Ã   s    RR   N(   t   applyRS   R   (   RO   RV   t   molColt   includeFingerprints(    (   RV   sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   AddMoleculeColumnToFrame¼   s    %"R+   c         C   sO   | d k r t  t j _ n t t j _ |  d k	 rK t j t |  ƒ |  _	 n  d S(   s\  Allows to change the rendering of the molecules between base64 PNG images and string representations. 
  This serves two purposes: First it allows to avoid the generation of images if this is not desired and, secondly, it allows to enable image rendering for
  newly created dataframe that already contains molecules, without having to rerun the time-consuming AddMoleculeColumnToFrame. Note: this behaviour is, because some pandas methods, e.g. head()
  returns a new dataframe instance that uses the default pandas rendering (thus not drawing images for molecules) instead of the monkey-patched one.
  t   StringN(
   RJ   R    t   Molt   __str__RG   R   R%   R&   R$   R   (   RO   RF   (    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   ChangeMoleculeRenderingÉ   s
    t   SMILESt   IDc   	         s(  d } t |  ƒ t k r* t |  d ƒ } n |  } xË t t j | ƒ ƒ D]´ \ } ‰  ˆ  d k rd qF n  t ‡  f d †  ˆ  j ƒ  Dƒ ƒ } ˆ  j	 d ƒ r« ˆ  j
 d ƒ | | <n  t j ˆ  ƒ | | <t j | d | g ƒ} | d k rë | } qF | j | ƒ } qF W| j ƒ  t | d | d | d | ƒ| S(	   s8    Read file in SDF format and return as Panda data frame t   rUc         3   s$   |  ] } | ˆ  j  | ƒ f Vq d  S(   N(   t   GetProp(   t   .0t   k(   t   mol(    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pys	   <genexpr>ß   s    t   _NameR   RV   RY   RZ   N(   R   t   typeRH   t   opent	   enumerateR    t   ForwardSDMolSuppliert   dictt   GetPropNamest   HasPropRc   t   MolToSmilesR   RP   t   appendt   closeR[   (	   t   filenamet
   smilesNamet   idNamet
   molColNameRZ   R*   t   ft   it   row(    (   Rf   sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   LoadSDFÖ   s$    " " 	
(   t   SaltRemoverc            s&   |  j  ‡  f d †  d d ƒ|  ˆ  <d S(   s@   
  Removes salts from mols in pandas DataFrame's ROMol column
  c            s   t  j |  ˆ  ƒ S(   N(   t   removert   StripMol(   R1   (   RY   (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR<   ò   s    RW   i   N(   RX   (   RO   RY   (    (   RY   sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   RemoveSaltsFromFrameî   s    t    c         C   s¦   t  j | ƒ } | d k rv xK t |  | t t |  | ƒ ƒ D]) \ } } | j d | ƒ | j | ƒ q< W| j ƒ  n, x |  | D] } | j | ƒ q� W| j ƒ  d S(   sk   
  Saves smi file. SMILES are generated from column with RDKit molecules. Column with names is optional.
  R~   Rg   N(   R    t   SmilesWritert   zipt   mapRH   t   SetPropt   writeRq   (   RO   t   outFileRY   t   NamesColt   wRM   R)   (    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   SaveSMILESFromFrameô   s    -c         K   sR   | r8 t  j |  | d t t t |  | ƒ ƒ | �} n t  j |  | | � } | S(   s2   
  Draw grid image of mols in pandas DataFrame.
  t   legends(   R   t   MolsToGridImageR�   RH   t   list(   RO   t   columnt
   legendsColR!   t   img(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   FrameToGridImage  s    2(   t   MurckoScaffold(   Ro   t   Murcko_SMILESc            sQ   | r+ |  j  ‡  f d †  d d ƒ|  | <n" |  j  ‡  f d †  d d ƒ|  | <d S(   s‚   
  Adds column with SMILES of Murcko scaffolds to pandas DataFrame. Generic set to true results in SMILES of generic framework.
  c            s    t  t j t j |  ˆ  ƒ ƒ ƒ S(   N(   Ro   R�   t   MakeScaffoldGenerict   GetScaffoldForMol(   R1   (   RY   (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR<     s    RW   i   c            s   t  t j |  ˆ  ƒ ƒ S(   N(   Ro   R�   R’   (   R1   (   RY   (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR<     s    N(   RX   (   RO   RY   t	   MurckoColt   Generic(    (   RY   sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   AddMurckoToFrame  s    %(   t   AllChemc         C   s0   t  j | ƒ } t j | ƒ t j |  | ƒ |  S(   s?   
  Aligns mol (RDKit mol object) to scaffold (SMILES string)
  (   R    RK   R–   t   Compute2DCoordst$   GenerateDepictionMatching2DStructure(   Rf   t   scaffold(    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   AlignMol  s    c            s)   |  j  ‡  ‡ f d †  d d ƒ|  ˆ  <d S(   s<   
  Aligns molecules in molCol to scaffolds in scaffoldCol
  c            s   t  |  ˆ  |  ˆ ƒ S(   N(   Rš   (   R1   (   RY   t   scaffoldCol(    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyR<   )  s    RW   i   N(   RX   (   RO   RY   R›   (    (   RY   R›   sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   AlignToScaffold%  s    t   __main__s-   pandas installation not found, skipping testss4   pandas installation >=0.10 not found, skipping testst   optionflags(E   t   __doc__t   rdkitR    t
   rdkit.ChemR   t   base64R   R   R%   R,   R   t   versiont   splitt   vt   intR   R   t   configt   _registered_optionsR.   RO   RP   R   RQ   t	   Exceptiont   eR$   R'   R4   R5   t   rdkit.AvalonR6   RA   t   ImportErrorRD   R]   t   __ge__RG   RJ   R^   RN   R   RS   R   R[   R_   Ry   Rz   R{   R}   R‡   RŽ   t   rdkit.Chem.ScaffoldsR�   Ro   R•   R–   Rš   Rœ   t   __name__t   syst   stderrt   doctestt   testmodt   ELLIPSISt   NORMALIZE_WHITESPACEt   failedt   triedt   exit(    (    (    sX   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/Chem/PandasTools.pyt   <module>N   sx   &	
					

		&"