B
    M}\                 @   s  d Z ddlZddlZddlmZ ddlmZ ddlmZmZ ddl	Z	ddl
Z
ddlmZ ddlmZmZ ddlmZmZ dd	lmZmZmZmZmZmZ ddlZd
dlmZ d
dlmZmZm Z m!Z!m"Z"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/m0Z0m1Z1m2Z2 d
dl3m4Z4m5Z5m6Z6 d
dl'm7Z7 e78ddkr^e7de78d Z7dZ9de7 Z:dd Z;dd e1D Z<eeddedded d!ed"d#gZ=de e"e=e!e#e$d$Z>e1e!e0e"e/e"iZ?d%ed& d%d%ed' d%d(d)dd*Z@d+d,d-d.ZAe1e0e/d/ZBd0d1d2d3d4d5d6d7ZCG d8d9 d9eDZEG d:d; d;eEZFdOd<d=ZGd>d? ZHeIejJd@dAdBZKdCdD ZLdEdF ZMe(jNddGdfdHdIZOG dJdK dKeDZPeQedLdMdNZRdS )P
    N)TextIO)datetime)logsqrt)StringIO)urlopenRequest)urlparse
urlunparse)arrayasarrayfloat64oneszerosany   )Color)ColorSchemeSymbolColor
monochromehydrophobicitybase_pairing	chemistrycharge)	Dirichlet)seq_io)amino_acid_composition)entropy)Alphabetunambiguous_dna_alphabetunambiguous_rna_alphabetunambiguous_protein_alphabetSeqList)isfloatArgumentErrorstdrepr)__version__+z:Create sequence logos from biological sequence alignments.z
WebLogo %sc             C   s   dd l }|j|  d S )Nr   )Zweblogo._cgiZ_cgimain)Zhtdocs_directoryweblogo r,   V/home/fristb/BIRCH/lib-linux-x86_64/python/lib/python3.7/site-packages/weblogo/logo.pycgix   s    r.   c             C   s   g | ]}t | qS r,   )r   ).0Z_kr,   r,   r-   
<listcomp>}   s    r0   GZorangeZTUZredCZblueAZgreen)autor   zbase pairingclassicr   r   r   g      ?   
   go@gФH#?)bitsZnatsdigitsZkTzkJ/molzkcal/molZprobabilityg@g%@g4333330@)ZsmallmediumZlarge)ZproteinZrnaZdnag      D@g     @I@g      C@g      B@g     E@g      E@gYQ@)z
H. sapienszE. colizS. cerevisiaez
C. eleganszD. melanogasterzM. musculuszT. thermophilusc               @   s    e Zd ZdZdd Zdd ZdS )LogoOptionsa   A container for all logo formatting options. Not all of these
    are directly accessible through the CLI or web interfaces.

    To display LogoOption defaults::

    >>> from weblogo import *
    >>> LogoOptions()

    All physical lengths are measured in points. (72 points per inch, 28.3 points per cm)

    Args:
        creator_text:           Embedded as comment in figures.
        logo_title:             Creates title for the sequence logo
        logo_label:             An optional figure label, added to the top left (e.g. '(a)').
        unit_name:              See std_units for options. (Default 'bits')
        yaxis_label:            Defaults to unit_name
        xaxis_label:            Add a label to the x-axis, or hide x-axis altogether.
        fineprint:              Defaults to WebLogo name and version

        show_yaxis:              Display entropy scale along y-axis (default: True)
        show_xaxis:             Display sequence numbers along x-axis (default: True)
        show_ends:              Display label at the ends of the sequence (default: False)
        show_fineprint:          Toggle display of the WebLogo version information in the lower
                                      right corner. Optional, but we appreciate the acknowledgment.
        show_errorbars:          Draw errorbars (default: False)
        show_boxes:              Draw boxes around stack characters (default: True)
        debug:                   Draw extra graphics debugging information.
        rotate_numbers:          Draw xaxis numbers with vertical orientation?
        scale_width:             boolean, scale width of characters proportional to ungaps
        pad_right:               Make a single line logo the same width as multiline logos
                                      (default: False)

        stacks_per_line:          Maximum number of logo stacks per logo line. (Default: 40)
        yaxis_tic_interval:       Distance between ticmarks on y-axis(default: 1.0)
        yaxis_minor_tic_ratio:    Distance between minor tic ratio
        yaxis_scale:              Sets height of the y-axis in designated units
        xaxis_tic_interval:       Distance between ticmarks on x-axis(default: 1.0)
        number_interval:          Distance between ticmarks (default: 1.0)

        shrink_fraction:          Proportional shrinkage of characters if show_boxes is true.

        errorbar_fraction:        Sets error bars display proportion
        errorbar_width_fraction:  Sets error bars display
        errorbar_gray:            Sets error bars' gray scale percentage (default .75)

        resolution:               Dots per inch (default: 96). Used for bitmapped output
                                       formats

        default_color:            Symbol color if not otherwise specified
        color_scheme:             A custom color scheme can be specified using CSS2 (Cascading
                                       Style Sheet) syntax.
                                       E.g. 'red', '#F00', '#FF0000', 'rgb(255, 0, 0)',
                                       'rgb(100%, 0%, 0%)' or 'hsl(0, 100%, 50%)' for the color red.

        stack_width:              Scale the visible stack width by the fraction of symbols in
                                       the column (I.e. columns with many gaps of unknowns are
                                       narrow.)  (Default: yes)
        stack_aspect_ratio:       Ratio of stack height to width (default: 5)

        logo_margin:              Default: 2 pts
        stroke_width:             Default: 0.5 pts
        tic_length:               Default: 5 pts
        stack_margin:             Default: 0.5 pts

        small_fontsize:           Small text font size in points
        fontsize:                 Regular text font size in points
        title_fontsize:           Title text font size in points
        number_fontsize:          Font size for axis-numbers, in points.

        text_font:                Select font for labels
        logo_font:                Select font for Logo
        title_font:               Select font for Logo's title

        first_index:              Index of first position in sequence data
        logo_start:               Lower bound of sequence to display
        logo_end:                 Upper bound of sequence to display

    c             K   s\  d| _ t| _d| _d| _d| _d| _d| _d| _d| _	d| _
d| _d| _d| _d| _d	| _d| _d	| _d| _d| _d
t | _d	| _d| _d| _d| _d| _d| _d| _td| _d| _ d	| _!d| _"d| _#d| _$t%d | _&d| _'d| _(d	| _)d| _*d| _+d| _,d| _-d| _.d| _/d| _0d| _1d| _2d| _3d| _4d| _5x"|6 D ]\}}t7| || q>W dS )z Create a new LogoOptions instance.

        >>> logooptions = LogoOptions(logo_title = "Some Title String")
        >>> logooptions.show_yaxis = False
        >>> repr(logooptions)

        N (   r8   Tg      ?   r   FzWebLogo g      ?g?g      ?g      ?g      X@Zblackr6   r:      r7         ZArialMTzArial-BoldMT)8alphabetrelease_descriptionZcreator_text
logo_titleZ
logo_labelstacks_per_line	unit_name
show_yaxisyaxis_labelyaxis_tic_intervalyaxis_minor_tic_ratioyaxis_scale
show_xaxisxaxis_labelxaxis_tic_intervalrotate_numbersnumber_interval	show_endsannotateshow_fineprintr'   	fineprintZ
show_boxesshrink_fractionZshow_errorbarserrorbar_fractionZerrorbar_width_fractionZerrorbar_gray
resolutionr   Zby_nameZdefault_colorcolor_schemedebuglogo_marginstroke_width
tic_length	std_sizesstack_widthstack_aspect_ratiostack_margin	pad_rightsmall_fontsizefontsizetitle_fontsizenumber_fontsizeZ	text_fontZ	logo_fontZ
title_fontfirst_index
logo_startlogo_endZscale_widthZreverse_stacksitemssetattr)selfkwargskvr,   r,   r-   __init__  sf    	

zLogoOptions.__init__c             C   s"   t t|  }|  t| |S )N)listvarskeyssortr&   )rk   Z
attributesr,   r,   r-   __repr__e  s    zLogoOptions.__repr__N)__name__
__module____qualname____doc__ro   rt   r,   r,   r,   r-   r;      s   NRr;   c               @   s   e Zd ZdZdddZdS )
LogoFormataC   Specifies the format of the logo. Requires LogoData and LogoOptions
    objects.

    >>> logodata = LogoData.from_seqs(seqs)
    >>> logooptions = LogoOptions()
    >>> logooptions.title = "A Logo Title"
    >>> format = LogoFormat(logodata, logooptions)

    Raises:
        ArgumentError: if arguments are invalid.
    Nc       
      C   s  |dk	r| j |j  |j| _|j| _d| _d| _d| _d| _d| _	d| _
d| _d| _d| _d| _d| _d| _d| _d| _d| _d| _d| _| j| j | _ddd dfddd d	fd
dd dfddd dfddd dfddd dfddd dfddd dfddd dfddd dfd d!d d"fd#d$d d%fd&d'd d(fd)d*d d+fd,d-d d.fd/d0d d1ff}x8|D ]0}|d2 t| |d3 sdt|d4 |d3 qdW | jdkr| j| _| jdkr| j| j d2 | _| j| j d2 | _| jd3krtd5d6| j| j d3k rtd7d8| j| j | jkr,td9d8| jr:d:| _| j sHd| _!| j"rVd:| _| j#dkrj| j$| _#| j#rzd:| _%nd| _%d| _&| j'st(| j$ }|r| jdkrtd;d<t)t*| j| | _'nd=| _'| j'd>krtd?d@| j+| j'kr|  j+dA  _+t,| j+| j- | _| j.dkr@| jt/kr:t/| j | _.nt0| _.d2| jd2 | j1  | _| jd2krz| j2szt3| j1| j| _1| jd4| j4  | _	| j5r| j6dB | _
n$| j&r| j7r| j6dC | _
ndD| _
| j&r| j7r| j6dC | _ndD| _| j7r| j8r| j9dE | _n| j9dC | _ndD| _dD| _| jr4| j:| _nd3| _d>| _| jrX|  j| j67  _| j!rt*| j d3kr|  j| j;7  _| j| j | j | _| j| j1 | j
 | j | _t<d4| j= | j | j | j| j  | _t<d4| j= | j | _t>? @dF| _dG}tAdHtBdGtCdIi}| j&r.| j|kr.|| j }|| _| jDdkrg | _DxLtE| jD ]>}|| j }	|	| jF d3kr| jDGdJ|	  n| jDGdK qRW t*| jD| jkrtdLdMdS )Nz, Create a new LogoFormat instance.

        NFrE   c             S   s   | dkS )Nr   r,   )xr,   r,   r-   <lambda>      z%LogoFormat.__init__.<locals>.<lambda>z!Stacks per line must be positive.r^   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   z&Stack width must be greater than zero.r_   c             S   s   | dkS )Nr   r,   )rz   r,   r,   r-   r{     r|   z-Stack aspect ratio must be greater than zero.rc   c             S   s   | dkS )Nr   r,   )rz   r,   r,   r-   r{     r|   zFont sizes must be positive.rb   c             S   s   | dkS )Nr   r,   )rz   r,   r,   r-   r{     r|   rd   c             S   s   | dkS )Nr   r,   )rz   r,   r,   r-   r{     r|   rV   c             S   s   | dko| dkS )Ng        g      ?r,   )rz   r,   r,   r-   r{     r|   zCThe visible fraction of the error bar must be between zero and one.rI   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   z*The yaxis tic interval cannot be negative.yaxis_minor_tic_intervalc             S   s   | o
| dk  S )Ng        r,   )rz   r,   r,   r-   r{     r|   zDistances cannot be negative.rN   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   z'Tic interval must be greater than zero.rP   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   z!Invalid interval between numbers.rU   c             S   s   | dko| dkS )Ng        g      ?r,   )rz   r,   r,   r-   r{     r|   zInvalid shrink fraction.r`   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   zInvalid stack margin.rZ   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   zInvalid logo margin.r[   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   zInvalid stroke width.r\   c             S   s   | dkS )Ng        r,   )rz   r,   r,   r-   r{     r|   zInvalid tic length.r   r   r6   z$Logo must contain at least one stackrh   z6Logo range extends before start of available sequence.Z
logo_rangez4Logo range extends beyond end of available sequence.TzNeed an alphabetrB   g      ?g        zInvalid yaxis scalerK   g       @g      @g      ?   g      @ -pdz%dr<   z-Annotations must be same length as sequences.rR   )H__dict__updaterB   lengthZseqlenZ
show_titleZshow_xaxis_labelr}   Zlines_per_logoZ
char_widthZline_margin_leftZline_margin_rightZline_margin_bottomZline_margin_topZtitle_heightZxaxis_label_heightZline_height
line_widthZlogo_heightZ
logo_widthZcreation_dateend_typer^   r_   Zstack_heightgetattrr%   rg   rf   rh   Ztotal_stacksrD   rT   rS   rM   rH   rF   Zshow_yaxis_labelrQ   rK   	std_unitsr   lenrI   floatrJ   rX   default_color_schemesr   rE   ra   minr`   rG   rc   rL   rO   re   rd   rb   intrZ   r   now	isoformatr"   r!   r    rR   rangerP   append)
rk   ZlogodataZlogooptionsZarg_conditionstestZconversion_factorr   Z	end_typesiindexr,   r,   r-   ro   {  s   







&

zLogoFormat.__init__)N)ru   rv   rw   rx   ro   r,   r,   r,   r-   ry   n  s   ry   c       
      C   sd  | dkrdS |   }| dkr$dS |dkrD|dk	rDttt|}|dk rTtd| dkrt|tt| }n| dks| dkr|tkr|tt	t
 }n|tt| }n|tkr|tt|  }nr|d d	kr|tt|dd  }nJt|r|tt|d
  }n(| d dkr:| d dkr:| dd }|dddddddd }t|t|d krtdtt|t
 }yRxLtt|d D ]8}||d  }||}t||d d  }	|	||< qW W n tk
r   tdY nX t|dkr$td|t| }||9 }ntd|  t|t|kr`td|S )a   Parse a description of the expected monomer distribution of a sequence.

    Valid compositions:

    * None or 'none'
        No composition sepecified
    * 'auto' or 'automatic'
        Use the typical average distribution
        for proteins and an equiprobable distribution for
        everything else.
    * 'equiprobable'
        All monomers have the same probability.
    * a percentage, e.g. '45%' or a fraction '0.45'
        The fraction of CG bases for nucleotide alphabets
    * a species name, e.g. 'E. coli', 'H. sapiens',
        Use the average CG percentage for the species's genome.
    * An explicit distribution
        e.g. {'A':10, 'C':40, 'G':40, 'T':10}
    Nnoner   zWeight cannot be negative.Zequiprobabler4   Z	automaticr)   %g      Y@{}r   ,r   '":r6   z0Explicit prior does not match length of alphabetz!Cannot parse explicit compositiong      z&Explicit prior does not match alphabetz$Unknown or malformed composition: %sz7The sequence alphabet and composition are incompatible.)striplowerr   r   r   
ValueErrorequiprobable_distributionr"   r   aa_compositionr   std_percentCGbase_distributionr$   replacesplitr   r   ordr   sum)
ZcompositionrB   weightcomppriorexplicitrletterr   valuer,   r,   r-   parse_priorL  sZ    


r   c             C   sJ   d| d  d }| d d }| d d }d| d  d }t ||||ftS )Ng      ?g      Y@g       @d   )r   r   )Z	percentCGr3   r2   r1   Tr,   r,   r-   r     s
    r   )r   returnc             C   s   t | t|  S )N)r   r   )r   r,   r,   r-   r     s    r   c              C   s   t t } d| d< | d= | S )zv Return a dictionary mapping between the names of formats for the sequence data
    and the corresponing parsers.
    transfacplain)dictr   Zformat_names)Zfin_choicesr,   r,   r-   _seq_formats  s    r   c              C   s(   dd t jD } | d | d | S )z? Returns a list of the names of accepted sequence data formats.c             S   s   g | ]}|j d  qS )r   )names)r/   fr,   r,   r-   r0     s    z_seq_names.<locals>.<listcomp>r   r   )r   formatsremover   )Z	fin_namesr,   r,   r-   
_seq_names  s    

r   Fc       
      C   s   t tjd|}|dkrL| |}| d}|dkrBtd| t|} n| tjkrbt|  } | 	d || }|dkst
|dkrtd|rx t|D ]\}}	|	 ||< qW |rt||_nt||_|S )zRead sequence data from the input stream and return a seqs object.

    The environment variable WEBLOGO_MAX_FILE_SIZE overides the max_file_size argument.
    Used to limit the load on the WebLogo webserver.
    ZWEBLOGO_MAX_FILE_SIZEr   r6   r<   z+File exceeds maximum allowed size: %d bytesNz,Please provide a multiple sequence alignment)r   osenvirongetreadIOErrorr   sysstdinseekr   r   	enumeratemaskr   rB   which)
ZfinZinput_parserrB   Zignore_lower_caseZmax_file_sizedataZ	more_dataseqsr   sr,   r,   r-   read_seq_data  s(    




r   c               @   s`   e Zd ZdZdddZedeejejd dddZ	ede
ejd dd	d
ZedddZdS )LogoDataa  The data needed to generate a sequence logo.

    Args:
        alphabet: The set of symbols to count.
                   See also --sequence-type, --ignore-lower-case
        length:   All sequences must be the same length, else WebLogo will return an error
        counts:   An array of character counts
        entropy:  The relative entropy of each column
        entropy_interval: entropy confidence interval
     Nc             C   s(   || _ || _|| _|| _|| _|| _dS )zCreates a new LogoData objectN)r   rB   countsr   entropy_intervalr   )rk   r   rB   r   r   r   r   r,   r,   r-   ro     s    zLogoData.__init__)rB   r   r   r   c             C   sf  |j \}}|dk	rt|t}|dks0t|dkrt|}t|t}d}xtd|D ]6}	t||	 }
|
dkrtd||	< qR|t||	  ||	< qRW nt|t}t|dft}t|}xntd|D ]`}	t||	 t}||7 }t|}|	|t| ||	< |
|t| d\||	 d< ||	 d< qW ttj|ddt}t|}|dkrLtd|| }| ||||||S )	z$Build a LogoData object from counts.Ng        r   r6   gffffff?r   )Zaxisz
No counts.)shaper   r   r   r   r   r   r   r   Zmean_relative_entropyZinterval_relative_entropynpr   maxr   )clsrB   r   r   
seq_lengthr3   Rentr   r   r2   alphaZ	posteriorr   Z
max_weightr,   r,   r-   from_counts  s6    	




,
zLogoData.from_counts)r   r   r   c             C   s|   t |dkst |d dkr$tdt |d }x2t|D ]&\}}|t |kr:td|d  dq:W | }| |j||S )z<Build a LogoData object from a SeqList, a list of sequences.r   zNo sequence data found.z@Sequence number %d differs in length from the previous sequencesr   	sequences)r   r   r   r%   Zprofiler   rB   )r   r   r   r   r   r   r   r,   r,   r-   	from_seqs-  s    zLogoData.from_seqs)r   c             C   s  t  }td|d td|d td|d td|d td|d td|d td|d td	d
|d x| jD ]}t|d|d qpW td|d xt| jD ]}t|d d|d x | j| D ]}t|d|d qW td| j|  d|d | jd k	r4td| j| d  d|d td| j| d  d|d ntd
d
d|d | jd k	rhtd| j|  d|d td|d qW td|d |	 S )Nz## LogoData)filez5# First column is position number, counting from zeroz*# Subsequent columns are raw symbol countsz+# Entropy is mean entropy measured in nats.z-# Low and High are the 95% confidence limits.z:# Weight is the fraction of non-gap symbols in the column.z#	#	)endr   z 	zEntropy	Low	High	Weightr   z%6.4fr   r<   z# End LogoData)
r   printrB   r   r   r   r   r   r   getvalue)rk   outar   cr,   r,   r-   __str__D  s8    
zLogoData.__str__)NNNNNN)N)N)ru   rv   rw   rx   ro   classmethodr   r   ndarrayr   r#   r   strr   r,   r,   r,   r-   r     s   
 
	,r   )
target_urlr   c             C   s   t | \}}}}}}|dkr6|dkr6|dkr6td| |dkr^|dkrJd}t|||||df} |d	krd
}t | \}}}	}}}|	dd }
||
 } t| }t|}t }t	|| |
d |S )z&opens files from a remote URL locationhttphttpsftpzCannot open url: %szwww.dropbox.comzdl=0zdl=1r<   zdrive.google.comz.https://docs.google.com/uc?export=download&id=/   r   )r
   r   r   r   r	   r   tempfileTemporaryFileshutilcopyfileobjr   )r   schemeZnet_locationpathparamqueryfragquery2Zgoogle_directdl_fragZpath_rawZid_filereqrestempr,   r,   r-   _from_URL_fileopenh  s$    

r   )N)Srx   r   r   Z	typing.ior   r   mathr   r   r   r   ior   Zurllib.requestr   r	   urllib.parser
   r   numpyr   r   r   r   r   r   r   Zcolorr   Zcolorschemer   r   r   r   r   r   r   Zlogomathr   r<   r   r   r   Zscipy.statsr   seqr   r    r!   r"   r#   utilsr$   r%   r&   r'   finddescriptionrC   r.   r   r5   Zstd_color_schemesr   r   r]   Zstd_alphabetsr   objectr;   ry   r   r   r   r   r   r   r   r   r   r   r   r   r,   r,   r,   r-   <module>(   s    $(

 , _
Q	' 