[e72cf6]: / __pycache__ / eval_utils.cpython-38.pyc

Download this file

242 lines (226 with data), 18.8 kB

U

¨‹cHkã@s¼UddlmZddlZddlZddlZddlZddlZ	ddl
ZddlZddl
mZddlmZddlmZddlmZddlmZmZmZmZmZddlmZddlmZm Z m!Z!dd	l"m#Z#ddl$Z$ddl%Z%e$j&d
dZ'ede(fe)d<e'dkre$j&d
dZ'e(e)d<e *e+¡Z,dddddddddgddddd
dddddddde-ƒfe	j.e(e/e(ee0e/e/ee/dfee/e1e/e/ee/dfe(e0e0e(ede(ej2j3ej2j4fe-ee/ee0deffdœd d!„Z5dddddddddgddddd
dddddddde-ƒfe	j.e(e/e(ee0e/e/ee/dfee/e1e/e/ee/dfe(e0e0e(ede(ej2j3ej2j4fe-ee/ee0deffdœd"d#„Z6ede(fe(d$œd%d&„Z7d'd(„Z8dLe	j.e/e(e(e1ej9d*œd+d,„Z:dMe	j.e/d-œd.d/„Z;dNe	j.e/e/e(e0e(ede(fe1ee0e0e0fd1œ	d2d3„Z<d4d5„Z=d6d7„Z>dOe	j.e/e/e(e(e(e(ede(fe1e0d:œ
d;d<„Z?dPe	j.ee0e/e/e/ee/e0e0fd=œd>d?„Z@dddd@dAd
de-ƒfe	j.ee/ee/dfe0e0e/e/e1e(e-edefdBœ
dCdD„ZAdQe/e(e1e1e(ee(dIœdJdK„ZBdS)Ré)ÚinfN)ÚFigure)Úspmatrix)Úchi2)ÚMappingÚSequenceÚTupleÚIterableÚUnion)Úissparse)Úadjusted_rand_scoreÚnormalized_mutual_info_scoreÚsilhouette_samples)ÚNearestNeighborsF)ZlogicalÚ
_cpu_countTÚdeltaég{®Gáz„?g{®Gáz”?g{®Gáz¤?g{®Gáz´?g{®GázÄ?g{®GázÔ?g{®Gázä?ÚleidenÚ
cell_typesÚ
batch_indicesÚumapZjpgi,g333333Ó?é)ÚadataÚn_epochÚ
embedding_keyÚn_neighborsÚresolutionsÚclustering_methodÚ
cell_type_colÚ	batch_colÚcolor_byÚ
return_figÚ
plot_fnameÚ
plot_ftypeÚplot_dirÚplot_dpiÚmin_distÚspreadÚn_jobsÚrandom_stateÚumap_kwargsÚreturnc!Csª|r4tjj |j|¡s4|j| t¡ d¡|j|<|rhtjj |j|¡sh|j| t¡ d¡|j|<t||||dd||jkrªt|ƒdkrªt	|||||d\}}}nd}}}|j| 
¡dkrZt|dkrÚ|jn|j
||j|ƒ}||jd	<t |¡}tjj|||d
}|rb|rb|jj||d	dd}|dk	rb| tj ||
›d
¡¡nd}d}|ox|j| 
¡dk}|rÐt||||d|d}t||||d|dd}tjj||d|dd}t||d}nd}}}}|	sð|dk	rŒ|dkr|r||gn|g}t|ƒ}d|jkrJ|jdD]}||kr,| d|¡q,|dk	r^|g|}t||||||
t|ƒ›d|›|	|
|d	} nd} t ||||||||| d	S)áÕEvaluates the clustering and batch correction performance of the given
    embeddings, and optionally plots the embeddings.

    Embeddings will be plotted if return_fig is True or plot_dir is provided.
    When tensorboard_dir is provided, will also save the embeddings using a
    tensorboard SummaryWriter.

    NOTE: Set n_jobs to 1 if you encounter pickling error.

    Args:
        adata: the dataset with the embedding to be evaluated.
        embedding_key: the key to the embedding. Must be in adata.obsm.
        n_neighbors: #neighbors used when computing neithborhood graph and
            calculating entropy of batch mixing / kBET.
        resolutions: a sequence of resolutions used for clustering.
        clustering_method: clustering method used. Should be one of 'leiden' or
            'louvain'.
        cell_type_col: a key in adata.obs to the cell type column.
        batch_col: a key in adata.obs to the batch column.
        return_fig: whether to return the Figure object. Useful for visualizing
            the plot.
        color_by: a list of adata.obs column keys to color the embeddings by.
            If None, will look up adata.uns['color_by']. Only used if is
            drawing.
        plot_fname: file name of the generated plot. Only used if is drawing.
        plot_ftype: file type of the generated plot. Only used if is drawing.
        plot_dir: directory to save the generated plot. If None, do not save
            the plot.
        plot_dpi: dpi to save the plot.
        writer: an initialized SummaryWriter to save the UMAP plot to. Only
            used if is drawing.
        min_dist: the min_dist argument in sc.tl.umap. Only used is drawing.
        spread: the spread argument in sc.tl.umap. Only used if is drawing.
        n_jobs: # jobs to generate. If <= 0, this is set to the number of
            physical cores.
        random_state: random state for knn calculation.
        umap_kwargs: other kwargs to pass to sc.pl.umap.

    Returns:
        A dict storing the ari, nmi, asw, ebm and k_bet of the cell embeddings
        with key "ari", "nmi", "asw", "ebm", "k_bet", respectively. If draw is
        True and return_fig is True, will also store the plotted figure with
        key "fig".
    ÚcategoryT©Úuse_reprr)Úcalc_knnr©rrrrNrÚXZsilhouette_width)Ú	group_keyÚembedÚmean)ÚindexÚcolumnsÚvaluesZaggfuncz.csvgF)r/rrr0r(éÚ	cell_type)Z	batch_keyr3r4Úverbose©r/r Ú.)	rr r&r'Úckpt_dirÚfnamer!Údpir*)	ÚariÚnmiÚaswÚasw_2ÚebmÚk_betÚ	batch_aswÚbatch_graph_scoreÚfig)!ÚpdÚapiÚtypesÚis_categorical_dtypeÚobsÚastypeÚstrÚ_get_knn_indicesÚlenÚ
clusteringÚnuniquerr2ÚobsmÚnpr5ÚscibÚmeZ
silhouetteZpivot_tableÚto_csvÚosÚpathÚjoinÚcalculate_entropy_batch_mixingÚcalculate_kbetZsilhouette_batchÚget_graph_connectivityÚlistÚunsÚinsertÚdraw_embeddingsÚdict)!rrrrrrrrr r!r"r#r$r%r&r'r(r)r*Úcluster_keyÚbest_ariÚbest_nmiÚswrCrDZsw_tableZ
need_batchrErFrGrHÚcolrI©rjúME:\cornell work\moETM\Demo code_all_data_pathway_gene_embedding\eval_utils.pyÚevaluates–Aÿ

ÿ
ûûú



ü÷rlcCsº|r4tjj |j|¡s4|j| t¡ d¡|j|<|rhtjj |j|¡sh|j| t¡ d¡|j|<t||||dd||jkrªt|ƒdkrªt	|||||d\}}}nd}}}|S)r,r-Tr.rr1N)
rJrKrLrMrNrOrPrQrRrS)rrrrrrrrr r!r"r#r$r%r&r'r(r)r*rerfrgrjrjrkÚevaluate_ari¹sArm)r(r+cCs |dkrdS|dkrt|ƒStS)zAIf n_jobs <= 0, set it as the number of physical cores _cpu_countNrr)Úintr©r(rjrjrkÚ_eff_n_jobssrpcCsž|jd}|jd}t |df¡}t|ƒD]n}t |||dd…f¡jddj}||}	t 	||	d|	¡}
dt
 |
|¡}|
||df<|||df<q*|S)Nrrr9F)Úsort)ÚsizeÚshaperVÚzerosÚrangerJÚSeriesÚvalue_countsr8ÚsumrÚcdf)Úknn_indicesÚattr_valuesÚ
ideal_distrÚdofÚnsÚresultsÚiZobserved_countsZexpected_countsÚstatZp_valuerjrjrkÚ_calculate_kbet_for_one_chunks

$r‚é)rr/rr)r0r+cCsÚ|r†|dks$||jks$t|›dƒ‚t |¡}|j|d||dd|j|jd<|j|jd<|j|jd<ddd||dd	d
œdœ|j	d<nJd|j	ks˜td
ƒ‚|j	ddd|ksÐtd|j	ddd›d|›ƒ‚|jdS)Nr2z! not in adata.obsm and is not "X"T)rZknnr/r)Zwrite_knn_indicesÚ	distancesÚconnectivitiesrzZ	euclideanr)rr/ÚmetricÚmethod)Zconnectivities_keyZ
distances_keyZknn_indices_keyÚparamsÚ	neighborszNo precomputed knn exists.rˆrzpre-computed n_neighbors is z, which is smaller than )
rUÚAssertionErrorÚscZ	NeighborsZcompute_neighborsr„Zobspr…rzra)rr/rr)r0r‰rjrjrkrQ%s6 
ÿüüÿÿÿrQ)rr/cCs$tjj||dtjj|dd}|S)Nr<r:)Z	label_key)r‹Úppr‰rWrXZgraph_connectivity)rr/Úscorerjrjrkr_Esr_皙™™™™©?)	rr/rrÚalphar)r(r0r+c
sžt d¡||jkst‚|j|jjdkrRt d|›d¡|j| d¡|j|<|j|jdddj	‰|j
d}ˆj}	|j|j	 ¡‰t
|	ƒˆ_t||ˆ||ƒ‰tt|ƒ|ƒ}tj|d	td
‰||}
||}t
|ƒD](}ˆ||
||krôd	ndˆ|d	<qÚddlm}
m‰m}|d|d
2t |
ƒ‡‡‡‡‡‡fdd„t
|ƒDƒƒ¡}W5QRX|jdd}|d}|d	}|dd…d	f|k ¡|}|||fS)a²Calculates the kBET metric of the data.

    kBET measures if cells from different batches mix well in their local
    neighborhood.

    Args:
        adata: annotated data matrix.
        use_rep: the embedding to be used. Must exist in adata.obsm.
        batch_col: a key in adata.obs to the batch column.
        n_neighbors: # nearest neighbors.
        alpha: acceptance rate threshold. A cell is accepted if its kBET
            p-value is greater than or equal to alpha.
        random_state: random seed. Used only if method is "hnsw".
        n_jobs: # jobs to generate. If <= 0, this is set to the number of
            physical cores.
        calc_knn: whether to re-calculate the kNN graph or reuse the one stored
            in adata.

    Returns:
        stat_mean: mean kBET chi-square statistic over all cells.
        pvalue_mean: mean kBET p-value over all cells.
        accept_rate: kBET Acceptance rate of the sample.
    zCalculating kbet...r-zMaking the column z of adata.obs categorical.TF)Ú	normalizerqrr)Údtype©ÚParallelÚdelayedÚparallel_backendÚlokyroc3s<|]4}ˆtƒˆˆ|ˆ|d…dd…fˆˆˆƒVqdS)rN)r‚©Ú.0r€©r{r”r|rzrZstartsrjrkÚ	<genexpr>Šsýÿz!calculate_kbet.<locals>.<genexpr>)ÚaxisN)Ú_loggerÚinforNrŠr‘ÚnameÚwarningrOrwr8rsrrÚcopyruÚ
categoriesrQÚminrprVrtrnÚjoblibr“r”r•Úconcatenater5rx)rr/rrrr)r(r0ÚnsampleÚnbatchZquotientÚ	remainderr€r“r•ZkBET_arrÚresZ	stat_meanZpvalue_meanZaccept_raterjr™rkr^Ms<"
ÿ

&üÿ	r^cCs6tj|dd\}}|| ¡}|t |d¡ ¡S)NT)Ú
return_countsg ÂëþKH´9)rVÚuniquerxÚlog)Z	hist_dataÚ_ÚcountsZfreqsrjrjrkÚ_entropyšsr®cs6tjjt |¡|d‰t ‡‡‡fdd„t|ƒDƒ¡S)N)rrcs g|]}tˆˆˆ|ƒ‘qSrj)r®r—©ÚbatchesÚindicesrzrjrkÚ
<listcomp>¤sÿz6_entropy_batch_mixing_for_one_pool.<locals>.<listcomp>)rVÚrandomÚchoiceÚaranger5ru)r°rzr¥Ún_samples_per_poolrjr¯rkÚ"_entropy_batch_mixing_for_one_pool sÿþÿr·é2éd)
rr/rrÚn_poolsr¶r)r(r0r+c	
s~t d¡ˆj‰tˆ||||ƒ‰ddlm}	m‰m}
|
d|dd2t 	|	ƒ‡‡‡‡‡‡fdd„t
|ƒDƒƒ¡}W5QRX|S)	aqCalculates the entropy of batch mixing of the data.

    kBET measures if cells from different batches mix well in their local
    neighborhood.

    Args:
        adata: annotated data matrix.
        use_rep: the embedding to be used. Must exist in adata.obsm.
        batch_col: a key in adata.obs to the batch column.
        n_neighbors: # nearest neighbors.
        n_pools: #pools of cells to calculate entropy of batch mixing.
        n_samples_per_pool: #cells per pool to calculate within-pool entropy.
        random_state: random seed. Used only if method is "hnsw".
        n_jobs: # jobs to generate. If <= 0, this is set to the number of
            physical cores.
        calc_knn: whether to re-calculate the kNN graph or reuse the one stored
            in adata.

    Returns:
        score: the mean entropy of batch mixing, averaged from n_pools samples.
    z#Calculating batch mixing entropy...rr’r–r)r(Zinner_max_num_threadsc3s&|]}ˆtƒˆjˆˆˆˆƒVqdS)N)r·rN)r˜r¬©rrr”rzr¶r¥rjrkršÔsýÿz1calculate_entropy_batch_mixing.<locals>.<genexpr>)rœrÚn_obsrQr£r“r”r•rVr5ru)rr/rrrºr¶r)r(r0r“r•rrjr»rkr]«s!
üÿr])rrrrrr+cCs8t|ƒdkstdƒ‚|dkr&tjj}n|dkr8tjj}ntdƒ‚||jksXt|›dƒ‚dtt}}}|D]²}	|›d|	›}
|||	|
d	t	|j||j|
ƒ}t
|j||j|
ƒ}|j|
 ¡}
||krÚ|	}|}||kræ|}||jkr|j| ¡d
krt	|j||j|
ƒ}qpd}qp|›d|›||fS)a¼Clusters the data and calculate agreement with cell type and batch
    variable.

    This method cluster the neighborhood graph (requires having run sc.pp.
    neighbors first) with "clustering_method" algorithm multiple times with the
    given resolutions, and return the best result in terms of ARI with cell
    type.
    Other metrics such as NMI with cell type, ARi with batch are logged but not
    returned. (TODO: also return these metrics)

    Args:
        adata: the dataset to be clustered. adata.obsp shouhld contain the keys
            'connectivities' and 'distances'.
        resolutions: a list of leiden/louvain resolution parameters. Will
            cluster with each resolution in the list and return the best result
            (in terms of ARI with cell type).
        clustering_method: Either "leiden" or "louvain".
        cell_type_col: a key in adata.obs to the cell type column.
        batch_col: a key in adata.obs to the batch column.

    Returns:
        best_cluster_key: a key in adata.obs to the best (in terms of ARI with
            cell type) cluster assignment column.
        best_ari: the best ARI with cell type.
        best_nmi: the best NMI with cell type.
    rz%Must specify at least one resolution.rÚlouvainzDPlease specify louvain or leiden for the clustering method argument.z not in adata.obsNr¬)Ú
resolutionZ	key_addedr)rRrŠr‹Útlrr½Ú
ValueErrorrNrrr
rT)rrrrrZclustering_funcZbest_resrfrgr¨rirArBZn_uniqueZ	ari_batchÚarjrjrkrSÞs."

 rSr=zumap.pdf)
rr r&r'r>r?r!r@r*r+c	
CsŠtjj|||dtjj|f|dddœ|—Ž}	|dk	rltj |¡sRtd|›dƒ‚|	jtj 	||¡|dd	|rt|	S|	 
¡t |	¡dS)
aÁEmbeds, plots and optionally saves the neighborhood graph with UMAP.

    Requires having run sc.pp.neighbors first.

    Args:
        adata: the dataset to draw. adata.obsp shouhld contain the keys
            'connectivities' and 'distances'.
        color_by: a str or a list of adata.obs keys to color the points in the
            scatterplot by. E.g. if both cell_type_col and batch_col is in
            color_by, then we would have two plots colored by cell type and
            batch variables, respectively.
        min_dist: The effective minimum distance between embedded points.
            Smaller values will result in a more clustered/clumped embedding
            where nearby points on the manifold are drawn closer together,
            while larger values will result on a more even dispersal of points.
        spread: The effective scale of embedded points. In combination with
            `min_dist` this determines how clustered/clumped the embedded
            points are.
        ckpt_dir: where to save the plot. If None, do not save the plot.
        fname: file name of the saved plot. Only used if ckpt_dir is not None.
        return_fig: whether to return the Figure object. Useful for visualizing
            the plot.
        dpi: the dpi of the saved plot. Only used if ckpt_dir is not None.
        umap_kwargs: other kwargs to pass to sc.pl.umap.

    Returns:
        If return_fig is True, return the figure containing the plot.
    )r&r'FT)ÚcolorÚshowr!Nz	ckpt_dir z does not exist.Ztight)r@Zbbox_inches)
r‹r¿rÚplrZr[ÚexistsrŠZsavefigr\ZclfÚpltÚclose)
rr r&r'r>r?r!r@r*rIrjrjrkrc s(þrcÚaggéxé
©rÊrÊ©Zmatplotlib_backendr@ÚframeonÚvector_friendlyÚfontsizeÚfigsizecCs"t |¡tj|||||ddS)u¤Set figure parameters.
    Args
        backend: the backend to switch to.  This can either be one of th
            standard backend names, which are case-insensitive:
            - interactive backends:
                GTK3Agg, GTK3Cairo, MacOSX, nbAgg,
                Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo,
                TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo
            - non-interactive backends:
                agg, cairo, pdf, pgf, ps, svg, template
            or a string of the form: ``module://my.module.name``.
        dpi: resolution of rendered figures – this influences the size of
            figures in notebooks.
        frameon: add frames and axes labels to scatter plots.
        vector_friendly: plot scatter plots using `png` backend even when
            exporting as `pdf` or `svg`.
        fontsize: the fontsize for several `rcParams` entries.
        figsize: plt.rcParams['figure.figsize'].
    )r@rÐrÏrÍrÎN)Ú
matplotlibÚuser‹Úset_figure_paramsrÌrjrjrkrÓVs
rÓ)rrƒrT)r)rrrƒrŽrNT)rrr¸r¸r¹rNT)rrr)rÈrÉTTrÊrË)CÚmathrrZÚloggingÚnumpyrVZscanpyr‹ZanndataÚadÚpandasrJrÑZmatplotlib.figurerÚmatplotlib.pyplotÚpyplotrÆZscipy.sparse.csrrZscipy.statsrÚtypingrrrr	r
Zscipy.sparserZsklearn.metricsrr
rZsklearn.neighborsrZpsutilrWÚ	cpu_countrrnÚ__annotations__Ú	getLoggerÚ__name__rœrdZAnnDatarPÚfloatÚboolr³ÚRandomStateÚ	Generatorrlrmrpr‚ÚndarrayrQr_r^r®r·r]rSrcrÓrjrjrjrkÚ<module>s’

î

íî

íSüû"þþ
ø
÷M
÷
ö6ûúCø
÷7úú