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

Download this file

282 lines (262 with data), 20.8 kB

B

ðaFkã@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rNx*|jdD]}||kr.| d|¡q.W|dk	rb|g|}t||||||
t|ƒ›d|›|	|
|d	} nd} t ||||||||| d	S)aÕ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-rrr.r(éÚ	cell_type)Z	batch_keyr0r1Ú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Únuniquerr/ÚobsmÚnpr2Ú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Úswr?r@Zsw_tableZ
need_batchrArBrCrDÚcolrE©rfú6C:\Users\Xin\Desktop\mscETM\Demo code_BS\eval_utils.pyÚevaluates‚A







rhcCsº|r4tjj |j|¡s4|j| t¡ d¡|j|<|rhtjj |j|¡sh|j| t¡ d¡|j|<t||||dd||jkrªt|ƒdkrªt	|||||d\}}}nd}}}|S)aÕ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".
    r,T)r-rr)r.r)rrrrN)
rFrGrHrIrJrKrLrMrNrO)rrrrrrrrr r!r"r#r$r%r&r'r(r)r*rarbrcrfrfrgÚevaluate_ari¸sAri)r(r+cCs |dkrdS|dkrt|ƒStS)zAIf n_jobs <= 0, set it as the number of physical cores _cpu_countNrr)Úintr)r(rfrfrgÚ_eff_n_jobssrkcCs¢|jd}|jd}t |df¡}xzt|ƒD]n}t |||dd…f¡jddj}||}	t 	||	d|	¡}
dt
 |
|¡}|
||df<|||df<q,W|S)Nrrr6F)Úsort)ÚsizeÚshaperRÚzerosÚrangerFÚSeriesÚvalue_countsr5ÚsumrÚcdf)Úknn_indicesÚattr_valuesÚ
ideal_distrÚdofÚnsÚresultsÚiZobserved_countsZexpected_countsÚstatZp_valuerfrfrgÚ_calculate_kbet_for_one_chunks

$r}é)rr-rr)r.r+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)Nr/z! not in adata.obsm and is not "X"T)rZknnr-r)Zwrite_knn_indicesÚ	distancesÚconnectivitiesruZ	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 )
rQÚAssertionErrorÚscZ	NeighborsZcompute_neighborsrZobspr€rur])rr-rr)r.r„rfrfrgrM$s& 
,rM)rr-cCs$tjj||dtjj|dd}|S)N)r-r7)Z	label_key)r†Úppr„rSrTZgraph_connectivity)rr-Úscorerfrfrgr[Dsr[皙™™™™©?)	rr-rrÚalphar)r(r.r+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
‰||}
||}x4t
|ƒD](}ˆ||
||kröd	ndˆ|d	<qÜWddlm}
m‰m}|d|d
2t |
ƒ‡‡‡‡‡‡fdd„t
|ƒDƒƒ¡}WdQRX|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)Ú	normalizerlrr)Údtype)ÚParallelÚdelayedÚparallel_backendÚloky)r(c3s<|]4}ˆtƒˆˆ|ˆ|d…dd…fˆˆˆƒVqdS)rN)r})Ú.0r{)rvrŽrwrurÚstartsrfrgú	<genexpr>Šsz!calculate_kbet.<locals>.<genexpr>N)Úaxis)Ú_loggerÚinforJr…rŒÚnameÚwarningrKrrr5rnrmÚcopyrpÚ
categoriesrMÚminrkrRrorjÚjoblibrrŽrÚconcatenater2rs)rr-rrrŠr)r(r.ÚnsampleZnbatchZquotientÚ	remainderr{rrZkBET_arrÚresZ	stat_meanZpvalue_meanZaccept_raterf)rvrŽrwrurr’rgrZLs8"


(rZcCs6tj|dd\}}|| ¡}|t |d¡ ¡S)NT)Ú
return_countsg ÂëþKH´9)rRÚuniquersÚlog)Z	hist_dataÚ_ÚcountsZfreqsrfrfrgÚ_entropy™sr¦cs6tjjt |¡|d‰t ‡‡‡fdd„t|ƒDƒ¡S)N)rmcs g|]}tˆˆˆ|ƒ‘qSrf)r¦)r‘r{)ÚbatchesÚindicesrurfrgú
<listcomp>¤sz6_entropy_batch_mixing_for_one_pool.<locals>.<listcomp>)rRÚrandomÚchoiceÚaranger2rp)r§ruržÚn_samples_per_poolrf)r§r¨rurgÚ"_entropy_batch_mixing_for_one_poolŸs
r®é2éd)
rr-rrÚn_poolsr­r)r(r.r+c	
s~t d¡ˆj‰tˆ||||ƒ‰ddlm}	m‰m}
|
d|dd2t 	|	ƒ‡‡‡‡‡‡fdd„t
|ƒDƒƒ¡}Wd	QRX|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...r)rrŽrrr)r(Zinner_max_num_threadsc3s&|]}ˆtƒˆjˆˆˆˆƒVqdS)N)r®rJ)r‘r¤)rrrŽrur­ržrfrgr“Ôsz1calculate_entropy_batch_mixing.<locals>.<genexpr>N)r•r–Ún_obsrMrœrrŽrrRr2rp)rr-rrr±r­r)r(r.rrrˆrf)rrrŽrur­ržrgrYªs!
rY)rrrrrr+cCs<t|ƒdkstdƒ‚|dkr&tjj}n|dkr8tjj}ntdƒ‚||jksXt|›dƒ‚dtt}}}xº|D]²}	|›d|	›}
|||	|
d	t	|j||j|
ƒ}t
|j||j|
ƒ}|j|
 ¡}
||krÜ|	}|}||krè|}||jkr |j| ¡d
kr t	|j||j|
ƒ}qrd}qrW|›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)rNr…r†Útlrr³Ú
ValueErrorrJrrr
rP)rrrrrZclustering_funcZbest_resrbrcr rer=r>Zn_uniqueZ	ari_batchÚarfrfrgrOÝs."


 rOr9zumap.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ÚplrVrWÚexistsr…ZsavefigrXZclfÚpltÚclose)
rr r&r'r:r;r!r<r*rErfrfrgr_s(
r_Úaggéxé
©rÀrÀ)Úmatplotlib_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)Ú
matplotlibZuser†Úset_figure_params)rÂr<rÃrÄrÅrÆrfrfrgrÈUs
rÈ)rr~rT)r)rrr~r‰rNT)rrr¯r¯r°rNT)rrr)r¾r¿TTrÀrÁ)CÚmathrrVÚloggingÚnumpyrRZscanpyr†ZanndataÚadÚpandasrFrÇZmatplotlib.figurerÚmatplotlib.pyplotÚpyplotr¼Zscipy.sparse.csrrZscipy.statsrÚtypingrrrr	r
Zscipy.sparserZsklearn.metricsrr
rZsklearn.neighborsrZpsutilrSÚ	cpu_countrrjÚ__annotations__Ú	getLoggerÚ__name__r•r`ZAnnDatarLÚfloatÚboolrªÚRandomStateÚ	Generatorrhrirkr}ÚndarrayrMr[rZr¦r®rYrOr_rÈrfrfrfrgÚ<module>sÒ

Z Z @D
,=(.