Spaces:
Sleeping
Sleeping
File size: 7,760 Bytes
2999286 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 |
#!/usr/bin/env python # coding: utf-8 # # Inference of MetaCell from Single-Cell RNA-seq # # Metacells are cell groupings derived from single-cell sequencing data that represent highly granular, distinct cell states. Here, we present single-cell aggregation of cell-states (SEACells), an algorithm for identifying metacells; overcoming the sparsity of single-cell data, while retaining heterogeneity obscured by traditional cell clustering. # # Paper: [SEACells: Inference of transcriptional and epigenomic cellular states from single-cell genomics data](https://www.nature.com/articles/s41587-023-01716-9) # # Code: https://github.com/dpeerlab/SEACells # # In[1]: import omicverse as ov import scanpy as sc import scvelo as scv ov.plot_set() # ## Data preprocessed # # We need to normalized and scale the data at first. # In[3]: adata = scv.datasets.pancreas() adata # In[4]: #quantity control adata=ov.pp.qc(adata, tresh={'mito_perc': 0.20, 'nUMIs': 500, 'detected_genes': 250}, mt_startswith='mt-') #normalize and high variable genes (HVGs) calculated adata=ov.pp.preprocess(adata,mode='shiftlog|pearson',n_HVGs=2000,) #save the whole genes and filter the non-HVGs adata.raw = adata adata = adata[:, adata.var.highly_variable_features] #scale the adata.X ov.pp.scale(adata) #Dimensionality Reduction ov.pp.pca(adata,layer='scaled',n_pcs=50) # ## Constructing a metacellular object # # We can use `ov.single.MetaCell` to construct a metacellular object to train the SEACells model, the arguments can be found in below. # # - :param ad: (AnnData) annotated data matrix # - :param build_kernel_on: (str) key corresponding to matrix in ad.obsm which is used to compute kernel for metacells # Typically 'X_pca' for scRNA or 'X_svd' for scATAC # - :param n_SEACells: (int) number of SEACells to compute # - :param use_gpu: (bool) whether to use GPU for computation # - :param verbose: (bool) whether to suppress verbose program logging # - :param n_waypoint_eigs: (int) number of eigenvectors to use for waypoint initialization # - :param n_neighbors: (int) number of nearest neighbors to use for graph construction # - :param convergence_epsilon: (float) convergence threshold for Franke-Wolfe algorithm # - :param l2_penalty: (float) L2 penalty for Franke-Wolfe algorithm # - :param max_franke_wolfe_iters: (int) maximum number of iterations for Franke-Wolfe algorithm # - :param use_sparse: (bool) whether to use sparse matrix operations. Currently only supported for CPU implementation. # In[5]: meta_obj=ov.single.MetaCell(adata,use_rep='scaled|original|X_pca', n_metacells=None, use_gpu='cuda:0') # In[6]: get_ipython().run_cell_magic('time', '', 'meta_obj.initialize_archetypes()\n') # ## Train and save the model # In[7]: get_ipython().run_cell_magic('time', '', 'meta_obj.train(min_iter=10, max_iter=50)\n') # In[9]: meta_obj.save('seacells/model.pkl') # In[6]: meta_obj.load('seacells/model.pkl') # ## Predicted the metacells # # we can use `predicted` to predicted the metacells of raw scRNA-seq data. There are two method can be selected, one is `soft`, the other is `hard`. # # In the `soft` method, Aggregates cells within each SEACell, summing over all raw data x assignment weight for all cells belonging to a SEACell. Data is un-normalized and pseudo-raw aggregated counts are stored in .layers['raw']. Attributes associated with variables (.var) are copied over, but relevant per SEACell attributes must be manually copied, since certain attributes may need to be summed, or averaged etc, depending on the attribute. # # In the `hard` method, Aggregates cells within each SEACell, summing over all raw data for all cells belonging to a SEACell. Data is unnormalized and raw aggregated counts are stored .layers['raw']. Attributes associated with variables (.var) are copied over, but relevant per SEACell attributes must be manually copied, since certain attributes may need to be summed, or averaged etc, depending on the attribute. # In[10]: ad=meta_obj.predicted(method='soft',celltype_label='clusters', summarize_layer='lognorm') # ## Benchmarking # # Benchmarking metrics were computed for each metacell for all combinations of data modality, dataset and method. Cell type purity was used to assess the quality of PBMC metacells. Methods were compared using the Wilcoxon rank-sum test. We note that this test might possibly inflate significance due to the dependency between metacells, but it nonetheless provides an estimate of the direction of difference. Top-performing metacell approaches should have scores that are low on compactness, high on separation and high on cell type purity # In[11]: SEACell_purity = meta_obj.compute_celltype_purity('clusters') separation = meta_obj.separation(use_rep='scaled|original|X_pca',nth_nbr=1) compactness = meta_obj.compactness(use_rep='scaled|original|X_pca') # In[12]: import seaborn as sns import matplotlib.pyplot as plt ov.plot_set() fig, axes = plt.subplots(1,3,figsize=(4,4)) sns.boxplot(data=SEACell_purity, y='clusters_purity',ax=axes[0], color=ov.utils.blue_color[3]) sns.boxplot(data=compactness, y='compactness',ax=axes[1], color=ov.utils.blue_color[4]) sns.boxplot(data=separation, y='separation',ax=axes[2], color=ov.utils.blue_color[4]) plt.tight_layout() plt.suptitle('Evaluate of MetaCells',fontsize=13,y=1.05) for ax in axes: ax.grid(False) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['bottom'].set_visible(True) ax.spines['left'].set_visible(True) # In[13]: import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(4,4)) ov.pl.embedding( meta_obj.adata, basis="X_umap", color=['clusters'], frameon='small', title="Meta cells", #legend_loc='on data', legend_fontsize=14, legend_fontoutline=2, size=10, ax=ax, alpha=0.2, #legend_loc='', add_outline=False, #add_outline=True, outline_color='black', outline_width=1, show=False, #palette=ov.utils.blue_color[:], #legend_fontweight='normal' ) ov.single.plot_metacells(ax,meta_obj.adata,color='#CB3E35', ) # ## Get the raw obs value from adata # # There are times when we compute some floating point type data such as pseudotime on the raw single cell data. We want to get the result of the original data on the metacell, in this case, we can use the `ov.single` function to get it. # # Note that the type parameter supports `str`,`max`,`min`,`mean`. # In[14]: ov.single.get_obs_value(ad,adata,groupby='S_score', type='mean') ad.obs.head() # ## Visualize the MetaCells # In[15]: import scanpy as sc ad.raw=ad.copy() sc.pp.highly_variable_genes(ad, n_top_genes=2000, inplace=True) ad=ad[:,ad.var.highly_variable] # In[16]: ov.pp.scale(ad) ov.pp.pca(ad,layer='scaled',n_pcs=30) ov.pp.neighbors(ad, n_neighbors=15, n_pcs=20, use_rep='scaled|original|X_pca') # In[17]: ov.pp.umap(ad) # We want the metacells to take on the same colours as the original data, a noteworthy fact is that the colours of the original data are stored in the `adata.uns['_colors']` # In[18]: ad.obs['celltype']=ad.obs['celltype'].astype('category') ad.obs['celltype']=ad.obs['celltype'].cat.reorder_categories(adata.obs['clusters'].cat.categories) ad.uns['celltype_colors']=adata.uns['clusters_colors'] # In[19]: ov.pl.embedding(ad, basis='X_umap', color=["celltype","S_score"], frameon='small',cmap='RdBu_r', wspace=0.5) # In[ ]: |