ó
a#nSc           @   s(  d  Z  d d l m Z d d l Z d d l Z d d l Z d d l m Z m Z m	 Z	 d d l
 m Z d d l m Z d d l m Z d d l Z d d l Z d d l Z d Z d	 e j d
 „ Z e j d „ Z d g g  d	 d „ Z d	 d d „ Z d d „ Z d „  Z e d k r$d d l Z y& e j e j d d d\ ƒ \ Z Z Wn$ d d l Z e j  ƒ  e ƒ  n Xe j ƒ  Z! e j" e! ƒ d g e! _# d	 e! _$ d	 e! _% d e! _& d e! _' d	 e! _( d e! _) d	 e! _* d e! _+ d e! _, d	 e! _- d e! _. xUe D]M\ Z/ Z0 e/ d k r"e0 e! _1 n  e/ d k r:e0 e! _& qþe/ d  k sRe/ d! k r—e2 e0 ƒ e! _# e3 e! j# ƒ e j4 e j5 f k rKe! j# f e! _# qKqþe/ d" k rµe6 e0 ƒ e! _7 qþe/ d# k rÍe0 e! _8 qþe/ d$ k råe0 e! _9 qþe/ d% k rýd e! _: qþe/ d& k rd	 e! _$ d e! _% qþe/ d' k r?d e! _$ d	 e! _% qþe/ d( k r]e6 e0 ƒ e! _; qþe/ d) k r{e6 e0 ƒ e! _< qþe/ d* k r“e0 e! _' qþe/ d+ k r«d e! _( qþe/ d, k rÍe= e0 ƒ d e! _) qþe/ d- k råd e! _* qþe/ d. k rýd	 e! _+ qþe/ d/ k rd e! _- qþe/ d0 k r3e= e0 ƒ e! _. qþe/ d1 k rþe0 e! _, qþqþWe! j1 sce! j& rre ƒ  d2 GHn  e d3 ƒ e j> e! j1 e! j& d4 e j? d5 e j@ d6 e! j) d7 e jA ƒZB eB jC ƒ  ZD eB jE ƒ  ZF e d8 eF ƒ e jG eF d9 f e j6 ƒ ZH e jG eF e jI ƒ ZJ d g eF ZL g  ZM e! j9 r?e e! j1 e! j9 ƒ ZN e d: ƒ eN jO ƒ  ZP eP jQ d; e! j9 e! j8 f ƒ e d< ƒ y eP jR ƒ  ZS Wn d ZS n Xx— eS r5e d= eT eM ƒ ƒ eS d	 ZS y  eM jU e jV eW eS ƒ ƒ ƒ Wn" d d l Z e j  ƒ  d> GHn Xe d? ƒ y eP jR ƒ  ZS WqŸd ZS qŸXqŸWd ZP nc x` e D]X ZX y e jY eZ eX d@ ƒ ƒ Z[ Wn& d d l Z dA eX GHe j  ƒ  qFXeM jU e[ ƒ qFWeT eM ƒ Z\ i  Z] dB g eT eM ƒ Z^ xÞe_ eM ƒ D]Ð\ Z` Z[ eB Za y e[ jb Zc Wn ed k
 rn Xe je ec ƒ e! j: r3e jf ea dC d ƒn  eg e[ dD ƒ rée! j% sTe! j$ rée jh ea jE ƒ  e[ ji dE d ƒ\ Zj Zk e! j; dF k rÍe jl ea e! j< e! j; d dG ej dH d ƒ\ Zm Zn ek en 7Zk em Zj n  e! j$ rûej ek Zk Zj qûn eo ea jE ƒ  ƒ Zk e dI eT ek ƒ ƒ e e[ eD ea dJ e! j# dK ek dL e! j* ƒ\ Zp Zq e dM ƒ e eq dN e! j+ dO e! j7 ƒZr e! j, r“eZ dP e! j, e` d f dQ ƒ Zs n d Zs xö e_ er ƒ D]è \ Zt Zu er et Zu eu d	 eL et <eH et d	 c eu d 7<eH et d c eu d9 7<e] jv et g  ƒ Zw ew jU eu d ƒ ew e] et <eJ et c d 7<es rU	es jx dR eu d	 ƒ n  eu d ep d9 k r¦eu d9 e^ e` k  r¦eu d9 e^ e` <q¦q¦We dS e^ e` ƒ qÔWe! j' rÐ	e e! eH eJ e] e\ dT ep ƒn-e\ d k rä	dU GHn dV GHd	 Zt xet eF k  rü
eJ et d	 k rü
e\ d k r¥
e	 jy e] et ƒ \ Zz Z{ e	 j| e{ eT e] et ƒ dW dX ƒZ} dY et d eH et d	 eJ et e} eH et d eJ et eJ et eW eL et ƒ f GHnJ dZ et d eH et d	 eJ et eH et d eJ et eJ et eW eL et ƒ f GHet d 7Zt qò	We	 jy e^ ƒ \ Zz Z{ d[ ez e{ f GHn  d S(]   s
	  Command line tool to construct an enrichment plot from saved composite models

Usage:  EnrichPlot [optional args] -d dbname -t tablename <models>

Required Arguments:
  -d "dbName": the name of the database for screening

  -t "tablename": provide the name of the table with the data to be screened

  <models>: file name(s) of pickled composite model(s).
     If the -p argument is also provided (see below), this argument is ignored.
     
Optional Arguments:
  - -a "list": the list of result codes to be considered active.  This will be
        eval'ed, so be sure that it evaluates as a list or sequence of
        integers. For example, -a "[1,2]" will consider activity values 1 and 2
        to be active

  - --enrich "list": identical to the -a argument above.      

  - --thresh: sets a threshold for the plot.  If the confidence falls below
          this value, picking will be terminated

  - -H: screen only the hold out set (works only if a version of 
        BuildComposite more recent than 1.2.2 was used).

  - -T: screen only the training set (works only if a version of 
        BuildComposite more recent than 1.2.2 was used).

  - -S: shuffle activity values before screening

  - -R: randomize activity values before screening

  - -F *filter frac*: filters the data before training to change the
     distribution of activity values in the training set.  *filter frac*
     is the fraction of the training set that should have the target value.
     **See note in BuildComposite help about data filtering**

  - -v *filter value*: filters the data before training to change the
     distribution of activity values in the training set. *filter value*
     is the target value to use in filtering.
     **See note in BuildComposite help about data filtering**

  - -p "tableName": provides the name of a db table containing the
      models to be screened.  If you use this argument, you should also
      use the -N argument (below) to specify a note value.
      
  - -N "note": provides a note to be used to pull models from a db table.

  - --plotFile "filename": writes the data to an output text file (filename.dat)
    and creates a gnuplot input file (filename.gnu) to plot it

  - --showPlot: causes the gnuplot plot constructed using --plotFile to be
    displayed in gnuplot.

iÿÿÿÿ(   t   RDConfigN(   t	   DataUtilst	   SplitDatat   Stats(   t	   DbConnect(   t   DataStructs(   t   CompositeRuns   2.4.0i    c         C   s/   | r | j  d |  ƒ n | j  d |  ƒ d S(   s¥    emits messages to _sys.stderr_
    override this in modules which import this one to redirect output

    **Arguments**

      - msg: the string to be displayed

  s   %s s   %s
N(   t   write(   t   msgt   noRett   dest(    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   messageO   s    	c         C   s   t  j j d |  ƒ d S(   s¥    emits messages to _sys.stderr_
    override this in modules which import this one to redirect output

    **Arguments**

      - msg: the string to be displayed

  s
   ERROR: %s
N(   t   syst   stderrR   (   R   R
   (    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   error\   s    	i   c         C   sò  |  j  | ƒ x’ t t |  ƒ ƒ D]~ } |  j | ƒ } t | d ƒ r  t | j ƒ t j k r  i  } t | d ƒ r’ x | j D] }	 d | |	 <q{ Wn  | | _ q  q  Wg  }
 |  j	 ƒ  r½ d } n d } | sÞ t t | ƒ ƒ } n  d } x| D]ù } | rQg  } xW t t |  ƒ ƒ D]: } |  j | ƒ } | j j
 | d ƒ s| j | ƒ qqWn d } | | } |  j | d | ƒ\ } } | r•|  j | ƒ } n  | d } | | k r¸| d 7} n  | | k rë |
 j | d | | | f ƒ që që W| |
 f S(   sÀ   collects the results of screening an individual composite model that match
    a particular value

   **Arguments**

     - mdl: the composite model

     - descs: a list of descriptor names corresponding to the data set

     - data: the data set, a list of points to be screened.

     - picking: (Optional) a list of values that are to be collected.
       For examples, if you want an enrichment plot for picking the values
       1 and 2, you'd having picking=[1,2].

    **Returns**

      a list of 4-tuples containing:

         - the id of the point 

         - the true result (from the data set)

         - the predicted result

         - the confidence value for the prediction
       
  t   _trainIndicesi   i    t
   onlyModelsiÿÿÿÿN(   t   SetInputOrdert   ranget   lent   GetModelt   hasattrt   typeR   t   typest   DictTypet   GetQuantBoundst   gett   appendt   Nonet   ClassifyExamplet   QuantizeActivity(   t   mdlt   descst   datat   pickingt   indicest   errorEstimatet   jt   tmpt   tist   vt   rest
   needsQuantt   nTrueActivest   it   uset   ptt   predt   conft   trueRes(    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   ScreenModelg   sD    ' 	 

$c         C   sª   | r |  j  d „  ƒ n  g  } d } d } xx t t |  ƒ ƒ D]d } |  | \ } } }	 }
 |
 | k r> |	 | k r | d 7} n  | d 7} | j | | | f ƒ q> q> W| S(   sú    Accumulates the data for the enrichment plot for a single model

    **Arguments**

      - predictions: a list of 3-tuples (as returned by _ScreenModels_)

      - thresh: a threshold for the confidence level.  Anything below
        this threshold will not be considered

      - sortIt: toggles sorting on confidence levels


    **Returns**

      - a list of 3-tuples:

        - the id of the active picked here
        
        - num actives found so far

        - number of picks made so far

  c         S   s   t  | d |  d ƒ S(   Ni   (   t   cmp(   t   xt   y(    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   <lambda>Ã   s    i    i   (   t   sortR   R   R   (   t   predictionst   thresht   sortItR)   t   nCorrectt   nPtsR,   t   idt   realR/   R0   (    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   AccumulateCountsª   s    
c         C   s~  t  |  d ƒ s |  j r d  Sd |  j } t | d ƒ } d } x| t | ƒ k  rI| | d k rI| d k r÷ t j | | ƒ \ }	 }
 t j |
 t | | ƒ d d ƒ} | j d | d | | d | | | | d | | | | | f ƒ nE | j d	 | d | | d | | | | d | | | | f ƒ | d 7} qC W| j ƒ  d
 |  j } t | d ƒ } d t	 } | | IJ| d k r¡| d | IJn  | d IJ| d k ræ| d } | d | I| d | | f IJn | d | IJ| j ƒ  t  |  d ƒ rz|  j
 rzyA d d  l } d d l m } | ƒ  } | d | ƒ t d ƒ Wqzd d  l } | j ƒ  qzXn  d  S(   Nt   plotFiles   %s.dats   w+i    i   t   leveliZ   s   %d %f %f %d %f
s   %d %f %f %d
s   %s.gnusõ   # Generated by EnrichPlot.py version: %s
  set size square 0.7
  set xr [0:]
  set data styl points
  set ylab 'Num Correct Picks'
  set xlab 'Num Picks'
  set grid
  set nokey
  set term postscript enh color solid "Helvetica" 16
  set term X
  s   set yr [0:%d]s   plot x with linesi   s!   replot "%s" using 1:2 with lines,s)   "%s" every %d using 1:2:5 with yerrorbarss   replot "%s" with pointst   showPlotiÿÿÿÿ(   t   Gnuplots	   load "%s"s   press return to continue...
(   R   R@   t   openR   R   t
   MeanAndDevt   GetConfidenceIntervalR   t   closet   __VERSION_STRINGRB   t   osRC   t	   raw_inputt	   tracebackt	   print_exc(   t   detailst   finalt   countst	   pickVectst   nModelst	   nTrueActst   dataFileNamet   outFR,   t   meant   sdt   confIntervalt   plotFileNamet   gnuFt   gnuHdrt   everyGapRI   RC   t   pRK   (    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   MakePlotÑ   sN    %"#(#"






	c           C   s!   t  j j t ƒ t  j d ƒ d S(   s$    displays a usage message and exits iÿÿÿÿN(   R   R   R   t   __doc__t   exit(    (    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   Usage  s    t   __main__s   d:t:a:N:p:cSTHF:v:s   thresh=s	   plotFile=RB   s
   pickleCol=t   OOBt   noSorts	   pickBase=t   doROCs
   rocThresh=s   enrich=t    s   -ds   -ts   -as   --enrichs   --threshs   -Ns   -ps   -Ss   -Hs   -Ts   -Fs   -vs
   --plotFiles
   --showPlots   --pickleCols   --OOBs   --noSorts   --doROCs   --rocThreshs
   --pickBases2   *******Please provide both the -d and -t argumentss   Building Data set
t   usert   passwordt	   pickleColt   pickleClasss	   npts: %d
i   s"   -> Retrieving models from databases$   select model from %s where note='%s's   -> Reconstructing modelss    Building model %ds   Model faileds     <-Donet   rbs   problems with model %s:g    „×—At   shufflet
   _splitFract   silentg        t   indicesToUset   indicesOnlys   screening %d examplesR"   R#   R$   t   accumulatingR:   R9   s   %s.%d.pickss   w+s   %s
s   Halfway point: %d
RR   sH   #Index	Avg_num_correct	Conf90Pct	Avg_num_picked	Num_picks	last_selections>   #Index	Avg_num_correct	Avg_num_picked	Num_picks	last_selectionRA   iZ   s   %d	%f	%f	%f	%d	%ss   %d	%f	%f	%d	%ss   Halfway point: %.2f(%.2f)(
   s   thresh=s	   plotFile=s   showPlots
   pickleCol=Rb   Rc   s	   pickBase=s   doROCs
   rocThresh=s   enrich=(~   R^   t   rdkitR    t   numpyt   cPicklet   copyt   rdkit.ML.DataR   R   R   t   rdkit.Dbase.DbConnectionR   R   t   rdkit.MLR   R   RI   R   RH   R   R   R   R2   R?   R]   R`   t   __name__t   getoptt   argvt   argst   extrasRK   RL   RM   t   SetDefaultst	   activeTgtt
   doTrainingt	   doHoldoutt   dbTableNameR@   RB   Rh   R$   R:   t   pickBaseRd   t	   rocThresht   argt   valt   dbNamet   evalR   t	   TupleTypet   ListTypet   floatt	   thresholdt   notet   persistTblNamet   shuffleActivitiest
   filterFract	   filterValt   intt   DBToDatat   defaultDBUsert   defaultDBPasswordt   ExplicitBitVectt   dataSett   GetVarNamesR    t   GetNPtsR<   t   zerosRN   t   integerRO   R   t   selPtst   modelst   connt	   GetCursort   curst   executet   fetchonet   blobR   R   t   loadst   strt	   modelNamet   loadRD   t   modelRQ   RP   t
   halfwayPtst	   enumeratet
   whichModelt   tmpDt   _randomSeedt   seedt   AttributeErrort   InitRandomNumberst   RandomizeActivitiesR   t   SplitIndicesRl   t   trainIdxt   testIdxt
   FilterDatat	   trainFiltt   tempR   R+   t	   screenRest   runningCountst   pickFileR,   t   entryR   R(   R   RE   RU   RV   RF   RW   (    (    (    sU   /public2/ftp/pub/ccp4/6.5/ccp4-6.5/lib/python2.7/site-packages/rdkit/ML/EnrichPlot.pyt   <module>C   s”  $C';	  
											!		
				


	
 
	
			
!
		
			#

(	" 