o
    Rŀg,E                 	   @   s  d Z ddlZddl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
ZdZde de dZde de de dZeejZedddd dgkseJ edddd ddgkstJ edddd dgksJ edddd ddgksJ edddd ddgksJ edddd g dksJ edddd g d ksJ ed!ddd g d"ksJ ed#ddd dd$gksJ ed%ddd g d&ksJ d'Zd(Zd)Zd*eef Zd+ZeeZed,sJ d*eef Zd-ZeeZed.sJ ed/r#J ed0s+J ed1s3J d2Zd3e Zed4eeeeeef ZG d5d6 d6eZ G d7d8 d8Z!G d9d: d:Z"G d;d< d<eZ#G d=d> d>e#Z$e$Z%G d?d@ d@e#Z&G dAdB dBeZ'G dCdD dDe(e'Z)G dEdF dFe)Z*G dGdH dHe'Z+G dIdJ dJe(e'Z,G dKdL dLe(e'Z-G dMdN dNe(e'Z.G dOdP dPe(e'Z/G dQdR dRe(e'Z0e1dSkrddTl2m3Z3 e3  dS dS )Ua[  Represent a Sequence Feature holding info about a part of a sequence.

This is heavily modeled after the Biocorba SeqFeature objects, and
may be pretty biased towards GenBank stuff since I'm writing it
for the GenBank parser output...

What's here:

Base class to hold a Feature
----------------------------

Classes:
 - SeqFeature

Hold information about a Reference
----------------------------------

This is an attempt to create a General class to hold Reference type
information.

Classes:
 - Reference

Specify locations of a feature on a Sequence
--------------------------------------------

This aims to handle, in Ewan Birney's words, 'the dreaded fuzziness issue'.
This has the advantages of allowing us to handle fuzzy stuff in case anyone
needs it, and also be compatible with BioPerl etc and BioSQL.

Classes:
 - Location - abstract base class of SimpleLocation and CompoundLocation.
 - SimpleLocation - Specify the start and end location of a feature.
 - CompoundLocation - Collection of SimpleLocation objects (for joins etc).
 - Position - abstract base class of ExactPosition, WithinPosition,
   BetweenPosition, AfterPosition, OneOfPosition, UncertainPosition, and
   UnknownPosition.
 - ExactPosition - Specify the position as being exact.
 - WithinPosition - Specify a position occurring within some range.
 - BetweenPosition - Specify a position occurring between a range (OBSOLETE?).
 - BeforePosition - Specify the position as being found before some base.
 - AfterPosition - Specify the position as being found after some base.
 - OneOfPosition - Specify a position consisting of multiple alternative positions.
 - UncertainPosition - Specify a specific position which is uncertain.
 - UnknownPosition - Represents missing information like '?' in UniProt.


Exceptions:
 - LocationParserError - Exception indicating a failure to parse a location
   string.

    N)ABC)abstractmethod)BiopythonDeprecationWarning)BiopythonParserWarning)
MutableSeq)reverse_complement)Seqz+(?:[a-zA-Z][a-zA-Z0-9_\.\|]*[a-zA-Z0-9]?\:)zone\-of\(\d+[,\d+]+\)z[<>]?(?:\d+|z)\.\.[<>]?(?:\d+|)(?z|complement\(z\)|[^,]+|complement\([^,]+\))123..145      z123..145,200..209z200..209zone-of(200,203)..300zcomplement(123..145),200..209zcomplement(123..145)z123..145,one-of(200,203)..209zone-of(200,203)..209z-123..145,one-of(200,203)..one-of(209,211),300)r   z one-of(200,203)..one-of(209,211)300z9123..145,complement(one-of(200,203)..one-of(209,211)),300)r   z,complement(one-of(200,203)..one-of(209,211))r   z!123..145,200..one-of(209,211),300)r   200..one-of(209,211)r   z123..145,200..one-of(209,211)r   z[complement(149815..150200),complement(293787..295573),NC_016402.1:6618..6676,181647..181905)zcomplement(149815..150200)zcomplement(293787..295573)zNC_016402.1:6618..6676z181647..181905z[<>]?-?\d+\.\.[<>]?-?\d+z\d+\^\d+z\(\d+\.\d+\)z([<>]?\d+|%s)\.\.([<>]?\d+|%s)z\((\d+)\.(\d+)\)z(3.9)zone\-of\((\d+[,\d+]+)\)zone-of(6,9)z	one-of(3)zone-of(3,6)zone-of(3,6,9)z[<>]?\d+z
bond\(%s\)zU^(?P<pair>%s)|(?P<between>%s)|(?P<within>%s)|(?P<oneof>%s)|(?P<bond>%s)|(?P<solo>%s)$c                   @      e Zd ZdZdS )LocationParserErrorz*Could not parse a feature location string.N__name__
__module____qualname____doc__ r   r   B/var/www/html/myenv/lib/python3.10/site-packages/Bio/SeqFeature.pyr          r   c                   @   s   e Zd ZdZ					d0d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dd ZeeeddZdd Zdd Zdd Zdd Zdd  Zd1d!d"Z	#		$	%		d2d&d'Zd(d) Zd*d+ Zd,d- Zd.d/ ZdS )3
SeqFeaturea  Represent a Sequence Feature on an object.

    Attributes:
     - location - the location of the feature on the sequence (SimpleLocation)
     - type - the specified type of the feature (ie. CDS, exon, repeat...)
     - id - A string identifier for the feature.
     - qualifiers - A dictionary of qualifiers on the feature. These are
       analogous to the qualifiers from a GenBank feature table. The keys of
       the dictionary are qualifier names, the values are the qualifier
       values.

    N <unknown id>c                 C   sd   |durt |tst |tstd|| _|| _|| _i | _|dur(| j| |dur0tddS )a  Initialize a SeqFeature on a sequence.

        location can either be a SimpleLocation (with strand argument also
        given if required), or None.

        e.g. With no strand, on the forward strand, and on the reverse strand:

        >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
        >>> f1 = SeqFeature(SimpleLocation(5, 10), type="domain")
        >>> f1.location.strand == None
        True
        >>> f2 = SeqFeature(SimpleLocation(7, 110, strand=1), type="CDS")
        >>> f2.location.strand == +1
        True
        >>> f3 = SeqFeature(SimpleLocation(9, 108, strand=-1), type="CDS")
        >>> f3.location.strand == -1
        True

        For exact start/end positions, an integer can be used (as shown above)
        as shorthand for the ExactPosition object. For non-exact locations, the
        SimpleLocation must be specified via the appropriate position objects.
        NzDSimpleLocation, CompoundLocation (or None) required for the locationz0Rather than sub_features, use a CompoundLocation)	
isinstanceSimpleLocationCompoundLocation	TypeErrorlocationtypeid
qualifiersupdate)selfr"   r#   r$   r%   sub_featuresr   r   r   __init__   s"   zSeqFeature.__init__c                 C   s   t dt | jjS )/Get function for the strand property (PRIVATE)./Please use .location.strand rather than .strand)warningswarnr   r"   strandr'   r   r   r   _get_strand   s
   zSeqFeature._get_strandc                 C   N   t dt z|| j_W dS  ty&   | jdu r%|dur"tddY dS  w )/Set function for the strand property (PRIVATE).r+   Nz$Can't set strand without a location.)r,   r-   r   r"   r.   AttributeError
ValueErrorr'   valuer   r   r   _set_strand      

zSeqFeature._set_strandz-Alias for the location's strand (DEPRECATED).fgetfsetdocc                 C   ,   t dt z| jjW S  ty   Y dS w )z2Get function for the reference property (PRIVATE).)Please use .location.ref rather than .refN)r,   r-   r   r"   refr3   r/   r   r   r   _get_ref     
zSeqFeature._get_refc                 C   r1   )z2Set function for the reference property (PRIVATE).r>   Nz!Can't set ref without a location.)r,   r-   r   r"   r?   r3   r4   r5   r   r   r   _set_ref  r8   zSeqFeature._set_refz*Alias for the location's ref (DEPRECATED).c                 C   r=   )z;Get function for the database reference property (PRIVATE)./Please use .location.ref_db rather than .ref_dbN)r,   r-   r   r"   ref_dbr3   r/   r   r   r   _get_ref_db"  rA   zSeqFeature._get_ref_dbc                 C   s   t dt || j_dS )z;Set function for the database reference property (PRIVATE).rC   N)r,   r-   r   r"   rD   r5   r   r   r   _set_ref_db-  s
   zSeqFeature._set_ref_dbz-Alias for the location's ref_db (DEPRECATED).c                 C   s:   t |to| j|jko| j|jko| j|jko| j|jkS )z;Check if two SeqFeature objects should be considered equal.)r   r   r$   r#   r"   r%   r'   otherr   r   r   __eq__;  s   




zSeqFeature.__eq__c                 C   sd   | j j d| j}| jr|d| j7 }| jr%| jdkr%|d| j7 }| jr,|d7 }|d7 }|S )z0Represent the feature as a string for debugging.r
   z, type=r   z, id=z, qualifiers=...r	   )	__class__r   r"   r#   r$   r%   r'   answerr   r   r   __repr__E  s   zSeqFeature.__repr__c                 C   sz   d| j  d}|d| j d7 }| jr!| jdkr!|d| j d7 }|d7 }t| jD ]}|d| d| j|  d7 }q*|S )	z+Return the full feature as a python string.ztype: 

location: r   zid: zqualifiers:
z	    Key: z	, Value: )r#   r"   r$   sortedr%   )r'   outqual_keyr   r   r   __str__Q  s   zSeqFeature.__str__c                 C   "   t | j|| j| j| j dS )zyReturn a copy of the feature with its location shifted (PRIVATE).

        The annotation qualifiers are copied.
        r"   r#   r$   r%   )r   r"   _shiftr#   r$   r%   copyr'   offsetr   r   r   rV   \  s   
zSeqFeature._shiftc                 C   rT   )a  Return a copy of the feature with its location flipped (PRIVATE).

        The argument length gives the length of the parent sequence. For
        example a location 0..20 (+1 strand) with parent length 30 becomes
        after flipping 10..30 (-1 strand). Strandless (None) or unknown
        strand (0) remain like that - just their end points are changed.

        The annotation qualifiers are copied.
        rU   )r   r"   _flipr#   r$   r%   rW   r'   lengthr   r   r   rZ   h  s   

zSeqFeature._flipc                 C   s"   | j du r	td| j j||dS )a  Extract the feature's sequence from supplied parent sequence.

        The parent_sequence can be a Seq like object or a string, and will
        generally return an object of the same type. The exception to this is
        a MutableSeq as the parent sequence will return a Seq object.

        This should cope with complex locations including complements, joins
        and fuzzy positions. Even mixed strand features should work! This
        also covers features on protein sequences (e.g. domains), although
        here reverse strand features are not permitted. If the
        location refers to other records, they must be supplied in the
        optional dictionary references.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
        >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
        >>> f = SeqFeature(SimpleLocation(8, 15), type="domain")
        >>> f.extract(seq)
        Seq('VALIVIC')

        If the SimpleLocation is None, e.g. when parsing invalid locus
        locations in the GenBank parser, extract() will raise a ValueError.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqFeature import SeqFeature
        >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
        >>> f = SeqFeature(None, type="domain")
        >>> f.extract(seq)
        Traceback (most recent call last):
           ...
        ValueError: The feature's .location is None. Check the sequence file for a valid location.

        Note - currently only compound features of type "join" are supported.
        NzNThe feature's .location is None. Check the sequence file for a valid location.
references)r"   r4   extract)r'   parent_sequencer^   r   r   r   r_   y  s
   
#zSeqFeature.extractStandard*Fc           
      C   s   |du rzt | jd d d }W n ty   d}Y nw |dvr)td| d| ||d }| jd|gd }	|du rE| jd	k}|j|	||||d
S )a	  Get a translation of the feature's sequence.

        This method is intended for CDS or other features that code proteins
        and is a shortcut that will both extract the feature and
        translate it, taking into account the codon_start and transl_table
        qualifiers, if they are present. If they are not present the
        value of the arguments "table" and "start_offset" are used.

        The "cds" parameter is set to "True" if the feature is of type
        "CDS" but can be overridden by giving an explicit argument.

        The arguments stop_symbol, to_stop and gap have the same meaning
        as Seq.translate, refer to that documentation for further information.

        Arguments:
         - parent_sequence - A DNA or RNA sequence.
         - table - Which codon table to use if there is no transl_table
           qualifier for this feature. This can be either a name
           (string), an NCBI identifier (integer), or a CodonTable
           object (useful for non-standard genetic codes).  This
           defaults to the "Standard" table.
         - start_offset - offset at which the first complete codon of a
           coding feature can be found, relative to the first base of
           that feature. Has a valid value of 0, 1 or 2. NOTE: this
           uses python's 0-based numbering whereas the codon_start
           qualifier in files from NCBI use 1-based numbering.
           Will override a codon_start qualifier

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
        >>> seq = Seq("GGTTACACTTACCGATAATGTCTCTGATGA")
        >>> f = SeqFeature(SimpleLocation(0, 30), type="CDS")
        >>> f.qualifiers['transl_table'] = [11]

        Note that features of type CDS are subject to the usual
        checks at translation. But you can override this behavior
        by giving explicit arguments:

        >>> f.translate(seq, cds=False)
        Seq('GYTYR*CL**')

        Now use the start_offset argument to change the frame. Note
        this uses python 0-based numbering.

        >>> f.translate(seq, start_offset=1, cds=False)
        Seq('VTLTDNVSD')

        Alternatively use the codon_start qualifier to do the same
        thing. Note: this uses 1-based numbering, which is found
        in files from NCBI.

        >>> f.qualifiers['codon_start'] = [2]
        >>> f.translate(seq, cds=False)
        Seq('VTLTDNVSD')
        Ncodon_startr   r   )r   r   r   z;The start_offset must be 0, 1, or 2. The supplied value is zR. Check the value of either the codon_start qualifier or the start_offset argumenttransl_tableCDS)tablestop_symbolto_stopcdsgap)intr%   KeyErrorr4   r_   getr#   	translate)
r'   r`   rf   start_offsetrg   rh   ri   rj   feat_seqcodon_tabler   r   r   rn     s.   C
zSeqFeature.translatec                 C      dS )a  Boolean value of an instance of this class (True).

        This behavior is for backwards compatibility, since until the
        __len__ method was added, a SeqFeature always evaluated as True.

        Note that in comparison, Seq objects, strings, lists, etc, will all
        evaluate to False if they have length zero.

        WARNING: The SeqFeature may in future evaluate to False when its
        length is zero (in order to better match normal python behavior)!
        Tr   r/   r   r   r   __bool__     zSeqFeature.__bool__c                 C   
   t | jS )a  Return the length of the region where the feature is located.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
        >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
        >>> f = SeqFeature(SimpleLocation(8, 15), type="domain")
        >>> len(f)
        7
        >>> f.extract(seq)
        Seq('VALIVIC')
        >>> len(f.extract(seq))
        7

        This is a proxy for taking the length of the feature's location:

        >>> len(f.location)
        7

        For simple features this is the same as the region spanned (end
        position minus start position using Pythonic counting). However, for
        a compound location (e.g. a CDS as the join of several exons) the
        gaps are not counted (e.g. introns). This ensures that len(f) matches
        len(f.extract(parent_seq)), and also makes sure things work properly
        with features wrapping the origin etc.
        )lenr"   r/   r   r   r   __len__  s   
zSeqFeature.__len__c                 C   ru   )ah  Iterate over the parent positions within the feature.

        The iteration order is strand aware, and can be thought of as moving
        along the feature using the parent sequence coordinates:

        >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
        >>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain")
        >>> len(f)
        5
        >>> for i in f: print(i)
        9
        8
        7
        6
        5
        >>> list(f)
        [9, 8, 7, 6, 5]

        This is a proxy for iterating over the location,

        >>> list(f.location)
        [9, 8, 7, 6, 5]
        )iterr"   r/   r   r   r   __iter__,  s   
zSeqFeature.__iter__c                 C   s
   || j v S )a  Check if an integer position is within the feature.

        >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
        >>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain")
        >>> len(f)
        5
        >>> [i for i in range(15) if i in f]
        [5, 6, 7, 8, 9]

        For example, to see which features include a SNP position, you could
        use this:

        >>> from Bio import SeqIO
        >>> record = SeqIO.read("GenBank/NC_000932.gb", "gb")
        >>> for f in record.features:
        ...     if 1750 in f:
        ...         print("%s %s" % (f.type, f.location))
        source [0:154478](+)
        gene [1716:4347](-)
        tRNA join{[4310:4347](-), [1716:1751](-)}

        Note that for a feature defined as a join of several subfeatures (e.g.
        the union of several exons) the gaps are not checked (e.g. introns).
        In this example, the tRNA location is defined in the GenBank file as
        complement(join(1717..1751,4311..4347)), so that position 1760 falls
        in the gap:

        >>> for f in record.features:
        ...     if 1760 in f:
        ...         print("%s %s" % (f.type, f.location))
        source [0:154478](+)
        gene [1716:4347](-)

        Note that additional care may be required with fuzzy locations, for
        example just before a BeforePosition:

        >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
        >>> from Bio.SeqFeature import BeforePosition
        >>> f = SeqFeature(SimpleLocation(BeforePosition(3), 8), type="domain")
        >>> len(f)
        5
        >>> [i for i in range(10) if i in f]
        [3, 4, 5, 6, 7]

        Note that is is a proxy for testing membership on the location.

        >>> [i for i in range(10) if i in f.location]
        [3, 4, 5, 6, 7]
        )r"   r5   r   r   r   __contains__F  s   
2zSeqFeature.__contains__)Nr   r   NNN)ra   Nrb   FNN)r   r   r   r   r)   r0   r7   propertyr.   r@   rB   r?   rE   rF   rD   rI   rM   rS   rV   rZ   r_   rn   rs   rw   ry   rz   r   r   r   r   r      s\    
/

-
_r   c                   @   0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )	Referenceaw  Represent a Generic Reference object.

    Attributes:
     - location - A list of Location objects specifying regions of
       the sequence that the references correspond to. If no locations are
       specified, the entire sequence is assumed.
     - authors - A big old string, or a list split by author, of authors
       for the reference.
     - title - The title of the reference.
     - journal - Journal the reference was published in.
     - medline_id - A medline reference for the article.
     - pubmed_id - A pubmed reference for the article.
     - comment - A place to stick any comments about the reference.

    c                 C   s4   g | _ d| _d| _d| _d| _d| _d| _d| _dS )zInitialize the class.r   Nr"   authorsconsrtmtitlejournal
medline_id	pubmed_idcommentr/   r   r   r   r)     s   
zReference.__init__c                 C   s   d}| j D ]
}|d| d7 }q|d| j d7 }| jr%|d| j d7 }|d| j d7 }|d| j d7 }|d| j d7 }|d	| j d7 }|d
| j d7 }|S )z4Return the full Reference object as a python string.r   rO   rN   z	authors: z	consrtm: ztitle: z	journal: zmedline id: zpubmed id: z	comment: r   )r'   rQ   single_locationr   r   r   rS     s   
zReference.__str__c                 C   s   | j j d| jdS )z9Represent the Reference object as a string for debugging.z(title=z, ...))rJ   r   r   r/   r   r   r   rM     s   zReference.__repr__c                 C   s`   | j |j ko/| j|jko/| j|jko/| j|jko/| j|jko/| j|jko/| j|jko/| j|jkS )zCheck if two Reference objects should be considered equal.

        Note prior to Biopython 1.70 the location was not compared, as
        until then __eq__ for the SimpleLocation class was not defined.
        )r   r   r   r   r   r   r   r"   rG   r   r   r   rI     s   






zReference.__eq__N)r   r   r   r   r)   rS   rM   rI   r   r   r   r   r~     s    r~   c                   @   s&   e Zd ZdZedd Zd	ddZdS )
Locationz,Abstract base class representing a location.c                 C      | j j dS )z8Represent the Location object as a string for debugging.(...)rJ   r   r/   r   r   r   rM        zLocation.__repr__NFTc           
      C   s  |  dr| d dkrtd|  d| dd } d}n|r!d}nd}|  d	r8d
}t| dd ddd }n?|  drMd}t| dd ddd }n*|  drbd}t| dd ddd }nt| ||}||_|dkru|j  |S g }|D ]&}	t|	||}|du r n=|jdkr|dkrtdn||_|	|j q{t
|dkr|S |dkr|D ]	}|jdksJ q|ddd }t||dS d| v rd
| v rtd|  dd| v rtdt | dd} t| S td|  d)a  Create a Location object from a string.

        This should accept any valid location string in the INSDC Feature Table
        format (https://www.insdc.org/submitting-standards/feature-table/) as
        used in GenBank, DDBJ and EMBL files.

        Simple examples:

        >>> Location.fromstring("123..456", 1000)
        SimpleLocation(ExactPosition(122), ExactPosition(456), strand=1)
        >>> Location.fromstring("complement(<123..>456)", 1000)
        SimpleLocation(BeforePosition(122), AfterPosition(456), strand=-1)

        A more complex location using within positions,

        >>> Location.fromstring("(9.10)..(20.25)", 1000)
        SimpleLocation(WithinPosition(8, left=8, right=9), WithinPosition(25, left=20, right=25), strand=1)

        Notice how that will act as though it has overall start 8 and end 25.

        Zero length between feature,

        >>> Location.fromstring("123^124", 1000)
        SimpleLocation(ExactPosition(123), ExactPosition(123), strand=1)

        The expected sequence length is needed for a special case, a between
        position at the start/end of a circular genome:

        >>> Location.fromstring("1000^1", 1000)
        SimpleLocation(ExactPosition(1000), ExactPosition(1000), strand=1)

        Apart from this special case, between positions P^Q must have P+1==Q,

        >>> Location.fromstring("123^456", 1000)
        Traceback (most recent call last):
           ...
        Bio.SeqFeature.LocationParserError: invalid feature location '123^456'

        You can optionally provide a reference name:

        >>> Location.fromstring("AL391218.9:105173..108462", 2000000)
        SimpleLocation(ExactPosition(105172), ExactPosition(108462), strand=1, ref='AL391218.9')

        >>> Location.fromstring("<2644..159", 2868, "circular")
        CompoundLocation([SimpleLocation(BeforePosition(2643), ExactPosition(2868), strand=1), SimpleLocation(ExactPosition(0), ExactPosition(159), strand=1)], 'join')
        complement(r	   zclosing bracket missing in ''   r   Nzjoin(join   r   zorder(order   zbond(bondzdouble complement in '{text}'?)operatorz"failed to parse feature location 'zO' containing a combination of 'join' and 'order' (nested operators) are illegalz,)z5Dropping trailing comma in malformed feature location)
startswithr4   _splitr   
fromstringr.   partsreverser   extendrv   r    r,   r-   r   replacer   )
textr\   circularstrandedr.   r   r   loclocspartr   r   r   r     sh   
/






zLocation.fromstring)NFT)r   r   r   r   r   rM   r   r   r   r   r   r     s
    
r   c                   @   s   e Zd ZdZd.ddZed/ddZdd	 Zd
d Ze	ee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' Ze	d(d) Ze	d*d+ Zd0d,d-ZdS )1r   a  Specify the location of a feature along a sequence.

    The SimpleLocation is used for simple continuous features, which can
    be described as running from a start position to and end position
    (optionally with a strand and reference information).  More complex
    locations made up from several non-continuous parts (e.g. a coding
    sequence made up of several exons) are described using a SeqFeature
    with a CompoundLocation.

    Note that the start and end location numbering follow Python's scheme,
    thus a GenBank entry of 123..150 (one based counting) becomes a location
    of [122:150] (zero based counting).

    >>> from Bio.SeqFeature import SimpleLocation
    >>> f = SimpleLocation(122, 150)
    >>> print(f)
    [122:150]
    >>> print(f.start)
    122
    >>> print(f.end)
    150
    >>> print(f.strand)
    None

    Note the strand defaults to None. If you are working with nucleotide
    sequences you'd want to be explicit if it is the forward strand:

    >>> from Bio.SeqFeature import SimpleLocation
    >>> f = SimpleLocation(122, 150, strand=+1)
    >>> print(f)
    [122:150](+)
    >>> print(f.strand)
    1

    Note that for a parent sequence of length n, the SimpleLocation
    start and end must satisfy the inequality 0 <= start <= end <= n.
    This means even for features on the reverse strand of a nucleotide
    sequence, we expect the 'start' coordinate to be less than the
    'end'.

    >>> from Bio.SeqFeature import SimpleLocation
    >>> r = SimpleLocation(122, 150, strand=-1)
    >>> print(r)
    [122:150](-)
    >>> print(r.start)
    122
    >>> print(r.end)
    150
    >>> print(r.strand)
    -1

    i.e. Rather than thinking of the 'start' and 'end' biologically in a
    strand aware manner, think of them as the 'left most' or 'minimum'
    boundary, and the 'right most' or 'maximum' boundary of the region
    being described. This is particularly important with compound
    locations describing non-continuous regions.

    In the example above we have used standard exact positions, but there
    are also specialised position objects used to represent fuzzy positions
    as well, for example a GenBank location like complement(<123..150)
    would use a BeforePosition object for the start.
    Nc                 C   s   t |tr	|| _nt |trt|| _ntd|dt| t |tr)|| _nt |tr4t|| _ntd|dt| t | jtr_t | j	tr_| j| j	kr_t
d| j	 d| j d|| _|| _|| _dS )a  Initialize the class.

        start and end arguments specify the values where the feature begins
        and ends. These can either by any of the ``*Position`` objects that
        inherit from Position, or can just be integers specifying the position.
        In the case of integers, the values are assumed to be exact and are
        converted in ExactPosition arguments. This is meant to make it easy
        to deal with non-fuzzy ends.

        i.e. Short form:

        >>> from Bio.SeqFeature import SimpleLocation
        >>> loc = SimpleLocation(5, 10, strand=-1)
        >>> print(loc)
        [5:10](-)

        Explicit form:

        >>> from Bio.SeqFeature import SimpleLocation, ExactPosition
        >>> loc = SimpleLocation(ExactPosition(5), ExactPosition(10), strand=-1)
        >>> print(loc)
        [5:10](-)

        Other fuzzy positions are used similarly,

        >>> from Bio.SeqFeature import SimpleLocation
        >>> from Bio.SeqFeature import BeforePosition, AfterPosition
        >>> loc2 = SimpleLocation(BeforePosition(5), AfterPosition(10), strand=-1)
        >>> print(loc2)
        [<5:>10](-)

        For nucleotide features you will also want to specify the strand,
        use 1 for the forward (plus) strand, -1 for the reverse (negative)
        strand, 0 for stranded but strand unknown (? in GFF3), or None for
        when the strand does not apply (dot in GFF3), e.g. features on
        proteins.

        >>> loc = SimpleLocation(5, 10, strand=+1)
        >>> print(loc)
        [5:10](+)
        >>> print(loc.strand)
        1

        Normally feature locations are given relative to the parent
        sequence you are working with, but an explicit accession can
        be given with the optional ref and db_ref strings:

        >>> loc = SimpleLocation(105172, 108462, ref="AL391218.9", strand=1)
        >>> print(loc)
        AL391218.9[105172:108462](+)
        >>> print(loc.ref)
        AL391218.9

        zstart= zend=zEnd location (z3) must be greater than or equal to start location (r	   N)r   Position_startrk   ExactPositionr!   r#   _endstartendr4   r.   r?   rD   )r'   r   r   r.   r?   rD   r   r   r   r)     s.   
8






zSimpleLocation.__init__Fc                 C   sl  |  dr| dd } d}nd}z| d\}}t|d }t|}W n	 ty,   Y nw d|  kr7|k r?n nt|||S z	| d\}} W n tyS   d}Y nw t| }|du retd	|  d
| 	 D ]
\}}	|	duru nqk|	| ks|J |dkrt
dt | dd } t| d}
t| }n|dkrt| d}
t| }ny|dv r| d\}}t|d}
t|}|
|kr|std|  dt
d|  t t|
||}td||}|dkr|| S || S n4|dkr!| d\}}t|}t|}|d |ks||kr|dkrt|}
|
}ntd|  d
|
dk r.td|  d
t|
|||dS )z-Create a SimpleLocation object from a string.r   r   r   Nz..r   r   :z"Could not parse feature location 'r   r   z+Dropping bond qualifier in feature locationr   solo)pairwithinoneofzit appears that 'zL' is a feature that spans the origin, but the sequence topology is undefinedzAttempting to fix invalid location %r as it looks like incorrect origin wrapping. Please fix input file, this could have unintended behavior.between^zinvalid feature location 'z0negative starting position in feature location ')r?   )r   splitrk   r4   r   _re_location_categorymatchr   	groupdictitemsr,   r-   r   r   r   r   )r   r\   r   r.   ser?   mkeyr6   s_pose_posf1f2r   r   r   r     s   




"

zSimpleLocation.fromstringc                 C      | j S )r*   )_strandr/   r   r   r   r0   7  s   zSimpleLocation._get_strandc                 C   s    |dvrt d||| _dS )r2   )r   r   r   Nz(Strand should be +1, -1, 0 or None, not N)r4   r   r5   r   r   r   r7   ;  s   
zSimpleLocation._set_strandz+Strand of the location (+1, -1, 0 or None).r9   c                 C   s   d| j  d| j d}| jr| jr| j d| j | }n| jr%| j| }| jdu r,|S | jdkr5|d S | jdkr>|d S |d	 S )
a   Return a representation of the SimpleLocation object (with python counting).

        For the simple case this uses the python splicing syntax, [122:150]
        (zero based counting) which GenBank would call 123..150 (one based
        counting).
        [r   ]Nr   z(+)r   z(-)z(?))r   r   r?   rD   r.   rK   r   r   r   rS   G  s   



zSimpleLocation.__str__c                 C   st   d}| j dur|d| j 7 }| jdur|d| j7 }| jdur)|d| j7 }| jj d| jd| j| dS )	z>Represent the SimpleLocation object as a string for debugging.r   Nz	, strand=z, ref=z	, ref_db=r
   , r	   )r.   r?   rD   rJ   r   r   r   )r'   optionalr   r   r   rM   ^  s   


"zSimpleLocation.__repr__c                 C   s.   t |trt| |gS t |tr| |S tS )ac  Combine location with another SimpleLocation object, or shift it.

        You can add two feature locations to make a join CompoundLocation:

        >>> from Bio.SeqFeature import SimpleLocation
        >>> f1 = SimpleLocation(5, 10)
        >>> f2 = SimpleLocation(20, 30)
        >>> combined = f1 + f2
        >>> print(combined)
        join{[5:10], [20:30]}

        This is thus equivalent to:

        >>> from Bio.SeqFeature import CompoundLocation
        >>> join = CompoundLocation([f1, f2])
        >>> print(join)
        join{[5:10], [20:30]}

        You can also use sum(...) in this way:

        >>> join = sum([f1, f2])
        >>> print(join)
        join{[5:10], [20:30]}

        Furthermore, you can combine a SimpleLocation with a CompoundLocation
        in this way.

        Separately, adding an integer will give a new SimpleLocation with
        its start and end offset by that amount. For example:

        >>> print(f1)
        [5:10]
        >>> print(f1 + 100)
        [105:110]
        >>> print(200 + f1)
        [205:210]

        This can be useful when editing annotation.
        )r   r   r    rk   rV   NotImplementedrG   r   r   r   __add__i  s
   
(

zSimpleLocation.__add__c                 C   s   t |tr
| |S tS )zMReturn a SimpleLocation object by shifting the location by an integer amount.r   rk   rV   r   rG   r   r   r   __radd__  s   

zSimpleLocation.__radd__c                 C   s   t |tr| | S tS )a  Subtracting an integer will shift the start and end by that amount.

        >>> from Bio.SeqFeature import SimpleLocation
        >>> f1 = SimpleLocation(105, 150)
        >>> print(f1)
        [105:150]
        >>> print(f1 - 100)
        [5:50]

        This can be useful when editing annotation. You can also add an integer
        to a feature location (which shifts in the opposite direction).
        r   rG   r   r   r   __sub__  s   
zSimpleLocation.__sub__c                 C   rr   a  Return True regardless of the length of the feature.

        This behavior is for backwards compatibility, since until the
        __len__ method was added, a SimpleLocation always evaluated as True.

        Note that in comparison, Seq objects, strings, lists, etc, will all
        evaluate to False if they have length zero.

        WARNING: The SimpleLocation may in future evaluate to False when its
        length is zero (in order to better match normal python behavior)!
        Tr   r/   r   r   r   __nonzero__  rt   zSimpleLocation.__nonzero__c                 C   s   t | jt | j S )ax  Return the length of the region described by the SimpleLocation object.

        Note that extra care may be needed for fuzzy locations, e.g.

        >>> from Bio.SeqFeature import SimpleLocation
        >>> from Bio.SeqFeature import BeforePosition, AfterPosition
        >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
        >>> len(loc)
        5
        )rk   r   r   r/   r   r   r   rw     s   zSimpleLocation.__len__c                 C   s.   t |ts	td|| jk s|| jkrdS dS )a  Check if an integer position is within the SimpleLocation object.

        Note that extra care may be needed for fuzzy locations, e.g.

        >>> from Bio.SeqFeature import SimpleLocation
        >>> from Bio.SeqFeature import BeforePosition, AfterPosition
        >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
        >>> len(loc)
        5
        >>> [i for i in range(15) if i in loc]
        [5, 6, 7, 8, 9]
        zWCurrently we only support checking for integer positions being within a SimpleLocation.FT)r   rk   r4   r   r   r5   r   r   r   rz     s   
zSimpleLocation.__contains__c                 c   sF    | j dkrt| jd | jd dE dH  dS t| j| jE dH  dS )a  Iterate over the parent positions within the SimpleLocation object.

        >>> from Bio.SeqFeature import SimpleLocation
        >>> from Bio.SeqFeature import BeforePosition, AfterPosition
        >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
        >>> len(loc)
        5
        >>> for i in loc: print(i)
        5
        6
        7
        8
        9
        >>> list(loc)
        [5, 6, 7, 8, 9]
        >>> [i for i in range(15) if i in loc]
        [5, 6, 7, 8, 9]

        Note this is strand aware:

        >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10), strand = -1)
        >>> list(loc)
        [9, 8, 7, 6, 5]
        r   r   N)r.   ranger   r   r/   r   r   r   ry     s   
"zSimpleLocation.__iter__c                 C   sJ   t |tsdS | j|jko$| j|jko$| j|jko$| j|jko$| j	|j	kS )z<Implement equality by comparing all the location attributes.F)
r   r   r   r   r   r   r   r.   r?   rD   rG   r   r   r   rI     s   




zSimpleLocation.__eq__c                 C   s,   | j s| jr| S t| j| | j| | jdS )zReturn a copy of the SimpleLocation shifted by an offset (PRIVATE).

        Returns self when location is relative to an external reference.
        r   r   r.   )r?   rD   r   r   r   r.   rX   r   r   r   rV     s   zSimpleLocation._shiftc                 C   sT   | j s| jr| S | jdkrd}n| jdkrd}n| j}t| j|| j||dS )zReturn a copy of the location after the parent is reversed (PRIVATE).

        Returns self when location is relative to an external reference.
        r   r   r   )r?   rD   r.   r   r   rZ   r   )r'   r\   flip_strandr   r   r   rZ     s   



zSimpleLocation._flipc                 C   s   | gS )a%  Read only list of sections (always one, the SimpleLocation object).

        This is a convenience property allowing you to write code handling
        both SimpleLocation objects (with one part) and more complex
        CompoundLocation objects (with multiple parts) interchangeably.
        r   r/   r   r   r   r   1  s   zSimpleLocation.partsc                 C   r   )zStart location - left most (minimum) value, regardless of strand.

        Read only, returns an integer like position object, possibly a fuzzy
        position.
        )r   r/   r   r   r   r   ;     zSimpleLocation.startc                 C   r   )zEnd location - right most (maximum) value, regardless of strand.

        Read only, returns an integer like position object, possibly a fuzzy
        position.
        )r   r/   r   r   r   r   D  r   zSimpleLocation.endc                 C   s   | j s| jr$|std| j  d| j |vrtd| j  d|| j  }|t| jt| j }t|tr9t|}| j	dkrBt
|}|S )a  Extract the sequence from supplied parent sequence using the SimpleLocation object.

        The parent_sequence can be a Seq like object or a string, and will
        generally return an object of the same type. The exception to this is
        a MutableSeq as the parent sequence will return a Seq object.
        If the location refers to other records, they must be supplied
        in the optional dictionary references.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqFeature import SimpleLocation
        >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
        >>> feature_loc = SimpleLocation(8, 15)
        >>> feature_loc.extract(seq)
        Seq('VALIVIC')

        z%Feature references another sequence (z), references mandatoryz), not found in referencesr   )r?   rD   r4   rk   r   r   r   r   r   r.   r   )r'   r`   r^   f_seqr   r   r   r_   M  s    



zSimpleLocation.extract)NNN)NFr{   )r   r   r   r   r)   staticmethodr   r0   r7   r|   r.   rS   rM   r   r   r   r   rw   rz   ry   rI   rV   rZ   r   r   r   r_   r   r   r   r   r   G  s>    
?Q^0
	

r   c                   @   s   e Zd ZdZd,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dd Zdd Zdd Zdd Zdd Zdd Zdd  Ze	d!d" Ze	d#d$ Ze	d%d& Ze	d'd( Zd-d*d+Zd)S ).r    zBFor handling joins etc where a feature location has several parts.r   c                 C   sR   || _ t|| _| jD ]}t|tstd|j qt|dk r'td|dS )a  Initialize the class.

        >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
        >>> f1 = SimpleLocation(10, 40, strand=+1)
        >>> f2 = SimpleLocation(50, 59, strand=+1)
        >>> f = CompoundLocation([f1, f2])
        >>> len(f) == len(f1) + len(f2) == 39 == len(list(f))
        True
        >>> print(f.operator)
        join
        >>> 5 in f
        False
        >>> 15 in f
        True
        >>> f.strand
        1

        Notice that the strand of the compound location is computed
        automatically - in the case of mixed strands on the sub-locations
        the overall strand is set to None.

        >>> f = CompoundLocation([SimpleLocation(3, 6, strand=+1),
        ...                       SimpleLocation(10, 13, strand=-1)])
        >>> print(f.strand)
        None
        >>> len(f)
        6
        >>> list(f)
        [3, 4, 5, 12, 11, 10]

        The example above doing list(f) iterates over the coordinates within the
        feature. This allows you to use max and min on the location, to find the
        range covered:

        >>> min(f)
        3
        >>> max(f)
        12

        More generally, you can use the compound location's start and end which
        give the full span covered, 0 <= start <= end <= full sequence length.

        >>> f.start == min(f)
        True
        >>> f.end == max(f) + 1
        True

        This is consistent with the behavior of the SimpleLocation for a single
        region, where again the 'start' and 'end' do not necessarily give the
        biological start and end, but rather the 'minimal' and 'maximal'
        coordinate boundaries.

        Note that adding locations provides a more intuitive method of
        construction:

        >>> f = SimpleLocation(3, 6, strand=+1) + SimpleLocation(10, 13, strand=-1)
        >>> len(f)
        6
        >>> list(f)
        [3, 4, 5, 12, 11, 10]
        zICompoundLocation should be given a list of SimpleLocation objects, not %sr   z3CompoundLocation should have at least 2 parts, not N)r   listr   r   r   r4   rJ   rv   )r'   r   r   r   r   r   r   r)   y  s   >


zCompoundLocation.__init__c                 C   s    d| j ddd | jD f S )zNReturn a representation of the CompoundLocation object (with python counting).z%s{%s}r   c                 s       | ]}t |V  qd S r{   )str.0r   r   r   r   	<genexpr>      z+CompoundLocation.__str__.<locals>.<genexpr>)r   r   r   r/   r   r   r   rS     s    zCompoundLocation.__str__c                 C   s   | j j d| jd| jdS )z>Represent the CompoundLocation object as string for debugging.r
   r   r	   )rJ   r   r   r   r/   r   r   r   rM     s   zCompoundLocation.__repr__c                 C   s(   t dd | jD dkr| jd jS dS )r*   c                 S   s   h | ]}|j qS r   r.   r   r   r   r   	<setcomp>  s    z/CompoundLocation._get_strand.<locals>.<setcomp>r   r   N)rv   r   r.   r/   r   r   r   r0     s   zCompoundLocation._get_strandc                 C   s   | j D ]}||_qdS )r2   N)r   r.   r'   r6   r   r   r   r   r7     s   
zCompoundLocation._set_stranda  Overall strand of the compound location.

        If all the parts have the same strand, that is returned. Otherwise
        for mixed strands, this returns None.

        >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
        >>> f1 = SimpleLocation(15, 17, strand=1)
        >>> f2 = SimpleLocation(20, 30, strand=-1)
        >>> f = f1 + f2
        >>> f1.strand
        1
        >>> f2.strand
        -1
        >>> f.strand
        >>> f.strand is None
        True

        If you set the strand of a CompoundLocation, this is applied to
        all the parts - use with caution:

        >>> f.strand = 1
        >>> f1.strand
        1
        >>> f2.strand
        1
        >>> f.strand
        1

        r9   c                 C   sx   t |trt| j|g | jS t |tr0| j|jkr&td| j d|j t| j|j | jS t |tr:| |S t)a  Combine locations, or shift the location by an integer offset.

        >>> from Bio.SeqFeature import SimpleLocation
        >>> f1 = SimpleLocation(15, 17) + SimpleLocation(20, 30)
        >>> print(f1)
        join{[15:17], [20:30]}

        You can add another SimpleLocation:

        >>> print(f1 + SimpleLocation(40, 50))
        join{[15:17], [20:30], [40:50]}
        >>> print(SimpleLocation(5, 10) + f1)
        join{[5:10], [15:17], [20:30]}

        You can also add another CompoundLocation:

        >>> f2 = SimpleLocation(40, 50) + SimpleLocation(60, 70)
        >>> print(f2)
        join{[40:50], [60:70]}
        >>> print(f1 + f2)
        join{[15:17], [20:30], [40:50], [60:70]}

        Also, as with the SimpleLocation, adding an integer shifts the
        location's coordinates by that offset:

        >>> print(f1 + 100)
        join{[115:117], [120:130]}
        >>> print(200 + f1)
        join{[215:217], [220:230]}
        >>> print(f1 + (-5))
        join{[10:12], [15:25]}
        zMixed operators z and )	r   r   r    r   r   r4   rk   rV   NotImplementedErrorrG   r   r   r   r     s   
!


zCompoundLocation.__add__c                 C   s6   t |trt|g| j | jS t |tr| |S t)zAdd a feature to the left.)r   r   r    r   r   rk   rV   r   rG   r   r   r   r   0  s
   


zCompoundLocation.__radd__c                 C   s   | j D ]	}||v r dS qdS )zCCheck if an integer position is within the CompoundLocation object.TFr   r   r   r   r   rz   9  s
   
zCompoundLocation.__contains__c                 C   rr   r   r   r/   r   r   r   r   @  rt   zCompoundLocation.__nonzero__c                 C      t dd | jD S )z1Return the length of the CompoundLocation object.c                 s   r   r{   )rv   r   r   r   r   r   P  r   z+CompoundLocation.__len__.<locals>.<genexpr>)sumr   r/   r   r   r   rw   N     zCompoundLocation.__len__c                 c   s    | j D ]}|E dH  qdS )zEIterate over the parent positions within the CompoundLocation object.Nr   )r'   r   r   r   r   ry   R  s   
zCompoundLocation.__iter__c                 C   s`   t |tsdS t| jt|jkrdS | j|jkrdS t| j|jD ]\}}||kr- dS q"dS )zXCheck if all parts of CompoundLocation are equal to all parts of other CompoundLocation.FT)r   r    rv   r   r   zip)r'   rH   	self_part
other_partr   r   r   rI   W  s   
zCompoundLocation.__eq__c                    s   t  fdd| jD | jS )zEReturn a copy of the CompoundLocation shifted by an offset (PRIVATE).c                       g | ]}|  qS r   )rV   r   rY   r   r   
<listcomp>g      z+CompoundLocation._shift.<locals>.<listcomp>)r    r   r   rX   r   r   r   rV   d  s   zCompoundLocation._shiftc                    sV   t dd | jD rt fdd| jddd D | jS t fdd| jD | jS )a  Return a copy of the locations after the parent is reversed (PRIVATE).

        Note that the order of the parts is NOT reversed unless all parts
        have strand=None, since the order has meaning for stranded features.
        Consider a CDS on the forward strand with exons small, medium
        and large (in length). Once we change the frame of reference
        to the reverse complement strand, the start codon is still part of
        the small exon, and the stop codon still part of the large exon -
        so the part order remains the same!

        Here is an artificial example, were the features map to the two upper
        case regions and the lower case runs of n are not used:

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqFeature import SimpleLocation
        >>> dna = Seq("nnnnnAGCATCCTGCTGTACnnnnnnnnGAGAMTGCCATGCCCCTGGAGTGAnnnnn")
        >>> small = SimpleLocation(5, 20, strand=1)
        >>> large = SimpleLocation(28, 52, strand=1)
        >>> location = small + large
        >>> print(small)
        [5:20](+)
        >>> print(large)
        [28:52](+)
        >>> print(location)
        join{[5:20](+), [28:52](+)}
        >>> for part in location.parts:
        ...     print(len(part))
        ...
        15
        24

        As you can see, this is a silly example where each "exon" is a word:

        >>> print(small.extract(dna).translate())
        SILLY
        >>> print(large.extract(dna).translate())
        EXAMPLE*
        >>> print(location.extract(dna).translate())
        SILLYEXAMPLE*
        >>> for part in location.parts:
        ...     print(part.extract(dna).translate())
        ...
        SILLY
        EXAMPLE*

        Now, let's look at this from the reverse strand frame of reference:

        >>> flipped_dna = dna.reverse_complement()
        >>> flipped_location = location._flip(len(dna))
        >>> print(flipped_location.extract(flipped_dna).translate())
        SILLYEXAMPLE*
        >>> for part in flipped_location.parts:
        ...     print(part.extract(flipped_dna).translate())
        ...
        SILLY
        EXAMPLE*

        The key point here is the first part of the CompoundFeature is still the
        small exon, while the second part is still the large exon:

        >>> for part in flipped_location.parts:
        ...     print(len(part))
        ...
        15
        24
        >>> print(flipped_location)
        join{[37:52](-), [5:29](-)}

        Notice the parts are not reversed. However, there was a bug here in older
        versions of Biopython which would have given join{[5:29](-), [37:52](-)}
        and the translation would have wrongly been "EXAMPLE*SILLY" instead.

        When all the parts have strand None, the order of the parts is reversed.
        In principle this does not change the meaning of the location, but improves
        the representation of feature locations spanning the origin in circular
        molecules.

        >>> loc = SimpleLocation(4, 6, None) + SimpleLocation(0, 1, None)
        >>> print(loc)
        join{[4:6], [0:1]}
        >>> print(loc._flip(6))
        join{[5:6], [0:2]}

        join{[0:2], [5:6]} would not be properly represented in SnapGene, Benchling, etc.
        c                 s   s    | ]}|j d u V  qd S r{   r   r   r   r   r   r     s    z)CompoundLocation._flip.<locals>.<genexpr>c                    r   r   rZ   r   r\   r   r   r     r   z*CompoundLocation._flip.<locals>.<listcomp>Nr   c                    r   r   r   r   r   r   r   r     r   )allr   r    r   r[   r   r   r   rZ   j  s   V zCompoundLocation._flipc                 C   r   )a'  Start location - left most (minimum) value, regardless of strand.

        Read only, returns an integer like position object, possibly a fuzzy
        position.

        For the special case of a CompoundLocation wrapping the origin of a
        circular genome, this will return zero.
        c                 s       | ]}|j V  qd S r{   )r   r   r   r   r   r         z)CompoundLocation.start.<locals>.<genexpr>)minr   r/   r   r   r   r        
zCompoundLocation.startc                 C   r   )a1  End location - right most (maximum) value, regardless of strand.

        Read only, returns an integer like position object, possibly a fuzzy
        position.

        For the special case of a CompoundLocation wrapping the origin of
        a circular genome this will match the genome length.
        c                 s   r   r{   )r   r   r   r   r   r     r   z'CompoundLocation.end.<locals>.<genexpr>)maxr   r/   r   r   r   r     r   zCompoundLocation.endc                 C   rr   zDNot present in CompoundLocation, dummy method for API compatibility.Nr   r/   r   r   r   r?        zCompoundLocation.refc                 C   rr   r   r   r/   r   r   r   rD     r   zCompoundLocation.ref_dbNc                    s*    fdd| j D }tdd |}|S )a	  Extract the sequence from supplied parent sequence using the CompoundLocation object.

        The parent_sequence can be a Seq like object or a string, and will
        generally return an object of the same type. The exception to this is
        a MutableSeq as the parent sequence will return a Seq object.
        If the location refers to other records, they must be supplied
        in the optional dictionary references.

        >>> from Bio.Seq import Seq
        >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
        >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
        >>> fl1 = SimpleLocation(2, 8)
        >>> fl2 = SimpleLocation(10, 15)
        >>> fl3 = CompoundLocation([fl1,fl2])
        >>> fl3.extract(seq)
        Seq('QHKAMILIVIC')

        c                    s   g | ]	}|j  d qS )r]   )r_   r   r`   r^   r   r   r     s    z,CompoundLocation.extract.<locals>.<listcomp>c                 S   s   | | S r{   r   )xyr   r   r   <lambda>  s    z*CompoundLocation.extract.<locals>.<lambda>)r   	functoolsreduce)r'   r`   r^   r   r   r   r   r   r_     s
   zCompoundLocation.extract)r   r{   )r   r   r   r   r)   rS   rM   r0   r7   r|   r.   r   r   rz   r   rw   ry   rI   rV   rZ   r   r   r?   rD   r_   r   r   r   r   r    v  s<    
K"/	_



r    c                   @   s*   e Zd ZdZedd ZedddZdS )	r   z,Abstract base class representing a position.c                 C   r   )z8Represent the Position object as a string for debugging.r   r   r/   r   r   r   rM   	  r   zPosition.__repr__r   c                    sb   dkr dkrt d| dkrt S | dr$tt| dd   S | dr5tt| dd   S | drFtt| dd   S t| }|durq|	 \}}t|  }t|  } dkrh|}n|}t
|||d	S t| }|dur|	 d } fd
d|dD } dkrtdd |D }n	tdd |D }t||dS tt|   S )a  Build a Position object from the text string.

        For an end position, leave offset as zero (default):

        >>> Position.fromstring("5")
        ExactPosition(5)

        For a start position, set offset to minus one (for Python counting):

        >>> Position.fromstring("5", -1)
        ExactPosition(4)

        This also covers fuzzy positions:

        >>> p = Position.fromstring("<5")
        >>> p
        BeforePosition(5)
        >>> print(p)
        <5
        >>> int(p)
        5

        >>> Position.fromstring(">5")
        AfterPosition(5)

        By default assumes an end position, so note the integer behavior:

        >>> p = Position.fromstring("one-of(5,8,11)")
        >>> p
        OneOfPosition(11, choices=[ExactPosition(5), ExactPosition(8), ExactPosition(11)])
        >>> print(p)
        one-of(5,8,11)
        >>> int(p)
        11

        >>> Position.fromstring("(8.10)")
        WithinPosition(10, left=8, right=10)

        Fuzzy start positions:

        >>> p = Position.fromstring("<5", -1)
        >>> p
        BeforePosition(4)
        >>> print(p)
        <4
        >>> int(p)
        4

        Notice how the integer behavior changes too!

        >>> p = Position.fromstring("one-of(5,8,11)", -1)
        >>> p
        OneOfPosition(4, choices=[ExactPosition(4), ExactPosition(7), ExactPosition(10)])
        >>> print(p)
        one-of(4,7,10)
        >>> int(p)
        4

        r   r   z|To convert one-based indices to zero-based indices, offset must be either 0 (for end positions) or -1 (for start positions).r   r   N<>)leftrightc                    s   g | ]
}t t|  qS r   )r   rk   r   posr   r   r   r   d  s    z'Position.fromstring.<locals>.<listcomp>,c                 s   r   r{   rk   r   r   r   r   r   f  r   z&Position.fromstring.<locals>.<genexpr>c                 s   r   r{   r   r   r   r   r   r   h  r   )choices)r4   UnknownPositionr   UncertainPositionrk   BeforePositionAfterPosition_re_within_positionr   groupsWithinPosition_re_oneof_positionr   r   r   OneOfPositionr   )r   rY   r   r   r   default	positionsr   r   r   r   r     s<   =




zPosition.fromstringNr   )r   r   r   r   r   rM   r   r   r   r   r   r   r     s    
r   c                   @   :   e Zd ZdZdddZdd Zdd Zd	d
 Zdd ZdS )r   a  Specify the specific position of a boundary.

    Arguments:
     - position - The position of the boundary.
     - extension - An optional argument which must be zero since we don't
       have an extension. The argument is provided so that the same number
       of arguments can be passed to all position types.

    In this case, there is no fuzziness associated with the position.

    >>> p = ExactPosition(5)
    >>> p
    ExactPosition(5)
    >>> print(p)
    5

    >>> isinstance(p, Position)
    True
    >>> isinstance(p, int)
    True

    Integer comparisons and operations should work as expected:

    >>> p == 5
    True
    >>> p < 6
    True
    >>> p <= 5
    True
    >>> p + 10
    ExactPosition(15)

    r   c                 C   $   |dkrt d| dt| |S )zCreate an ExactPosition object.r   Non-zero extension  for exact position.r3   rk   __new__clsposition	extensionr   r   r   r       zExactPosition.__new__c                 C   s   t t| S )zKReturn a representation of the ExactPosition object (with python counting).)r   rk   r/   r   r   r   rS     s   zExactPosition.__str__c                 C      d| j jt| f S )z=Represent the ExactPosition object as a string for debugging.%s(%i)rJ   r   rk   r/   r   r   r   rM     r   zExactPosition.__repr__c                 C      |  t| | S IReturn a copy of the position object with its location shifted (PRIVATE).rJ   rk   rX   r   r   r   r        zExactPosition.__add__c                 C   s   |  |t|  S EReturn a copy of the location after the parent is reversed (PRIVATE).r  r[   r   r   r   rZ     r  zExactPosition._flipNr  )	r   r   r   r   r  rS   rM   r   rZ   r   r   r   r   r   m  s    
"r   c                   @   r   )r  zSpecify a specific position which is uncertain.

    This is used in UniProt, e.g. ?222 for uncertain position 222, or in the
    XML format explicitly marked as uncertain. Does not apply to GenBank/EMBL.
    Nr   r   r   r   r   r    r   r  c                   @   r}   )r  zSpecify a specific position which is unknown (has no position).

    This is used in UniProt, e.g. ? or in the XML as unknown.
    c                 C   r   )z?Represent the UnknownPosition object as a string for debugging.z()r   r/   r   r   r   rM        zUnknownPosition.__repr__c                 C   s   t dS )z4Return the hash value of the UnknownPosition object.N)hashr/   r   r   r   __hash__  s   zUnknownPosition.__hash__c                 C      | S r  r   rX   r   r   r   r        zUnknownPosition.__add__c                 C   r%  r   r   r[   r   r   r   rZ     r&  zUnknownPosition._flipN)r   r   r   r   rM   r$  r   rZ   r   r   r   r   r    s    r  c                   @   @   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )r  aM  Specify the position of a boundary within some coordinates.

    Arguments:
    - position - The default integer position
    - left - The start (left) position of the boundary
    - right - The end (right) position of the boundary

    This allows dealing with a location like ((11.14)..100). This
    indicates that the start of the sequence is somewhere between 11
    and 14. Since this is a start coordinate, it should act like
    it is at position 11 (or in Python counting, 10).

    >>> p = WithinPosition(10, 10, 13)
    >>> p
    WithinPosition(10, left=10, right=13)
    >>> print(p)
    (10.13)
    >>> int(p)
    10

    Basic integer comparisons and operations should work as though
    this were a plain integer:

    >>> p == 10
    True
    >>> p in [9, 10, 11]
    True
    >>> p < 11
    True
    >>> p + 10
    WithinPosition(20, left=20, right=23)

    >>> isinstance(p, WithinPosition)
    True
    >>> isinstance(p, Position)
    True
    >>> isinstance(p, int)
    True

    Note this also applies for comparison to other position objects,
    where again the integer behavior is used:

    >>> p == 10
    True
    >>> p == ExactPosition(10)
    True
    >>> p == BeforePosition(10)
    True
    >>> p == AfterPosition(10)
    True

    If this were an end point, you would want the position to be 13
    (the right/larger value, not the left/smaller value as above):

    >>> p2 = WithinPosition(13, 10, 13)
    >>> p2
    WithinPosition(13, left=10, right=13)
    >>> print(p2)
    (10.13)
    >>> int(p2)
    13
    >>> p2 == 13
    True
    >>> p2 == ExactPosition(13)
    True

    c                 C   s>   ||ks||kst d|||f t| |}||_||_|S )zCreate a WithinPosition object.z3WithinPosition: %r should match left %r or right %r)RuntimeErrorrk   r  _left_rightr  r  r   r   objr   r   r   r    s   zWithinPosition.__new__c                 C      t | | j| jfS zzReturn the arguments accepted by __new__.

        Necessary to allow pickling and unpickling of class instances.
        rk   r)  r*  r/   r   r   r   __getnewargs__     zWithinPosition.__getnewargs__c                 C      d| j jt| | j| jf S )z>Represent the WithinPosition object as a string for debugging.%s(%i, left=%i, right=%i)rJ   r   rk   r)  r*  r/   r   r   r   rM   !     zWithinPosition.__repr__c                 C      d| j  d| j dS )zLReturn a representation of the WithinPosition object (with python counting).r
   .r	   r)  r*  r/   r   r   r   rS   *     zWithinPosition.__str__c                 C   "   |  t| | | j| | j| S )z?Return a copy of the position object with its location shifted.rJ   rk   r)  r*  rX   r   r   r   r   .     zWithinPosition.__add__c                 C   "   |  |t|  || j || j S r   rJ   rk   r*  r)  r[   r   r   r   rZ   4  r<  zWithinPosition._flipN
r   r   r   r   r  r0  rM   rS   r   rZ   r   r   r   r   r    s    D	r  c                   @   r'  )BetweenPositiona  Specify the position of a boundary between two coordinates (OBSOLETE?).

    Arguments:
     - position - The default integer position
     - left - The start (left) position of the boundary
     - right - The end (right) position of the boundary

    This allows dealing with a position like 123^456. This
    indicates that the start of the sequence is somewhere between
    123 and 456. It is up to the parser to set the position argument
    to either boundary point (depending on if this is being used as
    a start or end of the feature). For example as a feature end:

    >>> p = BetweenPosition(456, 123, 456)
    >>> p
    BetweenPosition(456, left=123, right=456)
    >>> print(p)
    (123^456)
    >>> int(p)
    456

    Integer equality and comparison use the given position,

    >>> p == 456
    True
    >>> p in [455, 456, 457]
    True
    >>> p > 300
    True

    The old legacy properties of position and extension give the
    starting/lower/left position as an integer, and the distance
    to the ending/higher/right position as an integer. Note that
    the position object will act like either the left or the right
    end-point depending on how it was created:

    >>> p2 = BetweenPosition(123, left=123, right=456)
    >>> int(p) == int(p2)
    False
    >>> p == 456
    True
    >>> p2 == 123
    True

    Note this potentially surprising behavior:

    >>> BetweenPosition(123, left=123, right=456) == ExactPosition(123)
    True
    >>> BetweenPosition(123, left=123, right=456) == BeforePosition(123)
    True
    >>> BetweenPosition(123, left=123, right=456) == AfterPosition(123)
    True

    i.e. For equality (and sorting) the position objects behave like
    integers.

    c                 C   s0   ||ks
||ks
J t | |}||_||_|S )z0Create a new instance in BetweenPosition object.)rk   r  r)  r*  r+  r   r   r   r  v  s
   zBetweenPosition.__new__c                 C   r-  r.  r/  r/   r   r   r   r0    r1  zBetweenPosition.__getnewargs__c                 C   r2  )z?Represent the BetweenPosition object as a string for debugging.r3  r4  r/   r   r   r   rM     r5  zBetweenPosition.__repr__c                 C   r6  )zMReturn a representation of the BetweenPosition object (with python counting).r
   r   r	   r8  r/   r   r   r   rS     r9  zBetweenPosition.__str__c                 C   r:  r  r;  rX   r   r   r   r     r<  zBetweenPosition.__add__c                 C   r=  r   r>  r[   r   r   r   rZ     r<  zBetweenPosition._flipNr?  r   r   r   r   r@  ;  s    :		r@  c                   @   r  )r  aH  Specify a position where the actual location occurs before it.

    Arguments:
     - position - The upper boundary of where the location can occur.
     - extension - An optional argument which must be zero since we don't
       have an extension. The argument is provided so that the same number
       of arguments can be passed to all position types.

    This is used to specify positions like (<10..100) where the location
    occurs somewhere before position 10.

    >>> p = BeforePosition(5)
    >>> p
    BeforePosition(5)
    >>> print(p)
    <5
    >>> int(p)
    5
    >>> p + 10
    BeforePosition(15)

    Note this potentially surprising behavior:

    >>> p == ExactPosition(5)
    True
    >>> p == AfterPosition(5)
    True

    Just remember that for equality and sorting the position objects act
    like integers.
    r   c                 C   r  )z/Create a new instance in BeforePosition object.r   r  r  r  r  r   r   r   r    r  zBeforePosition.__new__c                 C   r  z1Represent the location as a string for debugging.r  r  r/   r   r   r   rM     r   zBeforePosition.__repr__c                 C      dt |  S )zLReturn a representation of the BeforePosition object (with python counting).r   r   r/   r   r   r   rS     r"  zBeforePosition.__str__c                 C   r  r  r  rX   r   r   r   r        zBeforePosition.__add__c                 C      t |t|  S r   )r  rk   r[   r   r   r   rZ        zBeforePosition._flipNr  	r   r   r   r   r  rM   rS   r   rZ   r   r   r   r   r    s    
!r  c                   @   r  )r  a  Specify a position where the actual location is found after it.

    Arguments:
     - position - The lower boundary of where the location can occur.
     - extension - An optional argument which must be zero since we don't
       have an extension. The argument is provided so that the same number
       of arguments can be passed to all position types.

    This is used to specify positions like (>10..100) where the location
    occurs somewhere after position 10.

    >>> p = AfterPosition(7)
    >>> p
    AfterPosition(7)
    >>> print(p)
    >7
    >>> int(p)
    7
    >>> p + 10
    AfterPosition(17)

    >>> isinstance(p, AfterPosition)
    True
    >>> isinstance(p, Position)
    True
    >>> isinstance(p, int)
    True

    Note this potentially surprising behavior:

    >>> p == ExactPosition(7)
    True
    >>> p == BeforePosition(7)
    True

    Just remember that for equality and sorting the position objects act
    like integers.
    r   c                 C   r  )z2Create a new instance of the AfterPosition object.r   r  r  r  r  r   r   r   r  	  r  zAfterPosition.__new__c                 C   r  rA  r  r/   r   r   r   rM   	  r   zAfterPosition.__repr__c                 C   rB  )zKReturn a representation of the AfterPosition object (with python counting).r   r   r/   r   r   r   rS   	  r"  zAfterPosition.__str__c                 C   r  r  r  rX   r   r   r   r   	  rC  zAfterPosition.__add__c                 C   rD  r   )r  rk   r[   r   r   r   rZ   	  rE  zAfterPosition._flipNr  rF  r   r   r   r   r    s    
(r  c                   @   r'  )r	  a@  Specify a position where the location can be multiple positions.

    This models the GenBank 'one-of(1888,1901)' function, and tries
    to make this fit within the Biopython Position models. If this was
    a start position it should act like 1888, but as an end position 1901.

    >>> p = OneOfPosition(1888, [ExactPosition(1888), ExactPosition(1901)])
    >>> p
    OneOfPosition(1888, choices=[ExactPosition(1888), ExactPosition(1901)])
    >>> int(p)
    1888

    Integer comparisons and operators act like using int(p),

    >>> p == 1888
    True
    >>> p <= 1888
    True
    >>> p > 1888
    False
    >>> p + 100
    OneOfPosition(1988, choices=[ExactPosition(1988), ExactPosition(2001)])

    >>> isinstance(p, OneOfPosition)
    True
    >>> isinstance(p, Position)
    True
    >>> isinstance(p, int)
    True

    c                 C   s2   ||vrt d|d|t| |}||_|S )zInitialize with a set of possible positions.

        choices is a list of Position derived objects, specifying possible
        locations.

        position is an integer specifying the default behavior.
        zOneOfPosition: z should match one of )r4   rk   r  position_choices)r  r  r   r,  r   r   r   r  :	  s   zOneOfPosition.__new__c                 C   s   t | | jfS r.  )rk   rG  r/   r   r   r   r0  J	  s   zOneOfPosition.__getnewargs__c                 C   s   d| j jt| | jf S )z=Represent the OneOfPosition object as a string for debugging.z%s(%i, choices=%r))rJ   r   rk   rG  r/   r   r   r   rM   Q	  s
   zOneOfPosition.__repr__c                 C   s.   d}| j D ]	}|| d7 }q|dd d S )zKReturn a representation of the OneOfPosition object (with python counting).zone-of(r   Nr   r	   )rG  )r'   rQ   r  r   r   r   rS   Y	  s   
zOneOfPosition.__str__c                    s$   |  t|    fdd| jD S )r  c                    s   g | ]}|  qS r   r   r   pr   r   r   r   d	  s    z)OneOfPosition.__add__.<locals>.<listcomp>rJ   rk   rG  rX   r   r   r   r   a	  s   zOneOfPosition.__add__c                    s.   |   t|   fdd| jddd D S )r!  c                    r   r   r   rH  r   r   r   r   j	  r   z'OneOfPosition._flip.<locals>.<listcomp>Nr   rJ  r[   r   r   r   rZ   g	  s   &zOneOfPosition._flipNr?  r   r   r   r   r	  	  s     r	  __main__)run_doctest)4r   r   rer,   abcr   r   Bior   r   Bio.Seqr   r   r   
_reference_oneof_position_oneof_location_any_locationcompiler   r   _pair_location_between_location_within_position_within_locationr  r   r  _solo_location
_solo_bondr   r4   r   r   r~   r   r   FeatureLocationr    r   rk   r   r  r  r  r@  r  r  r	  r   
Bio._utilsrL  r   r   r   r   <module>   s   
5





   ZE     0   g=re9@
U
