o
    Nrf                      @   s  d dl Z d dlm  mZ d dlZd dlZd dlZ	ddl
mZmZmZ d dlmZ dZdZeeZi Zddd	ed< d
dd	ed< ddd	ed< ddd	ed< i Zddd	ed< ddd	ed< dd Zdd Zd"ddZdd Z			d#ddZi dfddZd d! ZdS )$    N   )get_quadtree_depthabs2genomic	natsorted)ThreadPoolExecutor   i   ZMeanmean)namevalueZMinminZMaxmaxzStandard DeviationstdzMin-MaxminMaxZWhiskerwhiskerc                 C   s&   dd t t| td D d d d S )Nc                 S   s   g | ]}d | qS )    ).0xr   r   ]/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/clodius/tiles/bigwig.py
<listcomp>       z(get_zoom_resolutions.<locals>.<listcomp>r   )ranger   	TILE_SIZE)
chromsizesr   r   r   get_zoom_resolutions   s   &r   c                 C   s(   t | }t| }t|| }|S )zj
    TODO: replace this with negspy

    Also, return NaNs from any missing chromosomes in bbi.fetch

    )bbir   r   keyspdSeries)bwpathr   Zchromosomeschrom_seriesr   r   r   get_chromsizes   s   
r"   c              	   C   s   |du rt | }g }| D ]\}}||t|gg7 }qn	|}dd |D }t|t}dgt|gtd|  t||ttd}|S )a*  
    Get the tileset info for a bigWig file

    Parameters
    ----------
    bwpath: string
        The path to the bigwig file from which to retrieve data
    chromsizes: [[chrom, size],...]
        A list of chromosome sizes associated with this tileset.
        Typically passed in to specify in what order data from
        the bigwig should be returned.

    Returns
    -------
    tileset_info: {'min_pos': [],
                    'max_pos': [],
                    'tile_size': 1024,
                    'max_zoom': 7
                    }
    Nc                 S      g | ]}t |d  qS r   intr   cr   r   r   r   H       z tileset_info.<locals>.<listcomp>r   r   )Zmin_posZmax_pos	max_width	tile_sizemax_zoomr   aggregation_modesrange_modes)r"   itemsr&   r   r   sumr-   r.   )r    r   Zchromsizes_listchromsizer,   tileset_infor   r   r   r3   +   s&   


r3   c                 C   s  | \}}}}}}}}t t|| | }	d}
|dkrd}
|dkr#d}
|
dkr.t|	|
fnt|	}z|j| }|j| }||||g}|	tjd}|dkrstj|i t	|dd|d d d	f< tj|i t	|d
d|d d df< n]|dkrtj|i t	|dd|d d d	f< tj|i t	|d
d|d d df< tj|i t	|dd|d d df< tj|i t	|dd|d d df< ntj|i t	||d|d d < ||kr|| d	kr|d d }W |S W |S W |S  t
y   tj|d d < Y |S  ty
   tj|d d < Y |S w )Nr   r   r   r   r   )Zbinsmissingr   )summaryr   r   r   r      r   )r&   npceilZzerosindexvaluesnanr   fetchdict
IndexErrorKeyError)ar    binsizer   aggregation_mode
range_modeZcidstartendZn_binsZn_dimr   r1   Zclenargskwargsr   r   r   
fetch_dataY   sH    

$&$$$& 
rH   c              
      s   d u rt t}|| tt||}tdd}	t|	t fdd|D }
W d    n1 s;w   Y  t|
S )N   )max_workersc                    s&   g | ]}t  gt| qS r   )tuplelistr'   rB   rA   r    r   rC   r   r   r      s    z#get_bigwig_tile.<locals>.<listcomp>)	r"   r   rL   r   r   maprH   r7   Zconcatenate)r    
zoom_level	start_posend_posr   rB   rC   resolutionsZcids_starts_endseZarraysr   rM   r   get_bigwig_tile   s    	
rT   c              
   C   sn  g }|D ]}| ddd }| dd }| d}ttt|dd }	t|dkr0|d nd}
|
tv r8|
nd}|
tv r@|
nd}tdd	 |D }|rcd
d	 |D }dd	 |D }tj	||d}nd}d|v rm|d }||v rv|| }nd}|	d }|	d }|du rt
| }t|t}td||   }|| }|| }t| ||||||d}t|}|||fg7 }q|S )a  
    Generate tiles from a bigwig file.

    Parameters
    ----------
    tileset: tilesets.models.Tileset object
        The tileset that the tile ids should be retrieved from
    tile_ids: [str,...]
        A list of tile_ids (e.g. xyx.0.0) identifying the tiles
        to be retrieved
    chromsizes_map: {uid: []}
        A set of chromsizes listings corresponding to the parameters of the
        tile_ids. To be used if a chromsizes id is passed in with the tile id
        with the `|cos:id` tag in the tile id
    chromsizes: [[chrom, size],...]
        A 2d array containing chromosome names and sizes. Overrides the
        chromsizes in chromsizes_map

    Returns
    -------
    tile_list: [(tile_id, tile_data),...]
        A list of tile_id, tile_data tuples
    |r   Nr   .r6   r   c                 S   s   g | ]}| d qS ):)split)r   or   r   r   r      s    ztiles.<locals>.<listcomp>c                 S   s   g | ]}|d  qS )r   r   r'   r   r   r   r      r   c                 S   r#   r$   r%   r'   r   r   r   r      r)   )r9   cosr   )rB   rC   )rX   rL   rN   r&   lenr-   r.   r=   r   r   r"   r   r   rT   hgfoZformat_dense_tile)r    Ztile_idsZchromsizes_mapr   Zgenerated_tilesZtile_idZtile_option_partsZtile_no_optionsZtile_id_partsZtile_positionreturn_valuerB   rC   Ztile_optionsZ
chromnamesZchromlengthsZchromsizes_to_useZchromsizes_idrO   Ztile_pos	max_depthr+   rP   rQ   ZdenseZ
tile_valuer   r   r   tiles   sP   




r_   c              
   C   sd   zt | }g }| D ]\}}|||g q|W S  ty1 } zt| td|d}~ww )a,  
    Get a list of chromosome sizes from this [presumably] bigwig
    file.

    Parameters:
    -----------
    filename: string
        The filename of the bigwig file

    Returns
    -------
    chromsizes: [(name:string, size:int), ...]
        An ordered list of chromosome names and sizes
    z-Error loading chromsizes from bigwig file: {}N)r"   r/   append	Exceptionloggererrorformat)filenamer!   datar1   r2   exr   r   r   r      s   
r   )N)Nr   N)r   Zclodius.tiles.formatr_   rd   r\   loggingnumpyr7   Zpandasr   utilsr   r   r   concurrent.futuresr   ZMAX_THREADSr   	getLogger__name__rb   r-   r.   r   r"   r3   rH   rT   r   r   r   r   r   <module>   s8    

.5
!N