OSCR

Spatial cartography of human thymus enables the geopositioning of lineage transcription factors in rare mimetic thymic epithelial cells.

Code ↔ Paper

15 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.

The 15 matches
  1. [1] § Method › Integration of spatial clusters across samples ↔ 2.DefineNiche/integrate_niches_functions.ipynb, lines 108–256 · score 0.98 · pyCombat, batch corrected, pseudobulk profiles, COL1A2, MS4A1, CD8A
  2. [2] § Method › Signalling pathways ↔ 3.CellCommunication/run_cellularCommunication.ipynb, lines 33–181 · score 0.86 · truncatedMean, cell communication, incoming, outgoing, probability, CellChat
  3. [3] § Method › Integration of spatial clusters across samples ↔ 1.ProcessSamples/scRNA_integrate.Rmd, lines 739–861 · score 0.85 · COL1A1, CD8A, FOXP3, IGHM, MKI67, TPSAB1
  4. [4] § Method › Spatial cell type annotation ↔ 2.DefineNiche/integrate_niches_functions.ipynb, lines 536–652 · score 0.84 · expressed genes identified, combined known cell, gene score, integrated fetal, 0–1, scRNA
  5. [5] § Method › Signalling pathways ↔ 1.ProcessSamples/scRNA_integrate.Rmd, lines 1228–1337 · score 0.81 · CellChat, communication probability, cell communication, incoming, outgoing, signals
  6. [6] § Method › Differential GO function ↔ 2.DefineNiche/integrate_niches_functions.ipynb, lines 776–797 · score 0.77 · GO_Biological_Process_2023, drug2cell, gene ontology
  7. [7] § Results › Thymus architecture and geopositioning of cell types ↔ 2.DefineNiche/integrate_niches_functions.ipynb, lines 108–256 · score 0.72 · PCA transformation, batch corrected, COL1A2, VWF, gene expression, CD34
  8. [8] § Method › sn/scRNA-seq integration with public data ↔ 1.ProcessSamples/scRNA_integrate.Rmd, lines 105–187 · score 0.69 · FindIntegrationAnchors, FindAllMarkers, UMAP, Seurat, sc, seq
  9. [9] § Results › Thymus architecture and geopositioning of cell types ↔ 2.DefineNiche/integrate_niches_functions.ipynb, lines 536–652 · score 0.69 · mTEC, known cell, spatial spot, expressed genes, scRNA, DP
  10. [10] § Results › High-resolution spatial transcriptomic atlas of human thymus ↔ 2.DefineNiche/integrate_niches_functions.ipynb, lines 654–720 · score 0.67 · COL1A2, MS4A1, CD8A, CD83, CD14, CD34
  11. [11] § Method › sc/snRNA-seq data processing ↔ 1.ProcessSamples/scRNA_integrate.Rmd, lines 33–100 · score 0.57 · SCTransform, Seurat, filtered, UMAP, RNA, PCA
  12. [12] § Method › Identification of mimeTFs in spatial multiome ↔ 4.MimeTFs/IdentifyMimeTFs.ipynb, lines 237–289 · score 0.55 · CITE spatial, mimeTFs, septa, multiome, protein, Stereo
  13. [13] § Method › Spatial transcriptomics data processing ↔ 3.CellCommunication/run_cellularCommunication.ipynb, lines 33–181 · score 0.54 · weighted, edge, mouse, diameter, networks, neighbours
  14. [14] § Results › Cell type mimicking function by mimeTFs expressing TECs ↔ 2.DefineNiche/integrate_niches_functions.ipynb, lines 776–797 · score 0.53 · Gene Ontology, biological processes, GO
  15. [15] § Results › Abundance and geopositioning of mimeTFs expressing cells ↔ 2.DefineNiche/Integrate_niche_celltype_samples.ipynb, lines 443–465 · score 0.50 · KRT1 high region, HC region, HCs, LQ, niche, spots

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Jupyter notebook · 857 lines · 33 KB · CC-BY-4.0 · 7 matches

  1. # %% [markdown]
  2. # # Functions
  3. # ### 1. integrate spatial samples
  4. # ### 2. define niches
  5. # ### 3. determine cell type -> cell-type-specificity score and RCTD
  6. # %%
  7. import scanpy as sc
  8. import networkx as nx
  9. import pandas as pd
  10. import matplotlib.pyplot as plt
  11. import numpy as np
  12. import h5py
  13. from anndata._io.specs import read_elem
  14. import seaborn as sns
  15. from numpy import inf
  16. from scipy.interpolate import griddata
  17. from skimage import measure
  18. from shapely.geometry import MultiPoint, Polygon
  19. import alphashape
  20. import matplotlib.colors as mcol
  21. import decoupler as dc
  22. from combat.pycombat import pycombat
  23. import matplotlib.pyplot as plt
  24. import matplotlib.colors as mcolors
  25. from sklearn.cluster import KMeans
  26. from sklearn import datasets
  27. from sklearn.decomposition import PCA
  28. from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
  29. import h5py
  30. from anndata._io.specs import read_elem
  31. import drug2cell as d2c
  32. import blitzgsea as blitz
  33. import warnings
  34. warnings.simplefilter(action='ignore', category=pd.errors.PerformanceWarning)
  35. warnings.filterwarnings("ignore", category=DeprecationWarning)
  36. warnings.simplefilter(action='ignore', category=FutureWarning)
  37. warnings.simplefilter(action='ignore', category=UserWarning)
  38. import matplotlib
  39. matplotlib.rcParams['pdf.fonttype'] = 42
  40. matplotlib.rcParams['ps.fonttype'] = 42
  41. plt.rcParams['pdf.fonttype'] = 42
  42. plt.rcParams['ps.fonttype'] = 42
  43. plt.style.use('seaborn-white')
  44. # %%
  45. # Load marker genes
  46. degenes_annot2 = pd.read_csv("/data/Combined_Analysis/DEG_scRNA-seq.csv", sep=",")
  47. custom_marker = pd.read_csv("/data/Combined_Analysis/Custom_markers.csv", sep=",")
  48. # %%
  49. ## Define colours scheme for the domain and niches
  50. domain_color = { 'C': '#4292c6',
  51. 'M':'#fc9272',
  52. 'S': '#41ab5d',
  53. 'LQ' : '#f0f0f0'
  54. }
  55. niche_color = {'C1': '#9ecae1','C2': '#4292c6','C3': '#08519c', 'M1':'#fc9272', 'M2':'#ef3b2c','M3':'#a50f15',
  56. 'S1': '#a1d99b','S2': '#74c476', 'S3': '#41ab5d', 'S4': '#006d2c', 'LQ' : '#f0f0f0', 'HC' : '#252525'
  57. }
  58. HC_niche_color = {'C1': '#9ecae1','C2': '#4292c6','C3': '#08519c', 'M1':'#fc9272', 'M2':'#ef3b2c','M3':'#a50f15',
  59. 'S1': '#a1d99b','S2': '#74c476', 'S3': '#41ab5d', 'S4': '#006d2c', 'LQ' : '#f0f0f0', 'KRT1+' : '#6a51a3','KRT1++' : '#3f007d'
  60. }
  61. # %%
  62. # Get pseudo-bulk profile for each leiden cluster within leiden cluster
  63. def findPseudobulk(adata, adata_raw, sample_name, save_folder, group='leiden'):
  64. """
  65. Calculate the pseudo bulk profile of the leiden clusters.
  66. Parameters:
  67. adata: spatial data with leiden cluster meta data
  68. adata_raw: raw counts spatial data
  69. sample_name: sample name
  70. save_folder: folder to save the file
  71. Returns:
  72. Write the pseudobulk profile to csv file
  73. """
  74. adata_raw.obs[group] = adata.obs.leiden
  75. adata_raw.obs.leiden = adata_raw.obs.leiden.astype('str')
  76. adata_raw.X = np.round(adata_raw.X)
  77. adata_raw.layers['raw_counts'] = adata_raw.X
  78. adata_raw.obs['orig.ident'] = sample_name
  79. pdata = dc.get_pseudobulk(
  80. adata_raw,
  81. sample_col='orig.ident',
  82. groups_col=group,
  83. layer='raw_counts',
  84. mode='sum',
  85. min_cells=0,
  86. min_counts=0
  87. )
  88. dc.plot_psbulk_samples(pdata, groupby=[group,'orig.ident'], figsize=(8, 4))
  89. pdata.T.to_df().to_csv(f"{save_folder}" + sample_name + group + '_sumgeneexp.csv')
  90. adata.obs.to_csv(f"{save_folder}" + sample_name + group + "_meta.csv")
  91. # %%
  92. def integrate_pca(df_exp, datasets, target_names, nPC=5, ncluster=20):
  93. """
  94. Integrate the sample cluster pseudobulk profiles using PCA
  95. - pyCombat batch correction
  96. - PCA transformation
  97. - Kmeans clustering
  98. - Plot marker gene expression
  99. Parameters:
  100. df_exp: pandas object with normalised
  101. datasets: list of data to correct for data
  102. target_names: sample names
  103. nPC: number of PCs to model
  104. ncluster: number of resulting groups
  105. Returns:
  106. Write the pseudobulk profile to csv file
  107. df_segment_avgSonly: Average profile of the kmeans group
  108. df_clusters: Contain sample-wise group information
  109. """
  110. batch = []
  111. for j in range(len(datasets)):
  112. batch.extend([j for _ in range(len(datasets[j].columns)-1)])
  113. # run pyComBat
  114. df_corrected = pycombat(df_exp,batch)
  115. df_corrected.to_csv(f"{save_folder}Psuedo_batchCorrected.csv")
  116. plt.boxplot(df_corrected)
  117. plt.show()
  118. X = df_corrected.transpose()
  119. y = np.array(batch)
  120. plt.style.use('seaborn-white')
  121. pca = PCA()
  122. pca.fit(X)
  123. per_var = np.round(pca.explained_variance_ratio_*100, decimals = 1)
  124. plt.figure(figsize = (10,6))
  125. plt.plot(range(1, len(per_var)+1), per_var.cumsum(), marker = "o", linestyle = "--")
  126. plt.grid()
  127. plt.ylabel("Percentage Cumulative of Explained Variance")
  128. plt.xlabel("Number of Components")
  129. plt.title("Explained Variance by Component")
  130. plt.show()
  131. pca = PCA(n_components = nPC)
  132. pca.fit(X)
  133. scores_pca = pca.transform(X)
  134. WCSS = []
  135. for i in range(1,30):
  136. kmeans_pca = KMeans(n_clusters = i, init = "k-means++", random_state = 42)
  137. kmeans_pca.fit(scores_pca)
  138. WCSS.append(kmeans_pca.inertia_)
  139. plt.figure(figsize = (10,6))
  140. plt.plot(range(1,30), WCSS, marker = "o", linestyle = "--")
  141. plt.grid()
  142. plt.title("Cluster using PCA Scores")
  143. plt.ylabel("WCSS")
  144. plt.xlabel("N Clusters")
  145. plt.show()
  146. kmeans_pca = KMeans(n_clusters = ncluster, init = "k-means++", random_state = 42)
  147. kmeans_pca.fit(scores_pca)
  148. df = pd.DataFrame(df_corrected.columns)
  149. # Concatening the original df with the components informations present in scores_pca
  150. df_clust_pca_kmeans = pd.concat([df, pd.DataFrame(scores_pca)], axis = 1)
  151. #print(df_clust_pca_kmeans)
  152. # Renaming the column label from each component
  153. df_clust_pca_kmeans.columns = ["sample_leiden", "comp1", "comp2", "comp3", "comp4", "comp5"]
  154. # Seting the cluster label to each observation, using the atribute .labels_
  155. df_clust_pca_kmeans["segment_kmeans_pca"] = kmeans_pca.labels_
  156. # Mapping each cluster segmentation and renaming their labels
  157. df_clust_pca_kmeans["segment"] = df_clust_pca_kmeans["segment_kmeans_pca"]
  158. df_clust_pca_kmeans.to_csv(f"{save_folder}Sample_psuedo_PCA.csv")
  159. sns.pairplot(df_clust_pca_kmeans[1:], hue='segment', palette='tab20')
  160. df_clust_pca_kmeans[['Sample', 'leiden_clusters']] = df_clust_pca_kmeans['sample_leiden'].str.split('_', n=1, expand=True)
  161. sns.pairplot(df_clust_pca_kmeans[1:], hue='Sample', palette='tab20')
  162. df_corrected_long = df_corrected.stack().reset_index().set_axis('Genes Sample_leiden avgExp'.split(), axis=1)
  163. df_corrected_long = pd.merge(df_corrected_long, df_clust_pca_kmeans, left_on='Sample_leiden', right_on='sample_leiden')
  164. df_corrected_long[['Sample', 'leiden_clusters']] = df_corrected_long['sample_leiden'].str.split('_', n=1, expand=True)
  165. df_corrected_long['Sample_segment'] = df_corrected_long['Sample'] + df_corrected_long['segment'].astype('str')
  166. df_segment_avg = df_corrected_long.groupby(['Sample_leiden', 'Genes']).mean('avgExp')
  167. df_segment_avg = df_segment_avg.reset_index()
  168. df_segment_avgM = df_segment_avg.pivot(index='Genes', columns='Sample_leiden', values='avgExp')
  169. sns.clustermap(df_segment_avgM[df_segment_avgM.axes[0].isin(['PRSS16',
  170. 'AIRE',
  171. 'COL1A2',
  172. 'HBB',
  173. 'CD4', 'CD8A',
  174. 'MS4A1', 'CD14', 'CD34'
  175. ])], annot=False, cmap="Reds", figsize=(50,3))
  176. df_segment_avg= df_corrected_long.groupby(['Sample_segment', 'Genes']).mean('avgExp')
  177. df_segment_avg = df_segment_avg.reset_index()
  178. df_segment_avgS = df_segment_avg.pivot(index='Genes', columns='Sample_segment', values='avgExp')
  179. df_segment_avgS.to_csv('df_segment_avgS.csv')
  180. sns.clustermap(df_segment_avgS[df_segment_avgS.axes[0].isin(['PRSS16', 'PSMB11','CCL25', 'LY75', 'TBATA',
  181. 'AIRE', 'FEZF2',
  182. 'KRT15',
  183. 'KRT1',
  184. 'EPCAM',
  185. 'LAMP3',
  186. 'ITGAX',
  187. 'CD74', 'CD83', 'MS4A1', 'CD34', 'VWF', 'COL1A2','CD4', 'CD8A', 'CD14','CDH5',
  188. 'PECAM1',
  189. 'HBB',
  190. 'LUM',
  191. 'PRX1'
  192. ])], annot=False, cmap="Reds", figsize=(15,8)).savefig(f"{save_folder}Sample_Segment.pdf")
  193. df_segment_avgSonly = df_corrected_long.groupby(['segment', 'Genes']).mean('avgExp')
  194. df_segment_avgSonly = df_segment_avgSonly.reset_index()
  195. df_segment_avgSonly = df_segment_avgSonly.pivot(index='Genes', columns='segment', values='avgExp')
  196. df_segment_avgSonly.to_csv(f"{save_folder}df_segment_avgSonlyF.csv")
  197. df_segment_avgSonly.sum().to_csv(f"{save_folder}segments_sumGenes.csv")
  198. df_clusters = df_clust_pca_kmeans
  199. df_clusters[['Sample', 'leiden_clusters']] = df_clusters['sample_leiden'].str.split('_', n=1, expand=True)
  200. sns.clustermap(df_segment_avgSonly[df_segment_avgSonly.axes[0].isin([
  201. 'PRSS16', 'PSMB11','CCL25', 'LY75', 'TBATA',
  202. 'AIRE', 'FEZF2',
  203. 'KRT15',
  204. 'KRT1',
  205. 'EPCAM',
  206. 'LAMP3',
  207. 'ITGAX',
  208. 'CD74', 'CD83', 'MS4A1', 'CD34', 'VWF', 'COL1A2','CD4', 'CD8A', 'CD14','CDH5',
  209. 'PECAM1',
  210. 'HBB',
  211. 'LUM',
  212. 'PRX1', 'VWF'
  213. ])], annot=False, cmap="viridis", z_score=True, figsize=(8,8)).savefig(f"{save_folder}Segments_markergenes_long.pdf")
  214. sns.clustermap(df_segment_avgSonly[df_segment_avgSonly.axes[0].isin(['AIRE',
  215. 'PRSS16', 'HBB'])], z_score=True, annot=False, cmap="Reds", figsize=(10,2)).savefig(f"{save_folder}Segments_markergenes.pdf")
  216. return df_segment_avgSonly, df_clusters
  217. # %%
  218. def addAnnotation(tmp_adata, Medulla, Cortex, Septa, LowQuality):
  219. """
  220. Add annotation based on the cluster/group numbers
  221. Parameters:
  222. tmp_adata: spatial data
  223. Medulla: list of medulla cluster numbers
  224. Cortex: list of cortex cluster numbers
  225. Septa: list of septa cluster numbers
  226. LowQuality: list of LQ cluster numbers
  227. Returns:
  228. spatial data with additional meta data
  229. """
  230. tmp_adata.obs["Domain"] = "NA"
  231. x = list(tmp_adata[tmp_adata.obs['segment'].isin(Medulla)].obs_names)
  232. tmp_adata.obs.loc[ x, 'Domain'] = 'M'
  233. x = list(tmp_adata[tmp_adata.obs['segment'].isin(Cortex)].obs_names)
  234. tmp_adata.obs.loc[ x, 'Domain'] = 'C'
  235. x = list(tmp_adata[tmp_adata.obs['segment'].isin(Septa)].obs_names)
  236. tmp_adata.obs.loc[ x, 'Domain'] = 'S'
  237. x = list(tmp_adata[tmp_adata.obs['segment'].isin(LowQuality)].obs_names)
  238. tmp_adata.obs.loc[ x, 'Domain'] = 'LQ'
  239. return tmp_adata
  240. # %%
  241. def compute_contour_boundary(points, alpha):
  242. """
  243. Compute the contour boundary (outline) of a given set of points.
  244. Compute alpha shape (concave hull)
  245. Parameters:
  246. points: x y points
  247. alpha: Large alpha values → More convex, simpler shape. Small alpha values → More concave, tighter fit around the points.
  248. Returns:
  249. Boundary coordinates
  250. """
  251. shape = alphashape.alphashape(points, alpha)
  252. if shape.is_empty:
  253. raise ValueError("Alpha shape failed; adjust alpha parameter.")
  254. if isinstance(shape, Polygon):
  255. boundary_coords = np.array(shape.exterior.coords)
  256. else:
  257. # If multiple polygons, combine their boundaries
  258. boundary_coords = np.vstack([np.array(poly.exterior.coords) for poly in shape.geoms])
  259. return boundary_coords
  260. def compute_contours(data, alpha):
  261. """
  262. Find the contour or boundary of the spatial groups
  263. Parameters:
  264. data: spatial data
  265. alpha: Large alpha values → More convex, simpler shape. Small alpha values → More concave, tighter fit around the points.
  266. Returns:
  267. The location of boundary position between spatial groups
  268. """
  269. df_all = pd.DataFrame(data)
  270. thres_len = 100
  271. category_mapping = {'C': 1, 'M': 2, 'S': 3}
  272. ###Outline
  273. outline_coords = compute_contour_boundary(df_all[['X', 'Y']].to_numpy(), alpha= alpha)
  274. boundary_data = []
  275. for point in outline_coords:
  276. boundary_data.append({
  277. 'Boundary': 'Outline',
  278. 'X': point[0],
  279. 'Y': point[1]
  280. })
  281. ### M
  282. df = df_all[df_all.Z.isin(['M'])]
  283. outline_coords = compute_contour_boundary(df[['X', 'Y']].to_numpy(), alpha=alpha)
  284. for point in outline_coords:
  285. boundary_data.append({
  286. 'Boundary': 'M',
  287. 'X': point[0],
  288. 'Y': point[1]
  289. })
  290. ### C-M
  291. df = df_all[df_all.Z.isin(['C','M'])]
  292. outline_coords = compute_contour_boundary(df[['X', 'Y']].to_numpy(), alpha=alpha)
  293. for point in outline_coords:
  294. boundary_data.append({
  295. 'Boundary': 'C-M',
  296. 'X': point[0],
  297. 'Y': point[1]
  298. })
  299. ### C-S
  300. df = df_all[df_all.Z.isin(['C','M', 'S'])]
  301. outline_coords = compute_contour_boundary(df[['X', 'Y']].to_numpy(), alpha= alpha)
  302. for point in outline_coords:
  303. boundary_data.append({
  304. 'Boundary': 'C-M-S',
  305. 'X': point[0],
  306. 'Y': point[1]
  307. })
  308. boundary_df = pd.DataFrame(boundary_data)
  309. return boundary_df
  310. def shortest_distance(point, coordinates):
  311. """
  312. Calculate the shortest distance from a given point to a list of coordinates.
  313. Parameters:
  314. point: one data x-y point
  315. coordinates: compare against these collection of points
  316. Returns:
  317. shortest distance value
  318. """
  319. point = np.array(point)
  320. coordinates = np.array(coordinates)
  321. # Compute squared distances (faster than directly computing Euclidean distances)
  322. squared_distances = np.sum((coordinates - point) ** 2, axis=1)
  323. # Find the index of the minimum distance
  324. min_index = np.argmin(squared_distances)
  325. # Compute the actual shortest distance
  326. shortest_dist= np.sqrt(squared_distances[min_index])
  327. # Get the closest point
  328. closest_point = tuple(coordinates[min_index])
  329. return shortest_dist
  330. def assign_subcategory(x, y, region, boundary_df): #contours):
  331. """
  332. Calculate distances and assign subcategories
  333. Parameters:
  334. region: C, M or S
  335. boundary_df: boundary positions
  336. Returns:
  337. Sub region assignment value
  338. """
  339. #distance_to_outline = shortest_distance((x,y), np.array(boundary_df[boundary_df.Boundary == 'Outline' ][['X', 'Y']].to_records(index=False)).tolist())
  340. distance_to_m = shortest_distance((x,y), np.array(boundary_df[boundary_df.Boundary == 'M' ][['X', 'Y']].to_records(index=False)).tolist())
  341. distance_to_cm = shortest_distance((x,y), np.array(boundary_df[boundary_df.Boundary == 'C-M' ][['X', 'Y']].to_records(index=False)).tolist())
  342. distance_to_cms = shortest_distance((x,y), np.array(boundary_df[boundary_df.Boundary == 'C-M-S' ][['X', 'Y']].to_records(index=False)).tolist())
  343. if region == 'C':
  344. if distance_to_m <= distance_to_cm:
  345. if distance_to_m <= distance_to_cms:
  346. return 'C1'
  347. elif distance_to_m > distance_to_cms:
  348. return 'C3'
  349. elif distance_to_m > distance_to_cm:
  350. if distance_to_m <= distance_to_cms:
  351. return 'C2'
  352. elif distance_to_m > distance_to_cms:
  353. return 'C3'
  354. elif region == 'M':
  355. if distance_to_m <= distance_to_cm:
  356. if distance_to_m <= 100:
  357. return 'M2'
  358. elif distance_to_m > 100:
  359. return 'M1'
  360. elif distance_to_m > distance_to_cm:
  361. return 'M3'
  362. elif region == 'S':
  363. if distance_to_cm <= distance_to_cms:
  364. if distance_to_m <= distance_to_cm:
  365. return 'S1'
  366. elif distance_to_m > distance_to_cm:
  367. return 'S2'
  368. else:
  369. return 'S3'
  370. def find_niche(tmp_adata, sample, s_value, alpha):
  371. """
  372. Main function to Find Niche based on boundaries and closeness to the boundaries
  373. Parameters:
  374. tmp_adata: spatial data
  375. s_value: spot size for spatial plotting function
  376. alpha: Large alpha values → More convex, simpler shape. Small alpha values → More concave, tighter fit around the points.
  377. sample: sample name
  378. Returns:
  379. spatial data with meta on Niche subregions based closeness to the boundaries
  380. """
  381. data = {
  382. 'X': tmp_adata.obs.x,
  383. 'Y': tmp_adata.obs.y,
  384. 'Z': tmp_adata.obs.Domain
  385. }
  386. df = pd.DataFrame(data)
  387. boundary_df = compute_contours(data, alpha)
  388. boundary_color = mcol.ListedColormap(["grey", "red", "blue","green"])
  389. plt.figure(figsize=(4, 3))
  390. plt.scatter(boundary_df['X'], boundary_df['Y'], c=pd.factorize(boundary_df['Boundary'])[0], s=0.05, cmap=boundary_color )
  391. plt.title("Boundaries")
  392. plt.xlabel("X")
  393. plt.ylabel("Y")
  394. plt.savefig(sample + "_boundary.pdf")
  395. print(boundary_df.Boundary.value_counts())
  396. df['Subcategory'] = df.apply(
  397. lambda row: assign_subcategory(row['X'], row['Y'], row['Z'], boundary_df),
  398. axis=1
  399. )
  400. df.to_csv(sample + '_subcategories.csv', index=False)
  401. boundary_df.to_csv(sample + '_boundaries.csv', index=False)
  402. tmp_adata.obs['Niche'] = df.Subcategory
  403. #sc.pl.embedding(tmp_adata, basis="spatial", color=['segment', 'Domain', 'Niche'], s=s_value, save= sample + "_domain_niche.pdf")
  404. tmp_adata.obs.to_csv(sample + '_meta_niche.csv', index=True)
  405. print(df.Subcategory.value_counts())
  406. # with plt.rc_context(): # Use this to set figure params like size and dpi
  407. # plt.rcParams['figure.dpi'] = 100
  408. # plt.rcParams["figure.figsize"] = (3,2)
  409. # sc.pl.dotplot(tmp_adata, gene_list, 'Niche', use_raw=False, cmap='viridis', show=True, dendrogram=False)
  410. return tmp_adata
  411. # %%
  412. # %%
  413. ## TissueTag
  414. import tissue_tag as tt
  415. def tissue_tag(adata, annotation_column, Number1, Number2):
  416. """
  417. Call the Tissue Tag python function to split the spatial Domains into concentric bins
  418. Parameters:
  419. adata: spatial data
  420. annotation_column: Domain C, M or S
  421. Number1: number of concentric bins - C
  422. Number2: number of concentric bins - M or S
  423. Returns:
  424. spatial data with meta on Tissue Tag based concentric niches
  425. """
  426. adata.obs['x'] = adata.obsm['spatial'][:, 0]
  427. adata.obs['y'] = adata.obsm['spatial'][:, 1]
  428. tt.dist2cluster_fast(
  429. df=adata.obs,
  430. annotation=annotation_column,
  431. KNN=10
  432. ) # calculate minimum mean distance of each spot to clusters
  433. structure = ['S','C','M']
  434. w = [0.2,0.8]
  435. df_anno = tt.calculate_axis_3p(adata.obs, anno=annotation_column, structure=structure, output_col='cma_3p', w=w)
  436. adata.obs = df_anno
  437. #cortex group
  438. labels_cortex = [f'C{i}' for i in range(1, Number1+1)]
  439. labels_cortex
  440. adata.obs['Cell_group'] = adata.obs[annotation_column].astype(str)
  441. adata.obs.loc[adata.obs[annotation_column] == 'C', 'Cell_group'] = pd.qcut(adata.obs.loc[adata.obs[annotation_column] == 'C', 'cma_3p'], q=Number1, labels=labels_cortex).astype(str)
  442. #Medulla group
  443. labels_medulla = [f'M{i}' for i in range(1, Number2+1)]
  444. labels_medulla
  445. adata.obs.loc[adata.obs[annotation_column] == 'M', 'Cell_group'] = pd.qcut(adata.obs.loc[adata.obs[annotation_column] == 'M', 'cma_3p'], q=Number2, labels=labels_medulla).astype(str)
  446. #Septa group
  447. labels_septa = [f'S{i}' for i in range(1, Number2+1)]
  448. labels_septa
  449. adata.obs.loc[adata.obs[annotation_column] == 'S', 'Cell_group'] = pd.qcut(adata.obs.loc[adata.obs[annotation_column] == 'S', 'cma_3p'], q=Number2, labels=labels_septa).astype(str)
  450. return adata
  451. # %%
  452. ## Cellspecificity score and RCTD cell type
  453. cts = [
  454. 'cTEC(P)','cTEC(Q)', 'cTEC(Q) SIRT1lo','cTEC DP',
  455. 'DN(Q)','DP(P) RUNX3hi', 'DP(P) FABP5hi', 'DP(Q) AQP3hi', 'DP(Q) FABP5lo', 'CD8aa','ab entry',
  456. 'mTEC I', 'mTEC II', 'mTEC III', 'mimeTEC', 'CD4/CD8/Treg', 'B pro(P)', 'B pro(Q)', 'B IGHMhi','B TRAF1hi', 'B TRAF5hi',
  457. 'DC1','DC2','aDC3','aDC1.2', 'pDC', 'Mono', 'Macro(Q)','Macro(Phago)', 'Mast',
  458. 'ETP', 'VSMC','Ery', 'Fib(P)', 'Fib(Q)', 'Endo']
  459. cts_rctd = ['ab.entry',
  460. 'aDC1.2', 'aDC3', 'B.IGHMhi', 'B.pro.P.', 'B.pro.Q.', 'B.TRAF1hi',
  461. 'B.TRAF5hi', 'CD4_CD8_Treg', 'CD8aa', 'cTEC.DP', 'cTEC.P.', 'cTEC.Q.',
  462. 'cTEC.Q..SIRT1lo', 'DC1', 'DC2', 'DN.Q.', 'DP.P..FABP5hi',
  463. 'DP.P..RUNX3hi', 'DP.Q..AQP3hi', 'DP.Q..FABP5lo', 'Endo', 'Ery', 'ETP',
  464. 'Fib.P.', 'Fib.Q.', 'Macro.Phago.', 'Macro.Q.', 'Mast', 'mimeTEC',
  465. 'Mono', 'mTEC.I', 'mTEC.II', 'mTEC.III', 'pDC', 'VSMC']
  466. def cell_specificity_score(adata, cts, sample):
  467. """
  468. cell-specificity-score calculates a gene score by combining known cell-type marker genes with the top ten differentially expressed genes
  469. identified from integrated fetal and pediatric scRNA-seq dataset
  470. Parameters:
  471. adata: spatial data
  472. cts: list of cell type names
  473. sample: sample name
  474. Returns:
  475. writes the cell type specificity score for all the spatial spots and cell type combination to a csv file
  476. """
  477. for c in cts:
  478. gl = degenes_annot2.gene[degenes_annot2.cluster == c][0:10]
  479. gl = list(set(gl).union(set(custom_marker.gene[custom_marker.celltype == c])))
  480. if len(gl) >0 :
  481. sc.tl.score_genes(adata,
  482. gl,
  483. ctrl_size=50,
  484. gene_pool=None, n_bins=25, score_name=c,
  485. random_state=0, copy=False, use_raw=None)
  486. adata.obs.loc[adata.obs[c] < 0.75, c] = 0
  487. adata.obs.loc[adata.obs[c] < 0.75, c] = 0
  488. adata.obs.loc[adata.obs[c] >= 0.75, c] = 1
  489. adata.obs.loc[adata.obs[c] >= 0.75, c] = 1
  490. adata.obs.to_csv(f'{save_folder}' + sample + "_CS_valuesMeta.csv")
  491. plot_CT_heatmaps(adata, cts, sample + 'CS')
  492. def plot_CT_heatmaps(adata, cts, sample):
  493. """
  494. Normalizes the cell type enrichment scores in sample based on Domains, Niche by boundary and Niche by tissuetag and visualises as heatmap
  495. Parameters:
  496. adata: spatial data
  497. cts: list of cell type names
  498. sample: sample name
  499. Returns:
  500. writes the cell type specificity score for all the spatial spots and cell type combination to a csv file
  501. """
  502. adata_meta = adata.obs
  503. meta_niche = adata_meta.groupby('Domain')[cts].sum()
  504. dfMax = meta_niche.max(axis=0) ### NOrmalize to 0-1 for each cell type
  505. meta_niche = meta_niche.divide(dfMax, axis=1)
  506. meta_niche[meta_niche ==np.nan] =0
  507. #print(meta_niche)
  508. t = meta_niche.sum(axis = 0)
  509. meta_niche.to_csv(f'{save_folder}' + sample + "_domain.csv")
  510. sub = meta_niche[meta_niche.index.isin (['C','M','S' ])]
  511. sns.clustermap(sub, row_cluster= False, col_cluster=False,
  512. cmap="viridis", figsize=(10,4)).savefig(f'{save_folder}' + sample + "_heatmap.pdf")
  513. adata_meta = adata.obs
  514. meta_niche = adata_meta.groupby('Niche')[cts].sum()
  515. dfMax = meta_niche.max(axis=0) ### NOrmalize to 0-1 for each cell type
  516. meta_niche = meta_niche.divide(dfMax, axis=1)
  517. meta_niche[meta_niche ==np.nan] =0
  518. #print(meta_niche)
  519. t = meta_niche.sum(axis = 0)
  520. meta_niche.to_csv(f'{save_folder}' + sample + "_niche.csv")
  521. # sub = meta_niche[meta_niche.index.isin (['C1','C2','C3','C4','M1','M2','M3','S1','S2','S3','S4' ])]
  522. sns.clustermap(sub, row_cluster= False, col_cluster=False,
  523. cmap="viridis", figsize=(10,4)).savefig(f'{save_folder}' + sample + "_niche_heatmap.pdf")
  524. adata_meta = adata.obs
  525. meta_niche = adata_meta.groupby('Niche_bysegment')[cts].sum() #Niche by boundary
  526. dfMax = meta_niche.max(axis=0) ### NOrmalize to 0-1 for each cell type
  527. meta_niche = meta_niche.divide(dfMax, axis=1)
  528. meta_niche[meta_niche ==np.nan] =0
  529. t = meta_niche.sum(axis = 0)
  530. meta_niche.to_csv(f'{save_folder}' + sample + "_Niche_bysegment.csv")
  531. sns.clustermap(meta_niche, row_cluster= False, col_cluster=False,
  532. cmap="viridis", figsize=(10,4)).savefig(f'{save_folder}' + sample + "_segment_heatmap.pdf")
  533. adata_meta = adata.obs
  534. meta_niche = adata_meta.groupby('Cell_group')[cts].sum() #Niche by tissuetag
  535. dfMax = meta_niche.max(axis=0) ### NOrmalize to 0-1 for each cell type
  536. meta_niche = meta_niche.divide(dfMax, axis=1)
  537. meta_niche[meta_niche ==np.nan] =0
  538. t = meta_niche.sum(axis = 0)
  539. meta_niche.to_csv(f'{save_folder}' + sample + "_Cell_group.csv")
  540. sns.clustermap(meta_niche, row_cluster= False, col_cluster=False,
  541. cmap="viridis", figsize=(10,4)).savefig(f'{save_folder}' + sample + "_Cell_group_heatmap.pdf")
  542. def rctd_score(adata, cts, sample, rctd):
  543. """
  544. Summarizes the RCTD cell type values
  545. Parameters:
  546. adata: spatial data
  547. cts: list of cell type names
  548. sample: sample name
  549. rctd: RCTD meta data
  550. Returns:
  551. calls cell type enrichment plots function for RCTD
  552. """
  553. adata.obs[cts] = rctd[cts].to_numpy()
  554. plot_CT_heatmaps(adata, cts, sample + 'RCTD')
  555. # %%
  556. def plot_spatialGeneExpression(adata, save_folder, sample, svalue):
  557. """
  558. Plotting functions for sptaial gene expression, clusters and niches.
  559. Parameters:
  560. adata: spatial data
  561. save_folder: folder to save plots
  562. sample: sample name
  563. svalue: spot size for spatial plotting function
  564. Returns:
  565. saves spatial plots in pdf and png for publication
  566. """
  567. with plt.rc_context(): # Use this to set figure params like size and dpi
  568. plt.rcParams['figure.dpi'] = 300
  569. plt.rcParams["figure.figsize"] = (3,3)
  570. sc.pl.embedding(adata, basis="spatial",
  571. color=['leiden_clusters'],
  572. s=svalue,
  573. show=False,
  574. color_map='Reds'
  575. )
  576. plt.savefig(f"{save_folder}" + sample + "leiden.png", bbox_inches="tight")
  577. plt.savefig(f"{save_folder}" + sample + "leiden.pdf", bbox_inches="tight")
  578. sc.pl.embedding(adata, basis="spatial",
  579. color=['Domain'],
  580. s=svalue, palette=domain_color,
  581. show=False,
  582. color_map='Reds'
  583. )
  584. plt.savefig(f"{save_folder}" + sample + "domain.png", bbox_inches="tight")
  585. plt.savefig(f"{save_folder}" + sample + "domain.pdf", bbox_inches="tight")
  586. sc.pl.embedding(adata, basis="spatial",
  587. color=[ 'Niche', 'Niche_bysegment', 'Cell_group'],
  588. s=svalue, palette=niche_color,
  589. show=False,
  590. color_map='Reds'
  591. )
  592. plt.savefig(f"{save_folder}" + sample + "groups.png", bbox_inches="tight")
  593. plt.savefig(f"{save_folder}" + sample + "groups.pdf", bbox_inches="tight")
  594. gene_list = ['CD4', 'CD8A', 'PRSS16', 'AIRE', 'CD34', 'MS4A1', 'CD83', 'CD14', 'COL1A2']
  595. nrow=1
  596. ncol=len(gene_list)
  597. fig,axs=plt.subplots(nrow,ncol,figsize=(18,2), dpi=100)
  598. # Plot expression for every marker on the corresponding Axes object
  599. col_idx=0
  600. row_idx=0
  601. for marker in gene_list:
  602. ax=axs[col_idx]
  603. sc.pl.embedding(adata, basis="spatial",
  604. color=marker,
  605. s=svalue, ax=ax,frameon=False,
  606. show=False,
  607. color_map='Reds')
  608. col_idx+=1
  609. # Alignment within the Figure
  610. fig.tight_layout()
  611. plt.savefig(f"{save_folder}" + sample + "markers.png", bbox_inches="tight")
  612. plt.savefig(f"{save_folder}" + sample + "marker.pdf", bbox_inches="tight")
  613. # %%
  614. def find_HC_regions(adata, save_folder, sample):
  615. """
  616. Annotating the spots with high KRT1 gene expression
  617. Parameters:
  618. adata: spatial data
  619. save_folder: folder to save plots
  620. sample: sample name
  621. Returns:
  622. saves meta data with KRT1 region information
  623. """
  624. cp_list = ['Sample', 'leiden_clusters', 'Domain', 'Niche', 'Niche_bysegment', 'Cell_group']
  625. adata.obs[cp_list] = meta[cp_list].to_numpy()
  626. adata.obs[cp_list] = adata.obs[cp_list].astype('category')
  627. adata.obs['Niche_bysegment_HC'] = adata.obs.Niche_bysegment.to_numpy()
  628. adata.obs['Niche_bysegment_HC'] = adata.obs.Niche_bysegment.to_numpy()
  629. adata.obs['Niche_bysegment_HC_M'] = adata.obs.Niche_bysegment.to_numpy()
  630. sub_adata = adata[adata[: , 'KRT1'].X > 0, :]
  631. sub_adata = sub_adata[sub_adata.obs.Domain.isin(['LQ', 'S']) ]
  632. sub_adataM = adata[adata[: , 'KRT1'].X > 0, :]
  633. sub_adataM = sub_adataM[sub_adataM.obs.Domain.isin(['LQ', 'S', 'M']) ]
  634. x = list(adata[adata.obs.index.isin(sub_adata.obs.index)].obs_names)
  635. adata.obs.loc[ x, 'Niche_bysegment_HC'] = 'KRT1+'
  636. x = list(adata[adata.obs.index.isin(sub_adataM.obs.index)].obs_names)
  637. adata.obs.loc[ x, 'Niche_bysegment_HC_M'] = 'KRT1+'
  638. sub_adata = adata[adata[: , 'KRT1'].X > 10, :]
  639. sub_adata = sub_adata[sub_adata.obs.Domain.isin(['LQ', 'S']) ]
  640. sub_adataM = adata[adata[: , 'KRT1'].X > 10, :]
  641. sub_adataM = sub_adataM[sub_adataM.obs.Domain.isin(['LQ', 'S', 'M']) ]
  642. x = list(adata[adata.obs.index.isin(sub_adata.obs.index)].obs_names)
  643. adata.obs.loc[ x, 'Niche_bysegment_HC'] = 'KRT1++'
  644. x = list(adata[adata.obs.index.isin(sub_adataM.obs.index)].obs_names)
  645. adata.obs.loc[ x, 'Niche_bysegment_HC_M'] = 'KRT1++'
  646. with plt.rc_context(): # Use this to set figure params like size and dpi
  647. plt.rcParams['figure.dpi'] = 300
  648. plt.rcParams["figure.figsize"] = (3,3)
  649. sc.pl.embedding(adata, basis="spatial", palette= HC_niche_color,
  650. color=['Niche_bysegment', 'Niche_bysegment_HC', 'Niche_bysegment_HC_M'], s=4)
  651. plt.savefig(f"{save_folder}" + sample + "groupsHC.png", bbox_inches="tight")
  652. plt.savefig(f"{save_folder}" + sample + "groupsHC.pdf", bbox_inches="tight")
  653. adata.obs.to_csv(f"{save_folder}" + sample + "_niche_HC.csv")
  654. print(adata.obs.Niche_bysegment_HC.value_counts())
  655. print(adata.obs.Niche_bysegment_HC_M.value_counts())
  656. # %%
  657. targets = blitz.enrichr.get_library("GO_Biological_Process_2023")
  658. def find_GO(adata, region):
  659. """
  660. Determine the differential gene ontology (GO) biological process terms y Domains or Niches
  661. Parameters:
  662. adata: spatial data
  663. save_folder: folder to save plots
  664. sample: sample name
  665. Returns:
  666. returns top 10 GO for each group as dataframe
  667. """
  668. d2c.score(adata, targets=targets, use_raw=True)
  669. sc.tl.rank_genes_groups(adata.uns['drug2cell'], groupby=region, method='wilcoxon')
  670. # Convert results to a pandas DataFrame
  671. df = pd.DataFrame({
  672. group: adata.uns['drug2cell'].uns['rank_genes_groups']['names'][group][:10]
  673. for group in adata.uns['drug2cell'].uns['rank_genes_groups']['names'].dtype.names
  674. })
  675. return (df)
  676. # %%
  677. def ThreeGene_plot(adata, gene, name):
  678. """
  679. Plot spatial three genes in RGB colours and also co-localization by the overlap of 2 colours
  680. Parameters:
  681. adata: spatial data
  682. gene: combination of genes
  683. name: file name
  684. Returns:
  685. spatial plots in png and pdf
  686. """
  687. combinations = gene
  688. for i in range(len(combinations)):
  689. cc = combinations[i]
  690. sc.tl.score_genes(adata, [cc[0]], ctrl_size=50,
  691. gene_pool=None, n_bins=25, score_name="1",
  692. random_state=0, copy=False, use_raw=None)
  693. sc.tl.score_genes(adata, [cc[1]], ctrl_size=50,
  694. gene_pool=None, n_bins=25, score_name="2",
  695. random_state=0, copy=False, use_raw=None)
  696. sc.tl.score_genes(adata, [cc[2]], ctrl_size=50,
  697. gene_pool=None, n_bins=25, score_name="3",
  698. random_state=0, copy=False, use_raw=None)
  699. adata.obs['1'] = adata.obs['1'] / max(adata.obs['1'])
  700. adata.obs['2'] = adata.obs['2'] / max(adata.obs['2'])
  701. adata.obs['3'] = adata.obs['3'] / max(adata.obs['3'])
  702. adata.obs.loc[adata.obs['1'] < 0.1, '1'] = 0
  703. adata.obs.loc[adata.obs['2'] < 0.1, '2'] = 0
  704. adata.obs.loc[adata.obs['3'] < 0.1, '3'] = 0
  705. adata.obs.loc[adata.obs['1'] >= 0.1, '1'] = 1
  706. adata.obs.loc[adata.obs['2'] >= 0.1, '2'] = 1
  707. adata.obs.loc[adata.obs['3'] >= 0.1, '3'] = 1
  708. adata.obs['Colour3'] = 'k'
  709. adata.obs['Colour3'][(adata.obs['1'] == 0) & (adata.obs['2'] == 0) & (adata.obs['3'] == 0)] = np.nan
  710. adata.obs['Colour3'][(adata.obs['1'] == 1) & (adata.obs['2'] == 0) & (adata.obs['3'] == 0)] = 'r'
  711. adata.obs['Colour3'][(adata.obs['1'] == 0) & (adata.obs['2'] == 1) & (adata.obs['3'] == 0)] = 'g'
  712. adata.obs['Colour3'][(adata.obs['1'] == 0) & (adata.obs['2'] == 0) & (adata.obs['3'] == 1)] = 'b'
  713. adata.obs['Colour3'][(adata.obs['1'] == 1) & (adata.obs['2'] == 1) & (adata.obs['3'] == 0)] = 'y'
  714. adata.obs['Colour3'][(adata.obs['1'] == 1) & (adata.obs['2'] == 0) & (adata.obs['3'] == 1)] = 'm'
  715. adata.obs['Colour3'][(adata.obs['1'] == 0) & (adata.obs['2'] == 1) & (adata.obs['3'] == 1)] = 'c'
  716. adata.obs['Colour3'][(adata.obs['1'] == 1) & (adata.obs['2'] == 1) & (adata.obs['3'] == 1)] = 'k'
  717. with plt.rc_context():
  718. plt.rcParams['figure.dpi'] = 4000
  719. plt.rcParams["figure.figsize"] = (2, 2)
  720. sc.pl.embedding(adata, basis="spatial",
  721. color="Colour3", s=0.35, show=False,
  722. palette=mcolors.BASE_COLORS, na_color='whitesmoke')
  723. plt.savefig(f"{name}_{cc}_50_4000dpi.png", bbox_inches="tight", format="png")
  724. plt.savefig(f"{name}_{cc}_50_4000dpi.pdf", bbox_inches="tight", format="pdf" )
  725. # %%

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

Overview

Authors: Uma S. Kamaraj1, Ying Chen1, Junjie Lei1, Pradeep Gautam1, Pongsatorn Horcharoensuk1,2, Czaryna K. M. Clemente3, Katja G. Weinacht4, Nicholas R. J. Gascoigne5,6,7,8, Jinmiao Chen9,10, Ching Kit Chen3,11, Qingfeng Chen1,9, Qi-Jing Li1,9, Lai Guan Ng12, Yuin-Han Loh1,2,8,13
13 affiliations
  1. Institute of Molecular and Cell Biology (IMCB), Agency for Science, Technology and Research (A*STAR),Singapore, Republic of Singapore
  2. Department of Physiology, NUS Yong Loo Lin School of Medicine,Singapore, Singapore
  3. Department of Pediatrics, Yong Loo Lin School of Medicine, National University of Singapore,Singapore, Singapore
  4. Department of Pediatrics, Division of Stem Cell Transplantation and Regenerative Medicine, Stanford University,Stanford, CA USA
  5. Immunology Translational Research Programme, Yong Loo Lin School of Medicine, National University of Singapore,Singapore, Singapore
  6. Department of Microbiology and Immunology, Yong Loo Lin School of Medicine, National University of Singapore,Singapore, Singapore
  7. Cancer Translational Research Programme, Yong Loo Lin School of Medicine, National University of Singapore,Singapore, Singapore
  8. NUS Graduate School’s Integrative Sciences and Engineering Programme, National University of Singapore,Singapore, Singapore
  9. Singapore Immunology Network (SIgN), Agency for Science, Technology and Research (A*STAR),Singapore, Singapore
  10. Immunology Translational Research Program, Department of Microbiology and Immunology, Yong Loo Lin School of Medicine, National University of Singapore,Singapore, Singapore
  11. Division of Cardiology, Department of Paediatrics, Khoo Teck Puat-National University Children’s Medical Institute, National University Health System,Singapore, Singapore
  12. Shanghai Immune Therapy Institute, School of Medicine, Shanghai Jiao Tong University, Renji Hospital,Shanghai, China
  13. Department of Biological Sciences, National University of Singapore,Singapore, Singapore
Journal: Nature communications, volume 17, issue 1, article 3721
Dates: received 25 June 2024; accepted 12 January 2026; published online 10 March 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41467-026-68596-w · PMID 41807357 · PMCID PMC13102919 · OpenAlex W7134846924
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: genetics / omics (modality), human (organism), cellular / molecular (subfield)
Methods: Smoothing, state filtering, decompositions, Machine learning, Preprocessing, fMRI & imaging
Keywords: Thymus, Systems analysis, Imaging the immune system, Transcriptomics
MeSH: Epithelial Cells*, Thymus Gland*, Transcription Factors*, B-Lymphocytes, Cell Lineage, Child, Child, Preschool, Dendritic Cells, Fetus, Gene Expression Profiling, Gene Expression Regulation, Developmental, Humans, Proteomics, Spatial Transcriptomics, Thymocytes (* major topic)
Topic: Myasthenia Gravis and Thymoma (Neurology, Medicine), according to OpenAlex
Citations: cited by 2 papers (Europe PMC); 65 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.

Repositories

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

UmaSangumathi/mimeTFs

License: none: the authors keep all their rights
State: the link answers, verified on 30 September 2026
Evidence: files inventoried
Commit: 6d1e67b8430c94e17b7bbe2803ed279995eef5d7, 6 October 2025
Languages: Jupyter (11), R (1)
Size: 14 files, 12 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, environment (requirements.txt), 12 notebooks
Not found: license file, CITATION.cff, tests, continuous integration, documentation
Tools: Matplotlib (2 files), NumPy (2 files), Scanpy (2 files), pandas (1 file), PyTorch (1 file), Squidpy (1 file)
Availability: 1 check, the latest on 30 September 2026: the link answers
  • 30 September 2026: the link answers
2 files

Zenodo 17851510

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: data.table (2 files), ggplot2 (2 files), Matplotlib (2 files), NumPy (2 files), pandas (2 files), Scanpy (2 files), Seurat (2 files), tidyverse (2 files), anndata (1 file), clusterProfiler (1 file), cowplot (1 file), h5py (1 file), NetworkX (1 file), PyTorch (1 file), reshape2 (1 file), scikit-image (1 file), scikit-learn (1 file), SciPy (1 file), seaborn (1 file)
Availability: 1 check, the latest on 30 September 2026: the link answers (HTTP 200)
  • 30 September 2026: the link answers (HTTP 200)
7 files
At the source:

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/s41467-026-68596-w.

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:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 9 scripts, each with its path and the digest of its content;
  • 15 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

Datasets cited

Data availability statement

The paper has a 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/s41467-026-68596-w.

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, 14 authors, 4 keywords, 15 MeSH terms, 6 funders, 64 references.

Cite

This paper

Kamaraj, U. S., Chen, Y., Lei, J., Gautam, P., Horcharoensuk, P., Clemente, C. K. M., Weinacht, K. G., Gascoigne, N. R. J., Chen, J., Chen, C. K., Chen, Q., Li, Q.-J., Ng, L. G., & Loh, Y.-H. (2026). Spatial cartography of human thymus enables the geopositioning of lineage transcription factors in rare mimetic thymic epithelial cells. Nature communications, 17(1), 3721. https://doi.org/10.1038/s41467-026-68596-w

BibTeX

@article{kamaraj2026spatial,
author = {Kamaraj, Uma S. and Chen, Ying and Lei, Junjie and Gautam, Pradeep and Horcharoensuk, Pongsatorn and Clemente, Czaryna K. M. and Weinacht, Katja G. and Gascoigne, Nicholas R. J. and Chen, Jinmiao and Chen, Ching Kit and Chen, Qingfeng and Li, Qi-Jing and Ng, Lai Guan and Loh, Yuin-Han},
title = {{Spatial cartography of human thymus enables the geopositioning of lineage transcription factors in rare mimetic thymic epithelial cells}},
journal = {Nature communications},
year = {2026},
month = mar,
volume = {17},
number = {1},
pages = {3721},
publisher = {Nature Publishing Group},
issn = {2041-1723},
doi = {10.1038/s41467-026-68596-w},
url = {https://doi.org/10.1038/s41467-026-68596-w},
pmid = {41807357},
pmcid = {PMC13102919}
}

RIS

TY - JOUR
AU - Kamaraj, Uma S.
AU - Chen, Ying
AU - Lei, Junjie
AU - Gautam, Pradeep
AU - Horcharoensuk, Pongsatorn
AU - Clemente, Czaryna K. M.
AU - Weinacht, Katja G.
AU - Gascoigne, Nicholas R. J.
AU - Chen, Jinmiao
AU - Chen, Ching Kit
AU - Chen, Qingfeng
AU - Li, Qi-Jing
AU - Ng, Lai Guan
AU - Loh, Yuin-Han
TI - Spatial cartography of human thymus enables the geopositioning of lineage transcription factors in rare mimetic thymic epithelial cells
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/03/10
VL - 17
IS - 1
SP - 3721
SN - 2041-1723
PB - Nature Publishing Group
DO - 10.1038/s41467-026-68596-w
UR - https://doi.org/10.1038/s41467-026-68596-w
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41467-026-68596-w",
"type": "article-journal",
"title": "Spatial cartography of human thymus enables the geopositioning of lineage transcription factors in rare mimetic thymic epithelial cells",
"container-title": "Nature communications",
"author": [
{
"family": "Kamaraj",
"given": "Uma S."
},
{
"family": "Chen",
"given": "Ying"
},
{
"family": "Lei",
"given": "Junjie"
},
{
"family": "Gautam",
"given": "Pradeep"
},
{
"family": "Horcharoensuk",
"given": "Pongsatorn"
},
{
"family": "Clemente",
"given": "Czaryna K. M."
},
{
"family": "Weinacht",
"given": "Katja G."
},
{
"family": "Gascoigne",
"given": "Nicholas R. J."
},
{
"family": "Chen",
"given": "Jinmiao"
},
{
"family": "Chen",
"given": "Ching Kit"
},
{
"family": "Chen",
"given": "Qingfeng"
},
{
"family": "Li",
"given": "Qi-Jing"
},
{
"family": "Ng",
"given": "Lai Guan"
},
{
"family": "Loh",
"given": "Yuin-Han"
}
],
"container-title-short": "Nat Commun",
"volume": "17",
"issue": "1",
"page": "3721",
"DOI": "10.1038/s41467-026-68596-w",
"PMID": "41807357",
"PMCID": "PMC13102919",
"ISSN": "2041-1723",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41467-026-68596-w",
"language": "en",
"issued": {
"date-parts": [
[
2026,
3,
10
]
]
}
}

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.xcrm.2026.102766 [code]
A longitudinal single-cell and spatial multiomic atlas of pediatric high-grade glioma.
Journal: Cell reports. Medicine
In common: anndata, clusterProfiler, Scanpy, 15 other tools, genetics / omics, cellular / molecular, 5 references
[2] doi:10.1038/s42003-026-10034-0 [code]
Region- and cell type-specific changes in gene expression in the cerebellum after classical fear conditioning.
Journal: Communications biology
In common: Squidpy, anndata, clusterProfiler, 13 other tools, genetics / omics, cellular / molecular, 3 references
[3] doi:10.1186/s13059-026-04177-w [code]
Genomic sequence evolution underlying human neocortical interareal diversification.
Journal: Genome biology
In common: Squidpy, anndata, Scanpy, 11 other tools, genetics / omics, cellular / molecular, 5 references
[4] doi:10.1038/s41467-026-71803-3 [code]
Charting the transition from in vitro gliogenesis to the in vivo maturation of human glial progenitor cells transplanted into the hypomyelinated mouse brain.
Journal: Nature communications
In common: Squidpy, anndata, Scanpy, 13 other tools, genetics / omics, cellular / molecular, 2 references
[5] doi:10.1093/nar/gkag706 [code]
scDifformer: diffusion-based post-training for virtual cell modeling across large-scale single-cell data.
Journal: Nucleic acids research
In common: Squidpy, anndata, Scanpy, 12 other tools, 3 references
[6] doi:10.21203/rs.3.rs-9676637/v1 [code]
A Comprehensive Benchmarking of Spatial Deconvolution and Domain Detection Methods across Diverse Tissues and Spatial Transcriptomic Technologies
Journal: Research Square (preprint)
In common: Squidpy, anndata, Scanpy, 14 other tools, genetics / omics, 1 reference
[7] doi:10.64898/2026.03.30.714220 [code]
An integrated single cell and spatial omics atlas of human prenatal development
Journal: bioRxiv (preprint)
In common: Squidpy, anndata, Scanpy, 9 other tools, 5 references
[8] doi:10.1038/s41592-026-03194-8 [code]
Beyond benchmarking: an expert-guided consensus approach to spatially aware clustering.
Journal: Nature methods
In common: Squidpy, anndata, Scanpy, 13 other tools, genetics / omics, 2 references
[9] doi:10.1002/imt2.70163 [code]
Spatial multi-omics unveils sphingolipid metabolic reprogramming within the retinal pathological niche.
Journal: iMeta
In common: anndata, clusterProfiler, Scanpy, 13 other tools, genetics / omics, cellular / molecular, 2 references
[10] doi:10.1186/s13073-026-01704-z [code]
Gene expression profiling enables refined parcellation of cortical layers in the heterogeneous human cerebral cortex.
Journal: Genome medicine
In common: anndata, Scanpy, Seurat, 13 other tools, genetics / omics, cellular / molecular, 2 references

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.

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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

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