o
    Rŀg7                     @   sD  d 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
dlmZ d
dlmZ dZde ZdZdZde Zde ZG dd dZG dd deZe ZG dd dZG dd dZG dd dZG dd deZG dd deZdd  Z d!d" Z!e"d#krdd$l#m$Z$ e$  dS dS )%a  Code to work with GenBank formatted files.

Rather than using Bio.GenBank, you are now encouraged to use Bio.SeqIO with
the "genbank" or "embl" format names to parse GenBank or EMBL files into
SeqRecord and SeqFeature objects (see the Biopython tutorial for details).

Using Bio.GenBank directly to parse GenBank files is only useful if you want
to obtain GenBank-specific Record objects, which is a much closer
representation to the raw file contents than the SeqRecord alternative from
the FeatureParser (used in Bio.SeqIO).

To use the Bio.GenBank parser, there are two helper functions:

    - read                  Parse a handle containing a single GenBank record
      as Bio.GenBank specific Record objects.
    - parse                 Iterate over a handle containing multiple GenBank
      records as Bio.GenBank specific Record objects.

The following internal classes are not intended for direct use and may
be deprecated in a future release.

Classes:
 - Iterator              Iterate through a file of GenBank entries
 - FeatureParser         Parse GenBank data in SeqRecord and SeqFeature objects.
 - RecordParser          Parse GenBank data into a Record object.

Exceptions:
 - ParserFailureError    Exception indicating a failure in the parser (ie.
   scanner or consumer)

    N)BiopythonParserWarning)Seq)Location)LocationParserError)	Reference)
SeqFeature)SimpleLocation   )GenBankScanner)FeatureValueCleaner          c                   @   s*   e Zd ZdZd	ddZdd Zdd ZdS )
Iteratora<  Iterator interface to move over a file of GenBank entries one at a time (OBSOLETE).

    This class is likely to be deprecated in a future release of Biopython.
    Please use Bio.SeqIO.parse(..., format="gb") or Bio.GenBank.parse(...)
    for SeqRecord and GenBank specific Record objects respectively instead.
    Nc                 C   s   || _ || _dS )a  Initialize the iterator.

        Arguments:
         - handle - A handle with GenBank entries to iterate through.
         - parser - An optional parser to pass the entries through before
           returning them. If None, then the raw entry will be returned.

        N)handle_parser)selfr   parser r   H/var/www/html/myenv/lib/python3.10/site-packages/Bio/GenBank/__init__.py__init__I   s   	
zIterator.__init__c                 C   sl   | j du r#g }	 | j }|sdS || | dkrnqd|S z| j | jW S  ty5   Y dS w )zlReturn the next GenBank record from the handle.

        Will return None if we ran out of records.
        NTz// )r   r   readlineappendrstripjoinparseStopIteration)r   linesliner   r   r   __next__U   s    



zIterator.__next__c                 C   s   t | jdS )zIterate over the records.N)iterr!   r   r   r   r   __iter__i      zIterator.__iter__N)__name__
__module____qualname____doc__r   r!   r$   r   r   r   r   r   A   s
    
r   c                   @   s   e Zd ZdZdS )ParserFailureErrorz5Failure caused by some kind of problem in the parser.N)r'   r(   r)   r*   r   r   r   r   r+   n   s    r+   c                   @   s"   e Zd ZdZd	ddZdd ZdS )
FeatureParserzParse GenBank files into Seq + Feature objects (OBSOLETE).

    Direct use of this class is discouraged, and may be deprecated in
    a future release of Biopython.

    Please use Bio.SeqIO.parse(...) or Bio.SeqIO.read(...) instead.
    r   r	   Nc                 C   s(   t || _|| _|r|| _dS t| _dS )a  Initialize a GenBank parser and Feature consumer.

        Arguments:
         - debug_level - An optional argument that species the amount of
           debugging information the parser should spit out. By default we have
           no debugging info (the fastest way to do things), but if you want
           you can set this as high as two and see exactly where a parse fails.
         - use_fuzziness - Specify whether or not to use fuzzy representations.
           The default is 1 (use fuzziness).
         - feature_cleaner - A class which will be used to clean out the
           values of features. This class must implement the function
           clean_value. GenBank.utils has a "standard" cleaner class, which
           is used by default.

        N)r
   _scanneruse_fuzziness_cleaner)r   debug_levelr.   feature_cleanerr   r   r   r   ~   s
   


zFeatureParser.__init__c                 C   s"   t | j| j}| j|| |jS )zParse the specified handle.)_FeatureConsumerr.   r/   r-   feeddatar   r   	_consumerr   r   r   r      s   zFeatureParser.parse)r   r	   Nr'   r(   r)   r*   r   r   r   r   r   r   r,   u   s    
r,   c                   @   s"   e Zd ZdZdddZdd ZdS )	RecordParserzParse GenBank files into Record objects (OBSOLETE).

    Direct use of this class is discouraged, and may be deprecated in
    a future release of Biopython.

    Please use the Bio.GenBank.parse(...) or Bio.GenBank.read(...) functions
    instead.
    r   c                 C      t || _dS )aj  Initialize the parser.

        Arguments:
         - debug_level - An optional argument that species the amount of
           debugging information the parser should spit out. By default we have
           no debugging info (the fastest way to do things), but if you want
           you can set this as high as two and see exactly where a parse fails.

        N)r
   r-   )r   r0   r   r   r   r         
zRecordParser.__init__c                 C   s   t  }| j|| |jS )z1Parse the specified handle into a GenBank record.)_RecordConsumerr-   r3   r4   r5   r   r   r   r      s   zRecordParser.parseN)r   r7   r   r   r   r   r8      s    
	r8   c                   @   s~   e Zd ZdZdgZdd Zedd Zedd Zed	d
 Z	edd Z
edd Zedd Zedd Zedd ZdS )_BaseGenBankConsumerzAbstract GenBank consumer providing useful general functions (PRIVATE).

    This just helps to eliminate some duplication in things that most
    GenBank consumers want to do.
    translationc                 C      d S r&   r   r#   r   r   r   r         z_BaseGenBankConsumer.__init__c                 C   sL   | dks| dkrd}n| d dkr| dd }n| }| d}dd |D S )z<Split a string of keywords into a nice clean list (PRIVATE).r   .N;c                 S      g | ]}|  qS r   strip.0xr   r   r   
<listcomp>       z8_BaseGenBankConsumer._split_keywords.<locals>.<listcomp>)split)keyword_stringkeywordskeyword_listr   r   r   _split_keywords   s   
z$_BaseGenBankConsumer._split_keywordsc                 C   s&   |  dd dd}dd | D S )z:Split a string of accession numbers into a list (PRIVATE).
r   rB   c                 S   s   g | ]
}|  r|  qS r   rD   rF   r   r   r   rI      s    z:_BaseGenBankConsumer._split_accessions.<locals>.<listcomp>)replacerK   )accession_string	accessionr   r   r   _split_accessions   s   z&_BaseGenBankConsumer._split_accessionsc                 C   s   | r| dkrg S | d dkr| dd }n| }| d}g }|D ]}| d}|| q d|v r:|d d|v s1dd |D S )	z8Split a string with taxonomy info into a list (PRIVATE).r@   rA   NrB   rP   r   c                 S   rC   r   rD   rF   r   r   r   rI      rJ   z8_BaseGenBankConsumer._split_taxonomy.<locals>.<listcomp>)rK   extendremove)taxonomy_stringtax_infotax_listnew_tax_listtax_item	new_itemsr   r   r   _split_taxonomy   s   


z$_BaseGenBankConsumer._split_taxonomyc                 C   s   d |  S )zClean whitespace out of a location string (PRIVATE).

        The location parser isn't a fan of whitespace, so we clean it out
        before feeding it into the parser.
        r   r   rK   )location_stringr   r   r   _clean_location   r:   z$_BaseGenBankConsumer._clean_locationc                 C   s"   ddg}|D ]}|  |d} q| S )zKRemove any newlines in the passed text, returning the new string (PRIVATE).rP   r   rQ   )textnewlineswsr   r   r   _remove_newlines   s   z%_BaseGenBankConsumer._remove_newlinesc                 C   s   d dd | dD S )zHReplace multiple spaces in the passed text with single spaces (PRIVATE).r   c                 s       | ]}|r|V  qd S r&   r   rF   r   r   r   	<genexpr>      z9_BaseGenBankConsumer._normalize_spaces.<locals>.<genexpr>r^   rc   r   r   r   _normalize_spaces
  s   z&_BaseGenBankConsumer._normalize_spacesc                 C   s   |  ddS )z1Remove all spaces from the passed text (PRIVATE).r   r   rb   rj   r   r   r   _remove_spaces  s   z#_BaseGenBankConsumer._remove_spacesc                 C   s   | d }|}||fS )a  Convert a start and end range to python notation (PRIVATE).

        In GenBank, starts and ends are defined in "biological" coordinates,
        where 1 is the first base and [i, j] means to include both i and j.

        In python, 0 is the first base and [i, j] means to include i, but
        not j.

        So, to convert "biological" to python coordinates, we need to
        subtract 1 from the start, and leave the end and things should
        be converted happily.
        r	   r   )startend	new_startnew_endr   r   r   _convert_to_python_numbers  s   z/_BaseGenBankConsumer._convert_to_python_numbersN)r'   r(   r)   r*   remove_space_keysr   staticmethodrO   rT   r]   r`   rf   rk   rl   rq   r   r   r   r   r<      s(    





	

r<   c                   @   s  e Zd ZdZdkddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zd3d4 Zd5d6 Zd7d8 Zd9d: Zd;d< Z d=d> Z!d?d@ Z"dAdB Z#dCdD Z$dEdF Z%dGdH Z&dIdJ Z'dKdL Z(dMdN Z)dOdP Z*dQdR Z+dSdT Z,dUdV Z-dWdX Z.dYdZ Z/d[d\ Z0d]d^ Z1d_d` Z2dadb Z3dcdd Z4dedf Z5dgdh Z6didj Z7dS )lr2   a&  Create a SeqRecord object with Features to return (PRIVATE).

    Attributes:
     - use_fuzziness - specify whether or not to parse with fuzziness in
       feature locations.
     - feature_cleaner - a class that will be used to provide specialized
       cleaning-up of feature values.

    Nc                 C   sb   ddl m} t|  |d d d| _d | j_d| j_|| _|| _d| _	g | _
d | _d | _d | _d S )Nr   )	SeqRecord)idr   )Bio.SeqRecordrt   r<   r   r4   ru   description_use_fuzziness_feature_cleaner	_seq_type	_seq_data_cur_reference_cur_feature_expected_size)r   r.   r1   rt   r   r   r   r   4  s   

z_FeatureConsumer.__init__c                 C   s   || j _dS )z6Set the locus name is set as the name of the Sequence.N)r4   name)r   
locus_namer   r   r   locusE  r%   z_FeatureConsumer.locusc                 C   r9   )zRecord the sequence length.N)intr~   r   contentr   r   r   sizeI  s   z_FeatureConsumer.sizec                 C   s   |  | _dS )zRecord the sequence type (SEMI-OBSOLETE).

        This reflects the fact that the topology (linear/circular) and
        molecule type (e.g. DNA vs RNA) were a single field in early
        files. Current GenBank/EMBL files have two fields.
        N)rE   rz   )r   typer   r   r   residue_typeM  s   z_FeatureConsumer.residue_typec                 C   s0   |r|dvrt d|d|| jjd< dS dS )yValidate and record sequence topology.

        The topology argument should be "linear" or "circular" (string).
        linearcircularUnexpected topology  should be linear or circulartopologyN)r+   r4   annotationsr   r   r   r   r   r   V  s   
z_FeatureConsumer.topologyc                 C   sn   |r5d|v s
d|v rt d|d|dd  dv r-|dd  s-td| t || jjd	< dS dS )
;Validate and record the molecule type (for round-trip etc).r   r   Molecule type  should not include topologyNDNARNA,Non-upper case molecule type in LOCUS line: molecule_type)r+   upperisupperwarningswarnr   r4   r   r   mol_typer   r   r   r   b  s   
$	z_FeatureConsumer.molecule_typec                 C      || j jd< d S )Ndata_file_divisionr4   r   )r   divisionr   r   r   r   w     z#_FeatureConsumer.data_file_divisionc                 C   r   )Ndater   )r   submit_dater   r   r   r   z  r   z_FeatureConsumer.datec                 C   ,   | j jr| j  jd| 7  _dS || j _dS )z6Set the definition as the description of the sequence.r   N)r4   rw   )r   
definitionr   r   r   r   }  s   z_FeatureConsumer.definitionc                 C   s   |  |}z|D ]}|| jjd vr| jjd | qW n ty,   || jjd< Y nw | jjsCt|dkrE| jjd d | j_dS dS dS )zSet the accession number as the id of the sequence.

        If we have multiple accession numbers, the first one passed is
        used.
        
accessionsr   N)rT   r4   r   r   KeyErrorru   len)r   acc_numnew_acc_numsaccr   r   r   rS     s   
z_FeatureConsumer.accessionc                 C      | d| jjd< d S )N-tlsrK   r4   r   r   r   r   r   r        z_FeatureConsumer.tlsc                 C   r   )Nr   tsar   r   r   r   r   r     r   z_FeatureConsumer.tsac                 C   r   )Nr   wgsr   r   r   r   r   r     r   z_FeatureConsumer.wgsc                 C   s    | j jdg |d d S )N
wgs_scafldr   )r4   r   
setdefaultr   rK   r   r   r   r   add_wgs_scafld      z_FeatureConsumer.add_wgs_scafldc                 C   r   )Nnidr   r   r   r   r   r     r   z_FeatureConsumer.nidc                 C   r   )Npidr   r   r   r   r   r     r   z_FeatureConsumer.pidc                 C   s`   | ddkr&|dd  r&| |dd  | |dd  d S |r.|| j_d S d S )Nr@   r	   r   )countrK   isdigitrS   version_suffixr4   ru   )r   
version_idr   r   r   version  s    z_FeatureConsumer.versionc                 C   s,   | dd}| jjdd | D  dS )a  Handle the information from the PROJECT line as a list of projects.

        e.g.::

            PROJECT     GenomeProject:28471

        or::

            PROJECT     GenomeProject:13543  GenomeProject:99999

        This is stored as dbxrefs in the SeqRecord to be consistent with the
        projected switch of this line to DBLINK in future GenBank versions.
        Note the NCBI plan to replace "GenomeProject:28471" with the shorter
        "Project:28471" as part of this transition.
        zGenomeProject:zProject:c                 s   rg   r&   r   rG   pr   r   r   rh     ri   z+_FeatureConsumer.project.<locals>.<genexpr>N)rQ   r4   dbxrefsrU   rK   r   r   r   r   project  s    z_FeatureConsumer.projectc                 C   sF   d|v r| dd}d|v s| | jjvr!| jj|  dS dS )a  Store DBLINK cross references as dbxrefs in our record object.

        This line type is expected to replace the PROJECT line in 2009. e.g.

        During transition::

            PROJECT     GenomeProject:28471
            DBLINK      Project:28471
                        Trace Assembly Archive:123456

        Once the project line is dropped::

            DBLINK      Project:28471
                        Trace Assembly Archive:123456

        Note GenomeProject -> Project.

        We'll have to see some real examples to be sure, but based on the
        above example we can expect one reference per line.

        Note that at some point the NCBI have included an extra space, e.g.::

            DBLINK      Project: 28471

        z: :N)rQ   rE   r4   r   r   r   r   r   r   dblink  s   z_FeatureConsumer.dblinkc                 C   s    |  sJ t|| jjd< dS )zSet the version to overwrite the id.

        Since the version provides the same information as the accession
        number, plus some extra info, we set this as the id if we have
        a version.
        sequence_versionN)r   r   r4   r   )r   r   r   r   r   r     s   z_FeatureConsumer.version_suffixc                 C   s   |  | jjd< d S )N	db_source)r   r4   r   r   r   r   r   r     s   z_FeatureConsumer.db_sourcec                 C   r   )Ngir   r   r   r   r   r   	  r   z_FeatureConsumer.gic                 C   s>   d| j jv r| j jd | | d S | || j jd< d S )NrM   )r4   r   rU   rO   r   r   r   r   rM     s   z_FeatureConsumer.keywordsc                 C   r   )Nsegmentr   r   r   r   r   r     r   z_FeatureConsumer.segmentc                 C   s<   |dkrd}n|d dkr|d d }n|}|| j jd< d S )Nr   rA   r@   sourcer   )r   r   source_infor   r   r   r     s   z_FeatureConsumer.sourcec                 C   r   )Norganismr   r   r   r   r   r   "  r   z_FeatureConsumer.organismc                 C   sD   |  |}z| jjd | W dS  ty!   || jjd< Y dS w )z.Record (another line of) the taxonomy lineage.taxonomyN)r]   r4   r   rU   r   )r   r   lineager   r   r   r   %  s   
z_FeatureConsumer.taxonomyc                 C   s8   | j dur| jjd | j  ng | jjd< t | _ dS )z/Signal the beginning of a new reference object.N
references)r|   r4   r   r   r   r   r   r   r   reference_num-  s   
z_FeatureConsumer.reference_numc                 C   s   | ds	J ||dd }g }d|v r*d|v r*|dd }| |}|| n9d|v rLd|v rL|d}||td	 d }| |}|| n|d
ksV| dkrWntd| d| jj || j	_
dS )a  Attempt to determine the sequence region the reference entails.

        Possible types of information we may have to deal with:

        (bases 1 to 86436)
        (sites)
        (bases 1 to 105654; 110423 to 111122)
        1  (residues 1 to 182)
        )r	   rA   basestor   Nresiduesz	residues siteszCould not parse base info z in record )endswith_split_reference_locationsrU   findr   rE   
ValueErrorr4   ru   r|   location)r   r   ref_base_infoall_locations	locationsresidues_startr   r   r   reference_bases8  s$   


z _FeatureConsumer.reference_basesc           
      C   s^   | d}g }|D ]#}| d\}}| t| t| \}}t||}	||	 q	|S )a!  Get reference locations out of a string of reference information (PRIVATE).

        The passed string should be of the form::

            1 to 20; 20 to 100

        This splits the information out and returns a list of location objects
        based on the reference locations.
        rB   r   )rK   rq   r   rE   r   r   )
r   r_   all_base_infonew_locations	base_inform   rn   ro   rp   this_locationr   r   r   r   `  s   

z+_FeatureConsumer._split_reference_locationsc                 C   ,   | j jr| j  jd| 7  _d S || j _d S Nr   r|   authorsr   r   r   r   r   w     z_FeatureConsumer.authorsc                 C   r   r   r|   consrtmr   r   r   r   r   }  r   z_FeatureConsumer.consrtmc                 C   sF   | j d u rtdt d S | j jr| j  jd| 7  _d S || j _d S )N*GenBank TITLE line without REFERENCE line.r   r|   r   r   r   titler   r   r   r   r     s   
z_FeatureConsumer.titlec                 C   r   r   r|   journalr   r   r   r   r     r   z_FeatureConsumer.journalc                 C      || j _d S r&   r|   
medline_idr   r   r   r   r        z_FeatureConsumer.medline_idc                 C   r   r&   r|   	pubmed_idr   r   r   r   r     r   z_FeatureConsumer.pubmed_idc                 C   r   )zDeal with a reference comment.r   N)r|   commentr   r   r   r   remark  s   z_FeatureConsumer.remarkc                 C   sL   z| j jd  dd| 7  < W d S  ty%   d|| j jd< Y d S w )Nr   rP   )r4   r   r   r   r   r   r   r   r     s
   $z_FeatureConsumer.commentc                 C   r   )Nstructured_commentr   r   r   r   r   r     r   z#_FeatureConsumer.structured_commentc                 C      |    dS z?Get ready for the feature table when we reach the FEATURE line.Nstart_feature_tabler   r   r   r   features_line  r%   z_FeatureConsumer.features_linec                 C   s,   | j dur| jjd | j  d| _ dS dS )z5Indicate we've got to the start of the feature table.Nr   )r|   r4   r   r   r#   r   r   r   r     s   

z$_FeatureConsumer.start_feature_tablec                 C   s$   t  | _|| j_| jj| j d S r&   )r   r}   r   r4   featuresr   r   r   r   r   feature_key  s   z_FeatureConsumer.feature_keyc           	   
   C   s   |  |}d|v r|d}|d| }| j}d| jjdd v }d| j v}z
t	
||||}W n tyQ } zt| dt d	}W Y d	}~nd	}~ww || j_d	S )
zParse out location information from the location string.

        This uses simple Python code with some regular expressions to do the
        parsing, and then translates the results into appropriate objects.
        rQ   ,   r   r   r   PROTEINz#; setting feature location to None.N)r`   r   r~   r4   r   getlowerrz   r   r   
fromstringr   r   r   r   r}   r   )	r   r   location_line	comma_poslengthis_circularstrandedr   er   r   r   r     s"   


z_FeatureConsumer.locationc                 C   s   |du r|| j jvrdg| j j|< dS dS t|dkr-|d dkr-|d dkr-|dd }td|r;td| t |d	d}| j	durM| j	
||}|| j jv r^| j j| | dS |g| j j|< dS )
zWhen we get a qualifier key and its value.

        Can receive None, since you can have valueless keys such as /pseudo
        Nr   r	   r   "rA   z[^"]"[^"]|^"[^"]|[^"]"$zuThe NCBI states double-quote characters like " should be escaped as "" (two double - quotes), but here it was not: %rz"")r}   
qualifiersr   researchr   r   r   rQ   ry   clean_valuer   r   keyvaluer   r   r   feature_qualifier  s(   $
z"_FeatureConsumer.feature_qualifierc                 C      t dz)Use feature_qualifier instead (OBSOLETE).z)Use the feature_qualifier method instead.NotImplementedError)r   content_listr   r   r   feature_qualifier_name     z'_FeatureConsumer.feature_qualifier_namec                 C   r  r  r  r   r   r   r   feature_qualifier_description  r  z._FeatureConsumer.feature_qualifier_descriptionc                 C   s   || j jd< dS )zDeal with CONTIG information.contigNr   r   r   r   r   contig_location
  s   z _FeatureConsumer.contig_locationc                 C   r>   r&   r   r   r   r   r   origin_name  r?   z_FeatureConsumer.origin_namec                 C   r>   r&   r   r   r   r   r   
base_count   r?   z_FeatureConsumer.base_countc                 C   r>   r&   r   r   r   r   r   base_number#  r?   z_FeatureConsumer.base_numberc                 C       d|vsJ | j |  dS )zAdd up sequence information as we get it.

        To try and make things speedier, this puts all of the strings
        into a list of strings, and then uses string.join later to put
        them together. Supposedly, this is a big time savings
        r   Nr{   r   r   r   r   r   r   sequence&  s   z_FeatureConsumer.sequencec                 C   s  | j jsd| j jv rtdt| j jd  | j j| j _n#| j jddkr@z| j  jd| j jd  7  _W n	 ty?   Y nw d| j	}| j
durht|dkrh| j
t|krhtd	| j
t|| j jf t d}| jrd
| j v s{d| j v r~d
}n'd| j v rd}nd| j v s| jdkrd}n| jdv rntd| j |dur| j jd|| j jd< |s| j
rtd| j
d| j _dS t|| j _dS )z(Clean up when we've finished the record.r   z,Problem adding version number to accession: r@   r   z.%ir   r   Nz+Expected sequence length %i, found %i (%s).r   MRNAr   r  PRTprotein)r   r   unspecifiedz/Could not determine molecule_type for seq_type r   )r	  )r4   ru   r   r   strr   r   r   r   r{   r~   r   r   r   r   rz   r   r  r   seq)r   r   r%  r   r   r   r   
record_end0  sX    



z_FeatureConsumer.record_endr&   )8r'   r(   r)   r*   r   r   r   r   r   r   r   r   r   rS   r   r   r   r   r   r   r   r   r   r   r   r   rM   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"  r%  r,  r   r   r   r   r2   )  sl    

		!(
!'
r2   c                   @   s  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d Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Z d<d= Z!d>d? Z"d@dA Z#dBdC Z$dDdE Z%dFdG Z&dHdI Z'dJdK Z(dLdM Z)dNdO Z*dPdQ Z+dRdS Z,dTdU Z-dVdW Z.dXdY Z/dZd[ Z0d\d] Z1d^d_ Z2d`da Z3dbdc Z4ddde Z5dfdg Z6dhdi Z7djS )kr;   zLCreate a GenBank Record object from scanner generated information (PRIVATE).c                 C   s<   t |  ddlm} | | _g | _d | _d | _d | _d S )Nr	   Record)	r<   r   r   r.  r4   r{   r|   r}   _cur_qualifier)r   r.  r   r   r   r   t  s   


z_RecordConsumer.__init__c                 C      | d| j_d S Nr   )rK   r4   r   r   r   r   r   r        z_RecordConsumer.tlsc                 C   r0  r1  )rK   r4   r   r   r   r   r   r     r2  z_RecordConsumer.tsac                 C   r0  r1  )rK   r4   r   r   r   r   r   r     r2  z_RecordConsumer.wgsc                 C   s   | j j|d d S r1  )r4   r   r   rK   r   r   r   r   r     s   z_RecordConsumer.add_wgs_scafldc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.locusc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.sizec                 C   s0   d|v sd|v rt d| dt || j_d S )NdnarnazInvalid seq_type (z): DNA/RNA should be uppercase.)r   r   r   r4   r   r   r   r   r   r     s   
z_RecordConsumer.residue_typec                 C   r   r&   )r4   r   r   r   r   r   r     r   z"_RecordConsumer.data_file_divisionc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.datec                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.definitionc                 C   s.   |  |D ]}|| jjvr| jj| qd S r&   )rT   r4   rS   r   )r   r   r   r   r   r   rS     s
   z_RecordConsumer.accessionc                 C   sj   |r3d|v s
d|v rt d|d|dd  dv r-|dd  s-td| t || j_dS dS )	r   r   r   r   r   r   Nr   r   )r+   r   r   r   r   r   r4   r   r   r   r   r   r     s   
$	z_RecordConsumer.molecule_typec                 C   s,   |r|dvrt d|d|| j_dS dS )r   r   r   r   N)r+   r4   r   r   r   r   r   r     s   
z_RecordConsumer.topologyc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.nidc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.pidc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.versionc                 C   s   |  | j_d S r&   )r   r4   r   r   r   r   r   r     r   z_RecordConsumer.db_sourcec                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.gic                 C      |  || j_d S r&   )rO   r4   rM   r   r   r   r   rM     r2  z_RecordConsumer.keywordsc                 C   s    | j jdd | D  d S )Nc                 s   rg   r&   r   r   r   r   r   rh     ri   z*_RecordConsumer.project.<locals>.<genexpr>)r4   projectsrU   rK   r   r   r   r   r     r   z_RecordConsumer.projectc                 C   s   | j j| d S r&   )r4   dblinksr   r   r   r   r   r     r2  z_RecordConsumer.dblinkc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.segmentc                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.sourcec                 C   r   r&   )r4   r   r   r   r   r   r     r   z_RecordConsumer.organismc                 C   r5  r&   )r]   r4   r   r   r   r   r   r     r2  z_RecordConsumer.taxonomyc                 C   s<   | j dur| jj| j  ddlm} | | _ || j _dS )zBGrab the reference number and signal the start of a new reference.Nr	   r-  )r|   r4   r   r   r   r.  r   numberr   r   r.  r   r   r   r     s
   

z_RecordConsumer.reference_numc                 C   r   r&   )r|   r   r   r   r   r   r     r   z_RecordConsumer.reference_basesc                 C   r   r&   r   r   r   r   r   r     r   z_RecordConsumer.authorsc                 C   r   r&   r   r   r   r   r   r     r   z_RecordConsumer.consrtmc                 C   s&   | j d u rtdt d S || j _d S )Nr   r   r   r   r   r   r     s   
z_RecordConsumer.titlec                 C   r   r&   r   r   r   r   r   r   	  r   z_RecordConsumer.journalc                 C   r   r&   r   r   r   r   r   r     r   z_RecordConsumer.medline_idc                 C   r   r&   r   r   r   r   r   r     r   z_RecordConsumer.pubmed_idc                 C   r   r&   )r|   r   r   r   r   r   r     r   z_RecordConsumer.remarkc                 C   s   | j  jd|7  _d S )NrP   )r4   r   r   r   r   r   r   r     s   z_RecordConsumer.commentc                 C   r   r&   )r4   r   r   r   r   r   r     r   z"_RecordConsumer.structured_commentc                 C   s   | j j| dS )z)Save reference data for the PRIMARY line.N)r4   primaryr   r   r   r   r   primary_ref_line     z _RecordConsumer.primary_ref_linec                 C   r>   r&   r   r   r   r   r   r:    r?   z_RecordConsumer.primaryc                 C   r   r   r   r   r   r   r   r   "  r%   z_RecordConsumer.features_linec                 C   s"   | j dur| jj| j  dS dS )z&Signal the start of the feature table.N)r|   r4   r   r   r#   r   r   r   r   &  s   
z#_RecordConsumer.start_feature_tablec                 C   s*   |    ddlm} | | _|| j_dS )zBGrab the key of the feature and signal the start of a new feature.r	   r-  N)_add_featurer   r.  Featurer}   r  r9  r   r   r   r   ,  s   
z_RecordConsumer.feature_keyc                 C   sB   | j dur| jdur| j j| j d| _| jj| j  dS dS )zAdd a feature to the record, with relevant checks (PRIVATE).

        This does all of the appropriate checking to make sure we haven't
        left any info behind, and that we are only adding info if it
        exists.
        N)r}   r/  r  r   r4   r   r#   r   r   r   r=  6  s   

z_RecordConsumer._add_featurec                 C   r5  r&   )r`   r}   r   r   r   r   r   r   F  r2  z_RecordConsumer.locationc                 C   s&   |  |g |d ur| | d S d S r&   )r  r  r  r   r   r   r  I  s   z!_RecordConsumer.feature_qualifierc                 C   sZ   ddl m} |D ]"}|dsd| }| jdur!| jj| j | | _|| j_qdS )zDeal with qualifier names.

        We receive a list of keys, since you can have valueless keys such as
        /pseudo which would be passed in with the next key (since no other
        tags separate them in the file)
        r	   r-  /N)	r   r.  
startswithr/  r}   r  r   	Qualifierr  )r   r  r.  r   r   r   r   r  N  s   




z&_RecordConsumer.feature_qualifier_namec                 C   s^   d| j jvr| j j d| j _| |}| jjD ]}|| j jv r%| |}q| || j _d S )N=)r/  r  rf   	__class__rr   rl   rk   r  )r   r   cur_contentremove_space_keyr   r   r   r  b  s   

z-_RecordConsumer.feature_qualifier_descriptionc                 C   r   r&   )r4   base_countsr   r   r   r   r!  n  r   z_RecordConsumer.base_countc                 C   r   r&   )r4   originr   r   r   r   r   q  r   z_RecordConsumer.origin_namec                 C   s   |  || j_dS )z<Signal that we have contig information to add to the record.N)r`   r4   r  r   r   r   r   r  t  r<  z_RecordConsumer.contig_locationc                 C   r#  )aC  Add sequence information to a list of sequence strings.

        This removes spaces in the data and uppercases the sequence, and
        then adds it to a list of sequences. Later on we'll join this
        list together to make the final sequence. This is faster than
        adding on the new string every time.
        r   Nr$  r   r   r   r   r%  x  s   z_RecordConsumer.sequencec                 C   s   d | j| j_|   dS )z;Signal the end of the record and do any necessary clean-up.r   N)r   r{   r4   r%  r=  r   r   r   r   r,    s   z_RecordConsumer.record_endN)8r'   r(   r)   r*   r   r   r   r   r   r   r   r   r   r   r   rS   r   r   r   r   r   r   r   rM   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  r!  r   r  r%  r,  r   r   r   r   r;   q  sl    	
r;   c                 C   s   t t| t S )aP  Iterate over GenBank formatted entries as Record objects.

    >>> from Bio import GenBank
    >>> with open("GenBank/NC_000932.gb") as handle:
    ...     for record in GenBank.parse(handle):
    ...         print(record.accession)
    ['NC_000932']

    To get SeqRecord objects use Bio.SeqIO.parse(..., format="gb")
    instead.
    )r"   r   r8   )r   r   r   r   r     s   r   c                 C   sT   t | }zt|}W n ty   tddw zt| td ty)   Y |S w )aO  Read a handle containing a single GenBank entry as a Record object.

    >>> from Bio import GenBank
    >>> with open("GenBank/NC_000932.gb") as handle:
    ...     record = GenBank.read(handle)
    ...     print(record.accession)
    ['NC_000932']

    To get a SeqRecord object use Bio.SeqIO.read(..., format="gb")
    instead.
    zNo records found in handleNz$More than one record found in handle)r   nextr   r   )r   iteratorrecordr   r   r   read  s   
rK  __main__)run_doctest)%r*   r  r   Bior   Bio.Seqr   Bio.SeqFeaturer   r   r   r   r   Scannerr
   utilsr   GENBANK_INDENTGENBANK_SPACERFEATURE_KEY_INDENTFEATURE_QUALIFIER_INDENTFEATURE_KEY_SPACERFEATURE_QUALIFIER_SPACERr   r   r+   r/   r,   r8   r<   r2   r;   r   rK  r'   
Bio._utilsrM  r   r   r   r   <module>   sL    -'o    L  
