o
    Rŀgg                     @   s   d 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	 G dd	 d	e	Z
G d
d deZedkr?ddlmZ e  dS dS )a  Bio.AlignIO support for "stockholm" format (used in the PFAM database).

You are expected to use this module via the Bio.AlignIO functions (or the
Bio.SeqIO functions if you want to work directly with the gapped sequences).

For example, consider a Stockholm alignment file containing the following::

    # STOCKHOLM 1.0
    #=GC SS_cons       .................<<<<<<<<...<<<<<<<........>>>>>>>..
    AP001509.1         UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGU
    #=GR AP001509.1 SS -----------------<<<<<<<<---..<<-<<-------->>->>..--
    AE007476.1         AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGU
    #=GR AE007476.1 SS -----------------<<<<<<<<-----<<.<<-------->>.>>----

    #=GC SS_cons       ......<<<<<<<.......>>>>>>>..>>>>>>>>...............
    AP001509.1         CUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
    #=GR AP001509.1 SS -------<<<<<--------->>>>>--->>>>>>>>---------------
    AE007476.1         UUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
    #=GR AE007476.1 SS ------.<<<<<--------->>>>>.-->>>>>>>>---------------
    //

This is a single multiple sequence alignment, so you would probably load this
using the Bio.AlignIO.read() function:

    >>> from Bio import AlignIO
    >>> align = AlignIO.read("Stockholm/simple.sth", "stockholm")
    >>> print(align)
    Alignment with 2 rows and 104 columns
    UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-G...UGU AP001509.1
    AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-C...GAU AE007476.1
    >>> for record in align:
    ...     print("%s %i" % (record.id, len(record)))
    AP001509.1 104
    AE007476.1 104

In addition to the sequences themselves, this example alignment also includes
some GR lines for the secondary structure of the sequences.  These are
strings, with one character for each letter in the associated sequence:

    >>> for record in align:
    ...     print(record.id)
    ...     print(record.seq)
    ...     print(record.letter_annotations['secondary_structure'])
    AP001509.1
    UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
    -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>---------------
    AE007476.1
    AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
    -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>---------------

Any general annotation for each row is recorded in the SeqRecord's annotations
dictionary.  Any per-column annotation for the entire alignment in in the
alignment's column annotations dictionary, such as the secondary structure
consensus in this example:

    >>> sorted(align.column_annotations.keys())
    ['secondary_structure']
    >>> align.column_annotations["secondary_structure"]
    '.................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............'

You can output this alignment in many different file formats
using Bio.AlignIO.write(), or the MultipleSeqAlignment object's format method:

    >>> print(format(align, "fasta"))
    >AP001509.1
    UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-A
    GGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
    >AE007476.1
    AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAA
    GGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
    <BLANKLINE>

Most output formats won't be able to hold the annotation possible in a
Stockholm file:

    >>> print(format(align, "stockholm"))
    # STOCKHOLM 1.0
    #=GF SQ 2
    AP001509.1 UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
    #=GS AP001509.1 AC AP001509.1
    #=GS AP001509.1 DE AP001509.1
    #=GR AP001509.1 SS -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>---------------
    AE007476.1 AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
    #=GS AE007476.1 AC AE007476.1
    #=GS AE007476.1 DE AE007476.1
    #=GR AE007476.1 SS -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>---------------
    #=GC SS_cons .................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............
    //
    <BLANKLINE>

Note that when writing Stockholm files, AlignIO does not break long sequences
up and interleave them (as in the input file shown above).  The standard
allows this simpler layout, and it is more likely to be understood by other
tools.

Finally, as an aside, it can sometimes be useful to use Bio.SeqIO.parse() to
iterate over the alignment rows as SeqRecord objects - rather than working
with Alignnment objects.

    >>> from Bio import SeqIO
    >>> for record in SeqIO.parse("Stockholm/simple.sth", "stockholm"):
    ...     print(record.id)
    ...     print(record.seq)
    ...     print(record.letter_annotations['secondary_structure'])
    AP001509.1
    UUAAUCGAGCUCAACACUCUUCGUAUAUCCUC-UCAAUAUGG-GAUGAGGGUCUCUAC-AGGUA-CCGUAAA-UACCUAGCUACGAAAAGAAUGCAGUUAAUGU
    -----------------<<<<<<<<---..<<-<<-------->>->>..---------<<<<<--------->>>>>--->>>>>>>>---------------
    AE007476.1
    AAAAUUGAAUAUCGUUUUACUUGUUUAU-GUCGUGAAU-UGG-CACGA-CGUUUCUACAAGGUG-CCGG-AA-CACCUAACAAUAAGUAAGUCAGCAGUGAGAU
    -----------------<<<<<<<<-----<<.<<-------->>.>>----------.<<<<<--------->>>>>.-->>>>>>>>---------------

Remember that if you slice a SeqRecord, the per-letter-annotations like the
secondary structure string here, are also sliced:

    >>> sub_record = record[10:20]
    >>> print(sub_record.seq)
    AUCGUUUUAC
    >>> print(sub_record.letter_annotations['secondary_structure'])
    -------<<<

Likewise with the alignment object, as long as you are not dropping any rows,
slicing specific columns of an alignment will slice any per-column-annotations:

    >>> align.column_annotations["secondary_structure"]
    '.................<<<<<<<<...<<<<<<<........>>>>>>>........<<<<<<<.......>>>>>>>..>>>>>>>>...............'
    >>> part_align = align[:,10:20]
    >>> part_align.column_annotations["secondary_structure"]
    '.......<<<'

You can also see this in the Stockholm output of this partial-alignment:

    >>> print(format(part_align, "stockholm"))
    # STOCKHOLM 1.0
    #=GF SQ 2
    AP001509.1 UCAACACUCU
    #=GS AP001509.1 AC AP001509.1
    #=GS AP001509.1 DE AP001509.1
    #=GR AP001509.1 SS -------<<<
    AE007476.1 AUCGUUUUAC
    #=GS AE007476.1 AC AE007476.1
    #=GS AE007476.1 DE AE007476.1
    #=GR AE007476.1 SS -------<<<
    #=GC SS_cons .......<<<
    //
    <BLANKLINE>

    )MultipleSeqAlignment)Seq)	SeqRecord   )AlignmentIterator)SequentialAlignmentWriterc                   @   sJ   e Zd ZdZdddddddd	Zd
ddZddddZdd Zdd ZdS )StockholmWriterz Stockholm/PFAM alignment writer.SSSATMPPLIASIN)secondary_structuresurface_accessibilitytransmembraneposterior_probabilityligand_bindingactive_siteintronRFMM)reference_annotation
model_maskOSOCLO)organismorganism_classificationlookc                 C   s   t |}| | _g | _|dkrtd| jdkrtd| jd | jd|  |D ]}| | q-|jrqt	|j
 D ]1\}}|| jv rY| jd| j|  d| d q?|| jv ro| jd| j|  d	| d q?	 q?| jd
 dS )zUse this to write (another) single alignment to an open file.

        Note that sequences and their annotation are recorded
        together (rather than having a block of annotation followed
        by a block of aligned sequences).
        r   zMust have at least one sequencez Non-empty sequences are requiredz# STOCKHOLM 1.0
z#=GF SQ %i
#=GC  
z_cons z//
N)lenget_alignment_length_length_of_sequences_ids_written
ValueErrorhandlewrite_write_recordcolumn_annotationssorteditemspfam_gc_mappingpfam_gr_mapping)self	alignmentcountrecordkv r7   K/var/www/html/myenv/lib/python3.10/site-packages/Bio/AlignIO/StockholmIO.pywrite_alignment   s&   


"
"zStockholmWriter.write_alignmentc              	   C   sp  | j t|jkrtd|j}|jdur$d|jv r$|j|jd kr$|j}|dd}d|jv rZd|jv rZd|jd  d	|jd  }|t| d |krZd
||jd |jd f }|| jv rftd| | j	| | j
| d|j d d|jv r| j
d| d| |jd  d n|jr| j
d| d| |j d |jr| j
d| d| |j d |jD ]}| j
d| d| | d q|j D ]%\}}|| jv r| t|}|r| j
d|| | j| |f  q	 q|j D ]5\}}|| jv r3tt|t|jkr3| t|}|r1| j
d|| | j| |f  q 	 q dS )z/Write a single SeqRecord to the file (PRIVATE).z%Sequences must all be the same lengthN	accessionr"   _startend/-z%s/%s-%szDuplicate record identifier: r#   #=GS z AC z DE z DR z#=GS %s %s %s
z#=GR %s %s %s
)r&   r$   seqr(   idnameannotationsreplacer'   appendr)   r*   cleandescriptiondbxrefsr.   pfam_gs_mappingstrletter_annotationsr0   )r1   r4   seq_namesuffixxrefkeyvaluedatar7   r7   r8   r+      sj   



""
"
$zStockholmWriter._write_recordN)	__name__
__module____qualname____doc__r0   r/   rJ   r9   r+   r7   r7   r7   r8   r      s    

"r   c                   @   s^   e Zd ZdZdddddddd	Zd
ddZddddZdZdd Zdd Z	dd Z
dd ZdS )StockholmIteratora  Loads a Stockholm file from PFAM into MultipleSeqAlignment objects.

    The file may contain multiple concatenated alignments, which are loaded
    and returned incrementally.

    This parser will detect if the Stockholm file follows the PFAM
    conventions for sequence specific meta-data (lines starting #=GS
    and #=GR) and populates the SeqRecord fields accordingly.

    Any annotation which does not follow the PFAM conventions is currently
    ignored.

    If an accession is provided for an entry in the meta data, IT WILL NOT
    be used as the record.id (it will be recorded in the record's
    annotations).  This is because some files have (sub) sequences from
    different parts of the same accession (differentiated by different
    start-end positions).

    Wrap-around alignments are not supported - each sequences must be on
    a single line.  However, interlaced sequences should work.

    For more information on the file format, please see:
    http://sonnhammer.sbc.su.se/Stockholm.html
    https://en.wikipedia.org/wiki/Stockholm_format
    http://bioperl.org/formats/alignment_formats/Stockholm_multiple_alignment_format.html

    For consistency with BioPerl and EMBOSS we call this the "stockholm"
    format.
    r   r   r   r   r   r   r   )r	   r
   r   r   r   r   r   r   r   )r   r   r   r   r    )r   r   r   Nc                 C   s  | j }| jdu r| }n| j}d| _|st| dkr!tdi }i }i }i }i }i }d}		 | }|s8nE| }|dkrE|| _n8|dkrMd}	n/|dkrSn)|d d	kr|	r]J d
d |ddD }
t|
dkrttd| |
\}}||vrd||< ||d ||  |	dd7  < nt|dkr||dd dkr|dd  dd\}}||vr|g||< n|| 
| n|dd dkr|dd  dd\}}||vrd||< ||  | 7  < n|dd dkrBz|dd  dd\}}}W n ty   |dd  dd\}}d}Y nw ||vr)i ||< ||| vr8|g|| |< nD|| | 
| n:|dd dkr||dd  dd\}}}||vrci ||< ||| vrpd|| |< || |  | 7  < q0t|t|ksJ | | _|| _|| _|| _|ru|ru| jdur| jt|krtdt|| jf tt| d }g }|D ]K}|| }|t|krtd| |\}}}tt||||d|id}||jd< |dur||jd< |dur||jd< | || |
| q| D ]\}}t||kr)td|t||f qt|}t| D ]:\}}|| jv rI||j| j| < q5|drg|dd | jv rg||j| j|dd  < q5||jd | < q5||_|S t)!z)Parse the next alignment from the handle.Nz# STOCKHOLM 1.0zDid not find STOCKHOLM headerFTz// r   #c                 S   s   g | ]}|  qS r7   )strip).0xr7   r7   r8   
<listcomp>  s    z.StockholmIterator.__next__.<locals>.<listcomp>r"   r      z3Could not split line into identifier and sequence:
.r?      z#=GF r!   r@   z#=GR z5Found %i records in this alignment, told to expect %iz8Sequences have different lengths, or repeated identifierr:   )rB   rC   rH   rD   r<   r=   z%s length %i, expected %i_conszGC:) r)   _headerreadlineStopIterationrZ   r(   splitr$   
setdefaultrE   rF   keysids	sequencesseq_annotationseq_col_annotationrecords_per_alignmentlistvalues_identifier_splitr   r   rD   _populate_meta_datar.   r   r-   r/   r,   endswithr0   _annotations)r1   r)   lineseqsri   gsgrgfgcpassed_end_alignmentpartsseq_idrA   featuretextalignment_lengthrecordsrC   r<   r=   r4   r5   r6   r2   r7   r7   r8   __next___  s   

"

R

	



 zStockholmIterator.__next__c                 C   sf   d|v r.| dd\}}|ddkr.z|d\}}|t|t|fW S  ty-   Y nw |ddfS )zDReturn (name, start, end) string tuple from an identifier (PRIVATE).r>   r   r?   N)rsplitr3   rf   intr(   )r1   
identifierrC   	start_endr<   r=   r7   r7   r8   rp     s   
z#StockholmIterator._identifier_splitc           
   	   C   sn   |  |\}}}||kr|g}n||g}i }|D ]}z|| D ]
}	|| |	 ||	< qW q ty4   Y qw |S )a  Take an identifier and returns dict of all meta-data matching it (PRIVATE).

        For example, given "Q9PN73_CAMJE/149-220" will return all matches to
        this or "Q9PN73_CAMJE" which the identifier without its /start-end
        suffix.

        In the example below, the suffix is required to match the AC, but must
        be removed to match the OS and OC meta-data::

            # STOCKHOLM 1.0
            #=GS Q9PN73_CAMJE/149-220  AC Q9PN73
            ...
            Q9PN73_CAMJE/149-220               NKA...
            ...
            #=GS Q9PN73_CAMJE OS Campylobacter jejuni
            #=GS Q9PN73_CAMJE OC Bacteria

        This function will return an empty dictionary if no data is found.
        )rp   KeyError)
r1   r   	meta_dictrC   r<   r=   identifier_keysansweridentifier_keyfeature_keyr7   r7   r8   _get_meta_data"  s   z StockholmIterator._get_meta_datac                 C   s  |  || j}|D ]P}|dkr#t|| dksJ || d |jd< q	|dkr0d|| |_q	|dkr:|| |_q	|| jv rMd|| |j| j| < q	d|| |jd	| < q	|  || j}|D ]}|| j	v ru|| |j
| j	| < qc|| |j
d
| < qcdS )z~Add meta-date to a SecRecord's annotations dictionary (PRIVATE).

        This function applies the PFAM conventions.
        ACr   r   r:   DEr#   DRz, zGS:zGR:N)r   rk   r$   rD   joinrH   rI   rJ   rl   r0   rL   )r1   r   r4   seq_datar}   seq_col_datar7   r7   r8   rq   D  s,   

z%StockholmIterator._populate_meta_data)rS   rT   rU   rV   r0   r/   rJ   rc   r   rp   r   rq   r7   r7   r7   r8   rW   .  s$    !

 7"rW   __main__)run_doctestN)rV   	Bio.Alignr   Bio.Seqr   Bio.SeqRecordr   
Interfacesr   r   r   rW   rS   
Bio._utilsr   r7   r7   r7   r8   <module>   s        =
