OSCR

Region- and cell type-specific changes in gene expression in the cerebellum after classical fear conditioning.

Code ↔ Paper

17 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

9 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 17 matches
  1. [1] § Methods › Visium spatial transcriptomics analysis › Differential gene expression analysis ↔ Codes/Analysis/spatial_pseudobulk_deseq.R, lines 274 to 347 · score 0.75 · DESeq, independentFiltering, pairwise comparison, LRT DEGs, alpha, HC · block oscr:b:AKDWCRPBYWEH5-D · Report a mismatch
  2. [2] § Methods › snRNA-seq data analysis › Preprocess and annotation ↔ Codes/Analysis/preprocess_annotate_snrna.ipynb, lines 599 to 615 · score 0.72 · Seurat v3, sc.pp.highly_variable_genes, flavor, latent, scVI, batch · Report a mismatch
  3. [3] § Methods › Visium spatial transcriptomics analysis › Spatial transcriptomics mapping and preprocess ↔ Codes/Analysis/preprocess_annotate_snrna.ipynb, lines 599 to 615 · score 0.72 · Seurat v3, sc.pp.highly_variable_genes, flavor, latent, scVI, batch · Report a mismatch
  4. [4] § Methods › Visium spatial transcriptomics analysis › Annotation of spatial clusters ↔ Codes/Analysis/annotation_cell2location.ipynb, lines 277 to 288 · score 0.71 · detection alpha, cell2location, cell abundance, training, model · Report a mismatch
  5. [5] § Results › Specific inhibitory neuron subtype expressing Kit is highly associated with fear conditioning ↔ Codes/Analysis/preprocess_annotate_snrna.ipynb, lines 794 to 801 · score 0.69 · Inh Piezo2, Inh Zfhx4, inhibitory neurons, Inh Kit, snRNA, cells · Report a mismatch
  6. [6] § Results › snRNA-seq in the DCN reveals cell type- and learning phase-specific transcriptional changes ↔ Codes/Figure/Figure5.R, lines 1 to 42 · score 0.66 · snRNA, CD DEGs, LRT DEGs, UMAP, astrocyte, Quadrant · block oscr:b:3AKJXY5RHNPE4-2 · Report a mismatch
  7. [7] § Methods › snRNA-seq data analysis › Transcription factor activity analysis ↔ Codes/Analysis/pySCENIC_downstream.R, lines 1 to 55 · score 0.60 · pySCENIC, motifs, AUC, adjacency, mm10, scores · block oscr:b:QSP6XPVMCQTWJ-7 · Report a mismatch
  8. [8] § Methods › Visium spatial transcriptomics analysis › Spatial transcriptomics mapping and preprocess ↔ Codes/Analysis/spatialclustering_squidpy.ipynb, lines 55 to 59 · score 0.60 · joint graph, Squidpy, space, resolution, Leiden, sc · Report a mismatch
  9. [9] § Results › Specific inhibitory neuron subtype expressing Kit is highly associated with fear conditioning ↔ Codes/Analysis/snrna_MAST.R, lines 1584 to 1642 · score 0.59 · Inh Piezo2, Inh Zfhx4, Inh Kit, snRNA, DEGs, DCN · block oscr:b:XHYC7TXYN2F4Z-Z · Report a mismatch
  10. [10] § Methods › snRNA-seq data analysis › Differential gene expression analysis ↔ Codes/Analysis/snrna_MAST.R, lines 928 to 996 · score 0.59 · pairwise comparison, log2FC, MAST, zlm, Hurdle, LRT · block oscr:b:0JD4Y3T09BG9E-2 · Report a mismatch
  11. [11] § Results › Specific inhibitory neuron subtype expressing Kit is highly associated with fear conditioning ↔ Codes/Analysis/preprocess_annotate_snrna.ipynb, lines 794 to 801 · score 0.57 · Inh Zfhx4, inhibitory neurons, Inh Kit, neuronal, cells · Report a mismatch
  12. [12] § Results › Specific inhibitory neuron subtype expressing Kit is highly associated with fear conditioning ↔ Codes/Figure/Figure6.R, lines 1 to 41 · score 0.56 · inhibitory neuron, Inh Kit, UMAP, Quadrant, Zfhx4, Grm5 · block oscr:b:JJK12T1DK4JQM-7 · Report a mismatch
  13. [13] § Results › Spatial transcriptomic analysis in the cerebellum after classical fear conditioning ↔ Codes/Figure/Figure2.R, lines 43 to 111 · score 0.56 · granular layer, molecular layer, ventricle, medulla, Purkinje, seq · block oscr:b:7HHZXKGSDZA17-M · Report a mismatch
  14. [14] § Results › Spatial transcriptomic analysis in the cerebellum after classical fear conditioning ↔ Codes/Analysis/spatial_pseudobulk_deseq.R, lines 274 to 347 · score 0.55 · granular layer, molecular layer, ventricle, medulla, Purkinje, seq · block oscr:b:AKDWCRPBYWEH5-D · Report a mismatch
  15. [15] § Methods › snRNA-seq data analysis › Transcription factor activity analysis ↔ Codes/Analysis/pySCENIC_downstream.R, lines 160 to 207 · score 0.54 · regulon activity, Bonferroni, RAS, scores, TF, cell · block oscr:b:28VAAREX2HC9W-T · Report a mismatch
  16. [16] § Results › Specific inhibitory neuron subtype expressing Kit is highly associated with fear conditioning ↔ Codes/Figure/Figure6.R, lines 1 to 41 · score 0.54 · inhibitory neurons, Inh Kit, Zfhx4, Grm5, regulator, neuronal · block oscr:b:JJK12T1DK4JQM-7 · Report a mismatch
  17. [17] § Methods › Visium spatial transcriptomics analysis › Differential gene expression analysis ↔ Codes/Analysis/spatial_pseudobulk_deseq.R, lines 65 to 84 · score 0.53 · mitochondrial genes, DESeq2, summing, subsets, cell · block oscr:b:YKZAZJWPHEX72-N · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 970 lines · 31 KB · CC-BY-4.0 · 4 matches

  1. # %%
  2. import gc
  3. import pandas as pd
  4. import numpy as np
  5. import scanpy as sc
  6. import anndata as ad
  7. import scvi
  8. import torch
  9. import anndata
  10. import copy
  11. from rich import print
  12. from scib_metrics.benchmark import Benchmarker
  13. from scvi.model.utils import mde
  14. from scvi_colab import install
  15. #import scrublet as scr
  16. import matplotlib.pyplot as plt
  17. import random
  18. import matplotlib as mpl
  19. import seaborn as sns
  20. # Set font
  21. mpl.rcParams['pdf.fonttype'] = 42
  22. mpl.rcParams['font.family'] = ['Arial']
  23. # Check torch
  24. torch.cuda.is_available()
  25. # %%
  26. scvi.settings.seed = 2023
  27. # %%
  28. import os
  29. os.chdir('/data1/Spatial_DCN/')
  30. # %%
  31. import gc
  32. # %%
  33. # set seed for randomness
  34. torch.manual_seed(2023)
  35. random.seed(2023)
  36. np.random.seed(2023)
  37. torch.backends.cudnn.deterministic = True
  38. torch.backends.cudnn.benchmark = False
  39. # %%
  40. # plot settings
  41. title_fs = 16
  42. axis_label_fs = 14
  43. axis_tick_fs = 12
  44. legend_fs = 10
  45. # %% [markdown]
  46. # # Import raw data
  47. # %%
  48. adata_hc = sc.read_h5ad('Resources/snRNA_samples/HC/HC_matrix/HC_matrix.h5ad')
  49. adata_cd = sc.read_h5ad('Resources/snRNA_samples/FC/FC_matrix/FC_matrix.h5ad')
  50. adata_tn = sc.read_h5ad('Resources/snRNA_samples/TN/TN_matrix/TN_matrix.h5ad')
  51. # %%
  52. # set same name as Visium
  53. adata_cd.obs['sample'] = 'CD'
  54. # %%
  55. adata_lst = [adata_hc, adata_cd, adata_tn]
  56. # %%
  57. samp_lst = ['HC', 'CD', 'TN']
  58. # %%
  59. for ad in adata_lst:
  60. ad.var_names = ad.var['gene_symbols'].astype(str)
  61. # %%
  62. for adata in adata_lst:
  63. adata.var_names_make_unique()
  64. # %%
  65. for i in range(3):
  66. print(f"Number of spots/genes for {samp_lst[i]} sample: {len(adata_lst[i].obs)}/{len(adata_lst[i].var)}")
  67. # %% [markdown]
  68. # # Doublet detection
  69. # %%
  70. hc_cnt = pd.DataFrame(data=adata_hc.X.toarray(), index=adata_hc.obs_names, columns=adata_hc.var_names)
  71. cd_cnt = pd.DataFrame(data=adata_cd.X.toarray(), index=adata_cd.obs_names, columns=adata_cd.var_names)
  72. tn_cnt = pd.DataFrame(data=adata_tn.X.toarray(), index=adata_tn.obs_names, columns=adata_tn.var_names)
  73. # %%
  74. hc_scrub = scr.Scrublet(hc_cnt, expected_doublet_rate= 0.008 * 7.6)
  75. cd_scrub = scr.Scrublet(cd_cnt, expected_doublet_rate= 0.008 * 10.8)
  76. tn_scrub = scr.Scrublet(tn_cnt, expected_doublet_rate= 0.008 * 7.9)
  77. # %%
  78. hc_db_scr, hc_db_pred = hc_scrub.scrub_doublets()
  79. cd_db_scr, cd_db_pred = cd_scrub.scrub_doublets()
  80. tn_db_scr, tn_db_pred = tn_scrub.scrub_doublets()
  81. # %%
  82. db_scr_lst = [hc_db_scr, cd_db_scr, tn_db_scr]
  83. db_pred_lst = [hc_db_pred, cd_db_pred, tn_db_pred]
  84. # %%
  85. for i in range(3):
  86. adata_lst[i].obs['doublet_score'] = db_scr_lst[i]
  87. adata_lst[i].obs['doublet_prediction'] = db_pred_lst[i]
  88. # %%
  89. for adata in adata_lst:
  90. print(len(adata[adata.obs['doublet_prediction'] == True].obs_names))
  91. # %%
  92. for i in range(3):
  93. adata_lst[i] = adata_lst[i][adata_lst[i].obs['doublet_prediction'] == False]
  94. print(f"Number of spots/genes for {samp_lst[i]} sample: {len(adata_lst[i].obs)}/{len(adata_lst[i].var)}")
  95. # %% [markdown]
  96. # # QC
  97. # %%
  98. # Basic filtering
  99. for adata in adata_lst:
  100. sc.pp.filter_genes(adata, min_cells= 3)
  101. for i in range(3):
  102. print(f"Number of spots/genes for {samp_lst[i]} sample: {len(adata_lst[i].obs)}/{len(adata_lst[i].var)}")
  103. # %%
  104. for adata in adata_lst:
  105. adata.var['mt'] = adata.var_names.str.startswith('mt-')
  106. sc.pp.calculate_qc_metrics(adata, qc_vars=['mt'], percent_top=None, log1p=False, inplace=True)
  107. # %%
  108. qc_lst = ['total_counts', 'n_genes_by_counts', 'pct_counts_mt']
  109. # %%
  110. concat_data = sc.concat(
  111. adata_lst,
  112. label="sample",
  113. keys=['HC', 'CD', 'TN'],
  114. index_unique="-",
  115. join = 'outer'
  116. )
  117. # %%
  118. # Plot QC parameters before QC
  119. fig, axes = plt.subplots(nrows = 3, ncols = 1, figsize= (14,10))
  120. for i in range(3):
  121. ax = sc.pl.violin(concat_data, keys = qc_lst[i], jitter = 0.4, show = False, groupby = 'sample', xlabel = None, size = 1, ylabel = '', ax= axes[i])
  122. ax.spines['right'].set_visible(False)
  123. ax.spines['top'].set_visible(False)
  124. ax.tick_params(axis='both', which='major', labelsize= axis_tick_fs)
  125. ax.grid(False)
  126. ax.set_title(f'{qc_lst[i]}', fontsize = title_fs)
  127. plt.subplots_adjust(hspace = 0.4)
  128. plt.savefig('Figures/20231019_res/vlnplot_beforeqc_aftrdbremove_allqcmetrics_3snrna_20231104.pdf', bbox_inches = 'tight')
  129. # %%
  130. # Spot filtering
  131. max_gene = 8000
  132. min_gene = 200
  133. max_count = 60000
  134. max_mito = 20
  135. for adata in adata_lst:
  136. sc.pp.filter_cells(adata, max_counts=max_count)
  137. sc.pp.filter_cells(adata, min_genes= min_gene)
  138. sc.pp.filter_cells(adata, max_genes= max_gene)
  139. for i in range(3):
  140. adata = adata_lst[i]
  141. adata = adata[adata.obs['pct_counts_mt'] < max_mito, ~(adata.var_names == "Gm42418")]
  142. adata_lst[i] = adata
  143. for i in range(3):
  144. print(f"Number of spots/genes for {samp_lst[i]} sample: {len(adata_lst[i].obs)}/{len(adata_lst[i].var)}")
  145. # %%
  146. concat_data = sc.concat(
  147. adata_lst,
  148. label="sample",
  149. keys=['HC', 'CD', 'TN'],
  150. index_unique="-",
  151. join = 'outer'
  152. )
  153. concat_data
  154. # 24735 spots, 23362 genes
  155. # 24303 spots, 23267 genes
  156. # %%
  157. # Plot QC parameters before QC
  158. fig, axes = plt.subplots(nrows = 3, ncols = 1, figsize= (14,10))
  159. for i in range(3):
  160. ax = sc.pl.violin(concat_data, keys = qc_lst[i], jitter = 0.4, show = False, groupby = 'sample', xlabel = None, size = 1, ylabel = '', ax= axes[i])
  161. ax.spines['right'].set_visible(False)
  162. ax.spines['top'].set_visible(False)
  163. ax.tick_params(axis='both', which='major', labelsize= axis_tick_fs)
  164. ax.grid(False)
  165. ax.set_title(f'{qc_lst[i]}', fontsize = title_fs)
  166. plt.subplots_adjust(hspace = 0.4)
  167. plt.savefig('Figures/20231019_res/vlnplot_afterqc_aftrdbremove_allqcmetrics_3snrna_20231104.pdf', bbox_inches = 'tight')
  168. # %%
  169. # save raw count
  170. concat_data.write_h5ad('Tables/Data/snrna_dcn_3samples_int_afterdoubletrm_rawcount_outerjoin_20231104.h5ad')
  171. # %%
  172. #concat_data = sc.read_h5ad('Tables/Tables/h5ad_data/snrna_dcn_3samples_int_afterdoubletrm_rawcount_outerjoin_20230831.h5ad')
  173. # %%
  174. concat_data.layers["counts"] = concat_data.X.copy()
  175. # %% [markdown]
  176. # # Normalize data
  177. # %%
  178. sc.pp.normalize_total(concat_data)
  179. sc.pp.log1p(concat_data)
  180. # %%
  181. concat_data.raw = concat_data
  182. # %% [markdown]
  183. # # SCVI analysis
  184. # %%
  185. # Selecting highly variable genes
  186. sc.pp.highly_variable_genes(
  187. concat_data,
  188. flavor="seurat_v3",
  189. n_top_genes=2000,
  190. layer="counts",
  191. batch_key="sample",
  192. subset=True,
  193. )
  194. # %%
  195. TF_CPP_MIN_LOG_LEVEL=0
  196. # %%
  197. scvi.model.SCVI.setup_anndata(concat_data, layer="counts", batch_key="sample")
  198. # %%
  199. vae = scvi.model.SCVI(concat_data, n_layers=2, n_latent=30, gene_likelihood="nb")
  200. vae.train()
  201. # %%
  202. SCVI_LATENT_KEY = "X_scVI"
  203. concat_data.obsm[SCVI_LATENT_KEY] = vae.get_latent_representation()
  204. # %%
  205. # Clustering
  206. sc.pp.neighbors(concat_data, use_rep="X_scVI")
  207. # %%
  208. sc.tl.leiden(concat_data, resolution = 0.3, key_added = 'leiden_0.3')
  209. sc.tl.leiden(concat_data, resolution = 0.4, key_added = 'leiden_0.4')
  210. sc.tl.leiden(concat_data, resolution = 0.5, key_added = 'leiden_0.5')
  211. sc.tl.leiden(concat_data, resolution = 0.6, key_added = 'leiden_0.6')
  212. sc.tl.leiden(concat_data, resolution = 0.7, key_added = 'leiden_0.7')
  213. sc.tl.leiden(concat_data, resolution = 0.8, key_added = 'leiden_0.8')
  214. sc.tl.leiden(concat_data, resolution = 0.9, key_added = 'leiden_0.9')
  215. sc.tl.leiden(concat_data, resolution = 1, key_added = 'leiden_1.0')
  216. sc.tl.leiden(concat_data, resolution = 1.1, key_added = 'leiden_1.1')
  217. sc.tl.leiden(concat_data, resolution = 1.2, key_added = 'leiden_1.2')
  218. sc.tl.leiden(concat_data, resolution = 1.3, key_added = 'leiden_1.3')
  219. sc.tl.leiden(concat_data, resolution = 1.4, key_added = 'leiden_1.4')
  220. sc.tl.leiden(concat_data, resolution = 1.5, key_added = 'leiden_1.5')
  221. # %%
  222. sc.tl.umap(concat_data)
  223. # %% [markdown]
  224. # ## Plotting
  225. # %% [markdown]
  226. # ### Plot doublet prediction
  227. # This process is conducted after doublet detection, and before removing doublet.
  228. # %%
  229. concat_data.obs['doublet_prediction'] = concat_data.obs['doublet_prediction'].astype('category')
  230. # %%
  231. concat_data[concat_data.obs['doublet_prediction'] == False].obs.value_counts('sample')
  232. # %%
  233. # Check doublet
  234. mpl.rcParams['figure.figsize'] = (7,6)
  235. ax = sc.pl.umap(concat_data, color = ['doublet_prediction'], show = False,legend_fontsize = legend_fs, size = 10, sort_order = False)
  236. ax.title.set_fontsize(title_fs)
  237. ax.xaxis.label.set_fontsize(axis_label_fs)
  238. ax.yaxis.label.set_fontsize(axis_label_fs)
  239. plt.savefig('Figures/20231019_res/umap_snrna_3samples_sample_doubletprediction_outerjoin_20231104.pdf', bbox_inches = 'tight')
  240. # %% [markdown]
  241. # ### Plotting UMAP
  242. # %%
  243. mpl.rcParams['figure.figsize'] = (5,5)
  244. ax = sc.pl.umap(concat_data, color = ['leiden_0.4','leiden_0.5', 'leiden_0.6', 'leiden_0.7', 'leiden_0.8', 'leiden_0.9', 'leiden_1.0',], ncols = 3, show = False, legend_fontsize = legend_fs, size = 10, sort_order = False,
  245. legend_loc = 'on data')
  246. for sp in ax:
  247. sp.title.set_fontsize(title_fs)
  248. sp.xaxis.label.set_fontsize(axis_label_fs)
  249. sp.yaxis.label.set_fontsize(axis_label_fs)
  250. #plt.savefig('Figures/20230827_res/umap_snrna_3samples_rmdoublets_sample_leiden_multirestest_outerjoin_20230831.pdf', bbox_inches = 'tight')
  251. # %%
  252. concat_data.obs['leiden'] = concat_data.obs['leiden_1.0'].astype('category')
  253. # %%
  254. mpl.rcParams['figure.figsize'] = (5.2,5)
  255. ax = sc.pl.umap(concat_data, color = ['leiden'], show = False, legend_fontsize = legend_fs, size = 10, sort_order = False,
  256. wspace = 0.25, legend_loc = 'on data')
  257. ax.title.set_fontsize(title_fs)
  258. ax.xaxis.label.set_fontsize(axis_label_fs)
  259. ax.yaxis.label.set_fontsize(axis_label_fs)
  260. plt.savefig('Figures/20231019_res/umap_snrna_3samples_leiden1.0_20231104.pdf', bbox_inches = 'tight')
  261. # %%
  262. pd.crosstab(concat_data.obs['leiden'], concat_data.obs['sample'])
  263. # %%
  264. # violin plot of QC metrics for each leiden cluster
  265. fig, axes = plt.subplots(nrows = 3, ncols = 1, figsize= (14,10))
  266. for i in range(3):
  267. ax = sc.pl.violin(concat_data, keys = qc_lst[i], jitter = 0.4, show = False, groupby = 'leiden', xlabel = None, size = 1, ylabel = '', ax= axes[i])
  268. ax.spines['right'].set_visible(False)
  269. ax.spines['top'].set_visible(False)
  270. ax.tick_params(axis='both', which='major', labelsize= axis_tick_fs)
  271. ax.grid(False)
  272. ax.set_title(f'{qc_lst[i]}', fontsize = title_fs)
  273. plt.subplots_adjust(hspace = 0.4)
  274. plt.savefig('Figures/20231019_res/vlnplot_allqcmetrics_byleiden_res0.8_3snrna_20231104.pdf', bbox_inches = 'tight')
  275. # %%
  276. # plot UMAP based on QC metrics
  277. mpl.rcParams['figure.figsize'] = (5,5)
  278. ax = sc.pl.umap(concat_data, color = qc_lst, size = 15, show = False, legend_fontsize= legend_fs,legend_loc = 'on data')
  279. for sp in ax:
  280. sp.title.set_fontsize(title_fs)
  281. sp.xaxis.label.set_fontsize(axis_label_fs)
  282. sp.yaxis.label.set_fontsize(axis_label_fs)
  283. plt.savefig('Figures/20231019_res/umap_leiden_qccriteria_res1.0_20231104.pdf', bbox_inches= 'tight')
  284. # %%
  285. # Plot each samples individually
  286. fig, axs = plt.subplots(ncols = 3, nrows = 1, figsize = (12,3.5))
  287. sc.pl.umap(concat_data[concat_data.obs['sample'] == 'HC',], color="leiden_1.0", size = 10,legend_loc= None,
  288. title = 'HC', show = False, ax = axs[0])
  289. sc.pl.umap(concat_data[concat_data.obs['sample'] == 'CD',], color="leiden_1.0", size = 10,legend_loc= None,
  290. title = 'CD', show = False, ax = axs[1])
  291. sc.pl.umap(concat_data[concat_data.obs['sample'] == 'TN',], color="leiden_1.0", size = 10,legend_loc= None,
  292. title = 'TN', show = False, ax = axs[2])
  293. for subplot in axs:
  294. subplot.set_xlabel(subplot.get_xlabel(), fontsize= axis_label_fs)
  295. subplot.set_ylabel(subplot.get_ylabel(), fontsize= axis_label_fs)
  296. subplot.set_title(subplot.get_title(), fontsize = title_fs)
  297. plt.savefig("Figures/20231019_res/umap_3samples_snrna_rmdoublets_scviclusters_splitsample_outerjoin_20231104.pdf", bbox_inches = 'tight')
  298. # %%
  299. concat_data.obs['leiden'].value_counts()
  300. # %%
  301. # remove cluster 26 due to low nuclei count
  302. concat_data = concat_data[~(concat_data.obs['leiden'] == '26')].copy()
  303. # %%
  304. # export data
  305. concat_data.write_h5ad('Tables/Data/snrna_dcn_3samples_rmdoublet_intscvi_res1.0_20231104.h5ad')
  306. # %%
  307. #concat_data = sc.read_h5ad('Tables/Data/snrna_dcn_3samples_rmdoublet_intscvi_res1.0_20231104.h5ad')
  308. # %% [markdown]
  309. # # Find markers of each cluster (for annotation)
  310. # %%
  311. concat_data = concat_data.raw.to_adata()
  312. # %%
  313. concat_data
  314. # 24303 cells, 23267 genes
  315. # %%
  316. raw_adata = sc.read_h5ad('Tables/Data/snrna_dcn_3samples_int_afterdoubletrm_rawcount_outerjoin_20231104.h5ad')
  317. # %%
  318. concat_data.layers['counts'] = raw_adata.X.copy()
  319. # %%
  320. sc.tl.rank_genes_groups(concat_data, groupby = 'leiden', pts = True, method = 'wilcoxon')
  321. # %%
  322. markers_df = sc.get.rank_genes_groups_df(concat_data, group = None)
  323. # %%
  324. markers_df.to_csv('Tables/snrna_3samples_resolution1.0_markergenes_df_testwilcox_20231116.csv')
  325. # %% [markdown]
  326. # # Annotation using marker genes
  327. # %%
  328. concat_data.obs['cell_type'] = ''
  329. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['0','1','6','15'])] = 'Oligodendrocyte'
  330. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['2','4', '24'])] = 'Granule_cell'
  331. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['3','8'])] = 'Astrocyte'
  332. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['5','9', '14', '19', '20', '23'])] = 'Inh_DCN'
  333. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['7', '12'])] = 'Exc_DCN'
  334. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['10'])] = 'OPC'
  335. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['11'])] = 'Microglia'
  336. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['13','22'])] = 'Vascular_cell'
  337. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['16'])] = 'Ependymal_cell'
  338. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['17'])] = 'Bergmanns_glia'
  339. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['18'])] = 'Endothelial_cell'
  340. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['21'])] = 'UBC'
  341. #concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['24'])] = 'Granule_cell_TN'
  342. concat_data.obs['cell_type'][concat_data.obs['leiden'].isin(['25'])] = 'Purkinje'
  343. # %%
  344. concat_data.obs['cell_type'] = concat_data.obs['cell_type'].astype('category')
  345. # %%
  346. concat_data.obs['cell_type'].value_counts()
  347. # %%
  348. concat_data.write_h5ad('Tables/Data/snrna_dcn_3samples_rmdoublet_res1.0_afterannot_20231104.h5ad')
  349. # %%
  350. concat_data = sc.read_h5ad('Tables/Data/snrna_dcn_3samples_rmdoublet_res1.0_afterannot_20231104.h5ad')
  351. # %%
  352. concat_data.X = concat_data.layers['counts'].copy()
  353. concat_data.write_h5ad('Tables/Data/snrna_dcn_3samples_res1.0_afterannot_rawcnts_20240214.h5ad')
  354. # %%
  355. cnt_data = sc.read_h5ad('Tables/Data/snrna_dcn_3samples_res1.0_afterannot_rawcnts_20240214.h5ad')
  356. # %%
  357. cnt_data.obs.to_csv('Tables/Data/snrna_metadata.csv')
  358. # %%
  359. df = pd.DataFrame(cnt_data.X.toarray(), index=cnt_data.obs_names, columns=cnt_data.var_names)
  360. # Save the DataFrame to a CSV file
  361. df.to_csv('Tables/Data/snrna_onlycnt_mtx.csv')
  362. # %%
  363. mpl.rcParams['figure.figsize'] = (6.5,5.5)
  364. ax = sc.pl.umap(concat_data, color = ['leiden','cell_type'], size = 15, show = False, legend_fontsize= legend_fs,legend_loc = 'on data')
  365. for sp in ax:
  366. sp.title.set_fontsize(title_fs)
  367. sp.xaxis.label.set_fontsize(axis_label_fs)
  368. sp.yaxis.label.set_fontsize(axis_label_fs)
  369. plt.savefig('Figures/20231019_res/umap_leiden_celltype_colors_res1.0_20231104.pdf', bbox_inches= 'tight')
  370. # %%
  371. mpl.rcParams['figure.figsize'] = (6.5,5.5)
  372. ax = sc.pl.umap(concat_data, color = ['leiden','cell_type'], size = 15, show = False, legend_fontsize= legend_fs,legend_loc = 'on data')
  373. for sp in ax:
  374. sp.title.set_fontsize(title_fs)
  375. sp.xaxis.label.set_fontsize(axis_label_fs)
  376. sp.yaxis.label.set_fontsize(axis_label_fs)
  377. plt.savefig('Figures/20240604_res/umap_leiden_celltype_colors_res1.0_20240714.pdf', bbox_inches= 'tight')
  378. # %% [markdown]
  379. # ## Check marker genes of cell types
  380. # %%
  381. concat_data
  382. # %%
  383. hc_data = concat_data[concat_data.obs['sample'] == 'HC'].copy()
  384. hc_data
  385. # %%
  386. concat_data.uns['cell_type_colors']
  387. # %%
  388. hc_data.uns['cell_type_colors']
  389. # %%
  390. np.max(hc_data.X)
  391. # %%
  392. plt.rcParams['figure.figsize'] = (10,4.5)
  393. sc.pl.violin(hc_data, keys=['Eef1a2'], groupby='cell_type',
  394. #palette = ['#1f77b4', '#aa40fc', '#e377c2', '#b5bd61','#17becf', '#aec7e8'],
  395. show = False)
  396. plt.title('Eef1a2 expression in homecage (baseline)', size = title_fs)
  397. plt.gca().xaxis.label.set_fontsize(axis_label_fs)
  398. plt.gca().yaxis.label.set_fontsize(axis_label_fs)
  399. plt.tick_params(axis='both', which='major', labelsize= axis_tick_fs)
  400. plt.xticks(rotation = 15)
  401. plt.savefig('Figures/20240604_res/vlnplot_hc_eef1a2_expr_percelltype_all_20240715.pdf', bbox_inches = 'tight')
  402. # %%
  403. sc.tl.rank_genes_groups(hc_data, groupby = 'cell_type', pts = True, method = 'wilcoxon', key_added = 'celltype_markers')
  404. markers_df_hc = sc.get.rank_genes_groups_df(hc_data, group = None, key = 'celltype_markers')
  405. # %%
  406. markers_df.to_csv('Tables/snrna_3samples_celltype_markergenes_df_testwilcox_20231104.csv')
  407. # %%
  408. concat_data.obs['cell_type'] = pd.Categorical(concat_data.obs['cell_type'], categories = ['Astrocyte', 'Bergmanns_glia', 'Endothelial_cell', 'Ependymal_cell',
  409. 'Granule_cell', 'Granule_cell_TN', 'Exc_DCN', 'Inh_DCN','Microglia',
  410. 'OPC', 'Oligodendrocyte','Purkinje', 'UBC', 'Vascular_cell'], ordered = True)
  411. # %%
  412. sc.pl.stacked_violin(concat_data, groupby = 'cell_type', var_names = ['Aldoc', 'Gdf10', 'Cldn5', 'Foxj1', 'Gabra6', 'Slc17a6', 'Gad2', 'Tmem119', 'Pdgfra','Plp1', 'Pcp2',
  413. 'Eomes', 'Vtn'], swap_axes = True, show = False,figsize = (10,10),
  414. save = 'celltype_markers_20231104.pdf'
  415. )
  416. # %%
  417. markers_df_hc[(markers_df_hc['names'] == 'Eef1a2')].sort_values('logfoldchanges', ascending = False)
  418. # %%
  419. pd.crosstab(concat_data.obs['sample'], concat_data.obs['cell_type'])
  420. # %% [markdown]
  421. # # Subset and reclustering of DCN inhibitory neurons
  422. # %%
  423. concat_data = sc.read_h5ad('Tables/Data/snrna_dcn_3samples_rmdoublet_res1.0_afterannot_20231104.h5ad')
  424. # %%
  425. adata_inh = concat_data[concat_data.obs['cell_type'].isin(['Inh_DCN'])].copy()
  426. # %%
  427. adata_inh.X = adata_inh.layers['counts'].copy()
  428. # %%
  429. adata_inh
  430. # 2032 cells, 23267 genes
  431. # %% [markdown]
  432. # ## QC
  433. # %%
  434. inh_lst = []
  435. for samp in samp_lst:
  436. adata = adata_inh[adata_inh.obs['sample'] == samp].copy()
  437. inh_lst.append(adata)
  438. # %%
  439. for adata in inh_lst:
  440. sc.pp.filter_genes(adata, min_cells = 3)
  441. # %%
  442. inh_lst
  443. # %%
  444. adata_inh = sc.concat(
  445. inh_lst,
  446. join = 'outer'
  447. )
  448. # %%
  449. adata_inh
  450. # 2032 nuclei, 18842 genes
  451. # %% [markdown]
  452. # ## Normalize
  453. # %%
  454. sc.pp.normalize_total(adata_inh)
  455. sc.pp.log1p(adata_inh)
  456. adata_inh.raw = adata_inh
  457. # %% [markdown]
  458. # ## Run SCVI
  459. # %%
  460. # Selecting highly variable genes
  461. sc.pp.highly_variable_genes(
  462. adata_inh,
  463. flavor="seurat_v3",
  464. n_top_genes=2000,
  465. layer="counts",
  466. batch_key="sample",
  467. subset=True,
  468. )
  469. TF_CPP_MIN_LOG_LEVEL=0
  470. scvi.model.SCVI.setup_anndata(adata_inh, layer="counts", batch_key="sample")
  471. vae_dcn = scvi.model.SCVI(adata_inh, n_layers=2, n_latent=30, gene_likelihood="nb")
  472. vae_dcn.train()
  473. # %%
  474. SCVI_LATENT_KEY = "X_scVI"
  475. adata_inh.obsm[SCVI_LATENT_KEY] = vae_dcn.get_latent_representation()
  476. # %%
  477. # Clustering
  478. sc.pp.neighbors(adata_inh, use_rep="X_scVI", n_pcs = 20)
  479. # %%
  480. sc.tl.umap(adata_inh)
  481. # %%
  482. sc.tl.leiden(adata_inh, resolution = 0.3, key_added = 'leiden_0.3')
  483. sc.tl.leiden(adata_inh, resolution = 0.4, key_added = 'leiden_0.4')
  484. sc.tl.leiden(adata_inh, resolution = 0.5, key_added = 'leiden_0.5')
  485. sc.tl.leiden(adata_inh, resolution = 0.6, key_added = 'leiden_0.6')
  486. sc.tl.leiden(adata_inh, resolution = 0.7, key_added = 'leiden_0.7')
  487. sc.tl.leiden(adata_inh, resolution = 0.8, key_added = 'leiden_0.8')
  488. sc.tl.leiden(adata_inh, resolution = 0.9, key_added = 'leiden_0.9')
  489. sc.tl.leiden(adata_inh, resolution = 1, key_added = 'leiden_1.0')
  490. sc.tl.leiden(adata_inh, resolution = 1.1, key_added = 'leiden_1.1')
  491. sc.tl.leiden(adata_inh, resolution = 1.2, key_added = 'leiden_1.2')
  492. sc.tl.leiden(adata_inh, resolution = 1.3, key_added = 'leiden_1.3')
  493. sc.tl.leiden(adata_inh, resolution = 1.4, key_added = 'leiden_1.4')
  494. sc.tl.leiden(adata_inh, resolution = 1.5, key_added = 'leiden_1.5')
  495. sc.tl.leiden(adata_inh, resolution = 1.6, key_added = 'leiden_1.6')
  496. sc.tl.leiden(adata_inh, resolution = 1.7, key_added = 'leiden_1.7')
  497. sc.tl.leiden(adata_inh, resolution = 1.8, key_added = 'leiden_1.8')
  498. sc.tl.leiden(adata_inh, resolution = 1.9, key_added = 'leiden_1.9')
  499. sc.tl.leiden(adata_inh, resolution = 2.0, key_added = 'leiden_2.0')
  500. # %%
  501. sc.pl.umap(adata_inh, color = 'leiden_1.0')
  502. # %%
  503. plt.rcParams['figure.figsize'] = (12,8)
  504. sc.pl.umap(adata_inh, color=["leiden_0.3", "leiden_0.5", "leiden_0.6", "leiden_0.7", 'leiden_1.4'], size = 60,ncols = 3, legend_fontsize = legend_fs, show = False,
  505. wspace = 0.2)
  506. # %%
  507. sc.pl.dendrogram(adata_inh, groupby = 'leiden_0.3')
  508. # %%
  509. adata_inh.write_h5ad('Tables/Data/snrna_subsetdcn_afterqc_scvi_20231104.h5ad')
  510. # %%
  511. #adata_inh = sc.read_h5ad('Tables/Data/snrna_subsetdcn_afterqc_scvi_20231104.h5ad')
  512. # %%
  513. adata_inh.X = adata_inh.layers['counts'].copy()
  514. # %% [markdown]
  515. # ## Annotating clusters using SCANVI
  516. # %%
  517. adata_inh
  518. # %%
  519. adata_inh = adata_inh.raw.to_adata()
  520. # %%
  521. adata_raw = sc.read_h5ad('Tables/Data/snrna_dcn_3samples_int_afterdoubletrm_rawcount_outerjoin_20231104.h5ad')
  522. adata_raw_inh = adata_raw[adata_inh.obs_names,adata_inh.var_names]
  523. # %%
  524. adata_inh.layers['counts'] = adata_raw_inh.X.copy()
  525. adata_inh.layers['log1p'] = adata_inh.X.copy()
  526. adata_inh.X = adata_inh.layers['counts'].copy()
  527. # %% [markdown]
  528. # Reference: Kebschull et al., 2021
  529. # %%
  530. # Train reference
  531. adata_ref = sc.read_h5ad('/data1/Spatial_DCN/Resources/kebschull_dcn_rawcounts_anndata.h5ad')
  532. adata_ref
  533. # 4605 cells, 53797 genes
  534. # %%
  535. adata_ref = adata_ref[adata_ref.obs['final.clusters2'].str.contains('Inh')].copy()
  536. adata_ref
  537. # 2363 cells, 53797 genes
  538. # %%
  539. adata_ref.layers['counts'] = adata_ref.X.copy()
  540. # %%
  541. # Match sample column name to reference
  542. adata_inh.obs['orig.ident'] = adata_inh.obs['sample']
  543. # %%
  544. # concatenate dataset with reference
  545. merged_data = adata_inh.concatenate(adata_ref)
  546. # %%
  547. merged_data
  548. # 4395 cells, 18020 genes
  549. # %% [markdown]
  550. # ### Run SCVI on reference merged dataset
  551. # %%
  552. merged_data.layers['counts'] = merged_data.X.copy()
  553. sc.pp.normalize_total(merged_data, target_sum = 1e4)
  554. sc.pp.log1p(merged_data)
  555. merged_data.raw = merged_data
  556. sc.pp.highly_variable_genes(
  557. merged_data, n_top_genes=3000, batch_key="orig.ident", subset=True, layer = 'counts', flavor = 'seurat_v3'
  558. )
  559. # %%
  560. TF_CPP_MIN_LOG_LEVEL=0
  561. # %%
  562. scvi.model.SCVI.setup_anndata(merged_data, batch_key="orig.ident", layer="counts", categorical_covariate_keys= ['batch'])
  563. # %%
  564. vae = scvi.model.SCVI(merged_data)
  565. vae.train()
  566. # %%
  567. # set reference column to project
  568. merged_data.obs['final.clusters2'] = merged_data.obs['final.clusters2'].cat.add_categories('Unknown')
  569. merged_data.obs = merged_data.obs.fillna(value = {'final.clusters2': 'Unknown'})
  570. # %% [markdown]
  571. # ### train SCANVI
  572. # %%
  573. lvae = scvi.model.SCANVI.from_scvi_model(vae, adata = merged_data, unlabeled_category = 'Unknown',labels_key = 'final.clusters2')
  574. lvae.train(max_epochs = 20, n_samples_per_label = 100)
  575. # %%
  576. merged_data.obs['SCANVI_prediction'] = lvae.predict(merged_data)
  577. # %%
  578. merged_data.obs['bc2'] = merged_data.obs.index.map(lambda x: x[:-2])
  579. cell_mapper = dict(zip(merged_data.obs.bc2, merged_data.obs.SCANVI_prediction))
  580. adata_inh.obs['SCANVI_predicted'] = adata_inh.obs.index.map(cell_mapper)
  581. # %%
  582. sc.pl.dendrogram(adata_inh, groupby = 'leiden_0.3')
  583. # %%
  584. # Clustering
  585. #mpl.rcParams['figure.figsize'] = (5.5,5)
  586. sc.pl.umap(adata_inh, color = ['leiden_0.5','SCANVI_predicted'], wspace = 0.35)
  587. # %% [markdown]
  588. # ## Find markers of DCN neuronal celltypes
  589. # %%
  590. sc.tl.rank_genes_groups(adata_inh, groupby = 'leiden_0.3', pts = True, method = 'wilcoxon', key_added='leiden_0.3_markers')
  591. markers_df = sc.get.rank_genes_groups_df(adata_inh, group = None, key='leiden_0.3_markers')
  592. # %%
  593. sc.tl.rank_genes_groups(adata_inh, groupby = 'neuronal_celltype', pts = True, method = 'wilcoxon', key_added='celltype_markers')
  594. markers_df = sc.get.rank_genes_groups_df(adata_inh, group = None, key='celltype_markers')
  595. # %%
  596. markers_df[markers_df['names'] == 'Kit'].sort_values(by = 'logfoldchanges', ascending = False)
  597. # %%
  598. markers_df[markers_df['names'] == 'Sox14'].sort_values(by = 'logfoldchanges', ascending = False)
  599. # %%
  600. marker_df = markers_df.rename(columns={"group": "Neuronal_celltype", "names": "Gene"})
  601. # %%
  602. adata_inh.obs['leiden_0.3'].value_counts()
  603. # %%
  604. adata_inh = adata_inh[~(adata_inh.obs['leiden_0.3'] == '7')]
  605. # %%
  606. # annotate inhibitory neuron cell type
  607. adata_inh.obs['neuronal_celltype'] = ''
  608. adata_inh.obs['neuronal_celltype'][adata_inh.obs['leiden_0.3'].isin(['1','2','3'])] = 'Inh_Zfhx4'
  609. adata_inh.obs['neuronal_celltype'][adata_inh.obs['leiden_0.3'].isin(['0', '4', '6', '8'])] = 'Inh_Kit'
  610. adata_inh.obs['neuronal_celltype'][adata_inh.obs['leiden_0.3'].isin(['5'])] = 'Inh_Piezo2'
  611. adata_inh.obs['neuronal_celltype'] = adata_inh.obs['neuronal_celltype'].astype('category')
  612. # %%
  613. adata_inh.obs['leiden'] = adata_inh.obs['leiden_0.3'].astype('category')
  614. # %%
  615. mpl.rcParams['figure.figsize'] = (5,5)
  616. ax = sc.pl.umap(adata_inh, color = ['leiden', 'neuronal_celltype'], wspace = 0.24, show = False,
  617. legend_fontsize= legend_fs, size = 40)
  618. for sp in ax:
  619. sp.title.set_fontsize(title_fs)
  620. sp.xaxis.label.set_fontsize(axis_label_fs)
  621. sp.yaxis.label.set_fontsize(axis_label_fs)
  622. plt.savefig('Figures/20240217_res/umap_snrna_onlyinh_color_leiden_ct_20240311.pdf', bbox_inches = 'tight')
  623. # %%
  624. figs, axs = plt.subplots(ncols = 1, nrows = 3, figsize = (4.2, 7))
  625. sc.pl.violin(adata_inh, groupby='neuronal_celltype', keys=['Kit'], ax = axs[0], show = False, size = 0)
  626. axs[0].set_title('Kit', size = title_fs, x = 0.08)
  627. sc.pl.violin(adata_inh, groupby='neuronal_celltype', keys=['Piezo2'], ax = axs[1], show = False, size = 0)
  628. axs[1].set_title('Piezo2', size = title_fs, x = 0.1)
  629. sc.pl.violin(adata_inh, groupby='neuronal_celltype', keys=['Zfhx4'], ax = axs[2], show = False, size = 0)
  630. axs[2].set_title('Zfhx4', size = title_fs, x = 0.1)
  631. for ax in axs:
  632. ax.title.set_fontsize(title_fs)
  633. ax.set_xlabel('')
  634. ax.set_ylabel('')
  635. ax.tick_params(labelsize=axis_tick_fs)
  636. plt.subplots_adjust(hspace = 0.4)
  637. plt.savefig('Figures/20240217_res/vlnplot_inhibitory_celltype_markers_20240507.pdf', bbox_inches = 'tight')
  638. # %%
  639. # Plot each samples individually
  640. fig, axs = plt.subplots(ncols = 3, nrows = 1, figsize = (11.5,3))
  641. sc.pl.umap(adata_inh[adata_inh.obs['sample'] == 'HC',], color="leiden", size = 35,legend_loc= None,
  642. title = 'HC', show = False, ax = axs[0])
  643. sc.pl.umap(adata_inh[adata_inh.obs['sample'] == 'CD',], color="leiden", size = 35,legend_loc= None,
  644. title = 'CD', show = False, ax = axs[1])
  645. sc.pl.umap(adata_inh[adata_inh.obs['sample'] == 'TN',], color="leiden", size = 35,legend_loc= None,
  646. title = 'TN', show = False, ax = axs[2])
  647. for subplot in axs:
  648. subplot.set_xlabel(subplot.get_xlabel(), fontsize= axis_label_fs)
  649. subplot.set_ylabel(subplot.get_ylabel(), fontsize= axis_label_fs)
  650. subplot.set_title(subplot.get_title(), fontsize = title_fs)
  651. plt.savefig('Figures/20240217_res/umap_snrna_onlyinh_splitsample_20240311.pdf', bbox_inches = 'tight')
  652. # %%
  653. adata_inh.X = adata_inh.layers['log1p'].copy()
  654. # %%
  655. # Plot each samples individually
  656. fig, axs = plt.subplots(ncols = 3, nrows = 1, figsize = (11.5,3))
  657. sc.pl.umap(adata_inh[adata_inh.obs['sample'] == 'HC',], color="Grm5", size = 35,legend_loc= None,
  658. title = 'HC', show = False, ax = axs[0], vmax = 3.5)
  659. sc.pl.umap(adata_inh[adata_inh.obs['sample'] == 'CD',], color="Grm5", size = 35,legend_loc= None,
  660. title = 'CD', show = False, ax = axs[1])
  661. sc.pl.umap(adata_inh[adata_inh.obs['sample'] == 'TN',], color="Grm5", size = 35,legend_loc= None,
  662. title = 'TN', show = False, ax = axs[2], vmax = 3.5)
  663. for subplot in axs:
  664. subplot.set_xlabel(subplot.get_xlabel(), fontsize= axis_label_fs)
  665. subplot.set_ylabel(subplot.get_ylabel(), fontsize= axis_label_fs)
  666. subplot.set_title(subplot.get_title(), fontsize = title_fs)
  667. #plt.savefig('Figures/20240217_res/umap_snrna_onlyinh_splitsample_20240311.pdf', bbox_inches = 'tight')
  668. # %%
  669. adata_inh.write_h5ad('Tables/Data/snrna_subsetinh_afterannot_20240311.h5ad')
  670. # %%
  671. adata_inh = sc.read_h5ad('Tables/Data/snrna_subsetinh_afterannot_20240311.h5ad')
  672. # %%
  673. markers_df.to_csv('Tables/3samples_dcn_inh_neurocelltype_markers_20241022.csv')
  674. # %% [markdown]
  675. # # Export for MAST
  676. # %%
  677. concat_out = concat_data[~(concat_data.obs['cell_type'].isin(['Granule_cell', 'UBC','Purkinje', 'Bergmanns_glia','Ependymal_cell', 'Vascular_cell', 'Endothelial_cell']))].copy()
  678. #dcn_out = adata_inh[~(adata_inh.obs['neuronal_celltype'] == 'Inhibitory_1_Zfhx4_TN')].copy()
  679. # %%
  680. concat_out.obs['cell_type'].unique()
  681. # %%
  682. concat_out.X = concat_out.layers['counts'].copy()
  683. #dcn_out.X = dcn_out.layers['counts'].copy()
  684. # %%
  685. sc.pp.normalize_total(concat_out, target_sum=1e6)
  686. sc.pp.log1p(concat_out)
  687. #
  688. #
  689. # ize_total(dcn_out, target_sum=1e6)
  690. #sc.pp.log1p(dcn_out)
  691. # %%
  692. def prep_anndata(adata_):
  693. def fix_dtypes(adata_):
  694. df = pd.DataFrame(adata_.X.A, index=adata_.obs_names, columns=adata_.var_names)
  695. df = df.join(adata_.obs)
  696. return sc.AnnData(df[adata_.var_names], obs=df.drop(columns=adata_.var_names))
  697. adata_ = fix_dtypes(adata_)
  698. sc.pp.filter_genes(adata_, min_cells=3)
  699. return adata_
  700. # %%
  701. concat_out = prep_anndata(concat_out)
  702. #dcn_out = prep_anndata(dcn_out)
  703. # %%
  704. concat_out
  705. #17383 cells, 22728 genes
  706. # %%
  707. adata_lst = []
  708. for ct in concat_out.obs['cell_type'].unique():
  709. adata_ct = concat_out[concat_out.obs['cell_type'] == ct].copy()
  710. adata_ct = prep_anndata(adata_ct)
  711. print(f"{ct}: {len(adata_ct.obs)} nucleis, {len(adata_ct.var)} genes")
  712. adata_lst.append(adata_ct)
  713. # %%
  714. inh_out = adata_inh.copy()
  715. # %%
  716. inh_out.X = adata_inh.layers['counts'].copy()
  717. # %%
  718. def prep_anndata(adata_):
  719. def fix_dtypes(adata_):
  720. df = pd.DataFrame(adata_.X.A, index=adata_.obs_names, columns=adata_.var_names)
  721. df = df.join(adata_.obs)
  722. return sc.AnnData(df[adata_.var_names], obs=df.drop(columns=adata_.var_names))
  723. adata_ = fix_dtypes(adata_)
  724. sc.pp.filter_genes(adata_, min_cells=3)
  725. return adata_
  726. # %%
  727. adata_lst = []
  728. for ct in inh_out.obs['neuronal_celltype'].unique():
  729. adata_ct = inh_out[inh_out.obs['neuronal_celltype'] == ct].copy()
  730. sc.pp.normalize_total(adata_ct, target_sum=1e6)
  731. sc.pp.log1p(adata_ct)
  732. adata_ct = prep_anndata(adata_ct)
  733. print(f"{ct}: {len(adata_ct.obs)} nucleis, {len(adata_ct.var)} genes")
  734. adata_lst.append(adata_ct)
  735. # %%
  736. for ad in adata_lst:
  737. ad.write_h5ad(f"Tables/Data/MAST_adatas/adata_{ad.obs['neuronal_celltype'][0]}_forMAST_analysis_20240311.h5ad")
  738. # %%
  739. np.max(adata_lst[0].X)

preprocess_annotate_snrna.ipynb, under CC-BY-4.0 · at the source

Overview

Authors: Jungeun Ji1,2, Jinhee Baek3,4, Kyoung-Doo Hwang3,4, Seunghwan Choi5, Junko Kasuya6, Seung-Eon Roh7, Sang Jeong Kim3,4,8,9, Ted Abel6, Joon-Yong An1,2,5, Yong-Seok Lee3,4,8,9,10
  1. Department of Integrated Biomedical and Life Science, Korea University,Seoul, Republic of Korea
  2. BK21FOUR R&E Center for Learning Health Systems, Korea University,Seoul, Republic of Korea
  3. Department of Physiology, Seoul National University College of Medicine,Seoul, Republic of Korea
  4. Department of Biomedical Science, Seoul National University College of Medicine,Seoul, Republic of Korea
  5. School of Biosystems and Biomedical Sciences, College of Health Sciences, Korea University,Seoul, Republic of Korea
  6. Department of Neuroscience and Pharmacology, Iowa Neuroscience Institute, University of Iowa,Iowa City, IA USA
  7. Department of Neuroscience, Johns Hopkins University,Baltimore, MD USA
  8. Neuroscience Research Institute, Seoul National Medical Research Center, Seoul, Republic of Korea
  9. Wide River Institute of Immunology, Seoul National University,Hongcheon, Republic of Korea
  10. Convergence Dementia Research Center, Medical Research Center, Seoul National University,Seoul, Republic of Korea
Institutions: Korea University (South Korea); Seoul National University (South Korea); University of Iowa (United States); Johns Hopkins University (United States)
Journal: Communications biology, volume 9, issue 1, article 878
Dates: received 17 April 2025; accepted 30 March 2026; published online 24 April 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s42003-026-10034-0 · PMID 42032255 · PMCID PMC13319209 · OpenAlex W7155565318
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: genetics / omics (modality), mouse (organism), cellular / molecular (subfield)
Methods: Statistics, fMRI & imaging
Keywords: Molecular neuroscience, Learning and memory
MeSH: Cerebellum*, Conditioning, Classical*, Fear*, Gene Expression Regulation*, Animals, Male, Memory, Mice, Mice, Inbred C57BL, Neurons (* major topic)
Topic: Memory and Neural Mechanisms (Cognitive Neuroscience, Neuroscience), according to OpenAlex
Citations: not cited yet (Europe PMC); 86 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.

Repository

Its files are read in the Code ↔ Paper reader above, with 17 matches between paragraphs and lines of code.

Zenodo 15335138

License: CC-BY-4.0
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: “Code availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: Seurat (8 files), tidyverse (8 files), cowplot (7 files), Matplotlib (5 files), NumPy (5 files), pandas (5 files), Scanpy (5 files), seaborn (5 files), PyTorch (4 files), ggplot2 (3 files), anndata (2 files), clusterProfiler (2 files), ComplexHeatmap (2 files), limma (2 files), SingleCellExperiment (2 files), circlize (1 file), data.table (1 file), DESeq2 (1 file), ggpubr (1 file), reshape2 (1 file), reticulate (1 file), rstatix (1 file), SciPy (1 file), Squidpy (1 file), statsmodels (1 file)
Availability: 1 check, the latest on 30 September 2026: the link answers (HTTP 200)
  • 30 September 2026: the link answers (HTTP 200)
13 files

Code availability statement

The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s42003-026-10034-0.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 13 scripts, each with its path and the digest of its content;
  • 17 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Code and data availability statement

The paper has a code and data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s42003-026-10034-0.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 30 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 10 authors, 2 keywords, 10 MeSH terms, 2 funders, 86 references.

Cite

This paper

Ji, J., Baek, J., Hwang, K.-D., Choi, S., Kasuya, J., Roh, S.-E., Kim, S. J., Abel, T., An, J.-Y., & Lee, Y.-S. (2026). Region- and cell type-specific changes in gene expression in the cerebellum after classical fear conditioning. Communications biology, 9(1), 878. https://doi.org/10.1038/s42003-026-10034-0

BibTeX

@article{ji2026region,
author = {Ji, Jungeun and Baek, Jinhee and Hwang, Kyoung-Doo and Choi, Seunghwan and Kasuya, Junko and Roh, Seung-Eon and Kim, Sang Jeong and Abel, Ted and An, Joon-Yong and Lee, Yong-Seok},
title = {{Region- and cell type-specific changes in gene expression in the cerebellum after classical fear conditioning}},
journal = {Communications biology},
year = {2026},
month = apr,
volume = {9},
number = {1},
pages = {878},
publisher = {Nature Portfolio},
issn = {2399-3642},
doi = {10.1038/s42003-026-10034-0},
url = {https://doi.org/10.1038/s42003-026-10034-0},
pmid = {42032255},
pmcid = {PMC13319209}
}

RIS

TY - JOUR
AU - Ji, Jungeun
AU - Baek, Jinhee
AU - Hwang, Kyoung-Doo
AU - Choi, Seunghwan
AU - Kasuya, Junko
AU - Roh, Seung-Eon
AU - Kim, Sang Jeong
AU - Abel, Ted
AU - An, Joon-Yong
AU - Lee, Yong-Seok
TI - Region- and cell type-specific changes in gene expression in the cerebellum after classical fear conditioning
T2 - Communications biology
J2 - Commun Biol
PY - 2026
DA - 2026/04/24
VL - 9
IS - 1
SP - 878
SN - 2399-3642
PB - Nature Portfolio
DO - 10.1038/s42003-026-10034-0
UR - https://doi.org/10.1038/s42003-026-10034-0
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s42003-026-10034-0",
"type": "article-journal",
"title": "Region- and cell type-specific changes in gene expression in the cerebellum after classical fear conditioning",
"container-title": "Communications biology",
"author": [
{
"family": "Ji",
"given": "Jungeun"
},
{
"family": "Baek",
"given": "Jinhee"
},
{
"family": "Hwang",
"given": "Kyoung-Doo"
},
{
"family": "Choi",
"given": "Seunghwan"
},
{
"family": "Kasuya",
"given": "Junko"
},
{
"family": "Roh",
"given": "Seung-Eon"
},
{
"family": "Kim",
"given": "Sang Jeong"
},
{
"family": "Abel",
"given": "Ted"
},
{
"family": "An",
"given": "Joon-Yong"
},
{
"family": "Lee",
"given": "Yong-Seok"
}
],
"container-title-short": "Commun Biol",
"volume": "9",
"issue": "1",
"page": "878",
"DOI": "10.1038/s42003-026-10034-0",
"PMID": "42032255",
"PMCID": "PMC13319209",
"ISSN": "2399-3642",
"publisher": "Nature Portfolio",
"URL": "https://doi.org/10.1038/s42003-026-10034-0",
"language": "en",
"issued": {
"date-parts": [
[
2026,
4,
24
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1016/j.celrep.2024.115149 [code]
Single-nucleus and spatial landscape of the sub-ventricular zone in human glioblastoma.
Journal: Cell reports
In common: Squidpy, reticulate, SingleCellExperiment, 21 other tools, cellular / molecular, 3 references
[2] doi:10.1038/s41593-025-02022-0 [code]
An integrated single-nucleus and spatial transcriptomics atlas reveals the molecular landscape of the human hippocampus.
Journal: Nature neuroscience
In common: Squidpy, reticulate, SingleCellExperiment, 19 other tools, genetics / omics, 3 references
[3] doi:10.1093/nar/gkaf1473 [code]
STAN, a computational framework for inferring spatially informed transcription factor activity.
Journal: Nucleic acids research
In common: Squidpy, reticulate, SingleCellExperiment, 19 other tools, genetics / omics, cellular / molecular, 2 references
[4] doi:10.1186/s13062-025-00691-2 [code]
Single-cell transcriptome analysis suggests cells of the tumor microenvironment as a major discriminator between brain and extracranial melanoma metastases.
Journal: Biology direct
In common: Squidpy, reticulate, SingleCellExperiment, 17 other tools, genetics / omics, cellular / molecular, 2 references
[5] doi:10.1007/s12311-022-01506-0 [code]
Cerebellum Lecture: the Cerebellar Nuclei-Core of the Cerebellum.
Journal: Cerebellum (London, England)
In common: circlize, ComplexHeatmap, Seurat, 4 other tools, mouse, 13 references
[6] doi:10.1186/s13059-026-04177-w [code]
Genomic sequence evolution underlying human neocortical interareal diversification.
Journal: Genome biology
In common: Squidpy, reticulate, anndata, 15 other tools, genetics / omics, mouse, cellular / molecular, 4 references
[7] doi:10.1038/s41467-023-40744-6 [code]
Projecting RNA measurements onto single cell atlases to extract cell type-specific expression profiles using scProjection.
Journal: Nature communications
In common: Squidpy, reticulate, SingleCellExperiment, 17 other tools, genetics / omics, cellular / molecular, 1 reference
[8] doi:10.1016/j.xgen.2024.100739 [code]
CSI-GEP: A GPU-based unsupervised machine learning approach for recovering gene expression programs in atlas-scale single-cell RNA-seq data.
Journal: Cell genomics
In common: reticulate, SingleCellExperiment, anndata, 16 other tools, genetics / omics, mouse, cellular / molecular, 3 references
[9] doi:10.1038/s41586-025-09083-y [code]
Single-cell transcriptomic and chromatin dynamics of the human brain in PTSD.
Journal: Nature
In common: Squidpy, reticulate, SingleCellExperiment, 15 other tools, genetics / omics, cellular / molecular, 4 references
[10] doi:10.15252/msb.202311670 [code]
CellNeighborEX: deciphering neighbor-dependent gene expression from spatial transcriptomics data.
Journal: Molecular systems biology
In common: Squidpy, anndata, limma, 17 other tools, genetics / omics, mouse, cellular / molecular, 1 reference

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1038/s42003-026-10034-0.svg)](https://openscicode.org/badge/doi/10.1038/s42003-026-10034-0)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1038/s42003-026-10034-0.svg
   :target: https://openscicode.org/badge/doi/10.1038/s42003-026-10034-0
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1038/s42003-026-10034-0"><img src="https://openscicode.org/badge/doi/10.1038/s42003-026-10034-0.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.