U
    _m7                     @   s   d dl m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 eedd	d
ddddddg	ZG dd deZdddZdS )    )FastaN)	constants)helpers)parser)bins)
dict_classseqidsourcefeaturetypestartendscorestrandframe
attributesc                   @   s   e Zd Zd%ddZd&ddZdd	 Zd
d Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zedd Zejdd Zedd Zejdd Zd'd d!Zd(d#d$ZdS ))Feature.NFc                 C   sX  |dks|dkrd}n|dk	r&t |}|dks6|dkr<d}n|dk	rLt |}|	pTt }	t|	tjrztj|	dd}	W n, tjk
r   t	
|	\}	}|p|}Y nX |
pg }
t|
tjrzt|
}
W n  tjk
r   |
d}
Y nX || _|| _|| _|| _|| _|| _|| _|| _|	| _|
| _| || _|| _|p>tj| _|| _|| _|| _dS )ad  
        Represents a feature from the database.

        Usually you won't want to use this directly, since it has various
        implementation details needed for operating in the context of FeatureDB
        objects.  Instead, try the :func:`gffutils.feature.feature_from_line`
        function.

        When printed, reproduces the original line from the file as faithfully
        as possible using `dialect`.


        Parameters
        ----------

        seqid : string
            Name of the sequence (often chromosome)

        source : string
            Source of the feature; typically the originating database or
            program that predicted the feature

        featuretype : string
            Type of feature.  For example "gene", "exon", "TSS", etc

        start, end : int or "."
            1-based coordinates; start must be <= end.  If "." (the default
            placeholder for GFF files), then the corresponding attribute will
            be None.

        score : string
            Stored as a string.

        strand : "+" | "-" | "."
            Strand of the feature; "." when strand is not relevant.

        frame : "0" | "1" | "2"
            Coding frame.  0 means in-frame; 1 means there is one extra base at
            the beginning, so the first codon starts at the second base;
            2 means two extra bases at the beginning.  Interpretation is strand
            specific; "beginning" for a minus-strand feature is at the end
            coordinate.

        attributes : string or dict
            If a string, first assume it is serialized JSON; if this fails then
            assume it's the original key/vals string.  If it's a dictionary
            already, then use as-is.

            The end result is that this instance's `attributes` attribute will
            always be a dictionary.

            Upon printing, the attributes will be reconstructed based on this
            dictionary and the dialect -- except if the original attributes
            string was provided, in which case that will be used directly.

            Notes on encoding/decoding: the only time unquoting
            (e.g., "%2C" becomes ",") happens is if `attributes` is a string
            and if `settings.ignore_url_escape_characters = False`. If dict or
            JSON, the contents are used as-is.

            Similarly, the only time characters are quoted ("," becomes "%2C")
            is when the feature is printed (`__str__` method).

        extra : string or list
            Additional fields after the canonical 9 fields for GFF/GTF.

            If a string, then first assume it's serialized JSON; if this fails
            then assume it's a tab-delimited string of additional fields.  If
            it's a list already, then use as-is.

        bin : int
            UCSC genomic bin. If None, will be created based on provided
            start/end; if start or end is "." then bin will be None.

        id : None or string
            Database-specific primary key for this feature.  The only time this
            should not be None is if this feature is coming from a database, in
            which case it will be filled in automatically.

        dialect : dict or None

            The dialect to use when reconstructing attribute strings; defaults
            to the GFF3 spec.  :class:`FeatureDB` objects will automatically
            attach the dialect from the original file.

        file_order : int
            This is the `rowid` special field used in a sqlite3 database; this
            is provided by FeatureDB.

        keep_order : bool
            If True, then the attributes in the printed string will be in the
            order specified in the dialect.  Disabled by default, since this
            sorting step is time-consuming over many features.

        sort_attribute_values : bool
            If True, then the values of each attribute will be sorted when the
            feature is printed.  Mostly useful for testing, where the order is
            important for checking against expected values. Disabled by
            default, since it can be time-consuming over many features.

        r    NT)Zisattributes	)intr   
isinstancesixstring_typesr   Z
_unjsonifyjsonZJSONDecodeErrorr   _split_keyvalssplitr   r	   r
   r   r   r   r   r   r   extracalc_binbinidr   dialect
file_order
keep_ordersort_attribute_values)selfr   r	   r
   r   r   r   r   r   r   r   r   r   r    r!   r"   r#   _dialect r&   /lib/python3.8/site-packages/gffutils/feature.py__init__   sJ    l	
zFeature.__init__c                 C   s>   |dkr:zt j | j| jdd}W n tk
r8   d}Y nX |S )zY
        Calculate the smallest UCSC genomic bin that will contain this feature.
        NT)Zone)r   r   r   	TypeError)r$   Z_binr&   r&   r'   r      s    
zFeature.calc_binc                 C   sJ   t t| }| jd krd}n| j}| jd kr2d}n| j}dj| |||dS )Nr   zH<Feature {x.featuretype} ({x.seqid}:{start}-{end}[{x.strand}]) at {loc}>)xr   r   loc)hexr   r   r   format)r$   Z
memory_locr   r   r&   r&   r'   __repr__   s    

  zFeature.__repr__c                 C   s*   t |trt| }t| |S | j| S d S N)r   r   _position_lookupgetattrr   )r$   keyattrr&   r&   r'   __getitem__   s    

zFeature.__getitem__c                 C   s.   t |tr t| }t| || n
|| j|< d S r/   )r   r   r0   setattrr   )r$   r2   valuer3   r&   r&   r'   __setitem__   s    
zFeature.__setitem__c                 C   s    t jr|  S t| dS d S )Nzutf-8)r   ZPY3__unicode__Zunicodeencoder$   r&   r&   r'   __str__   s    zFeature.__str__c                    s    fddt jd d D }|d d kr2d|d< nt|d |d< |d d krXd|d< nt|d |d< tj j j j jd}|	|  j
r|	d j
 d|S )	Nc                    s   g | ]}t  |qS r&   )r1   ).0kr:   r&   r'   
<listcomp>   s     z'Feature.__unicode__.<locals>.<listcomp>   r      )r"   r#   r   )r   _gffkeysstrr   Z_reconstructr   r    r"   r#   appendr   join)r$   itemsZreconstructed_attributesr&   r:   r'   r8      s"    

  
zFeature.__unicode__c                 C   s   t t| S r/   )hashrC   r:   r&   r&   r'   __hash__  s    zFeature.__hash__c                 C   s   t | t |kS r/   rC   r$   otherr&   r&   r'   __eq__
  s    zFeature.__eq__c                 C   s   t | t |kS r/   rI   rJ   r&   r&   r'   __ne__  s    zFeature.__ne__c                 C   s   | j | j d S )N   )stopr   r:   r&   r&   r'   __len__  s    zFeature.__len__c                 C   s   | j S r/   r   r:   r&   r&   r'   chrom  s    zFeature.chromc                 C   s
   || _ d S r/   rQ   r$   r6   r&   r&   r'   rR     s    c                 C   s   | j S r/   r   r:   r&   r&   r'   rO     s    zFeature.stopc                 C   s
   || _ d S r/   rT   rS   r&   r&   r'   rO   !  s    c                 C   s   |sF| j | j| j| j| j| j| j| j| jt	
| jt	
| j|  fS | j || j|| j|| j|| j| j| j|| j|| j|t	
| j|t	
| j||  fS )a  
        Return a tuple suitable for import into a database.

        Attributes field and extra field jsonified into strings. The order of
        fields is such that they can be supplied as arguments for the query
        defined in :attr:`gffutils.constants._INSERT`.

        If `encoding` is not None, then convert string fields to unicode using
        the provided encoding.

        Returns
        -------
        Tuple
        )r   r   r	   r
   r   r   r   r   r   r   Z_jsonifyr   r   r   decode)r$   encodingr&   r&   r'   astuple%  s6           

 
 

 
  

 
 zFeature.astupleTc                 C   sN   t |tjrt|dd}|| j | jd | j }|rH| jdkrH|jj	}|j
S )a  
        Retrieves the sequence of this feature as a string.

        Uses the pyfaidx package.

        Parameters
        ----------

        fasta : str
            If str, then it's a FASTA-format filename; otherwise assume it's
            a pyfaidx.Fasta object.

        use_strand : bool
            If True (default), the sequence returned will be
            reverse-complemented for minus-strand features.

        Returns
        -------
        string
        F)Zas_rawrN   -)r   r   r   r   rR   r   rO   r   reverseZ
complementseq)r$   ZfastaZ
use_strandrZ   r&   r&   r'   sequenceD  s    zFeature.sequence)r   r   r   r   r   r   r   r   NNNNNNFF)N)N)T)__name__
__module____qualname__r(   r   r.   r4   r7   r;   r8   rH   rL   rM   rP   propertyrR   setterrO   rW   r[   r&   r&   r&   r'   r      sH                          
 &
	




r   TFc                 C   s   |s|  d}g }|D ]"}| }t|dkr|| qt|dksNt||d } d| krp| dd}q| ddd}n| dd}z|d }W n tk
r   d}Y nX tj	||d	\}	}
t
tttj|}|	|d
< |dd |d< ||d< |dkr|
}tf d|i|S )aq  
    Given a line from a GFF file, return a Feature object

    Parameters
    ----------
    line : string

    strict : bool
        If True (default), assume `line` is a single, tab-delimited string that
        has at least 9 fields.

        If False, then the input can have a more flexible format, useful for
        creating single ad hoc features or for writing tests.  In this case,
        `line` can be a multi-line string (as long as it has a single non-empty
        line), and, as long as there are only 9 fields (standard GFF/GTF), then
        it's OK to use spaces instead of tabs to separate fields in `line`.
        But if >9 fields are to be used, then tabs must be used.

    keep_order, dialect
        Passed directly to :class:`Feature`; see docstring for that class for
        description

    Returns
    -------
    A new :class:`Feature` object.
    Fr   rN   r   z
N   r   )r    r   	   r   r"   r    )
splitlinesstriplenrD   AssertionErrorrstripr   
IndexErrorr   r   dictlistzipr   rB   r   )liner    strictr"   linesZ_linesiZfieldsZattr_stringZattrsr%   dr&   r&   r'   feature_from_lined  s2    


rq   )NTF)Zpyfaidxr   r   Z
simplejsonr   Zgffutilsr   r   r   r   Zgffutils.attributesr   ri   	enumerater0   objectr   rq   r&   r&   r&   r'   <module>   s$        V