Tissue reconstruction with generative AI
Overview of LUNA
LUNA is a diffusion-based generative model designed to generate spatial locations of cells from their gene expression. Using an attention-based mechanism, LUNA learns how each individual cell should attend to other cells according to their relevance to a cell’s own location and molecular features. During training, LUNA leverages spatial transcriptomics data with ground-truth cell locations to learn to generate cell locations conditioned on gene expression. During inference, the input to LUNA is the gene expression of dissociated cells, and the model then generates cell locations from pure Gaussian noise conditioned on gene expression, enabling inference of cell locations.
In the training phase, the input to LUNA is spatial transcriptomics data from single or multiple slices. LUNA learns cell embeddings that capture both the local and global tissue structure using a multihead self-attention mechanism22,23 that enables cells to learn to attend to other cells. We designed the loss in LUNA as an SE(2)-invariant function75,76,77,78 (it is robust to arbitrary rotations and translations of the predicted locations), only enforcing the preservation of relative distances between cells within each slice.
Training LUNA involves two main steps: (1) a corruption process that iteratively adds noise to the ground-truth cell locations, and (2) a denoising process that generates the ground-truth locations from the noise-corrupted locations. During the denoising process, LUNA learns to reverse the corruption process, gradually transitioning from noisier to less noisy cell locations. LUNA as a generative model is more robust to distribution shifts, compared to a regression model which is prone to overfitting to specific tissue distributions (Supplementary Fig. 35). Another benefit of using generative modeling lies in estimating uncertainty in predictions (Figs. 3c–e and 4h,i).
Learning cell representations
LUNA learns cell representations that capture the relationship between the molecular features of individual cells and their spatial context within tissue. These embeddings form the foundation for predicting the locations of cells.
The model is built on the premise that a cell’s location is influenced not only by its own molecular features but also by those of other cells in the tissue. To effectively model these interactions, LUNA employs a multihead self-attention mechanism22,23, which dynamically integrates information from all cells in the slice. This mechanism allows the model to assign attention scores to different cells based on their relevance to the prediction of each cell’s location, capturing both local and global cellular interactions. Once the cell embeddings are learned, LUNA projects each cell’s embedding into a 2D space to predict its location.
Formally, LUNA takes as input (1) molecular features of cells \({{X}}_{s}\in {{\mathbb{R}}}^{m\times d}\) in a given slice s, where m denotes the number of cells and d denotes the number of genes; (2) time step \(t\in {\mathbb{N}}\) uniformly sampled from 0 to the maximum diffusion time T; and (3) corrupted cell locations \({\tilde{{R}}}_{s,t}\in {{\mathbb{R}}}^{m\times 2}\) at time step t. The output of the model is the denoised cell locations \({\hat{{R}}}_{s}\in {{\mathbb{R}}}^{m\times 2}\) for a given slice s. We omit slice index s for the ease of notation.
LUNA is composed of multiple transformer layers, each integrating fully connected layers followed by the self-attention block. At each layer l given a fixed diffusion time t, LUNA learns (1) cell embeddings \({{F}}^{(l)}\in {{\mathbb{R}}}^{m\times {d}_{x}^{(l)}}\); (2) a diffusion time embedding \({\gamma }_{t}^{(l)}\in {\mathbb{R}}\); and (3) cell location embeddings \({{R}}^{(l)}\in {{\mathbb{R}}}^{m\times {d}_{r}^{(l)}}\).
The cell embeddings F(0) in layer 0 are initialized via a fully connected neural network layer that maps the molecular features of cells into the latent embedding space with dimensionality \({d}_{x}^{(0)}\):
$${{F}}^{(0)}={\mathrm{FCN}}({{X}}_{s}),$$
(1)
where FCN denotes a fully connected neural network layer. The diffusion time embedding \({\gamma }_{t}^{(0)}\) is initialized to the value of the diffusion time itself:
$${\gamma }_{t}^{(0)}=t.$$
(2)
Finally, the cell location embeddings are initialized as the corrupted cell locations obtained from the corruption process at time step t:
$${{R}}^{(0)}={\tilde{{R}}}_{t}.$$
(3)
Then, at each layer l ∈ {1, …, L}, LUNA first transforms cell embeddings, a diffusion time embedding and cell location embeddings using fully connected layers:
$${{F}}_{f}^{(l)}={\mathrm{FCN}}\left({{F}}^{(l-1)}\right),$$
(4)
$${\gamma }_{t}^{(l)}={\mathrm{FCN}}\left({\gamma }_{t}^{(l-1)}\right),$$
(5)
$${{R}}_{r}^{(l)}={\mathrm{FCN}}\left({{R}}^{(l-1)}\right).$$
(6)
The transformed cell embeddings, diffusion time embedding and cell location embeddings are concatenated to form a unified representation for each cell:
$${{H}}^{(l)}=\left[{{F}}_{f}^{(l)},{\gamma }_{t}^{(l)}{{\bf{1}}}_{m\times 1},{{R}}_{r}^{(l)}\right],$$
(7)
where 1m × 1 is a column vector of ones used to replicate the diffusion time embedding \({\gamma }_{t}^{(l)}\) across all m cells. To obtain final cell embeddings F(l) in layer l, the unified representation H(l) is passed through a self-attention block which computes attention weights between all pairs of cells23:
$${{F}}^{(l)}={\text{SelfAttention}}^{(l)}\left({{H}}^{(l)}\right).$$
(8)
This self-attention operation enables the model to aggregate information from all cells in a slice, capturing how each cell’s location is influenced by others. To ensure scalability, we implemented the efficient attention23 (an approximation of attention computation with a linear complexity). This approach reduces memory usage and computational complexity by circumventing the need for explicit pairwise interactions between every query–key pair (Supplementary Note 9).
Finally, the cell embeddings F(l) are used to predict the locations of each cell. The cell locations are generated from the embeddings using a fully connected layer that projects the location of each cell from the latent embedding space to the 2D physical space:
$${{R}}^{(l)}={\mathrm{FCN}}\left({{F}}^{(l)}\right).$$
(9)
At each layer, the updated locations are centered by subtracting the mean, ensuring that the cell locations remain stable and consistent relative to the tissue structure. At the final layer, the output cell locations are the predicted clean cell locations \(\hat{{R}}={{R}}^{(L)}\). To better illustrate the scalability of our model components, especially the efficient attention mechanism and the FCN layer, we conducted kernel-level profiling of LUNA (Supplementary Note 10 and Supplementary Table 3).
Loss objective
To optimize LUNA, we introduce a specific loss objective that is SE(2)-invariant. This geometric invariance is crucial because the spatial arrangement of cells in the tissue may undergo transformations due to experimental artifacts, while the underlying gene expression profiles remain unchanged.
To ensure SE(2)-invariance, LUNA introduces a pairwise loss function, which focuses on preserving the relative distances between all cells in the slice defined as follows:
$${{\mathcal{L}}}_{{\rm{diff}}}=\dfrac{1}{{m}^{2}}\parallel \Delta (\hat{{R}})-\Delta ({{R}}_{gt}){\parallel }_{F}^{2},$$
(10)
where \(\Delta (\cdot):{{\mathbb{R}}}^{m\times 2}\to {{\mathbb{R}}}^{m\times m}\) computes the pairwise squared Euclidean distances between the locations of all cells and \({{R}}_{gt}\in {{\mathbb{R}}}^{m\times 2}\) represents the ground-truth cell locations.
The function \(\Delta {(\hat{{R}})}_{ij}=\parallel {\hat{r}}_{i}-{\hat{r}}_{j}{\parallel }_{2}^{2}\) computes the squared distance between the predicted locations of cells i and j, and similarly, \(\Delta {({{R}}_{gt})}_{ij}=\parallel {r}_{i}-{r}_{j}{\parallel }_{2}^{2}\) computes the squared distance between the true locations. The pairwise loss then becomes:
$${{\mathcal{L}}}_{{\rm{diff}}}=\dfrac{1}{{m}^{2}}\mathop{\sum }\limits_{i=1}^{m}\mathop{\sum }\limits_{j=1}^{m}{\left(\parallel {\hat{r}}_{i}-{\hat{r}}_{j}{\parallel }_{2}^{2}-\parallel {r}_{i}-{r}_{j}{\parallel }_{2}^{2}\right)}^{2},$$
(11)
which penalizes deviations between the predicted and true pairwise distances, ensuring that the spatial relationships between cells are preserved.
The final loss is computed over all slices s ∈ {1, . . . S} where S denotes the total number of slices:
$${\mathcal{L}}=\dfrac{1}{S}\mathop{\sum }\limits_{s=1}^{S}{{\mathcal{L}}}_{\,\text{diff}\,}^{(s)}.$$
(12)
We further conducted a comprehensive ablation study on LUNA’s model components, which confirms that LUNA’s attention-based architecture is crucial for capturing complex spatial dependencies between cells, while the pairwise loss function plays a key role in maintaining relational consistency (Supplementary Note 8 and Supplementary Fig. 36).
Corruption process
The diffusion model training begins with a corruption process, where LUNA progressively introduces noise to the true cell locations in an autoregressive manner. This step gradually transitions the true cell locations into pure noise, with the resulting corrupted locations serving as inputs for the subsequent denoising process.
We denote the initial diffusion time step, where no noise has been introduced to the cell locations, as time step 0, where ground-truth spatial information is fully retained. Conversely, the maximum diffusion time step, denoted as T, represents the state where no ground-truth information is preserved, and the locations are sampled from pure Gaussian noise. The time step t is randomly selected from {0, 1, 2, …, T}. The corrupted cell locations at time step t for the slice s are denoted as \({\tilde{{R}}}_{t}\in {{\mathbb{R}}}^{m\times 2}\), where again we omit the slice index s for the ease of notation. From time step t − 1 to t, Gaussian noise is added to the corrupted cell locations \({\tilde{{R}}}_{t-1}\), yielding noisier locations \({\tilde{{R}}}_{t}\) according to a predefined noise scheduler24,25,79. This noise scheduler is controlled by the noise schedule exponent, which controls how much noise is injected or removed at each time step of the reverse diffusion process and governs the randomness during sampling80. At time step T, the true cell locations \({{R}}_{gt}={\tilde{{R}}}_{0}\) are transformed into corrupted cell locations \({\tilde{{R}}}_{T}\) that have a standard Gaussian distribution. The conditional distribution is defined as:
$${q}_{\phi }({\tilde{{R}}}_{t}| {\tilde{{R}}}_{t-1})={\mathcal{N}}\left({\tilde{{R}}}_{t}| \sqrt{{\alpha }_{t}}{\tilde{{R}}}_{t-1},(1-{\alpha }_{t}){I}\right),$$
(13)
where qϕ( ⋅ ∣ ⋅ ) represents the corruption process with a noise scheduler ϕ that conditionally transitions the cell location distribution from less corrupted to more corrupted states. \({\mathcal{N}}(\cdot | \cdot ,\cdot)\) denotes a Gaussian distribution, and I is the identity matrix. The noise scheduler ϕ, regulated by hyperparameters {αt}, controls the balance between retaining the original cell locations and adding noise and governs the randomness during sampling.
To mitigate computational complexity, we compute the conditional distribution of corrupted cell locations given the true cell locations Rgt, rather than from the previous diffusion step25,81:
$${q}_{\phi }({\tilde{{R}}}_{t}| {\tilde{{R}}}_{0})={\mathcal{N}}\left({\tilde{{R}}}_{t}| \sqrt{{\overline{\alpha }}_{t}}{\tilde{{R}}}_{0},(1-{\overline{\alpha }}_{t}){I}\right).$$
(14)
Sampling from this conditional distribution is equivalent to adding Gaussian noise to the true cell locations. As shown in ref. 81, the corrupted cell locations are computed as:
$${\tilde{{R}}}_{t}=\sqrt{{\overline{\alpha }}_{t}}{\tilde{{R}}}_{0}+\sqrt{(1-{\overline{\alpha }}_{t})}\epsilon ,$$
(15)
where \({\overline{\alpha }}_{t}=\mathop{\prod }\nolimits_{i = 1}^{t}{\alpha }_{i}\), and ϵ is drawn from a Gaussian distribution with mean 0 and variance I (\(\epsilon \sim {\mathcal{N}}(0,{I})\)). As t progresses from 0 to T, the cell locations become increasingly corrupted until they are indistinguishable from white noise. At t = T, the corrupted locations \({\tilde{{R}}}_{T}\) are sampled purely from Gaussian noise, with \({\overline{\alpha }}_{T}=0\). To ensure robustness to translations, we additionally subtract the center of mass from the noise ϵ and the data slices \({\tilde{{R}}}_{0}\), thus working with distributions defined in the subspace where the center of mass is fixed to 0 (refs. 82,83).
Denoising process
Given the corrupted locations, we train the LUNA model to recover the true cell locations by reversing the corruption process using gene expression profiles. We denote the model as μθ( ⋅ , ⋅ , ⋅ ) where θ represents all model parameters. LUNA progressively denoises the corrupted cell locations \({\tilde{{R}}}_{t}\) producing less corrupted locations \({\tilde{{R}}}_{t-1}\) given time step t, more corrupted locations \({\tilde{{R}}}_{t}\) at the time step t, and the molecular features X.
Eventually, LUNA learns to generate clean cell locations from pure white noise, transitioning from t = T to t = 0. To achieve this, the model first predicts the clean cell locations \(\hat{{R}}\) using the learned network μθ( ⋅ , ⋅ , ⋅ ). It then interpolates between the corrupted locations \({\tilde{{R}}}_{t}\) and the predicted clean locations \(\hat{{R}}\), producing less corrupted locations for the next diffusion step:
$${\tilde{{R}}}_{t-1}=\dfrac{(1-{\overline{\alpha }}_{t-1})\sqrt{{\alpha }_{t}}}{1-{\overline{\alpha }}_{t}}{\tilde{{R}}}_{t}+\dfrac{(1-{\alpha }_{t})\sqrt{{\overline{\alpha }}_{t-1}}}{1-{\overline{\alpha }}_{t}}\hat{{R}}.$$
(16)
Inference phase
Once the model μθ( ⋅ , ⋅ , ⋅ ) is trained, LUNA generates cell locations based on the molecular features of the cells in the test set \({{X}}_{ts}\in {{\mathbb{R}}}^{{m}_{ts}\times d}\). The inference process starts by sampling locations from a normal distribution \(\epsilon \sim {\mathcal{N}}(0,{I})\), where \(\epsilon \in {{\mathbb{R}}}^{{m}_{ts}\times 2}\). The noisy locations, Rts,T = ϵ are then refined through a sequence of diffusion steps.
At each step t, the model takes the noisy locations Rts,t, the molecular features Xts, and the time step t as inputs to predict the denoised locations for the next time step t − 1:
$${{R}}_{ts,t-1}=\dfrac{(1-{\overline{\alpha }}_{t-1})\sqrt{{\alpha }_{t}}}{1-{\overline{\alpha }}_{t}}{{R}}_{ts,t}+\dfrac{(1-{\alpha }_{t})\sqrt{{\overline{\alpha }}_{t-1}}}{1-{\overline{\alpha }}_{t}}{\mu }_{\theta }({{R}}_{ts,t},{{X}}_{ts},t).$$
(17)
This process is repeated for each time step, iterating from t = {T, . . ., 0} until the model generates the final clean cell locations at t = 0.
Hyperparameters
We use a consistent learning rate of 5 × 10−4 across all experiments, with a maximum diffusion time of 1,000 steps and a cosine noise schedule characterized by ν = 2, which dictates the noise addition rate to the coordinates. A detailed analysis of hyperparameter selection and robustness to different values is provided in Supplementary Note 4 and Supplementary Figs. 37 and 38.
Xenium data collection
We generate a new spatial transcriptomics dataset using Xenium. Animal husbandry and experimental procedures adhered to the Swiss Federal Veterinary Office guidelines and were authorized by the Cantonal Veterinary Office (cantonal animal license no. VD3499).
Animal procedures
C57BL/6J male mice were group-housed, with a maximum of four animals per cage, at 22 °C and 50–60% relative humidity, under a 12-h light–dark cycle. At 8 weeks of age, mice were anesthetized with a ketamine/xylazine cocktail prepared in sterile saline. Once fully anesthetized, mice were placed in a stereotaxic frame. The head was shaved, Viscotears was applied to protect the eyes, and the scalp was disinfected with liquid Betadine solution. After incision, connective tissue was removed to expose the skull and identify the bregma landmark for unilateral dorsal striatum injections.
Stereotaxic coordinates relative to bregma were anteroposterior +0.6 mm, mediolateral +2.0 mm and dorsoventral −2.6 mm. A small hole was drilled into the skull, preserving the dura mater, and 2 μl of mouse wild-type PFFs at a concentration of 2.5 μg μl−1 were injected into the right hemisphere at a flow rate of 0.4 μl min−1 using a Hamilton syringe. The needle was left in place for 5 min post-injection before slow retraction to minimize backflow and was cleaned from blood to avoid clogging. The incision was sutured, Betadine gel was applied and animals were monitored in a heated recovery cage until fully awake. Postoperative well-being was assessed daily in accordance with animal license scoring sheets.
Tissue preparation for Xenium
Xenium was performed on four C57BL/6J mice: two wild-type controls and two α-synuclein PFF-injected animals collected at 3MPI. One 3MPI animal was excluded before any downstream analysis because its coronal sections were not anatomically matched to the control sections, showing a systematic spatial offset in the sampled planes that precluded reliable cross-sample comparison. All analyses in this study, and the dataset deposited on figshare, are based on the remaining three animals (two control and one 3MPI). Control and 3MPI mice were killed via overdose of a ketamine/xylazine cocktail and brains were rapidly removed. Brains were embedded in Tissue-Tek O.C.T. compound (cat. no. 4583) within 10 × 10 × 5-mm cryomolds (Tissue-Tek, cat. no. 4565) and frozen by submersion in dry-ice-chilled (approximately −70 °C) isopentane (Sigma, cat. no. M32631). Frozen embedded brains were maintained on dry ice until transfer to −80 °C storage.
Coronal sections (10 μm) were cut on a Leica cryostat and mounted onto Xenium capture slides (10x Genomics, cat. no. 10006559). For each brain, one coronal section targeting the amygdala (−1.70 mm relative to bregma) and one targeting the striatum (+0.6 to −1 mm relative to bregma) were collected. Two sections were placed per capture slide, which were returned to −80 °C until processing. The predesigned 248-gene Xenium Mouse Brain Gene Expression panel was profiled across all sections on the Xenium in situ platform (10x Genomics).
Post-Xenium immunofluorescence
Following completion of the Xenium runs, slides were stored in PBS at 4 °C. For immunofluorescence staining, tissues were permeabilized with PBS containing 0.5% bovine serum albumin (BSA) and 0.1% Triton X-100, blocked with 2% BSA in PBS and then incubated overnight at 4 °C with primary antibody against phosphorylated Ser129 α-synuclein (pSer129 α-synuclein, clone EP1536Y, Abcam ab51253, RRID:AB_869973) at 1:1,000 dilution, followed by a secondary antibody (Invitrogen A32731, polyclonal, Alexa488) at 1:500 dilution.
Imaging was performed using a Leica DMi8 epifluorescence microscope equipped with a Lumencor SPECTRA X LED light source (nIR, 90-10172), a Leica DFC9000 GTC sCMOS camera (11547007) and a ×20 HC PC APO objective (NA 0.8, air), yielding a pixel size of 0.34 μm. Images were acquired with 10% tile overlap to cover the entire tissue section, collecting between 8 and 12 z-planes with 1-μm spacing.
Anatomical registration
Anatomical registration was performed using Aligning Big Brains and Atlases (https://go.epfl.ch/abba)84, which combines affine transformations and nonlinear warping with anatomical border-guided feature registration. Images were automatically aligned to the Allen Brain Atlas Common Coordinate Framework version 3 (CCFv3), and the alignment was subsequently manually refined to ensure precise anatomical correspondence.
Immunofluorescence data processing
2D images were obtained from the acquired immunofluorescence stacks by performing maximum-intensity projection channelwise on the raw stacks. The immunofluorescence images were then stitched into a mosaic image using ASHLAR85. Only the 4′,6-diamidino-2-phenylindole (DAPI) channel was used to compute the corrected stitched coordinates. The immunofluorescence images were then aligned to the Xenium images by running the software wsireg86, a Python wrapper of elastix87,88. Each image transformation was computed using only the DAPI channel of both acquisitions, and the same obtained transformation was applied to the other channels of the immunofluorescence images (no warping was applied to the Xenium data in the process). To calculate the α-synuclein intensity level per cell, we first normalized the aligned α-synuclein channel by applying percentile-based normalization, in which we transformed the intensity values of the image so that the first percentile is mapped to 0 and the 99.8th percentile is mapped to 1. The results from the normalization were then clipped to the \(\left[0,1\right]\) intensity range. The median normalized α-synuclein intensity per cell was then calculated by sequentially subsetting the normalized α-synuclein channel using the segmentation masks obtained from Xenium and aggregating accordingly.
Cell annotation
To annotate the Xenium data at the single-cell level, we used the scRNA-seq data published elsewhere89 as a reference for label transfer. We downloaded all the given single-cell references (v.2 and v.3) and then concatenated them to obtain a single h5ad data file. During the concatenation process, we randomly subsampled the data by a factor of 4 (we kept 25% of the single cells) to alleviate posterior computational workload. We then ran Tangram14 for each Xenium dataset using the preprocessed single-cell data as reference. We ran Tangram in its default settings except for the run mode, for which we used mode = ‘clusters’. This mode runs the mapping at the cluster level and substantially reduces computational complexity. We annotated the Xenium data using 34 clusters.
Reporting summary
Further information on research design is available in the Nature Portfolio Reporting Summary linked to this article.