o
    Rŀg                     @   s   d Z ddl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
 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 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rmddlmZ e  dS dS )zIBio.SearchIO objects to model high scoring regions between query and hit.    N)ge)le)BiopythonWarning)MultipleSeqAlignment)allitems)fragcascade)fullcascade)getattr_str)
singleitem)Seq)	SeqRecord   )_BaseHSPc                   @   s:  e Zd ZdZdZdd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eddZdd  Zd!d" Zeed#dZd$d% Zeed&dZd'd( Zeed)dZd*d+ Zeed)dZd,d- Zeed.dZd/d0 Zeed1dZd2d3 Z ee d4dZ!d5d6 Z"ee"d7dZ#d8d9 Z$d:d; Z%ee%d<dZ&d=d> Z'ee'd?dZ(d@dA Z)dBdC Z*ee*dDdZ+dEdF Z,ee,dGdZ-edHdI dJdKZ.e/dLdMdKZ0e/dNdOdKZ1e/dPdQdKZ2e/dRdSdKZ3e/dTdUdKZ4e5dVdKZ6e5dWdXdKZ7e5dYdZdKZ8e5d[d\dKZ9e5d]d^dKZ:e5d_d`dKZ;e5dadbdKZ<e5dcdddKZ=e5dedfdKZ>e5dgdhdKZ?e5didjdKZ@eAdkdKZBeAdWdldKZCeAdYdmdKZDeAd[dndKZEeAd]dodKZFeAd_dpdKZGeAdadqdKZHeAdcdrdKZIeAdedsdKZJeAdgdtdKZKeAdidudKZLeAdvdwdKZMeAdxdydKZNeAdzd{dKZOeAd|d}dKZPeAd~ddKZQeAdddKZReAdddKZSeAdddKZTdS )HSPa6  Class representing high-scoring region(s) between query and hit.

    HSP (high-scoring pair) objects are contained by Hit objects (see Hit).
    In most cases, HSP objects store the bulk of the statistics and results
    (e.g. e-value, bitscores, query sequence, etc.) produced by a search
    program.

    Depending on the search output file format, a given HSP will contain one
    or more HSPFragment object(s). Examples of search programs that produce HSP
    with one HSPFragments are BLAST, HMMER, and FASTA. Other programs such as
    BLAT or Exonerate may produce HSPs containing more than one HSPFragment.
    However, their native terminologies may differ: in BLAT these fragments
    are called 'blocks' while in Exonerate they are called exons or NER.

    Here are examples from each type of HSP. The first one comes from a BLAST
    search::

        >>> from Bio import SearchIO
        >>> blast_qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
        >>> blast_hsp = blast_qresult[1][0]     # the first HSP from the second hit
        >>> blast_hsp
        HSP(hit_id='gi|301171311|ref|NR_035856.1|', query_id='33211', 1 fragments)
        >>> print(blast_hsp)
              Query: 33211 mir_1
                Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ...
        Query range: [1:61] (1)
          Hit range: [0:60] (1)
        Quick stats: evalue 1.7e-22; bitscore 109.49
          Fragments: 1 (60 columns)
             Query - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
                     ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
               Hit - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG

    For HSPs with a single HSPFragment, you can invoke ``print`` on it and see the
    underlying sequence alignment, if it exists. This is not the case for HSPs
    with more than one HSPFragment. Below is an example, using an HSP from a
    BLAT search. Invoking ``print`` on these HSPs will instead show a table of the
    HSPFragment objects it contains::

        >>> blat_qresult = SearchIO.read('Blat/mirna.pslx', 'blat-psl', pslx=True)
        >>> blat_hsp = blat_qresult[1][0]       # the first HSP from the second hit
        >>> blat_hsp
        HSP(hit_id='chr11', query_id='blat_1', 2 fragments)
        >>> print(blat_hsp)
              Query: blat_1 <unknown description>
                Hit: chr11 <unknown description>
        Query range: [42:67] (-1)
          Hit range: [59018929:59018955] (1)
        Quick stats: evalue ?; bitscore ?
          Fragments: ---  --------------  ----------------------  ----------------------
                       #            Span             Query range               Hit range
                     ---  --------------  ----------------------  ----------------------
                       0               6                 [61:67]     [59018929:59018935]
                       1              16                 [42:58]     [59018939:59018955]

    Notice that in HSPs with more than one HSPFragments, the HSP's ``query_range``
    ``hit_range`` properties encompasses all fragments it contains.

    You can check whether an HSP has more than one HSPFragments or not using the
    ``is_fragmented`` property::

        >>> blast_hsp.is_fragmented
        False
        >>> blat_hsp.is_fragmented
        True

    Since HSP objects are also containers similar to Python lists, you can
    access a single fragment in an HSP using its integer index::

        >>> blat_fragment = blat_hsp[0]
        >>> print(blat_fragment)
              Query: blat_1 <unknown description>
                Hit: chr11 <unknown description>
        Query range: [61:67] (-1)
          Hit range: [59018929:59018935] (1)
          Fragments: 1 (6 columns)
             Query - tatagt
               Hit - tatagt

    This applies to HSPs objects with a single fragment as well::

        >>> blast_fragment = blast_hsp[0]
        >>> print(blast_fragment)
              Query: 33211 mir_1
                Hit: gi|301171311|ref|NR_035856.1| Pan troglodytes microRNA mir-520b ...
        Query range: [1:61] (1)
          Hit range: [0:60] (1)
          Fragments: 1 (60 columns)
             Query - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
                     ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
               Hit - CCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG

    Regardless of the search output file format, HSP objects provide the
    properties listed below. These properties always return values in a list,
    due to the HSP object itself being a list-like container. However, for
    HSP objects with a single HSPFragment, shortcut properties that fetches
    the item from the list are also provided.

    +----------------------+---------------------+-----------------------------+
    | Property             | Shortcut            | Value                       |
    +======================+=====================+=============================+
    | aln_all              | aln                 | HSP alignments as           |
    |                      |                     | MultipleSeqAlignment object |
    +----------------------+---------------------+-----------------------------+
    | aln_annotation_all   | aln_annotation      | dictionary of annotation(s) |
    |                      |                     | of all fragments' alignments|
    +----------------------+---------------------+-----------------------------+
    | fragments            | fragment            | HSPFragment objects         |
    +----------------------+---------------------+-----------------------------+
    | hit_all              | hit                 | hit sequence as SeqRecord   |
    |                      |                     | objects                     |
    +----------------------+---------------------+-----------------------------+
    | hit_features_all     | hit_features        | SeqFeatures of all hit      |
    |                      |                     | fragments                   |
    +----------------------+---------------------+-----------------------------+
    | hit_start_all        | hit_start*          | start coordinates of the    |
    |                      |                     | hit fragments               |
    +----------------------+---------------------+-----------------------------+
    | hit_end_all          | hit_end*            | end coordinates of the hit  |
    |                      |                     | fragments                   |
    +----------------------+---------------------+-----------------------------+
    | hit_span_all         | hit_span*           | sizes of each hit fragments |
    +----------------------+---------------------+-----------------------------+
    | hit_strand_all       | hit_strand          | strand orientations of the  |
    |                      |                     | hit fragments               |
    +----------------------+---------------------+-----------------------------+
    | hit_frame_all        | hit_frame           | reading frames of the hit   |
    |                      |                     | fragments                   |
    +----------------------+---------------------+-----------------------------+
    | hit_range_all        | hit_range           | tuples of start and end     |
    |                      |                     | coordinates of each hit     |
    |                      |                     | fragment                    |
    +----------------------+---------------------+-----------------------------+
    | query_all            | query               | query sequence as SeqRecord |
    |                      |                     | object                      |
    +----------------------+---------------------+-----------------------------+
    | query_features_all   | query_features      | SeqFeatures of all query    |
    |                      |                     | fragments                   |
    +----------------------+---------------------+-----------------------------+
    | query_start_all      | query_start*        | start coordinates of the    |
    |                      |                     | fragments                   |
    +----------------------+---------------------+-----------------------------+
    | query_end_all        | query_end*          | end coordinates of the      |
    |                      |                     | query fragments             |
    +----------------------+---------------------+-----------------------------+
    | query_span_all       | query_span*         | sizes of each query         |
    |                      |                     | fragments                   |
    +----------------------+---------------------+-----------------------------+
    | query_strand_all     | query_strand        | strand orientations of the  |
    |                      |                     | query fragments             |
    +----------------------+---------------------+-----------------------------+
    | query_frame_all      | query_frame         | reading frames of the query |
    |                      |                     | fragments                   |
    +----------------------+---------------------+-----------------------------+
    | query_range_all      | query_range         | tuples of start and end     |
    |                      |                     | coordinates of each query   |
    |                      |                     | fragment                    |
    +----------------------+---------------------+-----------------------------+

    For all types of HSP objects, the property will return the values in a list.
    Shortcuts are only applicable for HSPs with one fragment. Except the ones
    noted, if they are used on an HSP with more than one fragments, an exception
    will be raised.

    For properties that may be used in HSPs with multiple or single fragments
    (``*_start``, ``*_end``, and ``*_span`` properties), their interpretation depends
    on how many fragment the HSP has:

    +------------+---------------------------------------------------+
    | Property   | Value                                             |
    +============+===================================================+
    | hit_start  | smallest coordinate value of all hit fragments    |
    +------------+---------------------------------------------------+
    | hit_end    | largest coordinate value of all hit fragments     |
    +------------+---------------------------------------------------+
    | hit_span   | difference between ``hit_start`` and ``hit_end``  |
    +------------+---------------------------------------------------+
    | query_start| smallest coordinate value of all query fragments  |
    +------------+---------------------------------------------------+
    | query_end  | largest coordinate value of all query fragments   |
    +------------+---------------------------------------------------+
    | query_span | difference between ``query_start`` and            |
    |            | ``query_end``                                     |
    +------------+---------------------------------------------------+

    In addition to the objects listed above, HSP objects also provide the
    following properties and/or attributes:

    +--------------------+------------------------------------------------------+
    | Property           | Value                                                |
    +====================+======================================================+
    | aln_span           | total number of residues in all HSPFragment objects  |
    +--------------------+------------------------------------------------------+
    | molecule_type      | molecule_type of the hit and query SeqRecord objects |
    +--------------------+------------------------------------------------------+
    | is_fragmented      | boolean, whether there are multiple fragments or not |
    +--------------------+------------------------------------------------------+
    | hit_id             | ID of the hit sequence                               |
    +--------------------+------------------------------------------------------+
    | hit_description    | description of the hit sequence                      |
    +--------------------+------------------------------------------------------+
    | hit_inter_ranges   | list of hit sequence coordinates of the regions      |
    |                    | between fragments                                    |
    +--------------------+------------------------------------------------------+
    | hit_inter_spans    | list of lengths of the regions between hit fragments |
    +--------------------+------------------------------------------------------+
    | output_index       | 0-based index for storing the order by which the HSP |
    |                    | appears in the output file (default: -1).            |
    +--------------------+------------------------------------------------------+
    | query_id           | ID of the query sequence                             |
    +--------------------+------------------------------------------------------+
    | query_description  | description of the query sequence                    |
    +--------------------+------------------------------------------------------+
    | query_inter_ranges | list of query sequence coordinates of the regions    |
    |                    | between fragments                                    |
    +--------------------+------------------------------------------------------+
    | query_inter_spans  | list of lengths of the regions between query         |
    |                    | fragments                                            |
    +--------------------+------------------------------------------------------+

    .. [1] may be used in HSPs with multiple fragments

    _items c                    sl   |st ddD ] t fdd|D dkrt d  q|| _g | _|D ]}| | | j| q&dS )at  Initialize an HSP object.

        :param fragments: fragments contained in the HSP object
        :type fragments: iterable yielding HSPFragment
        :param output_index: optional index / ordering of the HSP fragment in
            the original input file.
        :type output_index: integer

        HSP objects must be initialized with a list containing at least one
        HSPFragment object. If multiple HSPFragment objects are used for
        initialization, they must all have the same ``query_id``,
        ``query_description``, ``hit_id``, ``hit_description``, and
        ``molecule_type`` properties.

        z6HSP objects must have at least one HSPFragment object.)query_idquery_descriptionhit_idhit_descriptionmolecule_typec                    s   h | ]}t | qS r   getattr.0fragattrr   K/var/www/html/myenv/lib/python3.10/site-packages/Bio/SearchIO/_model/hsp.py	<setcomp>      zHSP.__init__.<locals>.<setcomp>r   z;HSP object can not contain fragments with more than one %s.N)
ValueErrorlenoutput_indexr   _validate_fragmentappend)self	fragmentsr%   fragmentr   r   r    __init__   s   
zHSP.__init__c                 C   s   d| j j| j| jt| f S )z+Return string representation of HSP object.z(%s(hit_id=%r, query_id=%r, %r fragments))	__class____name__r   r   r$   r(   r   r   r    __repr__&  s   zHSP.__repr__c                 C   
   t | jS )zIterate over HSP items.)iterr   r.   r   r   r    __iter__/     
zHSP.__iter__c                 C   s
   || j v S )z+Return True if HSPFragment is on HSP items.r   r(   r*   r   r   r    __contains__3  r3   zHSP.__contains__c                 C   r0   )zReturn number of HSPs items.)r$   r   r.   r   r   r    __len__7  r3   zHSP.__len__c                 C   r0   )zReturn True if it has HSPs.)boolr   r.   r   r   r    __bool__;  r3   zHSP.__bool__c                 C   s  g }g }t | ddd}|d|  t | ddd}|d|  |dd	|  t| jd
krCd|  d|| jd  gS |dd  d}||d  ||d  t| jD ]V\}}t |d}t |d}	t |d}
d|	|
f }t|dkr|dd d n|}t |d}t |d}d||f }t|dkr|dd d n|}||t||||f  q_|  d d| S )z2Return a human readable summary of the HSP object.evaluez%.2g)fmtzevalue bitscorez%.2fz	bitscore zQuick stats: z; r   
r   z  Fragments: %s  %s  %s  %s)z---z------------------------------------r=   z%16s  %14s  %22s  %22s)#SpanzQuery rangez	Hit rangealn_spanquery_start	query_endz[%s:%s]   N   z~]	hit_starthit_end)	r	   r'   joinr$   r)   _str_hsp_header_str_aln	enumeratestr)r(   linesstatliner9   r;   patternidxblockr@   rA   rB   query_rangerE   rF   	hit_ranger   r   r    __str__?  s<   




 zHSP.__str__c                 C   s2   t |tr| | j| }| | |S | j| S )Return object of index idx.)
isinstanceslicer,   r   _transfer_attrs)r(   rO   objr   r   r    __getitem__m  s
   


zHSP.__getitem__c                 C   s<   t |ttfr|D ]}| | q	n| | || j|< dS )z2Set an item of index idx with the given fragments.N)rU   listtupler&   r   )r(   rO   r)   r*   r   r   r    __setitem__v  s   
zHSP.__setitem__c                 C   s   | j |= dS )zDelete item of index idx.Nr   )r(   rO   r   r   r    __delitem__  s   zHSP.__delitem__c                 C   s   t |ts	td| jrL|j| jkrtd| j|jf |j| jkr,td| j|jf |j	| j	kr<td| j	|j	f |j
| j
krNtd| j
|j
f d S d S )Nz1HSP objects can only contain HSPFragment objects.z6Expected HSPFragment with hit ID %r, found %r instead.z?Expected HSPFragment with hit description %r, found %r instead.z8Expected HSPFragment with query ID %r, found %r instead.z9Expected HSP with query description %r, found %r instead.)rU   HSPFragment	TypeErrorr   r   r#   idr   descriptionr   r   r4   r   r   r    r&     s:   




zHSP._validate_fragmentc                 C   s   t dd | jD S )Nc                 s   s    | ]}|j V  qd S Nr@   )r   frgr   r   r    	<genexpr>  s    z$HSP._aln_span_get.<locals>.<genexpr>)sumr)   r.   r   r   r    _aln_span_get  s   zHSP._aln_span_getz3Total number of columns in all HSPFragment objects.fgetdocc                    sT   |dv sJ |dv sJ d||f   fdd| j D }d |v r(td  t |S )Nhitquery)startend%s_%sc                    s   g | ]}t | qS r   r   r   
coord_namer   r    
<listcomp>  r"   z#HSP._get_coords.<locals>.<listcomp>z''None' exist in %s coordinates; ignored)r)   warningswarnr   )r(   seq_type
coord_typecoordsr   rq   r    _get_coords  s   zHSP._get_coordsc                 C      t | ddS )Nrl   rn   minry   r.   r   r   r    _hit_start_get     zHSP._hit_start_getz/Smallest coordinate value of all hit fragments.c                 C   rz   )Nrm   rn   r{   r.   r   r   r    _query_start_get  r~   zHSP._query_start_getz1Smallest coordinate value of all query fragments.c                 C   rz   )Nrl   ro   maxry   r.   r   r   r    _hit_end_get  r~   zHSP._hit_end_getz.Largest coordinate value of all hit fragments.c                 C   rz   )Nrm   ro   r   r.   r   r   r    _query_end_get  r~   zHSP._query_end_getc                 C   $   z| j | j W S  ty   Y d S w rb   rF   rE   r_   r.   r   r   r    _hit_span_get  
   zHSP._hit_span_getz.The number of hit residues covered by the HSP.c                 C   r   rb   rB   rA   r_   r.   r   r   r    _query_span_get  r   zHSP._query_span_getz0The number of query residues covered by the HSP.c                 C      | j | jfS rb   rE   rF   r.   r   r   r    _hit_range_get     zHSP._hit_range_getz+Tuple of HSP hit start and end coordinates.c                 C   r   rb   rA   rB   r.   r   r   r    _query_range_get  r   zHSP._query_range_getz-Tuple of HSP query start and end coordinates.c                 C   s   |dv sJ t | d| d }t | d| }|dkr tt}}ntt}}g }t|d d D ]\}}||| }	|||d  }
|t|	|
t|	|
f q/|S )Nrm   rl   z%s_strand_allr   z%s_range_allr   r   )r   r|   r   rJ   r'   )r(   rv   strandrx   	startfuncendfuncinter_coordsrO   coordrn   ro   r   r   r    _inter_ranges_get  s   
zHSP._inter_ranges_getc                 C   
   |  dS Nrl   r   r.   r   r   r    _hit_inter_ranges_get     
zHSP._hit_inter_ranges_getz:Hit sequence coordinates of the regions between fragments.c                 C   r   Nrm   r   r.   r   r   r    _query_inter_ranges_get  r   zHSP._query_inter_ranges_getz<Query sequence coordinates of the regions between fragments.c                 C   s(   |dv sJ d| }dd t | |D S )Nr   z%s_inter_rangesc                 S   s   g | ]
}|d  |d  qS )r   r   r   )r   r   r   r   r    rs   !  s    z(HSP._inter_spans_get.<locals>.<listcomp>r   )r(   rv   	attr_namer   r   r    _inter_spans_get  s   zHSP._inter_spans_getc                 C   r   r   r   r.   r   r   r    _hit_inter_spans_get#  r   zHSP._hit_inter_spans_getz)Lengths of regions between hit fragments.c                 C   r   r   r   r.   r   r   r    _query_inter_spans_get*  r   zHSP._query_inter_spans_getz+Lengths of regions between query fragments.c                 C   s   t | dkS )Nr   )r$   r.   r   r   r    <lambda>5  s    zHSP.<lambda>z6Whether the HSP has more than one HSPFragment objects.rj   r   z Description of the hit sequence.r   z"Description of the query sequence.r   zID of the hit sequence.r   zID of the query sequence.r   z5molecule_type of the hit and query SeqRecord objects.z#HSPFragment object, first fragment.rl   z3Hit sequence as a SeqRecord object, first fragment.rm   z5Query sequence as a SeqRecord object, first fragment.alnzAAlignment of the first fragment as a MultipleSeqAlignment object.aln_annotationz>Dictionary of annotation(s) of the first fragment's alignment.hit_featuresz&Hit sequence features, first fragment.query_featuresz(Query sequence features, first fragment.
hit_strandz'Hit strand orientation, first fragment.query_strandz)Query strand orientation, first fragment.	hit_framez+Hit sequence reading frame, first fragment.query_framez-Query sequence reading frame, first fragment.z List of all HSPFragment objects.z:List of all fragments' hit sequences as SeqRecord objects.z<List of all fragments' query sequences as SeqRecord objects.zBList of all fragments' alignments as MultipleSeqAlignment objects.z9Dictionary of annotation(s) of all fragments' alignments.z"List of all hit sequence features.z$List of all query sequence features.z,List of all fragments' hit sequence strands.z-List of all fragments' query sequence strandsz3List of all fragments' hit sequence reading frames.z5List of all fragments' query sequence reading frames.rE   z-List of all fragments' hit start coordinates.rA   z/List of all fragments' query start coordinates.rF   z+List of all fragments' hit end coordinates.rB   z-List of all fragments' query end coordinates.hit_spanz)List of all fragments' hit sequence size.
query_spanz+List of all fragments' query sequence size.rR   z5List of all fragments' hit start and end coordinates.rQ   z7List of all fragments' query start and end coordinates.N)r   r   )Ur-   
__module____qualname____doc___NON_STICKY_ATTRSr+   r/   r2   r5   r6   r8   rS   rY   r\   r]   r&   rg   propertyr@   ry   r}   rE   r   rA   r   rF   r   rB   r   r   r   r   r   rR   r   rQ   r   r   hit_inter_rangesr   query_inter_rangesr   r   hit_inter_spansr   query_inter_spansis_fragmentedr   r   r   r   r   r   r
   r*   rl   rm   r   r   r   r   r   r   r   r   r   r)   hit_all	query_allaln_allaln_annotation_allhit_features_allquery_features_allhit_strand_allquery_strand_allhit_frame_allquery_frame_allhit_start_allquery_start_allhit_end_allquery_end_allhit_span_allquery_span_allhit_range_allquery_range_allr   r   r   r    r      sN    c
(	.	


r   c                   @   s  e Zd ZdZ					dsd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eeddZdd Zdd ZeeeddZdd Zeedd Zd!d" Zd#d$ Zeeed%dZd&d' Zd(d) Zeeed*dZed+d,d-d.Zed+d/d0d.Zed1d,d2d.Zed1d/d3d.Zed4d,d5d.Zed4d/d6d.Z d7d8 Z!d9d: Z"d;d< Z#d=d> Z$ee#e$d?dZ%d@dA Z&dBdC Z'ee&e'dDdZ(dEdF Z)dGdH Z*dIdJ Z+ee*e+dKdZ,dLdM Z-dNdO Z.ee-e.dPdZ/dQdR Z0dSdT Z1dUdV Z2ee1e2dWdZ3dXdY Z4dZd[ Z5ee4e5d\dZ6d]d^ Z7d_d` Z8ee7e8dadZ9dbdc Z:ddde Z;ee:e;dfdZ<dgdh Z=ee=did Z>djdk Z?ee?dld Z@dmdn ZAeeAdod ZBdpdq ZCeeCdrd ZDdS )tr^   a7  Class representing a contiguous alignment of hit-query sequence.

    HSPFragment forms the core of any parsed search output file. Depending on
    the search output file format, it may contain the actual query and/or hit
    sequences that produces the search hits. These sequences are stored as
    SeqRecord objects (see SeqRecord):

    >>> from Bio import SearchIO
    >>> qresult = next(SearchIO.parse('Blast/mirna.xml', 'blast-xml'))
    >>> fragment = qresult[0][0][0]   # first hit, first hsp, first fragment
    >>> print(fragment)
          Query: 33211 mir_1
            Hit: gi|262205317|ref|NR_030195.1| Homo sapiens microRNA 520b (MIR520...
    Query range: [0:61] (1)
      Hit range: [0:61] (1)
      Fragments: 1 (61 columns)
         Query - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG
                 |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
           Hit - CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTTTAGAGGG

    # the query sequence is a SeqRecord object
    >>> fragment.query.__class__
    <class 'Bio.SeqRecord.SeqRecord'>
    >>> print(fragment.query)
    ID: 33211
    Name: aligned query sequence
    Description: mir_1
    Number of features: 0
    /molecule_type=DNA
    Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG')

    # the hit sequence is a SeqRecord object as well
    >>> fragment.hit.__class__
    <class 'Bio.SeqRecord.SeqRecord'>
    >>> print(fragment.hit)
    ID: gi|262205317|ref|NR_030195.1|
    Name: aligned hit sequence
    Description: Homo sapiens microRNA 520b (MIR520B), microRNA
    Number of features: 0
    /molecule_type=DNA
    Seq('CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAGTGCTTCCTTT...GGG')

    # when both query and hit are present, we get a MultipleSeqAlignment object
    >>> fragment.aln.__class__
    <class 'Bio.Align.MultipleSeqAlignment'>
    >>> print(fragment.aln)
    Alignment with 2 rows and 61 columns
    CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG 33211
    CCCTCTACAGGGAAGCGCTTTCTGTTGTCTGAAAGAAAAGAAAG...GGG gi|262205317|ref|NR_030195.1|

    <unknown id>Nc                 C   s   || _ i | _|| _|| _dD ]4}t| d| d t| d| g  dD ]}t| d||f d q"t|r<t| |t| qt| |d qdS )zInitialize the class.r   z_%s_descriptionz<unknown description>z_%s_features)r   framern   ro   rp   N)_molecule_typer   _hit_id	_query_idsetattreval)r(   r   r   rl   rm   r   rv   r   r   r   r    r+     s   	zHSPFragment.__init__c                 C   sH   d| j | jf }z
|dt|  7 }W n	 ty   Y nw d| jj|f S )z=Return HSPFragment info; hit id, query id, number of columns.zhit_id=%r, query_id=%rz, %i columnsz%s(%s))r   r   r$   AttributeErrorr,   r-   )r(   infor   r   r    r/     s   zHSPFragment.__repr__c                 C      | j S )zReturn alignment span.rc   r.   r   r   r    r6        zHSPFragment.__len__c                 C   s   |   d |   S )z+Return string of HSP header and alignments.r<   )rH   rI   r.   r   r   r    rS        zHSPFragment.__str__c           	      C   s   | j durm| j| j| j| jd}| jdur | j| |_|jj|_| jdur0| j| |_|jj|_	dD ]}dD ]}d||f }t
| |}t||| q6q2i |_| j D ]\}}t|| t|kscJ || |j|< qS|S td)rT   N)r   r   r   )ra   r   r   rk   rp   z;Slicing for HSP objects without alignment is not supported.)r   r,   r   r   r   rm   featuresr   rl   r   r   r   r   itemsr$   r_   )	r(   rO   rX   r   rv   r   self_valkeyvaluer   r   r    rY     s4   





zHSPFragment.__getitem__c              	   C   s  g }t | d}|d|  | jd ur| jd urz| jj}W n ty)   d}Y nw z| jj}W n ty;   d}Y nw d}d| jv rQt| jdt	rQ| jd }| j
dkrr|dd|f  |rh|d	|  |dd
|f  nK| j
d dkr|d}nd| j
d  }|dd|d d ||dd  f  |r|d|d d ||dd  f  |dd
|d d ||dd  f  d|S )Nr@   z  Fragments: 1 (%s columns)? 
similarityC   z	%10s - %sQueryz             %sHitB      z~~~~z%10s - %s%s%s;   z             %s%s%sr<   )r	   r'   rm   rl   seqr   r   rU   getrK   r@   rG   )r(   rL   r@   qseqhseqsimilcontr   r   r    rI   @  s@   


&$&
zHSPFragment._str_alnc           	      C   s  |dv sJ |du r|S t |ttfstd| |dkrdnd}t| d| d}|durCt|t|krCtdt||t||f t| d| }t| d	| }t| d
| }d| }t |tru||_||_||_	||_
| j|jd< |S t |trtt|||||d| jid}|S )zCheck the given sequence for attribute setting (PRIVATE).

        :param seq: sequence to check
        :type seq: string or SeqRecord
        :param seq_type: sequence type
        :type seq_type: string, choice of 'hit' or 'query'

        rk   Nz3%s sequence must be a string or a SeqRecord object.rm   rl   z_%szASequence lengths do not match. Expected: %r (%s); found: %r (%s).z%s_idz%s_descriptionz%s_featureszaligned %s sequencer   )r`   namera   r   annotations)rU   rK   r   r_   r   r$   r#   r`   ra   r   r   r   r   r   )	r(   r   rv   opp_typeopp_seqseq_idseq_desc	seq_featsseq_namer   r   r    _set_seqk  sJ   	

	zHSPFragment._set_seqc                 C   r   rb   )_hitr.   r   r   r    _hit_get     zHSPFragment._hit_getc                 C      |  |d| _d S r   )r   r   r(   r   r   r   r    _hit_set     zHSPFragment._hit_setz5Hit sequence as a SeqRecord object, defaults to None.)ri   fsetrj   c                 C   r   rb   )_queryr.   r   r   r    
_query_get  r   zHSPFragment._query_getc                 C   r   r   )r   r   r   r   r   r    
_query_set  r   zHSPFragment._query_setz7Query sequence as a SeqRecord object, defaults to None.c                 C   sp   | j d u r| jd u rd S | jd u rt| j g}n| j d u r$t| jg}nt| j | jg}| j}|d ur6||_|S rb   )rm   rl   r   r   )r(   msar   r   r   r    _aln_get  s   

zHSPFragment._aln_getzGQuery-hit alignment as a MultipleSeqAlignment object, defaults to None.rh   c                 C   r   rb   )r   r.   r   r   r    _molecule_type_get  r   zHSPFragment._molecule_type_getc                 C   sR   || _ z|| jjd< W n	 ty   Y nw z	|| jjd< W d S  ty(   Y d S w )Nr   )r   rm   r   r   rl   r   r   r   r    _molecule_type_set  s   zHSPFragment._molecule_type_setzVmolecule type used in the fragment's sequence records and alignment, defaults to None.c                 C   sb   z| j  W | j S  ty0   | jd urt| j| _ Y | j S | jd ur,t| j| _ Y | j S Y | j S w rb   )	_aln_spanr   rm   r$   rl   r.   r   r   r    rg     s   

zHSPFragment._aln_span_getc                 C   s
   || _ d S rb   )r  r   r   r   r    _aln_span_set  r   zHSPFragment._aln_span_setz8The number of alignment columns covered by the fragment.ra   rl   zHit sequence description.r   rm   zQuery sequence description.r`   zHit sequence ID.zQuery sequence ID.r   zHit sequence features.zQuery sequence features.c                 C      |dvr
t d| |S )N)r   r   r   Nz*Strand should be -1, 0, 1, or None; not %rr#   )r(   r   r   r   r    _prep_strand  s   zHSPFragment._prep_strandc                 C   st   |dv sJ t | d| }|d u r8t | d| }|d ur8z|t| }W n ty/   d}Y nw t| d| | |S )Nrk   z
_%s_strandz%s_framer   z	%s_strand)r   absZeroDivisionErrorr   )r(   rv   r   r   r   r   r    _get_strand
  s   zHSPFragment._get_strandc                 C   r   r   r  r.   r   r   r    _hit_strand_get  r   zHSPFragment._hit_strand_getc                 C      |  || _d S rb   )r	  _hit_strandr   r   r   r    _hit_strand_set  r~   zHSPFragment._hit_strand_setz&Hit sequence strand, defaults to None.c                 C   r   r   r  r.   r   r   r    _query_strand_get&  r   zHSPFragment._query_strand_getc                 C   r  rb   )r	  _query_strandr   r   r   r    _query_strand_set)  r~   zHSPFragment._query_strand_setz(Query sequence strand, defaults to None.c                 C   r  )N)r   r   r      r   Nz=Strand should be an integer between -3 and 3, or None; not %rr  )r(   r   r   r   r    _prep_frame3  s
   zHSPFragment._prep_framec                 C   r   rb   )
_hit_framer.   r   r   r    _hit_frame_get:  r   zHSPFragment._hit_frame_getc                 C   r  rb   )r  r  r   r   r   r    _hit_frame_set=  r~   zHSPFragment._hit_frame_setz-Hit sequence reading frame, defaults to None.c                 C   r   )z+Get query sequence reading frame (PRIVATE).)_query_framer.   r   r   r    _query_frame_getF  r   zHSPFragment._query_frame_getc                 C   s   |  || _dS )z+Set query sequence reading frame (PRIVATE).N)r  r  r   r   r   r    _query_frame_setJ  s   zHSPFragment._query_frame_setz/Query sequence reading frame, defaults to None.c                 C   s^   |d u r|S t |tsJ zt| |}W n ty   | Y S w |d u r&|S |||s-J |S rb   )rU   intr   r   )r(   r   opp_coord_nameop	opp_coordr   r   r    _prep_coordU  s   zHSPFragment._prep_coordc                 C   r   )z0Get the sequence hit start coordinate (PRIVATE).)
_hit_startr.   r   r   r    r}   g  r   zHSPFragment._hit_start_getc                 C      |  |dt| _dS )z0Set the sequence hit start coordinate (PRIVATE).rF   N)r#  r   r$  r   r   r   r    _hit_start_setk  r   zHSPFragment._hit_start_setz0Hit sequence start coordinate, defaults to None.c                 C   r   )z2Get the query sequence start coordinate (PRIVATE).)_query_startr.   r   r   r    r   u  r   zHSPFragment._query_start_getc                 C   r%  )z2Set the query sequence start coordinate (PRIVATE).rB   N)r#  r   r'  r   r   r   r    _query_start_sety  r   zHSPFragment._query_start_setz2Query sequence start coordinate, defaults to None.c                 C   r   )z.Get the hit sequence end coordinate (PRIVATE).)_hit_endr.   r   r   r    r     r   zHSPFragment._hit_end_getc                 C   r%  )z.Set the hit sequence end coordinate (PRIVATE).rE   N)r#  r   r)  r   r   r   r    _hit_end_set  r   zHSPFragment._hit_end_setz.Hit sequence end coordinate, defaults to None.c                 C   r   )z0Get the query sequence end coordinate (PRIVATE).)
_query_endr.   r   r   r    r     r   zHSPFragment._query_end_getc                 C   r%  )z0Set the query sequence end coordinate (PRIVATE).rA   N)r#  r   r+  r   r   r   r    _query_end_set  r   zHSPFragment._query_end_setz0Query sequence end coordinate, defaults to None.c                 C   $   z| j | j W S  ty   Y dS w )zDReturn the number of residues covered by the hit sequence (PRIVATE).Nr   r.   r   r   r    r     
   zHSPFragment._hit_span_getz3The number of residues covered by the hit sequence.c                 C   r-  )z=Return the number or residues covered by the query (PRIVATE).Nr   r.   r   r   r    r     r.  zHSPFragment._query_span_getz5The number of residues covered by the query sequence.c                 C   r   )z,Return the start and end of a hit (PRIVATE).r   r.   r   r   r    r        zHSPFragment._hit_range_getz'Tuple of hit start and end coordinates.c                 C   r   )z.Return the start and end of a query (PRIVATE).r   r.   r   r   r    r     r/  zHSPFragment._query_range_getz)Tuple of query start and end coordinates.)r   r   NNN)Er-   r   r   r   r+   r/   r6   rS   rY   rI   r   r   r   r   rl   r   r   rm   r  r   r  r  r   rg   r  r@   r   r   r   r   r   r   r   r	  r  r  r  r   r  r  r   r  r  r  r   r  r  r   r#  r}   r&  rE   r   r(  rA   r   r*  rF   r   r,  rB   r   r   r   r   r   rR   r   rQ   r   r   r   r    r^     s   6
	#+2
r^   __main__)run_doctest)r   rt   operatorr   r   Bior   	Bio.Alignr   Bio.SearchIO._utilsr   r   r   r	   r
   Bio.Seqr   Bio.SeqRecordr   _baser   r   r^   r-   
Bio._utilsr1  r   r   r   r    <module>   s:        '    
