U
    vIÀdk/  ã                   @   s  d dl 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mZ ddlmZ ddlmZ eeƒZedd	„ ƒZe ej¡d
d„ ƒZe e¡dd„ ƒZe e
j¡dd„ ƒZeedœdd„ƒZe e¡edœdd„ƒZ e ej!¡ej!dœdd„ƒZ"e e#dƒ¡ddœdd„ƒZ$edd„ ƒZ%z@ddl&m'Z( dd„ Z)e% e(j*¡dd „ ƒZ+e e(j*¡d!d"„ ƒZ,W n e-k
�r‚   Y nX d8ej.e/d$œd%d&„Z0e/d'œd(d)„Z1ej2e/eej!ej3f d*œd+d,„Z4ee/ee f d-œd.d/„Z5e/d0œd1d2„Z6G d3d4„ d4e#ƒZ7e/e/e	d5œd6d7„Z8dS )9é    N)ÚwrapsÚsingledispatch)ÚMappingÚAnyÚSequenceÚUnionÚCallable)Úsparseé   )Ú
get_logger)ÚSparseDatasetc                 C   s
   t  | ¡S )zConvert x to a numpy array)ÚnpÚasarray©Úx© r   úF/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/anndata/utils.pyr      s    r   c                 C   s   |   ¡ S ©N)Ztoarrayr   r   r   r   Úasarray_sparse   s    r   c                 C   s
   t | jƒS r   )r   Úvaluer   r   r   r   Úasarray_sparse_dataset   s    r   c                 C   s   | d S )N.r   r   r   r   r   Úasarray_h5py_dataset    s    r   )Úreturnc                 C   s   t | ƒS r   ©Údict©Úobjr   r   r   Úconvert_to_dict%   s    r   r   c                 C   s   | S r   r   r   r   r   r   Úconvert_to_dict_dict*   s    r   c                    s8   ˆ j jd krtdˆ j › d�ƒ‚‡ fdd„ˆ j j ¡ D ƒS )NuN   Can only convert np.ndarray with compound dtypes to dict, passed array had â€œu   â€�.c                    s   i | ]}|ˆ | “qS r   r   )Ú.0Úkr   r   r   Ú
<dictcomp>6   s      z+convert_to_dict_ndarray.<locals>.<dictcomp>)ÚdtypeÚfieldsÚ	TypeErrorÚkeysr   r   r   r   Úconvert_to_dict_ndarray/   s
    ÿr&   c                 C   s   t ƒ S r   r   r   r   r   r   Úconvert_to_dict_nonetype9   s    r'   c                 C   s
   | j | S )z—    Return the size of an array in dimension `axis`.

    Returns None if `x` is an awkward array with variable length in the requested dimension.
    ©Úshape)r   Úaxisr   r   r   Údim_len>   s    r+   )Úawkwardc           	      K   sŽ  | j rl| jrd}n| j}|d | d }d|  kr@t|ƒk sVn td|d › d�ƒ‚|| |d< tj ¡ S | jrÄ||d krÄ|  	d¡dkr td|d › d�ƒ‚| j
r²| j|d< nd	|d< tj ¡ S | jrî||d krît| jƒ|d< tj ¡ S | j�r
td
|d › �ƒ‚n€| j�rŠd}| jD ]Z}d|d i}tjt||d� |dk�rP|d }n$||d k�rd	|d< tj ¡   S �q||d< tj ¡ S dS )zNCallback function for dim_len_awkward, resolving the dim_len for a given level)r   r*   r
   zaxis=z is too deepÚoutZ	__array__)ÚstringÚ
bytestringéÿÿÿÿz.Cannot recurse into record type found at axis=N©Úlateral_context)Zis_numpyZ
is_unknownr)   Úlenr$   ÚakÚcontentsZ
EmptyArrayZis_listZ	parameterZ
is_regularÚsizeZ	is_recordr#   Zis_unionÚ	transformÚ_size_at_depth)	ZlayoutÚdepthr2   Úkwargsr)   Z
numpy_axisÚresultÚcontentÚcontextr   r   r   r8   K   sN    


ÿ
ý

r8   c                 C   sV   |dk rt dƒ‚n@|dkr"t| ƒS d|i}tjt| |d� |d dkrJdS |d S dS )a  Get the length of an awkward array in a given dimension

        Returns None if the dimension is of variable length.

        Code adapted from @jpivarski's solution in https://github.com/scikit-hep/awkward/discussions/1654#discussioncomment-3521574
        r   zDoes not support negative axisr*   r1   r-   r0   N)ÚNotImplementedErrorr3   r4   r7   r8   )Úarrayr*   r=   r   r   r   Údim_len_awkward‰   s    
ýr@   c                 C   s   | S r   r   r   r   r   r   Úasarray_awkward£   s    rA   ú-)ÚindexÚjoinc                 C   s  | j r
| S ddlm} | j ¡ }| jdd�}|| }t|ƒ}|ƒ }d}g }	t|ƒD ]d\}
}||  d7  < || t|| ƒ }||krš| 	|¡ |||
< qRd}t
|	ƒdk rZ|	 |¡ qZqR|ræt d	|› d
�d d d d t|	ƒ ¡ |||< tj|| jd�} | S )aË  
    Makes the index unique by appending a number string to each duplicate index element:
    '1', '2', etc.

    If a tentative name created by the algorithm already exists in the index, it tries
    the next integer in the sequence.

    The first occurrence of a non-unique value is ignored.

    Parameters
    ----------
    join
         The connecting string between name and integer.

    Examples
    --------
    >>> from anndata import AnnData
    >>> adata = AnnData(np.ones((2, 3)), var=pd.DataFrame(index=["a", "a", "b"]))
    >>> adata.var_names
    Index(['a', 'a', 'b'], dtype='object')
    >>> adata.var_names_make_unique()
    >>> adata.var_names
    Index(['a', 'a-1', 'b'], dtype='object')
    r   )ÚCounterÚfirst)ZkeepFr
   Té   zSuffix used (z3[0-9]+) to deduplicate index values may make index zGvalues difficult to interpret. There values with a similar suffixes in z;the index. Consider using a different delimiter by passing z`join={delimiter}`zEExample key collisions generated by the make_index_unique algorithm: )Úname)Z	is_uniqueÚcollectionsrE   ÚvaluesÚcopyZ
duplicatedÚsetÚ	enumerateÚstrÚaddr3   ÚappendÚwarningsÚwarnÚpdÚIndexrH   )rC   rD   rE   rJ   Zindices_dupZ
values_dupZ
values_setÚcounterZissue_interpretation_warningZexample_colliding_valuesÚiÚvZtentative_new_namer   r   r   Úmake_index_unique«   sJ    


ÿþýüûÿrX   ©Úattrc                 C   s0   | dkrdnd}t j|› d| › d�tdd� d S )NZobsZObservationÚVariablez3 names are not unique. To make them unique, call `.z_names_make_unique`.é   )Ú
stacklevel)rQ   rR   ÚUserWarning)rZ   Únamesr   r   r   Úwarn_names_duplicatesé   s    ür`   )ÚdfrH   r   c                 C   sT   t dd„ | jD ƒƒr$| j ¡  ¡ }n|  ¡ }| j ¡ dkrPt |› d|j	› �¡ |S )Nc                 s   s   | ]}t |tjƒV  qd S r   )Ú
isinstancerS   ZSparseDtype)r   Údtr   r   r   Ú	<genexpr>÷   s     z(ensure_df_homogeneous.<locals>.<genexpr>r
   z% converted to numpy array with dtype )
ÚallZdtypesr	   Zto_cooZtocsrZto_numpyZnuniquerQ   rR   r"   )ra   rH   Úarrr   r   r   Úensure_df_homogeneousó   s    rg   )Úsourcec                 C   sº   t |  ¡ ƒ}zdd„ |  ¡ D ƒ}W n tk
r>   tdƒ‚Y nX t t|dd„ |D ƒdd„ |D ƒƒƒ}t |¡}t t	|d ƒf|¡}t
|jƒD ]&\}}tj|| || d d�||< qŽ|S )	Nc                 S   s<   g | ]4}t  |d  ¡jjdkr(t  |¡nt  |¡ d¡‘qS )r   >   ÚUÚSri   )r   r?   r"   Úcharr   Zastype)r   Úcolr   r   r   Ú
<listcomp>  s   þÿz:convert_dictionary_to_structured_array.<locals>.<listcomp>uV   Currently only support ascii strings. Donâ€™t use â€œÃ¶â€� etc. for sample annotation.c                 S   s   g | ]}t |jƒ‘qS r   )rN   r"   ©r   Úcr   r   r   rm     s     c                 S   s   g | ]}|j d  f‘qS )r
   r(   rn   r   r   r   rm     s     r   r
   )r"   )Úlistr%   rJ   ÚUnicodeEncodeErrorÚ
ValueErrorÚzipr   r"   Zzerosr3   rM   r_   r?   )rh   r_   ÚcolsZ
dtype_listr"   rf   rV   rH   r   r   r   Ú&convert_dictionary_to_structured_array   s"    ü
ÿ
ÿ
 ru   ©Únew_namec                    s   ‡ fdd„}|S )zœ    This is a decorator which can be used to mark functions
    as deprecated. It will result in a warning being emitted
    when the function is used.
    c                    s&   t ˆ ƒ‡ ‡fdd„ƒ}t|ddƒ |S )Nc                     sJ   t  dt¡ t jdˆ› dˆ j› dˆ j› d�tdd� t  dt¡ ˆ | |ŽS )	NÚalwayszUse z instead of z, z will be removed in the future.r\   )Úcategoryr]   Údefault)rQ   ÚsimplefilterÚDeprecationWarningrR   Ú__name__)Úargsr:   )Úfuncrw   r   r   Únew_func-  s    üz/deprecated.<locals>.decorator.<locals>.new_funcÚ__deprecatedT)r   Úsetattr)r   r€   rv   )r   r   Ú	decorator,  s    zdeprecated.<locals>.decoratorr   )rw   rƒ   r   rv   r   Ú
deprecated%  s    r„   c                   @   s   e Zd ZdZdd„ ZdS )ÚDeprecationMixinMetazt    Use this as superclass so deprecated methods and properties
    do not appear in vars(MyClass)/dir(MyClass)
    c                    s"   dd„ ‰‡ ‡fdd„t  ˆ ¡D ƒS )Nc                 S   s   t | tƒr| j} t| ddƒS )Nr�   F)rb   ÚpropertyÚfgetÚgetattrrY   r   r   r   Úis_deprecatedG  s    
z3DeprecationMixinMeta.__dir__.<locals>.is_deprecatedc                    s    g | ]}ˆt ˆ |d ƒƒs|‘qS r   )rˆ   )r   Úitem©Úclsr‰   r   r   rm   L  s   þz0DeprecationMixinMeta.__dir__.<locals>.<listcomp>)ÚtypeÚ__dir__)rŒ   r   r‹   r   rŽ   F  s    þzDeprecationMixinMeta.__dir__N)r}   Ú
__module__Ú__qualname__Ú__doc__rŽ   r   r   r   r   r…   @  s   r…   )ÚmodulerH   r   c              
      s^   ddl m} z|| ƒ} t| |ƒ}W n6 ttfk
rX } z|‰ ‡ fdd„}W 5 d}~X Y nX |S )a      Try to import function from module. If the module is not installed or
    function is not part of the module, it returns a dummy function that raises
    the respective import error once the function is called. This could be a
    ModuleNotFoundError if the module is missing or an AttributeError if the
    module is installed but the function is not exported by it.

    Params
    -------
    module
        Module to import from. Can be nested, e.g. "sklearn.utils".
    name
        Name of function to import from module.
    r   )Úimport_modulec                     s   ˆ ‚d S r   r   )Ú_Ú__©Úerrorr   r   r   j  s    zimport_function.<locals>.funcN)Ú	importlibr“   rˆ   ÚImportErrorÚAttributeError)r’   rH   r“   r   Úer   r–   r   Úimport_functionS  s    rœ   )rB   )9rQ   Ú	functoolsr   r   Útypingr   r   r   r   r   Zh5pyZpandasrS   Únumpyr   Zscipyr	   Úloggingr   Z_core.sparse_datasetr   r}   Úloggerr   ÚregisterZspmatrixr   r   ZDatasetr   r   r   r   Zndarrayr&   r�   r'   r+   Úcompatr,   r4   r8   ZArrayr@   rA   r™   rT   rN   rX   r`   Z	DataFrameZ
csr_matrixrg   ru   r„   r…   rœ   r   r   r   r   Ú<module>   s\   






	
	>


> þ%