January 01, 1970
Spatial and Single-cell transcriptomics are transformative in deciphering cellular dynamics. As the fundamental paradigm for reconstructing cell developmental paths, trajectory inference (TI) is critical. However, existing methods require extensive manual intervention and proficiency in heterogeneous tools, posing a significant barrier to efficient TI analysis. To bridge this gap, we propose SpaCellAgent, an autonomous large language model (LLM) multi-agent framework that automates end-to-end spatiotemporal analysis and narrative generation. SpaCellAgent utilizes a multi-agent architecture for strategic workflow planning, a dynamic tool-orchestration engine for adaptive algorithm selection, and a self-evolution module that iteratively refines performance through feedback. We evaluate SpaCellAgent on six heterogeneous datasets encompassing complex temporal developmental trajectories, diverse sequencing platforms, and spatially-resolved tissue architectures. SpaCellAgent consistently demonstrates over 40% improvement in analytical efficiency while maintaining expert-aligned performance. By converting natural language specifications into optimized analytical workflows and fully automating the pipeline, SpaCellAgent democratizes advanced spatiotemporal modeling and establishes a scalable, agent-driven paradigm for computational biology. The code and materials are available at https://github.com/LittleXH-shw/SpaCellAgent.
<ccs2012> <concept> <concept_id>10010147.10010178.10010219.10010220</concept_id> <concept_desc>Computing methodologies Multi-agent systems</concept_desc> <concept_significance>500</concept_significance> </concept> <concept> <concept_id>10010405.10010444.10010450</concept_id> <concept_desc>Applied computing Bioinformatics</concept_desc> <concept_significance>500</concept_significance> </concept> <concept> <concept_id>10010405.10010444.10010935.10010454</concept_id> <concept_desc>Applied computing Transcriptomics</concept_desc> <concept_significance>500</concept_significance> </concept> </ccs2012>
Single-cell RNA sequencing (scRNA-seq) has revolutionized our understanding of cellular diversity and developmental processes by enabling transcriptome profiling at individual cell resolution [1]. This technology captures the heterogeneity within cell populations [2], revealing rare cell types [3], transitional states [4], and dynamic expression patterns that were previously obscured in bulk measurements [5]. Recently, the rapid development of spatial transcriptomics technologies has enabled the preservation of gene expression with spatial coordinates, allowing the mapping of cellular states within their native tissue architectures [6], [7]. These approaches provide unprecedented insights into how cellular states evolve both temporally and spatially [8], offering a comprehensive view of developmental trajectories [9], disease mechanisms [10], and tissue homeostasis [11], [12]. However, systematically uncovering molecular mechanisms from such high-dimensional cellular states necessitates intricate analysis pipelines [13]. Within this methodological landscape, Trajectory Inference (TI) stands out as a pivotal instrument for investigating cellular development and inferring cell fate, effectively reconstructing the continuous progression of biological processes from static snapshots [14].
To operationalize cellular development trajectory analysis, a diverse array of computational approaches has been established, including Monocle [15], PAGA [16], Slingshot [17], and Diffusion Pseudotime (DPT) [18]. These methods are grounded in distinct mathematical frameworks, ranging from graph-based algorithms to principal curve fitting and diffusion maps, to infer cellular ordering and branching structures. However, despite their theoretical advancements, these methods exhibit inconsistent performance across varying data dimensionalities and trajectory topologies [19], thereby necessitating manual selection and heuristic tuning by domain experts.
Recent advances in large language models (LLMs) have catalyzed a paradigm shift from manual tool-centric analysis to autonomous LLMs agent-driven exploration [20], [21]. Beyond code generation and complex reasoning [22], [23], LLMs can now orchestrate heterogeneous computational tools and democratize scientific interpretation by bridging raw outputs with meaningful insights [24], [25]. Despite this transformative potential, the integration of LLMs agent workflows into single-cell lineage reconstruction remains nascent, lacking an end-to-end closed-loop solution. Crucially, existing approaches lack automated mechanisms for self-evolution and iterative refinement; their static nature often yields suboptimal inference results and imposes a prohibitive manual burden. Consequently, there is an imperative for a unified framework that leverages the biological reasoning abilities of pre-trained LLMs as a cognitive core, autonomously orchestrating TI workflows.
To fill these gaps, we introduce SpaCellAgent, an autonomous LLM-driven framework that performs end-to-end spatial analysis and biological narrative generation. In contrast to traditional static and rigidly defined pipelines [26], [27], SpaCellAgent introduces a collaborative multi-agent architecture that dynamically assigns specialized roles, such as planner, executor, evaluator, and reporter, to each LLM. Specifically, the planner analyzes trajectory analysis objectives and topological data properties to decompose the lineage reconstruction process into executable milestones, while the executor autonomously identifies optimal algorithmic strategies through a dynamic tool orchestration engine to generate robust implementation code. The evaluator assesses the quality of the reconstructed lineage, diagnosing specific TI anomalies such as implausible branching and pseudotime inversion, while synthesizing corrective feedback for iterative improvement through a self-refinement mechanism. Additionally, SpaCellAgent incorporates a self-evolution module that persistently accumulates reusable error fixes and validated analysis templates across tasks, enabling continuous improvement and knowledge accumulation. Extensive benchmarking demonstrates that SpaCellAgent outperforms state-of-the-art (SOTA) baselines in topological fidelity while reducing the analysis time by 41.2%. Crucially, it reconciles scalability with robustness, delivering stable, expert-aligned trajectory analysis performance.
In general, the main contributions of this work can be summarized as follows:
We propose SpaCellAgent, an autonomous multi-agent framework that performs end-to-end TI analysis by integrating scRNA-seq and spatial transcriptomics data, and generates interpretable biological reports derived from the TI results and other downstream analyses.
SpaCellAgent couples data-driven strategy selection with a self-evolving refinement mechanism, enabling the system to autonomously adapt to diverse biological heterogeneities while continuously accumulating knowledge to optimize analysis robustness.
Extensive experiments demonstrate SpaCellAgent’s expert-aligned performance, and its 41.2% improvement in analytical efficiency compared to manual expert workflows. Therefore, our SpaCellAgent drastically shortens the time-to-insight for complex trajectory analysis.
The computational reconstruction of cellular developmental trajectories has evolved through distinct methodological paradigms [14], [19]. In the realm of scRNA-seq, foundational tools established the premise of ordering cells along a latent pseudotime [18]. Monocle pioneered this approach using minimum spanning trees (MST) and reversed graph embedding to resolve branching lineages [15]. Slingshot introduced principal curves for stable multi-lineage inference [17], while PAGA utilized graph abstraction to effectively reconcile clustering with trajectory topology [16]. The advent of spatial transcriptomics has catalyzed a paradigm shift in developmental modeling, necessitating the integration of physical topology into lineage reconstruction. Recent frameworks, such as SpaceFlow [28] and STORIES [29], have extended TI by incorporating spatial neighborhood constraints to model tissue-scale gene expression gradients. Despite these methodological strides, the existing TI landscape remains fragmented and heavily reliant on manual expertise. Researchers are often constrained by heterogeneous computational ecosystems, necessitating experience-dependent method choice and inefficient manual exploration of the hyperparameter space. This lack of standardization not only hampers reproducibility but also creates a prohibitive barrier for domain scientists. To address these challenges, we propose SpaCellAgent, an LLM-driven agentic framework that autonomously orchestrates adaptive algorithm selection and iterative code refinement, ensuring robust and reproducible analysis across diverse biological contexts.
The advent of LLMs, such as Gemini 2.5 [30], has led to a paradigm shift in code generation, natural language reasoning, and complex task decomposition. Building on these capabilities, general-purpose multi-agent architectures, such as ChatDev [31], have demonstrated how specialized agents can collaborate to autonomously execute intricate software engineering tasks. Recently, this agent-driven paradigm has notably extended to physics, where frameworks like ChemCrow [24] have successfully demonstrated the efficacy of LLMs in automating material property prediction and orchestrating chemical synthesis. However, in biomedicine and bioinformatics, the adoption of such workflows has been predominantly limited to textual tasks, such as literature retrieval and hypothesis formulation [32], [33]. The potential for driving closed-loop, empirical data analysis, particularly for multi-step computational biology workflows, remains largely underexplored. Existing LLM agent frameworks, primarily optimized for general-purpose software engineering or text processing, lack the domain-specific abilities for biological data analysis. Specifically, they do not support the autonomous orchestration of heterogeneous TI analysis algorithms, nor do they possess the error-recovery mechanisms necessary for processing high-dimensional, noisy omics data. To date, a unified framework capable of executing end-to-end, closed-loop trajectory analysis tasks remains absent. Our SpaCellAgent fills this gap by establishing an LLM-driven autonomous framework that dynamically optimizes algorithmic selection, delivering end-to-end TI analysis through a robust, self-optimizing workflow.
Formally, let a single-cell dataset be denoted as \({D} = \{ \mathbf{X}, \mathbf{S} \}\). The gene expression profile is represented by a matrix \(\mathbf{X} \in \mathbb{R}^{N \times G}\), where \(N\) denotes the number of cells and \(G\) represents the number of genes. Each row \(\mathbf{x}_i \in \mathbb{R}^G\) corresponds to the high-dimensional expression vector of cell \(i\). In the context of spatial transcriptomics, each cell is additionally associated with a spatial coordinate vector \(\mathbf{s}_i \in \mathbb{R}^D\) (typically \(D=2\) for tissue sections), forming a spatial coordinate matrix \(\mathbf{S} \in \mathbb{R}^{N \times D}\). A common and advantageous approach is to model cellular relationships as a graph \(G = (V, E)\), with nodes \(V\) representing cells. The adjacency matrix \(\mathbf{A} \in {0, 1}^{N \times N}\) is constructed based on pairwise transcriptomic similarity for scRNA-seq data. For spatial transcriptomics, it is built by integrating the expression matrix with physical coordinates, enabling the capture of the local manifold structure. The primary objective of TI is to reconstruct a dynamic developmental process from these static snapshots. Mathematically, this can be formulated as learning a mapping \(f: (\mathbf{X}, \mathbf{S}) \to \mathcal{T}\), that projects the high-dimensional data onto a low-dimensional latent manifold \(\mathcal{T}\), which represents the continuous space of all possible cell states along the process. Crucially, the inference of \(\mathcal{T}\) is operationally realized by jointly determining:
Pseudotime Ordering (\(\boldsymbol{\tau}\)): A continuous scalar value \(\tau_i \in [0, 1]\) that assigns each cell a coordinate on the manifold \(\mathcal{T}\), representing its progression level. for each cell \(i\), representing its progression level along the biological process, where \(\tau=0\) denotes the root state and \(\tau=1\) denotes the terminal state.
Lineage Structure: A connectivity graph or a set of principal curves describing the global topology (e.g., linear, bifurcating, or tree-structured) of cell fate decisions.
In spatial-aware TI, the inferred pseudotime \(\boldsymbol{\tau}\) must be smooth with respect to both the transcriptomic manifold \(\mathbf{X}\) and the spatial graph defined by \(\mathbf{S}\).
LLM-driven autonomous agents represent a paradigm shift in which LLMs serve as the “brain” for planning, reasoning, and action execution. While the individual agent demonstrates impressive capabilities in task decomposition, it is prone to instability in complex scenarios. Consequently, recent research focuses on multi-agent collaboration, which mimics human group dynamics by assigning distinct roles to specialized agents. By facilitating inter-agent interaction and iterative feedback, this collaborative architecture overcomes the limitations of a single agent, offering superior robustness and accuracy for handling sophisticated workflows such as computational biology tasks.
In this section, we introduce the overview of the SpaCellAgent. As shown in Figure 2, SpaCellAgent is an autonomous, LLM-driven framework designed to organize complex trajectory analysis on single-cell and spatial transcriptomics data. Distinct from static code generation tools, our frameworks implement a dynamic, closed-loop workflow powered by multi-agent collaboration. Upon receiving a natural language task description, the system initiates a collaborative process involving distinct agent roles. This process encompasses data perception, where input characteristics are inspected; strategic planning, where optimal TI and downstream analysis methods are selected; and autonomous execution, where executable Python or R scripts are generated and verified. The workflow culminates in the generation of a comprehensive report, integrating visual outputs with biological interpretation, thereby streamlining the path from raw data to scientific hypothesis formulation.
Planner agent. The planner agent acts as the system’s reasoning engine, decomposing high-level user intents into executable logics. It accepts a dual input: the natural language query and a structured metadata profile of the target dataset, encompassing gene expression counts, sparsity patterns, and spatial modalities. Leveraging an LLM with specialized planning instructions, the agent synthesizes a directed action sequence encoded in a JSON file. Each node in this sequence is assigned a unique ID and a descriptive label, establishing a machine-readable backbone that facilitates robust downstream execution and human-in-the-loop verification. Executor agent. The executor agent bridges the gap between abstract planning and concrete execution. It consists of two tightly coupled components responsible for dynamic tool retrieval and context-aware code generation.
Tool selector. This component functions as a semantic router, mapping high-level task descriptions to specific computational tools. It queries a curated registry containing both standard single-cell methods and spatial-aware algorithms. By utilizing an LLM conditioned on the dataset characteristics and user requirements, the tool selector dynamically configures the analysis pipeline, avoiding the drawbacks of static default settings and ensuring compatibility with the data’s intrinsic spatiotemporal structure.
Coder. The Coder functions as a specialized implementer, synthesizing executable scripts to instantiate abstract TI methods into runnable workflows. Leveraging a polyglot architecture, it flexibly interfaces with optimal tools across the Python and R ecosystems to resolve complex lineage topologies. The generation process adheres to rigorous constraints, managing the serialization of single-cell objects and ensuring the seamless flow of pseudotime and trajectory coordinates between heterogeneous analysis environments.
Evaluator agent. The evaluator agent enforces a rigorous quality control protocol through a dual-layer validation mechanism comprising a code evaluator for execution integrity and a biological evaluator for scientific plausibility.
Code evaluator. This component constitutes the foundational verification stage, specifically tasked with guaranteeing the integrity of TI workflows. It systematically inspects execution logs for algorithm-specific failures and verifies the existence of output files. If runtime exceptions are detected, the component extracts the error context and routes it as actionable debugging feedback to the executor. This enables the system to autonomously attempt code correction, explicitly skipping the biological validation phase to optimize token usage.
Biological evaluator. The biological evaluator moves beyond syntax to assess the biological fidelity of the inferred trajectories. Ingesting the generated plots and statistical summaries, the agent utilizes LLMs to cross-reference the findings with established biological priors. It specifically targets common TI artifacts, such as biologically impossible lineage transitions or inverted developmental paths. For example, it checks alignment with the known cellular hierarchy, allowing it to flag biologically impossible transitions, such as erroneously assigning a terminally differentiated cell as the trajectory root. If such a discrepancy is detected, the biological evaluator flags the result as biologically incoherent and provides a targeted diagnostic hypothesis, guiding the planner to refine the upstream configuration.
Knowledge-augmented fallback mechanism. To enhance generalization to trajectory inference tasks outside the model’s experience distribution, we design a knowledge-augmented fallback mechanism integrated into the biological evaluator agent. Specifically, when SpaCellAgent encounters a trajectory inference task that falls outside its internal experience memory, the biological evaluator initiates an automated search through PubMed to retrieve the latest biological reference, including tissue-specific markers and similar case studies. This allows the agent to evaluate its TI results in peer-reviewed scientific evidence rather than heuristic guessing.
Dynamic tool discovery and registration mechanism. To break through the boundaries of a predefined registry, SpaCellAgent is designed with a dynamic tool discovery and registration mechanism, enabling adaptive bioinformatics problem-solving. Specifically, if the agent determines that the existing tool registry is insufficient to execute the formulated plan, it will dynamically introduce and invoke new tools (e.g., importing a novel Python/R package for a specific spatial transcriptomics algorithm). Once the analysis incorporating the new tool successfully passes biological validation, SpaCellAgent will archive the successful analysis pipeline into the global memory and extract and register the newly utilized tool into the tool registry. Through this strategy, the tool registry autonomously expands and evolves by integrating novel tools and registering validated workflows.
Dual-layer memory architecture. To ensure coherent reasoning across varying temporal scales, SpaCellAgent implements a hierarchical memory system comprising local and global modules. Local memory serves as an ephemeral, intra-task context buffer. It logs the full trajectory of the current analysis step, including iterative code drafts, execution traces, and diagnostic evaluations. This comprehensive history allows the coder to engage in context-aware debugging, preventing recursive errors during self-correction. In contrast, global memory serves as a persistent inter-task knowledge base. It consolidates successfully verified code snippets and reasoning patterns from historical runs. By retrieving relevant exemplars from this global repository, the agent enables knowledge transfer across different datasets, effectively bootstrapping new tasks with proven analytical templates. This dual capability equips it with greater adaptability and scalability when confronting the high heterogeneity and complex dependencies inherent in spatial and single-cell data.
| Method | Real-Gold | Real-Silver | Synthetic | |||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2-5 (lr)6-9 (lr)10-13 | Corr | HIM | WCor | F1 | Corr | HIM | WCor | F1 | Corr | HIM | WCor | F1 |
| DPT | 0.213 | 0.515 | 0.385 | 0.262 | 0.259 | 0.387 | 0.413 | 0.279 | 0.308 | 0.483 | 0.323 | 0.345 |
| RaceID/StemID | 0.220 | 0.334 | 0.501 | 0.206 | 0.288 | 0.389 | 0.501 | 0.206 | 0.361 | 0.381 | 0.562 | 0.128 |
| Scorpius | 0.295 | 0.576 | 0.551 | 0.139 | 0.602 | 0.569 | 0.719 | 0.574 | 0.455 | 0.431 | 0.525 | 0.436 |
| PAGA | 0.256 | 0.469 | 0.735 | 0.402 | 0.431 | 0.497 | 0.680 | 0.381 | 0.470 | 0.539 | 0.649 | 0.358 |
| PAGA Tree | 0.319 | 0.523 | 0.478 | 0.440 | 0.442 | 0.614 | 0.670 | 0.519 | 0.501 | 0.605 | 0.664 | 0.439 |
| Slingshot | 0.347 | 0.651 | 0.749 | 0.483 | 0.469 | 0.551 | 0.639 | 0.541 | 0.448 | 0.431 | 0.445 | 0.421 |
| SpacellAgent | 0.480 | 0.710 | 0.711 | 0.608 | 0.774 | 0.322 | 0.719 | 0.645 | 0.564 | 0.560 | 0.660 | 0.509 |
6pt
Self-refinement mechanism. To ensure robustness in TI analysis, SpaCellAgent incorporates an autonomous self-refinement mechanism. For each step, the system initiates a bounded iterative process in which the evaluator assesses the execution output. Successful iterations commit to the intermediate dataset state and advance the workflow. In contrast, failures trigger a refinement cycle: the coder receives an augmented context containing the full interaction history, truncated error logs, and semantic feedback from the evaluator. Guided by prompts that enforce strategy divergence to avoid repetitive errors, the agent synthesizes revised code for re-execution. This loop persists until success is achieved or the maximum attempt limit is reached. By integrating rule-based error detection with LLM-driven diagnosis, this mechanism autonomously resolved syntax errors and API discrepancies encountered during trajectory analysis, enabling the seamless modeling of cellular dynamics.
Cross-task self-evolution. Beyond within-task self-refinement, SpaCellAgent integrates a self-evolution mechanism for continual learning in TI analysis. This module treats successful TI workflows as reusable knowledge, archiving verified code snippets alongside biological contextual metadata into a global memory repository. Upon encountering new datasets, the coder queries this repository to retrieve relevant analysis templates, effectively utilizing a retrieval-augmented generation strategy to bias the model toward proven architectural patterns. Furthermore, the system accumulates error-fix pairs from historical failures, allowing it to proactively apply discovered remedies, such as parameter adjustments or alternative method selection, to recurrent issues. Over time, this cumulative knowledge base transforms SpaCellAgent into an adaptive system, progressively enhancing convergence speed, stability, and trajectory analysis consistency across diverse biological scenarios.
Together, the self-refinement and self-evolution mechanisms transform SpaCellAgent from a static pipeline into a continuously improving system. As it is applied to more datasets and use cases, its internal knowledge base becomes richer, enabling superior generalization to unseen biological contexts and robust handling of complex lineage topologies over time.
Model configuration. In all reported experiments, the agents were instantiated using the DeepSeek-V3 model [22]. We accessed the model through API with the temperature set to 0.0 and the \(Top\text{-}p\) set to 1 to prioritize precise and deterministic outputs. For the self-reflection task, we employed a slightly higher temperature of 0.4 (with \(Top\text{-}p\) to 1), allowing the agent to explore alternative biological hypotheses when the initial path failed. Additionally, the maximum output token limit was set to 128,000 to accommodate long-sequence biological reasoning.
Datasets. In this study, we employed a diverse set of six datasets comprising both synthetic and curated benchmarks (REAL-GOLD, REAL-SILVER, SYNTHETIC) [19], and real-world spatial tissues, such as the Mouse Dorsal Midbrain, Axolotl Neuron Regeneration [7], and an unpublished Mouse Spinal Cord Injury (SCI) Dataset. The details of the datasets are in Appendix 9.1. These datasets provide comprehensive coverage of contexts essential for robust TI evaluation: maturation, cellular states, germline specification, technical variability, and spatial organization.
Baselines. We compared SpaCellAgent with five established methods representing diverse algorithmic paradigms:
DPT [18]: A diffusion-based method that estimates pseudotime by simulating random walks on a transition matrix to resolve branching lineages.
RaceID/StemID [34]: A clustering-based framework that combines outlier-sensitive clustering with minimum spanning trees to identify lineage connectivity.
Scorpius [35]: A linear inference method that orders cells by projecting them onto a shortest-path curve derived from k-nearest neighbor distances.
PAGA [16]: A graph abstraction technique that preserves global topology by constructing a coarse-grained connectivity map between cell clusters, capable of capturing complex cyclic structures.
PAGA Tree [16]: A variant of PAGA optimized for hierarchical lineages, which directs the abstracted graph to generate a rooted, tree-like trajectory structure.
Slingshot [17]: A curve-fitting approach that employs semi-supervised principal curves to model smooth, branching trajectories across pre-defined cluster centers.
For all baselines, we adopt the default parameter settings as provided in their original implementations.
We employed four complementary metrics to assess SpaCellAgent from the perspectives of cellular ordering, branch assignment, biological feature relevance, and global network topology.
Correlation. We calculated the Spearman rank correlation coefficient \(\rho\) between the geodesic distance matrices of reference and predicted trajectories: \[\text{Corr} = \rho({D}_{ref}, {D}_{pred}).\] This metric quantifies the preservation of global cellular relationships along the inferred milestone network.
F1 Branches (F1). We used the Jaccard-based F1 score to evaluate structural correspondence: \[F1_{branch} = 2 \cdot \frac{Recovery \cdot Relevance}{Recovery + Relevance}.\] It assesses the model’s accuracy in capturing milestone branches and ensuring the purity of cell assignments to those branches.
Feature importance weighted correlation (wCor). This metric evaluates the agent’s ability to identify key trajectory-driving genes. We performed Random Forest (RF) regression to extract gene importance vectors from the predicted coordinates: \[wCor = \text{corr}_w(\text{FI}_{ref}, \text{FI}_{pred}).\] The Pearson correlation is weighted by reference importance to emphasize biologically significant drivers.
Hamming-Ipsen-Mikhailov score (HIM). To compare the inferred milestone network \(\mathcal{G}_{pred}\) with the ground truth \(\mathcal{G}_{ref}\), we employed the HIM distance: \[HIM = 1- \frac{1}{\sqrt{2}} \sqrt{d_H^2 + d_{IM}^2},\] where \(d_H\) represents normalized Hamming distance and \(d_{IM}\) represents Ipsen-Mikhailov distances.
For all metrics defined above, higher values consistently indicate superior performance.
To evaluate the trajectory analysis capabilities of SpaCellAgent, we first evaluated both baselines and SpaCellAgent across three diverse benchmarks: REAL-GOLD, REAL-SILVER, and SYNTHETIC. The general results shown in Table 1 present a comprehensive performance comparison. Then, we conducted a comparison with LLM-based baselines. The details are provided in Appendix 9.3.
As shown in Table 1, SpaCellAgent achieves SOTA performance, ranking first in the majority of metrics across all datasets. Notably, on the REAL-GOLD dataset, SpaCellAgent outperforms the second-best method, Slingshot, with an average Correlation of 0.480 and an F1 score of 0.608. This substantial improvement is attributed to the self-refinement and self-evolution mechanisms within SpaCellAgent, which autonomously mitigate errors arising from manual parameter tuning. In contrast to baseline methods constrained by static algorithmic assumptions, SpaCellAgent employs its LLM-driven planner and tool selector to perform dynamic data profiling. This mechanism empowers the agent to autonomously orchestrate the optimal configuration of analytical tools tailored to each specific dataset, thereby circumventing the drawbacks of human bias and manual optimization errors.
Spatial trajectory analysis and biological insights. To further investigate the capability of SpaCellAgent in analyzing high-dimensional data with spatial coordination, we applied SpaCellAgent to the Mouse Embryonic Dorsal Midbrain dataset. This dataset contains 26,738 spatially resolved cells from the mouse embryonic dorsal midbrain, with expression profiles for 24,045 genes and temporal information from stages E12.5, E14.5, and E16.5. Unlike dissociated single-cell data, this task requires the agent to reconcile gene expression similarity with physical proximity.
As shown in Figure 4, SpaCellAgent autonomously orchestrated the data preprocessing and visualized the clustering landscape through UMAP. Critically, SpaCellAgent proactively inferred the latent developmental pathways and automatically generated trajectory plots based on its reasoning. These visualizations reveal that SpaCellAgent accurately reconstructed the bifurcation trajectory from Radial Glia-like (RGL) progenitors into distinct neuronal (NeuB) and glial (GlioB) lineages. This trajectory aligns with the temporal progression from E12.5 to E16.5, as illustrated in Figure 5, and is driven by a distinct shift in marker expression, transitioning from Sox2-positive progenitors to Nurr1- and Th-positive neurons. These results are consistent with prior studies [7], [36]. Subsequently, we conducted functional enrichment analysis, validating the biological plausibility of the identified lineage, highlighting key pathways such as axonogenesis and dopamine metabolic processes, which are intrinsic to midbrain development. Next, we applied SpaCellAgent to the Axolotl Neuron Regeneration dataset, another spatially resolved dataset capturing complex tissue reconstruction.
To evaluate the generalization capability and real-world utility of SpaCellAgent, we deployed the framework on a private scRNA-seq dataset of Mouse SCI provided by our collaborating hospital. This dataset captures the impact of high-salt (HS) versus normal-salt (NS) intake across three specific time points: Day 0, Day 7, and Day 28. Specifically, time point day 0 denotes the Sham-operated (SAM) group, serving as the uninjured baseline control where the surgical procedure was performed without inducing spinal cord damage.
SpaCellAgent first devised a TI analysis plan based on the structural characteristics of the data and user requirements, and designated the optimal analytical tool for each step of the workflow. Subsequently, SpaCellAgent executed the workflow according to the specified plan. Following the cell annotation step, it analyzed potential cell developmental trajectories within the SCI context based on the annotation results. Subsequently, SpaCellAgent executed the TI step, modeling the lineage progression from precursors to mature cells by constructing a pseudo-temporal ordering, as shown in Figure 4. SpaCellAgent further conducted temporal expression profiling, revealing that HS-OPCs persistently upregulated the inhibitor Sox17 even at late stages while failing to sustain Plp1.
To quantify this developmental perturbation, SpaCellAgent further employed pseudotime analysis to dissect the underlying lineage dynamics. As shown in Figure 6, solid lines representing fitted expression trends along the differentiation pseudotime clearly reveal a premature termination of the HS trajectory and a significant expression gap in Plp1 compared to the NS lineage. The results reveal that, by integrating velocity-derived streamlines with fate probability calculations, the agent autonomously identified a marked differentiation blockade in the HS group. Unlike the continuous NS trajectory, the HS lineage exhibited fragmented streamlines and early-stage cell arrest, indicating impaired endogenous remyelination. These findings are consistent with prior studies highlighting the detrimental impact of high-salt diets on post-injury neural recovery [37], [38]. These results substantiate SpaCellAgent’s capacity for autonomous hypothesis formulation in unseen biological contexts, proving its practical utility as a powerful assistant for accelerating novel scientific discoveries. Then, we conducted an enrichment analysis to quantitatively validate the biological fidelity. The details are provided in Appendix 9.3.
To verify the effectiveness of SpaCellAgent’s components, we conducted ablation studies with the following variants: (1) SpaCellAgent w/o planner; (2) SpaCellAgent w/o evaluator; (3) SpaCellAgent w/o self-evolution (w/o Evol.); (4) GPT-4 (w/o agent); (5) w/o experience memory.
Effectiveness analysis. We first conducted ablation experiments on the REAL-GOLD benchmark, alongside the Mouse Embryonic Dorsal Midbrain and Axolotl Neuron Regeneration Datasets. For this analysis, we defined a standardized TI workflow comprising six tasks and measured the Task Success Rate (TSR) to compare different variants. The results given in Figure 7 show the necessity of the full multi-agent architecture. Specifically, GPT-4 exhibits the poorest performance, primarily due to its inability to manage the intricate context of long-horizon TI workflows, which often results in code generation failures. Regarding the architectural variants, the w/o planner variant suffers from a lack of strategic direction, leading to failures in decomposing complex biological goals into actionable sub-tasks. Similarly, the w/o evaluator variant operates without the critical self-correction mechanism, rendering it incapable of resolving runtime errors or refining suboptimal outputs, which significantly undermines overall robustness compared to the SpaCellAgent framework.
Efficiency analysis. To evaluate efficiency, we recruited five domain experts actively engaged in bioinformatics research (spanning Master’s and Ph.D. levels) to establish an averaged human baseline. The details of experts team are provided in Appendix 9.7. Then, we benchmarked SpaCellAgent against the human baseline and the variant w/o self-evolution. As shown in Table 2, SpaCellAgent recorded the lowest total execution time of 38.0 minutes, outperforming the human average by 41.2% and the non-evolutionary baseline by 32.7%. Gains were most significant in complex downstream tasks, with SpaCellAgent surpassing human experts by 53.6% in Step 4 and 63.9% in Step 5. While humans slightly lead in initial preprocessing, the self-evolution mechanism minimizes redundant debugging in later stages, ensuring superior scalability for end-to-end analysis. Collectively, these results demonstrate that SpaCellAgent significantly alleviates the manual burden of complex trajectory inference, offering a scalable and time-efficient paradigm for high-throughput biological hypothesis formulation.
Cross-Model sensitivity analysis. To demonstrate our framework’s robustness, we conducted additional sensitivity experiments using GPT-5.2 and claude-sonnet-4-6 as alternative foundational models. We experimented with five subsets from the real gold benchmark and calculated Spearman’s rank correlation. Meanwhile, we conducted an effectiveness analysis on complex real-world datasets for 10 runs and calculated the success rate (SR). The results of these cross-model comparisons are shown in Table 3. The results show consistent gains in both efficiency and accuracy, confirming that the performance is driven by our agentic framework design.
| Task | Human Expert | w/o Evol. | SpaCellAgent |
|---|---|---|---|
| Step1 | 10.0 ± 1.6 | 15.4 ± 1.2 | 12.4 ± 0.8 |
| Step2 | 8.4 ± 1.2 | 6.8 ± 2.0 | 6.5 ± 1.4 |
| Step3 | 11.2 ± 2.0 | 8.8 ± 0.8 | 5.6 ± 0.6 |
| Step4 | 8.4 ± 1.2 | 11.0 ± 1.2 | 3.9 ± 0.7 |
| Step5 | 26.6 ± 3.8 | 14.5 ± 1.5 | 9.6 ± 0.9 |
| Total Time | 64.6 | 56.5 | 38.0 |
| Dataset | Deepseek-V3 | GPT-5.2 | claude-sonnet-4-6 | |||
|---|---|---|---|---|---|---|
| S1 | 0.526 | 0.538 | 0.518 | |||
| S2 | 0.615 | 0.613 | 0.624 | |||
| S3 | 0.571 | 0.570 | 0.582 | |||
| S4 | 0.483 | 0.494 | 0.481 | |||
| S5 | 0.755 | 0.768 | 0.768 | |||
| SR | 0.8 | 0.9 | 0.9 |
Tool selection consistency analysis. To evaluate the tool selection consistency and planning accuracy of SpaCellAgent, we conducted systematic experiments of potential issues such as tool selection errors and agent planning failures. Specifically, we repeated the same analysis task 5 times independently on each of the three real-world datasets: the Mouse Dorsal Midbrain (Midbrain), Axolotl Neuron Regeneration (Axolotl), and SCI (with the same input and the temperature set to 0). We measured the tool selection consistency of each dataset. Meanwhile, we invited a human expert team to evaluate the planning accuracy and feasibility (use a quality score rated on a scale from 0 to 10). We implemented a standardized TI workflow as defined in our effectiveness analysis, measuring the consistency rate across all repeated trials. Subsequently, we invited the human expert team to independently evaluate the accuracy and feasibility of the generated analysis plans and each step of the code. The results are shown in Table 4. The result shows that our framework achieves consistently high tool selection reliability and planning accuracy across all three datasets, confirming that the standardized workflow effectively mitigates tool selection errors and planning failures.
| Dataset | Midbrain | Axolotl | SCI | |||
|---|---|---|---|---|---|---|
| Step1 | 1.0 | 1.0 | 1.0 | |||
| Step2 | 1.0 | 1.0 | 1.0 | |||
| Step3 | 1.0 | 1.0 | 1.0 | |||
| Step4 | 1.0 | 1.0 | 1.0 | |||
| Step5 | 0.9 | 0.8 | 1.0 | |||
| Quality score | 8.0 ± 0.7 | 7.8 ± 0.4 | 7.2 ± 0.8 |
To quantitatively verify the effectiveness of the Knowledge-augmented fallback mechanism, we conduct an additional ablation study with the w/o experience memory variants on the real-gold dataset. The details are provided in Appendix 9.8.
We introduce SpaCellAgent, an autonomous self-evolving LLM-based multi-agent framework for trajectory analysis. By integrating a collaborative multi-agent architecture with dynamic tool orchestration, SpaCellAgent plans workflows, selects methods, executes analyses, and generates interpretable reports, closing the gap between raw data and biological insight. The results of the experiment confirm that the SpaCellAgent matches the performance of the experts while reducing the analysis time by more than 40% and lowering the accessibility barrier for the domain researchers. Ablation studies validate the critical roles of agent-based decomposition, iterative self-refinement, and knowledge reuse across tasks in achieving robustness and stability. Future work will extend the SpaCellAgent to spatial multi-omics integration and tighter coupling with regulatory network analysis, positioning SpaCellAgent as a foundational step toward scalable, intelligent assistants in computational biology.
This work was partially supported by the National Natural Science Foundation of China (Grant No. 62525213, 62372459, 62325604), the Beijing Natural Science Foundation (Grant No. L253021), and the Innovative Research Group Project of Hunan Province (Grant No. 2025JJ10008).
All authors adhere to all ACM Publications Policies, including ACM’s Publications Policy on Research Involving Human Participants and Subjects. The regulatory mechanisms inferred by SpaCellAgent, while computationally robust and consistent with established literature, remain hypotheses that warrant future validation through in vivo experimental assays. All datasets utilized in this study were acquired and processed in strict adherence to ethical guidelines and privacy regulations.
In this work, we mainly employ GenAI to identify and correct syntax errors and polish writing.
We formalize the Trajectory Inference (TI) task as a manifold learning problem. Given a single-cell gene expression matrix \(\mathbf{X} \in \mathbb{R}^{N \times M}\) comprising \(N\) cells and \(M\) genes, the objective is to learn a low-dimensional manifold \(\mathcal{M}\) embedded in a latent space \(\mathcal{Z} \in \mathbb{R}^{N \times d}\) (where \(d \ll M\)), and a pseudotime function \(\tau: \mathcal{Z} \rightarrow \mathbb{R}_{\ge 0}\) that maps each cell to its developmental progression. We contrast two dominant formalisms employed in our evaluation: cluster-based abstraction and principal graph learning.
This class of methods approximates the continuous manifold \(\mathcal{M}\) using a coarse-grained graph derived from discrete cell partitions.
Manifold Partitioning: The latent space \(\mathcal{Z}\) is partitioned into \(k\) disjoint clusters \(\mathcal{C} = \{C_1, C_2, \dots, C_k\}\) using algorithms such as Louvain or \(k\)-means. Each cluster is represented by a centroid \(\mu_i\).
Graph extraction: A connectivity graph \(\mathcal{G}_{abs} = (\mathcal{V}, \mathcal{E})\) is constructed where nodes \(\mathcal{V}\) correspond to cluster centroids. An edge \(e_{ij} \in \mathcal{E}\) is established if the connectivity metric \(S(C_i, C_j)\) (e.g., statistical interconnectivity in PAGA) exceeds a threshold \(\delta\): \[\mathcal{E} = \{ (i, j) \mid S(C_i, C_j) > \delta \}.\]
Curve Fitting and Pseudotime: A set of smooth principal curves \(\Gamma = \{\gamma_1, \dots, \gamma_b\}\) is fitted through the centroids along the topology of \(\mathcal{G}_{abs}\). The pseudotime \(\tau_i\) for a cell \(\mathbf{z}_i\) is computed by projecting the cell onto the nearest curve \(\gamma\): \[\tau_i = \int_{\text{root}}^{\text{proj}(\mathbf{z}_i, \gamma)} || \frac{\partial \gamma(t)}{\partial t} || dt.\]
Instead of relying on discrete clusters, this formalism employs Reverse Graph Embedding (RGE) to learn a continuous tree structure \(\mathcal{T}\) directly within the latent space.
Graph Initialization: A simpler graph structure (e.g., a tree) is initialized in the latent space \(\mathcal{Z}\).
Optimization Objective: The algorithm iteratively updates the graph nodes \(\mathcal{V}_{\mathcal{T}}\) and edges to minimize the distance between the data points and the graph structure, typically minimizing a regularized quantization error: \[\min_{\mathcal{T}, \mathbf{Y}} \sum_{i=1}^{N} || \mathbf{z}_i - f(\mathbf{z}_i) ||^2 + \lambda \Omega(\mathcal{T}).\] where \(f(\mathbf{z}_i)\) projects cell \(i\) to the nearest point on the graph \(\mathcal{T}\), and \(\Omega(\mathcal{T})\) is a regularization term enforcing graph smoothness or tree structure.
Geodesic Pseudotime: Upon convergence, the pseudotime is defined as the geodesic distance \(d_g(\cdot, \cdot)\) along the learned principal graph from a designated root node \(r\): \[\tau_i = d_g(\text{proj}(\mathbf{z}_i, \mathcal{T}), r).\]
The cognitive architecture of SpaCellAgent is governed by role-specific system instructions that delineate the operational boundaries and reasoning protocols for each agent. Below, we provide the verbatim system prompts used to instantiate the Planner, Executor, and Evaluator agents. These prompts are engineered to enforce strict adherence to biological logic, code syntax correctness, and iterative self-refinement.
The cognitive architecture of SpaCellAgent is governed by role-specific system instructions that delineate the operational boundaries and reasoning protocols for each agent. Below, we provide the verbatim system prompts used to instantiate the Planner, Executor, and Evaluator agents. These prompts are engineered to enforce strict adherence to biological logic, code syntax correctness, and iterative self-refinement.
The Planner is instructed to decompose the user’s biological query into a logical sequence of analytical milestones.
"User Task Description": "user_task", "User Data Description": "data_representation", "Output Format Requirements": "steps": [ "id": 1, "description": "Step 1 description" , "id": 2, "description": "Step 2 description" ]
The Executor is tasked with translating the high-level plan into executable Python scripts, utilizing the predefined tool registry.
None
Figure 8: No caption.
None
Figure 9: No caption.
The Evaluator serves as the quality assurance module, analyzing execution logs and visual outputs to synthesize refinement strategies.
"prompt": [ "You are an experienced bioinformatics expert.", "Please evaluate whether the code execution was successful...", "", "**Important Evaluation Rules**:", "1. If the execution results contain any of the following keywords, the execution failed:", " - Ëxecution error,̈ Ëxecution failed"̈, " - Ërror,̈ Ëxception,̈ T̈raceback"̈, " ...", "", "User Requirements:", "user_requirements", "", "Please output strictly in the following format..." ]
"prompt": [ "You are a distinguished Senior Computational Biologist.", "Your task is to evaluate the **scientific validity** and **biological plausibility** of the analysis results generated by the previous step.", "Unlike the Code Evaluator, you assume the code executed without errors; your focus is on the **quality and meaning** of the output.", "**Evaluation Criteria**:", "1. **Data Integrity & Statistics**:", " - Check if the output contains valid biological signals (e.g., variable genes found, clusters identified).", " - Fail if results are empty, trivial (e.g., 0 cells remaining), or statistically insignificant (e.g., all p-values > 0.05).", "2. **Biological Plausibility**:", " - **Clustering**: Fail if the number of clusters is extreme (e.g., 1 cluster or >100 clusters for a small dataset).", " - **Annotation**: Fail if marker genes are non-specific (e.g., mitochondrial genes only).", "3. **Trajectory Inference (TI) Specifics** (if applicable):", " - **Topology**: Fail if the inferred trajectory is highly fragmented (disconnected manifolds) or purely linear when branching is expected.", " - **Pseudotime**: Check if the root cell selection aligns with user intent (e.g., time 0 should be at the stem/progenitor stage).", "User Requirements: user_requirements", "Data Description: data_description", "Current Task Step: step_description", "Analysis Results (Logs & Summaries): execution_result", "Please output strictly in the following format:", "Evaluation Result: [Pass / Fail / Needs Refinement]", "Biological Critique: [Briefly analyze the biological meaning. E.g., T̈rajectory successfully captures the bifurcating lineage.]̈", "Refinement Strategy: [If Fail: Provide specific parameter adjustments (e.g., Ïncrease resolution to 0.8)̈. If Pass: N̈one]̈" ]
To facilitate the autonomous orchestration of complex bioinformatics workflows, we provide the Executor agent with a rigorous Tool Registry Schema. As presented in Table 5, each computational tool (e.g., functions from Scanpy, Squidpy, or Monocle3) is encapsulated with a semantic description, strict parameter constraints, and input/output specifications. This structured definition enables the Large Language Model (LLM) to accurately map high-level analytical intent to specific function calls without hallucinating non-existent parameters.
| Analysis Step | Description | Mainstream Tools | Lang. |
|---|---|---|---|
| Preprocessing & QC | Quality control, doublet removal, mitochondrial gene filtering, and data normalization. | Scanpy, Seurat, DoubletFinder |
Py/R |
| Dimensionality Reduction | Mapping high-dimensional gene expression data into low-dimensional space (PCA, UMAP, t-SNE). | Scanpy, Seurat | Py/R |
| Clustering & Annotation | Identifying cell subgroups based on profiles and annotating cell types using marker genes. | Leiden, Louvain, SingleR |
Py/R |
| Trajectory Inference | Constructing pseudo-temporal ordering to reconstruct cell differentiation lineages. | Monocle3, Slingshot, PAGA, Palantir |
R/Py |
| RNA Velocity | Predicting future cell states using the ratio of spliced to unspliced transcripts. | scVelo, velocyto | Py |
| Fate Probability | Integrating velocity and trajectory data to compute differentiation probabilities. | CellRank | Py |
| Differential Expression | Identifying statistically significant differentially expressed genes (DEGs) between clusters. | Wilcoxon Rank Sum, DESeq2, MAST |
R/Py |
| Functional Enrichment | Analyzing biological pathways (GO, KEGG) enriched in specific gene sets. | clusterProfiler, gseapy, GSEA |
R/Py |
| Cell-Cell Communication | Inferring intercellular interaction networks based on ligand-receptor databases. | CellChat, CellPhoneDB, NicheNet |
R/Py |
| Spatial Analysis | Identifying spatial domains and spatially variable genes (SVGs) using coordinates. | Squidpy, Giotto, SpaceRanger |
Py/R |
To comprehensively evaluate the generalization capability and robustness of the SpaCellAgent framework, we curated a diverse benchmark suite comprising three published real-world datasets, one unpublished real-world dataset, and one simulated dataset. These datasets encompass a wide spectrum of biological contexts, ranging from distinct organisms to varying tissue types. We fix the seed as 42 to ensure that the same spatial transcriptomics dataset yields consistent analytical trajectories across multiple runs.
Crucially, the selected datasets exhibit significant heterogeneity in terms of data sparsity, sequencing depth, and underlying topological complexity (including linear, bifurcation, and multifurcation trajectories). This diversity allows us to rigorously assess the agent’s ability to autonomously adapt its analysis strategy to different data distributions and sequencing technologies (e.g., 10x Genomics, Smart-seq2, and spatial transcriptomics protocols).
| Dataset | Organism | Shape (Cell \(\times\) Gene) | Technology | Type | Source |
|---|---|---|---|---|---|
| Mouse Midbrain (E12.5) | Mouse | \(3,671 \times 24,045\) | Stereo-seq | Spatial | Chen et al. |
| Mouse Midbrain (E14.5) | Mouse | \(3,648 \times 24,045\) | Stereo-seq | Spatial | Chen et al. |
| Mouse Midbrain (E16.5) | Mouse | \(19,419 \times 24,045\) | Stereo-seq | Spatial | Chen et al. |
| Mouse Midbrain (Total) | Mouse | 26,738 \(\times\) 24,045 | Stereo-seq | Spatial | Chen et al. |
| Axolotl Neuron (D2) | Axolotl | \(518 \times 10,000\) | Stereo-seq | Spatial | Chen et al. |
| Axolotl Neuron (D5) | Axolotl | \(726 \times 10,000\) | Stereo-seq | Spatial | Chen et al. |
| Axolotl Neuron (D10) | Axolotl | \(911 \times 10,000\) | Stereo-seq | Spatial | Chen et al. |
| Axolotl Neuron (D20) | Axolotl | \(1,437 \times 10,000\) | Stereo-seq | Spatial | Chen et al. |
| Axolotl Neuron (D30) | Axolotl | \(1,345 \times 10,000\) | Stereo-seq | Spatial | Chen et al. |
| Axolotl Neuron (Total) | Axolotl | 4,937 \(\times\) 10,000 | Stereo-seq | Spatial | Chen et al. |
| Mouse SCI (HSSAM) | Mouse | \(9,094 \times 55,401\) | 10x Genomics | scRNA-seq | This work |
| Mouse SCI (HSD7) | Mouse | \(13,526 \times 55,401\) | 10x Genomics | scRNA-seq | This work |
| Mouse SCI (HSD28) | Mouse | \(11,268 \times 55,401\) | 10x Genomics | scRNA-seq | This work |
| Mouse SCI (NSSAM) | Mouse | \(9,926 \times 55,401\) | 10x Genomics | scRNA-seq | This work |
| Mouse SCI (NSD7) | Mouse | \(8,145 \times 55,401\) | 10x Genomics | scRNA-seq | This work |
| Mouse SCI (NSD28) | Mouse | \(11,074 \times 55,401\) | 10x Genomics | scRNA-seq | This work |
| Mouse SCI (Total) | Mouse | 63,033 \(\times\) 55,402 | 10x Genomics | scRNA-seq | This work |
0pt
| Organism | Shape (Cell \(\times\) Gene) | Technology | Type | Source |
|---|---|---|---|---|
| Mouse | \(291 \times 3,582\) | Fluidigm C1 | scRNA-seq | GSE52529 |
| Mouse | \(65 \times 1,095\) | Fluidigm C1 | scRNA-seq | GSE52583 |
| Mouse | \(541 \times 3,630\) | Smart-seq | scRNA-seq | GSE48968 |
| Mouse | \(408 \times 3,387\) | Smart-seq | scRNA-seq | |
| Mouse | \(435 \times 3,604\) | Smart-seq | scRNA-seq | |
| Mouse | \(264 \times 5,310\) | Fluidigm C1 | scRNA-seq | E-MTAB-2805 |
| Human | \(272 \times 5,708\) | Tang et al. | scRNA-seq | GSE63818 |
| Human | \(166 \times 3,457\) | Tang et al. | scRNA-seq | |
| Human | \(101 \times 3,502\) | Tang et al. | scRNA-seq | |
| Human | \(222 \times 3,766\) | Fluidigm C1 | scRNA-seq | GSE64016 |
| Mouse | \(238 \times 1,845\) | Fluidigm C1 | scRNA-seq | GSE60781 |
| Human | \(1,299 \times 4,135\) | Fluidigm C1 | scRNA-seq | E-MTAB-3929 |
| Mouse | \(873 \times 2,863\) | Smart-seq | scRNA-seq | GSE59114 |
| Mouse | \(493 \times 2,406\) | Smart-seq | scRNA-seq | |
| Mouse | \(158 \times 1,737\) | Fluidigm C1 | scRNA-seq | GSE71982 |
| Mouse | \(117 \times 1,673\) | Fluidigm C1 | scRNA-seq | |
| Mouse | \(85 \times 1,584\) | Fluidigm C1 | scRNA-seq | |
| Mouse | \(85 \times 1,648\) | Fluidigm C1 | scRNA-seq | |
| Mouse | \(197 \times 3,982\) | Fluidigm C1 | scRNA-seq | GSE74596 |
| Mouse | \(355 \times 3,301\) | Fluidigm C1 | scRNA-seq | GSE67310 |
| Mouse | \(3,694 \times 999\) | Fluidigm C1 | scRNA-seq | GSE75330 |
| Human | \(4,959 \times 1,008\) | Fluidigm C1 | scRNA-seq | |
| Human | \(501 \times 3,523\) | Fluidigm C1 | scRNA-seq | GSE85066 |
| Macaque | \(182 \times 5,273\) | SC3-seq | scRNA-seq | GSE74767 |
| Macaque | \(83 \times 4,780\) | SC3-seq | scRNA-seq | |
| Macaque | \(272 \times 5,376\) | SC3-seq | scRNA-seq | |
| Macaque | \(351 \times 5,416\) | SC3-seq | scRNA-seq | |
| Mouse | \(318 \times 2,702\) | Fluidigm C1 | scRNA-seq | GSE70240, 243, 244, 236 |
| Mouse | \(376 \times 2,967\) | Fluidigm C1 | scRNA-seq | GSE70240, 244, 236 |
| Mouse | \(60 \times 1,849\) | Smart-seq2 | scRNA-seq | GSE79363 |
| Mouse | \(749 \times 1,033\) | Fluidigm C1 | scRNA-seq | GSE67602 |
| Mouse | \(699 \times 1,060\) | Fluidigm C1 | scRNA-seq | |
| Mouse | \(346 \times 1,009\) | Fluidigm C1 | scRNA-seq | |
| Mouse | \(213 \times 4,872\) | Fluidigm C1 | scRNA-seq | GSE90860 |
| Human | \(659 \times 3,630\) | Smart-seq2 | scRNA-seq | GSE86146 |
| Human | \(629 \times 4,691\) | Smart-seq2 | scRNA-seq | |
| Human | \(659 \times 3,630\) | Smart-seq2 | scRNA-seq | |
| Human | \(671 \times 4,459\) | Smart-seq2 | scRNA-seq |
15pt
| Organism | Shape (Cell \(\times\) Gene) | Technology | Type | Source |
|---|---|---|---|---|
| Mouse | \(322 \times 6,763\) | Smart-seq2 | scRNA-seq | GSE87375 |
| Mouse | \(563 \times 6,372\) | Smart-seq2 | scRNA-seq | |
| Mouse | \(503 \times 2,037\) | Smart-seq2 | scRNA-seq | GSE90047 |
| Mouse | \(192 \times 1,534\) | Smart-seq2 | scRNA-seq | GSE99951 |
| Mouse | \(456 \times 3,585\) | Smart-seq2 | scRNA-seq | |
| Fly | \(277 \times 1,514\) | Smart-seq2 | scRNA-seq | GSE100058 |
| Fly | \(169 \times 982\) | Smart-seq2 | scRNA-seq | |
| Fly | \(454 \times 2,703\) | Smart-seq2 | scRNA-seq | |
| Mouse | \(3,580 \times 698\) | 10X Chromium | scRNA-seq | GSE95315 |
| Mouse | \(414 \times 12,532\) | rdRNA-seq | scRNA-seq | GSE98664 |
15pt
To ensure the robustness of downstream trajectory inference tasks and mitigate the technical noise inherent in high-throughput sequencing technologies (e.g., dropouts, amplification bias), we implement a rigorous preprocessing pipeline \(\Phi\). Let \(\mathcal{D} = \{(\mathbf{x}_i, \mathbf{s}_i)\}_{i=1}^N\) denote the raw dataset, where \(\mathbf{x}_i \in \mathbb{R}^M\) represents the gene expression vector for cell \(i\) across \(M\) genes, and \(\mathbf{s}_i \in \mathbb{R}^2\) denotes its spatial coordinates (if applicable). The pipeline transforms this raw input into a denoised, low-dimensional latent representation \(\mathbf{Z}\), formally defined as:
\[\mathbf{Z} = \Phi(\mathbf{X}) = \text{PCA}(\text{SelectFeatures}(\text{LogNorm}(\text{QC}(\mathbf{X})))).\]
The detailed protocol typically involves the following four stages:
The first stage filters out low-quality observations that could introduce artifacts into the manifold learning process. We define the set of valid cells \(\mathcal{D}'\) by imposing constraints on the library size (total counts) and mitochondrial content. Low library sizes often indicate empty droplets or dead cells, while anomalously high counts suggest doublets. High mitochondrial proportions are a signature of cellular stress or apoptosis. \[\begin{align} \mathcal{D}' = \{i \mid \quad & \text{min\_genes} < \|\mathbf{x}_i\|_0 < \text{max\_genes} \\ \land \quad & \text{pct\_mt}(\mathbf{x}_i) < \theta_{mt} \}. \end{align}\] where \(\|\mathbf{x}_i\|_0\) denotes the number of detected genes (L0 norm), and \(\theta_{mt}\) is the threshold for mitochondrial percentage (typically \(10\% - 20\%\)).
Since cellular sequencing depths can vary significantly due to technical capture efficiency rather than biological differences, we apply a global scaling normalization. The expression vector for each cell is normalized to a fixed total count \(s\): \[\mathbf{x}_i' = s \cdot \frac{\mathbf{x}_i}{\sum_j x_{ij}}.\] Subsequently, we apply a natural logarithm transformation to stabilize the variance across the dynamic range of expression values and to transform the data distribution closer to normality: \[\mathbf{x}_i'' = \ln(\mathbf{x}_i' + 1).\] The addition of a pseudo-count of 1 preserves sparsity for non-expressed genes.
To reduce computational complexity and focus on biological heterogeneity, we subset the feature space to Highly Variable Genes (HVGs). We model the relationship between mean expression \(\mu_j\) and dispersion \(\sigma^2_j\) for each gene \(j\). Genes with a dispersion significantly higher than expected given their mean expression are retained, forming the subset \(G_{HVG}\) (typically \(|G_{HVG}| \approx 2000\)). This step effectively filters out housekeeping genes (constant expression) and low-abundance noise.
Finally, we project the high-dimensional normalized data restricted to \(G_{HVG}\) into a lower-dimensional latent space to capture the principal axes of variation. We perform Principal Component Analysis (PCA) via Singular Value Decomposition (SVD) on the centered and scaled data matrix: \[\mathbf{Z} = \text{SVD}_k(\mathbf{X}_{HVG} - \bar{\mathbf{X}}_{HVG}).\] The resulting matrix \(\mathbf{Z} \in \mathbb{R}^{N \times k}\) (where \(k=50\)) serves as the compact input representation for the subsequent agent-driven trajectory inference modules. This projection preserves the global topology of the cellular manifold while discarding orthogonal components largely attributed to technical noise.
LLM-based baselines comparison. We conducted an additional experiment to compare our framework with the following LLM-based baselines to demonstrate the advantages of our framework:
CellAgent: a LLM-driven multi-agent framework for single-cell RNA sequencing (scRNA-seq) data analysis.
scAgents: a multi-agent framework for fully autonomous end-to-end single-cell analysis.
We experiment with five subsets (S1 to S5) from the real gold benchmark and calculate the Spearman rank correlation. The results are in the Table 9. According to the results, our method shows the best performance.
| Method | S1 | S2 | S3 | S4 | S5 | |
|---|---|---|---|---|---|---|
| CellAgent | 0.473 | 0.577 | 0.577 | 0.481 | 0.703 | |
| scAgents | 0.440 | 0.458 | 0.533 | 0.475 | 0.642 | |
| Ours | 0.526 | 0.615 | 0.571 | 0.483 | 0.755 |
Quantitative biological validation. To quantitatively validate the biological fidelity of the trajectories results in the main experiment, we performed an enrichment analysis based on our TI results of the three real-world datasets. Specifically, we quantified the GO enrichment p-values for the dynamic driver genes identified along the trajectory. The results are given in the Table 10. The results can statistically prove that the genes discovered by our agent are significantly enriched in the expected biological pathways.
| Metrics | Midbrain | Axolotl | SCI |
|---|---|---|---|
| P-values | < 0.001 | < 0.001 | < 0.001 |
| Task ID | Task Name | Description & Objectives |
|---|---|---|
| Task 1 | Data Ingestion and Quality Control | Load raw expression matrix and spatial coordinates. Filter low-quality cells (e.g., high mitochondrial content, low gene counts) to output a cleaned AnnData object. |
| Task 2 | Preprocessing and Normalization | Normalize data (e.g., CPM) and perform logarithmic transformation. Identify Highly Variable Genes (HVGs) to mitigate feature space noise. |
| Task 3 | Dimensionality Reduction | Perform Principal Component Analysis (PCA) on HVGs, followed by non-linear reduction (e.g., UMAP, t-SNE) to visualize the global manifold structure. |
| Task 4 | Clustering and Root Identification | Cluster cells (Leiden/Louvain) and identify the trajectory start point ("root") via automatic marker detection (e.g., stemness genes) or user priors. |
| Task 5 | Trajectory Inference and Pseudotime Calculation | Core Step: Apply specific TI algorithms (e.g., PAGA, DPT, Monocle) to infer the lineage backbone and calculate pseudotime values for all cells. |
| Task 6 | Visualization and Result Export | Visualize the inferred trajectory on low-dimensional embeddings (colored by pseudotime) and export the final object for downstream analysis. |
To provide a comprehensive qualitative assessment of SpaCellAgent, we present additional visualizations of the inferred cellular trajectories across benchmarks, as shown in Figure 12 13 14 11 10. The figures below illustrate the low-dimensional manifold embeddings colored by inferred pseudotime and ground-truth cell types. These visualizations visually substantiate our quantitative findings, demonstrating the framework’s capability to correctly recover complex topologies, including linear, bifurcating, and multifurcating lineages, that characterize diverse biological processes.
Beyond reconstructing the backbone of cellular development, SpaCellAgent autonomously conducts downstream characterization to uncover biological mechanisms. In this section, we include supplementary results of the Axolotl Neuron Regeneration dataset (15 16), and visualizations of gene expression dynamics along the inferred paths of the Mouse Dorsal Midbrain dataset (17). The following heatmaps and gene trend plots highlight the agent’s ability to identify spatially and temporally variable genes that drive cell fate decisions, confirming the biological plausibility of the reconstructed lineages.
Due to space constraints in the main manuscript, we provide an extended analysis of the case studies here. We intermediate outputs generated during the analysis of theunpublished Mouse SCI datasets. As shown in Figure 18, the visualization of the pseudotime plot and PAGA plot shows the global TI of Mouse SCI datasets. Then, we plot the DEG heat map of the whole Mouse SCI dataset using SpaCellAgent, as shown in Figure 19. Subsequently, we conduct gene ontology enrichment analysis on the whole dataset, as shown in Figure 20. These results further exemplify the robustness of the self-evolution module, visualizing how the agent detects anomalies, corrects errors, and iteratively refines the trajectory model to align with biological priors.
Expert Selection.We recruit 5 domain experts: Expert 1 holds a Ph.D. degree in biomedical engineering. Expert 2 to 5 holds Ph.D. degrees in clinical medicine. Crucially, all experts possess over 3 years of hands-on experience in omics data analysis.
Standardized Instructions. Before the experiment, all experts receive a briefing on the task objectives and success criteria:
Task objectives. They are provided with basic information about the test datasets, a standardized analysis workflow, and the flexibility to select their preferred analytical tools based on personal expertise and preference.
Success criteria. When the expert finishes the TI analysis and validates its biological relevance and significance.
Tool Equivalency. The human experts are equipped with standard SOTA computational tools widely used in the industry. We list these computational tools and provide them to both the human experts and SpaCellAgent.
Timing Protocol. The timer commences exactly when the raw datasets are made available to the user/expert and concludes when the final validated output is submitted. For a rigorous comparison, we partition the standard trajectory inference analysis into five standardized stages: Step 1: Data Preprocessing, Step 2: Batch Correction, Step 3: Cell Type Annotation, Step 4: Dimensionality Reduction and Clustering, Step 5: Trajectory inference and pseudotime calculation.
Statistical Variance Analysis. To strengthen the claim of our 41.2% improvement, we provide the experiment details of appropriate statistical summaries (mean and standard deviation). The results are in the following table.
To guarantee a fair and rigorous benchmark across all ablation variants (including SpaCellAgent w/o Planner, Evaluator, or Self-Evolution) and the GPT-4 baseline, we established a Standardized TI Workflow. This protocol systematically deconstructs the multifaceted lineage reconstruction process into six distinct, sequential tasks, mirroring the standard bioinformatics pipeline from data ingestion to visualization. Crucially, this granular decomposition allows us to pinpoint specific failure modes, whether they stem from logic errors in pseudotime calculation or syntax errors in plotting, thereby offering a high-resolution view of each component’s contribution. For the quantitative assessment via Task Success Rate (TSR), a variant is deemed successful at a specific step strictly if it generates executable code that yields valid intermediate artifacts without runtime exceptions. The detailed definitions of these six pivotal tasks are enumerated in Table 11. In our ablation study, the full SpaCellAgent autonomously generates this 5-step plan via its planner. In contrast, the w/o Planner variant attempts to execute the entire pipeline in a monolithic block, while GPT-4 operates without the guidance of this structured decomposition.
| Task ID | Task Name | |
|---|---|---|
| Task 1 | Data Ingestion and Quality Control | |
| Task 2 | Preprocessing and Normalization | |
| Task 3 | Dimensionality Reduction | |
| Task 4 | Clustering and Root Identification | |
| Task 5 | Trajectory Inference and Pseudotime Calculation |
To quantitatively verify the effectiveness of the Knowledge-augmented fallback mechanism, we conduct an ablation study with the w/o experience memory variants on the real-gold dataset. We calculate the Spearman’s rank correlation, p-value, and the total time cost. The results are shown in Table 13.
| Model | correlation | P-value | Time cost |
|---|---|---|---|
| w/o experience memory | 0.526 | < 0.001 | 46.0 |
| Ours | 0.538 | < 0.001 | 38.0 |
Recent Advancements in Robust Learning and Reasoning. In recent years, significant progress has been made in enhancing machine learning performance under complex data constraints and reasoning tasks. Addressing the challenges of data scarcity and distribution shifts, researchers have developed innovative frameworks for few-shot hypothesis adaptation [39], [40] and novel class discovery [41], [42], which effectively improve model generalization in open-world scenarios. Beyond statistical learning, there is a growing trend towards integrating causal mechanisms into deep learning. For instance, Li et al. [43] introduced transformer-based architectures for spatial-temporal counterfactual estimation, while Chi et al. [44] conducted comprehensive evaluations to unveil the underlying causal reasoning capabilities of large language models.