U
    Åmœd³‡  ã                   @   s¾  d Z ddlmZmZ ddlmZmZ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ZddlmZmZmZmZmZmZ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dddhZ&ddddddddhe&B Z'ddddddde"feee(f eed  ee( ee( ee( e)ee( e)eed de!f edœ
dd„Zdfee(ef ee( e)ee( ed!œd"d#„Z*ddd$œd%d&„Z+e,e
j-d'œd(d)„Z.dd*œd+d,„Z/dgd-dd dd.œee(ef ee( e(e(ee) eee(ef  ed/œd0d1„Z0d2d de"d fdd3œeee(f ed4 e)e)eed de!f e)e(ed5œd6d7„Z1d2d de"fd8d3œd9d:„Z2d2d de"fd8d3œd;d<„Z3dhee(ef eeed>  eed  ee4 d?œd@dA„Z5dieee(f e)ee(ee4e6e)e(df f dBœdCdD„Z7eee(f dEœdFdG„Z8djedHœdIdJ„Z9ee(ef e(dKœdLdM„Z:ee(e;ee	f edNœdOdP„Z<e(e6dQœdRdS„Z=e(e)dQœdTdU„Z>e(ee)e)f dQœdVdW„Z?e(ee4e6e)e(df dQœdXdY„Z@dZd[„ ZAdked\œd]d^„ZBe(ed_œd`da„ZCdldbdc„ZDdmedHœddde„ZEdS )nzReading and Writing
é    )ÚPathÚPurePath)ÚUnionÚDictÚOptionalÚTupleÚBinaryION)Úimread)ÚAnnDataÚread_csvÚ	read_textÚ
read_excelÚread_mtxÚ	read_loomÚread_hdf)Úreadé   )Úsettings)ÚLiteral)ÚEmptyÚ_empty)ÚloggingÚcsvÚtsvÚtabÚdataÚtxtÚanndataÚxlsxÚh5Úh5adÚmtxúmtx.gzúsoft.gzÚloomF)Úrzr+)ÚgzipZlzf)
ÚfilenameÚbackedÚsheetÚextÚ	delimiterÚfirst_column_namesÚ
backup_urlÚcacheÚcache_compressionÚreturnc	                 K   s~   t | ƒ} t| ƒr2t| f||||||||dœ|	—ŽS t| ƒ}
tj|
d tj  } |  ¡ srtd|
›d| ›dt	› d�ƒ‚t
| |d�S )a¿      Read file and return :class:`~anndata.AnnData` object.

    To speed up reading, consider passing ``cache=True``, which creates an hdf5
    cache file.

    Parameters
    ----------
    filename
        If the filename has no file extension, it is interpreted as a key for
        generating a filename via ``sc.settings.writedir / (filename +
        sc.settings.file_format_data)``.  This is the same behavior as in
        ``sc.read(filename, ...)``.
    backed
        If ``'r'``, load :class:`~anndata.AnnData` in ``backed`` mode instead
        of fully loading it into memory (`memory` mode). If you want to modify
        backed attributes of the AnnData object, you need to choose ``'r+'``.
    sheet
        Name of sheet/table in hdf5 or Excel file.
    ext
        Extension that indicates the file type. If ``None``, uses extension of
        filename.
    delimiter
        Delimiter that separates data within text file. If ``None``, will split at
        arbitrary number of white spaces, which is different from enforcing
        splitting at any single white space ``' '``.
    first_column_names
        Assume the first column stores row names. This is only necessary if
        these are not strings: strings in the first column are automatically
        assumed to be row names.
    backup_url
        Retrieve the file from an URL if not present on disk.
    cache
        If `False`, read from source, if `True`, read from fast 'h5ad' cache.
    cache_compression
        See the h5py :ref:`dataset_compression`.
        (Default: `settings.cache_compression`)
    kwargs
        Parameters passed to :func:`~anndata.read_loom`.

    Returns
    -------
    An :class:`~anndata.AnnData` object
    )r(   r)   r*   r+   r,   r-   r.   r/   Ú.zReading with filekey z failed, the inferred filename zx does not exist. If you intended to provide a filename, either use a filename ending on one of the available extensions z or pass the parameter `ext`.©r(   )r   Úis_valid_filenameÚ_readÚstrr   ÚwritedirÚfile_format_dataÚexistsÚ
ValueErrorÚ
avail_extsÚ	read_h5ad)r'   r(   r)   r*   r+   r,   r-   r.   r/   ÚkwargsZfilekey© r=   úI/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/readwrite.pyr   6   s.    8ÿ÷
öÿr   T)r'   ÚgenomeÚgex_onlyr-   r0   c           	   	   C   sü   t  d| › �¡}t| |d�}|s0t  d| › �¡ t t| ƒd¡�}d|k}W 5 Q R X |rêt| |d�}|r¼||jd j	kr¢t
d|› d	| › d
t|jd  ¡ ƒ› d�ƒ‚|dd…|jd |kf }|rÚ|dd…|jd dkf }|jrø| ¡ }nt| ||d�}|S )aü      Read 10x-Genomics-formatted hdf5 file.

    Parameters
    ----------
    filename
        Path to a 10x hdf5 file.
    genome
        Filter expression to genes within this genome. For legacy 10x h5
        files, this must be provided if the data contains more than one genome.
    gex_only
        Only keep 'Gene Expression' data and ignore other feature types,
        e.g. 'Antibody Capture', 'CRISPR Guide Capture', or 'Custom'
    backup_url
        Retrieve the file from an URL if not present on disk.

    Returns
    -------
    Annotated data matrix, where observations/cells are named by their
    barcode and variables/genes by gene name. Stores the following information:

    :attr:`~anndata.AnnData.X`
        The data matrix is stored
    :attr:`~anndata.AnnData.obs_names`
        Cell names
    :attr:`~anndata.AnnData.var_names`
        Gene names
    :attr:`~anndata.AnnData.var`\ `['gene_ids']`
        Gene IDs
    :attr:`~anndata.AnnData.var`\ `['feature_types']`
        Feature types
    úreading ©r-   ú... did not find original file r%   z/matrix©Ústartr?   z-Could not find data corresponding to genome 'ú' in 'ú'. Available genomes are: r1   NÚfeature_typesúGene Expression©r?   rE   )ÚloggÚinfoÚ$_check_datafile_present_and_downloadÚdebugÚh5pyÚFiler5   Ú_read_v3_10x_h5ÚvarÚvaluesr9   ÚlistÚuniqueZis_viewÚcopyÚ_read_legacy_10x_h5)	r'   r?   r@   r-   rE   Ú
is_presentÚfZv3Úadatar=   r=   r>   Úread_10x_h5Š   s(    &$ÿ
r[   rJ   c             
   C   s|  t  t| ƒd¡��`}�z8t| ¡ ƒ}|sRt|ƒdkrHtd| › d|› �ƒ‚|d }n"||krttd|› d| › d|› �ƒ‚i }t||| ƒ dd	lm	} |d
 \}}|d }	|d j
t 
d¡krØ|d  d¡}	|d |	dd…< ||	|d |d f||fd�}
t|
t|d  t¡d�t|d  t¡|d  t¡d�d�}tjd|d� |W W  5 Q R £ S  tk
�rl   tdƒ‚Y nX W 5 Q R X dS )zA
    Read hdf5 file from Cell Ranger v2 or earlier versions.
    r%   r   ú'z‰' contains more than one genome. For legacy 10x h5 files you must specify the genome if more than one is present. Available genomes are: r   zCould not find genome 'rF   rG   ©Ú
csr_matrixÚshaper   Úint32Úfloat32NÚindicesÚindptr©r_   Úbarcodes©Ú	obs_namesÚ
gene_namesÚgenes)Ú	var_namesÚgene_ids©ÚobsrR   Ú ©Útimeú.File is missing one or more required datasets.)rO   rP   r5   rT   ÚkeysÚlenr9   Ú_collect_datasetsÚscipy.sparser^   ÚdtypeÚnpÚviewr
   ÚdictÚastyperK   rL   ÚKeyErrorÚ	Exception)r'   r?   rE   rY   ÚchildrenÚdsetsr^   ÚMÚNr   ÚmatrixrZ   r=   r=   r>   rW   È   sJ    ÿ
ÿþþýrW   )r~   Úgroupc                 C   s:   |  ¡ D ],\}}t|tjƒr*|d | |< qt| |ƒ qd S )Nr=   )ÚitemsÚ
isinstancerO   ZDatasetrt   )r~   r‚   ÚkÚvr=   r=   r>   rt   ý   s    rt   rD   c          
      C   s6  t  t| ƒd¡��}zôi }t||d ƒ ddlm} |d \}}|d }|d jt d¡krz|d  d¡}|d |d	d	…< |||d
 |d f||fd�}t	|t
|d  t¡d�t
|d  t¡|d  t¡|d  t¡|d  t¡d�d�}	tjd|d� |	W W  5 Q R £ S  tk
�r&   tdƒ‚Y nX W 5 Q R X d	S )z?
    Read hdf5 file from Cell Ranger v3 or later versions.
    r%   r�   r   r]   r_   r   r`   ra   Nrb   rc   rd   re   rf   ÚnameÚidZfeature_typer?   )rj   rk   rH   r?   rl   rn   ro   rq   )rO   rP   r5   rt   ru   r^   rv   rw   rx   r
   ry   rz   rK   rL   r{   r|   )
r'   rE   rY   r~   r^   r   r€   r   r�   rZ   r=   r=   r>   rQ     s8    þüý
rQ   zfiltered_feature_bc_matrix.h5)Ú
count_fileÚ
library_idÚload_imagesÚsource_image_path)Úpathr?   r‰   rŠ   r‹   rŒ   r0   c             	      sR  t | ƒ} t| | |d�}tƒ |jd< ddlm} || | dd��‰tˆjƒ‰ W 5 Q R X |dkrrtˆ  d¡d d	ƒ}tƒ |jd |< |�rNt| d
 | d | d | d d�}| 	¡ D ]F‰ˆ 
¡ s°t‡fdd„dD ƒƒræt dˆ› d�¡ q°tdˆ› d�ƒ‚q°tƒ |jd | d< dD ]Z}	z,tt||	› d� ƒƒ|jd | d |	< W n& tk
�rf   td|	› d�ƒ‚Y nX �qt |d  ¡ ¡|jd | d< ‡ fdd„dD ƒ|jd | d< tj|d  dd!�}
d"d#d$d%d&d'g|
_|
d" |
_|jj|
d(d)�|_|jd'd&g  ¡ |jd< |jjd"d'd&gd*d+� |dk	�rNtt |ƒ ¡ ƒ}t|ƒ|jd | d d,< |S )-až      Read 10x-Genomics-formatted visum dataset.

    In addition to reading regular 10x output,
    this looks for the `spatial` folder and loads images,
    coordinates and scale factors.
    Based on the `Space Ranger output docs`_.

    See :func:`~scanpy.pl.spatial` for a compatible plotting function.

    .. _Space Ranger output docs: https://support.10xgenomics.com/spatial-gene-expression/software/pipelines/latest/output/overview

    Parameters
    ----------
    path
        Path to directory for visium datafiles.
    genome
        Filter expression to genes within this genome.
    count_file
        Which file in the passed directory to use as the count file. Typically would be one of:
        'filtered_feature_bc_matrix.h5' or 'raw_feature_bc_matrix.h5'.
    library_id
        Identifier for the visium library. Can be modified when concatenating multiple adata objects.
    source_image_path
        Path to the high-resolution tissue image. Path will be included in
        `.uns["spatial"][library_id]["metadata"]["source_image_path"]`.

    Returns
    -------
    Annotated data matrix, where observations/cells are named by their
    barcode and variables/genes by gene name. Stores the following information:

    :attr:`~anndata.AnnData.X`
        The data matrix is stored
    :attr:`~anndata.AnnData.obs_names`
        Cell names
    :attr:`~anndata.AnnData.var_names`
        Gene names
    :attr:`~anndata.AnnData.var`\ `['gene_ids']`
        Gene IDs
    :attr:`~anndata.AnnData.var`\ `['feature_types']`
        Feature types
    :attr:`~anndata.AnnData.uns`\ `['spatial']`
        Dict of spaceranger output files with 'library_id' as key
    :attr:`~anndata.AnnData.uns`\ `['spatial'][library_id]['images']`
        Dict of images (`'hires'` and `'lowres'`)
    :attr:`~anndata.AnnData.uns`\ `['spatial'][library_id]['scalefactors']`
        Scale factors for the spots
    :attr:`~anndata.AnnData.uns`\ `['spatial'][library_id]['metadata']`
        Files metadata: 'chemistry_description', 'software_version', 'source_image_path'
    :attr:`~anndata.AnnData.obsm`\ `['spatial']`
        Spatial spot coordinates, usable as `basis` by :func:`~scanpy.pl.embedding`.
    )r?   Zspatialr   )rP   r%   ©ÚmodeNZlibrary_idsúutf-8z!spatial/tissue_positions_list.csvzspatial/scalefactors_json.jsonzspatial/tissue_hires_image.pngzspatial/tissue_lowres_image.png)Útissue_positions_fileÚscalefactors_json_fileÚhires_imageÚlowres_imagec                 3   s   | ]}|t ˆ ƒkV  qd S )N)r5   ©Ú.0Úx)rY   r=   r>   Ú	<genexpr>€  s     zread_visium.<locals>.<genexpr>)r“   r”   z6You seem to be missing an image file.
Could not find 'z'.zCould not find 'r\   Zimages)ZhiresZlowresZ_imagez_image'r’   Zscalefactorsc                    s:   i | ]2}|ˆ kr|t ˆ | tƒr.tˆ | d ƒnˆ | “qS )r�   )r„   Úbytesr5   ©r–   r…   )Úattrsr=   r>   Ú
<dictcomp>–  s   þ zread_visium.<locals>.<dictcomp>)Zchemistry_descriptionZsoftware_versionÚmetadatar‘   ©ÚheaderZbarcodeZ	in_tissueZ	array_rowZ	array_colZpxl_col_in_fullresZpxl_row_in_fullresÚleft)ÚhowT)ÚcolumnsZinplacerŒ   )r   r[   ry   ZunsrO   rP   r›   r5   ÚpoprS   r8   ÚanyrK   ÚwarningÚOSErrorr	   r|   ÚjsonÚloadsÚ
read_bytesÚpdr   r¢   Úindexrm   ÚjoinZto_numpyZobsmZdropÚresolve)r�   r?   r‰   rŠ   r‹   rŒ   rZ   rP   ÚfilesÚresZ	positionsr=   )r›   rY   r>   Úread_visium)  sx    >ü
ÿÿ
ÿ
þú
ÿþ
ÿr°   Úgene_symbols)Úprefix)r±   rk   )r�   rj   Úmake_uniquer.   r/   r@   r²   r0   c                C   sŠ   t | ƒ} |dkrdn|}| |› d�  ¡ }|r2tnt}|t| ƒ|||||d�}	|sV|sZ|	S ttdd„ |	jd ƒƒ}
|	dd…|
f  ¡ S dS )a      Read 10x-Genomics-formatted mtx directory.

    Parameters
    ----------
    path
        Path to directory for `.mtx` and `.tsv` files,
        e.g. './filtered_gene_bc_matrices/hg19/'.
    var_names
        The variables index.
    make_unique
        Whether to make the variables index unique by appending '-1',
        '-2' etc. or not.
    cache
        If `False`, read from source, if `True`, read from fast 'h5ad' cache.
    cache_compression
        See the h5py :ref:`dataset_compression`.
        (Default: `settings.cache_compression`)
    gex_only
        Only keep 'Gene Expression' data and ignore other feature types,
        e.g. 'Antibody Capture', 'CRISPR Guide Capture', or 'Custom'
    prefix
        Any prefix before `matrix.mtx`, `genes.tsv` and `barcodes.tsv`. For instance,
        if the files are named `patientA_matrix.mtx`, `patientA_genes.tsv` and
        `patientA_barcodes.tsv` the prefix is `patientA_`.
        (Default: no prefix)

    Returns
    -------
    An :class:`~anndata.AnnData` object
    Nrn   ú	genes.tsv)rj   r³   r.   r/   r²   c                 S   s   | dkS )NrI   r=   )r—   r=   r=   r>   Ú<lambda>ö  ó    zread_10x_mtx.<locals>.<lambda>rH   )	r   Úis_fileÚ_read_legacy_10x_mtxÚ_read_v3_10x_mtxr5   rT   ÚmaprR   rV   )r�   rj   r³   r.   r/   r@   r²   Zgenefile_existsr   rZ   Zgex_rowsr=   r=   r>   Úread_10x_mtx½  s$    )úÿr»   rn   c                C   sÎ   t | ƒ} t| |› d� ||d�j}tj| |› d� ddd�}|dkr||d j}|rdtj t 	|¡¡}||_
|d	 j|jd
< n.|d
kr¢|d	 j|_
|d j|jd< ntdƒ‚tj| |› d� dd�d	 j|_|S )zF
    Read mex from output from Cell Ranger v2 or earlier versions
    z
matrix.mtx©r.   r/   r´   Nú	©rŸ   Úsepr±   r   r   rk   ú4`var_names` needs to be 'gene_symbols' or 'gene_ids'zbarcodes.tsvrž   ©r   r   ÚTrª   r   rS   r   ÚutilsZmake_index_uniqueÚIndexrj   rR   r9   rg   ©r�   rj   r³   r.   r/   r²   rZ   ri   r=   r=   r>   r¸   û  s&    ý
 r¸   c                C   sÞ   t | ƒ} t| |› d� ||d�j}tj| |› d� ddd�}|dkr||d j}|rdtj t 	|¡¡}||_
|d	 j|jd
< n.|d
kr¢|d	 j|_
|d j|jd< ntdƒ‚|d j|jd< tj| |› d� dd�d	 j|_|S )zD
    Read mtx from output from Cell Ranger v3 or later versions
    zmatrix.mtx.gzr¼   zfeatures.tsv.gzNr½   r¾   r±   r   r   rk   rÀ   é   rH   zbarcodes.tsv.gzrž   rÁ   rÅ   r=   r=   r>   r¹     s,    ý
ÿr¹   r&   )r   r   r   Znpz)r'   rZ   r*   ÚcompressionÚcompression_optsc                 C   sˆ   t | ƒ} t| ƒr@| } t| dd�}|dkr.|}q`||kr`tdƒ‚n | }|dkrRtjn|}t||ƒ} |dkrt| | ¡ n|j| ||d� dS )a§      Write :class:`~anndata.AnnData` objects to file.

    Parameters
    ----------
    filename
        If the filename has no file extension, it is interpreted as a key for
        generating a filename via `sc.settings.writedir / (filename +
        sc.settings.file_format_data)`. This is the same behavior as in
        :func:`~scanpy.read`.
    adata
        Annotated data matrix.
    ext
        File extension from wich to infer file format. If `None`, defaults to
        `sc.settings.file_format_data`.
    compression
        See http://docs.h5py.org/en/latest/high/dataset.html.
    compression_opts
        See http://docs.h5py.org/en/latest/high/dataset.html.
    T©Ú
return_extNzxIt suffices to provide the file type by providing a proper extension to the filename.One of "txt", "csv", "h5" or "npz".r   )rÇ   rÈ   )r   r3   r9   r   r7   Ú_get_filename_from_keyZ
write_csvsÚwrite)r'   rZ   r*   rÇ   rÈ   Zext_Úkeyr=   r=   r>   rÌ   B  s(    ÿ
  ÿrÌ   )r'   Úasheaderr0   c                 C   sˆ   t | ƒ} ddlm} |g ƒ}t| ƒD ]^}d|kr$|r>| d¡r$| d¡rT|dd… n|}| d¡\}}| ¡ }| ¡ }t|ƒ||< q$|S )aª      Read parameter dictionary from text file.

    Assumes that parameters are specified in the format::

        par1 = value1
        par2 = value2

    Comments that start with '#' are allowed.

    Parameters
    ----------
    filename
        Filename of data file.
    asheader
        Read the dictionary from the header (comment section) of a file.

    Returns
    -------
    Dictionary that stores parameters.
    r   )ÚOrderedDictú=ú#r   N)r5   ÚcollectionsrÏ   ÚopenÚ
startswithÚsplitÚstripÚconvert_string)r'   rÎ   rÏ   ÚparamsÚlinerÍ   Úvalr=   r=   r>   Úread_paramsz  s    rÛ   )r�   c              	   O   s¦   t | ƒ} | j ¡ s | jjdd� t|ƒdkr8|d |d< |  d¡�Z}| ¡ D ]J\}}|dk	rn| d|› d�¡ | ¡ D ]\}}| |› d	|› d
�¡ qvqLW 5 Q R X dS )zc    Write parameters to file, so that it's readable by read_params.

    Uses INI file format.
    T©Úparentsr   r   NÚwú[z]
z = Ú
)r   ÚparentÚis_dirÚmkdirrs   rÓ   rƒ   rÌ   )r�   ÚargsÚmapsrY   rŸ   rº   rÍ   rÚ   r=   r=   r>   Úwrite_params¡  s    
ræ   )r'   c
                 K   sB  |d k	r |t kr tdt › �ƒ‚nt| dd�}t| |d�}|sLt d| › �¡ |dkrˆ|d krht| |d�S t d|› d	| › �¡ t| |ƒS tj	t
| ƒ d
| d¡ }|jdkr¶| d¡}|rÚ| ¡ rÚt d|› �¡ t|ƒS |sîtd| › d
�ƒ‚t d| › �¡ |�s|	�st d¡ |dk�s(|dk�rH|d k�r<tdƒ‚n
t| |ƒ}n¤|dk�r\t| ƒ}n�|dk�rtt| |d�}nx|dk�rª|dk�rœt d¡ t d¡ t| ||ƒ}nB|dk�r¾t| ƒ}n.|dk�rÜtf d| i|
—Ž}ntd|› d
�ƒ‚|�r>t d tj› d!�¡ |tk�rtj}|j ¡ �s0|jjdd"� |j||d#� |S )$Nz0Please provide one of the available extensions.
TrÉ   rB   rC   >   r    r   r2   zreading sheet z from file r1   z.h5ad>   ú.gzú.bz2rn   z... reading from cache file zDid not find file rA   zlThis might be very slow. Consider passing `cache=True`, which enables much faster reading from a cache file.r   Zxlsz5Provide `sheet` parameter when reading '.xlsx' files.>   r"   r!   r   )r,   >   r   r   r   r   r   zA... assuming '.data' means tab or white-space separated text filez'change this by passing `ext` to sc.readr#   r$   r'   zUnknown extension z... writing an z( cache file to speedup reading next timerÜ   )rÇ   )r:   r9   r3   rM   rK   rN   r;   r   r   ZcachedirÚ_slugifyÚreplaceÚsuffixÚwith_suffixr·   rL   ÚFileNotFoundErrorÚhintr   r   r   r   Ú_read_softgzr   r7   r   r/   rá   râ   rã   rÌ   )r'   r(   r)   r*   r+   r,   r-   r.   r/   Zsuppress_cache_warningr<   rX   Z
path_cacherZ   r=   r=   r>   r4   ¹  sv    ÿ
 ÿ

ÿ






ÿ



ÿ
r4   )r�   r0   c                 C   s    t | tƒst| ƒ} t| jƒ}|d dkr4| d¡ n4t|d ƒdkrh|d dd… dkrh|d d |d< d |¡}d|ks‚t|ƒ‚|dd…  d¡rœt|ƒ‚|S )	zMake a path into a filename.r   ú/é   r   Nz:\ú-ú:)	r„   r   rT   Úpartsr£   rs   r¬   ÚAssertionErrorrÔ   )r�   rô   r'   r=   r=   r>   ré     s    

$
ré   )r'   r0   c              	      s|  ddl }|j| dd���"}i ‰|D ]p}| d¡r6 q”q"| d¡rT| d¡d  ¡ }q"| d	¡r"| d¡d  d
¡}dd„ |D ƒ}|D ]}|ˆ|< q„q"| ¡  ¡  d¡‰dd„ tˆƒD ƒ}‡fdd„|D ƒ‰‡fdd„ˆD ƒ}g g  }	}
|D ]J}| d¡�r  �q6| d¡‰ ‡ fdd„|D ƒ}|
 |¡ |	 ˆ d ¡ qêW 5 Q R X t 	|
¡j
}
tjd|iˆd�}tj|	d�}t|
|||
jd�S )a-      Read a SOFT format data file.

    The SOFT format is documented here
    http://www.ncbi.nlm.nih.gov/geo/info/soft2.html.

    Notes
    -----
    The function is based on a script by Kerby Shedden.
    http://dept.stat.lsa.umich.edu/~kshedden/Python-Workshop/gene_expression_comparison.html
    r   NÚrtrŽ   z!dataset_table_beginz!subset_descriptionrÐ   r   z!subset_sample_idú,c                 S   s   g | ]}|  ¡ ‘qS r=   )rÖ   r•   r=   r=   r>   Ú
<listcomp>5  s     z _read_softgz.<locals>.<listcomp>r½   c                 S   s   g | ]\}}|  d ¡r|‘qS )ZGSM)rÔ   )r–   Úir—   r=   r=   r>   rø   ;  s     
 c                    s   g | ]}ˆ | ‘qS r=   r=   ©r–   rù   )Úsample_namesr=   r>   rø   =  s     c                    s   g | ]}ˆ | ‘qS r=   r=   rš   )Úsamples_infor=   r>   rø   ?  s     z!dataset_table_endc                    s   g | ]}t ˆ | ƒ‘qS r=   )Úfloatrú   )ÚVr=   r>   rø   K  s     Úgroups)r«   )ÚXrm   rR   rv   )r&   rÓ   rÔ   rÕ   rÖ   ÚreadlineÚ	enumerateÚappendrw   ÚarrayrÂ   rª   Z	DataFramer
   rv   )r'   r&   ÚfilerÙ   Zsubset_descriptionZ
subset_idsr…   rb   rÿ   rh   r   r—   rm   rR   r=   )rþ   rû   rü   r>   rï     s:    





rï   )Ústringr0   c                 C   s*   zt | ƒ W dS  tk
r$   Y dS X dS )z¥Check whether string is float.

    See also
    --------
    http://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python
    TFN)rý   r9   ©r  r=   r=   r>   Úis_float[  s
    r  c                 C   s*   zt | ƒ W dS  tk
r$   Y dS X dS )z Check whether string is integer.TFN)Úintr9   r  r=   r=   r>   Úis_inti  s
    r
  c                 C   s    | dkrdS | dkrdS dS dS )z Check whether string is boolean.ÚTrue)TTÚFalse)TF)FFNr=   r  r=   r=   r>   Úconvert_boolr  s
    r  c                 C   sL   t | ƒrt| ƒS t| ƒr t| ƒS t| ƒd r8t| ƒd S | dkrDdS | S dS )z%Convert string to int, float or bool.r   r   ÚNoneN)r
  r	  r  rý   r  r  r=   r=   r>   r×   |  s    r×   c               	   C   sj   ddl } dd„ |  ¡ D ƒ}g }|D ]>}z"| ¡ }|D ]}| |j¡ q4W q" | jk
r^   Y q"X q"t|ƒS )z-Get files used by processes with name scanpy.r   Nc                 s   s   | ]}|  ¡ d kr|V  qdS )ZscanpyN)r‡   )r–   Úprocr=   r=   r>   r˜   “  s     z!get_used_files.<locals>.<genexpr>)ÚpsutilZprocess_iterZ
open_filesr  r�   ZNoSuchProcessÚset)r  Zloop_over_scanpy_processesÚ	filenamesr  ÚflistÚntr=   r=   r>   Úget_used_files�  s    ÿr  )r0   c                 C   s&   |d krt jn|}t j| › d|› � S )Nr1   )r   r7   r6   )rÍ   r*   r=   r=   r>   rË   £  s    rË   )Úurlr�   c                 C   s¢  zdd l }ddlm} W n  tk
r8   ddlm} Y nX ddlm}m} ddlm} d}d}�z|| ddid�}	z||	ƒ}
W nJ |k
rÈ   t	 
d	¡ dd
lm} ddlm} ||	||ƒ d�d�}
Y nX |
�˜}| ¡  dd ¡}|dddd|d krö|nt|ƒd��Z}| d¡�D}| |¡}|�rN| |¡ |d7 }| t|ƒ¡ | |¡}�qW 5 Q R X W 5 Q R X W 5 Q R X W n. ttfk
�rœ   | ¡ �r–| ¡  ‚ Y nX d S )Nr   )Útqdm)ÚurlopenÚRequest)ÚURLErrori    z
User-agentzscanpy-user)ÚheaderszFFailed to open the url with default certificates, trying with certifi.)Úwhere)Úcreate_default_context)Úcafile)Úcontextzcontent-lengthÚBTr   i   )ÚunitZ
unit_scaleZminitersZunit_divisorÚtotalÚwb)Ú
ipywidgetsZ	tqdm.autor  ÚImportErrorÚurllib.requestr  r  Úurllib.errorr  rK   r¥   Úcertifir  Ússlr  rL   Úgetr	  rÓ   r   rÌ   Úupdaters   ÚKeyboardInterruptr|   r·   Úunlink)r  r�   r$  r  r  r  r  Ú	blocksizeÚblocknumÚreqZopen_urlr  r  Úrespr"  ÚtrY   Úblockr=   r=   r>   Ú	_download¨  sV    ÿû ú

0
r4  c                 C   sl   t | ƒ} |  ¡ rdS |dkr dS t d|› d�¡ | j ¡ s^t d| j› d�¡ | jjdd� t|| ƒ dS )	z6Check whether the file is present, otherwise download.TNFztry downloading from url
z0
... this may take a while but only happens oncezcreating directory z/ for saving datarÜ   )r   r·   rK   rL   rá   râ   rã   r4  )r�   r-   r=   r=   r>   rM   Û  s    
ÿ

rM   c                 C   s  | j }t|ƒdkr>t d|› d|dd… › d�¡ |dd… }t|ƒdkrŠ|d dd… tkrŠ|d dd… d	krŠ|r†|d dd… S d
S |rº|d dd… tkrº|r¶|d dd… S d
S d |¡dkrÔ|rÐdS d
S d |¡dkrî|rêdS d
S |södS t| ›dt› d�ƒ‚dS )z)Check whether the argument is a filename.rÆ   z,Your filename has more than two extensions: z!.
Only considering the two last: éþÿÿÿNr1   r   r   )ÚgzÚbz2Téÿÿÿÿrn   z.soft.gzr#   z.mtx.gzr"   FzU does not end on a valid extension.
Please, provide one of the available extensions.
z<
Text files with .gz and .bz2 extensions are also supported.)Úsuffixesrs   rK   r¥   Ú	text_extsr:   r¬   r9   )r'   rÊ   r*   r=   r=   r>   r3   î  s*    ÿ4ýÿr3   )NTN)N)Nr&   N)F)	NNNNNNFNF)N)N)F)FÚ__doc__Úpathlibr   r   Útypingr   r   r   r   r   rO   r§   Únumpyrw   Zpandasrª   Zmatplotlib.imager	   r   r
   r   r   r   r   r   r   r   r;   Z	_settingsr   Z_compatr   Ú_utilsr   r   rn   r   rK   r:  r:   r5   Úboolr[   rW   ry   ÚGrouprt   rQ   r°   r»   r¸   r¹   r	  rÌ   rý   rÛ   ræ   r4   ré   r™   rï   r  r
  r  r×   r  rË   r4  rM   r3   r=   r=   r=   r>   Ú<module>   s.  $	ûø	÷÷

õV   ü
û>5& þù
ø úø
÷@ûù$ûù(   û


û9 ÿ
 þ'         öÿT?	
3
