
    DUfd                    *   d dl Z d dlmZ d dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlm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mZmZmZmZmZmZmZmZmZmZm Z  ddl!mZ dd	l"m#Z#m$Z$m%Z%m&Z&m'Z' dd
l!m(Z( d dl)Z)ddl!m*Z* dd
l!m(Z( i Z+i Z,i Z-d Z.d Z/	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ0 G d de1          Z2 G d de1          Z3 G d de4          Z5 G d de1          Z6d Z7e8dk    r$d dl9Z9 e9j:        e9j;        e9j<        z             dS dS )    N)dedent)islice)warn)Path   )get_tempdir_tagscall_bedtools_flatten_list_check_sequence_stderrisBAMisBGZIPisGZIPBEDToolsErrorpybedtoolsError_call_randomintersectSplitOutput)helpers)IntervalFileIntervalIteratorIntervalcreate_interval_from_listBedToolsFileError)	filenames)settingsc                    t          | t                    r"t          |                                           }nRt	          | d          st	          | d          r d                    d | D                       }nt          d| z            |                                \  }}|                                }|                                }t          |d                   |d<   t          |d                   |d<   t          |d                   |d<   t          |d	                   |d	<   t          t          t          ||                              S )
z
    jaccard method doesn't return an interval file, rather, it returns a short
    summary of results.  Here, we simply parse it into a dict for convenience.
    next__next__ c                     g | ]}|S  r!   .0is     O/var/www/html/software/conda/lib/python3.11/site-packages/pybedtools/bedtool.py
<listcomp>z+_jaccard_output_to_dict.<locals>.<listcomp>;   s    ^^^Aa^^^    zUnexpected object %rr   r         )
isinstancestropenreadhasattrjoin
ValueError
splitlinessplitintfloatdictlistzip)skwargs_sheaderdatas        r%   _jaccard_output_to_dictr=   3   s   
 !S 5!WW\\^^	F		 5wq*55 5WW^^^^^$$/!3444==??LFD\\^^F::<<D$q'llDG$q'llDGDGnnDG$q'llDGS&&''(((r'   c                    d|v rt          |           S t          | t                    rt          |           }t	          | d          r| }t          |                                          }i }|D ]}g ||<   |D ]}|                                \  }}}	}
t          |          t          |          t          |	          t          |
          g}t          ||          D ] \  }}||         
                    |           !|S )a  
    reldist, if called with -detail, returns a valid BED file with the relative
    distance as the last field.  In that case, return the BedTool immediately.
    If not -detail, then the results are a table, in which case here we parse
    into a dict for convenience.
    detailr   )BedToolr*   r+   r,   r.   r   r2   r4   r3   r7   append)r8   r9   iterabler;   resultshr$   reldistcounttotalfractionr<   ds                r%   _reldist_output_handlerrJ   H   s    6qzz!S 77q& (^^!!##FG  

 ! !*+''))'xgE

CJJhH%% 	! 	!DAqAJa    	!Nr'   Fc                    	
 d	 t          j        t          j                   dgz   t           j        t           j                  }|                                d                                                             dd                              d          dgd	 D             z   d	                              dz   n# t          $ r
 d
 z  dY nw xY w	
 fd}|S )a  
    Do-it-all wrapper, to be used as a decorator.

    *prog* is the name of the BEDTools program that will be called.  The help
    for this program will also be added to the decorated method's docstring.

    *implicit* is the BEDTools program arg that should be filled in
    automatically.

    *bam* will disable the implicit substitution if *bam* is in the kwargs.
    This is typically 'abam' or 'ibam' if the program accepts BAM input.

    *other* is the BEDTools program arg that is passed in as the second input,
    if supported.  Within the semantics of BEDTools, the typical case will be
    that if implicit='a' then other='b'; if implicit='i' then other=None.

    *uses_genome*, if True, will check for 'g' and/or 'genome' args and
    retrieve the corresponding genome files as needed.

    *make_tempfile_for* is used for the sequence methods and indicates which
    kwarg should have a tempfile made for it if it's not provided ('fo' for the
    sequence methods)

    *check_stderr*, if not None, is a function that accepts a string (which
    will be anything written to stdout when calling the wrapped program).  This
    function should return True if the string is OK, and False if it should
    truly be considered an error.  This is needed for wrapping fastaFromBed,
    which will report to stderr that it's creating an index file.

    *add_to_bedtool* is used for sequence methods.  It is a dictionary mapping
    kwargs to attributes to be created in the resulting BedTool.  Typically it
    is {'fo':'seqfn'} which will add the resulting sequence name to the
    BedTool's .seqfn attribute. If *add_to_bedtool* is not None, then the
    returned BedTool will be *self* with the added attribute.  If a key is
    "stdout" (e.g., {"stdout": attr_name}), then save the stdout of the command
    as a tempfile and store the tempfile's name in the attribute.  This is
    required for linksBed and bedToIgv.

    *nonbam* is a kwarg that even if the input file was a BAM, the output will
    *not* be BAM format.  For example, the `-bed` arg for intersectBed will
    cause the output to be in BED format, not BAM.  If not None, this can be a
    string, a list of strings, or the special string "ALL", which means that
    the wrapped program will never return BAM output.

    *force_bam*, if True, will force the output to be BAM.  This is used for
    bedToBam.

    *genome_none_if* is a list of arguments that will ignore the requirement
    for a genome.  This is needed for window_maker, where -b and -g are
    mutually exclusive.

    *genome_ok_if* is a list of arguments that, if they are in
    *genome_none_if*, are still OK to pass in.  This is needed for bedtool
    genomecov, where -g is not needed if -ibam is specified...but it's still OK
    if the user passes a genome arg.

    *genome_if* is a list of arguments that will trigger the requirement for
    a genome; otherwise no genome needs to be specified.

    *does_not_return_bedtool*, if not None, should be a function that handles
    the returned output.  Its signature should be ``func(output, kwargs)``,
    where `output` is the output from the [possibly streaming] call to BEDTools
    and `kwargs` are passed verbatim from the wrapped method call. Some
    examples of methods that use this are jaccard, reldist, fisher, and split
    methods.

    *arg_order*, if not None, is a sorted list of arguments. This is used by
    handle_kwargs() to deal with things like issues 81 and 345, where some
    BEDTools programs are sensitive to argument order.
    Fz-h)stdoutstderrr   _z**
z

**Original BEDTools help:**::c                     g | ]}d |z   S )	r!   r"   s     r%   r&   z_wraps.<locals>.<listcomp>   s    ;W;W;WD1H;W;W;Wr'   z"%s" does not appear to be installed or on the path, so this method is disabled.  Please install a more recent version of BEDTools and re-import to use this method.Tc                    t           <   
t          <   
t          <   rfd}|S g }r)|                    t	          ddd                     r"|                    t	          d                     	
fd}| j        d}n| j        }|d	                    |          z   z   |_        | j        |_        |S )
z
        Accepts a function to be wrapped; discards the original and returns a
        new, rebuilt-from-scratch function based on the kwargs passed to
        _wraps().
        Nc                  "    t                    N)NotImplementedError)argsr9   help_strs     r%   not_implemented_funcz7_wraps.<locals>.decorator.<locals>.not_implemented_func   s    )(333r'   z
                    For convenience, the file or stream this BedTool points to
                    is implicitly passed as the `-z` argument to `z`
                a  
                    There are two alternatives for supplying a genome.  Use
                    `g="genome.filename"` if you have a genome's chrom sizes
                    saved as a file. This is the what BEDTools expects when
                    using it from the command line. Alternatively, use the
                    `genome="assembly.name"` (for example, `genome="hg19"`) to
                    use chrom sizes for that assembly without having to manage
                    a separate file.  The `genome` argument triggers a call
                    `pybedtools.chromsizes`, so see that method for more
                    details.
                c                    t          |          dk    r t          |          dk    sJ |d         |<   |vr7|vr31| j        s| j        |<   n| j        |<   nt          dz            }rCr,D ]}||v s|k    rd}rD ]}||v s|k    r
d|v sd|v rd}rd}D ]}||v s|k    rd}|r | j        di |}|vr|                                 |<    | j        dd	|\  }}}d}| j        rd}d
k    rd}.d
k    r(t          t                    rg}	n}	|	D ]
}||v rd} nrd}| }
t          ||||
          }r	 |fi |S Lt                                                    D ])\  }}|dk    r|}n||         }t          | ||           | }*nt          |          }||_        ||_        ~|S )zn
            A newly created function that will be returned by the _wraps()
            decorator
            r   r   NzE"%s" currently can't handle BAM input, please use bam_to_bed() first.FggenomeT)prog	arg_orderALL)stdincheck_stderrdecode_outputrL   r!   )len_isbamfnr   check_genome_tmphandle_kwargsr*   r+   r
   r6   itemssetattrr@   _cmds)selfrV   r9   check_for_genomer$   cmdstmpr_   result_is_bam_nonbamra   streamkwattrvalueresultadd_to_bedtoolr]   bamr`   does_not_return_bedtool	force_bam	genome_ifgenome_none_ifgenome_ok_ifimplicitmake_tempfile_fornonbamotherr\   uses_genomes                   r%   wrappedz*_wraps.<locals>.decorator.<locals>.wrapped  s<    4yy1}}4yyA~~~~ $Qu ''&&){ '+wF8$$ &*gs
 .DFJK    + 4! <+ 5 5;;!x--/4,
 $ <!- < <A F{{a8mm$'6MMx67I7I7;$4 4',$& 4 4KKQ(]]/3, 5**44V44 !,$F2204		F,-  2t1  <t<E <  <4: <  <D#u
 "M { % $  % !foofc** %%hGG$G   AF{{(- #  % $ --M #)+  F ' A..v@@@@@
 ) $^%9%9%;%; < < " "HBX~~ & &r
D$...!FF" !)FMFLMr'   r   rO   )	_implicit_registry_other_registry_bam_registryrA   r   __doc__r/   __name___name)funcrX   _add_docr   origrv   r]   rw   r`   rx   ry   rz   r{   r|   rW   r}   r~   r   not_implementedr   r\   r   s        r%   	decoratorz_wraps.<locals>.decorator   s    $,4 $)OD!?"%M$  	(4 4 4 4 4 (' 		OO
  xx	'     	OO
    K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	 K	^ <DD<D8!4!44x? r'   )
subprocessPopenr   _version_2_15_plus_namesPIPEcommunicatedecodereplacer2   r/   OSError)r\   r}   rw   r   r   r~   r`   rv   r   ry   r{   rz   r|   rx   r]   pr   rW   r   s   ```````````````  @@r%   _wrapsr   a   s   | O,T22dV;??
 
 

 ==??1%,,.. ##C.. >>$''78;W;Wh;W;W;WW99X&&-
     "&	& 	 O O O O O O O O O O O O O O O O O O O O Ob s   C C C*)C*c                      e Zd Zej        ZddZe	 	 	 	 	 dd            Zd Zd Z	dd	Z
d
 ZddZd ZddZddZd Zd ZddZd ZddZd Zed             ZddZed             Zd Zed             Zd Zd Zd  Zd! Zd" Z d# Z!d$ Z"d% Z#dd&Z$d' Z%	 	 	 	 dd(Z&d) Z'd* Z(ed+             Z)dd-Z*dd.Z+dd/Z,e e-d0d1dd2          d3                         Z.e.Z/e e-d4d1dd5d16          d7                         Z0e0Z1 e-d8d1dd9          d:             Z2ed;             Z3e3Z4e e-d<d=d>d?d@d=d?gA          dB                         Z5e e-dCd@ddDdEe6dEdFiG          dH                         Z7e7Z8e9dI             Z:e e-dJd@dDe6K          dL                         Z;e;Z<e e-dMd@N          dO                         Z=e=Z>e e-dPd=d>dQ          dR                         Z?e e-dSd1dddT          dU                         Z@e e-dVd1dddT          dW                         ZAe e-dXd1ddQ          dY                         ZBe e-dZd=d>dQ          d[                         ZCe e-d\d=d>d?d@]          d^                         ZDe e-d_d1dddT          d`                         ZEe e-dad1ddbdcgd          de                         ZFe e-dfd1N          dg                         ZGe e-dhd1di          dj                         ZHe e-dkd1dldlgdlgdd5m          dn                         ZIeIZJe e-dod=d>d?d5]          dp                         ZKe e-dqd@dDdEdEdFie6r          ds                         ZLeLZMe e-dtd1di          du                         ZNe e-dvd1N          dw                         ZOe e-dxd=d>d?dy]          dz                         ZPePZQe e-d{d=d>|          d}                         ZReRZSe e-d~d1N          d                         ZTe e-dd1d1          d                         ZUeUZVe e-dd=d>|          d                         ZWe e-dddg          d                         ZXeXZYe e-dd          d                         ZZe e-dd1dd          d                         Z[e[Z\e e-dd1N          d                         Z]e e-d          d                         Z^e^Z_e e-ddd>gd>dg          d                         Z`e`Zae e-dd1N          d                         Zbe e-dd1ddi          d                         Zce e-dd1ddi          d                         Zde e-dd1d1dddi          d                         ZeeeZf e-dd=d>eg          d             Zh e-dd=d>ei          d             Zj e-dd1d1          d             Zk e-dd=d>deljm                  d             Zn e-dd1eljo                  d             Zp e-dd1N          d             Zqd Zrd Zsd Zt	 	 	 ddZud Zv	 ddZw	 	 	 	 	 	 ddZx	 	 	 	 ddZy	 	 	 	 ddZz	 	 	 	 	 	 ddZ{ed             Z|edd            Z}eddÄ            Z~eddĄ            Zdń ZedƄ             ZdǄ ZddɄZddʄZdd˄Zdd̄Zd̈́ Zdd΄ZddτZdS )r@   NFc                    |rt          d          || _        d| _        d| _        |r|}|                                 }t          |d          }|                                D ]g}t          |                                          dk    r(d	                    |
                                          dz   }|                    |           h|                                 ndt          t          |          j                  v rt          |          }t!          |t"                    r	|j        }nIt!          |t                    r|rd	| _        nGt&          j                            |          sd
|z  }t-          |          t/          |          | _        | j        rt1          j        |          j        }g }	|                                D ]9\  }
}t!          |t8                    r|D ]}t!          |t:                    r[|	                    d	                    d|
z   gd t?          |                                d	          D             z                        rt!          |t                    r|	                    |           t!          |t:                    r\|	                    d	                    d|
z   gd t?          |                                d	          D             z                        ,t          d          d	                    |	          dz   | _        nRt!          |t8          t@          f          r4t#          tC          |                    "                                j        }n|}|| _        d	                    d tG          d          D                       }|| _$        | tJ          |<   d| _&        d| _'        tQ                      | _)        dS )aE  
        Wrapper around Aaron Quinlan's ``BEDtools`` suite of programs
        (https://github.com/arq5x/bedtools); also contains many useful
        methods for more detailed work with BED files.

        *fn* is typically the name of a BED-like file, but can also be
        one of the following:

            * a string filename
            * another BedTool object
            * an iterable of Interval objects
            * an open file object
            * a "file contents" string (see below)

        If *from_string* is True, then you can pass a string that contains
        the contents of the BedTool you want to create.  This will treat all
        spaces as TABs and write to tempfile, treating whatever you pass as
        *fn* as the contents of the bed file.  This also strips empty lines.

        Typical usage is to point to an existing file::

            a = BedTool('a.bed')

        But you can also create one from scratch from a string::

            >>> s = '''
            ... chrX  1  100
            ... chrX 25  800
            ... '''
            >>> a = BedTool(s, from_string=True)

        Or use examples that come with pybedtools::

             >>> example_files = pybedtools.list_example_files()
             >>> assert 'a.bed' in example_files
             >>> a = pybedtools.example_bedtool('a.bed')

        zCRemote BAM no longer supported (since BEDTools does not support it)Fr   wr   rQ   rO   zpathlib.PurePathTzFile "%s" does not exist@c                 ^    g | ]*}d                      t          t          |                    +S :r/   mapr+   r#   js     r%   r&   z$BedTool.__init__.<locals>.<listcomp>#  s<     /. /. /.45 14S!0E0E/. /. /.r'   reversec                 ^    g | ]*}d                      t          t          |                    +S r   r   r   s     r%   r&   z$BedTool.__init__.<locals>.<listcomp>0  s<     '& '& '&,- ),S!(=(='& '& '&r'   zunhandled type in BAM headerc                 J    g | ] }t          j        t          j                  !S r!   randomchoicestringascii_lowercaser#   rN   s     r%   r&   z$BedTool.__init__.<locals>.<listcomp>E  s%    OOOv}V%;<<OOOr'      N)*r0   remoterc   _bam_headerrf   r,   r1   rb   stripr/   r2   writecloser+   type__mro__r*   r@   rd   ospathexistsFileNotFoundErrorr   pysamSamfiler;   rh   r6   r5   rA   sortedtupleitersaveasrange_tagr	   
_hascounts
_file_typeHistoryhistory)rk   rd   from_stringr   bed_contentsfoutlinemsgr;   
txt_headerkvr$   tags                 r%   __init__zBedTool.__init__  s   N  	X    ]	LBC==D$//11 ! !tzz||$$))yy..5

4    JJLLLL "Sb)9%:%:::WW "g&& LU B$$ H ,"&DKK7>>"-- 582=/444"'))DK ; 3D"]2..5F* "$J & M M1%a.. M%& 9 9#-a#6#6 !9$.$5$5(,		-01WI/. /.9?		SW9X9X9X/. /. /.-.)* )*%& %& %& %& &03%7%7 !9$.$5$5a$8$8$89 (400 M&-- $		%(1WI'& '&17		41P1P1P'& '& '&%&!" !"    #--K"L"LL'+yy'<'<t'CD$ Bu.. T"XX&&--//2
 ggOOeAhhOOOPP	c
yyr'   rQ   .c                 z   	 ddl }n# t          $ r t          d          w xY w||                                 }t          ||||          }	|	                    |            |j        |fi |	 t          |t                    r|}
n&	 |j        }
n# t          $ r t          d          w xY wt          |
          S )ap  
        Creates a BedTool from a pandas.DataFrame.

        If `outfile` is None, a temporary file will be used. Otherwise it can
        be a specific filename or an open file handle. Additional kwargs will
        be passed to `pandas.DataFrame.to_csv`.

        The fields of the resulting BedTool will match the order of columns in
        the dataframe.
        r   Nz*pandas must be installed to use dataframes)sepr;   na_repindexz\`outfile` is not a string and doesn't have a `name` attribute. Unable to determine filename.)pandasImportErrorrf   r5   updateto_csvr*   r+   nameAttributeErrorr0   r@   )rk   dfoutfiler   r;   r   r   r9   r   default_kwargsrd   s              r%   from_dataframezBedTool.from_dataframeL  s    *	LMMMM 	L 	L 	LJKKK	L?iikkG#fV5QQQf%%%	',,^,,,gs## 		BB\!    4  
 r{{s    !	B B+c                 H      fd}t           |                      S )aj  
        Split each feature using a user-defined function.

        Calls the provided function `func` with each interval.  In contrast to
        `each` (which does something similar), this method expects `func` to
        return an *iterable* of Interval objects.

        args and kwargs are passed directly to `func`.

        Returns a new BedTool.
        c               3   <   K   D ]}  | gR i D ]}|V  d S rT   r!   )orig_intervalintervalrV   r   r9   rk   s     r%   	generatorz BedTool.split.<locals>.generator  sY      !% # # $] DT D D DV D D # #H"NNNN## #r'   r@   )rk   r   rV   r9   r   s   ```` r%   r2   zBedTool.splitw  sD    	# 	# 	# 	# 	# 	# 	# 	#
 yy{{###r'   c           	         t          |t                    r|}n+t          |t                    sJ t          j        |          }|                                 }t          |d          5 }t          |                                          D ]V\  }}|\  }}t          |          }t          |          }|	                    d
                    |||g          dz              W	 ddd           n# 1 swxY w Y   |                     |          S )a  
        Ensure all features fall within chromosome limits.

        Some peak-callers extend peaks such that the boundaries overstep
        chromosome coordinates.  Upon uploading such a file to a genome browser
        like UCSC, this results in an error like::

            Error line 101 of custom track: chromEnd larger than chrom chr2
            size

        Use this method to clean your file, truncating any out-of-bounds
        features to fit within the chromosome coordinates of `genome`.

        `genome` can be either an assembly name ('dm3') or a dictionary where
        keys are chrom and values are (start, stop) tuples.
        r   rQ   rO   N)r*   r5   r+   r   
chromsizesrf   r,   r6   rh   r   r/   	intersect)	rk   r[   	chromdictrn   r   chromcoordsstartstops	            r%   truncate_to_chromzBedTool.truncate_to_chrom  sM   " fd## 	3IIfc******622Iiikk#s^^ 	Ct!%ioo&7&7!8!8 C Cv$tE

4yy

499eUD%9::TABBBB	C	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C ~~c"""s   (A9C..C25C2c                    |                                  st          d          t          j        | j                  }t          |t                    r|}|j        |j        |j	        }}}nbt          j                            |          }||}d\  }}n9|                    ddd          \  }}}t          |          t          |          }}	 |                    t!          |          ||          n# t          $ r |r g Y nw xY wfd}	t#           |	                                                      }
|                                 |
S )a  
        Retrieve all intervals within coordinates from a "tabixed" BedTool.

        Given either a string in "chrom:start-stop" format, or an interval-like
        object with chrom, start, stop attributes, return a *streaming* BedTool
        of the features in this BedTool that overlap the provided interval.

        If the coordinates are invalid, an empty generator is returned unless
        `check_coordinates=True` in which case a ValueError will be raised.
        MThis BedTool has not been indexed for tabix -- please use the .tabix() methodNNNr   r(   r)   c               3   $   K   D ]	} | dz   V  
d S )NrO   r!   )r$   rC   s    r%   genz$BedTool.tabix_intervals.<locals>.gen  s/        $h r'   )_tabixedr0   r   	TabixFilerd   r*   r   r   r   r   r   coord_researchgroupr3   fetchr+   r@   r   r   )rk   interval_or_stringcheck_coordinatestbxr   r   r   endmatchr   xrC   s              @r%   tabix_intervalszBedTool.tabix_intervals  sj    }} 	4   odg&& ((33 	2)H (#5EE $++,>??E}*'
ss %*KK1a$8$8!uc ZZSs	iiE

E377GG 	 	 	  			 	 	 	 	
 CCEENN!!##		s   $C3 3DDc                     |                                  st          d          t          j        | j                  }|j        S )zA
        Returns a list of contigs from the tabix index.
        r   )r   r0   r   r   rd   contigs)rk   r   s     r%   tabix_contigszBedTool.tabix_contigs  sF     }} 	4  
 odg&&{r'   Tc                     |                                  r|s| S |                     ||          }t          j        ||| j                   t          |          S )a  
        Prepare a BedTool for use with Tabix.

        Returns a new BedTool that has been BGZIP compressed
        and indexed by tabix.

        Parameters
        ----------

        in_place : bool
            If True (default), then assume the file is already sorted and
            replace the existing file with the BGZIPed version.

        force : bool
            If True (default is False), then overwrite both the index and the
            BGZIP file.

        is_sorted : bool
            If True (default is False), then assume the file is already sorted
            so that BedTool.bgzip() doesn't have to do that work.
        )in_placeforce)r  preset)r   bgzipr   tabix_index	file_typer@   )rk   r  r  	is_sortedrd   s        r%   tabixzBedTool.tabix  s]    . ==?? 	5 	K ZZZ77"E$.AAAAr{{r'   c                     t          | j        t                    r=t          | j                  r+t          j                            | j        dz             rdS dS dS dS )z
        Verifies that we're working with a tabixed file: a string filename
        pointing to a BGZIPed file with a .tbi file in the same dir.
        z.tbiTN)r*   rd   r+   r   r   r   r   rk   s    r%   r   zBedTool._tabixed  sn     tw$$	  	 tw/00	
 4	 	 	 	 	 	r'   c                    |rd}nd}t          | j        t                    r|st          | j                  r| j        S |so|s|                     d          j        }n|                                 }|dz   }t          j                            |           t          j
        |||           |S |rZ|s.|                     d                                          j        }n| j        }| j        dz   }t          j
        |||           |S dS )aR  
        Helper function for more control over "tabixed" BedTools.

        Checks to see if we already have a BGZIP file; if not then prepare one.
        Always leaves the original file alone.  You can always just make a
        BedTool out of an already sorted and BGZIPed file to avoid this step.

        `in_place` will put the BGZIPed file in the same dir (possibly after
        sorting to tempfile).

        If `is_sorted`, then assume the file is already sorted. Otherwise call
        bedtools sort with the `-header` option.

        `force` will overwrite without asking.
        z-fr   T)r;   .gz)r  N)r*   rd   r+   r   sortrf   r@   	TEMPFILESrA   r   tabix_compressr   )rk   r  r  r	  	force_argrd   outfns          r%   r  zBedTool.bgzip  s5      	III dgs## 	E 	tw w  	 !YYdY++.YY[[ JE$$U+++  U%8888L  	 YYdY++22447WGeOE U%8888L	 	r'   c                 F   t          | j                  }g }t                      }|D ]}|j        }|                    t
          j                            t
          j                            |          d                    r*|	                    d          r|
                    |           |t          }d                    |          }|r= |d|z            }	|	                                d         dk    st          d           dS |D ]}t          j        |           dS )	a  
        Use at your own risk!  This method will delete temp files. You will be
        prompted for deletion of files unless you specify *ask=False*.

        Deletes all temporary files created during the history of this BedTool
        up to but not including the file this current BedTool points to.

        Any filenames that are in the history and have the following pattern
        will be deleted::

            <TEMP_DIR>/pybedtools.*.tmp

        (where <TEMP_DIR> is the result from get_tempdir() and is by default
        "/tmp")

        Any files that don't have this format will be left alone.

        (*raw_input_func* is used for testing)
        
pybedtoolsz.tmpNz
	zDelete these files?
	%s
(y/N) r   yzOK, not deleting.)r   r   r   rd   
startswithr   r   r/   abspathendswithrA   inputlowerprintunlink)
rk   askraw_input_funcflattened_history	to_deletetempdirr$   rd   str_fnsanswers
             r%   delete_temporary_historyz BedTool.delete_temporary_historyT  s   ( *$,77	--" 	) 	)AB}}RW\\"'//'*B*BLQQRR );;v&& )$$R(((!"N++i(( 	#^$G'$QRRF<<>>!$++)*** 	 	BIbMMMMr'   c                 *      fd} j         |_         |S )z
        Decorator to add a method and its kwargs to the history.

        Assumes that you only add this decorator to bedtool instances that
        return other bedtool instances
        c                     | g|R i |}| j         }|j         }t          ||| ||          }t          | j                  dk    r|j                            | j                   |j                            |           |S )Nr   )r   HistorySteprb   r   rA   )rk   rV   r9   ru   
parent_tag
result_taghistory_stepmethods          r%   	decoratedz*BedTool._log_to_history.<locals>.decorated  s     VD24222622F JJ 'fdJ
 L 4<  1$$%%dl333 N!!,///Mr'   )r   )r,  r-  s   ` r%   _log_to_historyzBedTool._log_to_history  s.    	 	 	 	 	2 #N	r'   c                 B    t          fd| D                       S )ao  
        Filter features by user-defined function.

        Takes a function *func* that is called for each feature in the
        `BedTool` object and returns only those for which the function returns
        True.

        *args and **kwargs are passed directly to *func*.

        Returns a streaming BedTool; if you want the filename then use the
        .saveas() method.

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> subset = a.filter(lambda b: b.chrom == 'chr1' and b.start < 150)
        >>> len(a), len(subset)
        (4, 2)

        so it has extracted 2 records from the original 4.

        c              3   4   K   | ]} |gR i |V  d S rT   r!   )r#   frV   r   r9   s     r%   	<genexpr>z!BedTool.filter.<locals>.<genexpr>  sB      DDa44+CD+C+C+CF+C+CDDDDDDDr'   r   )rk   r   rV   r9   s    ```r%   filterzBedTool.filter  s0    * DDDDDD4DDDEEEr'   
   c                    | j         dk    rdS d}t          g           }| D ]7}||k    r n.|dz  }|                    t          |j                  g           8t          |          dk    s
J |            t          |          d         S )a  
        Number of fields in each line of this BedTool (checks `n` lines)

        Return the number of fields in the features this file contains.  Checks
        the first *n* features.

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> a.field_count()
        6
        emptyr   r   )r  setr   rb   fieldsr6   )rk   nr$   r8  feats        r%   field_countzBedTool.field_count  s     >W$$1R 	. 	.D1uuFAMM3t{++,----6{{aF||Ar'   c                 H      fd}t           |                      S )a>  
        Modify each feature with a user-defined function.

        Applies user-defined function *func* to each feature.  *func* must
        accept an Interval as its first argument; *args and **kwargs will be
        passed to *func*.

        *func* must return an Interval object OR a value that evaluates to
        False, in which case the original feature will be removed from the
        output.  This way, an additional "filter" call is not necessary.

        >>> def truncate_feature(feature, limit=0):
        ...     feature.score = str(len(feature))
        ...     if len(feature) > limit:
        ...         feature.stop = feature.start + limit
        ...         feature.name = feature.name + '.short'
        ...     return feature

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b = a.each(truncate_feature, limit=100)
        >>> print(b) #doctest: +NORMALIZE_WHITESPACE
        chr1	1	100	feature1	99	+
        chr1	100	200	feature2	100	+
        chr1	150	250	feature3.short	350	-
        chr1	900	950	feature4	50	+
        <BLANKLINE>

        c               3   :   K   D ]}  | gR i }|r|V  d S rT   r!   )r1  ru   rV   r   r9   rk   s     r%   
_generatorz BedTool.each.<locals>._generator  sQ       ! !a1$111&11 ! LLL! !r'   r   )rk   r   rV   r9   r>  s   ```` r%   eachzBedTool.each  sD    <	! 	! 	! 	! 	! 	! 	! 	! zz||$$$r'   geneexonc                    |                                  }| j        dk    r[t          fd|D                                                       }t          fd|D                                                       }n| j        dk    rf|                                dk    r;|                                                                }|                                }n"|}d}t          d          t          d          t          t                                          d	          5 }t          |j
                  }|D ]Vfd
|                    d          D             }t          |          D ]\  }	|	dk    rTj        j        k    rDdddj                 }
t          dj        j        j        j        |
j        fz  |           `|	t%          |          dz
  k    rTj        j        k     rDdddj                 }
t          dj        j        j        j        |
j        fz  |           |	t%          |          dz
  k    r?j        }||	dz            j        }t          dj        ||j        j        fz  |           !X	 ddd           n# 1 swxY w Y   t          |j                  S )a  
        Create intron features (requires specific input format).

        NOTE: this method assumes a simple file with non-overlapping exons. For
        more sophisticated features, consider the gffutils package instead.

        Given a BED12 or a GFF with exons, create a new `BedTool` with just
        introns.  The output is a bed6 file with the score column (5) being one
        of 'intron'/'utr5'/'utr3'
        gffc              3   4   K   | ]}|d          k    |V  dS r(   Nr!   )r#   r1  rA  s     r%   r2  z"BedTool.introns.<locals>.<genexpr>  +       > >q1 > >r'   c              3   4   K   | ]}|d          k    |V  dS rE  r!   )r#   r1  r@  s     r%   r2  z"BedTool.introns.<locals>.<genexpr>  rF  r'   bed   Nz*.introns() only supported for bed12and GFFz).introns() only supported for BED and GFFr   c                 T    g | ]$}|j         j         k    |j        j        k    "|%S r!   )r   r   )r#   erZ   s     r%   r&   z#BedTool.introns.<locals>.<listcomp>  s<       w!'))aequnn .<nnr'   T)same_strandr   utr5utr3)+-z%s	%i	%i	%s	%s	%sfiler   z%s	%i	%i	%s	intron	%s)r  r  r@   r   r;  bed6rU   r,   rf   r   rd   r   	enumerater   strandr  r   r   rb   r   )rk   r@  rA  r8   	exon_iter	gene_iterfhexon_intervalsexonsr$   utristartiendrZ   s    ``          @r%   intronszBedTool.introns  sB    IIKK>U"" > > > >A > > >??FFHHI > > > >A > > >??FFHHII^u$$}}"$$FFHHOO--	HHJJ		 	 	)C  
 &&QRRR',,..#&& #	")),77N       +221$2GG    )//  GAtAvv$*qw"6"6$*88B4 wQVS!(ST!#    
 c%jj1n,,AE1A1A$*88B4 w!%ahOP!#    
 c%jj1n,,!%$QU|18 wafahGH!#   ' #	 #	 #	 #	 #	 #	 #	 #	 #	 #	 #	 #	 #	 #	 #	H rws   %E/J!!J%(J%c                 d    t          | d          st          | d          r| S t          |           S )z1
        Returns an iterable of features
        r   r   )r.   r   r  s    r%   featureszBedTool.features?  s8     4   	GD*$=$= 	KDzzr'   c                     t          | j        t                    st          d          | j        rd| _        n?	 t          t          |                     j        | _        n# t          $ r
 d| _        Y nw xY w| j        S )z
        Return the type of the current file.  One of ('bed','vcf','gff', 'bam',
        'sam', 'empty').

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> print(a.file_type)
        bed
        zcChecking file_type not supported for non-file BedTools. Use .saveas() to save as a temp file first.rw   r6  )
r*   rd   r+   r0   rc   r   r   r   r  StopIterationr  s    r%   r  zBedTool.file_typeG  s     $'3'' 	-  
 ; 	*#DOO*"&tDzz"2"2"<  * * *")* s   &A! !A54A5c                 n   |rt          fd| D                       S t          |                                 d          5 }| D ]Et          d                    t          t          fdD                                 |           F	 ddd           n# 1 swxY w Y   t          |j                  S )a  
        Analagous to unix `cut`.

        Similar to unix `cut` except indexes are 0-based, must be a list
        and the columns are returned in the order requested.

        This method returns a BedTool of results, which means that the indexes
        returned must be valid GFF/GTF/BED/SAM features.

        If you would like arbitrary columns -- say, just chrom and featuretype
        of a GFF, which would not comprise a valid feature -- then instead of
        this method, simply use indexes on each feature, e.g,

        >>> gff = pybedtools.example_bedtool('d.gff')
        >>> results = [(f[0], f[2]) for f in gff]

        In addition, `indexes` can contain keys of the GFF/GTF attributes, in
        which case the values are returned. e.g. 'gene_name' will return the
        corresponding name from a GTF, or 'start' will return the start
        attribute of a BED Interval.
        c              3   6   K   | ]fd D             V  dS )c                      g | ]
}|         S r!   r!   r#   rs   r1  s     r%   r&   z)BedTool.cut.<locals>.<genexpr>.<listcomp>x  s    999QtW999r'   Nr!   )r#   r1  indexess    @r%   r2  zBedTool.cut.<locals>.<genexpr>x  s9      HHa9999999HHHHHHr'   r   rQ   c                      g | ]
}|         S r!   r!   rf  s     r%   r&   zBedTool.cut.<locals>.<listcomp>|  s    -J-J-J$ag-J-J-Jr'   rQ  N)r@   r,   rf   r  r/   r   r+   r   )rk   rg  rq   rX  r1  s    `  @r%   cutzBedTool.cuta  s   ,  	$HHHH4HHHIIIdiikk3'' W2 W WA$))C-J-J-J-J'-J-J-J$K$KLLSUVVVVVWW W W W W W W W W W W W W W W 27###s   A	BBBc                     t          j        t          j        t          j        d          }|j        }t          j                            |           |S )z
        Makes a tempfile and registers it in the BedTool.TEMPFILES class
        variable.  Adds a "pybedtools." prefix and ".tmp" extension for easy
        deletion if you forget to call pybedtools.cleanup().
        F)prefixsuffixdelete)	tempfileNamedTemporaryFiler   tempfile_prefixtempfile_suffixr   r@   r  rA   )rk   tmpfns     r%   rf   zBedTool._tmp  sO     +++
 
 

 
  '''r'   c                    | j         rt          | j                  S t          | j        t                    rt
          j                            | j                  s't          d	                    | j                            t          | j                  r't          t          j        | j        d                    S t          t          | j        d                    S t          | j                  S )za
        Dispatches the right iterator depending on how this BedTool was
        created
        z{0} does not existrtr)rc   BAMrd   r*   r+   r   r   r   r   formatr   r   gzipr,   r  s    r%   __iter__zBedTool.__iter__  s    
 ; 	  tw<< dgs## 	-7>>$'** N'(<(C(CDG(L(LMMMdg <'	$'4(@(@AAA'TWc(:(:;;;
 $DG,,,r'   c                 |    t          | j        t                    rt          | j                  S t	          d          )Nz3Please convert to a file-based BedTool using saveas)r*   rd   r+   r   r0   r  s    r%   	intervalszBedTool.intervals  s6    dgs## 	T(((RSSSr'   c                 >   t          | j        t                    r?t          j                            | j                  s| j        r
d| j        z  S d| j        z  S t          | j        t                    rt          | j                  S dt          | j                  z  S )Nz<BedTool(%s)>z<BedTool(MISSING FILE: %s)>)	r*   rd   r+   r   r   r   r   r@   reprr  s    r%   __repr__zBedTool.__repr__  s    dgs## 	3w~~dg&& ?$+ ?&004tw>>)) 	3== "T$']]22r'   c                     g }t          |           D ]P}t          |          }t          |t                    r|                    d          }|                    |           Qd                    |          S )zJ
        Returns the string representation of the whole `BedTool`
        zUTF-8r   )r   r+   r*   bytesr   rA   r/   )rk   rh   r$   s      r%   __str__zBedTool.__str__  sm     d 	 	AAA!U## &HHW%%LLOOOOwwu~~r'   c                 *    |                                  S rT   )rF   r  s    r%   __len__zBedTool.__len__  s    zz||r'   c                 *   t          |t                    r|}nXt          |t                    rCt          | j        t                    rt          |j        t                    st	          d          t          |           t          |          k    rdS dS )Nz@Testing equality only supported for BedTools that point to filesTF)r*   r+   r@   rd   rU   )rk   r   	other_strs      r%   __eq__zBedTool.__eq__  s    eS!! 		IIw'' 	dgs++ :#4 4  *4   t99E

""4ur'   c                 .    |                      |           S rT   )r  )rk   r   s     r%   __ne__zBedTool.__ne__  s    ;;u%%%%r'   c                    t          |t                    r!t          | |j        |j        |j                  S t          |t                    r't          t          | ||dz                       d         S t          d          )Nr   r   z;Only slices or integers allowed for indexing into a BedTool)	r*   slicer   r   r   stepr3   r6   r0   )rk   keys     r%   __getitem__zBedTool.__getitem__  sx    c5!! 	$	38SX>>>S!! 	tS#'2233A66P  r'   c                     	 |                      |d          }nF# t          $ r9}| j        dk    s|j        dk    rt          j        dd          }n|Y d }~nd }~ww xY w|S )NTur6  r   r   )r   r   r  r  r@   )rk   r   ru   rK  s       r%   __add__zBedTool.__add__  s    	^^ET^22FF 	 	 	'))u'/I/I#+BDAAA 	 s    
A/AAc                 4   	 |                      |d          }n~# t          $ rq | j        dk    r"|j        dk    rt          j        dd          }nA|j        dk    r|                                 }n!| j        dk    rt          j        dd          }Y nw xY w|S )NT)r   r6  r   r  )r   r   r  r  r@   r   )rk   r   ru   s      r%   __sub__zBedTool.__sub__  s    
	B^^ET^22FF 	B 	B 	B '))70J0J#+BDAAAG++7**#+BDAAA	B s    A8BBc                    t          | j        t                    st          d          |r'd                    d | d|         D                       S | j        rt          d          t          | j                  rt          j        }d}n	t          }d} || j        |          5 }t          |          D ]\  }}||k    r nt          |d	           ddd           dS # 1 swxY w Y   dS )
a  
        Prints the first *n* lines or returns them if as_string is True

        Note that this only opens the underlying file (gzipped or not), so it
        does not check to see if the file is a valid BED file.

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> a.head(2) #doctest: +NORMALIZE_WHITESPACE
        chr1	1	100	feature1	0	+
        chr1	100	200	feature2	0	+
        <BLANKLINE>

        z0head() not supported for non file-based BedToolsr   c              3   4   K   | ]}t          |          V  d S rT   r+   )r#   r   s     r%   r2  zBedTool.head.<locals>.<genexpr>  s(      ::3t99::::::r'   Nzhead() not supported for BAMrt  ru   )r   )r*   rd   r+   rU   r/   rc   r   rx  r,   rT  r  )rk   r9  	as_stringopenfuncopenmodefinr$   r   s           r%   headzBedTool.head  sS    $'3'' 	%B    	;77::bqb::::::; 	)%&DEEEdg 9$'8,, )(~~ ) )GAtQxx$C(((((	) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) )s   &/C""C&)C&c                     t          |t                    rt          j        |          | _        n,t          |t                    r|| _        nt          d          | S )aY  
        Prepare BedTool for operations that require chromosome coords.

        Set the chromsizes for this genome. If *chromsizes* is a string, it
        will be considered a genome assembly name.  If that assembly name is
        not available in pybedtools.genome_registry, then it will be searched
        for on the UCSC Genome Browser.

        Example usage:

            >>> hg19 = pybedtools.chromsizes('hg19')
            >>> a = pybedtools.example_bedtool('a.bed')
            >>> a = a.set_chromsizes(hg19)
            >>> print(a.chromsizes['chr1'])
            (0, 249250621)

        zMNeed to specify chromsizes either as a string (assembly name) or a dictionary)r*   r+   r  r   r5   r0   )rk   r   s     r%   set_chromsizeszBedTool.set_chromsizes   sc    $ j#&& 	(3J??DOO
D)) 	(DOO3   r'   c                 l   ||                                  }|rt          j        nt          }|rt          j        nt          }t          |t                    r||j        ru|rt          d          t          |d          5 }|                    t          | j        d          	                                           ddd           n# 1 swxY w Y   |S t          |t                    rt          |j        t                    r ||d          5 }t          j        dk    r ||j        dd	          }	n ||j        d          }	|r*|                    |                                d
z              |                    |	           |	                                 ddd           n# 1 swxY w Y   n ||d          5 }|D ]\}
t          |
t           t"          f          rt%          t!          |
                    }
|                    t          |
                     ]	 ddd           n# 1 swxY w Y   |S )a  
        Collapses an iterable into file *fn* (or a new tempfile if *fn* is
        None).

        Returns the newly created filename.

        Parameters
        ----------

        iterable : iter
            Any iterable object whose items can be converted to an Interval.

        fn : str
            Output filename, if None then creates a temp file for output

        trackline : str
            If not None, string to be added to the top of the output. Newline
            will be added.

        in_compressed : bool
            Indicates whether the input is compressed

        out_compressed : bool
            Indicates whether the output should be compressed
        NzFtrackline provided, but input is a BAM file, which takes no track linewbrbwt)r)   r   rt  ignore)errorsrO   )rf   rx  r,   r*   r@   rc   r0   r   rd   r-   r+   sysversion_infor   
writelinesr   r6   r   r   )rk   rB   rd   	tracklinein_compressedout_compressedin_open_funcout_open_funcout_in_r$   s              r%   	_collapsezBedTool._collapse=  s   B :B$1;tyyt%3=		 h(( 	X_ 	  6   b$ 74

4..33556667 7 7 7 7 7 7 7 7 7 7 7 7 7 7I h(( 	'ZS-I-I 	'r4(( D#e++&,x{DJJJCC&,x{D99C 9JJy0047888$$$		               r4(( 'D! ' 'A!!dE]33 ?5d1gg>>JJs1vv&&&&'' ' ' ' ' ' ' ' ' ' ' ' ' ' '
 	s8   >;CC	C	BF$$F(+F(<A H))H-0H-c                 0   t           j                            dt          j        |                     d}dddddddd}d}	 | j        rt          |         }nt          |         }||         }t          |t                    r|j
        }t          |t                    r|||<   d}nd||<   d |D             }n# t          $ r Y nw xY w	 t          |         }	||	         }
t          |
t                    r|
j
        }
t          |
t                    r|
||	<   nt          |
t          t          f          rrt          |
d         t                    rW	 t!          |
d                             d	                    }|                     |
          ||	<   n-# t&          $ r |
||	<   Y nw xY w|                     |
          ||	<   n# t          $ r Y nw xY w|                    d
d          rd}n/|                    dd          }|r|}n|                                 }|                    dd          }|g}|g }|D ]H}||v rB|                    |          }|                    d|z              |                    |           It/          t          |                                          d          D ]O\  }}t          |t2                    r|r|                    d|z              67t          |t                    st          |t                    rt          t5          t          |                    }	 ||         }n# t          $ r |}Y nw xY w|dk    r.|                    d|z              |                    |           |                    d|z              |                    |                    |                     |                    d|z              |                    t          |                     Q|r|                    |           |||fS )ak  
        Handle most cases of BEDTool program calls, but leave the specifics
        up to individual methods.

        *prog* is a BEDTools program name, e.g., 'intersectBed'.

        *arg_order* lists any arguments that are sensitive to order. Everything
        else will be reverse-sorted.

        *kwargs* are passed directly from the calling method (like
        self.intersect).

        This method figures out, given how this BedTool was constructed, what
        to send to BEDTools programs -- for example, an open file to stdin with
        the `-` argument, or a filename with the `-a` argument.
        z,BedTool.handle_kwargs() got these kwargs:
%sr  ,)annotateBed
getOverlapgroupBymultiIntersectBedmergeBedintersectBedmapBedNr_   c              3   4   K   | ]}t          |          V  d S rT   r  r"   s     r%   r2  z(BedTool.handle_kwargs.<locals>.<genexpr>  s(      33AQ333333r'   r   rQ   rq   outputadditional_argsrP  Tr   )r  loggerdebugpprintpformatrc   r   r   r*   r@   rd   r+   KeyErrorr   r6   r   r   r2   r  
IndexErrorpoprf   rA   r   rh   boolr   extendr/   )rk   r\   r]   r9   default_list_delimiterlist_delimitersr_   inarg1	instream1inarg2	instream2rN   rn   r  r  rm   argvalr  rt   delims                        r%   rg   zBedTool.handle_kwargs  s   " 	;V^F=S=S	
 	
 	

 "%!$
 
 	{ 2&t,+D1 vI )W-- )%L	 )S)) 4!*v ")v33333 	 	 	D	
+	$T*F vI )W-- )%L	 )S)) ;!*v Ie}55 ;*!c; ; ;/1)A,2D2DT2J2JKKA%)^^I%>%>F6NN! / / /%.F6NNN/ "&	!:!:v 	 	 	D	 ::h%% 	"CCZZ$//F "iikk **%6== v I 	! 	!Cf}}jjooC#I&&&C    !fllnn!5!5tDDD 	( 	(JC%&& ( KKc	****E4(( (Jue,D,D (Se__--3+D1EE 3 3 32EEE3 C<<KKc	***KK&&&& KKc	***KK

5 1 12222 C#I&&&CJJ'''' 	)KK(((S%s]   A4B7 7
CCBF; A F F; FF; FF; ;
GG/L88MMc                 J   d|vr.d|vr*t          | d          r| j        |d<   nt          d          d|v rd|v rt          d          d|vr^d|v rZt          |d         t                    r	|d         }nt          j        |d                   }t          j        |          }||d<   |d= t          |d         t                    rt          j        |d                   |d<   t          j        	                    |d                   sd|d         z  }t          |          |S )z
        Handles the different ways of specifying a genome in kwargs:

        g='genome.file' specifies a file directly
        genome='dm3' gets the file from genome registry
        self.chromsizes could be a dict.        rZ   r[   r   zXNo genome specified. Use the "g" or "genome" kwargs, or use the .set_chromsizes() methodz$Cannot specify both "g" and "genome"zGenome file "%s" does not exist)r.   r   r0   r*   r5   r  chromsizes_to_filer   r   r   r   )rk   r9   genome_dictgenome_filer   s        r%   re   zBedTool.check_genome1  sP    vHF$:$:t\** "os /   &==X//CDDD fV!3!3&*D11 F$X.(3F84DEE$7DDK%F3Kx 
 fSk4(( 	E$7sDDF3Kw~~fSk** 	)3vc{CC#C(((r'   c                 j   |                                  }t          |d          }t          | j        t                    r#t          t          | j        d                    n6|                                 }t          t          |j        d                    fd}t           |                      S )a  
        Remove invalid features that may break BEDTools programs.

        >>> a = pybedtools.BedTool("chr1 10 100\nchr1 10 1",
        ... from_string=True)
        >>> print(a.remove_invalid()) #doctest: +NORMALIZE_WHITESPACE
        chr1	10	100
        <BLANKLINE>

        r   ru  c               3      K   	 	 t                    } | j        | j        k    r| V  n'n7# t          j        $ r Y 9t
          $ r Y Dt          $ r Y Ot          $ r Y d S w xY w_rT   )r   r   r   r  MalformedBedLineErrorOverflowErrorr  rb  )featurer$   s    r%   r>  z*BedTool.remove_invalid.<locals>._generatorw  s      "1ggG}44%  & "7   H$   H!   H$   EEs    $, A 	A 	A 	A A )rf   r,   r*   rd   r+   r   r   r@   )rk   rn   r   r>  r$   s       @r%   remove_invalidzBedTool.remove_invalid`  s     iikkC~~ dgs## 	4 dgs!3!344AA++--C cfc!2!233A	 	 	 	 	$ zz||$$$r'           c                 J   t          |t                    st          d          | j        }t          |t                    s|                                 j        }| j        r|                                 j        }t          j	        |          }|
                    |||          S )a  
        Return all intervals that overlap `interval`.

        Calls the `all_hits` method of an IntervalFile to return all intervals
        in this current BedTool that overlap `interval`.

        Require that overlaps have the same strand with same_strand=True.

        Notes:
                If this current BedTool is generator-based, it will be
                converted into a file first.

                If this current BedTool refers to a BAM file, it will be
                converted to a BED file first using default arguments.  If you
                don't want this to happen, please convert to BED first before
                using this method.
        Need an Interval instance)r*   r   r0   rd   r+   r   rc   
bam_to_bedr  r   all_hitsrk   r   rL  overlaprd   interval_files         r%   r  zBedTool.all_hits      $ (H-- 	:8999W"c"" 	"!B; 	&""%B"/33%%hWEEEr'   c                 J   t          |t                    st          d          | j        }t          |t                    s|                                 j        }| j        r|                                 j        }t          j	        |          }|
                    |||          S )a  
        Return whether or not any intervals overlap `interval`.

        Calls the `any_hits` method of an IntervalFile.  If there were any hits
        within `interval` in this BedTool, then return 1; otherwise 0.

        Require that overlaps have the same strand with same_strand=True.

        Notes:
                If this current BedTool is generator-based, it will be
                converted into a file first.

                If this current BedTool refers to a BAM file, it will be
                converted to a BED file first using default arguments.  If you
                don't want this to happen, please convert to BED first before
                using this method.
        r  )r*   r   r0   rd   r+   r   rc   r  r  r   any_hitsr  s         r%   r  zBedTool.any_hits  r  r'   c                 J   t          |t                    st          d          | j        }t          |t                    s|                                 j        }| j        r|                                 j        }t          j	        |          }|
                    |||          S )a  
        Return the number of intervals that overlap `interval`.

        Calls the `count_hits` method of an IntervalFile.  Returns the number
        of valid hits in this BedTool that overlap `interval`.

        Require that overlaps have the same strand with same_strand=True.

        Notes:
                If this current BedTool is generator-based, it will be
                converted into a file first.

                If this current BedTool refers to a BAM file, it will be
                converted to a BED file first using default arguments.  If you
                don't want this to happen, please convert to BED first before
                using this method.
        r  )r*   r   r0   rd   r+   r   rc   r  r  r   
count_hitsr  s         r%   r  zBedTool.count_hits  s    $ (H-- 	:8999W"c"" 	"!B; 	&""%B"/33''+wGGGr'   bed12ToBed6r$   )r\   r}   rw   r   c                     dS )z/
        Wraps `bedtools bed12tobed6`.
        Nr!   rk   r9   s     r%   rS  zBedTool.bed6  s	     	r'   bamToBedr^   )r\   r}   r   r   rw   c                     dS )z,
        Wraps `bedtools bamtobed`.
        Nr!   r  s     r%   r  zBedTool.bam_to_bed        r'   bedToBam)r\   r}   r   ry   c                     dS )z
        Wraps bedToBam and is called internally for BED/GFF/VCF files by
        self.to_bam (which needs to do something different for SAM files...)
        Nr!   r  s    r%   _bed_to_bamzBedTool._bed_to_bam  r  r'   c           
         | j         dk    r| S | j         dv r | j        di |S | j         dk    r | j        di |}t          d t	          |d                   D                       }g }i }dg}t          |                                          D ]g\  }\  }}|                    t          |t          |                               |||<   |                    d	                    ||                     hd	d
i|d}	d
                    |          dz   }|                                 }
|                                 }t	          |
d          5 }|                    |           | D ]E}|                    d
                    t          t          |j                            dz              F	 ddd           n# 1 swxY w Y   t!          j        |
d          }t!          j        |d|          }|D ]}|                    |           |                                 |                                 t'          |          }d|_        |S dS )z
        Wraps `bedtools bedtobam`

        If self.fn is in BED/VCF/GFF format, call BEDTools' bedToBam.  If
        self.fn is in SAM format, then create a header out of the genome file
        and then convert using `samtools`.
        rw   )rH  rC  vcfsamc              3   >   K   | ]}|                                 V  d S rT   )r2   r"   s     r%   r2  z!BedTool.to_bam.<locals>.<genexpr>  s*      ??!''))??????r'   rZ   z
@HD	VN:1.0)SNLNz@SQ	SN:{0}	LN:{1}VNz1.0)HDSQrO   r   rQ   Nru  r  )templateTr!   )r  r  re   r5   r,   rT  rh   rA   r3   rw  r/   rf   r   r   r+   r8  r   AlignmentFiler   r@   rc   )rk   r9   r[   r  ref_idstext_headerr$   r   r   r;   sam_tmpbam_tmpr   r   samfilebamfile	alignmentnew_bedtools                     r%   to_bamzBedTool.to_bam  s    >U""K>222#4#--f--- >U"" 'T&0000F ??T&+->->?????FBG(/K&v||~~66 G G	6Aq		$!A///000
""#8#?#?1#E#EFFFF "5M44F ))K0047K iikkGiikkGgs## Lt

;''' $ L LHJJtyyS(/)B)BCCdJKKKKLL L L L L L L L L L L L L L L
 )'377G)'4'JJJG$ ) )	i((((MMOOOMMOOO!'**K!%K] #"s   AF;;F?F?r  ababamrH  )r\   r}   r   rw   r   r]   c                     dS )z-
        Wraps `bedtools intersect`.
        Nr!   r  s    r%   r   zBedTool.intersect>  r  r'   fastaFromBedfifoseqfn)r\   r}   rw   r   r~   r`   rv   c                     dS )a  
        Wraps `bedtools getfasta`.

        *fi* is passed in by the user; *bed* is automatically passed in as the
        bedfile of this object; *fo* by default is a temp file.  Use
        save_seqs() to save as a file.

        The end result is that this BedTool will have an attribute, self.seqfn,
        that points to the new fasta file.

        Example usage:

        >>> a = pybedtools.BedTool("""
        ... chr1 1 10
        ... chr1 50 55""", from_string=True)
        >>> fasta = pybedtools.example_filename('test.fa')
        >>> a = a.sequence(fi=fasta)
        >>> print(open(a.seqfn).read())
        >chr1:1-10
        GATGAGTCT
        >chr1:50-55
        CCATC
        <BLANKLINE>

        Nr!   r  s    r%   sequencezBedTool.sequenceF  r  r'   c                    t          | t                    rV|                     d          \  }}t          t	          t
          |                    d                              \  }}|dz  }n| d         | d         | d         }}}t          d|||fz  d          } |                     |	          }d
                    d t          |j
        d          D                       S )a
  
        Return just the sequence from a region string or a single location
        >>> fn = pybedtools.example_filename('test.fa')
        >>> BedTool.seq('chr1:2-10', fn)
        'GATGAGTCT'
        >>> BedTool.seq(('chr1', 1, 10), fn)
        'GATGAGTCT'
        r   rP  r   r   r(   z%s	%i	%iTr  )r  r   c                 N    g | ]"}|d          dk    |                                 #S )r   >)rstrip)r#   ls     r%   r&   zBedTool.seq.<locals>.<listcomp>  s)    QQQqQqTS[[

[[[r'   ru  )r*   r+   r2   r6   r   r3   r@   r  r/   r,   r
  )locfastar   	start_endr   r   lseqs          r%   seqzBedTool.seqn  s     c3 	7"yy~~E9c#ys';';<<==JE3QJEE #AAA#5EleUC%88dKKK||u|%%wwQQDS,A,AQQQRRRr'   nucBed)r\   r}   r   r`   c                     dS )z
        Wraps `bedtools nuc`.

        Profiles nucleotide content.  The returned BED file contains extra
        information about the nucleotide content
        Nr!   r  s    r%   nucleotide_contentzBedTool.nucleotide_content  r  r'   multiBamCov)r\   r}   c                     dS )zk
        Wraps `bedtools multicov`.

        Pass a list of sorted and indexed BAM files as `bams`
        Nr!   r  s    r%   multi_bam_coveragezBedTool.multi_bam_coverage  r  r'   subtractBed)r\   r}   r   rw   c                     t           t          d<   dt          vr| j        t          d<    | j        dddit          \  }}}t	          |||          }t          |          S )a  
        Wraps `bedtools subtract`.

        Subtracts from another BED file and returns a new BedTool object.

        Example usage:

            >>> a = pybedtools.example_bedtool('a.bed')
            >>> b = pybedtools.example_bedtool('b.bed')

            Do a "stranded" subtraction:

            >>> c = a.subtract(b, s=True)

            Require 50% of features in `a` to overlap:

            >>> c = a.subtract(b, f=0.5)
        r  r  r\   r  r_   r!   )r  r9   rd   rg   r
   r@   )rk   rm   rn   r_   rq   s        r%   subtractzBedTool.subtract  sg    * sf'F3K-4-KK=KFKKc5tS666vr'   slopBed)r\   r}   r   rw   r   c                     dS )z(
        Wraps `bedtools slop`.
        Nr!   r  s    r%   slopzBedTool.slop  r  r'   shiftBedc                     dS )a>  
        Wraps `bedtools shift`.

        Shift each feature by user-defined number of bases. Returns a new BedTool object.

        Example usage:

            >>> a = pybedtools.example_bedtool('a.bed')

            Shift every feature by 5bp:

            >>> b = a.shift(genome='hg19', s=5)
            >>> print(b) #doctest: +NORMALIZE_WHITESPACE
            chr1	6	105	feature1	0	+
            chr1	105	205	feature2	0	+
            chr1	155	505	feature3	0	-
            chr1	905	955	feature4	0	+
            <BLANKLINE>

            Shift features on the '+' strand by -1bp and on '-' strand by +3bp:

            >>> b = a.shift(genome='hg19', p=-1, m=3)
            >>> print(b) #doctest: +NORMALIZE_WHITESPACE
            chr1	0	99	feature1	0	+
            chr1	99	199	feature2	0	+
            chr1	153	503	feature3	0	-
            chr1	899	949	feature4	0	+
            <BLANKLINE>

            # Disabling, see https://github.com/arq5x/bedtools2/issues/807
            Shift features by a fraction of their length (0.50):

            #>>> b = a.shift(genome='hg19', pct=True, s=0.50)
            #>>> print(b) #doctest: +NORMALIZE_WHITESPACE
            #chr1	50	149	feature1	0	+
            #chr1	150	250	feature2	0	+
            #chr1	325	675	feature3	0	-
            #chr1	925	975	feature4	0	+
            #<BLANKLINE>

        Nr!   r  s    r%   shiftzBedTool.shift  r  r'   r  c                     dS )aS  
        Wraps `bedtools merge`.

        Merge overlapping features together. Returns a new BedTool object.

        Example usage:

            >>> a = pybedtools.example_bedtool('a.bed')

            Merge:

            >>> c = a.merge()

            Allow merging of features 500 bp apart:

            >>> c = a.merge(d=500)

        Nr!   r  s    r%   mergezBedTool.merge  r  r'   
closestBedc                     dS )a  
        Wraps `bedtools closest`.

        Return a new BedTool object containing closest features in *b*.  Note
        that the resulting file is no longer a valid BED format; use the
        special "_closest" methods to work with the resulting file.

        Example usage::

            a = BedTool('in.bed')

            # get the closest feature in 'other.bed' on the same strand
            b = a.closest('other.bed', s=True)

        Nr!   r  s    r%   closestzBedTool.closest  r  r'   	windowBed)r\   r}   r   rw   r   c                     dS )a  
        Wraps `bedtools window`.

        Example usage::

            >>> a = pybedtools.example_bedtool('a.bed')
            >>> b = pybedtools.example_bedtool('b.bed')
            >>> print(a.window(b, w=1000)) #doctest: +NORMALIZE_WHITESPACE
            chr1	1	100	feature1	0	+	chr1	155	200	feature5	0	-
            chr1	1	100	feature1	0	+	chr1	800	901	feature6	0	+
            chr1	100	200	feature2	0	+	chr1	155	200	feature5	0	-
            chr1	100	200	feature2	0	+	chr1	800	901	feature6	0	+
            chr1	150	500	feature3	0	-	chr1	155	200	feature5	0	-
            chr1	150	500	feature3	0	-	chr1	800	901	feature6	0	+
            chr1	900	950	feature4	0	+	chr1	155	200	feature5	0	-
            chr1	900	950	feature4	0	+	chr1	800	901	feature6	0	+
            <BLANKLINE>
        Nr!   r  s    r%   windowzBedTool.window  r  r'   
shuffleBedc                     dS )a  
        Wraps `bedtools shuffle`.

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> seed = 1 # so this test always returns the same results
        >>> b = a.shuffle(genome='hg19', chrom=True, seed=seed)
        >>> print(b) #doctest: +NORMALIZE_WHITESPACE
        chr1	123081365	123081464	feature1	0	+
        chr1	243444570	243444670	feature2	0	+
        chr1	194620241	194620591	feature3	0	-
        chr1	172792873	172792923	feature4	0	+
        <BLANKLINE>
        Nr!   r  s    r%   shufflezBedTool.shuffle/  r  r'   sortBedrZ   r[   )r\   r}   r   rz   c                     dS )a  
        Wraps `bedtools sort`.

        Note that chromosomes are sorted lexograpically, so chr12 will come
        before chr9.

        Example usage:

        >>> a = pybedtools.BedTool('''
        ... chr9 300 400
        ... chr1 100 200
        ... chr1 1 50
        ... chr12 1 100
        ... chr9 500 600
        ... ''', from_string=True)
        >>> print(a.sort()) #doctest: +NORMALIZE_WHITESPACE
        chr1	1	50
        chr1	100	200
        chr12	1	100
        chr9	300	400
        chr9	500	600
        <BLANKLINE>
        Nr!   r  s    r%   r  zBedTool.sortB  r  r'   r  c                     dS )a  
        Wraps  `bedtools annotate`.

        Annotate this BedTool with a list of other files.
        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b_fn = pybedtools.example_filename('b.bed')
        >>> print(a.annotate(files=b_fn)) #doctest: +NORMALIZE_WHITESPACE
        chr1	1	100	feature1	0	+	0.000000
        chr1	100	200	feature2	0	+	0.450000
        chr1	150	500	feature3	0	-	0.128571
        chr1	900	950	feature4	0	+	0.020000
        <BLANKLINE>
        Nr!   r  s    r%   annotatezBedTool.annotate]  r  r'   flankBed)r\   r}   r   c                      | j         di |}d|vr
| j        |d<    | j        dddi|\  }}}t          |||          }t	          |          S )a  
        Wraps `bedtools flank`.

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> print(a.flank(genome='hg19', b=100)) #doctest: +NORMALIZE_WHITESPACE
        chr1	0	1	feature1	0	+
        chr1	100	200	feature1	0	+
        chr1	0	100	feature2	0	+
        chr1	200	300	feature2	0	+
        chr1	50	150	feature3	0	-
        chr1	500	600	feature3	0	-
        chr1	800	900	feature4	0	+
        chr1	950	1050	feature4	0	+
        <BLANKLINE>

        r$   r\   r6  r  r!   )re   rd   rg   r
   r@   )rk   r9   rm   rn   r_   rq   s         r%   flankzBedTool.flankp  sv    * #",,V,,f'F3K-4-HH:HHHc5tS666vr'   genomeCoverageBedibam)r\   r}   rw   r{   r|   r   r   c                     dS )a  
        Wraps `bedtools genomecov`.

        Note that some invocations of `bedtools genomecov` do not result in
        a properly-formatted BED file. For example, the default behavior is to
        report a histogram of coverage. Iterating over the resulting,
        non-BED-format file will raise exceptions in pybedtools' parser.

        Consider using the `BedTool.to_dataframe` method to convert these
        non-BED files into a pandas DataFrame for further use.

        Example usage:

        BAM file input does not require a genome:

        >>> a = pybedtools.example_bedtool('x.bam')
        >>> b = a.genome_coverage(bg=True)
        >>> b.head(3) #doctest: +NORMALIZE_WHITESPACE
        chr2L	9329	9365	1
        chr2L	10212	10248	1
        chr2L	10255	10291	1

        Other input does require a genome:

        >>> a = pybedtools.example_bedtool('x.bed')
        >>> b = a.genome_coverage(bg=True, genome='dm3')
        >>> b.head(3) #doctest: +NORMALIZE_WHITESPACE
        chr2L	9329	9365	1
        chr2L	10212	10248	1
        chr2L	10255	10291	1

        Non-BED format results:
        >>> a = pybedtools.example_bedtool('x.bed')
        >>> b = a.genome_coverage(genome='dm3')
        >>> df = b.to_dataframe(names=['chrom', 'depth', 'n', 'chromsize', 'fraction'])
        Nr!   r  s    r%   genome_coveragezBedTool.genome_coverage  r  r'   coverageBedc                     dS )a  
        Wraps `bedtools coverage`.

        Note that starting in version 2.24.0, BEDTools swapped the semantics of
        the "a" and "b" files.

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b = pybedtools.example_bedtool('b.bed')
        >>> c = b.coverage(a)
        >>> c.head(3) #doctest: +NORMALIZE_WHITESPACE
        chr1	155	200	feature5	0	-	2	45	45	1.0000000
        chr1	800	901	feature6	0	+	1	1	101	0.0099010
        Nr!   r  s    r%   coveragezBedTool.coverage  r  r'   maskFastaFromBed)r\   r}   r   r~   rv   r`   c                     dS )a  
        Wraps `bedtools maskfasta`.

        Masks a fasta file at the positions in a BED file and saves result as
        'out' and stores the filename in seqfn.

        >>> a = pybedtools.BedTool('chr1 100 110', from_string=True)
        >>> fasta_fn = pybedtools.example_filename('test.fa')
        >>> a = a.mask_fasta(fi=fasta_fn, fo='masked.fa.example')
        >>> b = a.slop(b=2, genome='hg19')
        >>> b = b.sequence(fi=a.seqfn)
        >>> print(open(b.seqfn).read())
        >chr1:98-112
        TTNNNNNNNNNNAT
        <BLANKLINE>
        >>> os.unlink('masked.fa.example')
        >>> if os.path.exists('masked.fa.example.fai'):
        ...     os.unlink('masked.fa.example.fai')
        Nr!   r  s    r%   
mask_fastazBedTool.mask_fasta  r  r'   complementBedc                     dS )a=  
        Wraps `bedtools complement`.
        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> a.complement(genome='hg19').head(5) #doctest: +NORMALIZE_WHITESPACE
        chr1	0	1
        chr1	500	900
        chr1	950	249250621
        chr2	0	243199373
        chr3	0	198022430
        Nr!   r  s    r%   
complementzBedTool.complement  r  r'   r  c                     dS )a  
        Wraps `bedtools overlap`.

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b = pybedtools.example_bedtool('b.bed')
        >>> c = a.window(b, w=10).overlap(cols=[2,3,8,9])
        >>> print(c) #doctest: +NORMALIZE_WHITESPACE
        chr1	100	200	feature2	0	+	chr1	155	200	feature5	0	-	45
        chr1	150	500	feature3	0	-	chr1	155	200	feature5	0	-	45
        chr1	900	950	feature4	0	+	chr1	800	901	feature6	0	+	1
        <BLANKLINE>
        Nr!   r  s    r%   r  zBedTool.overlap	  r  r'   	pairToBedbedpec                     dS )z-
        Wraps `bedtools pairtobed`.
        Nr!   r  s    r%   pair_to_bedzBedTool.pair_to_bed	  r  r'   
pairToPair)r\   r}   r   c                     dS )z.
        Wraps `bedtools pairtopair`.
        Nr!   r  s    r%   pair_to_pairzBedTool.pair_to_pair"	  r  r'   r  c                     dS )aC  
        Wraps `bedtools groupby`.

        Example usage:

        >>> a = pybedtools.example_bedtool('gdc.gff')
        >>> b = pybedtools.example_bedtool('gdc.bed')
        >>> c = a.intersect(b, c=True)
        >>> d = c.groupby(g=[1, 4, 5], c=10, o=['sum'])
        >>> print(d) #doctest: +NORMALIZE_WHITESPACE
        chr2L	41	70	0
        chr2L	71	130	2
        chr2L	131	170	4
        chr2L	171	200	0
        chr2L	201	220	1
        chr2L	41	130	2
        chr2L	171	220	1
        chr2L	41	220	7
        chr2L	161	230	6
        chr2L	41	220	7
        <BLANKLINE>

        Nr!   r  s    r%   groupbyzBedTool.groupby,	  r  r'   tagBam)r\   r}   rw   c                     dS )zd
        Wraps `bedtools tag`.

        `files` and `labels` should lists of equal length.

        Nr!   r  s    r%   tag_bamzBedTool.tag_bamG	  r  r'   r  c                     dS )zG
        Wraps  `bedtools map`; See also :meth:`BedTool.each`.
        Nr!   r  s    r%   r   zBedTool.mapT	  r  r'   r  r6  )r\   r   rz   c                     dS )a  
        Wraps `bedtools multiintersect`.

        Provide a list of filenames as the "i" argument. e.g. if you already
        have BedTool objects then use their `.fn` attribute, like this::

            >>> x = pybedtools.BedTool()
            >>> a = pybedtools.example_bedtool('a.bed')
            >>> b = pybedtools.example_bedtool('b.bed')
            >>> result = x.multi_intersect(i=[a.fn, b.fn])
            >>> print(result)   #doctest: +NORMALIZE_WHITESPACE
            chr1	1	155	1	1	1	0
            chr1	155	200	2	1,2	1	1
            chr1	200	500	1	1	1	0
            chr1	800	900	1	2	0	1
            chr1	900	901	2	1,2	1	1
            chr1	901	950	1	1	1	0
            <BLANKLINE>

        Nr!   r  s    r%   multi_intersectzBedTool.multi_intersect[	  r  r'   	randomBed)r\   r   c                     dS )a  
        Wraps `bedtools random`.

        Since this method does not operate on an existing file, create
        a BedTool with no arguments and then call this method, e.g.,

        >>> x = BedTool()
        >>> y = x.random(l=100, n=10, genome='hg19')
        Nr!   r  s    r%   r   zBedTool.randomv	  r  r'   
bedpeToBam)r}   r   ry   c                     dS )z.
        Wraps `bedtools bedpetobam`.
        Nr!   r  s    r%   bedpe_to_bamzBedTool.bedpe_to_bam	  r  r'   
clusterBedc                     dS )z,
        Wraps  `bedtools cluster`.
        Nr!   r  s    r%   clusterzBedTool.cluster	  r  r'   unionBedGraphs)r\   c                     dS )z
        Wraps `bedtools unionbedg`.

        Warning: using the `header=True` kwarg will result in a file that is
        not in true BED format, which may break downstream analysis.
        Nr!   r  s    r%   union_bedgraphszBedTool.union_bedgraphs	  r  r'   windowMakerr   )r\   r   r{   r   r]   c                     dS )z/
        Wraps `bedtools makewindows`.
        Nr!   r  s    r%   window_makerzBedTool.window_maker	  r  r'   
expandColsc                     dS )z)
        Wraps `bedtools expand`
        Nr!   r  s    r%   expandzBedTool.expand	  r  r'   linksBedrL   
links_html)r\   r}   rv   c                     dS )z
        Wraps `linksBed`.

        The resulting BedTool will have a new attribute `links_html`.  This
        attribute is a temp filename containing the HTML links.
        Nr!   r  s    r%   linkszBedTool.links	  r  r'   bedToIgv
igv_scriptc                     dS )z
        Wraps `bedtools igv`.

        The resulting BedTool will have a new attribute `igv_script`.  This
        attribute is a temp filename containing the IGV script.
        Nr!   r  s    r%   igvzBedTool.igv	  r  r'   
bamToFastqfqfastq)r\   r}   rw   r~   rv   c                     dS )z
        Wraps `bedtools bamtofastq`.

        The `fq` argument is required.

        The resulting BedTool will have a new attribute, `fastq`.
        Nr!   r  s    r%   bam_to_fastqzBedTool.bam_to_fastq	  r  r'   jaccard)r\   r}   r   rx   c                     dS )zP
        Returns a dictionary with keys (intersection, union, jaccard).
        Nr!   r  s    r%   rt  zBedTool.jaccard	  r  r'   rE   c                     dS )a  
        If detail=False, then return a dictionary with keys (reldist, count,
        total, fraction), which is the summary of the bedtools reldist.

        Otherwise return a BedTool, with the relative distance for each
        interval in A in the last column.
        Nr!   r  s    r%   rE   zBedTool.reldist	  r  r'   samplec                     dS )z!
        Wraps 'sample'.
        Nr!   r  s    r%   rw  zBedTool.sample	  r  r'   fisher)r\   r}   r   r   rx   c                     dS )a  
        Wraps 'fisher'. Returns an object representing the output.

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b = pybedtools.example_bedtool('b.bed')
        >>> f = a.fisher(b, genome='hg19')
        >>> print(f)  # doctest: +NORMALIZE_WHITESPACE
        # Number of query intervals: 4
        # Number of db intervals: 2
        # Number of overlaps: 3
        # Number of possible intervals (estimated): 13958448
        # phyper(3 - 1, 4, 13958448 - 4, 2, lower.tail=F)
        # Contingency Table Of Counts
        #_________________________________________
        #           |  in -b       | not in -b    |
        #     in -a | 3            | 1            |
        # not in -a | 0            | 13958444     |
        #_________________________________________
        # p-values for fisher's exact test
        left	right	two-tail	ratio
        1	8.8247e-21	8.8247e-21	inf
        <BLANKLINE>


        >>> f.table['not in -a']['in -b']
        0

        >>> f.table['not in -a']['not in -b']
        13958444

        >>> f.table['in -a']['in -b']
        3

        >>> f.table['in -a']['not in -b']
        1

        >>> f.two_tail
        8.8247e-21
        Nr!   r  s    r%   ry  zBedTool.fisher	  r  r'   r2   )r\   r}   rx   c                     dS )a  
        Wraps 'bedtools split'.

        BedTool objects have long had a `split` method which splits intervals
        according to a custom function. Now that BEDTools has a `split` tool,
        the method name conflicts. To maintain backwards compatibility, the
        method wrapping the BEDTools command is called `splitbed`.

        Since this tool does not return a single BED file, the method parses
        the output and returns a SplitOutput object, which includes an
        attribute, `bedtools`, that is a list of BedTool objects created from
        the split files.

        To keep the working directory clean, you may want to consider using
        `prefix=BedTool._tmp()` to get a temp file that will be deleted when
        Python exits cleanly.

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> s = a.splitbed(n=2, p="split")
        >>> assert len(a) == 4, len(a)
        >>> assert len(s.bedtools) == 2
        >>> print(s.bedtools[0]) # doctest: +NORMALIZE_WHITESPACE
        chr1	150	500	feature3	0	-
        <BLANKLINE>
        >>> print(s.bedtools[1]) # doctest: +NORMALIZE_WHITESPACE
        chr1	100	200	feature2	0	+
        chr1	1	100	feature1	0	+
        chr1	900	950	feature4	0	+
        <BLANKLINE>
        Nr!   r  s    r%   splitbedzBedTool.splitbed*
  r  r'   spacingc                     dS )a1  
        Wraps `bedtools spacing`

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> print(a.spacing())  # doctest: +NORMALIZE_WHITESPACE
        chr1	1	100	feature1	0	+	.
        chr1	100	200	feature2	0	+	0
        chr1	150	500	feature3	0	-	-1
        chr1	900	950	feature4	0	+	400
        Nr!   r  s    r%   r}  zBedTool.spacingK
  r  r'   c                     t          | d          st          | d          rt          d | D                       S t          d t          |           D                       S )a  
        Count the number features in this BedTool.

        Number of features in BED file. Does the same thing as len(self), which
        actually just calls this method.

        Only counts the actual features.  Ignores any track lines, browser
        lines, lines starting with a "#", or blank lines.

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> a.count()
        4
        r   r   c              3      K   | ]}d V  dS r   Nr!   r   s     r%   r2  z BedTool.count.<locals>.<genexpr>i
  s"      ''Qq''''''r'   c              3      K   | ]}d V  dS r  r!   r   s     r%   r2  z BedTool.count.<locals>.<genexpr>j
  s"      ))1))))))r'   )r.   sumr   r  s    r%   rF   zBedTool.countX
  sg      4   	(GD*$=$= 	(''$''''''))d4jj))))))r'   c                     t          | d          st          d          t          | j                  }|                                }|                                 |S )z
        Print the sequence that was retrieved by BedTool.sequence.

        See usage example in :meth:`BedTool.sequence`.
        r
  .Use .sequence(fasta) to get the sequence first)r.   r0   r,   r
  r-   r   )rk   r1  r8   s      r%   print_sequencezBedTool.print_sequencel
  sT     tW%% 	OMNNNFFHH				r'   c                 p   t          | d          st          d          t          |d          5 }t          | j                  5 }|                    |                                           ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   t          | j                  }||_        |S )a   
        Save sequences, after calling BedTool.sequence.

        In order to use this function, you need to have called
        the :meth:`BedTool.sequence()` method.

        A new BedTool object is returned which references the newly saved file.

        Example usage:

        >>> a = pybedtools.BedTool('''
        ... chr1 1 10
        ... chr1 50 55''', from_string=True)
        >>> fasta = pybedtools.example_filename('test.fa')
        >>> a = a.sequence(fi=fasta)
        >>> print(open(a.seqfn).read())
        >chr1:1-10
        GATGAGTCT
        >chr1:50-55
        CCATC
        <BLANKLINE>
        >>> b = a.save_seqs('example.fa')
        >>> assert open(b.fn).read() == open(a.fn).read()
        >>> if os.path.exists('example.fa'):
        ...     os.unlink('example.fa')
        r
  r  r   N)r.   r0   r,   r
  r   r-   r@   rd   )rk   rd   r   seqfiler  s        r%   	save_seqszBedTool.save_seqsy
  s!   8 tW%% 	OMNNN"c]] 	+ddj!! +W

7<<>>***+ + + + + + + + + + + + + + +	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ dg&&s5   B(A9-B9A=	=B A=	BBBc                    d|vs|d         ddi|d<   	 ddl n# t          $ r t          d          w xY wfd}t          |t                    rt	          |          }nt          |t                    s
J d            |d         }t           | j        |fi |          }	|s | j        |fd	|i|}
n"|t          d
           | j	        |f||d|}

                    t          |
                    }
                    |
          }t          t          |
                    }t          |
|	k              |z  }t          |
|	k               |z  }|	|z  }d}d}                    |
||g          \  }} ||
|	          }d	|d|	d| j        d|j        | j        t          |           |j        t          |          dt          |           dt          |          d|d|d|d|d|d|z  |d|z  |i}|r|
|d<   n~
|S )a  
        Dictionary of results from many randomly shuffled intersections.

        Sends args and kwargs to :meth:`BedTool.randomintersection` and
        compiles results into a dictionary with useful stats.  Requires
        numpy.

        If `include_distribution` is True, then the dictionary will include the
        full distribution; otherwise, the distribution is deleted and cleaned
        up to save on memory usage.

        This is one possible way of assigning significance to overlaps between
        two files. See, for example:

            Negre N, Brown CD, Shah PK, Kheradpour P, Morrison CA, et al. 2010
            A Comprehensive Map of Insulator Elements for the Drosophila
            Genome. PLoS Genet 6(1): e1000814. doi:10.1371/journal.pgen.1000814

        Example usage:

        Make chromsizes a very small genome for this example:

        >>> chromsizes = {'chr1':(1,1000)}
        >>> a = pybedtools.example_bedtool('a.bed').set_chromsizes(chromsizes)
        >>> b = pybedtools.example_bedtool('b.bed')
        >>> try:
        ...     results = a.randomstats(b, 100, debug=True)
        ... except ImportError:
        ...     pass

        *results* is a dictionary that you can inspect.

        (Note that the following examples are not run as part of the doctests
        to avoid forcing users to install NumPy just to pass tests)

        The actual overlap::

            print(results['actual'])
            3

        The median of all randomized overlaps::

            print(results['median randomized'])
            2.0

        The percentile of the actual overlap in the distribution of randomized
        overlaps, which can be used to get an empirical p-value::

            print(results['percentile'])
            90.0
        intersect_kwargsNr  Tr   z"Need to install NumPy for stats...c           	      :                        |           } t          |           }                    | |k              sS                    | |          }                      t	          t          t          |                                         }n?                     t	          t          t          |                                         dz   }                    |           } t          | |k    g          }                    ||                   |z  dz  }|S )zn
            copied from scipy.stats.percentileofscore, to avoid dependency on
            scipy.
            g      ?g      Y@)	arrayrb   anyrA   r6   r   r  r   mean)r  scorer9  a_lenidxpctnps         r%   percentileofscorez.BedTool.randomstats.<locals>.percentileofscore
  s    
 AAAFF1:&& <IIa''eCFFmm!4!455eCFFmm!4!455;

Ae%%C775:&&*e3CJr'   4Either filename or another BedTool instance required
iterationszK`genome_fn` must be provided if using the new _randomintersection mechanism)r  	genome_fng      @g     `X@actualfile_afile_brk   r   zfrac randomized above actualzfrac randomized below actualzmedian randomized
normalized
percentilez
lower_%sthz
upper_%sthdistribution)numpyr   r*   r+   r@   rb   r   randomintersectionr0   _randomintersectionr  r6   medianr4   r  r  rd   )rk   r   r  newr  include_distributionr9   r  i_kwargsr  r  	med_countr9  
frac_above
frac_belowr  lower_threshupper_threshr  upperactual_percentilerI   r  s                         @r%   randomstatszBedTool.randomstats
  s   x f,,&9K2L2T*-tF%&	D 	D 	D 	DBCCC	D	 	 	 	 	& eS!! 	FENNEEw  F FEF F F
 ,-^T^E66X6677
  	242 ",06 LL
   8   443",	 EK L xx\ 2 233 IIl++	#l##$$.//!3
.//!3
i'
}}\L,3OPPu--lFCC*fdgehGSYYHc%jjCIISZZ*J*J*+<'<'
"   	 ,Ans    5c                      | j         |i |S )zR
        For backwards compatibility; see BedTool.parallel_apply instead.
        )parallel_apply)rk   rV   r9   s      r%   	random_opzBedTool.random_op;  s     #t"D3F333r'   r   c              #   J  K   |dk    r#t          |          D ]} i V  t          |r|nt          j        |          ||z  g|z  }|dxx         ||z  z  cc<   fdt          |          D             }	|	D ]}
|
                                V  t          )aD  
        Generalized method for applying a function in parallel.

        Typically used when having to do many random shufflings.

        `func_args` and `func_kwargs` will be passed to `func` each time in
        `iterations`, and these iterations will be split across `processes`
        processes.

        Notes on the function, `func`:

            * the function should manually remove any tempfiles created.  This
              is because the BedTool.TEMPFILES list of auto-created tempfiles
              does not share state across processes, so things will not get
              cleaned up automatically as they do in a single-process
              pybedtools session.

            * this includes deleting any "chromsizes" or genome files --
              generally it will be best to require a genome filename in
              `func_kwargs` if you'll be using any BedTool methods that accept
              the `g` kwarg.

            * the function should be a module-level function (rather than a
              class method) because class methods can't be pickled across
              process boundaries

            * the function can have any signature and have any return value

        `_orig_pool` can be a previously-created multiprocessing.Pool instance;
        otherwise, a new Pool will be created with `processes`
        r   c                 >    g | ]}                               S r!   )apply_async)r#   itr   	func_argsfunc_kwargsr   s     r%   r&   z*BedTool.parallel_apply.<locals>.<listcomp>u  s6     
 
 
<>AMM$	;77
 
 
r'   )r   rb  multiprocessingPoolget)rk   r  r   r  r  	processes
_orig_poolr  iterations_eachrC   ru  r   s     ```      @r%   r  zBedTool.parallel_applyA  s     D >>J'' 6 6dI5555555 	0AA$Y//A%	12Y>zI55
 
 
 
 
 
 
BG
BSBS
 
 
  	 	A%%''MMMMr'   c                     |i }|i }|st          d          t          |                     |t          j        j        | |ft          |||          ||                    S )a  
        Computes the naive Jaccard statistic (intersection divided by union).

        .. note::

            If you don't need the randomization functionality of this method,
            you can use the simpler BedTool.jaccard method instead.

        See Favorov et al. (2012) PLoS Comput Biol 8(5): e1002529 for more
        info on the Jaccard statistic for intersections.

        If `iterations` is None, then do not perform random shufflings.

        If `iterations` is an integer, perform `iterations` random shufflings,
        each time computing the Jaccard statistic to build an empirical
        distribution.  `genome_fn` will also be needed; optional `processes`
        will split the iteations across multiple CPUs.

        Returns a tuple of the observed Jaccard statistic and a list of the
        randomized statistics (which will be an empty list if `iterations` was
        None).
        N8Need a genome filename in order to perform randomization)r  shuffle_kwargsjaccard_kwargsr  r   r  r  r  r  )r0   r6   r  r  statsrandom_jaccardr5   )rk   r   r  r  r  r  r  r  s           r%   r  zBedTool.random_jaccard|  s    @ !N!N 	YWXXX%%4- '#1#1  
 $%    
 
 	
r'   c                     |i }|t          d          }|st          d          t          |                     |t          j        j        | |ft          |||          ||                    S )zj
        Re-implementation of BedTool.randomintersection using the new
        `random_op` method
        NTr  r  r  r  r  r  )r5   r0   r6   r  r  r  random_intersection)rk   r   r  r  r  r  r  r  s           r%   r  zBedTool._randomintersection  s     !N##d||| 	YWXXX%%9- '#1%5  
 $%    
 
 	
r'   c                     |i }|i }|st          d          t          |                     |t          j        j        | |ft          |||          ||                    S )z}
        Like randomintersection, but return the bp overlap instead of the
        number of intersecting intervals.
        Nr  r  r  )r0   r6   r  r  r  random_intersection_bpr5   )rk   r   r  r  r  r  r  r  s           r%   randomintersection_bpzBedTool.randomintersection_bp  s     !N#! 	YWXXX%%<- '#1%5  
 $%    
 
 	
r'   c	              #       K   lt          j                  |z  gz  }	|	dxx         |z  z  cc<    fd|	D             }
|
D ]}|                                D ]}|V  t          i ddidvrdd<                       dd          }t	          |          D ]}r|d<   rT|d	k    rd
|d||z  }nd|z  }t
          j                            |           t
          j                                         |r"  j	        di }|
                                }n  j	        di } |j        fddi}t          |          V  |j                                         ~~dS )a|  
        Perform `iterations` shufflings, each time intersecting with `other`.

        Returns a generator of integers where each integer is the number of
        intersections of a shuffled file with *other*. This distribution can
        be used in downstream analysis for things like empirical p-values.

        *intersect_kwargs* and *shuffle_kwargs* are passed to self.intersect()
        and self.shuffle() respectively.  By default for intersect, u=True is
        specified -- but s=True might be a useful option for strand-specific
        work.

        Useful kwargs for *shuffle_kwargs* are chrom, excl, or incl.  If you
        use the "seed" kwarg, that seed will be used *each* time shuffleBed is
        called -- so all your randomization results will be identical for each
        iteration.  To get around this and to allow for tests, debug=True will
        set the seed to the iteration number.  You may also break up the
        intersections across multiple processes with *processes* > 1.

        Example usage:

            >>> chromsizes = {'chr1':(0, 1000)}
            >>> a = pybedtools.example_bedtool('a.bed')
            >>> a = a.set_chromsizes(chromsizes)
            >>> b = pybedtools.example_bedtool('b.bed')
            >>> results = a.randomintersection(b, 10, debug=True)
            >>> print(list(results))
            [1, 0, 1, 2, 4, 2, 2, 1, 2, 4]

        Nr  c                 r    g | ]3}                     t          |ft          	                     4S ))r  r  r  report_iterations_orig_processes)r  r   r5   )
r#   r  r  r  r   r   r  r  rk   r  s
     r%   r&   z.BedTool.randomintersection.<locals>.<listcomp>$  sg         )5"%)9'5#*;(1  
 
  r'   r  Tr   Fseedr   zapprox (total across z processes): z%srq   r!   )r  r  r  rb  r   r  rM   r   flushr1  r  r   rb   rd   r   )rk   r   r  r  r  r  r  r  r  r  rC   ru  rt   resortr$   r   tmp0rn   tmp2r   s   `` `````           @r%   r  zBedTool.randomintersection  sT     R  $Y//A)Y67)COB:	#99           *  G     UUWW    EKKKK !N# #T{&&&$(S!!%%h66z"" !	 !	A +)*v&  	#"Q&&&'O++CC
 !1*C
  %%%
  """  5#t|55n55iikk"dl44^44 3=HHtH7GHHDd))OOO GMMOOOC!	 !	r'   c           
         t          |          dk    s
J d            g }|D ]b}t          |t          t          f          rt	          |          }nt          |t                    s
J d            |                    |           c|                    dd          }|                    dd          }|                    dd          }|r|rt          d	          |s	 | j	        }| g|z   }	t          | j	        gd
 |D             z                                 dg          }
t          |                                 gd |D             z                                 dg                              dg          }t          |          dk    }t          t          |
                    dk    }n# t          $ r t          d          w xY w|                                 }|s|r|r~t          |d          5 }| D ]$}|                    t          |                     %|D ])}|D ]$}|                    t          |                     %*	 ddd           n# 1 swxY w Y   nH|s|rt!          |          }t          |d          5 }| D ]:}|                    d                    |j        d|                   dz              ;|D ]?}|D ]:}|                    d                    |j        d|                   dz              ;@	 ddd           n# 1 swxY w Y   nt          |d          5 }| D ],}|                    d|j        |j        |j        fz             -|D ]1}|D ],}|                    d|j        |j        |j        fz             -2	 ddd           n# 1 swxY w Y   t	          |          }|r7 |                    d          j        di |}t1          j        |           |S |S )a  
        Concatenate interval files together.

        Concatenates two BedTool objects (or an object and a file) and does an
        optional post-merge of the features.

        *postmerge=True* by default; use *postmerge=False* if you want to keep
        features separate.

        *force_truncate=False* by default; *force_truncate=True* to truncate
        all files to chrom, start, stop.

        When *force_truncate=False* and *postmerge=False*, the output will
        contain the smallest number of fields observed across all inputs. This
        maintains compatibility with BEDTools programs, which assume constant
        number of fields in all lines of a file.

        Other kwargs are sent to :meth:`BedTool.merge` (and assuming that
        *postmerge=True*).

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b = pybedtools.example_bedtool('b.bed')
        >>> print(a.cat(b)) #doctest: +NORMALIZE_WHITESPACE
        chr1	1	500
        chr1	800	950
        <BLANKLINE>
        >>> print(a.cat(*[b,b],
        ...   postmerge=False)) #doctest: +NORMALIZE_WHITESPACE
        chr1	1	100	feature1	0	+
        chr1	100	200	feature2	0	+
        chr1	150	500	feature3	0	-
        chr1	900	950	feature4	0	+
        chr1	155	200	feature5	0	-
        chr1	800	901	feature6	0	+
        chr1	155	200	feature5	0	-
        chr1	800	901	feature6	0	+
        <BLANKLINE>
        r   z,You must specify at least one other bedfile!r  	postmergeTforce_truncateFrq   zThe post-merge step in the `cat()` method perfoms a sort, which uses stream=True.  Using stream=True for the merge as well will result in a deadlock!c                     g | ]	}|j         
S r!   )r  r"   s     r%   r&   zBedTool.cat.<locals>.<listcomp>  s    'H'H'H'H'H'Hr'   r6  c                 6    g | ]}|                                 S r!   )r;  r"   s     r%   r&   zBedTool.cat.<locals>.<listcomp>  s     /T/T/TA/T/T/Tr'   Nr   zCan't check filetype or field count -- is one of the files you're merging a 'streaming' BedTool?  If so, use .saveas() to save to file firstr   rQ   rO   z	%s	%i	%i
)rq   r!   )rb   r*   r+   r   r@   rA   r  r  r0   r  r7  
differencer;  rf   r,   r   minr/   r8  r   r   r   r  r(  r   r  )rk   othersr9   
other_bedsr   r  r  stream_mergea_typefiles	filetypes
field_numssame_field_num	same_typern   TMPr1  	minfieldscrI   s                       r%   catzBedTool.catd  s   T 6{{Q N
 	% 	%E%#t-- J!7  J JIJ J J e$$$$ JJ{D11	$4e<<zz(E22 	I 	    	+^$'H'HZ'H'H'HH *gY''  ))++,/T/T/T/T/TTUUZ''Z__ 
 "%ZA!5I//14		    K   iikk 	N) 	N 	Nc3 *3 & &AIIc!ff%%%%' * *E" * *		#a&&))))*** * * * * * * * * * * * * * *   	NI 	NJIc3 J3 F FAIIdii)(<==DEEEE' J JE" J J		$))AHZiZ,@"A"AD"HIIIIJJJ J J J J J J J J J J J J J J c3 N3 J JAIIn!%/HHIIII' N NE" N N		.AGQWae3L"LMMMMNNN N N N N N N N N N N N N N N CLL 	)d##)33F33A IcNNNHHsF   CF+ +G2AIIIB LLL,A$NN!$N!c                 :   ||                                  }|-t          j                            |          \  }}|dk    rd}nd}t	          | j        t                    ot          | j                  }|                     | ||||          }t          |          S )aX  
        Make a copy of the BedTool.

        Optionally adds `trackline` to the beginning of the file.

        Optionally compresses output using gzip.

        if the filename extension is .gz, or compressed=True,
        the output is compressed using gzip

        Returns a new BedTool for the newly saved file.

        A newline is automatically added to the trackline if it does not
        already have one.

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b = a.saveas('other.bed')
        >>> b.fn
        'other.bed'
        >>> print(b == a)
        True

        >>> b = a.saveas('other.bed', trackline="name='test run' color=0,55,0")
        >>> open(b.fn).readline()
        "name='test run' color=0,55,0\n"
        >>> if os.path.exists('other.bed'):
        ...     os.unlink('other.bed')
        Nr  TF)rd   r  r  r  )
rf   r   r   splitextr*   rd   r+   r   r  r@   )rk   rd   r  
compressed__	extensionr  s          r%   r   zBedTool.saveas  s    @ :B G,,R00MB	E!!!

"
"47C00DVDG__^^'%  
 
 r{{r'   c                     t          | j        t                    s|                     | |          }nt	          j        | j        |           t          |          S )a  
        Move to a new filename (can be much quicker than BedTool.saveas())

        Move BED file to new filename, `fn`.

        Returns a new BedTool for the new file.

        Example usage:

        >>> # make a copy so we don't mess up the example file
        >>> a = pybedtools.example_bedtool('a.bed').saveas()
        >>> a_contents = str(a)
        >>> b = a.moveto('other.bed')
        >>> b.fn
        'other.bed'
        >>> b == a_contents
        True
        )rd   )r*   rd   r+   r  shutilmover@   rk   rd   s     r%   movetozBedTool.moveto  sO    ( $'3'' 	%,,BBK$$$r{{r'   c                    ||||t          d          |                                 }|t          j        |           |rt	          t          t          |                               }t          j        |           |d|         }t          |d          5 }t          |           D ]+\  }}||v r"|
                    t          |                     ,	 ddd           n# 1 swxY w Y   ni|rgt          |d          5 }| D ];}t          j                    |k    r"|
                    t          |                     <	 ddd           n# 1 swxY w Y   t          |          S )a  
        Return a BedTool containing a random subset.

        NOTE: using `n` will be slower and use more memory than using `f`.

        Parameters
        ----------

        n : int
            Number of features to return. Only one of `n` or `f` can be provided.

        f : float, 0 <= f <= 1
            Fraction of features to return. Cannot be provided with `n`.

        seed : float or int
            Set random.seed

        Example
        -------

        >>> seed = 0  # only for test, otherwise use None

        `n` will always give the same number of returned features, but will be
        slower since it is creating an index and then shuffling it.

        >>> a = pybedtools.example_bedtool('a.bed')
        >>> b = a.random_subset(n=2)
        >>> len(b)
        2

        Using a fraction `f` will be faster but depending on seed will result
        in slightly different total numbers.

        >>> a = pybedtools.example_bedtool('x.bam')
        >>> len(a)
        45593
        >>> b = a.random_subset(f=0.4, seed=seed)
        >>> len(b)
        18316

        Check that we have approximately the right fraction
        >>> print('{0:.2f}'.format(len(b) / len(a)))
        0.40

        Nz*Exactly one of `n` or `f` must be providedr   )r0   rf   r   r  r6   r   rb   r1  r,   rT  r   r+   r@   )	rk   r9  r1  r  rr  idxsrn   r$   r  s	            r%   random_subsetzBedTool.random_subset5  s   ^ YQYam!-IJJJ		K 	*c$ii(())DN4   8DeS!! 0S"+D// 0 0JAwDyy		#g,,///00 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  	*eS!! *S * *A}!++		#a&&)))** * * * * * * * * * * * * * *
 u~~s$   <C$$C(+C(?EEEc                     |                                  }d}|                                D ]}|t          |          z  }|S )a  
        Return the total number of bases covered by this interval file.

        Does a self.merge() first to remove potentially multiple-counting
        bases.

        Example usage:

        >>> a = pybedtools.example_bedtool('a.bed')

        This does a merge() first, so this is what the total coverage is
        counting:

        >>> print(a.merge()) #doctest: +NORMALIZE_WHITESPACE
        chr1	1	500
        chr1	900	950
        <BLANKLINE>

        >>> print(a.total_coverage())
        549
        r   )r(  r`  rb   )rk   r  total_bpr  s       r%   total_coveragezBedTool.total_coverage|  sD    , JJLLzz|| 	% 	%GG$HHr'   c                 v    t          |                                          D ]\  }}t          | ||           | S )a  
        Helper method for adding attributes in the middle of a pipeline.

        Given arbitrary keyword arguments, turns the keys and values into
        attributes.  Useful for labeling BedTools at creation time.

        Example usage:

        >>> # add a "label" attribute to each BedTool
        >>> a = pybedtools.example_bedtool('a.bed')                                   .with_attrs(label='transcription factor 1')
        >>> b = pybedtools.example_bedtool('b.bed')                                   .with_attrs(label='transcription factor 2')
        >>> for i in [a, b]:
        ...     print('{0} features for {1}'.format(i.count(), i.label))
        4 features for transcription factor 1
        2 features for transcription factor 2

        )r6   rh   ri   )rk   r9   r  rt   s       r%   
with_attrszBedTool.with_attrs  sA    * v||~~.. 	& 	&JCD#u%%%%r'   c                     t          | j        t                    s|                     | j                  }n| j        }t	          |          S )zR
        Returns an IntervalFile of this BedTool for low-level interface.
        )r*   rd   r+   r  r   r  s     r%   as_intervalfilezBedTool.as_intervalfile  sB     $'3'' 	((BBBBr'   r   c                     t                                           }|t                                           }d|| j        |||g}t          j        d                    |                     t          |          S )a  
        Returns a new BedTool of the liftedOver features, saving the unmapped
        ones as `unmapped`.  If `unmapped` is None, then discards the unmapped
        features.

        `liftover_args` is a string of additional args that is passed,
        verbatim, to liftOver.

        Needs `liftOver` from UCSC to be on the path and a `chainfile`
        downloaded from UCSC.
        NliftOverr  )r@   rf   rd   r   systemr/   )rk   	chainfileunmappedliftover_argsru   rm   s         r%   liftoverzBedTool.liftover  s^     ||~~HM47IvxP
	#((4..!!!vr'   c              #     K   ddl m} |ddi}d|vr#|                    t          d                     |r_|                     |                                          }|                    |                                          } |j        |fddi|}n | j        |fddi|}|D ]}t          |d	                   V  dS )
a  
        Returns an iterator of the *absolute* distances between features in
        self and other.

        If `use_midpoints` is True, then only use the midpoints of features
        (which will return values where features are overlapping).  Otherwise,
        when features overlap the value will always be zero.

        `closest_kwargs` are passed to self.closest(); either `d` or
        'D` are required in order to get back distance values (`d=True` is
        default)
        r   midpointNrI   TD)rI   rq   r  )featurefuncsr  r   r5   r?  r   r+  r3   )	rk   r   closest_kwargsuse_midpointsr  mid_self	mid_otherr  r$   s	            r%   absolute_distancezBedTool.absolute_distance  s      	+*****!!4[Nn$$!!$,,,/// 	Cyy**1133H

8,,3355I  JJ4J>JJAAUBB4B>BBA 	 	Aae**	 	r'   c              #     K   ||t          d          |r|rt          d          |rt          |          }|rt          |          }ddlm}  |                     |          j        di |}|                    |                                          }|                    |dd	          }|D ])}	t          |	d
                   t          |	          z  V  *dS )a  
        Returns an iterator of relative distances between features in self and
        other.

        First computes the midpoints of self and other, then returns distances
        of each feature in `other` relative to the distance between `self`
        features.

        Requires either `genome` (dictionary of chromsizes or assembly name) or
        `g` (filename of chromsizes file).
        Nz5Need either `genome` or `g` arg for relative distancez*Please specify only one of `genome` or `g`)r[   )rZ   r   r  T)waorq   r  r!   )
r0   r5   r  r  r?  rE  r   r   r4   rb   )
rk   r   r[   rZ   g_dictr  r  r  hitsr$   s
             r%   relative_distancezBedTool.relative_distance  s      NTUUU 	Ka 	KIJJJ 	)(((F 	AYYYF****** +DIIh*44V44JJx((//11	{{5d4{88 	( 	(A",,Q'''''	( 	(r'   c                    |                                  }| j        dk    s|dk     rt          d          ddl}ddl}|r|j                                        }n|j                                        }|                    d | D             t                    }	|	|
                    |	                   }	|                    |	           ||r|                    |	|          }||_        ||r|                    |	|          }||_        |S )aL  
        Returns a normalization instance for use by featurefuncs.add_color().

        Parameters
        ----------
        vmin, vmax : float, int, or None
            `vmin` and `vmax` set the colormap bounds; if None then
            these will be determined from the scores in the BED file.

        log : bool
            If True, put the scores on a log scale; of course be careful
            if you have negative scores

        percentile : bool
            If True, interpret vmin and vmax as a percentile in the range
            [0,100] rather than absolute values.
        rH     z5colorizing only works for BED files with score fieldsr   Nc                     g | ]	}|j         
S r!   )r  r"   s     r%   r&   z.BedTool.colormap_normalize.<locals>.<listcomp>*  s    111q17111r'   )dtype)r;  r  r0   
matplotlibr  colorsLogNorm	Normalizer  r4   isfinite	autoscaler  vminvmax)
rk   r  r  r  logr;  r  r  normscoress
             r%   colormap_normalizezBedTool.colormap_normalize  s$   $ &&((Ne##qWXXX 	1$,,..DD$..00D11D111??F++,v 3}}VT22DI 3}}VT22DIr'   c                      t                     fd}t           |                                                      S )zK
        Returns a new BedTool with only intervals at lines `inds`
        c               3   v   K   d} t                    D ]#\  }}||          k    r|V  | dz  } | k    r d S $d S )Nr   r   )rT  )r   r$   r  indslengthrk   s      r%   _genzBedTool.at.<locals>._gen?  s_      A'oo  
7Q<<!MMMFAF{{ r'   )rb   r@   r   )rk   r$  r&  r%  s   `` @r%   atz
BedTool.at9  sU     T	 	 	 	 	 	 	 ttvv%%'''r'   c           	      ,   | j         rt          d          t          | j        t                    st          d          	 ddl}n# t          $ r t          d          w xY w|                    dd          }||s	 t          j	        | j
                 d|                                          }t          |          |                                 k     r2t          d| j
        d|d	|                                 d
           d}n# t          $ r d}Y nw xY w||d<   t          j                            | j                  r@t          j                            | j                  dk    r |j        | j        g|R ddi|S |                                S )a  
        Create a pandas.DataFrame, passing args and kwargs to pandas.read_csv
        The separator kwarg `sep` is given a tab `\t` as value by default.

        Parameters
        ----------
        disable_auto_names : bool
            By default, the created dataframe fills in column names
            automatically according to the detected filetype (e.g., "chrom",
            "start", "end" for a BED3 file). Set this argument to True to
            disable this behavior.
        z-BAM not supported for converting to DataFramez,use .saveas() to make sure self.fn is a filer   Nz7pandas must be installed to convert to pandas.DataFramenameszDefault names for filetype z are:
z
but file has z; fields; you can supply custom names with the `names` kwargr   rQ   )rc   r0   r*   rd   r+   r   r   r  r   _column_namesr  r;  rb   r   r  r   r   isfilegetsizeread_csv	DataFrame)rk   disable_auto_namesrV   r9   r   r)  _namess          r%   to_dataframezBedTool.to_dataframeJ  s    ; 	NLMMM$'3'' 	MKLLL	YMMMM 	Y 	Y 	YWXXX	Y 

7D))=!3=
!/?@T$BRBRBTBT@TUv;;!1!1!3!333D ,0>>>6664CSCSCUCUCUCUW  
 "F   $F7O7>>$'"" 	&rwtw'?'?!'C'C"6?47FTFFFtFvFFF##%%%s   A A >BD DDc                 ~   | j         rt          d          t          | j        t                    st          d          d}|}t          | j        d          }|                    dd           |                                }g }	 ||k     r|}|                    | d           |                    |          }|	                    |
                    d                     t          |          |k    s||k    rn||z  }|d                    d	 || d
         D                       }	|r|	S t          |	           d
S )z
        Like `head`, but prints last 10 lines of the file by default.

        To avoid consuming iterables, this only works with file-based, non-BAM
        BedTool objects.

        Use `as_string=True` to return a string.
        z(tail() not yet implemented for BAM fileszVtail() not implemented for non-file-based BedTool objects.  Please use saveas() first.i    r  r   r(   Tr   c                 6    g | ]}|                                 S r!   )r   r"   s     r%   r&   z BedTool.tail.<locals>.<listcomp>  s     <<<!((**<<<r'   N)rc   r0   r*   rd   r+   r,   seektellr-   r  r1   rb   r/   r  )
rk   linesr  bufsizeoffsetr1  	file_sizer<   chunkru   s
             r%   tailzBedTool.tailv  sZ    ; 	IGHHH$'3'' 	?   $ 	
q!FFHH		7"""FFF7AFF6NNEKK((..///4yyE!!Vy%8%8gF	 <<dE677m<<<== 	M&MMMMMr'   )NFF)NrQ   Fr   F)F)TFF)TN)r4  )r@  rA  )r4  F)NNFF)Fr  )FNFr  )NNr   NNN)NNNr   )NNr   N)NNFFNN)NNNrT   )Nr   )NFr   )r   
__module____qualname__r   r  r   classmethodr   r2   r   r   r  r
  r   r  r%  r.  r3  r;  r?  r^  r`  propertyr  ri  rf   ry  r{  r~  r  r  r  r  r  r  r  r  r  r  rg   re   r  r  r  r  r   rS  bed12tobed6r  bamtobedr  r  bedtobamr   r   r  getfastastaticmethodr  r  nucr  multicovr   r#  r&  r(  r+  r.  r1  r  r5  r8  r<  	genomecovr?  rB  	maskfastarE  r  rJ  	pairtobedrM  
pairtopairrO  rR  r   r   rU  
multiinterr   rZ  
bedpetobamr]  r`  	unionbedgrc  makewindowsrf  rj  rn  rs  
bamtofastqr=   rt  rJ   rE   rw  r   FisherOutputry  r   r|  r}  rF   r  r  r  r  r  r  r  r  r  r  r   r  r  r  r  r  r  r  r  r!  r'  r1  r;  r!   r'   r%   r@   r@     s	       #IS! S! S! S!j  ( ( ( [(T$ $ $(# # #@9 9 9 9v     @
 
 
3 3 3 3j) ) ) )V" " "HF F F.   0$% $% $%LE  E  E  E N     X2$ $ $ $<   [- - -0 T T XT	3 	3 	3
 
 
    & & &  	 	 	  !) !) !) !)F  @ E E E ENk  k  k Z- - -^ (% (% _(%TF F F F8F F F F8H H H H8 V$dCCC  DC _ KVceMMM  NM _ HVcttLLL  ML = = _=@ HV#SfS&M3 3 3 3 3 _
 V+g     _8 HS S \S( VT@V     _ CV///  0/ _ "HVCTBBB  CB _8 VS$DQQQ  RQ _
 Vc4TRRR) ) SR _)V Vc4@@@  A@ _( V3DAAA  BA _" Vs#6%PPP  QP _( V4TtTTT  UT _" VSdsHoVVV  WV _2 V---  .- _" Vct<<<  =< _8 V xX  $ $  _$N  IVCVERRR  SR _" Vg+     _, IV3DAAA  BA _ V,,,  -, _" Vs#6'RRR  SR _ IV3777  87 _ JVS)))  *) _2 VCS111  21 _ CVCs333  43 _
 V$$7)LLL  ML _. !JV$///	 	 0/ _	 VL3DDIII  JI _ JV,,,  -, _
 V!"""  #" _  IVD#c^a]bccc  dc _ KV,,,  -, _
 Vc8\:RSSS  TS _ Vc8\:RSSS  TS _ Vg     _ JV 7	    
 V 7	     VCS111  21
 V ' 4  ' ' 'R V3@STTT  UT@ VS)))
 
 *)
* * *(  % % %V "Y Y Y Yv4 4 4 QU9 9 9 9| 3
 3
 3
 3
t !
 !
 !
 !
P !
 !
 !
 !
N k k k kZ ~ ~ _~@ 3 3 3 _3j    _2 D D D _DL  8   _0        &   <( ( ( (B* * * *X( ( ("*& *& *& *&X& & & & & &r'   r@   c                   ,    e Zd Zd Zd Zd Zd Zd ZdS )rv  c                     || _         t          | j         t                    st          d          t	          j        | j                   | _        dS )z
        Wraps pysam.Samfile so that it yields pybedtools.Interval objects when
        iterated over.

        The pysam.Samfile can be accessed via the .pysam_bamfile attribute.
        z%Only files are supported, not streamsN)rq   r*   r+   r0   r   r   pysam_bamfile)rk   rq   s     r%   r   zBAM.__init__  sI     $+s++ 	FDEEE"]4;77r'   c                    |j         dk    r | j                            |j                   }nd}|j        dk    r3|j        |j         k    rd}n"| j                            |j                  }nd}|j        dk    rd}nt          |j        dz             }|j        r|j        }nd}g }|j        D ]a\  }}t          |t                    rd}	nt          |t                    rd}	nd}	|                    d	                    ||	|                     bd
                    |          }|j        r|j        }
nd}
|j        r|j        }nd}|j        t          |j                  |t          |j        dz             t          |j                  |||t          |j                  |
|g}|r|                    |           d |v rt+          d|z            t-          |          S )Nr   *=0r   r$   r1  Zz{0}:{1}:{2}rQ   zFound 'None' in fields: %s)rnamerS  getrnamernextpnextr+   cigarstringtagsr*   r3   r4   rA   rw  r/   r  qualqnameflagposmapqtlenr0   r   )rk   ru  rY  r[  r\  r]  r^  r   r   tr  r_  r8  s                r%   _aligned_segment_to_intervalz BAM._aligned_segment_to_interval  s   7a<<&//88EEE7a<<w!'!!*33AG<<E 7a<<EE !$$E= 	-KKK F 	7 	7DAq!S!! Au%% KK,,Q1556666yy5 	%CCC6 	6DDD GKK 	NNKKKK
  	 MM$6>>9FBCCC(000r'   c                     | S rT   r!   r  s    r%   ry  zBAM.__iter__  s    r'   c                 P    |                      t          | j                            S rT   )rf  r   rS  r  s    r%   r   zBAM.__next__  s!    00d6H1I1IJJJr'   c                 *    |                                  S rT   )r   r  s    r%   r   zBAM.next  s    }}r'   N)r   r<  r=  r   rf  ry  r   r   r!   r'   r%   rv  rv    sf        
8 
8 
8H1 H1 H1T  K K K    r'   rv  c                       e Zd Zd ZdS )r   c                 :    t                               |            dS )z{
        Represents one or many HistorySteps.  Mostly used for nicely formatting
        a series of HistorySteps.
        N)r6   r   r  s    r%   r   zHistory.__init__  s    
 	dr'   N)r   r<  r=  r   r!   r'   r%   r   r     s#            r'   r   c                        e Zd Zd Zd Zd ZdS )r(  c                    	 |j         | _        n# t          $ r |j        | _        Y nw xY w|| _        || _        |j        | _        d                    d t          d          D                       }|| _	        || _
        dS )z
        Class to represent one step in the history.

        Mostly used for its __repr__ method, to try and exactly replicate code
        that can be pasted to re-do history steps
        r   c              3   R   K   | ]"}t          j        t          j                  V  #d S rT   r   r   s     r%   r2  z'HistoryStep.__init__.<locals>.<genexpr>  s/      NNfmF$:;;NNNNNNr'   r   N)r   r,  r   r   rV   r9   rd   r/   r   r)  r*  )rk   r,  rV   r9   bedtool_instancer)  r*  r   s           r%   r   zHistoryStep.__init__  s    	. ,DKK 	. 	. 	.$o	. 	"%ggNNU1XXNNNNN$$s    ((c                 |    t          |t          j                  r|j        }t          |t                    rd|z  }|S )zT
        Wrap strings in quotes and convert bedtool instances to filenames.
        z"%s")r*   r  r@   rd   r+   )rk   r  s     r%   
_clean_argzHistoryStep._clean_arg   s@     c:-.. 	&Cc3 	3,C
r'   c                     d}|dz  }t           j                             j                  r|d j        z  z  }n|d j        z  z  }|d j        z  z  }d                    t           j         j                            }d                     fdt           j
                                                  D                       }t          |          dk    r|d	z  }|||fz  }|d
 j        z  z  }|d j        z  z  }|S )Nr   z<HistoryStep> z$BedTool("%(fn)s").%(method)s(%%s%%s)zBedTool("MISSING FILE: %(fn)s")z.%(method)s(%%s%%s)r  c                 \    g | ](}|d          d                     |d                   )S )r   rV  r   )rq  )r#   r$   rk   s     r%   r&   z(HistoryStep.__repr__.<locals>.<listcomp>7  s9    XXX!dooad3334XXXr'   r   z, z, parent tag: %sz, result tag: %s)r   r   r   rd   __dict__r/   r   rq  rV   r6   r9   rh   rb   r)  r*  )rk   r8   args_stringkwargs_strings   `   r%   r~  zHistoryStep.__repr__*  s   	7>>$'"" 	77$-GGAA2T]BBA&66A hhs4?DI>>??XXXXd4;CTCTCVCV>W>WXXX
 
 {a4Km,,	$/11	$/11r'   N)r   r<  r=  r   rq  r~  r!   r'   r%   r(  r(    sA        % % %&      r'   r(  c                     t           j                            t          j                    |           } t           j                            |           sd| z  }t          |          t          |           S )z
    Return a bedtool using a bed file from the pybedtools examples directory.
    Use :func:`list_example_files` to see a list of files that are included.
    z%s does not exist)r   r   r/   r   data_dirr   r   r@   )rd   r   s     r%   example_bedtoolry  C  s\    
 
i(**B	/	/B7>>" %!B&$$$2;;r'   __main__)optionflags)NNNNFNNNNFNNNNN)=rn  textwrapr   r  r   operatorr   r  r   r   r  	itertoolsr   r  rx  r   warningsr   pathlibr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   	cbedtoolsr   r   r   r   r   r   r  r   r   r   r   r=   rJ   r   objectr@   rv  r6   r   r(  ry  r   doctesttestmodELLIPSISNORMALIZE_WHITESPACEr!   r'   r%   <module>r     sp                				 



                                                                                                 ) ) )*  4 

 P P P Pf
h3 h3 h3 h3 h3f h3 h3 h3Vga a a a a& a a aH    d   4 4 4 4 4& 4 4 4n	 	 	 zNNNGO 073O OPPPPPP r'   