
    DUfs                       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'dMdZ( G d de          Z)	 	 	 dNdOd%Z*dPd)Z+dQd.Z,dRd2Z-dSd3Z.	 dTdUd9Z/	 dVdWd>Z0 G d? d@e          Z1	 	 	 	 dXdYdEZ2	 	 	 	 dXdZdIZ3	 dVd[dLZ4dS )\    )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 indexeslist[np.ndarray | h5py.Dataset]bufsizeintreturntuple[np.ndarray, np.ndarray]c                   t          j        | d         j                  }t          t	          |                     D ]}|| |         z  }d}|d         }dg}dg}d}	 t          |t          ||z   |          |          dz
  }	|	|k    r|	dz  }	|                    |	           |                    ||	                    ||	         |k    rn|	}||	         }yt          j        |          }t          j        |          }t          j	        |          }
|
|k    
                                }|dk    r0t          j        | d| d|
                                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   T)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)r   r   combined_indexicombined_startcombined_nnzbin1_partitioncum_nrecordsr!   hinrecords_per_epochn_overs               J/var/www/html/software/conda/lib/python3.11/site-packages/cooler/reduce.pymerge_breakpointsr;   .   s   V Xgaj.//N3w<<   % %'!*$N!"%LSN3L	
B,(,77
 
 
 	 88 !GBb!!!N2.///"--'+),, Xn--N8L))L.. 7*//11Fzz L Lg L L.@.D.D.F.FKL L L	
 	
 	

 <''    c                  (    e Zd ZdZ	 	 dddZddZdS )CoolerMergerz,
    Implementation of cooler merging.

    Ncoolerslist[Cooler]mergebufr   columnslist[str] | Noneaggdict[str, Any] | Nonec                f   t          |          | _        || _        |dgn|| _        d | j        D             | _        || j                            |           |d         j        }|t          d |D                       dk    rt          d          |d         j	        }t          dt          |                    D ]4}t          j        ||         j	        |k              st          d          5d S |d                                         g d         d d          }t          dt          |                    D ]s}||                                         g d         d d          }	t          |	          t          |          k    st          j        |	|k              st          d	          td S )
Ncountc                    i | ]}|d S r-    .0cols     r:   
<dictcomp>z)CoolerMerger.__init__.<locals>.<dictcomp>   s    7773C777r<   r   c                    h | ]	}|j         
S rJ   )binsizerL   cs     r:   	<setcomp>z(CoolerMerger.__init__.<locals>.<setcomp>   s    ///!AI///r<   r
   z%Coolers must have the same resolutionz&Coolers must have the same chromosomeschromstartendz$Coolers must have same bin structure)listr?   rA   rB   rD   updaterP   r(   
ValueError
chromsizesr'   r$   allbins)
selfr?   rA   rB   rD   rP   r[   r2   r]   bins2s
             r:   __init__zCoolerMerger.__init__   s    G}} $+Oyy77$,777?HOOC    !*$//w///00144 !HIII .J1c'll++ O Ovgaj3zABB O$%MNNNOO O 1:??$$%>%>%>?BD1c'll++ M M
))*C*C*CDQQQGJJ#d))++BF5D=4I4I+$%KLLL ,M Mr<   r   Iterator[dict[str, np.ndarray]]c           	   #  ~  
K   d | j         D             }t          || j                  \  }}t          j        |          }t
                              dt          |                      t
                              d|            t
                              d|            d | j         D             }t
                              d|            dgt          | j                   z  }|dd          D ]Ǌ

fd	|D             }t          j
        d
 t          | j         ||          D             dd          }|                    ddgd                              | j                                                  }	d |	                                D             V  t
                              d|            |}d S )Nc                D    g | ]}|                     d           d         S )rindexes/bin1_offset)openrQ   s     r:   
<listcomp>z)CoolerMerger.__iter__.<locals>.<listcomp>   s(    LLL!166#;;45LLLr<   zn_merge_epochs: zbin1_partition: znrecords_per_merge_epoch: c                P    g | ]#}t          |                                          $S rJ   )r(   pixelsrQ   s     r:   rg   z)CoolerMerger.__iter__.<locals>.<listcomp>   s&    666AAHHJJ666r<   znnzs: r   r
   c                     g | ]
}|         S rJ   rJ   )rL   indexbin1_ids     r:   rg   z)CoolerMerger.__iter__.<locals>.<listcomp>   s    999U7^999r<   c                `    g | ]+\  }}}||z
  d k    |                                 ||         ,S )r   )ri   )rL   rR   rV   stops       r:   rg   z)CoolerMerger.__iter__.<locals>.<listcomp>   sH       &5$u)) HHJJuTz*)))r<   T)axisignore_indexrl   bin2_idsortc                $    i | ]\  }}||j         S rJ   valuesrL   kvs      r:   rN   z)CoolerMerger.__iter__.<locals>.<dictcomp>   s     66641a1ah666r<   zrecords consumed: )r?   r;   rA   r$   r,   loggerinfor(   debugpdconcatzipgroupby	aggregaterD   reset_indexitems)r^   r   r5   r6   r8   nnzsstartsstopscombineddfrl   s             @r:   __iter__zCoolerMerger.__iter__   s     LLt|LLL (9$-'P'P$W\22@s+='>'>@@AAA888999F2DFFGGG66666OTOO$$$s4<(((%abb) 	 	G9999999E y *-dlFE*J*J  
 !  H   )Y!7d CC48$$  76288::666666KK4U44555FF1	 	r<   )NN)r?   r@   rA   r   rB   rC   rD   rE   r   ra   )__name__
__module____qualname____doc__r`   r   rJ   r<   r:   r>   r>      sX          %)%)M M M M M<( ( ( ( ( (r<   r>   
output_uristr
input_uris	list[str]rA   rB   rC   dtypesrE   rD   Nonec           	     @   t                               d                    d                    |                               d |D             }d |D             }t	          |          rd}	n!t          |          sd}	nt          d          |d	g}t          t                    }
|D ]`}|	                                j
        }|D ]B}||vrt          d
| d|j         d          |
|                             ||                    Ca|i }|D ]}||vrt          j        |
|          ||<   |d                                         g d         dd         }|d         j                            dd          }t#          ||||          }t%          | ||f||||	d| dS )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:
{}
c                ,    g | ]}t          |          S rJ   r   )rL   paths     r:   rg   z!merge_coolers.<locals>.<listcomp>  s    000TF4LL000r<   c                $    g | ]}|j         d k    S )symmetric-upper)storage_mode)rL   clrs     r:   rg   z!merge_coolers.<locals>.<listcomp>
  s!    EEEs#44EEEr<   TFz1Cannot merge symmetric and non-symmetric coolers.NrG   Pixel value column '' not found in input ''.r   rT   zgenome-assembly)rA   rB   rD   )rB   r   assemblysymmetric_upper)rz   r{   formatjoinr\   anyrZ   r   rX   ri   r   filenamer*   r$   result_typer]   getr>   r   )r   r   rA   rB   r   rD   kwargsclrsis_symmr   	dtype_mapr   pixel_dtypesrM   r]   r   iterators                    r:   r   r      s   b KK%%dii
&;&;<<===00Z000DEEEEEG
7|| N\\ NLMMM)D!!I 	9 	9zz||* 	9 	9C,&& /3 / /!l/ / /  
 #%%l3&78888	9 ~ : :f.)C.9F3K7<<>>3334QQQ7DAw| 1488HD8W#NNNH
	 '	 	 	 	 	 	 	r<   edges
np.ndarraymaxlenc           
        t          j        |           } t          |           dk    r| d         dk    sJ t           j        dt          j        t          j        |                     f         }fdt          dt          t          j        |d         z                                D             }|	                    |d                    t          j
        t          j        ||                    }| |         S )zGiven an integer interval partition ``edges`` from 0..nnz, prune the
    edges to make the new subintervals roughly ``maxlen`` in length.
       r   c                    g | ]}|z  S rJ   rJ   )rL   r2   r   s     r:   rg   z+_greedy_prune_partition.<locals>.<listcomp>?  s    LLL1FQJLLLr<   r    )r$   asarrayr(   r_cumsumr,   r'   r   ceilr*   uniquesearchsorted)r   r   cumlencutsidxs    `   r:   _greedy_prune_partitionr   8  s     JuEu::??uQx1}}}}U1bi///0FLLLLaRWVBZ&5H-I-I)J)J K KLLLDKKr

)BOFD11
2
2C:r<   r[   	pd.Seriesbase_binsizebins_per_tilec                    ||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   r   r$   log2)r[   r   r   tile_length_bptotal_bpn_tilesn_zoom_levelss          r:   get_quadtree_depthr   E  sX     #\1N :Hi>122G 	"''"2"23344Mr<   rV   mulIterator[int]c              #  `   K   t          |           t          |          }} | V  	 | |z  } | V  
)z
    Generate a geometric progression of integers.

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

    r   rV   r   s     r:   geomprogr   `  sB       USXX3E
KKKr<   c              #  R   K   t          |           } | V  	 dD ]	}| |z  V  
| dz  } )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.

    T)r      
   r   r   r   s     r:   niceprogr   o  sQ       JJE
KKK 	 	C#+r<   nicern   styleLiteral['binary', 'nice']	list[int]c                   | |k    rg S |dk    rt          | d          }n)|dk    rt          |           }nt          d| d           t          |          g}	 t          |          }||k    rn|                    |           ,|S )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   r   z1Expected style value of 'binary' or 'nice'; got 'r   )r   r   rZ   nextr*   )rV   rn   r   genseqns         r:   preferred_sequencer     s    R t||	ua  	&uooPuPPPQQQ99+CIIt88

1	 Jr<   resolutionsbaseslist[int] | None)tuple[np.ndarray, np.ndarray, np.ndarray]c                   |t          |           h}nt          |          }t          j        t	          |                    |                               }t          j        t          |          t                     }t          j        t          |          t                     }t          t          |                    ddd         D ]>\  }}|dz
  }|dk    r.|||         z  dk    r|||<   |||         z  ||<   n|dz  }|dk    .?t          |          D ]1\  }}|dk    r&||         |vrt          d||          d| d          2|||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(   r   rX   	enumeraterZ   )r   r   resnpredmultr2   targetps           r:   get_multiplier_sequencer     s   8 }[!!"E

8F5;;{334455DGCIIS))))DGCIIS))))D)D//**44R40  	6E1ffQ1$$Q DG+QQ 1ff $  177tAwe++2d1g 2 2).2 2 2  
 tr<   c                  N    e Zd ZdZefddZedd            ZddZddZ	ddZ
dS ) CoolerCoarsenerz/
    Implementation of cooler coarsening.

    
source_urir   factorr   	chunksizerB   r   rD   rE   	batchsizemapr   c                B   || _         || _        || _        t          |t                    r|dk    sJ || _        t	          |          | _        ddg| _        t          |          | _	        | j        | j	        z   | _
        d | j	        D             | _        || j                            |           t          |          }|j        }	|j        | _        |                    d          | _        |                    d          | _        | j        d | _        n| j        |z  | _        |                                g d         d d          }
|                     |
|	|          | _        t1          |	| j                  | _        g }| j        j                                        D ]E\  }}| j        |         }| j        |dz            }|                    | j        |||                    F|                    | j        d                    t=          || j                  | _        d S )	Nr
   rl   rq   c                    i | ]}|d S rI   rJ   rK   s     r:   rN   z,CoolerCoarsener.__init__.<locals>.<dictcomp>  s    ===3C===r<   zindexes/chrom_offsetre   rT   r    ) _mapr   r   
isinstancer   r   r   index_columnsrX   value_columnsrB   rD   rY   r   r[   rP   old_binsize
_load_dsetold_chrom_offsetold_bin1_offsetnew_binsizer]   coarsen_binsnew_binsr   gsidmapr   extendr*   r   r   )r^   r   r   r   rB   rD   r   r   r   r[   old_binsr   _chromr2   c0c1s                   r:   r`   zCoolerCoarsener.__init__  s    	$"&#&&56A::::Y'3!']])D,>>==$*<===?HOOC   Z  ^
 ; #/E F F"~~.CDD ##D#/&8D88::7778;))(JGG$Z?? ,,.. 	= 	=IFA&q)B&q1u-BLL-bFl;<<<<T)"-...,UDNCC


r<   r  pd.DataFramer[   r   r   c                    fd}|                      dd          g d                             |                              d          S )Nc                    | ddg                                          j        d d          }| d         j        dz
  d          j        }t          |          t          |          k     rt          j        || j                 f         }||d<   |S )NrU   rV   rW   r
   )copyilocrv   r(   r$   r   name)groupoutrW   r[   r   s      r:   _eachz+CoolerCoarsener.coarsen_bins.<locals>._each9  s    '*+00227&AC,#FQJ$8&$89@C3xx#c((""eCEJ!778CJJr<   rU   TobservedrT   )drop)r   applyr   )r  r[   r   r  s    `` r:   r  zCoolerCoarsener.coarsen_bins5  sf    	 	 	 	 	 	 WWtW,,-F-F-FHU5\\[d[##		
r<   spantuple[int, int]c                   |\  }}t          | j                  }|                    dd          | j                 }|||         }t                              | d|            | j        j        }| j        j        }| j        j	        }	| j        j
        }
|d         j        }|d         j        }|d         j        }|d         j        }|Q|	|         |z   }|	|         |z   }t          j        |
|d	
          dz
  |d<   t          j        |
|d	
          dz
  |d<   nzt          j        ||z                                t                     }t          j        ||z                                t                     }||         |z   |d<   ||         |z   |d<   |                    | j        d                              | j                                                  S )NTF)r   convert_enum chrom1chrom2start1start2right)sider
   rl   rq   rr   )r   r   ri   rB   rz   r{   r  rP   chrom_binoffsetchrom_absposstart_absposrv   r$   r   floorastyper   r   r   r   rD   r   )r^   r  r!   r7   r   tablechunkrP   r"  r#  r$  	chrom_id1	chrom_id2r  r  
abs_start1
abs_start2rel_bin1rel_bin2s                      r:   
_aggregatezCoolerCoarsener._aggregateH  s   BT_%%

5
99$,GberLLBLL!!! '/'1w+w+(O*	(O*	x'x'?%i069J%i069JjwGGG!K ) jwGGG!K ) x 01188==Hx 01188==H.y9HDE).y9HDE) MM$,4M88Ytx  []]	
r<   c                    	 |                      |          }n/# t          $ r"}t          t          |                    |d }~ww xY w|S N)r/  MemoryErrorRuntimeErrorr   )r^   r  r(  es       r:   r   zCoolerCoarsener.aggregatep  sT    	.OOD))EE 	. 	. 	.s1vv&&A-	.s    
A?Ara   c              #    K   | j         }t          t          | j        d d         | j        dd                              }t	          dt          |          |          D ]}	 |dk    rt          j                     |                     | j	        ||||z                      }|dk    rt          j
                     n# |dk    rt          j
                     w w xY w|D ]"}d |                                D             V  #d S )Nr    r
   r   c                $    i | ]\  }}||j         S rJ   ru   rw   s      r:   rN   z,CoolerCoarsener.__iter__.<locals>.<dictcomp>  s     :::tq!q!(:::r<   )r   rX   r   r   r'   r(   r   acquirer   r   releaser   )r^   r   spansr2   resultsr   s         r:   r   zCoolerCoarsener.__iter__w  s     N	SCRC$*QRR.99::q#e**i00 		; 		;A#q==LNNN))DNE!a)m:K4LMMq==LNNN q==LNNNN ! ; ;::rxxzz:::::::;		; 		;s   "?B;;CN)r   r   r   r   r   r   rB   r   rD   rE   r   r   r   r   )r  r
  r[   r   r   r   r   r
  )r  r  r   r
  r   )r   r   r   r   r   r`   staticmethodr  r/  r   r   rJ   r<   r:   r   r     s          6D 6D 6D 6D 6Dp 
 
 
 \
$&
 &
 &
 &
P   ; ; ; ; ; ;r<   r   base_urir   r   nprocc           
        t          |           }	t          |          }|dg}|i }|	                                j        }
|D ]=}||
vrt	          d| d|	j         d          |                    ||
|                    >	 |dk    r/t          j        |          }|                    dt                     t          | ||||||dk    r|j        nt                    }|j        }|                    d	d
           t          |||f||	j        dk    d| |dk    r|                                 dS dS # |dk    r|                                 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

    NrG   r   r   r   r
   r   )rB   rD   r   r   r*   Tr   )r   r   )r   r   ri   r   rZ   r   
setdefaultmpPoolr   r   r   r  r   r   close)r<  r   r   r   r=  rB   r   rD   r   r   input_dtypesrM   poolr   r  s                  r:   r   r     s   l 

C[[F)~::<<&L 6 6l""VsVVclVVV   c<#4555519975>>Dfd+++"!AII3
 
 
 $(D)))	
 ,0AA	
 	
 	
 	
 	
 199JJLLLLL 95199JJLLLL s   BD5 5E	base_urisstr | list[str]outfilec                   t          | t                    r| g} i }	i }
t                      }| D ]}t          |          \  }}t	          ||          }|j        dn|j        }||f|	|<   |                                dd                             dd                                          	                                |
|<   |
                    |           t          ||          \  }}}t          |          }t                              d| d           |dg}|D ]R}t                              d	t          |          z              |	|         \  }}t          j        |d
          5 }t          j        |d          5 }d| }|                    |dz   ||dz              |                    |dz   ||dz              ddgt%          |          D ]%}|                    |d| z   ||d| z              &|                    |dz   ||dz              ||         j                            ||         j                   ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   Tt+          |          D ]q}||         dk    r|||                  }|||         z  }t                              d| d| d           t-          |d| z   |d| z   ||         |f||||dd| rt          j        |d          5 }|j                            dt.          d           ddd           dS # 1 swxY w Y   dS )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
   rU   Tr  z$Copying base matrices and producing z new zoom levels.rG   z
Bin size: rd   wz/resolutions/z/chromsz/binsrl   rq   z/pixels/z/indexesr    zAggregating from z to r#   z::resolutions/r+)r=  rB   r   rD   modezHDF5::MCOOL)r   zformat-version)r   r   r   r   r   rP   r]   r   sizer0   addr   r(   rz   r{   h5pyFiler  rX   attrsrY   r'   r   r   )rE  rG  r   r   r=  rB   r   rD   r   parsed_urisn_bins_longest_chrombase_resolutions	input_uriinfileingroupr   r   r   r   r   n_zoomssrcdestprefixrM   r2   prev_binsizerP   fws                                r:   r   r     s   j )S!!  K	Kuu + +	*955VW%%K/qqS[%+W$5L!HHJJqqqMWWtW,,TVVSUU	 	\* 	\**** /{<LMMD$$iiG
KKQwQQQRRR) ) : :L3|#4#44555%l3Yvs## 	:sYw$$	:(,3\33FHHWy($0BCCCHHWw&fw.>???!9=tG}}=  ....----   
 HHWz)4*1DEEEL%%c'l&8999	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	: 	:" 7^^ 
 
7b==DG}a(DDD'DDDEEE5|5550w000G		

 	
 	
 	
 	
 	
 	
 
7D	!	! 
R
$8PQQ	
 	
 	

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
sI   +I%CII%II%II%%I)	,I)	#L88L<?L<rT  tuple[int, dict[str, int]]c           	        t          |           \  }}t          ||          }t          |j        |j        t
                    }d}	t                              dt          j	        |j                              t                              d|j                    t                              d|            t                              dd|z              t                              d| d| dz   d	z              t                      }
t          |          }|j        }t                              d
t          |          z   dz   t          |          z              t          j        |d          5 }t          j        |d          5 }|                    ||t          |                     ||
|<   ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   t          |dz
  dd          D ]}||	z  }t          |dz             }t          |          }t                              dt          |          z   dz   t          |          z              t!          |dz   t          |          z   |dz   t          |          z   |	|||           ||
|<   t          j        |d          5 }|j                            d|i           ||j        d<   |j                            |
           ddd           n# 1 swxY w Y   ||
fS )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: rd   rI  Nr
   r    zAggregating at zoom level: z::)r   r=  r   rJ  zmax-zoomz	max-zooms)r   r   r   r[   rP   HIGLASS_TILE_DIMrz   r{   r$   r-   r   r   rN  rO  r  r'   r   rP  rY   )rT  rG  r=  r   r   rU  rV  r   rW  r   zoom_levels	zoomLevelrP   rX  rY  r2   	prevLevelr\  s                     r:   legacy_zoomifyrc  r  s    'y11OFG

!
!C >NOOGF
KK>bfS^&<&<>>???
KK)CK))***
KK%G%%&&&
KK2AL22333
KK'
?
?W
?
?
?	@
!	"   --KGIkG
KKY/-?#g,,NOOO 
63		 )3	7C	 	 )$($I///!(I) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) ) 7Q;B'' ) )6AJJ	FF	))nn 'll	
 	
 	
 	dNS^^+dNS^^+	
 	
 	
 	
 ")I	7D	!	! %R
W-... '
$$$	% % % % % % % % % % % % % % % KsI   4G
*G 4G G	GG	GGG1AK>>LL)r   r   r   r   r   r   )NNN)r   r   r   r   rA   r   rB   rC   r   rE   rD   rE   r   r   )r   r   r   r   r   r   )r[   r   r   r   r   r   r   r   )rV   r   r   r   r   r   )rV   r   r   r   )r   )rV   r   rn   r   r   r   r   r   r1  )r   r   r   r   r   r   )r
   NNN)r<  r   r   r   r   r   r   r   r=  r   rB   rC   r   rE   rD   rE   r   r   )rE  rF  rG  r   r   r   r   r   r=  r   rB   rC   r   rE   rD   rE   r   r   )
rT  r   rG  r   r=  r   r   r   r   r]  )5
__future__r   r   r.   bisectr   collectionsr   r   typingr   r   r	   rN  multiprocessr@  numpyr$   pandasr}   _loggingr   _typingr   _versionr   apir   r   r   parallelr   utilr   r   __all__r   rz   r_  	ZOOMS_4DNr;   r>   r   r   r   r   r   r   r   r   r   r   rc  rJ   r<   r:   <module>rs     s   " " " " " "         0 0 0 0 0 0 0 0 ) ) ) ) ) ) ) ) ) )                                . . . . . .       ) ) ) ) ) ) ) )       6 6 6 6 6 6 6 6
?
?
? 
H		   	"U( U( U( U(pL L L L L= L L Lf !%$(!%` ` ` ` `F
 
 
 
   6      ( (.: : : : :~ #7 7 7 7 7tM; M; M; M; M;m M; M; M;j  $$(!%h h h h h`  $$(!%}
 }
 }
 }
 }
B DH@  @  @  @  @  @  @ r<   