B
    3Rca                 @   s  d Z ddlmZ ddlmZmZ ddlmZ ddlmZ ddl	m
Z
 ddlmZ ddlmZmZ 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Zdd
lZdd
lZddlmZ edZeddddgZedZdd ZG dd dZ G dd dZ!e" Z#ej$e#_%de#_&ej'j(e#_)de#_*e#fe!dddZ+d+ddZ,d,e!eed
d
f dd d!Z-d"d# Z.e!d$d%d&Z/d'd( Z0d)d* Z1d
S )-u  
Free Wilson Analysis

A Mathematical Contribution to Structurre-Activity Studies
Spencer M, Free, Jr and James W Wilson
Journal of Medicinal Chemistry
Vol 7, Number 4, July 6, 1964

Basic usage: get a scaffold (or scaffolds) some compounds and their scores, 
then run freewilson:


Read some example data:
```
>>> import os, sys
>>> DATA_PATH = "data"
>>> smilesfile = os.path.join(DATA_PATH, "CHEMBL2321810.smi")
>>> scaffoldfile = os.path.join(DATA_PATH, "CHEMBL2321810_scaffold.mol")
>>> csvfile = os.path.join(DATA_PATH, "CHEMBL2321810_act.csv")
>>> mols = []
>>> for line in open(smilesfile):
...     smiles, name = line.strip().split()
...     m = Chem.MolFromSmiles(smiles)
...     m.SetProp("_Name", name)
...     mols.append(m)
>>> scaffold = Chem.MolFromMolBlock(open(scaffoldfile).read())
>>> data = {k:float(v) for k,v in list(csv.reader(open(csvfile)))[1:]}
>>> scores = [data[m.GetProp("_Name")] for m in mols]

```

And do the decomposition:
```
>>> from freewilson import FWDecompose, FWBuild, predictions_to_csv
>>> decomp = FWDecompose(scaffold, mols, scores)

```

Scores need to be in an appropriate form for regression analysis, i.e. pIC50s as opposed to IC50s.
Enumerations are a lot faster if you know a prediction cutoff or molecular weight cutoff.

Scaffolds can be any scaffold or smarts pattern or list of either.  The system automatically 
enumerates matching cores in the analysis.

To see if the decomposition is useful, check the r squared value

```
>>> print(f"Training R^2 is {decomp.r2:0.2f}")
Training R^2 is 0.81

```
Finally you can build the decomposition into new molecules:

```
>>> for pred in FWBuild(decomp):                            # doctest: +SKIP
...     print(pred.smiles, pred.prediction)

```

Now this builds both well and poorly predicted molecules.  To prevent
this you can use the following filters while building:

   1. pred_filter:  given a prediction, return True to keep the molecule
   2. hvy_filter: given a heavy atom count, return True to keep the molecule
   3. mw_filter: given a molecular weight, return True to keep the molecule
   4. mol_filter: given a sanitized molecule, return True to keep the molecule

Here are some examples (see using Molecular Filters below)

```
>>> preds = FWBuild(decomp, 
...                 pred_filter=lambda x: x > 8, 
...                 mw_filter=lambda mw: 100<mw<550)
>>> predictions_to_csv(sys.stdout, decomp, preds)

```

More Info
---------
You can also get some more information by setting logging to INFO

```
>>> import logging
>>> logging.getLogger().setLevel(logging.INFO)
>>> preds = list(FWBuild(decomp, pred_filter=lambda x: x > 8))

```

You'll see something like this:

```
INFO:root:Enumerating rgroups with no broken cycles...
INFO:root:	Core	1
INFO:root:	R1	73
INFO:root:	R10	2
INFO:root:	R3	445
100%|███████████████████████████████████████████████████████| 64970/64970 [00:05<00:00, 11247.38it/s]
INFO:root:Wrote 3 results out of 64970
	In Training set: 628
	Bad MW: 0
	Bad Pred: 64339
	Bad Filters: 0
	Bad smi: 0
	min mw: 380.429
	max mw: 772.4030000000001
	
	min pred: 2.8927324757327666
	max pred: 8.148182660251193
```

Using FMCS to find a scaffold
-----------------------------

If you don't have a good feel for the dataset, you can generate the scaffold by using
the rdFMCS package.  The following tries to find a decent MCS that covers 80% of the
input structures


```
>>> from rdkit.Chem import rdFMCS
>>> mcs = rdFMCS.FindMCS(mols[0:8], threshold=0.8, atomCompare=rdFMCS.AtomCompare.CompareAny,
...                      completeRingsOnly=True)                           # doctest: +SKIP
>>> decomp = FWDecompose(mcs.queryMol, mols, scores)                       # doctest: +SKIP

```
    )rdRGroupDecomposition)molzipDescriptors)rdBase)Chem)Ridge)r2_score)defaultdict
namedtuple)tqdmN)List)	GeneratorZ
freewilsonFreeWilsonPrediction
predictionsmilesrgroupsz\*:([0-9]+)c             C   s  t  }g }x@| dD ]2}|ddkr>||kr4qn
|| || qW d|} ttj| dd}t	|}|d }i }t
t}x6|D ].}	||	 }
|
r|	||
< ||
  d7  < qW t|d }g }xz|dd D ]j}xd|D ]\}	||	 }
|
r||
 d  }||
< |dkr||	| |||
 |f |d7 }qW qW x|D ]~\}}
||}t| }t|dkrR|d |}td}||}	||	}||
 || | tjj qRW t|S )	z~Fix a rgroup smiles for molzip, note that the core MUST come first
    in the smiles string, ala core.rgroup1.rgroup2 ...
    .*   F)sanitizer   N   )setsplitcountaddappendjoinr   ZRWMolMolFromSmilesZGetMolFragsr	   intZGetAtomWithIdxZGetAtomMapNummaxZSetAtomMapNumlistZGetBondslenZGetOtherAtomZAtomZAddAtomZAddBondZGetIdxZBondTypeZSINGLEr   )r   ZdupesZslsmZfragsZcoreZatommapsZcountsidxZatommapZnext_atommapZadd_atommapZfragmentr   ZatomidxatomZbondsZoatomZxatom r&   ,share/RDKit/Contrib/FreeWilson/freewilson.py
molzip_smi   sR    









 r(   c               @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
RGroupa  FreeWilson RGroup
        smiles - isomeric smiles of the rgroup
        rgroup - Rgroup name ['Core', 'R1', 'R2'...]
        count - number of molecules with the rgroup
        coefficient - ridge regression coefficient
        idx - one-hot encoding for the rgroup
    Nc       
      C   s   || _ || _|| _|| _|| _tdd tt|D | _	t
|}|rdt|| _t|| _nt
 }t
j|dd}|rd| _d| _xB| D ]6}| }	|  j||	7  _|	dkr|  jd7  _qW t|| _nd| _d| _d S )Nc             S   s   g | ]}t |qS r&   )r   ).0xr&   r&   r'   
<listcomp>   s    z#RGroup.__init__.<locals>.<listcomp>F)r   g        r   r   )r   rgroupr   coefficientr$   tuplesorteddummypatfindalldummiesr   r   r   MolWtmwHeavyAtomCounthvyctZGetPeriodicTableZGetAtomsZGetAtomicNumZGetAtomicWeight)
selfr   r-   r   r.   r$   r#   tabler%   Z	atomicnumr&   r&   r'   __init__   s.    
zRGroup.__init__c             C   sB   dt | j dt | j dt | j dt | j dt | j dS )NzRGroup(smiles=z	, rgroup=z, count=z, coefficient=z, idx=))reprr   r-   r   r.   r$   )r8   r&   r&   r'   __str__   s    zRGroup.__str__c             C   s   |   S )N)r=   )r8   r&   r&   r'   __repr__   s    zRGroup.__repr__)N)__name__
__module____qualname____doc__r:   r=   r>   r&   r&   r&   r'   r)      s   
 r)   c               @   s   e Zd ZdZdd ZdS )FreeWilsonDecompositiona  FreeWilson decomposition
      rgroups - dictionary of rgroup to list of RGroups
                 i.e. {'Core': [RGroup(...), ...]
                       'R1': [ RGroup(...), RGroup(...)],
                      }
      rgroup_to_descriptor_idx - one hot encoding of smiles to descriptor index
      fitter - scikit learn compatible fitter used for regression
      N - number of rgroups
      r2 - regression r squared
      descriptors - set of the descriptors for molecules in the training set
                    used to not enumerate existing molecules
      row_decomposition - original rgroup decomposition (With row key 'molecule' is an rdkit molecule)
    c	       	      C   sL   || _ || _|| _t|| _|| _tdd |D | _|| _|| _	|| _
d S )Nc             S   s   g | ]}t |qS r&   )r/   )r*   dr&   r&   r'   r,     s    z4FreeWilsonDecomposition.__init__.<locals>.<listcomp>)r   rgroup_to_descriptor_idxfitterr!   Nr2r   descriptorsrow_decompositionnum_trainingnum_reconstructed)	r8   r   rE   rF   rH   rI   rJ   rK   rL   r&   r&   r'   r:     s    
z FreeWilsonDecomposition.__init__N)r?   r@   rA   rB   r:   r&   r&   r&   r'   rC      s   rC   F)returnc          
   C   s  g }g }i }t t}t|t|kr@tdt| dt| tdt| d t| |}g }	g }
xNtt	t
||D ]8\}\}}||dkr~|| |	| |
| q~W |  tdt| dt|  |std d	S |jd
d}td t }t t}d}xtt
||
D ]\}\}}g }x^| D ]R\}}|| ||  d7  < ||krFt|||< || t||dd qFW ||d< d|}yt }t|}|d7 }W n"   tdt|	| | Y nX q,W tdt|  td| d|  |dkr6td|| xbt
|	|D ]T\}}||d< dgt| }|| x(| D ]}||krtd||| < qtW qBW t|t|kstdt| dt| dtd t }||| | |}t!||}td|  td|j"d xL| D ]@}x8|D ]0}||j# |_$|j%||j#  |_&||j# |_'q2W q(W t(||||||||S )ad  
    Perform a free wilson analysis
        : param scaffolds : scaffold or list of scaffolds to use for the rgroup decomposition
        : param mols : molecules to decompose
        : param scores : list of floating point numbers for the regression (
                             you may need convert these to their logs in some cases)
        : param decomp_params : RgroupDecompositionParams default [
                                    default_decomp_params = rdkit.Chem.rdRGroupDecomposition.RGroupDecompositionParameters()
                                    default_decomp_params.matchingStrategy = rgd.GA
                                    default_decomp_params.onlyMatchAtRGroups = False
                                   ]
                                If you only want to decompose on specific group locations
                                set onlyMatchAtRGroups to True


        >>> from rdkit import Chem
        >>> from freewilson import FWBuild, FWDecompose
        >>> from rdkit.Chem import Descriptors
        >>> scaffold = Chem.MolFromSmiles("c1cccnc1")
        >>> mols = [Chem.MolFromSmiles("c1cccnc1"+"C"*(i+1)) for i in range(100)]
        >>> scores = [Descriptors.MolLogP(m) for m in mols]
        >>> fw = FWDecompose(scaffold, mols, scores)
        >>> for pred in FWBuild(fw):
        ...   print(pred)

    For an easy way to report predictions see 

       >>> from freewilson import FWBuild, predictions_to_csv
       >>> import sys
       >>> predictions_to_csv(sys.stdout, FWBuild(fw))

   
    See FWBuild docs to see how to filter predictions, molecular weight or molecular properties.
    z>The number of molecules must match the number of scores #mols z	 #scores zDecomposing z molecules...r   zMatched z out of z(No scaffolds matched the input moleculesNT)ZasSmileszGet unique rgroups...r   Zoriginal_idxr   zfailed:zDescriptor size zReconstructed z6Could only reconstruct %s out of %s training moleculesZmoleculezNumber of descriptors(z)) doesn't match number of matcved scores(r;   zRidge Regressing...zR2 zIntercept = z.2f))r	   r    r!   
ValueErrorloggerinforgdZRGroupDecomposition	enumerater   zipZAddr   ZProcesserrorZGetRGroupsAsRowsr   	BlockLogsr   itemsr)   r   r(   printr   MolToSmilesloggingZwarningvaluesAssertionErrorr   Zfitpredictr   Z
intercept_r   r   Zcoef_r.   r$   rC   )Z	scaffoldsmolsscoresZdecomp_paramsrI   Zmatched_scoresZ
rgroup_idxr   Z
decomposerZmatchedZmatched_indicesimolZscoredecompositionblockerZrgroup_countsrL   Znum_molsrowr$   Z
row_smilesr-   r   ZreconstructedZ
descriptorZlmZpredsrH   Z
sidechainsr&   r&   r'   FWDecompose-  s    # 






"


0



rd   c       %   (   c   s   |j }|j}d}x| D ]}	|t|	9 }qW d}
d}d}d}d}d}d}d}d}d}d}d}d}d}|d pld}xtttj|  |dD ]\}}|r|| dkrtjd|
 d	| d
| d| d| d| d| d| d| d| d| t	j
d d}d}dg| }x,|D ]$}d||j< ||j7 }||j7 }qW t||jkrN|d7 }qt||}t||}|r|||s||d7 }qt||}t||}|r||s|d7 }q||gd }t||}t||}|r||s|d7 }q|d7 }tdd |D } dtdd |D }!yt|!}"W n   |d7 }wY nX d}#|r\||"s\|d7 }qt|"}$t||$|V  |
d7 }
qW td|
 d	| d| d| d| d| d| d| d| d| d| d| d| d| d| d| d| d| d| & d S )Nr   r   i g    _g    _B
   )ZtotalzWrote z results out of z
	
	In Training Setz

	Bad MW: z
	Bad Pred: z
	Bad Filters: z
	Bad smi: z

	min mw: z

	max mw: z
	
	min pred: z
	max pred: )filec             S   s   g | ]
}|j qS r&   )r   )r*   gr&   r&   r'   r,     s    z_enumerate.<locals>.<listcomp>r   c             S   s   g | ]
}|j qS r&   )r   )r*   rg   r&   r&   r'   r,     s    Fz
	In Training set: z
	Bad HVY: z
	min hvy: z
	max hvy: )rG   rF   r!   r   rR   	itertoolsproductrY   debugsysstderrr$   r5   r7   r/   rI   minr   r\   r   r   r(   r   rX   r   rP   )%r   fw	mw_filter
hvy_filterpred_filter
mol_filterrG   rF   Znum_productsrZwroteZin_training_setZrejected_predZrejected_mwZrejected_hvyZ	good_predZrejected_filtersZrejected_badZmin_mwZmax_mwZmin_hvyZmax_hvyZmax_predZmin_predZdeltar_   groupsr5   hvyrI   rg   predr   Zsmir`   ZrejectedZout_smir&   r&   r'   
_enumerate  s    
$R










rw   )rn   rM   c          	   c   s>  t  }t }tt}tt}x| j D ]r\}	}
|	dkrD|
||	< q*||	 }xN|
D ]F}|| qRt|j	dkr|
|j	 ||j	 | qR|| qRW q*W td x.| D ]"\}}td| dt|  qW dd t| D }x$t|| ||||dD ]}|V  qW t }x4| jD ]*}|d d	kr$|
t|dd
  q$W |rbtd x|D ]}|t| }d| jd i}|| |dddd |D  < x"|D ]}d| }|| ||< qW x0| D ]$\}}td| dt|  qW x6tdd t| D | ||||dD ]}|V  q$W qhW d
S )a  Enumerate the freewilson decomposition and return their predictions

       :param fw: FreeWilsonDecomposition generated from FWDecompose
       :param pred_filter: return True if the prediction is in a desireable range
                           e.g.  lambda pic50: pic50>=8
       :param mw_filter: return True if the enumerated molecular weight is in a desireable rrange
                           e.g. lambda mw: 150 < mw < 550
       :param hvy_filter: return True if the enumerated heavy couont is in a desireable rrange
                           e.g. lambda hvy: 10 < hvy < 50
       :param mol_filter: return True if the molecule is ok to be enumerated
                           e.g. lambda mol: -3 < Descriptors.MolLogp(mol) < 5
    Corer   z,Enumerating rgroups with no broken cycles...	c             S   s   g | ]\}}|qS r&   r&   )r*   keyr-   r&   r&   r'   r,     s    zFWBuild.<locals>.<listcomp>)rq   ro   rp   rr   r   RNz)Enumerating rgroups with broken cycles...zR%sr   c             S   s   g | ]}t |qS r&   )str)r*   r+   r&   r&   r'   r,   5  s    c             S   s   g | ]\}}|qS r&   r&   )r*   rz   r-   r&   r&   r'   r,   =  s    )r   rU   r   r	   r    r   rV   r   r!   r3   r   rY   rP   r0   rw   r   r   )rn   rq   ro   rp   rr   rb   ZcyclesZrgroups_no_cyclesZrgroup_cyclesrz   r-   Z	no_cyclesrg   kvr   ZresindicesZrgroup_indicesZmissingr#   r&   r&   r'   FWBuild  sb    




 
 r   c             C   s(   | d dkr dt | dd fS | dfS )z-Sort groups like R1 R2 R10 not R1 R10 R2
    r   r{   r   N)r   )rs   r&   r&   r'   _rgroup_sortE  s     r   )ra   c             C   s   d}x|D ]}|st  }x|jD ]}|| q W t|td}i }xt|D ]\}}	|||	< qLW t| }ddgdd t|D  }
|	|
 dgt
| }	x|jD ]}|j|	||j < qW |jt|jg|	 }|	| q
W |
S )zOutput predictions in csv format to the output stream

       :param outstream: output stream to write results
       :param decomposition: freewillson decomposition
       :param predictions: list of Predictions to output
    N)rz   r   r   c             S   s   g | ]}| d qS )Z_smilesr&   )r*   rgr&   r&   r'   r,   ^  s    z&predictions_to_csv.<locals>.<listcomp> )r   r   r   r0   r   rR   csvwriterr    Zwriterowr!   r   r-   r<   r   )Z	outstreamra   Zpredictionsr   rv   r   r-   lookupr_   r   headerr"   rc   r&   r&   r'   predictions_to_csvK  s&    


r   c                 s"  ddl m  ddlm tdddgks.ttdddgksDttdddgksZttd	ddgkspt d
}  fddtdD }fdd|D }t	| ||}xnt
|dd dd dd fdddD ]D}t }x|jD ]}||j qW t|}t|dddgkstqW d S )Nr   )r   )r   zC[*:1]N.[H][*:2]12zC[*:1]N.[HH][*:2]zC[*:1]N.[2H][*:2]zC[*:1]N.[CH2][*:2]z[*:2]c1cccnc1[*:1]c                s.   g | ]&}  d |d  d d|d   qS )rG   r   Zc1cccnc1C)r   )r*   r_   )r   r&   r'   r,   r  s    z#test_freewilson.<locals>.<listcomp>re   c                s   g | ]}  |qS r&   )MolLogP)r*   r#   )r   r&   r'   r,   s  s    c             S   s   d|   k odk S   S )N   r&   )r+   r&   r&   r'   <lambda>w      z!test_freewilson.<locals>.<lambda>c             S   s   d|   k odk S   S )Nd   i  r&   )r5   r&   r&   r'   r   x  r   c             S   s   d|   k odk S   S )Nre   2   r&   )ru   r&   r&   r'   r   y  r   c                s   d  |   k odk S   S )Nr   r   )r   )r#   )r   r&   r'   r   z  r   )rq   ro   rp   rr   rx   ZR1ZR2)rdkitr   
rdkit.Chemr   r1   r2   r[   r   rangerd   r   r   r   r   r-   r0   r    )Zscaffoldr]   r^   rn   rv   r   Z	sidechainr&   )r   r   r'   test_freewilsonh  s(    
r   c              C   s   d} t | dddd}t| }|jt|ks2t|jt|ksFt|j	dksTtd} t | dddd}|jdksvt|jd	kst|j	dkstd
} t | dddd}|jdkst|jdkst|j	t
 kstd S )Nz[*:2]c1ccccc1[*:1]rx   r   g?)r   r-   r   r.   )r   r   z[*:2]cccccc[*:1]gMbX9R@   ZNoper   )r)   r   r   r5   r   r4   r[   r7   r6   r3   r/   )r   r   r`   r&   r&   r'   test_rgroups  s     
r   )NNNN)NNNN)2rB   r   r   rQ   r   r   r   r   r   Zsklearn.linear_modelr   Zsklearn.metricsr   collectionsr	   r
   r   rh   Zmathrk   typingr   rY   r   rer   Z	getLoggerrO   r   compiler1   r(   r)   rC   ZRGroupDecompositionParametersZdefault_decomp_paramsZGAZmatchingStrategyZonlyMatchAtRGroupsZRGroupScoreZFingerprintVarianceZscoreMethodZremoveHydrogensPostMatchrd   rw   r   r   r   r   r   r&   r&   r&   r'   <module>   sJ   

2-
{
M   M