B
    h}\	[                 @   s2  d Z ddlmZ ddlZdddddd	d
ddddddddddd
gZG dd deZeddZededdZededdZ	ededdZ
ededd Zed!ed"d#Zed$ed%d&Zed'ed(d'Zed)ed*d)Zed+ed,d-Zed.d/ZG d0d deZG d1d	 d	eZd2d Zd3d Zd4d ZdS )5a   Alphabetic sequences and associated tools and data.

Seq is a subclass of a python string with additional annotation and an alphabet.
The characters in string must be contained in the alphabet. Various standard
alphabets are provided.


Classes ::

    Alphabet    -- A subset of non-null ascii characters
    Seq         -- An alphabetic string
    SeqList     -- A collection of Seq's

Alphabets ::

    o generic_alphabet  -- A generic alphabet. Any printable ASCII character.
    o protein_alphabet -- IUCAP/IUB Amino Acid one letter codes.
    o nucleic_alphabet -- IUPAC/IUB Nucleic Acid codes 'ACGTURYSWKMBDHVN-'
    o dna_alphabet -- Same as nucleic_alphabet, with 'U' (Uracil) an
        alternative for 'T' (Thymidine).
    o rna_alphabet -- Same as nucleic_alphabet, with 'T' (Thymidine) an
        alternative for 'U' (Uracil).
    o reduced_nucleic_alphabet -- All ambiguous codes in 'nucleic_alphabet' are
        alternative to 'N' (aNy)
    o reduced_protein_alphabet -- All ambiguous ('BZJ') and non-canonical amino
        acids codes ( 'U', Selenocysteine and 'O', Pyrrolysine)  in
        'protein_alphabet' are alternative to 'X'.
    o unambiguous_dna_alphabet -- 'ACGT'
    o unambiguous_rna_alphabet -- 'ACGU'
    o unambiguous_protein_alphabet -- The twenty canonical amino acid one letter
        codes, in alphabetic order, 'ACDEFGHIKLMNPQRSTVWY'

Amino Acid Codes::

    Code  Alt.  Meaning
    -----------------
    A           Alanine
    B           Aspartic acid or Asparagine
    C           Cysteine
    D           Aspartate
    E           Glutamate
    F           Phenylalanine
    G           Glycine
    H           Histidine
    I           Isoleucine
    J           Leucine or Isoleucine
    K           Lysine
    L           Leucine
    M           Methionine
    N           Asparagine
    O           Pyrrolysine
    P           Proline
    Q           Glutamine
    R           Arginine
    S           Serine
    T           Threonine
    U           Selenocysteine
    V           Valine
    W           Tryptophan
    Y           Tyrosine
    Z           Glutamate or Glutamine
    X    ?      any
    *           translation stop
    -    .~     gap

Nucleotide Codes::

    Code  Alt.  Meaning
    ------------------------------
    A           Adenosine
    C           Cytidine
    G           Guanine
    T           Thymidine
    U           Uracil
    R           G A (puRine)
    Y           T C (pYrimidine)
    K           G T (Ketone)
    M           A C (aMino group)
    S           G C (Strong interaction)
    W           A T (Weak interaction)
    B           G T C (not A) (B comes after A)
    D           G A T (not C) (D comes after C)
    H           A C T (not G) (H comes after G)
    V           G C A (not T, not U) (V comes after U)
    N   X?      A G C T (aNy)
    -   .~      A gap




Refs:
    http://www.chem.qmw.ac.uk/iupac/AminoAcid/A2021.html
    http://www.chem.qmw.ac.uk/iubmb/misc/naseq.html

Authors:
    GEC 2004,2005
    )arrayNAlphabetSeqrnadnaproteinSeqListgeneric_alphabetprotein_alphabetnucleic_alphabetdna_alphabetrna_alphabetreduced_nucleic_alphabetreduced_protein_alphabetunambiguous_dna_alphabetunambiguous_rna_alphabetunambiguous_protein_alphabetc               @   s   e Zd ZdZddddgZd)ddZd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zed*d'd(ZdS )+r   zoAn ordered subset of printable ascii characters.

    Status:
        Beta
    Authors:
        - GEC 2005
    _letters_alternatives
_ord_table
_chr_tableNc             C   sl  t | }ddd tddD }|dkr0|}||_tdd}|dkrL|}td	gd
 }xHt|D ]<\}}t|}	|	dkrt	d||	 d	krt	d|||	< qdW g }
g }xP|D ]H\}}||krt|}	||	 d	kr|t| ||	< |

| |
| qW d|
d|f|_|d d	ks&t||_tdgd
 }x"t|D ]\}}t|||< qDW | |_|S )aX  Create a new, immutable Alphabet.

        e.g.
        Alphabet( 'ACDEFGHIKLMNPQRSTVUWY',
                  zip('acdefghiklmnpqrstvuwy', 'ACDEFGHIKLMNPQRSTVUWY') )

        arguments:
        - letters -- the letters in the alphabet. The ordering determines
            the ordinal position of each character in this alphabet.
        - alt -- A list of (alternative, canonical) letters. The alternatives
            are given the same ordinal position as the canonical characters.
            e.g. (('?','X'),('x', 'X')) states that '?' and 'x' are synonomous
            with 'X'.  Values that are not in 'letters' are ignored. Alternatives
            that are already in 'letters' are also ignored. If the same
            alternative character is used twice then the alternative is assigned
            to the canonical character that occurs first in 'letters'. The
            default is to assume that upper and lower case characters are
            equivalent, unless both cases are included in 'letters'.
        raises:
            ValueError : Repetitive or otherwise illegal set of letters.
         c             S   s   g | ]}t |qS  )chr).0Z_Alphabet__ir   r   U/home/fristb/BIRCH/lib-linux-x86_64/python/lib/python3.7/site-packages/weblogo/seq.py
<listcomp>   s    z$Alphabet.__new__.<locals>.<listcomp>       NabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ      r   z)Alphabet cannot contain null character \0zRepetitive alphabet)object__new__joinranger   zip	bytearray	enumerateord
ValueErrorappendr   AssertionErrorr   decoder   )clslettersalternativesselfascii_lettersZequivalent_by_caseZ	ord_tableianZ_fromZ_toecZ	chr_tabler   r   r   r$      sD    


zAlphabet.__new__c             C   s0   | j }x$t|D ]}|t| dkrdS qW dS )z:True if all characters of the string are in this alphabet.r!   FT)r   strr*   )r2   stringtablesr   r   r   
alphabetic   s
    zAlphabet.alphabeticc             C   s
   | j | S )z9 The n'th character in the alphabet (zero indexed) or \0 )r   )r2   r6   r   r   r   r      s    zAlphabet.chrc             C   s   | j t| S )zgThe ordinal position of the character c in this alphabet,
        or 255 if no such character.
        )r   r*   )r2   r8   r   r   r   r*      s    zAlphabet.ordc                s&    fdd|D }d |}t| S )z9Convert a sequence of ordinals into an alphabetic string.c                s   g | ]} j | qS r   )r   )r   r6   )r2   r   r   r     s    z!Alphabet.chrs.<locals>.<listcomp>r   )r%   r   )r2   Zsequence_of_intsr8   r<   r   )r2   r   chrs  s    
zAlphabet.chrsc             C   s,   t |}|| j}tdt|d }|S )z;Convert an alphabetic string into a byte array of ordinals.Br   )r9   	translater   r   codecslatin_1_encode)r2   r:   r<   r5   r   r   r   ords	  s    zAlphabet.ordsc             C   s"   |  |std| | |S )zNormalize an alphabetic string by converting all alternative symbols
        to the canonical equivalent in 'letters'.
        zNot an alphabetic string.)r=   r+   r>   rC   )r2   r:   r   r   r   	normalize  s    
zAlphabet.normalizec             C   s   t | S )z% Letters of the alphabet as a string.)r9   )r2   r   r   r   r0     s    zAlphabet.lettersc             C   s   d| j  d t| j d S )NzAlphabet( 'z', zipz ))r   reprr   )r2   r   r   r   __repr__$  s    zAlphabet.__repr__c             C   s
   t | jS )N)r9   r   )r2   r   r   r   __str__'  s    zAlphabet.__str__c             C   s
   t | jS )N)lenr   )r2   r   r   r   __len__*  s    zAlphabet.__len__c             C   s   t |dsdS | j|jkS )Nr   F)hasattrr   )r2   otherr   r   r   __eq__-  s    
zAlphabet.__eq__c             C   s   |  | S )N)rL   )r2   rK   r   r   r   __ne__2  s    zAlphabet.__ne__c             C   s
   t | jS )N)iterr   )r2   r   r   r   __iter__5  s    zAlphabet.__iter__c             C   s
   | j | S )N)r   )r2   keyr   r   r   __getitem__8  s    zAlphabet.__getitem__c             C   s   t t| jS )N)hashtupler   )r2   r   r   r   __hash__;  s    zAlphabet.__hash__c                sH   |dkrt ttf}ddl  fdd|D }|t|}|| }|S )a   Returns the most appropriate unambiguous protein, RNA or DNA alphabet
        for a Seq or SeqList. If a list of alphabets is supplied, then the best alphabet
        is selected from that list.

        The heuristic is to count the occurrences of letters for each alphabet and
        downweight longer alphabets by the log of the alphabet length. Ties
        go to the first alphabet in the list.

        Nr   c                s(   g | ] }t | t| qS r   )sumtallylogrH   )r   r5   )mathseqsr   r   r   O  s    z"Alphabet.which.<locals>.<listcomp>)r   r   r   rX   indexmax)rY   Z	alphabetsZscorebestr5   r   )rX   rY   r   which>  s    zAlphabet.which)N)N)__name__
__module____qualname____doc__	__slots__r$   r=   r   r*   r>   rC   rD   r0   rF   rG   rI   rL   rM   rO   rQ   rT   staticmethodr]   r   r   r   r   r      s(   
KzACDEFGHIKLMNOPQRSTUVWYBJZX*-zacdefghiklmnopqrstuvwybjzx?.~zACDEFGHIKLMNOPQRSTUVWYBJZXX--zACGTURYSWKMBDHVN-zacgturyswkmbdhvnXx?.~zACGTURYSWKMBDHVNNNN--zACGTRYSWKMBDHVN-zacgtryswkmbdhvnXx?.~UuzACGTRYSWKMBDHVNNNN--TTzACGURYSWKMBDHVN-zacguryswkmbdhvnXx?.~TtzACGURYSWKMBDHVNNNN--UUzACGTN-z acgtryswkmbdhvnXx?.~TtRYSWKMBDHVz ACGTNNNNNNNNNNNNNN--TTNNNNNNNNNNzACDEFGHIKLMNPQRSTVWYX*-zacdefghiklmnpqrstvwyx?.~BbZzUuzACDEFGHIKLMNPQRSTVWYXX--XXXXCCZACGTZacgtZACGUZacguZACDEFGHIKLMNPQRSTVWYZacdefghiklmnopqrstuvwyZACDEFGHIKLMNOPQRSTUVWYz&ACGTRYSWKMBDHVN-acgtUuryswkmbdhvnXx?.~z&TGCAYRSWMKVHDBN-tgcaAayrswmkvhdbnXx?.~c                   s   e Zd ZdZeddfddZedd Zdd Zd3d	d
Z	dd Z
dd Zdd Z fddZdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd4d%d&Zd'd( Zd)d* Zd+d, Zd-d. Zd5d/d0Zd6d1d2Z  ZS )7r   aY   An alphabetic string. A subclass of "str" consisting solely of
    letters from the same alphabet.

    Attributes:
        alphabet    -- A string or Alphabet of allowed characters.
        name        -- A short string used to identify the sequence.
        description -- A string describing the sequence

    Authors :
        GEC 2005
    Nc             C   sZ   t | |}|d krt}t|ts*t|}||sDtd||f ||_||_||_	|S )Nz Sequence not alphabetic %s, '%s')
r9   r$   r	   
isinstancer   r=   r+   	_alphabetnamedescription)r/   objalphabetrf   rg   r2   r   r   r   r$     s    

zSeq.__new__c             C   s   | j S )N)re   )r2   r   r   r   ri     s    zSeq.alphabetc             C   s   | j | S )z[ Convert sequence to an array of integers
        in the range [0, len(alphabet) )
        )ri   rC   )r2   r   r   r   rC     s    zSeq.ordsc             C   sP   |s
| j }t|}dg| }|| }x$|D ]}||k r,||  d7  < q,W |S )zCounts the occurrences of alphabetic characters.

        Arguments:
        - alphabet -- an optional alternative alphabet

        Returns :
            A list of character counts in alphabetic order.
        r      )ri   rH   rC   )r2   ri   LcountsrC   r6   r   r   r   rV     s    



z	Seq.tallyc             C   s   | j }|t| || jS )N)	__class__r9   rQ   ri   )r2   rP   r/   r   r   r   rQ     s    zSeq.__getitem__c             C   s   | j }|t| || jS )N)rm   r9   __add__ri   )r2   rK   r/   r   r   r   rn     s    zSeq.__add__c             C   s   | j }|t| || jS )N)rm   r9   rn   ri   )r2   rK   r/   r   r   r   __radd__  s    zSeq.__radd__c                s   | j }|tt| || jS )N)rm   superr   r%   ri   )r2   Zstr_listr/   )rm   r   r   r%     s    zSeq.joinc             C   s*   t |dsdS | j|jkrdS t| |S )Nri   F)rJ   ri   r9   rL   )r2   rK   r   r   r   rL     s
    
z
Seq.__eq__c             C   s   |  | S )N)rL   )r2   rK   r   r   r   rM     s    z
Seq.__ne__c             C   s   t | S )z' Converts Seq to a raw string.
        )r9   )r2   r   r   r   tostring  s    zSeq.tostringc             C   s   | j }|| ddd | jS )zReturn the reversed sequence.

        Note that this method returns a new object, in contrast to
        the in-place reverse() method of list objects.
        N)rm   ri   )r2   r/   r   r   r   reverse  s    zSeq.reversec             C   s
   |  dS )Nz-.~)remove)r2   r   r   r   ungap  s    z	Seq.ungapc                s<   | j }d fddt| D }||tdd| jS )z]Return a new alphabetic sequence with all characters in 'delchars'
         removed.
        r   c             3   s   | ]}|t  kr|V  qd S )N)set)r   char)delcharsr   r   	<genexpr>  s    zSeq.remove.<locals>.<genexpr>)rm   r%   r9   r@   	maketransri   )r2   rx   r/   Zcleanseqr   )rx   r   rt     s    z
Seq.removec             C   s(   | j }tdd}|t| || jS )z*Return a lower case copy of the sequence. r    r   )rm   r9   rz   r@   ri   )r2   r/   transr   r   r   lower  s    z	Seq.lowerc             C   s(   | j }tdd}|t| || jS )z*Return a lower case copy of the sequence. r   r    )rm   r9   rz   r@   ri   )r2   r/   r{   r   r   r   upper  s    z	Seq.upperr   Xc             C   sL   t |}t |dkrtd|| }t||}| j}|t| || jS )zReplace all occurrences of letters with the mask character.
        The default is to replace all lower case letters with 'X'.
        rj   zMask should be single character)rH   r+   r9   rz   rm   r@   ri   )r2   r0   maskZLLtor{   r/   r   r   r   r     s    zSeq.maskc             C   s   ddl m} | | S )zTranslate a nucleotide sequence to a polypeptide using full
        IUPAC ambiguities in DNA/RNA and amino acid codes, using the
        standard genetic code. See weblogo.transform.GeneticCode for
        details and more options.
        rj   )GeneticCode)	transformr   stdr@   )r2   r   r   r   r   r@     s    zSeq.translatec             C   s   ddl m} | | S )zTranslate a protein sequence back into coding DNA, using the
        standard genetic code. See weblogo.transform.GeneticCode for
        details and more options.
        rj   )r   )r   r   r   back_translate)r2   r   r   r   r   r   #  s    zSeq.back_translatec             C   s   |    S )zpReturns reversed complementary nucleic acid sequence (i.e. the other
        strand of a DNA sequence.)
        )rs   
complement)r2   r   r   r   reverse_complement+  s    zSeq.reverse_complementc             C   s:   t | jstdt| t}| j}||| j| j| j	S )z,Returns complementary nucleic acid sequence.zIncompatable alphabets)
r   r=   ri   r+   r9   r@   _complement_tablerm   rf   rg   )r2   r<   r/   r   r   r   r   1  s
    zSeq.complementc             c   sl   t | |k rdS | j|  }xFtdt || d D ],}||||  }|dks^||r8|V  q8W dS )zReturn an iteration over all subwords of length k in the sequence. If an optional
        alphabet is provided, only words from that alphabet are returned.

        >>> list(Seq("abcabc").words(3))
        ['abc', 'bca', 'cab', 'abc']
        Nr   rj   )rH   ri   rD   rq   r&   r=   )r2   kri   seqr4   wordr   r   r   words9  s    z	Seq.wordsc             C   s$   ddl m} t| ||}||S )zReturn a count of all subwords in the sequence.

        >>> from weblogo.seq import *
        >>> Seq("abcabc").word_count(3)
        [('abc', 2), ('bca', 1), ('cab', 1)]
        rj   )group_count)utilsr   sortedr   )r2   r   ri   r   r   r   r   r   
word_countM  s    zSeq.word_count)N)r   r~   )N)N)r^   r_   r`   ra   r	   r$   propertyri   rC   rV   rQ   rn   ro   r%   rL   rM   rq   rs   ru   rt   r|   r}   r   r@   r   r   r   r   r   __classcell__r   r   )rm   r   r     s2   
		


c               @   sR   e Zd ZdZdddgZg dddfddZdd	 Zdd
dZdddZdddZ	dS )r   z A list of sequences.
    ri   rf   rg   Nc             C   s"   t | | || _|| _|| _d S )N)list__init__ri   rf   rg   )r2   Zalistri   rf   rg   r   r   r   r   b  s    zSeqList.__init__c             C   sd   t | dkrdS | j}|dkr(| d j}t | d }x*| D ]"}t ||krNdS |j|kr:dS q:W dS )z2Are all sequences of the same length and alphabet?r   TNF)rH   ri   )r2   Ark   r<   r   r   r   	isalignedm  s    


zSeqList.isalignedc             C   s<   |s
| j }|stdg }x| D ]}||| q W |S )z< Convert sequence list into a 2D array of ordinals.
        zNo alphabet)ri   r+   r,   rC   )r2   ri   r   r<   r   r   r   rC   }  s    
zSeqList.ordsc                s:    s
| j   stddd t fdd| D  D }|S )zCounts the occurrences of alphabetic characters.

        Arguments:
            - alphabet -- an optional alternative alphabet

        Returns :
        A list of character counts in alphabetic order.
        zNo alphabetc             S   s   g | ]}t |qS r   )rU   )r   r8   r   r   r   r     s    z!SeqList.tally.<locals>.<listcomp>c                s   g | ]}|  qS r   )rV   )r   r<   )ri   r   r   r     s    )ri   r+   r'   )r2   ri   rl   r   )ri   r   rV     s    	 zSeqList.tallyc       	         s   |s
| j }|stdt| | |}t|d } fddtd|D }xR|D ]J}t||krjtdx0t|D ]$\}}| k rt|| |  d7  < qtW qRW ddlm} |||S )zgCounts the occurrences of characters in each column.

        Returns: Motif(counts, alphabet)
        zNo alphabetr   c                s   g | ]}d g  qS )r   r   )r   l)Nr   r   r     s    z#SeqList.profile.<locals>.<listcomp>z6Sequences are of incommensurate lengths. Cannot tally.rj   )Motif)ri   r+   rH   rC   r&   r)   Zmatrixr   )	r2   ri   rC   rk   rl   ojr6   r   r   )r   r   profile  s     

zSeqList.profile)N)N)N)
r^   r_   r`   ra   rb   r   r   rC   rV   r   r   r   r   r   r   \  s   


c             C   s   t | tdS )zACreate an alphabetic sequence representing a stretch of DNA.
    )ri   )r   r   )r:   r   r   r   r     s    c             C   s   t | tdS )zACreate an alphabetic sequence representing a stretch of RNA.
    )ri   )r   r   )r:   r   r   r   r     s    c             C   s   t | tdS )zICreate an alphabetic sequence representing a stretch of polypeptide.
    )ri   )r   r
   )r:   r   r   r   r     s    )ra   r   rA   __all__r#   r   r	   r'   r
   r   r   r   r   r   r   r   r   r9   rz   r   r   r   r   r   r   r   r   r   r   r   <module>z   sh   	 @
 ][