
    DUf5M                        d dl Z d dlmZ d dlZd dlmZ d dlmZ d dlZd dlZ G d dej	                  Z
 G d de          Zdd
Zd Zd Z G d de          Z G d de          Z G d de          Zedk    r~	  ej        d          Z ej        d          Z eedi e                                          Z eed ed	          e                                          Z ej                     dS dS )    N)defaultdict)collections)pyplotc                   T    e Zd Z	 	 	 	 	 ddZd Zd Zd	 Zd
 Zd Ze	d             Z
dS )TrackNr      denseTc                    t          |t          j                  r"t          |j        t                    r|| _        n+t          j        |                                          | _        || _        || _        || _	        || _
        |                                  |                                 }|                    t          |                     t          j        j        | fd|                                 i| dS )a	  
        Subclass of matplotlib's PolyCollection that can be added to an Axes.

        :param features:
            Can be an existing BedTool, or anything than can be used to create
            a BedTool (e.g., a filename or a generator of Interval objects)

        :param ybase:
            y-coord of the bottom edge of the track (in data coordinates)

        :param yheight:
            How high each feature will be, in data coordinates

        :param visibility:
            Mimics the settings in the UCSC Genome Browser:

            * "dense" is the default; overlapping features can be seen if you
              set alpha < 1.

            * "squish" prevents adjacent features from overlapping.  This keeps
              `yheight` for all features, so if you have a lot of features
              piling up, the track will be a lot higher on the y-axis than
              `yheight`.

        :param stranded:
            If boolean and True, will draw arrrow-shaped features to indicate
            direction (where the point is 10% of the total gene length)

            If a dictionary, map strands to colors, e.g., {'+': 'r', '-': 'b'}.

        :param kwargs:
            Additional keyword args are passed to
            matplotlib.collections.PolyCollection.

        Notes:

        After creating a track, use the `ymax` attribute to get the max y-value
        used in the track -- useful if you've created a "squish" track but
        would like to stack another track on top, and need to calculate what
        the new Track's `ybase` should be.

        The returned PolyCollection will have the `features` attribute, which
        contains the BedTool it was created from -- so you can write callback
        functions for event handling, e.g.::

            def callback(event):
                '''
                prints the feature's line when clicked in the plot
                '''
                coll = event.artist
                for i in event.ind:
                    print coll.features[i]

            fig.canvas.mpl_connect('on_pick', callback)


        >>> a = pybedtools.example_bedtool('a.bed')
        >>> track = pybedtools.contrib.plotting.Track(a, alpha=0.5, picker=5)
        >>> import matplotlib.pyplot as plt
        >>> fig = plt.figure()
        >>> ax = fig.add_subplot(111)
        >>> ax.add_collection(track) #doctest: +ELLIPSIS
        <pybedtools.contrib.plotting.Track object at 0x...>
        >>> limits = ax.axis('tight')
        )
facecolorsvertsN)
isinstance
pybedtoolsBedToolfnstrfeaturessaveas_visibility_ybase_yheightstranded_check_stranded_dict_colorsupdatedictr   PolyCollection__init__
_get_verts)	selfr   chromybaseyheight
visibilityr   kwargsr   s	            X/var/www/html/software/conda/lib/python3.11/site-packages/pybedtools/contrib/plotting.pyr   zTrack.__init__   s    V h
 233 	B
K9
 9
 	B %DMM&.x88??AADM% !!###\\^^
dj111222"+DTT8I8ITVTTTTT    c                    | j         rt          | j         t                    st          |          dz  }|j        dk    r<|j        |f|j        ||z   f|j        |z   ||z   f|j        ||dz  z   f|j        |z   |fgS |j        dk    r<|j        |f|j        ||z   f|j        |z
  ||z   f|j        ||dz  z   f|j        |z
  |fgS |j        |f|j        ||z   f|j        ||z   f|j        |fgS )N皙?-g      ?+)r   r   r   lenstrandstopstart)r   featurer!   r"   offsets        r%   _shapezTrack._shapee   s5   = 	DM4!@!@ 	\\C'F~$$\5)\57?3]V+UW_=]EGcM$9:]V+U3  3&&]E*]EGO4\F*EGO<\57S=#89\F*E2  ]E"]EGO,\57?+\5!	
 	
r&   c                    g }| j         dk    rR| j        D ]6}|                    |                     || j        | j                             7| j        | j        z   | _        | j         dk    rg }| j        }| j        | j        z   | _        | j        D ]}d }t          |          D ].\  }}|j        |k    r| j        || j        z  z   }|j	        ||<    n/|9| j        t          |          | j        z  z   }|                    |j                   |                    |                     ||| j                             | j        t          |          | j        z  z   | _        |S )Nr	   squish)r   r   appendr1   r   r   ymax	enumerater.   r-   r+   end)r   r   r/   stackr!   iss          r%   r   zTrack._get_verts   sp   w&&= O OT[[$+t}MMNNNNdm3DIx'' EKEdm3DI= 
I 
I%e,,  DAq}q(( $a$-.? ?#*<a ) = K#e**t}*DDELL---T[[%GGHHHHc%jj4=&@@DIr&   c                     t          | j        t                    sdS d| j        vrt          d| j        z            d| j        vrt          d| j        z            dS )NTr*   z1stranded dict "%s" does not have required key "+"r)   z1stranded dict "%s" does not have required key "-")r   r   r   
ValueErrorr   s    r%   r   zTrack._check_stranded_dict   sv    $-.. 	4dm##FV   dm##FV   tr&   c           	          t          | j        t                    sd S g }| j        D ]V}	 |                    | j        |j                            )# t          $ r! t          d| j        d|j        d          w xY w|S )Nzstrand color dict "z"" does not have a key for strand "")r   r   r   r   r4   r,   KeyError)r   colorsr/   s      r%   r   zTrack._colors   s    $-.. 	4} 	 	GdmGN;<<<<   h)-H  
 s   %A+A:c                 R    |                      |j                  }|j        |j        fS )z;
        Needs `ax` to convert to transData coords
        )get_datalim	transDataxminxmax)r   axbbs      r%   	get_xlimszTrack.get_xlims   s(     bl++!!r&   c                 6    | j         | j        | j         z
  dz  z   S )Ng       @)r   r5   r=   s    r%   midpointzTrack.midpoint   s    {di$+5<<<r&   )Nr   r   r	   T)__name__
__module____qualname__r   r1   r   r   r   rI   propertyrK    r&   r%   r   r   
   s         XU XU XU XUt
 
 
6  B    " " " = = X= = =r&   r   c                        e Zd ZdZd ZddZdS )BinaryHeatmapzT
    Class-based version of the `binary_heatmap` function for more flexibility.
    c                    || _         || _        g }|D ]}t          |t          j                  rIt          |j        t                    s|                                }|                    |j                   et          |t                    r|                    |           t          j                    	                    ||d          | _
        t          t                    | _        t          t                    }g | _        | j
        D ]\}|d         }| j        |xx         dz  cc<   | j                            |dd                     ||                             |           ]i | _        t          |                                          D ]!\  }}	t          j        |	          | j        |<   "t%          j        | j        t                    | _        t)          | j                  | _        d S )NT)r9   namescluster   r      )dtype)btsrT   r   r   r   r   r   r   r4   multi_intersectresultsr   intclass_countslistmatrixclassified_intervalsitemsnparraysort_binary_matrixsort_ind)
r   rY   rT   _btsbt_classified_intervalsitemclskvs
             r%   r   zBinaryHeatmap.__init__   s   
  	  	 B"j011  !"%-- %BBE""""B$$  B ")++;;% < 
 
 (,, +D 1 1L 	4 	4Dq'Cc"""a'"""KtABBx(((!#&--d3333$&!.446677 	A 	ADAq+5+=a+@+@D%a((ht{#666*4;77r&   Nc           	         |*t          j        d          }|                    d          }|                    | j        | j                 ddt          j        j        d          }|	                    t          t          t          | j                                                 |                    | j        d	           ||                    d
           |S )N)   
   figsizeo   autonearestupper)aspectinterpolationcmaporiginZ   )rotationg      ?)left)pltfigureadd_subplotimshowr_   re   
matplotlibcmbinary
set_xticksr^   ranger+   rT   set_xticklabelssubplots_adjust)r   rG   figmappables       r%   plotzBinaryHeatmap.plot   s    :*W---C%%B 99K&#%  
 
 	d5TZ1122333
4:333:T***	r&   N)rL   rM   rN   __doc__r   r   rP   r&   r%   rR   rR      sB         )8 )8 )8V     r&   rR   Tc                 l    t          | |          }|r|                                 |j        |j        fS )a  
    Plots a "binary heatmap", showing the results of a multi-intersection.

    Each row is a different genomic region found in at least one of the input
    BedTools; each column represents a different file.  Black indicates whether
    a feature was found at that particular site.  Rows with black all the way
    across indicates that all features were colocalized at those sites.

    `bts` is an iterable of BedTool objects or filenames; `names` is a list of
    labels to use in the plot and is exactly the same length as `bts`.

    If `plot=True`, then plot the sorted, labeled matrix with matplotlib.

    Returns (summary, m) where `summary` is a dictionary summarizing the
    results and `m` is the sorted NumPy array.  See source for further details.
    )rY   rT   )rR   r   r]   r_   )rY   rT   r   rU   bhs        r%   binary_heatmapr     s:    " 
3e	,	,	,B 
			?BI%%r&   c                     d t          d| j        d         dz             ddd         D             }| |z  }t          j        |                    d                    ddd         }|S )zU
    Performs a column-weighted sort on a binary matrix, returning the new index
    c                     g | ]}d |z  S )   rP   .0r9   s     r%   
<listcomp>z&sort_binary_matrix.<locals>.<listcomp>*  s    >>>!qAv>>>r&   r   N)axis)r   shaperb   argsortsum)mweights	score_matinds       r%   rd   rd   $  sp     ?>uQ
Q77"=>>>G GI *Y]]]**
+
+DDbD
1CJr&   c                     g }t          t          |                                           d d          D ]}|                    d|z             d                    |          S )zQ
    Convenience function useful printing the results from binary_heatmap().
    c                     | d         S )Nr   rP   )xs    r%   <lambda>z binary_summary.<locals>.<lambda>:  s
    ad r&   T)keyreversez%s : %s
)sortedr^   ra   r4   join)dr:   ri   s      r%   binary_summaryr   5  sa     	AtAGGIINNDIII % %	d#$$$$99Q<<r&   c                       e Zd ZddZddZdS )TrackCollectionr   Nr(   c                     || _         || _        || _        || _        | j         D ]E\  }}d|v rt	          d| j        j        z            d|v rt	          d| j        j        z            FdS )aZ  
        Handles multiple tracks on the same figure.

        :param config:
            A list of tuples that configures tracks.

            Each tuple contains a filename, BedTool object, or other
            iterable of pybedtools.Interval objects and a dictionary of
            keyword args that will be used to create a corresponding Track
            object, e.g.::

                [
                    ('a.bed',
                        dict(color='r', alpha=0.5, label='a')),
                    (BedTool('a.bed').intersect('b.bed'),
                        dict(color='g', label='b')),
                ]

            In this dictionary, do not specify `ybase`, since that will be
            handled for you.  Also do not specify `yheight` in these
            dictionaries -- `yheight` should be provided as a separate kwarg to
            so that the `padding` kwarg works correctly.

        :param figsize:
            Figure size tuple of (width, height), in inches.

        :param padding:
            Amount of padding to place in between tracks, as a fraction of
            `yheight`
        r!   zLPlease do not specify "ybase"; this is handled automatically by the %s classr"   zTPlease do not specify "yheight", this should be a separate arg to the %s constructorN)configrq   r"   paddingr<   	__class__rL   )r   r   r"   rq   r   r   r$   s          r%   r   zTrackCollection.__init__@  s    >  $ 	 	Hf&   ?AEAXY   F"" "$(N$;<   #	 	r&   c                 j   |/t          j        | j                  }|                    d          }g }g }d}d}| j        | j        z  }| j        ddd         D ]\  }}	t          |f| j        |d|	}
|
j        |z   }|	                    |
           d|	v r|
                    |	d                    n'|
                    t          |                     |dz  }|
                    |
j                   |                    |           |                    |           |                    d	           |S )
z
        If `ax` is None, create a new figure.  Otherwise, plot on `ax`.
        Iterates through the configuration, plotting each BedTool-like object
        as a separate track.
        Nrp   rr   r   r   )r"   r!   labelr   tight)r}   r~   rq   r   r"   r   r   r   r5   add_collectionr4   r   rK   
set_yticksset_yticklabelsr   )r   rG   r   yticksyticklabelsr!   r9   r   r   r$   ts              r%   r   zTrackCollection.plotq  sN    :*T\222C%%B,- !%DDbD 1 		& 		&HfhLELLVLLAFW$Ea   &  ""6'?3333""3q66***QMM!*%%%%
f
;'''
	r&   )r   Nr(   r   )rL   rM   rN   r   r   rP   r&   r%   r   r   ?  s=        / / / /b           r&   r   c                   8     e Zd Z	 	 	 	 	 	 d fd	Zd fd	Z xZS )BedToolsDemoNTc	                    |i }|i }|i }|| _         || _        || _        d |D             }|rX|D ]U}t          |d         t                    st          d          t          j                            ||d                   |d<   Vt          j
        |d         d                   }t          ||          }t          |          dk    r ||d         d         fi |}n+t          |          dk    r	 |di |}nt          d          |                    ||f           || _         t          t           |           j        |g|	R i |
 dS )	aT  
        Class to handle BEDTools demos in a way that maintains flexibility.

        If the `config` list contains only one item, assume the method is one
        of the "-i" tools that only operate on one file.

        If the `config` list contains two items, then use the first as "-a" and
        the second as "-b".

        :param config:
            Either a list of (filename, options) tuples -- see docstring for
            TrackCollection for more info.

        :param method:
            Method of `BedTool` object to use, e.g., 'intersect'

        :param data_path:
            If not None, this path will be prepended to the files listed in
            `config`

        :param result_kwargs:
            Configuration for the results track.  This isn't added to the
            config list because the results haven't been created yet...

        :param method_kwargs:
            Keyword argument that are passed to the method, e.g., `u=True`

        :param title_kwargs:
            Keyword args for plot title (the text itself will come from the
            command that was run; this is for things like font size)

        :param new_style:
            Edit commands so that they use the "new style" BEDTools calls
            ("bedtools intersect" rather than "intersectBed")

        :param subplots_adjust:
            Additional kwargs sent to the figure's subplots_adjust() method,
            e.g., `dict(top=0.7)`


        :param args:
            Addtional arguments sent to TrackCollection

        :param kwargs:
            Additional keyword arguments sent to TrackCollection
        Nc                 ,    g | ]}t          |          S rP   )r^   r   s     r%   r   z)BedToolsDemo.__init__.<locals>.<listcomp>  s    ***a$q''***r&   r   z<data_path was specified, so you need filenames in the configr   r   zM`config` must have length 1 (for '-i' tools) or length 2 (for '-a -b' tools).rP   )title_kwargs	new_styler   r   r   r<   ospathr   r   r   getattrr+   r4   resultsuperr   r   )r   r   method	data_pathresult_kwargsmethod_kwargsr   r   r   argsr$   confbt1r   r   s                 r%   r   zBedToolsDemo.__init__  s   v  M ML(". +*6*** 	; ; ;!$q'3// $2   ',,y$q'::Q 1..f%%v;;!VF1IaL::M::FF[[AV,,m,,FF0  
 	v}-...*lD!!*6CDCCCFCCCCCr&   c                    t          t          |                               |          }| j        j        d d          }| j        r@dt          j        j        t          j
                            |d                            z  |d<    |j        d                    d |D                       fi | j         | j        r |j        j        di | j         |S )Nzbedtools %sr    c                 L    g | ]!}t           j                            |          "S rP   )r   r   basenamer   s     r%   r   z%BedToolsDemo.plot.<locals>.<listcomp>  s(    AAAqrw//22AAAr&   rP   )r   r   r   r   _cmdsr   r   settings_prog_namesr   r   r   	set_titler   r   r   r~   )r   rG   cmdsr   s      r%   r   zBedToolsDemo.plot  s    <&&++B//{ #> 	%1"'2B2B472K2KLM G 	SXXAADAAABBXXdFWXXX 	>%BI%==(<===	r&   )NNNNTNr   )rL   rM   rN   r   r   __classcell__r   s   @r%   r   r     s|        
 ^D ^D ^D ^D ^D ^D@         r&   r   c                        e Zd Z fdZ xZS )ConfiguredBedToolsDemoc                    ddl }|                    t          |                    }ddg}|D ]}||v rt          d|z            ||d<   ||d<   |                    |            t          t          |           j        di | dS )a#  
        Wrapper around BedToolsDemo class that reads in a YAML config file.
        Useful for using the same "style" configuration many times.

        Contents of `yaml_config` must be YAML versions of BedToolsDemo args
        and kwargs **except** `method` and `method_kwargs`.
        r   Nr   r   z*'%s' cannot be provided in the YAML configrP   )yamlloadopenr<   r   r   r   r   )
r   yaml_configr   r   r$   r   r   
disalloweddisr   s
            r%   r   zConfiguredBedToolsDemo.__init__  s     	yyk**++0
 	U 	UCd{{ !MPS!STTT   X -_F4$d++4<<t<<<<<r&   )rL   rM   rN   r   r   r   s   @r%   r   r     s8        = = = = = = = = =r&   r   __main__zdemoconfig.yaml 	intersect)r   r   r   )u)TT)r   r   r   r   r   r}   numpyrb   r   r   r   objectrR   r   rd   r   r   r   r   rL   example_filename	conf_filer   r   ax1r   ax2showrP   r&   r%   <module>r      sK   				 # # # # # #     " " " " " " $ $ $ $ $ $        {= {= {= {= {=K& {= {= {=|A A A A AF A A AH& & & &0  "  R R R R Rf R R Rjl l l l l? l l l^= = = = =\ = = =0 z  ,
+,=>>I+
+B//I
 
 +R9  
dff  !
 +TTD\\\Y  
dff  CHJJJJJ3 r&   