
    tf2                    8   d Z ddlmZ ddlZddlZddlmZ ddlmZm	Z	 ddl
mZ ddlmZmZ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 d	dlmZmZmZmZm Z m!Z!  ed      Z" G d de#      Z$dddddddddd	dddddddddd	dZ%d Z&	 d0	 	 	 	 	 d1dZ'	 	 	 	 	 	 	 d2dZ(	 	 	 	 d3dZ)d Z*	 	 	 	 	 	 	 	 	 	 	 	 d4d Z+	 	 	 	 d5	 	 	 	 	 	 	 	 	 d6d!Z, G d" d#      Z- G d$ d%e-      Z. G d& d'e-      Z/ G d( d)e-      Z0 G d* d+e-      Z1 G d, d-e-      Z2 G d. d/e-      Z3y)7z
Contact Binners
~~~~~~~~~~~~~~~

Binners are iterators that convert input data of various flavors into a
properly sorted, chunked stream of binned contacts.

    )annotationsN)bisect_left)CounterOrderedDict)partial)AnyCallableIterator)is_integer_dtype   )
get_logger)
MapFunctor)GenomeSegmentationbalanced_partition
check_binsget_chromsizes	partitionrlencodezcooler.createc                      e Zd Zy)BadInputErrorN)__name__
__module____qualname__     _/var/www/html/software/conda/envs/higlass/lib/python3.12/site-packages/cooler/create/_ingest.pyr   r   %   s    r   r   TFreflectchromstart)r   r   end12)	decode_chromsis_one_basedtril_actionchrom_fieldanchor_fieldsided_fieldssuffixessortvalidatepos)r   r-   )bg2pairsc           	     	   |rt        j                  t        j                  | d   |j                  d      j
                        }t        j                  t        j                  | d   |j                  d      j
                        }na| d   j                  }| d   j                  }|
rAd|j                  fd|j                  ffD ]"  \  }}t        |      rt        d| ddz          |dk  |dk  z  }t        j                  |      r | }||   }||   }| |   j                         } t        |       sg | d	<   g | d
<   | S t        j                  | ||d   z            }t        j                  | ||d   z            }|r
|dz  }|dz  }|
r|j                  |j                  fD ]  }t        |      rt        d       |dk  |dk  z  }t        j                  |      r=| |   }t        dj                  |j                         j                  d                  |j                   j                  |   }|j                   j                  |   }||kD  ||kD  z  }t        j                  |      r=| |   }t        dj                  |j                         j                  d                  |1||kD  ||k(  ||kD  z  z  }t        j                  |      r
|dk(  r||   ||   c||<   ||<   ||   ||   c||<   ||<   |D ]\  }| j"                  |||d   z   f   | j"                  |||d   z   f   	 c| j"                  |||d   z   f<   | j"                  |||d   z   f<   ^ n|dk(  r+| }||   }||   }||   }||   }| |   j                         } nQ|dk(  r=| |   }t        dj                  |j                         j                  d                  t%        d| d      |j&                  }|j(                  }||j*                  }|j,                  }g }g }t/        ||||      D ]  \  } }!}"}#||    }$|| dz      }%|j1                  |$t        j2                  ||$|% ||    |!z   d      z   dz
         ||"   }$||"dz      }%|j1                  |$t        j2                  ||$|% ||"   |#z   d      z   dz
          || d	<   || d
<   n||   ||z  z   | d	<   ||   ||z  z   | d
<   |	r| j5                  d	d
g      } | S )Nchrom1T)orderedchrom2`z` column is non-integer. z6If string, use `decode_chroms=True` to convert to enumr   bin1_idbin2_id   z!Found a non-integer anchor columnzFound an anchor position with negative value. Make sure your coordinates are 1-based or use the --zero-based option when loading. 
{}	sepz8Found an anchor position exceeding chromosome length:
{}r   dropraisezFound lower triangle pairs:
{}Unknown tril_action value: ''rightside)nparraypdCategoricalcontigscodesvaluesdtyper   r   anycopylenformatheadto_csv
chromsizesloc
ValueErrorchrom_binoffsetbinsizechrom_absposstart_absposzipappendsearchsortedsort_values)&chunkgsr$   r%   r&   r'   r(   r)   r*   r+   r,   
chrom1_ids
chrom2_idscoldtto_dropmaskanchor1anchor2is_negerrchromsizes1chromsizes2	is_excessis_trilfieldrS   rT   rU   rV   bin1_idsbin2_idscid1pos1cid2pos2lohis&                                         r   _sanitize_recordsrt   C   s    XXNN5?BJJEKK

 XXNN5?BJJEKK

 8_++
8_++
%z'7'788ZEUEU:VW R'+'C5 9:RS  A~*q.1G	vvgx%
%
d  " u:ii hhu\HQK789Ghhu\HQK789G11 =='--0 	IB#B'#$GHH	I A+'A+.66&>-C%%+VCHHJ,=,=$,=,G%H  mm**:6mm**:6{*w/DE	66)	"CKRRHHJ%%$%/  
*:%'G*;<
 66'?i'w'w' ;G$j&9 6=W5EwwGW2 ''"2) E
 		'58A;+>">?		'58A;+>">?		'58A;+>">?		'58A;+>">? &x'-
'-
!$-!$-d((*'Gn#5<<
))d)3  !#?}A!NOO ((OjjG&)*gz7&S 	"D$d &B *BOO// B'd);d)B 	 !&B *BOO// B'd);d)B 		& $i#i*:6G9KKi*:6G9KKi !!9i"89 Lr   c                    |	 t         |   }ni }|j                         } |j                  di | t        |       }t        ||       |d<   t        t        fi |S # t        $ r t        d| d      dw xY w)a  
    Builds a funtion to sanitize and assign bin IDs to a data frame of
    paired genomic positions based on a provided genomic bin segmentation.

    Parameters
    ----------
    bins : DataFrame
        Bin table to compare records against.
    schema : str, optional
        Use pre-defined parameters for a particular format. Any options can be
        overriden via kwargs. If not provided, values for all the options below
        must be given.

    decode_chroms : bool
        Convert string chromosome names to integer IDs based on the order given
        in the bin table. Set to False if the chromosomes are already given as
        an enumeration, starting at 0. Records with either chrom ID < 0 are
        dropped.
    is_one_based : bool
        Whether the input anchor coordinates are one-based, rather than
        zero-based. They will be converted to zero-based.
    tril_action : 'reflect', 'drop', 'raise' or None
        How to handle lower triangle ("tril") records.
        If set to 'reflect', tril records will be flipped or "reflected"
        to their mirror image: "sided" column pairs will have their values
        swapped.
        If set to 'drop', tril records will be discarded. This is useful if
        your input data is symmetric, i.e. contains mirror duplicates of every
        record.
        If set to 'raise', an exception will be raised if any tril record is
        encountered.
    chrom_field : str
        Base name of the two chromosome/scaffold/contig columns.
    anchor_field : str
        Base name of the positional anchor columns.
    sided_fields : sequence of str
        Base names of column pairs to swap values between when
        mirror-reflecting records.
    suffixes : pair of str
        Suffixes used to identify pairs of sided columns. e.g.: ('1', '2'),
        ('_x', '_y'), etc.
    sort : bool
        Whether to sort the output dataframe by bin_id and bin2_id.
    validate : bool
        Whether to do type- and bounds-checking on the anchor position
        columns. Raises BadInputError.

    Returns
    -------
    callable :
        Function of one argument that takes a raw dataframe and returns a
        sanitized dataframe with bin IDs assigned.

    NzUnknown schema: 'r>   r\   r   )	SANITIZE_PRESETSKeyErrorrR   rK   updater   r   r   rt   )binsschemakwargsoptionsrP   s        r   sanitize_recordsr}      s    v 	F&v.G llnGGNNV%J&z48GDM$000  	F0:;E	Fs   	A A6c	                T   |r| |xx   dz  cc<   | |xx   dz  cc<   || |   | |   kD  }	t        j                  |	      r|dk(  r| j                  |	|f   | j                  |	|f   	 c| j                  |	|f<   | j                  |	|f<   |D ]\  }
| j                  |	|
|d   z   f   | j                  |	|
|d   z   f   	 c| j                  |	|
|d   z   f<   | j                  |	|
|d   z   f<   ^ n+|dk(  r| |	    } n|dk(  rt        d      t	        d| d      |r| j                  ||g      S | S )	Nr7   r   r   r;   r<   "Found bin1_id greater than bin2_idr=   r>   )rB   rJ   rQ   r   rR   rZ   )r[   r\   r%   r&   
bin1_field
bin2_fieldr)   r*   r+   rj   rk   s              r   _sanitize_pixelsr   -  s    jQjQ
 
#eJ&7766'?i'
 IIgz12IIgz12IIgz12IIgz12
 * E
 		'58A;+>">?		'58A;+>">?		'58A;+>">?		'58A;+>">? &wh'#$HII #?}A!NOO:>5j*56IEIr   c                V    t        |       }t        ||       |d<   t        t        fi |S )ai  
    Builds a function to sanitize an already-binned genomic data with
    genomic bin assignments.

    Parameters
    ----------
    bins : DataFrame
        Bin table to compare pixel records against.
    is_one_based : bool, optional
        Whether the input bin IDs are one-based, rather than zero-based.
        They will be converted to zero-based.
    tril_action : 'reflect', 'drop', 'raise' or None
        How to handle lower triangle ("tril") pixels.
        If set to 'reflect' [default], tril pixels will be flipped or
        "reflected" to their mirror image: "sided" column pairs will have their
        values swapped.
        If set to 'drop', tril pixels will be discarded. This is useful if
        your input data is duplexed, i.e. contains mirror duplicates of every
        record.
        If set to 'raise', an exception will be raised if any tril record is
        encountered.
    bin1_field : str
        Name of the column representing ith (row) axis of the matrix.
        Default is 'bin1_id'.
    bin2_field : str
        Name of the column representing jth (col) axis of the matrix.
        Default is 'bin2_id'.
    sided_fields : sequence of str
        Base names of column pairs to swap values between when mirror-reflecting
        pixels.
    suffixes : pair of str
        Suffixes used to identify pairs of sided columns. e.g.: ('1', '2'),
        ('_x', '_y'), etc.
    sort : bool
        Whether to sort the output dataframe by bin_id and bin2_id.

    Returns
    -------
    callable :
        Function of one argument that takes a raw dataframe and returns a
        sanitized dataframe.

    r\   )r   r   r   r   )ry   r{   rP   s      r   sanitize_pixelsr   \  s0    ^  %J%j$7F4L#.v..r   c                t   |rb| d   dk  | d   dk  z  }t        j                  |      rt        d      | d   |k\  | d   |k\  z  }t        j                  |      rt        d      |r+| d   | d   kD  }t        j                  |      rt        d      t        | t        j
                        st	        j
                  |       } |r`| j                  ddg      }	|	j                         r=| |	   }
t        dj                  |
j                         j                  d	                  |r| j                  ddg      } | S )
Nr5   r   r6   zFound bin ID < 0zaFound a bin ID that exceeds the declared number of bins. Check whether your bin table is correct.r   zFound duplicate pixels:
{}r8   r9   )rB   rJ   r   
isinstancerD   	DataFrame
duplicatedrM   rN   rO   rZ   )r[   n_binsboundscheck	triucheckdupcheckensure_sortedre   ri   rj   is_duprf   s              r   _validate_pixelsr     s:   	"Q&5+;a+?@66&> 2339%/E)4D4NO	66); 
 	"U9%5566'? DEEeR\\*U#!!9i"89::<-C-44SXXZ5F5F45F5PQ  !!9i"89Lr   c                ,    t        t        | ||||      S )Nr   r   r   r   r   )r   r   r   s        r   validate_pixelsr     s#     # r   c                J     i i |rdvr
dd<   dd<    fd}|S )a=  
    Generates a function that aggregates bin-assigned records by pixel.

    Parameters
    ----------
    sort : bool, optional
        Sort group keys. Get better performance by turning this off.
        Note that this does not influence the order of observations within each
        group.
    count : bool, optional
        Output the number of records per pixel. Default is True.
    agg : dict, optional
        Dict of column names -> functions or names.
    rename : dict, optional
        Dict to rename columns after aggregating.

    Returns
    -------
    Function that takes a dataframe of records with bin IDs assigned, groups
    them by pixel, counts them, and optionally aggregates other value columns.

    Notes
    -----
    The GroupBy 'count' method ignores NaNs within groups, as opposed to 'size'.

    countsizer5   c                    | j                  ddg      j                        j                        j                         S )Nr5   r6   )r+   columns)groupby	aggregaterenamereset_index)r[   aggr   r+   s    r   _aggregate_recordsz-aggregate_records.<locals>._aggregate_records  s9    MM9i0tM<Ys^VFV#[]		
r   r   )r+   r   r   r   r   s   ` `` r   aggregate_recordsr     sF    @ {~ #I#y
 r   c                       e Zd ZdZddZddZy)ContactBinnerz3
    Base class for iterable contact binners.

    c                ^    | j                   j                         }|j                  dd        |S )N_map)__dict__rK   pop)selfds     r   __getstate__zContactBinner.__getstate__   s'    MM 	fdr   c                    t         )a
  Iterator over chunks of binned contacts (i.e., nonzero pixels)

        Chunks are expected to have the following format:

        * dict of 1D arrays
        * keys `bin1_id`, `bin2_id`, `count`
        * arrays lexically sorted by `bin_id` then `bin2_id`

        )NotImplementedErrorr   s    r   __iter__zContactBinner.__iter__  s
     "!r   N)returndictr   zIterator[dict[str, np.ndarray]])r   r   r   __doc__r   r   r   r   r   r   r     s    


"r   r   c                  P    e Zd ZdZ	 	 	 	 	 	 	 	 d	dZd
dZddZddZddZddZ	y)HDF5AggregatorzE
    Aggregate contacts from a hiclib-style HDF5 contacts file.

    c                $   || _         |j                  dd      | _        |j                  dd      | _        |j                  dd      | _        |j                  dd      | _        t        ||      | _        || _        | j                         | _
        y )	NC1chrms1P1cuts1C2chrms2P2cuts2)h5r   r   r   r   r   r   r\   	chunksize_index_chromsr   )r   h5pairsrP   ry   r   r{   s         r   __init__zHDF5Aggregator.__init__  sx     **T8,**T7+**T8,**T7+$Z6"++-r   c           
         t        | j                  | j                     | j                        \  }}}t	        t        |            t	        |      k7  rt        d      t        t        |t        |||z                     S )Nz6Read pair coordinates are not sorted on the first axis)	r   r   r   r   rL   setrR   r   rW   )r   startslengthsrH   s       r   r   zHDF5Aggregator._index_chroms)  se    "*477477+;T^^"Ls6{s6{*UVVCFFW,< =>??r   c           	     *   t        d| j                  | j                     || fd| j                  | j                     || fd| j                  | j                     || fd| j                  | j
                     || fg      }t        j                  |      S )N	chrom_id1cut1	chrom_id2cut2)r   r   r   r   r   r   rD   r   )r   rr   rs   datas       r   _load_chunkzHDF5Aggregator._load_chunk0  s    dggdgg.r"56)"R01dggdgg.r"56)"R01	
 ||D!!r   c              #    K   | j                   }| j                  | j                  | j                  | j                  f\  }}}}| j
                  }| j                  j                  }| j                  j                  }	| j                  j                  }
| j                  j                  }| j                  j                  }| j                  j                  |   }| j                  j                  |d      \  }}|}|}||k  r|t        ||z   |      }}||   ||   |dz
     z   }t!        t#        j$                  ||d            dz
  }|d   |   }t'        ||   |||      }||k(  r|}t(        j+                  | d|        | j-                  ||      }|||   ||    ||   || z   }|||   ||    ||   || z   }t#        j.                  ||kD        rt1        d      |	=t#        j$                  ||d      dz
  |d<   t#        j$                  ||d      dz
  |d	<   nt#        j2                  |d
   |	z        j5                  t"        j6                        }t#        j2                  |d   |	z        j5                  t"        j6                        }|
|d   j8                     |z   |d<   |
|d   j8                     |z   |d	<   |j;                  dd	g      }|d   j=                         j?                         jA                  ddi      }| ||k  ry y w)N)r   r7   r?   r@   r     a   Found a read pair that maps to the lower triangle of the contact map (side1 > side2). Check that the provided chromosome ordering and read pair file are consistent such that all pairs map to the upper triangle with respect to the given chromosome ordering.r5   r6   r   r   r   r   r   r   )!r   r   r   r   r   r   r\   ry   rT   rS   rU   rV   idmapr   getminintrB   rY   r   loggerinfor   rJ   rR   floorastypeint64rH   r   r   r   r   )r   r   r   r   r   r   r   r   ry   rT   rS   rU   rV   cidchrom_lochrom_hirr   rs   absposbin_idbin_endtableabspos1abspos2rel_bin1rel_bin2gbyr   s                               r   r   zHDF5Aggregator.aggregate;  s    ''$''477DGG;BBNN	ww||''//''11ww++ww++ggmmE"!^^//X>(8mR)^X6B!#&R!V)<<FvGLMPQQF5k&)GWR['2x@BRxKK2$at% $$R,E"72;r"#56R9KKG"72;r"#56R9KKGvvg'( @  OOL'H1L i  OOL'H1L i  88E&MG$;<CCBHHM88E&MG$;<CCBHHM#253E3L3L#MPX#Xi #253E3L3L#MPX#Xi  --I 67CK g 67	  I] 8ms   LLLc                2    t        | j                  d         S )Nr   )rL   r   r   s    r   r   zHDF5Aggregator.sizey  s    4778$%%r   c              #     K   | j                   j                  D ]H  }| j                  |      D ]2  }|j                         D ci c]  \  }}||j                   c}} 4 J y c c}}w wN)r\   rF   r   itemsrH   )r   r   dfkvs        r   r   zHDF5Aggregator.__iter__|  s[     WW__ 	;EnnU+ ;/1xxz:tq!q!(({::;	;:s   AA+A%
A+N)r   z
h5py.GrouprP   	pd.Seriesry   pd.DataFramer   r   )r   zdict[str, tuple[int, int]])r   zdict[str, np.ndarray])r   strr   r   )r   r   r   )
r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     sM    
.. . 	.
 ."@	"<|&;r   r   c                  N    e Zd ZdZeddf	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 d	dZd
dZy)TabixAggregatorzl
    Aggregate contacts from a sorted, BGZIP-compressed and tabix-indexed
    tab-delimited text file.

    r7   Fc                J   	 dd l }dd l}	dd l}
|	j                  |
j
                  d<   || _        || _        t        |      | _	        |j                  dd      | _        |j                  dd      | _        t        ||      | _        || _        d | _        |j#                  |dd	
      5 }	 |j$                  D cg c]  }|j'                  d	       c}| _        t-        | j(                        st/        d      	 d d d        | j                  j$                  D ]-  }|| j(                  vst1        j2                  dd| dz          / t1        j2                  d       y # t        $ r t        d      d w xY wc c}w # t*        $ r |j$                  | _        Y w xY w# 1 sw Y   xY w)Nr   z%pysam is required to read tabix filesprotocolr      r      rasciiencodingNo reference sequences found.Did not find contig  '' in contact list file.zNOTE: When using the Tabix aggregator, make sure the order of chromosomes in the provided chromsizes agrees with the chromosome ordering of read ends in the contact list file.)pysamImportErrorpickledillHIGHEST_PROTOCOLsettingsr   n_chunksboolr%   r   r   r   r   r\   filepath	n_records	TabixFilerF   decodefile_contigsAttributeErrorrL   RuntimeErrorwarningswarn)r   r  rP   ry   mapr  r%   r{   r   r   r   fcr   s                 r   r   zTabixAggregator.__init__  s   	Q 	$*$;$;j!	  .**T1%**T1% %Z6 !__XsW_= 	D.@A		$J1QXXg%6$J! t(()"#BCC *	D WW__ 	ED---*r%8O-PP	 	>	
I  	QEFDP	Q. %K! .$%II!.	D 	DsM   E &F(E96E4E9 FE14E99FFFFF"c                n   |\  }}}dd l }| j                  }| j                  j                  }| j                  j                  }| j                  j
                  }	| j                  j                  }
| j                  j                  }t        | j                        }| j                  }| j                  }t        j                  d| d| d| d       | j                  j                  |||f      }g }|j                  |dd      5 }|j!                         }t#               }|j%                         D ]  \  }}|j                  ||j&                  |j(                  |	      D ]m  }||   }t        ||         |z
  }	 ||   }|5|	|   }|	|d
z      }|t-        j.                  ||| |
|   |z   d      z   d
z
  }n|	|   ||z  z   }||xx   d
z  cc<   o |s|j1                  t3        j4                  |t7        |j9                               t7        |j;                               dg d      j=                  d             |j?                           	 d d d        t        j                  d| d| d| d       tA        |      rt3        jB                  |d      S d S # t*        $ r Y Gw xY w# 1 sw Y   \xY w)Nr   Binning :-|*r   r   r   )parserr7   r?   r@   r5   r6   r   r   r6   	Finished axis)"r   r  r\   rT   r   rS   rU   rV   r   r%   r   r   r   r   fetchr  asTupler   iterrowsr   r    rw   rB   rY   rX   rD   r   listkeysrH   rZ   clearrL   concat)r   granger1   r   r    r   r  rT   r   rS   rU   rV   decrr   r   
these_binsrowsr  r  accumulatorr5   bin1liner3   rq   rp   rr   rs   r6   s                                r   r   zTabixAggregator.aggregate  s    $s==''//''11ww++ww++4$$%WWWWhvhawauB78WW]]FE3#78
__XsW_= .	$]]_F!)K!+!4!4!6 *$GGFDJJGP .D!"XFtBx=4/D!$V}
 ,T2,TAX6 oo ,R 3 ,T 2T 9%,      #2$"747?"K(A-(3.6 #LL'.'+K,<,<,>'?%)+*<*<*>%?
 !@ "k),	 !!#U*$	.	$` 	ixqqR89*-d)ryyA&==O $ ! !.	$ .	$s2   A4J+:J?CJ+	J(	$J+'J(	(J++J4c              #    K   t        | j                  | j                  | j                        }| j	                  | j
                  |      D ]5  }||j                         D ci c]  \  }}||j                   c}} 7 y c c}}w wr   r   r\   r  r  r   r   r   rH   r   grangesr   r   r   s        r   r   zTabixAggregator.__iter__  k     $TWWdmmT=N=NO))DNNG4 	;B~/1xxz:tq!q!(({::	;:   AB	B	#B:B	N)r  r   rP   r   ry   r   r  r   r  r   r%   r  r!  ztuple[str, int, int]r   zpd.DataFrame | Noner   r   r   r   r   r  r   r   r   r   r   r   r   r     sp     "4
4
 4
 	4

 4
 4
 4
lG>*G>	G>R;r   r   c                  T    e Zd ZdZedddf	 	 	 	 	 	 	 	 	 	 	 	 	 d	dZ	 	 	 	 d
dZddZy)PairixAggregatorzm
    Aggregate contacts from a sorted, BGZIP-compressed and pairix-indexed
    tab-delimited text file.

    r7   F|c                   	 dd l }	dd l}
dd l}|
j                  |j
                  d<   || _        || _        t        |      | _	        || _
        |	j                  |d      }|j                         | _        |j                         | _        |j!                         | _        |j%                         | _        |j)                         }||d   vrt+        d| d|d    d      t-        t.        j0                  j3                  |D cg c]  }|j5                  |       c}            | _        t9        | j6                        st;        d      t/        j<                  | j6                  d	      D ]G  \  }}|j?                  ||      s|j?                  ||      s,t;        d
d| | | d| | | d	z          tA        |d      r|jC                         }|dk  r
d}||z   |z   }tE        d      }|d	z  |z  }| j                  }tG        | j                  |      | _        | j                  |kD  r&tH        jK                  d| d| j                   d       tM        ||      | _'        || _(        d | _)        | jN                  jT                  D ]-  }|| j6                  vstW        jX                  dd| dz          / y # t        $ r t        d      d w xY wc c}w )Nr   z1pypairix is required to read pairix-indexed filesr   r   z The contig separator character `z+` does not appear in the first block name `z8`. Please specify the correct character as `block_char`.r   r   z'Pairs are not triangular: found blocks r>   z'' and 'get_linecountig    חAzPairs file has z  lines. Increasing max-split to .r   r   r   )-pypairixr   r   r   r   r  r   r  r  r%   
block_charopenget_chr1_colr   get_chr2_colr   get_startpos1_colr   get_startpos2_colr   get_blocknamesrR   r   	itertoolschainfrom_iterablesplitr  rL   r
  combinationsexists2hasattrr4  r   maxr   r   r   r\   r  r  rF   r  r  )r   r  rP   ry   r  r  r%   r7  r{   r6  r   r   r  
blocknames	blocknamec1c2n_linesMAXINT32	max_chunkold_nr   s                         r   r   zPairixAggregator.__init__  s   	 	$*$;$;j!	  .$MM(C(..".."%%'%%'%%'
Z]*2:, ?33=a=/ BAA 
  OO))=G+09	
++ 
 4$$%>??,,T->->B 	FByyR QYYr2%6"="j\"XbT*bTKL 	 1o&oo'G{%"X-7E
I!|y0HMMEx8DM}}u$%gY ///3}}oQ@ %Z6 ! WW__ 	ED---*r%8O-PP	I  	C	:+s   J2  K2Kc                   |\  }}}dd l }| j                  }| j                  j                  }| j                  j                  }| j                  j
                  }	| j                  j                  }
| j                  j                  }t        | j                        }| j                  }| j                  }t        j                  d| d| d| d       |j                  |d      }| j                  j                  |||f      }| j                  j                   |d  }t#               }g }|j%                         D ]v  \  }}|j'                         D ]  \  }}||   }||k7  r?|j)                  ||      r-|j+                  |d|||j,                  |j.                        }|}n,|j+                  ||j,                  |j.                  |d|      }|}|D ]b  }t        ||         |z
  }|5|	|   }|	|dz      }|t1        j2                  ||| |
|   |z   d	      z   dz
  }n|	|   ||z  z   }||xx   dz  cc<   d  |s|j5                  t7        j8                  |t;        |j=                               t;        |j?                               d
g d
      jA                  d             |jC                          y t        j                  d| d| d| d       tE        |      rt7        jF                  |d      S d S )Nr   r  r  r  r  r   r7   r?   r@   r  r   r6   r  r  )$r6  r  r\   rT   rP   rS   rU   rV   r   r%   r   r   r   r   r8  r  r   r   r  r   rC  query2Dr   r    rB   rY   rX   rD   r   r  r  rH   rZ   r  rL   r   ) r   r!  r1   r   r    r6  r  rT   rP   rS   rU   rV   r"  r   r   r  r#  remaining_chromsr%  r$  r5   r&  r3   rp   chrom2_sizeiteratorpos2_colr'  rq   rr   rs   r6   s                                    r   r   zPairixAggregator.aggregatem  s    $s==''//WW''
''11ww++ww++4$$% WWWWhvhawauB78MM(C(WW]]FE3#78
77==1 i'002 1	 MGT 0 6 6 8  .(0V#		&&(A yy;

DHH H  "H yy

DHHfa H  "H$ .DtH~.5D,T2,TAX6 oo ,R 3 ,T 2T 9%,      #2$"747?"K(A-(%. .D KK#*#'(8(8(:#;!%k&8&8&:!;
 < +i(	 c1	 f 	ixqqR89*-d)ryyA&==r   c              #    K   t        | j                  | j                  | j                        }| j	                  | j
                  |      D ]5  }||j                         D ci c]  \  }}||j                   c}} 7 y c c}}w wr   r)  r*  s        r   r   zPairixAggregator.__iter__  r,  r-  N)r  r   rP   r   ry   r   r  r   r  r   r%   r  r7  r   r.  r   r/  r   r   r   r1  r1    s     "UU U 	U
 U U U UnP>*P>	P>d;r   r1  c                  $    e Zd ZdZd Zd ZddZy)SparseBlockLoaderr   c                   t        ||      }|| _        t        |j                        | _        || _        t        |      }t        |      }|d   j                  j                  }t        j                  |dz   t              | _        d}t        t        |       D ]  \  }	}
}|	| j                  ||dz    |dz   } || j                  |d  || _        y Nr   r7   )rI   r   r   ry   r  indexchromosomesr   rL   catrG   rB   zerosr   offsetsrW   r   mappingr   rP   ry   r_  r   n_chromsr   	chrom_idscurr_valr   _lengthvalues               r   r   zSparseBlockLoader.__init__      $
+	
 0 01"z?TM%%++	xx1C8%((9*=%> 	!!E7E16DLLEAI.qyH	! #)XYr   c           	         	 | j                   ||f   }|S # t        $ rJ 	 | j                   ||f   j                  }Y |S # t        $ r t        j                  d| d| d        w xY ww xY wNzBlock for {z, z} not foundr_  rw   Tr  r  r   r1   r3   blocks       r   select_blockzSparseBlockLoader.select_block      	LL0E   	VV^466   VHBvhlKL	    	A(='A$$A(c           	   #    K   dd l }| j                  }t        |      D ]  \  }}| j                  |   }| j                  |dz      |z
  }t	        d|| j
                        }|D ]  \  }}	g }
||d  D ]=  }	 | j                  ||      }|
j                  |j                         ||	d d f          ? |j                  j                  |
      j                         j                         }|j                  |j                  |j                  }}}||z   ||z   k  }||   ||   ||   }}}||z   ||z   |d   y # t        $ r Y w xY ww)Nr   r7   r  )scipy.sparser[  	enumerater^  r   r   rm  rw   rX   tocsrsparsehstacktocoorowr_   r   )r   scipyr[  rn   r1   offsetchrom1_nbinsspansrr   rs   chunksr3   rl  Xijr   rb   triu_itriu_jtriu_vs                        r   r   zSparseBlockLoader.__iter__  sg     	&&%k2 	LD&\\$'F<<q1F:Lat~~>E B)$%0 ;F! $ 1 1&& A MM%++-2q"9:; LL''/557==?%%a1

3)*4!D'1T7  &%# 	 $ ! !s+   A0E3D8B3E8	E	EE	ENr   r   r   r   r   r   rm  r   r   r   r   rV  rV    s    $	r   rV  c                  ,    e Zd ZdZ	 	 	 	 	 	 ddZddZy)ArrayLoaderz
    Load a dense genome-wide numpy array contact matrix.
    Works with array-likes such as h5py.Dataset and memmapped arrays

    See Also
    --------
    numpy.save, numpy.load (mmap_mode)

    c                l    t        |      |j                  d   k7  rt        d      || _        || _        y )Nr   z4Number of bins must equal the dimenion of the matrix)rL   shaperR   rC   r   )r   ry   rC   r   s       r   r   zArrayLoader.__init__  s2     t9A&STT
"r   c              #    K   | j                   j                  d   }t        d|| j                        }|D ]T  \  }}| j                   ||d d f   }t	        j
                  |      \  }}||z   |k  }||   ||   }
}	||	z   |
||	|
f   d V y w)Nr   r  )rC   r  r   r   rB   nonzero)r   r   r{  rr   rs   r}  r~  r  rb   r  r  s              r   r   zArrayLoader.__iter__  s     !!!$!VT^^4  	FB

2b5!8$A::a=DAqFq=DtWagFF ;!66>* 	s   BBN)ry   r   rC   znp.ndarray | h5py.Datasetr   r   r   )r   r   r   r   r   r   r   r   r   r  r    s-    	#	# )	# 		#r   r  c                  "    e Zd ZdZd Zd Zd Zy)ArrayBlockLoaderr   c                   t        ||      }|| _        t        |j                        | _        || _        t        |      }t        |      }|d   j                  j                  }t        j                  |dz   t              | _        d}t        t        |       D ]  \  }	}
}|	| j                  ||dz    |dz   } || j                  |d  || _        y rX  rY  r`  s               r   r   zArrayBlockLoader.__init__3  rf  r   c           	         	 | j                   ||f   }|S # t        $ rJ 	 | j                   ||f   j                  }Y |S # t        $ r t        j                  d| d| d        w xY ww xY wrh  ri  rk  s       r   rm  zArrayBlockLoader.select_blockE  rn  ro  c           	   #    K   | j                   }t        |      D ]  \  }}| j                  |   }| j                  |dz      |z
  }t        d|| j                        }|D ]  \  }}g }	||d  D ]/  }
	 | j                  ||
      }|	j                  |||d d f          1 t        j                  |	d      }t        j                  |      \  }}||z   ||z   k  }||   ||   }}||z   ||z   |||f   d   y # t        $ r Y w xY ww)Nr7   r   r  r  )r[  rr  r^  r   r   rm  rw   rX   rB   concatenater  )r   r[  rn   r1   ry  rz  r{  rr   rs   r|  r3   rl  r}  r~  r  rb   r  r  s                     r   r   zArrayBlockLoader.__iter__P  s>    &&%k2 	LD&\\$'F<<q1F:Lat~~>E B)$%0 3F! $ 1 1&& A MM%2q/23 NN62zz!}1

3!"4!D'  &%vv~. 	 $ ! !s+   A+D.C8 A8D8	D	DD	DNr  r   r   r   r  r  0  s    $	r   r  r   )ry   r   rz   z
str | Noner   &Callable[[pd.DataFrame], pd.DataFrame])Fr   r5   r6   r   r!   T)ry   r   r   r  )r   r   r   r  r   r  r   r  r   r  r   r  )TTNN)
r+   r  r   r  r   zdict[str, Any] | Noner   zdict[str, str] | Noner   r  )4r   
__future__r   r>  r  bisectr   collectionsr   r   	functoolsr   typingr   r	   r
   h5pynumpyrB   pandasrD   pandas.api.typesr   _loggingr   _typingr   utilr   r   r   r   r   r   r   rR   r   rv   rt   r}   r   r   r   r   r   r   r   r   r1  rV  r  r  r   r   r   <module>r     s   #    ,  * *    - !    
O	$	J 	  1
  (
 4^F F1
F1F1 ,	F1X 	,J^1/
1/ ,1/hD  	
  ,$ !%$(	4
44 
4 "	4
 ,4n" "0m;] m;`J;m J;Zt;} t;n> >B&- &R;} ;r   