B
    3Rc               	   @   s  d dl mZ d dlZd dlZd dlZd dlmZ d dlmZ d dl	m
Z
 eeZdZdZdZdZdZdZx:dD ]2Zyee dZW n ek
r   wpY nX P qpW edkred	 edZx@d
D ]8ZeedreejereejeZeedrP qdZqW edkred edZx*dD ]"Zeejer$eejeZP q$W edkrbed ee Z ee dsede j!j d edZ"dZ#x\dD ]TZ$yeej de$ Z"W n ek
r   wY nX ee"dree"dZ#P qW e#dkred edZ%ee#ds*ed eee#dZ%eedrNeej&ds\ed eyd dl'Z(W n" e)k
r   ed  Y nX eedZ*ej&j+Z+dd Z,e-dZ.G d d! d!Z/d"d# Z0d$d% Z1d&d' Z2d(d) Z3d*d+ Z4d6d-d.Z5d7d0d1Z6d2d3 Z7d4d5 Z8dS )8    )StringION)minidom)
ExpatError)MolZ__rdkitMolAsImage)z	pandas.iopandasz.formatsz&Failed to import pandas formats module)DataFrameRendererDataFrameFormatterformatto_htmlz1Failed to find the pandas to_html method to patch)Zget_adjustmentZ_get_adjustmentz<Failed to find the pandas get_adjustment() function to patchlenzFailed to find the pandas z.len() method to patch)r	   Zhtml.ZHTMLFormatterz6Failed to find the pandas HTMLFormatter class to patch_write_cellz>Failed to find the HTMLFormatter._write_cell() method to patchprintingpprint_thingz(Failed to find the pprint_thing functionzFailed to import pandasc             C   s^   d}y@t | }|j}|jdkrBd|j krB|jd jdkrBd}W n tk
rX   Y nX |S )NF)ZsvgZimgZdivzdata-contentzrdkit/moleculeT)r   ZparseStringZ
firstChildZnodeNameZ
attributeskeysvaluer   )sresultZxmlZ	root_node r   7lib/python3.7/site-packages/rdkit/Chem/PandasPatcher.pyis_molecule_imageP   s    

r   z^(.*style=["'][^"^']*)(["'].*)$c               @   sF   e Zd ZdZdddZedd Zedd Zed	d
 Z	dd Z
dS )MolFormatterzFormat molecules as imagesNc             C   s
   || _ dS )z"Store original formatters (if any)N)orig_formatter)selfr   r   r   r   __init__d   s    zMolFormatter.__init__c             C   s   t | ddS )zDefault formatter function)	
)Zescape_chars)r   )xr   r   r   default_formatterh   s    zMolFormatter.default_formatterc             C   s
   t | tS )zReturn True if x is a Chem.Mol)
isinstancer   )r   r   r   r   is_molm   s    zMolFormatter.is_molc                s0   | d} fdd|j|tj  D S )zQReturn an instance of MolFormatter for each column that contains Chem.Mol objectsobjectc                s   i | ]}  |d |qS )N)get).0col)clsorig_formattersr   r   
<dictcomp>v   s   z/MolFormatter.get_formatters.<locals>.<dictcomp>)Zselect_dtypescolumnsZapplymapr   r!   any)r&   Zdfr'   Z	df_subsetr   )r&   r'   r   get_formattersr   s    
zMolFormatter.get_formattersc             C   s0   |  |rt|S t| jr&| |S | |S )z$Return x formatted based on its type)r!   PrintAsImageStringcallabler   r   )r   r   r   r   r   __call__{   s
    


zMolFormatter.__call__)N)__name__
__module____qualname____doc__r   staticmethodr   r!   classmethodr+   r.   r   r   r   r   r   a   s   
	r   c             C   s   t | |ot| |S )N)hasattrgetattr)frameattrr   r   r   check_rdk_attr   s    r9   c             C   s   t | |d d S )NT)setattr)r7   r8   r   r   r   set_rdk_attr   s    r;   c                sX  d}| j jdkr| j}n$| j jdkr*| }ntd| j j |j}t|ts\t| f||S |j}z|pji  t	 t
s fddt| jD  nt
   t|   |_t| f||}|dkrttdst| drt| jd	r| j }|otot }|rHt|}t| drHt	| jtrH| jd
 | j| |S ||_X dS )zeA patched version of the to_html method
     that allows rendering molecule images in data frames.
  Nr   r   z"patched_to_html: unexpected class c                s   i | ]\}} | |qS r   r   )r$   ir%   )
formattersr   r   r(      s    z#patched_to_html.<locals>.<dictcomp>Z
get_resultbufgetvaluer   )	__class__r/   fmt
ValueErrorr7   r9   RDK_MOLS_AS_IMAGE_ATTRorig_to_htmlr=   r    dict	enumerater)   updater   r+   r5   html_formatter_classr>   r?   InteractiveRendererZ	isEnabledZinjectHTMLFooterAfterTabler   seekwrite)r   argskwargsr7   rA   r'   ZresZshould_injectr   )r=   r   patched_to_html   s:    



rN   c       	      O   s   dt  d}| j}zt| jtrt|rd| _|dd}|dkr|ddpPd}t|}|rvt	d	| d
|}n|r|d7 }|d| d7 }||d< t
| |f||S || _X dS )z< Disable escaping of HTML in order to render img / svg tags ztext-align: ;FkindNZtdtags z\1 z\2 zstyle="")
molJustifyescaper5   r7   rC   r   r#   
styleRegexmatchsuborig_write_cell)	r   r   rL   rM   Z	styleTagsZ
def_escaperP   rQ   rX   r   r   r   patched_write_cell   s"    
r[   c                 s   t  } | j  fdd| _| S )zA Avoid truncation of data frame values that contain HTML content c                s   t | rdS  | f||S )Nr   )r   )textrL   rM   )orig_lenr   r   <lambda>   s    z(patched_get_adjustment.<locals>.<lambda>)orig_get_adjustmentr   )adjr   )r]   r   patched_get_adjustment   s    ra   Tc             C   s:   | rt tjjjt n ttjjjtr6ttjjjt d S )N)r;   pdZcorer7   Z	DataFramerC   r5   delattr)Zimagesr   r   r   renderImagesInAllDataFrames   s    rd   imagec             C   s2   |  dst| t nt| tr.t| t d S )Nstr)lower
startswithr;   rC   r5   rc   )r7   Zrendererr   r   r   changeMoleculeRendering   s    
ri   c               C   sV   t tdtkrttdt t tdtkr4ttdt t tjtt	krRttjtt	 d S )Nr
   r   )
r6   to_html_classrN   r:   rH   r[   pandas_formatsr	   get_adjustment_namera   r   r   r   r   patchPandas   s    rm   c               C   s6   t rttdt  tr ttdt tr2ttjtt d S )Nr
   r   )	rD   r:   rj   rZ   rH   r_   rk   r	   rl   r   r   r   r   unpatchPandas   s    rn   )T)re   )9ior   Zloggingre	importlibZxml.domr   Zxml.parsers.expatr   Z
rdkit.Chemr   Z	getLoggerr/   logrC   rI   r,   rU   Zpandas_framerk   Zpandas_formats_nameimport_moduleModuleNotFoundErrorZwarningrj   Zto_html_class_namer5   r	   r6   AttributeErrorr_   rl   r`   Z__classZhtml_formatter_modulerH   Zhtml_formatter_module_namerZ   r   r   rb   ImportErrorrD   r   r   compilerW   r   r9   r;   rN   r[   ra   rd   ri   rm   rn   r   r   r   r   <module>   s   




















#'	

