OSCR

Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive <i>m/z</i> mapping and exploration.

Code ↔ Paper

2 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 2 matches
  1. [1] § MATERIALS AND METHODS › Quantitative evaluation of the MSI visualizations › Evaluation metrics ↔ msi_visual/metrics.py, lines 130–257 · score 0.56 · distance correlation, Pearson, MSI visualization, Euclidean, metric, cosine
  2. [2] § MATERIALS AND METHODS › Visualization methods › Saliency optimization ↔ msi_visual/saliency_opt.py, lines 133–181 · score 0.51 · soft ranking, PyTorch, saliency, optimization

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

Python · 268 lines · 11 KB · MIT · 1 match

  1. import scipy
  2. from msi_visual.normalization import spatial_total_ion_count, total_ion_count, median_ion
  3. from sklearn.metrics.pairwise import euclidean_distances, cosine_similarity
  4. from scipy.stats import entropy
  5. import random
  6. import time
  7. import sys
  8. import numpy as np
  9. import matplotlib
  10. from PIL import Image
  11. import matplotlib.pyplot as plt
  12. import cv2
  13. from zadu import zadu
  14. from sklearn.manifold import trustworthiness
  15. def smoothness_saliency_metrics(cosine, maxabs, outputs):
  16. max_rank = np.maximum(
  17. cosine.argsort().argsort(),
  18. maxabs.argsort().argsort())
  19. cosine_rank = cosine.argsort().argsort()
  20. result_rank = outputs.argsort().argsort()
  21. result = {}
  22. corr_cosine = scipy.stats.pearsonr(cosine, outputs).statistic
  23. corr_maxabs = scipy.stats.pearsonr(maxabs, outputs).statistic
  24. spearman_cosine = scipy.stats.spearmanr(cosine, outputs).statistic
  25. spearman_maxabs = scipy.stats.spearmanr(maxabs, outputs).statistic
  26. N = len(outputs)
  27. for gamma in [0, 2.0]:
  28. #max_rank = max_rank + 1e-6
  29. saliency_30 = (((result_rank - max_rank + N * 0.3) > 0)
  30. * max_rank**gamma).sum() / sum(max_rank**gamma)
  31. saliency_20 = (((result_rank - max_rank + N * 0.2) > 0)
  32. * max_rank**gamma).sum() / sum(max_rank**gamma)
  33. saliency_10 = (((result_rank - max_rank + N * 0.1) > 0)
  34. * max_rank**gamma).sum() / sum(max_rank**gamma)
  35. smoothness_30 = (((cosine_rank - result_rank - N * 0.3) < 0)
  36. * (N - cosine_rank)**gamma).sum() / sum((N - cosine_rank)**gamma)
  37. smoothness_20 = (((cosine_rank - result_rank - N * 0.2) < 0)
  38. * (N - cosine_rank)**gamma).sum() / sum((N - cosine_rank)**gamma)
  39. smoothness_10 = (((cosine_rank - result_rank - N * 0.1) < 0)
  40. * (N - cosine_rank)**gamma).sum() / sum((N - cosine_rank)**gamma)
  41. saliency_20 = (((result_rank - max_rank + N * 0.2) > 0)
  42. * max_rank**gamma).sum() / sum(max_rank**gamma)
  43. result[f"Saliency Δ=20% gamma={gamma}"] = saliency_20
  44. result[f"Smoothness Δ=20% gamma={gamma}"] = smoothness_20
  45. result[f"Saliency Δ=30% gamma={gamma}"] = saliency_30
  46. result[f"Smoothness Δ=30% gamma={gamma}"] = smoothness_30
  47. result[f"Saliency Δ=10% gamma={gamma}"] = saliency_10
  48. result[f"Smoothness Δ=10% gamma={gamma}"] = smoothness_10
  49. result[f"Avg. Saliency gamma={gamma}"] = (saliency_10 + saliency_20 + saliency_30) / 3
  50. result[f"Avg. Smoothness gamma={gamma}"] = (smoothness_10 + smoothness_20 + smoothness_30) / 3
  51. result["Correlation Cosine"] = corr_cosine
  52. result["Correlation L-∞"] = corr_maxabs
  53. result["Spearman Cosine"] = spearman_cosine
  54. result["Spearman L-∞"] = spearman_maxabs
  55. return result
  56. class RandomPairSampler:
  57. def __init__(self, img, num_samples, mask):
  58. self.pairs = self.generate_pairs(img, num_samples, mask)
  59. def generate_pairs(self, img, num_samples, mask):
  60. nrow, ncol = img.shape[0], img.shape[1]
  61. points = np.mgrid[:nrow, :ncol].reshape(2, -1).T
  62. points = list(points)
  63. img_mask = np.uint8(img.max(axis=-1) > 0) * 255
  64. if mask is not None:
  65. img_mask[mask == 0] = 0
  66. points = [(a, b) for a, b in points if img_mask[a, b] > 0]
  67. pairs = []
  68. for _ in range(min(len(points), num_samples)):
  69. point_a = random.choice(points)
  70. point_b = random.choice(points)
  71. pairs.append((point_a, point_b))
  72. return pairs
  73. def get_input_distances(self, img):
  74. data = {}
  75. distances = ["L-2", "Cosine", "L-∞", "Output"]
  76. for distance in distances:
  77. data[distance] = []
  78. for index, (point_a, point_b) in enumerate(self.pairs):
  79. a, b = img[point_a[0], point_a[1]], img[point_b[0], point_b[1]]
  80. data["L-2"].append(np.linalg.norm(a - b, 2))
  81. data['Cosine'].append(
  82. 1 -
  83. cosine_similarity(
  84. np.array(
  85. [a]),
  86. np.array(
  87. [b]))[
  88. 0,
  89. 0])
  90. data['L-∞'].append(np.abs(a - b).max())
  91. for key in data:
  92. data[key] = np.float32(data[key])
  93. return data
  94. def get_output_distance(self, visualization):
  95. result = []
  96. for point_a, point_b in self.pairs:
  97. a, b = visualization[point_a[0], point_a[1]
  98. ], visualization[point_b[0], point_b[1]]
  99. a = np.float32(a)
  100. b = np.float32(b)
  101. d = np.linalg.norm(a - b, 2)
  102. result.append(d)
  103. return np.float32(result)
  104. class MSIVisualizationMetrics:
  105. def __init__(self, normalized, visualization, mask=None, num_samples=30000):
  106. self.img_mask = np.uint8(normalized.max(axis=-1) > 0) * 255
  107. self.img_mask_reshaped = self.img_mask.reshape(self.img_mask.shape[0] * self.img_mask.shape[1])
  108. indices = [i for i in range(len(self.img_mask_reshaped)) if self.img_mask_reshaped[i] > 0]
  109. if len(indices) <= num_samples:
  110. self.random_indices = indices
  111. else:
  112. self.random_indices = random.sample(indices, num_samples // 5)
  113. self.data_subset = normalized.reshape(-1, normalized.shape[-1])
  114. self.visualization_subset = visualization.reshape((self.data_subset.shape[0], -1))
  115. self.data_subset = self.data_subset[self.random_indices]
  116. self.visualization_subset = self.visualization_subset[self.random_indices]
  117. self.sampler = RandomPairSampler(normalized, num_samples, mask)
  118. self.data = self.generate_input_output_samples(
  119. normalized, cv2.cvtColor(
  120. visualization, cv2.COLOR_RGB2LAB), self.sampler)
  121. def generate_input_output_samples(
  122. self, normalized, visualization, sampler):
  123. data = sampler.get_input_distances(normalized)
  124. data["Output"] = sampler.get_output_distance(visualization)
  125. return data
  126. def get_metrics(self):
  127. cosine = self.data["Cosine"]
  128. maxabs = self.data["L-∞"]
  129. outputs = self.data["Output"]
  130. metrics = smoothness_saliency_metrics(cosine, maxabs, outputs)
  131. spec = [{"id": "mrre", "params": { "k": 100 },}, {"id": "lcmc", "params": { "k": 100 }}]
  132. t0 = time.time()
  133. scores = zadu.ZADU(spec, self.data_subset).measure(self.visualization_subset)
  134. for zadu_metric in scores:
  135. for m in zadu_metric:
  136. metrics[m] = zadu_metric[m]
  137. print("zadu took", time.time() - t0)
  138. t0 = time.time()
  139. trustworthiness_score = trustworthiness(self.data_subset, self.visualization_subset, metric='euclidean', n_neighbors=100)
  140. trustworthiness_score_chevbyshev = trustworthiness(self.data_subset, self.visualization_subset, metric='chebyshev', n_neighbors=100)
  141. metrics["Trustworthiness"] = trustworthiness_score
  142. metrics["Trustworthiness L-∞"] = trustworthiness_score_chevbyshev
  143. print(time.time() - t0, "trustwo")
  144. return metrics
  145. def get_correlation_scatter_plot(self, title=None):
  146. cosine = self.data["Cosine"]
  147. maxabs = self.data["L-∞"]
  148. outputs = self.data["Output"]
  149. metrics = self.get_metrics()
  150. fig = plt.figure()
  151. ax = fig.add_subplot()
  152. max_rank = np.maximum(
  153. cosine.argsort().argsort(),
  154. maxabs.argsort().argsort())
  155. # corr = scipy.stats.pearsonr(max_rank, outputs).statistic
  156. expected_rank = max_rank
  157. result_rank = outputs.argsort().argsort()
  158. diff_rank = np.abs(result_rank - expected_rank)
  159. cm = matplotlib.pyplot.get_cmap("RdYlGn_r")
  160. colors = cm(np.linspace(0, 1, len(outputs)))
  161. N = len(diff_rank) // 2
  162. cs = [colors[diff_rank[i]]
  163. for i in range(len(outputs))] # could be done with numpy's repmat
  164. matplotlib.pyplot.scatter(cosine, maxabs, color=cs, s=10, alpha=0.5)
  165. sm = plt.cm.ScalarMappable(cmap=cm)
  166. sm.set_clim(vmin=0, vmax=1)
  167. plt.colorbar(sm, ax=plt.gca())
  168. ax.set_xlabel('m/z values Cosine distance')
  169. ax.set_ylabel('m/z values L-∞ distance')
  170. if title:
  171. ax.set_title(title)
  172. for name, value in metrics.items():
  173. plt.plot([], [], ' ', label=f"{name} {value:.3f}")
  174. plt.legend()
  175. return fig
  176. def get_correlation_plot(self, title=None):
  177. cosine = self.data["Cosine"]
  178. maxabs = self.data["L-∞"]
  179. outputs = self.data["Output"]
  180. fig, ax = plt.subplots()
  181. for inputs, name in zip([cosine, maxabs], ["Cosine", "L-∞"]):
  182. sorted_distances = sorted(inputs)
  183. indices = list(
  184. range(
  185. len(sorted_distances) // 10,
  186. len(sorted_distances),
  187. len(sorted_distances) // 10))
  188. indices.append(len(sorted_distances) - 1)
  189. graph_distances, graph_corrs = [], []
  190. for index in indices:
  191. d = sorted_distances[index]
  192. relevant_indices = [
  193. i for i in range(
  194. len(inputs)) if inputs[i] < d]
  195. corr = scipy.stats.pearsonr(
  196. inputs[relevant_indices],
  197. outputs[relevant_indices]).statistic
  198. graph_distances.append(
  199. int(100 * index / len(sorted_distances)))
  200. graph_corrs.append(corr)
  201. plt.plot(graph_distances, graph_corrs, label=name)
  202. plt.legend()
  203. if title:
  204. plt.title(
  205. 'Visualization distance correlation with spectra\n' +
  206. title)
  207. else:
  208. plt.title('Visualization distance correlation with spectra')
  209. plt.xlabel('Maximum input distance percentile')
  210. plt.ylabel('Pearson rank correlation')
  211. ax.set_yticks(list(np.arange(0, np.max(corr) + 0.05, 0.05)))
  212. return fig
  213. if __name__ == "__main__":
  214. img = np.load(sys.argv[1])
  215. visualization = np.array(Image.open(sys.argv[2]))
  216. normalized = total_ion_count(img)
  217. random.seed(0)
  218. metrics = MSIVisualizationMetrics(normalized, visualization)
  219. print(metrics.get_metrics())
  220. metrics.get_correlation_scatter_plot()
  221. plt.show()

metrics.py, under MIT · at the source

Overview

Authors: Jacob Gildenblat1, Jens Pahnke1,2,3,4,5,6
  1. Pahnke Lab, Oslo, Norway
  2. Translational Neurodegeneration Research and Neuropathology Lab, Department of Clinical Medicine, Medical Faculty, University of Oslo, Sognsvannsveien 20, Oslo NO-0372, Norway
  3. Section of Neuropathology Research, Department of Pathology, Division of Laboratory Medicine, Oslo University Hospital, Sognsvannsveien 20, Oslo NO-0372, Norway
  4. Institute of Nutritional Medicine, University of Lübeck and University Medical Center Schleswig-Holstein, Ratzeburger Allee 160, Lübeck D-23538, Germany
  5. Department of Neuromedicine and Neuroscience, The Faculty of Medicine and Life Sciences, University of Latvia, Jelgavas iela 3, Rīga LV-1004, Latvia
  6. Department of Neurobiology, School of Neurobiology, Biochemistry and Biophysics, The Georg S. Wise Faculty of Life Sciences, Tel Aviv University, G. S. Wise Street, Ramat Aviv IL-6997801, Israel
Institutions: Oslo University Hospital (Norway); Tel Aviv University (Israel); University of Oslo (Norway); University of Latvia (Latvia); University of Lübeck (Germany)
Journal: Science advances, volume 12, issue 35, article eaed3650
Dates: received 24 October 2025; accepted 17 July 2026; published online 26 August 2026; in print August 2026
Type: Research article · Language: English
License: CC BY-NC
Identifiers: DOI 10.1126/sciadv.aed3650 · PMID 42647616 · PMCID PMC13510675 · OpenAlex W7204261474
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: genetics / omics (modality), other (modality), mouse (organism), methods / tools (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions, Machine learning, Connectivity, fMRI & imaging
MeSH: Image Processing, Computer-Assisted*, Mass Spectrometry*, Animals, Brain, Kidney, Lipidomics, Mice, Software (* major topic)
Topic: Mass Spectrometry Techniques and Applications (Spectroscopy, Chemistry), according to OpenAlex
Funding: Helse Sør-Øst RHF (2022046); Norges Forskningsrådet (327571, 295910); Nationalforeningen for folkehelse (Demenspris 2025, Norway); European Innovation Council (OPTIPATH 7D, 101185769)
Citations: not cited yet (Europe PMC); 58 references in the paper

Abstract

Mass spectrometry imaging (MSI) produces high-dimensional molecular data, but practical interpretation remains limited by visualizations that incompletely preserve global structure. We present MSI-VISUAL, an open-source framework for interactive MSI analysis that integrates truthful dimensionality reduction visualizations with region-of-interest selection, statistical comparison, and direct mass/charge ratio (m/z) mapping. MSI-VISUAL introduces four visualization strategies: SALO and SPEAR (optimization-based methods designed to improve global structure preservation across distance metrics) and TOP3 and PR3D (lightweight approaches for memory-efficient, rapid visualization of large datasets). Across benchmarks and lipidomics case studies, including mouse brain and kidney pathology examples, the proposed methods outperform commonly used alternatives in our benchmarks, improve detection of subtle tissue differences, and reveal fine molecular-anatomical patterns that support biological insights. These results establish MSI-VISUAL as a scalable framework for discovery-oriented and diagnostic MSI workflows.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

Repository

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

Zenodo 19465293

License: MIT
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: “Data, code, and materials availability:”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (70 files), Pillow (44 files), OpenCV (43 files), scikit-learn (30 files), Matplotlib (20 files), PyTorch (10 files), SciPy (10 files), pandas (6 files), TensorFlow (5 files), XGBoost (4 files), UMAP (3 files), Keras (2 files), SHAP (2 files), NetworkX (1 file), Numba (1 file), scikit-image (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)
96 files

The paper's code and data availability statement is in the Data section.

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;
  • 94 scripts, each with its path and the digest of its content;
  • 2 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.

Data, code, and materials availability

All data and code needed to evaluate and reproduce the results in the paper are present in the paper and/or the Supplementary Materials. The mouse dataset files are available in PRIDE (https://proteomecentral.proteomexchange.org/cgi/GetDataset?ID=PXD056609). We release the code as an open-source package on Zenodo (https://doi.org/10.5281/zenodo.19465293). This study did not generate new materials.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

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, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 2 authors, 8 MeSH terms, 4 funders, 43 references.

Cite

This paper

Gildenblat, J., & Pahnke, J. (2026). Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive &lt;i&gt;m/z&lt;/i&gt; mapping and exploration. Science advances, 12(35), eaed3650. https://doi.org/10.1126/sciadv.aed3650

BibTeX

@article{gildenblat2026truthful,
author = {Gildenblat, Jacob and Pahnke, Jens},
title = {{Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive \&lt;i\&gt;m/z\&lt;/i\&gt; mapping and exploration}},
journal = {Science advances},
year = {2026},
month = aug,
volume = {12},
number = {35},
pages = {eaed3650},
publisher = {American Association for the Advancement of Science},
issn = {2375-2548},
doi = {10.1126/sciadv.aed3650},
url = {https://doi.org/10.1126/sciadv.aed3650},
pmid = {42647616},
pmcid = {PMC13510675}
}

RIS

TY - JOUR
AU - Gildenblat, Jacob
AU - Pahnke, Jens
TI - Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive &lt;i&gt;m/z&lt;/i&gt; mapping and exploration
T2 - Science advances
J2 - Sci Adv
PY - 2026
DA - 2026/08/26
VL - 12
IS - 35
SP - eaed3650
SN - 2375-2548
PB - American Association for the Advancement of Science
DO - 10.1126/sciadv.aed3650
UR - https://doi.org/10.1126/sciadv.aed3650
LA - en
ER -

CSL-JSON

{
"id": "10.1126/sciadv.aed3650",
"type": "article-journal",
"title": "Truthful visualizations for mass spectrometry imaging enable high-spatial-resolution interactive &lt;i&gt;m/z&lt;/i&gt; mapping and exploration",
"container-title": "Science advances",
"author": [
{
"family": "Gildenblat",
"given": "Jacob"
},
{
"family": "Pahnke",
"given": "Jens"
}
],
"container-title-short": "Sci Adv",
"volume": "12",
"issue": "35",
"page": "eaed3650",
"DOI": "10.1126/sciadv.aed3650",
"PMID": "42647616",
"PMCID": "PMC13510675",
"ISSN": "2375-2548",
"publisher": "American Association for the Advancement of Science",
"URL": "https://doi.org/10.1126/sciadv.aed3650",
"language": "en",
"issued": {
"date-parts": [
[
2026,
8,
26
]
]
}
}

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.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: SHAP, XGBoost, Keras, 13 other tools, mouse
[2] doi:10.1016/j.isci.2026.116825 [code]
Social hierarchy shapes behavioral and transcriptional responses to chronic stress and ketamine in male mice.
Journal: iScience
In common: SHAP, XGBoost, UMAP, 11 other tools, genetics / omics, mouse
[3] doi:10.7554/elife.110588 [code]
Opening the black box toward a modular approach to spike sorting.
Journal: eLife
In common: XGBoost, UMAP, Numba, 10 other tools, methods / tools, mouse
[4] 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: Keras, UMAP, Numba, 10 other tools, genetics / omics
[5] doi:10.3389/fnsys.2026.1822122 [code]
Convergence-divergence circuits for multimodal integration of innate and learned opponent valences.
Journal: Frontiers in systems neuroscience
In common: Keras, UMAP, Numba, 10 other tools
[6] doi:10.1038/s41467-026-72057-9 [code]
Sex-specific behavioral feedback modulates sensorimotor processing and drives flexible social behavior.
Journal: Nature communications
In common: Keras, UMAP, Numba, 10 other tools
[7] doi:10.1371/journal.pcbi.1014571 [code]
SynAPSeg: A novel dataset and image analysis framework for deep learning-based synapse detection and quantification.
Journal: PLoS computational biology
In common: Keras, Numba, TensorFlow, 10 other tools
[8] 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: Keras, UMAP, Numba, 9 other tools
[9] doi:10.1038/s41592-026-03057-2 [code]
CREsted: modeling genomic and synthetic cell-type-specific enhancers across tissues and species.
Journal: Nature methods
In common: Keras, UMAP, Numba, 8 other tools, methods / tools, genetics / omics, mouse
[10] doi:10.1016/j.bpj.2026.06.005 [code]
Curvature-based machine-learning method for automated segmentation of dendritic spines.
Journal: Biophysical journal
In common: SHAP, XGBoost, Keras, 8 other tools

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.