
    tfs                    @   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
mZm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mZ dd	lm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" g dZ# ee$      Z%dZ&g dZ'	 	 	 	 	 	 d dZ( G d de      Z)	 	 	 d!	 	 	 	 	 	 	 	 	 	 	 	 	 d"dZ*d#dZ+	 	 	 	 	 	 	 	 d$dZ,d%dZ-d&dZ.	 d'	 	 	 	 	 	 	 d(dZ/	 d)	 	 	 	 	 d*dZ0 G d de      Z1	 	 	 	 d+	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,dZ2	 	 	 	 d+	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d-dZ3	 d)	 	 	 	 	 	 	 	 	 d.dZ4y)/    )annotationsN)bisect_right)OrderedDictdefaultdict)AnyIteratorLiteral   )
get_logger)
MapFunctor)__format_version_mcool__)Cooler)ContactBinnercreate)lock)GenomeSegmentationparse_cooler_uri)merge_coolerscoarsen_coolerzoomify_cooler   )i  i  i  i'  ia  iP  i i i  i@B i%& i@KL i c                t   t        j                  | d   j                        }t        t	        |             D ]
  }|| |   z  } d}|d   }dg}dg}d}	 t        |t        ||z   |      |      dz
  }	|	|k(  r|	dz  }	|j                  |	       |j                  ||	          ||	   |k(  rn|	}||	   }^t        j                  |      }t        j                  |      }t        j                  |      }
|
|kD  j                         }|dkD  r-t        j                  | d| d|
j                         dd       ||fS )	a  
    Given ``k`` bin1_offset indexes, determine how to partition the data from
    ``k`` corresponding pixel tables for a k-way merge.

    The paritition is a subsequence of bin1 IDs, defining the bounds of chunks
    of data that will be loaded into memory from each table in a single "epoch"
    of merging data. The bounds are calculated such that no single epoch will
    load more than ``bufsize`` records into memory.

    However, the ``bufsize`` condition is not guaranteed and a warning will be
    raised if it cannot be satisfied for one or more epochs (see Notes).

    Parameters
    ----------
    indexes : sequence of 1D array-like of equal length
        Offset arrays that map bin1 IDs to their offset locations in a
        corresponding pixel table.
    bufsize : int
        Maximum number of pixel records loaded into memory in a single merge
        epoch.

    Returns
    -------
    bin1_partition : 1D array
        Bin1 IDs defining where to partition all the tables for merging.
    cum_nrecords : 1D array
        Cumulative number of records (from all pixel tables combined) that will
        be processed at each epoch.

    Notes
    -----
    The one exception to the post-condition is when a single bin1 increment in
    a table contains more than ``bufsize`` records.
    r   )lor
   z/ merge epochs will require buffering more than z  pixel records, with as many as g.)npzerosshaperangelenr   minappendarraydiffsumwarningswarnmax)indexesbufsizecombined_indexicombined_startcombined_nnzbin1_partitioncum_nrecordsr   hinrecords_per_epochn_overs               W/var/www/html/software/conda/envs/higlass/lib/python3.12/site-packages/cooler/reduce.pymerge_breakpointsr6   .   su   V XXgaj../N3w<  %'!*$%N!"%LSN3L	
B
(,7
 	 8 !GBb!N2./"-'+) , XXn-N88L)L. 7*//1FzhEgY O..@.D.D.Fq-IL	

 <''    c                  4    e Zd ZdZ	 	 d	 	 	 	 	 	 	 ddZddZy)CoolerMergerz,
    Implementation of cooler merging.

    Nc                $   t        |      | _        || _        |dgn|| _        | j                  D ci c]  }|d c}| _        || j                  j                  |       |d   j                  }|t        |D ch c]  }|j                   c}      dkD  rt        d      |d   j                  }t        dt        |            D ]2  }	t        j                  ||	   j                  |k(        r)t        d       y |d   j                         g d   d d  }
t        dt        |            D ]W  }	||	   j                         g d   d d  }t        |      t        |
      k7  st        j                  ||
k(        rNt        d       y c c}w c c}w )	Ncountr&   r   r
   z%Coolers must have the same resolutionz&Coolers must have the same chromosomeschromstartendz$Coolers must have same bin structure)listcoolersmergebufcolumnsaggupdatebinsizer!   
ValueError
chromsizesr    r   allbins)selfrA   rB   rC   rD   colrF   crH   r-   rJ   bins2s               r5   __init__zCoolerMerger.__init__   sn    G} $+Oy*.,,73CJ7?HHOOC  !*$$w/!AII/014 !HII ..J1c'l+ Ovvgaj33zAB$%MNNO 1:??$%>?BD1c'l+ M
)*CDQGJ#d)+BFF5D=4I$%KLLM 8 0s   
F;Fc              #  V  K   | j                   D cg c]  }|j                  d      d    }}t        || j                        \  }}t	        j
                  |      }t        j                  dt        |              t        j                  d|        t        j                  d|        | j                   D cg c]  }t        |j                                }}t        j                  d|        dgt        | j                         z  }|dd  D ]  }|D 	cg c]  }	|	|   	 }
}	t        j                  t        | j                   ||
      D cg c]!  \  }}}||z
  dkD  r|j                         || # c}}}dd	
      }|j                  ddgd	      j                  | j                         j#                         }|j%                         D ci c]  \  }}||j&                   c}} t        j                  d|
        |
} y c c}w c c}w c c}	w c c}}}w c c}}w w)Nrindexes/bin1_offsetzn_merge_epochs: zbin1_partition: znrecords_per_merge_epoch: znnzs: r   r
   T)axisignore_indexbin1_idbin2_idsortzrecords consumed: )rA   openr6   rB   r   r%   loggerinfor!   debugpixelspdconcatzipgroupby	aggregaterD   reset_indexitemsvalues)rK   rM   r*   r0   r1   r3   nnzsstartsrU   indexstopsr>   stopcombineddfkvs                    r5   __iter__zCoolerMerger.__iter__   s    ?C||L!166#;45LL (9$--'P$WW\2&s+='>&?@A''78912D1EFG)-6AAHHJ66fTFO$s4<<((%ab) 	G189U7^9E9 yy +.dllFE*J &5$u) HHJuT*
 !H   )Y!7d C488$  ,.88:641a1ahh;66KK,UG45F1	 M 7
 :  7sA   H)HBH); H?H)H&,H)&H8AH)H#*?H))NN)rA   zlist[Cooler]rB   intrC   list[str] | NonerD   dict[str, Any] | NonereturnzIterator[dict[str, np.ndarray]])__name__
__module____qualname____doc__rO   ro    r7   r5   r9   r9      sD     %)%)MM M "	M
 #M<(r7   r9   c           	     "   t         j                  dj                  dj                  |                   |D cg c]  }t	        |       }}|D 	cg c]  }	|	j
                  dk(   }
}	t        |
      rd}nt        |
      sd}nt        d      |dg}t        t              }|D ]Z  }	|	j                         j                  }|D ]9  }||vrt        d	| d
|	j                   d      ||   j                  ||          ; \ |i }|D ]  }||vst        j                   ||    ||<   ! |d   j#                         g d   dd }|d   j                  j%                  dd      }t'        ||||      }t)        | ||f||||d| yc c}w c c}	w )a  
    Merge multiple coolers with identical axes.

    The merged cooler is stored at ``output_uri``.

    .. versionadded:: 0.8.0

    Parameters
    ----------
    output_uri : str
        Output cooler file path or URI.
    input_uris : list of str
        List of input file path or URIs of coolers to combine.
    mergebuf : int
        Maximum number of pixels processed at a time.
    columns : list of str, optional
        Specify which pixel value columns to include in the aggregation.
        Default is to use all available value columns.
    dtypes : dict, optional
        Specific dtypes to use for value columns. Default is to propagate
        the current dtypes of the value columns.
    agg : dict, optional
        Functions to use for aggregating each value column. Pass the same kind
        of dict accepted by ``pandas.DataFrame.groupby.agg``. Default is to
        apply 'sum' to every value column.
    kwargs
        Passed to ``cooler.create``.

    Notes
    -----
    The default output file mode is 'w'. If appending output to an existing
    file, pass `mode='a'`.

    See also
    --------
    cooler.coarsen_cooler
    cooler.zoomify_cooler

    zMerging:
{}
symmetric-upperTFz1Cannot merge symmetric and non-symmetric coolers.Nr;   Pixel value column '' not found in input ''.r   r<   zgenome-assembly)rB   rC   rD   )rC   dtypesassemblysymmetric_upper)rZ   r[   formatjoinr   storage_moderI   anyrG   r   r@   r]   r   filenamer#   r   result_typerJ   getr9   r   )
output_uri
input_urisrB   rC   r   rD   kwargspathclrsclris_symmr   	dtype_mappixel_dtypesrL   rJ   r   iterators                     r5   r   r      s   b KK%%dii
&;<=%/0TF4L0D0@DEs#44EGE
7|\LMM)D!I 	9zz|** 	9C,& *3% 0!ll^2/ 
 #%%l3&78	9	9 ~ :f..)C.9F3K:
 7<<>34Q7DAw|| 148HD8W#NH
	 '	 	I 1Es   FFc           	        t        j                  |       } t        |       dk\  r| d   dk(  sJ t         j                  dt        j                  t        j
                  |             f   }t        dt        t        j                  |d   |z                    D cg c]  }||z  	 }}|j                  |d          t        j                  t        j                  ||            }| |   S c c}w )zGiven an integer interval partition ``edges`` from 0..nnz, prune the
    edges to make the new subintervals roughly ``maxlen`` in length.
       r   r   )r   asarrayr!   r_cumsumr%   r    rp   ceilr#   uniquesearchsorted)edgesmaxlencumlenr-   cutsidxs         r5   _greedy_prune_partitionr   8  s     JJuEu:?uQx1},,UU1bii//0F %aRWWVBZ&5H-I)J KL1FQJLDLKKr

))BOOFD1
2C: Ms   C)c                    ||z  }t        |       }t        j                  ||z        }t        t        j                  t	        j
                  |                  }|S )aH  
    Number of zoom levels for a quad-tree tiling of a genomic heatmap.

    At the base resolution, we need N tiles, where N is the smallest power of
    2 such that the tiles fully cover the 1D data extent. From that starting
    point, determine the number of zoom levels required to "coarsen" the map
    up to 1 tile.

    )r&   mathr   rp   r   log2)rH   base_binsizebins_per_tiletile_length_bptotal_bpn_tilesn_zoom_levelss          r5   get_quadtree_depthr   E  sP     #\1N :Hii>12G 		"'''"234Mr7   c              #  T   K   t        |       t        |      }} |  	 | |z  } |  
w)z
    Generate a geometric progression of integers.

    Beginning with integer ``start``, yield an unbounded geometric progression
    with integer ratio ``mul``.

    rp   r>   muls     r5   geomprogr   `  s4      USX3E
K
 s   &(c              #  R   K   t        |       } |  	 dD ]	  }| |z    | dz  } w)z
    Generate a nice progression of integers.

    Beginning with integer ``start``, yield a sequence of "nicely" spaced
    integers: an unbounded geometric progression with ratio 10, interspersed
    with steps of ratios 2 and 5.

    )r      
   r   r   r   s     r5   niceprogr   o  s@      JE
K
 	C#+	 s   %'c                    | |kD  rg S |dk(  rt        | d      }n |dk(  rt        |       }nt        d| d       t              g}	 t        |      }||kD  r	 |S |j	                  |       %)a  
    Return a sequence of integers with a "preferred" stepping pattern.

    Parameters
    ----------
    start : int
        Starting value in the progression.
    stop : int
        Upper bound of progression, inclusive. Values will not exceed this.
    style : {'nice', 'binary'}
        Style of progression. 'nice' gives geometric steps of 10 with 2 and 5
        in between. 'binary' gives geometric steps of 2.

    Returns
    ------
    list of int

    Examples
    --------
    For certain values of `start` (n * 10^i), nice stepping produces familiar
    "preferred" sequences [1]_:

    Note denominations in Dollars (1-2-5)

        >>> preferred_sequence(1, 100, 'nice')
        [1, 2, 5, 10, 20, 50, 100]


    Coin denominations in Cents

        >>> preferred_sequence(5, 100, 'nice')
        [5, 10, 25, 50, 100]

    .. [1] https://en.wikipedia.org/wiki/Preferred_number#1-2-5_series

    binaryr   nicez1Expected style value of 'binary' or 'nice'; got 'r   )r   r   rG   nextr#   )r>   rj   stylegenseqns         r5   preferred_sequencer     s    R t|	ua 	&uoFugRPQ9+C
It8 J 	

1	 r7   c                @   |t        |       h}nt        |      }t        j                  t	        |j                  |                   }t        j                  t        |      t               }t        j                  t        |      t               }t        t        |            ddd   D ]7  \  }}|dz
  }|dk\  s|||   z  dk(  r|||<   |||   z  ||<   -|dz  }|dk\  r'9 t        |      D ]'  \  }}|dk(  s||   |vst        d||    d| d       |||fS )	a"  
    From a set of target resolutions and one or more base resolutions
    deduce the most efficient sequence of integer multiple aggregations
    to satisfy all targets starting from the base resolution(s).

    Parameters
    ----------
    resolutions: sequence of int
        The target resolutions
    bases: sequence of int, optional
        The base resolutions for which data already exists.
        If not provided, the smallest resolution is assumed to be the base.

    Returns
    -------
    resn: 1D array
        Resolutions, sorted in ascending order.
    pred: 1D array
        Index of the predecessor resolution in `resn`. A value of -1 implies
        that the resolution is a base resolution.
    mult: 1D array
        Multiplier to go from predecessor to target resolution.

    N)dtyper   r
   r   zResolution z. cannot be derived from the base resolutions: r   )r"   setr   r$   sorteduniononesr!   rp   r@   	enumeraterG   )resolutionsbasesresnpredmultr-   targetps           r5   get_multiplier_sequencer     sB   8 }[!"E
88F5;;{345DGGCIS))DGGCIS))D)D/*4R40 	6E1fQ1$Q DG+QQ 1f $ 17tAwe+d1gY ')).q2  tr7   c                  p    e Zd ZdZef	 	 	 	 	 	 	 	 	 	 	 	 	 ddZe	 	 	 	 	 	 	 	 d	d       Zd
dZd
dZ	ddZ
y)CoolerCoarsenerz/
    Implementation of cooler coarsening.

    c                \   || _         || _        || _        t        |t              r|dkD  sJ || _        t	        |      | _        ddg| _        t        |      | _	        | j                  | j                  z   | _
        | j                  D ci c]  }|d c}| _        || j                  j                  |       t        |      }	|	j                  }
|	j                  | _        |	j#                  d      | _        |	j#                  d      | _        | j                   d | _        n| j                   |z  | _        |	j+                         g d   d d  }| j-                  ||
|      | _        t1        |
| j.                        | _        g }| j2                  j4                  j7                         D ]G  \  }}| j$                  |   }| j$                  |dz      }|j9                  | j&                  |||          I |j;                  | j&                  d          t=        || j                        | _        y c c}w )	Nr
   rU   rV   r&   zindexes/chrom_offsetrR   r<   r   ) _map
source_uri	batchsize
isinstancerp   factor	chunksizeindex_columnsr@   value_columnsrC   rD   rE   r   rH   rF   old_binsize
_load_dsetold_chrom_offsetold_bin1_offsetnew_binsizerJ   coarsen_binsnew_binsr   gsidmaprd   extendr#   r   r   )rK   r   r   r   rC   rD   r   maprL   r   rH   old_binsr   _chromr-   c0c1s                    r5   rO   zCoolerCoarsener.__init__  s    	$"&#&6A:55Y'3!']))D,>,>>*.*<*<=3CJ=?HHOOC Z ^^
 ;; #/E F"~~.CD ##D#//&8D88:78;))(JG$Z? ,,. 	=IFA&&q)B&&q1u-BLL--bFl;<		=
 	T))"-.,UDNNC
A >s   	
H)c                    fd}| j                  dd      g d   j                  |      j                  d      S )Nc                   | ddg   j                         j                  d d    }| d   j                  dz
  d    j                  }t        |      t        |      k  r"t        j
                  || j                     f   }||d<   |S )Nr=   r>   r?   r
   )copyilocre   r!   r   r   name)groupoutr?   rH   r   s      r5   _eachz+CoolerCoarsener.coarsen_bins.<locals>._each9  s    '*+00277&AC,##FQJ$8&$89@@C3x#c("eeCEJJ!778CJJr7   r=   Tobservedr<   )drop)ra   applyrc   )r   rH   r   r   s    `` r5   r   zCoolerCoarsener.coarsen_bins5  s>    	 WWtW,-FHU5\[d[#		
r7   c                   |\  }}t        | j                        }|j                  dd      | j                     }||| }t        j                  | d|        | j                  j                  }| j                  j                  }| j                  j                  }	| j                  j                  }
|d   j                  }|d   j                  }|d   j                  }|d   j                  }|M|	|   |z   }|	|   |z   }t        j                  |
|d	
      dz
  |d<   t        j                  |
|d	
      dz
  |d<   nlt        j                  ||z        j                  t               }t        j                  ||z        j                  t               }||   |z   |d<   ||   |z   |d<   |j#                  | j$                  d      j'                  | j(                        j+                         S )NTF)r   convert_enum chrom1chrom2start1start2right)sider
   rU   rV   rW   )r   r   r]   rC   rZ   r[   r   rF   chrom_binoffsetchrom_absposstart_absposre   r   r   floorastyperp   ra   r   rb   rD   rc   )rK   spanr   r2   r   tablechunkrF   r   r   r   	chrom_id1	chrom_id2r   r   
abs_start1
abs_start2rel_bin1rel_bin2s                      r5   
_aggregatezCoolerCoarsener._aggregateH  s   BT__%

5
9$,,Gbrd!B4L! ''//''11ww++ww++(O**	(O**	x''x''?%i069J%i069JjwG!K ) jwG!K ) xx 0188=Hxx 0188=H.y9HDE).y9HDE) MM$,,4M8Ytxx []	
r7   c                v    	 | j                  |      }|S # t        $ r}t        t        |            |d }~ww xY wN)r
  MemoryErrorRuntimeErrorstr)rK   r  r  es       r5   rb   zCoolerCoarsener.aggregatep  s?    	.OOD)E   	.s1v&A-	.s    	838c              #    K   | j                   }t        t        | j                  d d | j                  dd              }t	        dt        |      |      D ]  }	 |dkD  rt        j                          | j                  | j                  ||||z          }|dkD  rt        j                          	 |D ]2  }|j                         D ci c]  \  }}||j                   c}} 4  y # |dkD  rt        j                          w w xY wc c}}w w)Nr   r
   r   )r   r@   r`   r   r    r!   r   acquirer   rb   releaserd   re   )rK   r   spansr-   resultsrl   rm   rn   s           r5   ro   zCoolerCoarsener.__iter__w  s     NN	SCR$**QR.9:q#e*i0 		;A#q=LLN))DNNE!a)m4LMq=LLN ;/1xxz:tq!q!(({::;		; q=LLN ! ;s*   AD;C'2DD
D'D	DN)r   r  r   rp   r   rp   rC   	list[str]rD   rr   r   rp   r   r   )r   pd.DataFramerH   	pd.Seriesr   rp   rt   r  )r  ztuple[int, int]rt   r  rs   )ru   rv   rw   rx   r   rO   staticmethodr   r
  rb   ro   ry   r7   r5   r   r     s     6D6D 6D 	6D
 6D #6D 6D 6Dp 

,5
?B
	
 
$&
P;r7   r   c           
     x   t        |       }	t        |      }|dg}|i }|	j                         j                  }
|D ]7  }||
vrt	        d| d|	j
                   d      |j                  ||
|          9 	 |dkD  r+t        j                  |      }|j                  dt               t        | ||||||dkD  rj                  nt              }|j                  }|j                  d	d
       t        |||f||	j                  dk(  d| |dkD  rj                          yy# |dkD  rj                          w w xY w)aP  
    Coarsen a cooler to a lower resolution by an integer factor *k*.

    This is done by pooling *k*-by-*k* neighborhoods of pixels and aggregating.
    Each chromosomal block is coarsened individually. Result is a coarsened
    cooler stored at ``output_uri``.

    .. versionadded:: 0.8.0

    Parameters
    ----------
    base_uri : str
        Input cooler file path or URI.
    output_uri : str
        Input cooler file path or URI.
    factor : int
        Coarsening factor.
    chunksize : int
        Number of pixels processed at a time per worker.
    nproc : int, optional
        Number of workers for batch processing of pixels. Default is 1,
        i.e. no process pool.
    columns : list of str, optional
        Specify which pixel value columns to include in the aggregation.
        Default is to use all available value columns.
    dtypes : dict, optional
        Specific dtypes to use for value columns. Default is to propagate
        the current dtypes of the value columns.
    agg : dict, optional
        Functions to use for aggregating each value column. Pass the same kind
        of dict accepted by ``pandas.DataFrame.groupby.agg``. Default is to
        apply 'sum' to every value column.
    kwargs
        Passed to ``cooler.create``.

    See also
    --------
    cooler.zoomify_cooler
    cooler.merge_coolers

    Nr;   r}   r~   r   r
   r   )rC   rD   r   r   r#   Tr|   )r   r   )r   rp   r]   r   rG   r   
setdefaultmpPoolr   r   r   r   r   r   close)base_urir   r   r   nprocrC   r   rD   r   r   input_dtypesrL   poolr   r   s                  r5   r   r     sd   l 
C[F)~::<&&L 6l"&se+Ecll^SUV  c<#45619775>Dfd+"!AI3
 $$(D)	
 ,,0AA	
 	
 19JJL 519JJL s   7BD! !D9c                   t        | t              r| g} i }	i }
t               }| D ]  }t        |      \  }}t	        ||      }|j
                  dn|j
                  }||f|	|<   |j                         dd j                  dd      j                         j                         |
|<   |j                  |        t        ||      \  }}}t        |      }t        j                  d| d       |dg}|D ]  }t        j                  d	t        |      z          |	|   \  }}t        j                   |d
      5 }t        j                   |d      5 }d| }|j#                  |dz   ||dz          |j#                  |dz   ||dz          ddgt%        |      D ]!  }|j#                  |d| z   ||d| z          # |j#                  |dz   ||dz          ||   j&                  j)                  ||   j&                         ddd       ddd        t+        |      D ][  }||   dk(  r|||      }|||   z  }t        j                  d| d| d       t-        |d| z   |d| z   ||   |f||||dd| ] t        j                   |d      5 }|j&                  j)                  dt.        d       ddd       y# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   yxY w)a  
    Generate multiple cooler resolutions by recursive coarsening.

    Result is a "zoomified" or "multires" cool file stored at ``outfile``
    using the MCOOL v2 layout, where coolers are stored under a hierarchy of
    the form ``resolutions/<r>`` for each resolution ``r``.

    .. versionadded:: 0.8.0

    Parameters
    ----------
    base_uris : str or sequence of str
        One or more cooler URIs to use as "base resolutions" for aggregation.
    outfile : str
        Output multires cooler (mcool) file path.
    resolutions : list of int
        A list of target resolutions to generate.
    chunksize : int
        Number of pixels processed at a time per worker.
    nproc : int, optional
        Number of workers for batch processing of pixels. Default is 1,
        i.e. no process pool.
    columns : list of str, optional
        Specify which pixel value columns to include in the aggregation.
        Default is to use only the column named 'count' if it exists.
    dtypes : dict, optional
        Specific dtypes to use for value columns. Default is to propagate
        the current dtypes of the value columns.
    agg : dict, optional
        Functions to use for aggregating each value column. Pass the same kind
        of dict accepted by ``pandas.DataFrame.groupby.agg``. Default is to
        apply 'sum' to every value column.
    kwargs
        Passed to ``cooler.create``.

    See also
    --------
    cooler.coarsen_cooler
    cooler.merge_coolers

    Nr
   r=   Tr   z$Copying base matrices and producing z new zoom levels.r;   z
Bin size: rQ   wz/resolutions/z/chromsz/binsrU   rV   z/pixels/z/indexesr   zAggregating from z to r   z::resolutions/r+)r   rC   r   rD   modezHDF5::MCOOL)r   zformat-version)r   r  r   r   r   rF   rJ   ra   sizer)   addr   r!   rZ   r[   h5pyFiler   r@   attrsrE   r    r   r   )	base_urisoutfiler   r   r   rC   r   rD   r   parsed_urisn_bins_longest_chrombase_resolutions	input_uriinfileingroupr   r   r   r   r   n_zoomssrcdestprefixrL   r-   prev_binsizerF   fws                                r5   r   r     s8   j )S!K	Ku +	*95VW%KK/qS[[%+W$5L!HHJqMWWtW,TVSU	 	\* 	\*+ /{<LMD$$iG
KK6wi?PQR) ) :L3|#445%l3YYvs# 	:sYYw$	:(,$\N3FHHWy($0BCHHWw&fw.>?!9=tG}= ..xu-- HHWz)4*1DEL%%c'l&8&89	: 	: 	::( 7^ 
7b=DG}a('~T'!DE|n55wi00G		

 	
 	

& 
7D	! 
R
$8PQ	

 
I	: 	: 	: 	:H
 
s1   6KB/J:<K#K:K?KK	Kc           	        t        |       \  }}t        ||      }t        |j                  |j                  t
              }d}	t        j                  dt        j                  |j                                t        j                  d|j                          t        j                  d|        t        j                  dd|z          t        j                  d| d| dz   d	z          t               }
t        |      }|j                  }t        j                  d
t        |      z   dz   t        |      z          t        j                  |d      5 }t        j                  |d      5 }|j                  ||t        |             ||
|<   ddd       ddd       t        |dz
  dd      D ]  }||	z  }t        |dz         }t        |      }t        j                  dt        |      z   dz   t        |      z          t!        |dz   t        |      z   |dz   t        |      z   |	|||       ||
|<    t        j                  |d      5 }|j"                  j%                  d|i       ||j"                  d<   |j"                  j%                  |
       ddd       ||
fS # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   ||
fS xY w)zL
    Quad-tree tiling using legacy MCOOL layout (::0, ::1, ::2, etc.).

    r   ztotal_length (bp): z	binsize: z	n_zooms: zquad tile cover: zCopying base matrix to level z and producing z new zoom levels zcounting down to 0...zZoom level: z bin size: rQ   r$  Nr
   r   zAggregating at zoom level: z::)r   r   r   r%  zmax-zoomz	max-zooms)r   r   r   rH   rF   HIGLASS_TILE_DIMrZ   r[   r   r&   r   r  r)  r*  r   r    r   r+  rE   )r1  r-  r   r   r   r2  r3  r   r4  r   zoom_levels	zoomLevelrF   r5  r6  r-   	prevLevelr9  s                     r5   legacy_zoomifyr?  r  s    'y1OFG

!C >NOGF
KK%bffS^^&<%=>?
KK)CKK=)*
KK)G9%&
KK#AL>23
KK'I_WI->
?	@
!	" -KGIkkG
KKY/-?#g,NO 
63	 )3	7C	 )$($I/!(I) ) 7Q;B' )6AJ	F	))n 'l	
 	dNS^+dNS^+	
 ")I)), 
7D	! %R
W-. '
$	% KG) ) ) ):% Ks1   J++"JJ+
AJ8J(	#J++J58K)r*   zlist[np.ndarray | h5py.Dataset]r+   rp   rt   ztuple[np.ndarray, np.ndarray])NNN)r   r  r   r  rB   rp   rC   rq   r   rr   rD   rr   rt   None)r   
np.ndarrayr   rp   rt   rA  )rH   r  r   rp   r   rp   rt   rp   )r>   rp   r   rp   rt   Iterator[int])r>   rp   rt   rB  )r   )r>   rp   rj   rp   r   zLiteral['binary', 'nice']rt   	list[int]r  )r   rC  r   zlist[int] | Nonert   z)tuple[np.ndarray, np.ndarray, np.ndarray])r
   NNN)r  r  r   r  r   rp   r   rp   r   rp   rC   rq   r   rr   rD   rr   rt   r@  )r,  zstr | list[str]r-  r  r   rC  r   rp   r   rp   rC   rq   r   rr   rD   rr   rt   r@  )
r1  r  r-  r  r   rp   r   rp   rt   ztuple[int, dict[str, int]])5
__future__r   r   r'   bisectr   collectionsr   r   typingr   r   r	   r)  multiprocessr  numpyr   pandasr^   _loggingr   _typingr   _versionr   apir   r   r   parallelr   utilr   r   __all__ru   rZ   r;  	ZOOMS_4DNr6   r9   r   r   r   r   r   r   r   r   r   r   r?  ry   r7   r5   <module>rS     s   "    0 ) )        .  )  6
? 
H	 	"U(,U(U( #U(pL= Lf !%$(!%``` ` 	`
 "` 
` 
`F
  		6( (.::
: %: 	:~ #777 /7tM;m M;j  $$(!%hhh h 	h
 h h "h 
h 
h`  $$(!%}
}
}
 }
 	}

 }
 }
 "}
 
}
 
}
B DH@ @  @ ),@ 9<@ @ r7   