o
    Nrf                     @  s~  d dl mZ d dlZd dlmZ d dlZd dlZd dlZd dl	m	Z	 d dl
mZ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mZmZ dd	lmZmZ dd
lm Z m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3 ddl4m5Z5 edZ6dxddZ7	dydzdd Z8d{d(d)Z9d|d2d3Z:d}d6d7Z;d~d9d:Z<dd=d>Z=dddBdCZ>ddFdGZ?	dddIdJZ@ddNdOZAddPdQZB											?		?	?	ddRdSZC				T			UddVdWZD	ddXdYZEdZF ZGd[F ZHd\d] ZIeIeGeHd^					?		_	T			U				?		dddrdsZJeIeGeHd^					?		_	T			U				?		dddvdwZKdS )    )annotationsN)datetime)AnyIterable   )
get_logger)Tabular)__format_version____format_version_scool____version__)getput)get_binsizeget_chromsizesget_meta
infer_metaparse_cooler_urirlencode   )BIN1OFFSET_DTYPE	BIN_DTYPECHROM_DTYPECHROMID_DTYPECHROMOFFSET_DTYPECHROMSIZE_DTYPECOORD_DTYPECOUNT_DTYPEMAGICMAGIC_SCOOLPIXEL_DTYPESPIXEL_FIELDSURL)validate_pixelszcooler.creategrp
h5py.Groupchromspd.DataFrameh5optsdictreturnNonec                 C  s   t |}tj|d td}| j	d|f|j|d| | j	d|ft|d d| t| }dD ]}|	| q4|rGt
| ||  dS dS )	a4  
    Write the chromosome table.

    Parameters
    ----------
    grp : h5py.Group
        Group handle of an open HDF5 file with write permissions.
    chroms : DataFrame
        Chromosome table containing at least 'chrom' and 'length' columns
    h5opts : dict
        HDF5 dataset filter options.

    namedtypeshaper-   datalengthr+   r1   Nr+   )r1   )lennparrayr   create_datasetr-   r   listkeysremover   )r#   r%   r'   n_chromsnamescolumnscol r?   ^/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/cooler/create/_create.pywrite_chroms0   s0   
	rA   Tbins
chromnames	list[str]chrom_as_enumboolc              	     s:  t |}t |}tt|t|  fdd|d D }|r'tjt fd}nt}z| j	d|f||d|}	W n tyX   |rUd}t}| j	d|f||d|}	n Y nw |s`d|	j	d< | j		d|ft
|d	 d| | j	
d|ft
|d
 d| t| }
dD ]}|
| q|
rt| ||
  dS dS )a4  
    Write the genomic bin table.

    Parameters
    ----------
    grp : h5py.Group
        Group handle of an open HDF5 file with write permissions.
    bins : pandas.DataFrame
        BED-like data frame with at least three columns: ``chrom``, ``start``,
        ``end``, sorted by ``chrom`` then ``start``, and forming a complete
        genome segmentation. The ``chrom`` column must be sorted according to
        the ordering in ``chroms``.
    chromnames : sequence of str
        Contig names.
    h5opts : dict
        HDF5 dataset filter options.

    c                      g | ]} | qS r?   r?   ).0chromidmapr?   r@   
<listcomp>q       zwrite_bins.<locals>.<listcomp>rI   enumr.   Fz/chroms/nameZ	enum_pathstartendrI   rP   rQ   NrI   )rP   )rQ   )r4   r(   ziprangeh5pyspecial_dtyper   r7   
ValueErrorattrsr   r8   r9   r:   r   )r#   rB   rC   r'   rE   r;   n_bins	chrom_idschrom_dtypeZ
chrom_dsetr=   r>   r?   rJ   r@   
write_binsS   sf   

r]   rZ   intmax_sizer=   pd.Index | list[str]dtypespd.Series | dict[str, Any]c              	   C  s   t |}td| |}| j	d|dt|f|fd| | j	d|dt|f|fd| d|v rH| j	d	|dt|f|fd| dD ]}z|| W qJ ty\   Y qJw |rw|D ]}| j|f||t|f|fd| qad S d S )
N   bin1_id)r-   r/   maxshapebin2_idcountrd   rf   rg   )rd   )rf   )rg   )	r8   minr7   r   r   r   r:   rX   float)r#   rZ   r_   r=   ra   r'   Z	init_sizer>   r?   r?   r@   prepare_pixels   sb   



rk   filepathstr	grouppathiterableTabular | Iterable[Tabular]lock
Any | Nonetuple[int, int]c              	     s>  d}d}t |D ]\}}	t|	tjrdd |	 D }	zu|dur$|  td|  t	| dM}
|
|   fdd|D }t
|	|d  }t||D ]\}}||| f |	| |||| < qM||7 }d	|	v rt||	d	  7 }|
  W d   n1 sw   Y  W |dur|  q|dur|  w w ||fS )
a  
    Write the non-zero pixel table.

    Parameters
    ----------
    filepath : str
        Path to HDF5 output file.
    grouppath : str
        Qualified path to destination HDF5 group.
    columns : sequence
        Sequence of column names
    iterable : an iterable object
        An object that processes and yields binned contacts from some input
        source as a stream of chunks. The chunks must be either pandas
        DataFrames or mappings of column names to arrays.
    h5opts : dict
        HDF5 filter options.
    lock : multiprocessing.Lock, optional
        Optional lock to synchronize concurrent HDF5 file access.

    r   c                 S  s   i | ]\}}||j qS r?   )valuesrH   kvr?   r?   r@   
<dictcomp>       z write_pixels.<locals>.<dictcomp>Nzwriting chunk r+c                   rG   r?   r?   rH   r>   r#   r?   r@   rL      rM   z write_pixels.<locals>.<listcomp>rg   )	enumerate
isinstancepd	DataFrameitemsacquireloggerdebugrV   Filer4   rT   resizesumflushrelease)rl   rn   r=   ro   r'   rq   nnztotalichunkfwZdsetsnr>   Zdsetr?   r|   r@   write_pixels   s:   

r   r   
np.ndarrayc           	      C  s`   | d }t j|d td}d}tt|d D ]\}}}||||d < |d }q|||d < |S )Nrd   r   r,   r   i@B )r5   zerosr   rT   r   )	r#   rZ   r   Zbin1bin1_offsetcurr_valrP   _lengthvaluer?   r?   r@   index_pixels
  s   
r   r;   c           	      C  s^   | d }t j|d td}d}tt| D ]\}}}||||d < |d }q|||d < |S )NrI   r   r,   r   )r5   r   r   rT   r   )	r#   r;   rZ   r[   chrom_offsetr   rP   r   r   r?   r?   r@   
index_bins  s   
r   r   r   c                 C  sD   | j 	dt|ft|d| | j 	dt|ft|d| dS )a  
    Write the indexes.

    Parameters
    ----------
    grp : h5py.Group
        Group handle of an open HDF5 file with write permissions.
    chrom_offset : sequence
        Lookup table: chromosome ID -> first row in bin table (bin ID)
        corresponding to that chromosome.
    bin1_offset : sequence
        Lookup table: genomic bin ID -> first row in pixel table (pixel ID)
        having that bin on the first axis.

    r   r.   r   N)r   )r   )r7   r4   r   r   )r#   r   r   r'   r?   r?   r@   write_indexes   s$   
r   Finfoscoolc                 C  s   d|v sJ |sd|v sJ | dd t|di |d< t  |d< dt |d< |r8t|d	< t	|d
< nt
|d	< t|d
< t|d< | j| dS )a  
    Write the file description and metadata attributes.

    Parameters
    ----------
    grp : h5py.Group
        Group handle of an open HDF5 file with write permissions.
    info : dict
        Dictionary, unnested with the possible exception of the ``metadata``
        key. ``metadata``, if present, must be JSON-serializable.

    Required keys
    -------------
    nbins : int
        number of genomic bins
    nnz : int
        number of non-zero pixels

    nbinsr   genome-assemblyunknownmetadatazcreation-datezcooler-zgenerated-byformatzformat-versionz
format-urlN)
setdefaultjsondumpsr   r   now	isoformatr   r   r
   r   r	   r!   rY   update)r#   r   r   r?   r?   r@   
write_infoE  s   
r   rename_dictdict[str, str]c              	   C  s  t | d d}t|}tj||jjtd}| d= | d j		d
|f|j
|d| t | d }t|}t|d j
tjrtt|t|}|d jj}	tjt|fd}
| d	= z| d j		d|f|
|	d| W d S  ty   t}
| d j		d|f|
|	d| Y d S w d S )Nr%   r+   r,   zchroms/namer.   rB   rI   rN   
bins/chromr3   rS   )r   Z	set_indexr4   r5   r6   renameindexrt   r   r7   r-   r~   r   ZCategoricalDtyper(   rT   rU   catcodesrV   rW   r   rX   )r#   r   r'   r%   r;   Z	new_namesrB   rZ   rK   r[   r\   r?   r?   r@   _rename_chromsj  sN   
r   dict | Nonec                 C  sJ   t |}| d}t||| W d   n1 sw   Y  |   dS )a  
    Substitute existing chromosome/contig names for new ones. They will be
    written to the file and the Cooler object will be refreshed.

    Parameters
    ----------
    clr : Cooler
        Cooler object that can be opened with write permissions.
    rename_dict : dict
        Dictionary of old -> new chromosome names. Any names omitted from
        the dictionary will be kept as is.
    h5opts : dict, optional
        HDF5 filter options.

    rz   N)_set_h5optsopenr   Z_refresh)Zclrr   r'   fr?   r?   r@   rename_chroms  s
   r   pd.Series | dict | Nonekwargsdict[str, Any]c                 C  s6   d|v r| d u r| d} tdt | S td| S )Nr-   zUse dtypes= instead of dtype=zReceived both "dtypes" and "dtype" arguments. Please use "dtypes" to provide a column name -> dtype mapping. "dtype" remains as an alias but is deprecated.)popwarningswarnFutureWarningrX   )ra   r   r?   r?   r@   _get_dtypes_arg  s   
r   c                 C  s|   i }| d ur| |  h d}| D ]}||vr!td| dq|dd |d dkr6d|vr6d|d< |dd	 |S )
N>	   compressionZscaleoffsetZtrack_timesshufflecompression_optschunksZ
fletcher32re   	fillvaluezUnknown storage option ''.r   gzipr      r   T)r   r9   rX   r   )r'   resultZavailable_optskeyr?   r?   r@   r     s   
r   c           5   	   K  s  t | \}}t|}|du r|rdnd}t|	}	t|tjs#td|r-|du r-tdt||}dD ]}||j	vrCtd| dq4|du rMg d	}nt
|}d
D ]}||vr_|d| qS|du ritt}nt|}tt}|| t||td}zddlm} W n ttfy   d}Y nw t||rdd | D }t|j	}n(t|tjr|f}t|j	}nt|tr|f}tdd | D j	}n|}d}|dur|D ]}||vr|tv rdnd}t| d| dq| }|d t|d< t|}z| }W n
 ty   Y nw t| \}}tj||dddgd}t|} t|}!t|}"|s;|r;t d d}|
sG|sG|sG|rTt!|"|
|||}#t"|#|}t#$||B}$t%&d| d| d  |d!kr{d"D ]}%|%|$v rx|$|%= qnnz|$'| W n ty   |$|= |$'| Y nw W d   n	1 sw   Y  |rat |\}&}'t | \}(})t#$|&d#^}*t#$|(d#G}+|*d$ |+|) d$< |*d% |+|) d%< |*d& |+|) d&< |*d' |+|) d'< t
|( }dD ]}|)| q|rt*|+|) d( ||  W d   n	1 sw   Y  W d   n	1 sw   Y  t#$|d#0}$|$| },|,'d)}-|r?|"|"d*  d+ |" }.n|"|" }.t+|-|"|.|j	t|j,|	 W d   n	1 s[w   Y  nbt#$|d#S}$|$| },t%&d, |,'d$}-t-|-||	 t%&d- |,'d(}-t.|-||d |	 |,'d)}-|r|"|"d*  d+ |" }.n|"|" }.t+|-|"|.|j	t|j,|	 W d   n	1 sw   Y  t%&d. t/0|d)}/t1||/|j	||	|\}0}1t#$|d#{}$|$| },t%&d/ |,'d0}-t2|,d( |!|"}2t3|,d) |"|0}3t4|-|2|3|	 t%&d1 i }4| durd2nd3|4d4< | dur| nd5|4d6< |r(d7nd8|4d9< |!|4d:< |"|4d;< |1|4d<< |0|4d=< |durE||4d>< |durN||4d?< t5|,|4 W d   dS 1 s_w   Y  dS )@a  
    Create a new Cooler.

    Deprecated parameters
    ---------------------
    chromsizes : Series
        Chromsizes are now inferred from ``bins``.
    append : bool, optional
        Append new Cooler to the file if it exists. If False, an existing file
        with the same name will be truncated. Default is False.
        Use the ``mode`` argument instead.
    dtype : dict, optional
        Dictionary mapping column names in the pixel table to dtypes.
        Use the ``dtypes`` argument instead.

    NawzSecond positional argument must be a pandas DataFrame. Note that the `chromsizes` argument is now deprecated: see documentation for `create`.zWIf the parameter `append_scool` is set, the parameter `scool_root_uri` must be defined.rR    Missing column from bin table: 'r   rh   )rd   rf   r   )Zdefault_dtyper   r?   c                 s  s    | ]}|  V  qd S N)compute)rH   xr?   r?   r@   	<genexpr>.  s    zcreate.<locals>.<genexpr>c                 S  s   g | ]	\}}||j fqS r?   r,   ru   r?   r?   r@   rL   5  s    zcreate.<locals>.<listcomp>ZStandardZUserz column not found in input: ''rI   r2   r+   r1   r=   zTCreating a non-symmetric matrix, but `triucheck` was set to True. Changing to False.FCreating cooler at "::"/)r%   rB   pixelsindexesrz   r%   r   z
bins/startzbins/endrB   r   r   r   Writing chromsWriting binszWriting pixelszWriting indexesr   Writing infofixedvariablebin-typenullbin-sizezsymmetric-upperZsquarezstorage-modenchromsr   r   r   r   r   )6r   oprealpathr   r~   r   r   rX   r   r=   r8   insertr(   r   r   r   rj   dask.dataframeImportErrorAttributeError
to_delayedr   r   r    copyastypeobjectr   rT   r   r4   r   r   r"   maprV   r   r   r   create_groupr9   r:   r   rk   ra   rA   r]   	posixpathjoinr   r   r   r   r   )5cool_urirB   r   r=   ra   r   assemblysymmetric_uppermoder'   boundscheck	triucheckdupcheckensure_sortedrq   appendappend_scoolscool_root_urir   	file_path
group_pathr>   dtypes_metadask_dfro   Zinput_columnsZcol_type
chromsizesrC   lengthsr%   binsizer;   rZ   	validatorr   r+   Zsrc_pathZ	src_groupZdst_pathZ	dst_groupsrcdsth5r#   r_   targetr   Z	ncontactsr   r   r   r?   r?   r@   create  sJ  %











 











$r   -1   c
              	     s  ddl m  ddlm} | }|d t|d< |dur$dd |D }|du r2tt	| d }n|d	kr8d}t
||
}tjd
k}|rI|rId}n|}g }tjd||d}|| g }t|D ]+\}}|jd t| }|| td| d|  t|||f||dd|
 q`t|}||	  krdkrn nqtjd|tt|td}tjd||d}|| g }t|dd |dd D ]C\}}| fdd||| D ||d}|jd | d	|  }|| td| d	| d|  t|||f||dd|
 q|}n|}| fdd|D ||d}td|   t| ||f|||d|
 |rN|rN|D ]}|jsF|  t|j q<~dS )aa  
    Create a Cooler in two passes via an external sort mechanism. In the first
    pass, a sequence of data chunks are processed and sorted in memory and saved
    to temporary Coolers. In the second pass, the temporary Coolers are merged
    into the output. This way the individual chunks do not need to be provided
    in any particular order.

    r   Cooler)CoolerMergerrI   Nc                 S  s   g | ]}|d vr|qS )>   rd   rf   r?   r{   r?   r?   r@   rL     ry   z)create_from_unordered.<locals>.<listcomp>r   -ntFz.multi.cool)suffixdeletedirr   zWriting chunk z: r   )r=   ra   r   r,   r   c                      g | ]} |qS r?   r?   rH   urir
  r?   r@   rL     rM   r   zMerging chunks c                   r  r?   r?   r  r
  r?   r@   rL   %  rM   zMerging into )apir  reducer  r   r   r   r   dirnamer   r   osr+   tempfileNamedTemporaryFiler   r}   rm   r   r   r  r4   r5   Zlinspacer^   sqrtrT   closedcloser:   )r   rB   r   r=   ra   r   mergebufdelete_temptemp_dir	max_merger   r  Z
is_windowsr  Z
temp_filestfurisr   r   r  r   edgesZtf2Zuris2lohiZchunk_subsetZ
final_urisr?   r
  r@   create_from_unordered  s   




"

r(  c                 C  s  t |}t| \}}zddlm}	 ddlm}
 W n ttfy'   d}	d}
Y nw t||
r1| }z|	 }W n tyC   |j
}Y nw t|d}|| }|D ]}||| v rj|setd| dd || |= qQt||	r| D ]<}d}| D ]3}| }z|d	ur|  t|| |||d
 W |d	ur|  n
|d	ur|  w w |t|7 }q|qtnk|r|	 D ]:}d}|| D ]1}z|d	ur|  t|| ||i||d
 W |d	ur|  n
|d	ur|  w w |t|7 }qqn1z|d	ur|  t|| |d|d
 W |d	ur|  n|d	ur|  w w W d	   d	S W d	   d	S W d	   d	S 1 s9w   Y  d	S )a  
    Append one or more data columns to an existing table.

    Parameters
    ----------
    cool_uri : str
        Path to Cooler file or URI to Cooler group.
    table : str
        Name of table (HDF5 group).
    data : dict-like
        DataFrame, Series or mapping of column names to data. If the input is a
        dask DataFrame or Series, the data is written in chunks.
    chunked : bool, optional
        If True, the values of the data dict are treated as separate chunk
        iterators of column data.
    force : bool, optional
        If True, replace existing columns with the same name as the input.
    h5opts : dict, optional
        HDF5 dataset filter options to use (compression, shuffling,
        checksumming, etc.). Default is to use autochunking and GZIP
        compression, level 6.
    lock : multiprocessing.Lock, optional
        Optional lock to synchronize concurrent HDF5 file access.

    r   r   )Seriesr?   rz   r   z' column already exists. z Use --force option to overwrite.N)r&  r'   )r   r   r   r   r)  r   r   r~   Zto_framer9   r=   rV   r   rX   r   r   r   r   r   r4   )r   tabler0   chunkedforcer'   rq   r   r   r   Zdask_seriesr<   r   r  r+   r   r   r   r?   r?   r@   r   2  s   









$ r   aI  
    columns : sequence of str, optional
        Customize which value columns from the input pixels to store in the
        cooler. Non-standard value columns will be given dtype ``float64``
        unless overriden using the ``dtypes`` argument. If ``None``, we only
        attempt to store a value column named ``"count"``.
    dtypes : dict, optional
        Dictionary mapping column names to dtypes. Can be used to override the
        default dtypes of ``bin1_id``, ``bin2_id`` or ``count`` or assign
        dtypes to custom value columns. Non-standard value columns given in
        ``dtypes`` must also be provided in the ``columns`` argument or they
        will be ignored.
    metadata : dict, optional
        Experiment metadata to store in the file. Must be JSON compatible.
    assembly : str, optional
        Name of genome assembly.
    ordered : bool, optional [default: False]
        If the input chunks of pixels are provided with correct triangularity
        and in ascending order of (``bin1_id``, ``bin2_id``), set this to
        ``True`` to write the cooler in one step.
        If ``False`` (default), we create the cooler in two steps using an
        external sort mechanism. See Notes for more details.
    symmetric_upper : bool, optional [default: True]
        If True, sets the file's storage-mode property to ``symmetric-upper``:
        use this only if the input data references the upper triangle of a
        symmetric matrix! For all other cases, set this option to False.
    mode : {'w' , 'a'}, optional [default: 'w']
        Write mode for the output file. 'a': if the output file exists, append
        the new cooler to it. 'w': if the output file exists, it will be
        truncated. Default is 'w'.

    Other parameters
    ----------------
    mergebuf : int, optional
        Maximum number of records to buffer in memory at any give time during
        the merge step.
    delete_temp : bool, optional
        Whether to delete temporary files when finished.
        Useful for debugging. Default is False.
    temp_dir : str, optional
        Create temporary files in a specified directory instead of the same
        directory as the output file. Pass ``-`` to use the system default.
    max_merge : int, optional
        If merging more than ``max_merge`` chunks, do the merge recursively in
        two passes.
    h5opts : dict, optional
        HDF5 dataset filter options to use (compression, shuffling,
        checksumming, etc.). Default is to use autochunking and GZIP
        compression, level 6.
    lock : multiprocessing.Lock, optional
        Optional lock to control concurrent access to the output file.
    ensure_sorted : bool, optional
        Ensure that each input chunk is properly sorted.
    boundscheck : bool, optional
        Input validation: Check that all bin IDs lie in the expected range.
    dupcheck : bool, optional
        Input validation: Check that no duplicate pixels exist within any chunk.
    triucheck : bool, optional
        Input validation: Check that ``bin1_id`` <= ``bin2_id`` when creating
        coolers in symmetric-upper mode.
a  
    Notes
    -----
    If the pixel chunks are provided in the correct order required for the
    output to be properly sorted, then the cooler can be created in a single
    step by setting ``ordered=True``.

    If not, the cooler is created in two steps via an external sort mechanism.
    In the first pass, the sequence of pixel chunks are processed and sorted in
    memory and saved to temporary coolers. In the second pass, the temporary
    coolers are merged into the output file. This way the individual chunks do
    not need to be provided in any particular order. When ``ordered=False``,
    the following options for the merge step are available: ``mergebuf``,
    ``delete_temp``, ``temp_dir``, ``max_merge``.

    Each chunk of pixels will go through a validation pipeline, which can be
    customized with the following options: ``boundscheck``, ``triucheck``,
    ``dupcheck``, ``ensure_sorted``.
c                    s    fdd}|S )Nc                   s   | j jdi  | _ | S )Nr?   )__doc__r   )funcr   r?   r@   decorate  s   z#_format_docstring.<locals>.decorater?   )r   r0  r?   r/  r@   _format_docstring  s   r1  )Zother_parametersnotesr   r   r   list[str] | Nonedict[str, Any] | Noner   r   
str | Noneorderedr   r   r  r   r!  r"  r   r   r   r   c                 C  s   t |tjtfrt|ddg}d}|r+t| ||||||||	||||||d dS t| ||fi d|d|d|d|d	|d
|	d|d|d|d|d|d|d|
d|d|d| dS )a  
    Create a cooler from bins and pixels at the specified URI.

    Because the number of pixels is often very large, the input pixels are
    normally provided as an iterable (e.g., an iterator or generator) of
    DataFrame **chunks** that fit in memory.

    .. versionadded:: 0.8.0

    Parameters
    ----------
    cool_uri : str
        Path to cooler file or URI string. If the file does not exist,
        it will be created.
    bins : pandas.DataFrame
        Segmentation of the chromosomes into genomic bins as a BED-like
        DataFrame with columns ``chrom``, ``start`` and ``end``. May contain
        additional columns.
    pixels : DataFrame, dictionary, or iterable of either
        A table, given as a dataframe or a column-oriented dict, containing
        columns labeled ``bin1_id``, ``bin2_id`` and ``count``, sorted by
        (``bin1_id``, ``bin2_id``). If additional columns are included in the
        pixel table, their names and dtypes must be specified using the
        ``columns`` and ``dtypes`` arguments. For larger input data, an
        **iterable** can be provided that yields the pixel data as a sequence
        of chunks. If the input is a dask DataFrame, it will also be processed
        one chunk at a time.
    {other_parameters}

    See also
    --------
    cooler.create_scool
    cooler.create.sanitize_records
    cooler.create.sanitize_pixels

    {notes}

    rd   rf   T)r=   ra   r   r   r   r   r   r   r   r   r'   rq   r=   ra   r   r   r   r   r   r   r   r   r'   rq   r  r   r!  r"  N)r~   r   r   r(   Zsort_valuesr  r(  )r   rB   r   r=   ra   r   r   r6  r   r   r  r   r!  r"  r   r   r   r   r'   rq   r?   r?   r@   create_cooler  st   >
	
r7  cell_name_pixels_dictdict[str, pd.DataFrame]c           ,   	     s
  t | \}}t|}t tjr fdd|D }t|}n2 }t|dkr*td|tt	| g d  t|}t|}t
||D ]\}}||krOtdqCt||}dD ]}| jvrftd| dqW|d	u rptt}nt|}tt}||     d
 t d
< t }z| }W n	 ty   Y nw t
| \}} tj|| dddgd}!t }"t|!}#t }$t||	>}%td| d| d |dkrdD ]	}&|&|%v r|%|&= qnz|%| W n ty   |%|= |%| Y nw W d	   n	1 sw   Y  t|d/}%|%| }'td |'d}(t|(|!| td |'d}(t|( |!d | W d	   n	1 sBw   Y  t|dO}%|%| }'td i })|"d	ur`dnd|)d< |"d	urk|"nd|)d< |#|)d< t||)d < |$|)d!< |d	ur||)d"< |d	ur||)d#< t|'|)d$ W d	   n	1 sw   Y  |D ][}*d|*v r|*dd% }+n|*}+t | d& |+ ||* ||* fi d'|d(|d#|d)|d*|d+|d,d-d.|d/|d0|d1|d2|d3|d4|
d5|d6|d7|d8d$d9|  qd	S ):a  
    Create a single-cell (scool) file.

    For each cell store a cooler matrix under **/cells**, where all matrices
    have the same dimensions.

    Each cell is a regular cooler data collection, so the input must be a
    bin table and pixel table for each cell. The pixel tables are provided as
    a dictionary where the key is a unique cell name. The bin tables can be
    provided as a dict with the same keys or a single common bin table can be
    given.

    .. versionadded:: 0.8.9

    Parameters
    ----------
    cool_uri : str
        Path to scool file or URI string. If the file does not exist,
        it will be created.
    bins : :class:`pandas.DataFrame` or Dict[str, DataFrame]
        A single bin table or dictionary of cell names to bins tables. A bin
        table is a dataframe with columns ``chrom``, ``start`` and ``end``.
        May contain additional columns.
    cell_name_pixels_dict : Dict[str, DataFrame]
        Cell name as key and pixel table DataFrame as value.
        A table, given as a dataframe or a column-oriented dict, containing
        columns labeled ``bin1_id``, ``bin2_id`` and ``count``, sorted by
        (``bin1_id``, ``bin2_id``). If additional columns are included in the
        pixel table, their names and dtypes must be specified using the
        ``columns`` and ``dtypes`` arguments. For larger input data, an
        **iterable** can be provided that yields the pixel data as a sequence
        of chunks. If the input is a dask DataFrame, it will also be processed
        one chunk at a time.
    {other_parameters}

    See also
    --------
    cooler.create_cooler
    cooler.zoomify_cooler

    {notes}

    c                   s   i | ]}| qS r?   r?   )rH   	cell_namerB   r?   r@   rx     s    z create_scool.<locals>.<dictcomp>r   zAt least one bin must be given.rR   z.Bins and pixel dicts do not have matching keysr   r   NrI   r2   r+   r1   r   r   r   r   r   )r%   rB   rz   r   r%   r   rB   r   r   r   r   r   r   r   Zncellsr   r   r   Tr  z	::/cells/r=   ra   r   r6  r   r   r   r   r   r   r   r'   rq   r  r   r!  r"  r   r   )!r   r   r~   r   r   sortedr4   rX   nextiterrT   r   r=   r(   r   r   r   r   r   r   r   r   r   rV   r   r   r   r   rA   r]   r   splitr  ),r   rB   r8  r=   ra   r   r   r6  r   r   r  r   r!  r"  r   r   r   r   r'   rq   r   r   r   Z	bins_dict
cell_namesZ	bins_keysZkey_binsZ
key_pixelsr>   r   r   rC   r   r%   r  r;   rZ   r   r+   r  r#   r   r   r:  r?   r;  r@   create_scoolZ  s   C




	








	
rA  )r#   r$   r%   r&   r'   r(   r)   r*   )T)r#   r$   rB   r&   rC   rD   r'   r(   rE   rF   r)   r*   )r#   r$   rZ   r^   r_   r^   r=   r`   ra   rb   r'   r(   r)   r*   )rl   rm   rn   rm   r=   r`   ro   rp   r'   r(   rq   rr   r)   rs   )r#   r$   rZ   r^   r   r^   r)   r   )r#   r$   r;   r^   rZ   r^   r)   r   )
r#   r$   r   r   r   r   r'   r(   r)   r*   )F)r#   r$   r   r(   r   rF   r)   r*   )r#   r$   r   r   r'   r(   r)   r*   r   )r   r   r'   r   r)   r*   )ra   r   r   r   r)   r   )r'   r   r)   r   )NNNNTNNTTTFNFFN)NNNr  TNr	  )FFNN)NNNNFTr   r  TNr	  TTTFNN)*r   rm   rB   r&   r   rp   r=   r3  ra   r4  r   r   r   r5  r6  rF   r   rF   r   rm   r  r^   r   rF   r!  r5  r"  rm   r   rF   r   rF   r   rF   r   rF   r'   r   rq   rr   r)   r*   )*r   rm   rB   r&   r8  r9  r=   r3  ra   r4  r   r   r   r5  r6  rF   r   rF   r   rm   r  r^   r   rF   r!  r5  r"  r^   r   rF   r   rF   r   rF   r   rF   r'   r   rq   rr   r)   r*   )L
__future__r   r  Zos.pathpathr   r   r  r   r   typingr   r   rV   numpyr5   Zpandasr   Z
simplejsonr   Z_loggingr   Z_typingr   _versionr	   r
   r   corer   r   utilr   r   r   r   r   r    r   r   r   r   r   r   r   r   r   r   r   r    r!   Z_ingestr"   r   rA   r]   rk   r   r   r   r   r   r   r   r   r   r  r(  r   stripZ_DOC_OTHER_PARAMSZ
_DOC_NOTESr1  r7  rA  r?   r?   r?   r@   <module>   s     <
(
F
3
>

%
%'


 z
k
a<>

k