Skip to content

Latest commit

 

History

20 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

RPuGB: Spatial Perturbation and Tissue Simulation Library for Functional Genomics

RPuGB (Raeumliche Perturbations- und Gewebesimulations-Bibliothek) is a scientific Python library for spatial perturbation analysis, causal bystander decoupling, and in silico tissue simulation in functional genomics. Staged as a software Resource for functional genomics, RPuGB decouples non-cell-autonomous microenvironmental bystander effects from cell-autonomous responses in spatial CRISPR screens, models spatiotemporal pharmacodynamics via anisotropic reaction-diffusion partial differential equations, synthesizes counterfactual tissue states with generative graph diffusion transformers, and programmatically audits execution against 51 binding European Union, Finnish national, and Nordic cross-border statutory instruments.


1. The 14 Lanthanide Engines

RPuGB is organized into fourteen specialized Lanthanide engines (Module 58 Cerium to Module 71 Lutetium). Each engine is mapped to the lanthanide element whose physical or optical properties parallel the computational phase it executes:

Element Engine Name Subpackage Functional Scope and Biophysical Analogy
58 Ce Cerium rpugb.ce Optical barcode decoding, maximum likelihood guide assignment, and SpatialData Zarr synchronization. (Cerium is used in precision optical glass polishing).
59 Pr Praseodymium rpugb.pr Spatial QC filtering, illumination depth normalization, serial slice alignment, and optical crosstalk deconvolution. (Praseodymium filters spectral light).
60 Nd Neodymium rpugb.nd Spatial graph topologies (Delaunay, $k$-NN, radius), continuous distance decay kernels, and Moran's $I$ autocorrelation. (Neodymium generates permanent magnetic fields).
61 Pm Promethium rpugb.pm Robinson Double Machine Learning (DML), spatial propensity fitting, DAG causal discovery, and bystander field decoupling. (Promethium emits radiating energy).
62 Sm Samarium rpugb.sm Spatially lagged ligand-receptor rewiring, paracrine gradient attenuation distance, and niche remodeling scoring. (Samarium captures neutrons in nuclear reactors).
63 Eu Europium rpugb.eu Spatial response cartography, radial phenotypic profiles, causal effect distributions, and Nature Biotechnology vector exports. (Europium produces vivid red phosphorescence).
64 Gd Gadolinium rpugb.gd Multichannel contrast enhancement, 3D volumetric tissue slicing, and interactive Napari polygon ROI selection. (Gadolinium provides contrast in medical imaging).
65 Tb Terbium rpugb.tb Tissue interface gradient detection, tumor margin displacement velocity, and immune infiltration flux modeling. (Terbium detects magneto-acoustic structural phase shifts).
66 Dy Dysprosium rpugb.dy Finite-volume reaction-diffusion PDEs, anisotropic permeability tensors, and spatial Hill equation dose-response. (Dysprosium maintains stability under extreme thermal gradients).
67 Ho Holmium rpugb.ho Targeted in silico CRISPR knockouts, combinatorial disruption screens, and sequence guide efficiency calibration. (Holmium lasers execute microscopic surgical cuts).
68 Er Erbium rpugb.er Spatial Graph Diffusion Transformers, Latent Spatial VAEs, counterfactual slice sampling, and Wasserstein-1 fidelity metrics. (Erbium amplifiers regenerate optical signals).
69 Tm Thulium rpugb.tm Precision benchmarking against Mixscape, scMAGeCK, and Pertpy, calculating spatial SNR and causal recovery rates. (Thulium provides precise calibration standards).
70 Yb Ytterbium rpugb.yb Custom PyTorch CUDA kernels, AMD ROCm LUMI supercomputer optimization, multi-GPU distributed tensors, and Slurm synthesis. (Ytterbium powers accurate atomic clocks).
71 Lu Lutetium rpugb.lu In silico synthetic lethality prediction, theranostic window scoring ($\Theta$), multi-target drug ranking, and 3Rs animal replacement tracking. (Lutetium-177 is the premier targeted cancer theranostic).

2. Installation and Environment Setup

RPuGB supports Linux x86_64, Linux aarch64, macOS Apple Silicon (ARM64), and Microsoft Windows under Python 3.10, 3.11, and 3.12.

2.1 Standard Installation via PyPI

pip install rpugb

2.2 Optional Acceleration and Interactive Extras

# GPU acceleration (PyTorch, PyG)
pip install rpugb[gpu]

# Interactive 3D visualization with Napari
pip install rpugb[viz]

# Spatial ecosystem and SpatialData bridge
pip install rpugb[spatial]

# Complete development and documentation suite
pip install rpugb[all]

2.3 Installation from Source

git clone https://github.com/olaflaitinen/rpugb.git
cd rpugb
pip install -e ".[all]"

2.4 Pinned Scientific Conda Environment

conda env create -f environment.yml
conda activate rpugb

3. Quick Start: Bystander Decoupling Workflow

The following minimal example demonstrates spatial graph construction, continuous distance decay kernel evaluation, and Robinson Double Machine Learning causal bystander decoupling on a synthetic annular perturbation field:

import anndata as ad
import numpy as np
import rpugb
import rpugb.nd as nd
import rpugb.pm as pm
from rpugb.utils.datasets import generate_synthetic_perturbation_field

# 1. Generate synthetic annular perturbation field (1,000 cells, 100 genes)
adata = generate_synthetic_perturbation_field(n_cells=1000, n_genes=100, seed=42)

# 2. Construct spatial Delaunay graph and compute continuous Gaussian distance decay weights
nd.build_spatial_graph(adata, method="delaunay")
nd.compute_niche_weights(adata, decay_function="gaussian", bandwidth=50.0)

# 3. Decouple cell-autonomous effects from radiating bystander influence fields
pm.decouple_bystander_effects(
    adata,
    target_col="perturbation_status",
    control_label="non_targeting",
    spatial_key="spatial",
    n_folds=5,
)

# 4. Inspect decoupled effect matrices in AnnData
print("Autonomous Effect Matrix Shape:", adata.obsm["rpugb_autonomous_effect"].shape)
print("Bystander Effect Matrix Shape: ", adata.obsm["rpugb_bystander_effect"].shape)

The complete end-to-end workflow from raw multiplexed image ingestion to combinatorial knockout modeling and Slurm batch submission is provided in examples/crispr_screen_end_to_end.py.


4. Core Mathematical Formulations and Lanthanide Algorithms

In accordance with Nature Portfolio reporting standards, all mathematical methods and statistical estimators implemented in RPuGB are formally derived below:

4.1 Causal Bystander Decoupling via Double Machine Learning (Promethium, Module 61)

Promethium estimates unconfounded Average Treatment Effects (ATE) under localized spatial confounding by executing Robinson's semi-parametric transformation over cross-fitting folds $I_k$:

$$ \hat{\tau} = \frac{\sum_{i \in I_k} \tilde{T}_i \tilde{Y}_i}{\sum_{i \in I_k} \tilde{T}_i^2} $$

where $\tilde{T}_i = T_i - \hat{m}(X_i)$ represents the residualized treatment assignment indicator, $\tilde{Y}_i = Y_i - \hat{g}(X_i)$ represents the residualized spatial expression outcome, and nuisance conditional expectations $\hat{m}$ and $\hat{g}$ are estimated over the out-of-fold complementary data partition $I_k^{c}$.

4.2 Spatial Autocorrelation Statistics (Neodymium, Module 60)

Neodymium quantifies spatial gene expression patterning and coordinate clustering via the global Moran's $I$ statistic:

$$ I = \frac{n}{\sum_{i} \sum_{j} w_{ij}} \cdot \frac{\sum_{i} \sum_{j} w_{ij} (x_i - \bar{x})(x_j - \bar{x})}{\sum_{i} (x_i - \bar{x})^2} $$

where $w_{ij}$ denotes the spatial connectivity weight between cells $i$ and $j$, $n$ is the total cell count, $x_i$ is the single-cell expression value, and $\bar{x}$ is the global mean expression across the tissue coordinate space.

4.3 Reaction-Diffusion Pharmacodynamics (Dysprosium, Module 66)

Dysprosium models spatiotemporal drug diffusion, vascular clearance, and therapeutic consumption over irregular tissue meshes using non-linear finite-volume PDE integration:

$$ \frac{\partial C}{\partial t} = \nabla \cdot (D(\mathbf{x}) \nabla C) - k_{\text{clear}} C + S(\mathbf{x}, t) $$

where $C(\mathbf{x}, t)$ is the local molecular concentration, $D(\mathbf{x})$ is the spatially varying anisotropic permeability tensor derived from extracellular matrix density, $k_{\text{clear}}$ is the first-order clearance rate constant, and $S(\mathbf{x}, t)$ represents the vascular injection source term. Local phenotypic response is modeled via the spatial Hill equation:

$$ E(C) = E_{\max} \cdot \frac{C^{n_H}}{EC_{50}^{n_H} + C^{n_H}} $$

where $E_{\max}$ is the maximal biological effect, $EC_{50}$ is the half-maximal effective concentration, and $n_H$ is the Hill cooperativity coefficient.

4.4 In Silico Theranostic Window Index (Lutetium, Module 71)

Lutetium prioritizes therapeutic targets and combinatorial CRISPR disruptions by computing the in silico theranostic window index:

$$ \Theta = \frac{E_{\text{tumor}}}{E_{\text{healthy}}} $$

where $E_{\text{tumor}}$ and $E_{\text{healthy}}$ represent the model-predicted phenotypic killing efficacy in tumor compartments and adjacent healthy tissue margins, respectively.

4.5 Intercellular Ligand-Receptor Rewiring (Samarium, Module 62)

Samarium calculates the cell-specific intercellular communication potential for a ligand-receptor pair $(l, r)$ by multiplying cellular ligand expression with the spatially lagged receptor expression of its contiguous neighborhood $N(i)$:

$$ S_{i,(l,r)} = E_{i,l} \cdot \frac{1}{|N(i)|} \sum_{j \in N(i)} E_{j,r} $$

The condition-level differential rewiring score between perturbed cells $T$ and non-targeting control cells $C$ is computed as:

$$ \Delta_{(l,r)} = \frac{1}{|T|} \sum_{i \in T} S_{i,(l,r)} - \frac{1}{|C|} \sum_{i \in C} S_{i,(l,r)} $$

4.6 Tissue Margin Boundary Displacement Velocity (Terbium, Module 65)

Terbium tracks morphological boundary displacement velocities across histological compartments between consecutive time points $t_1$ and $t_2$:

$$ v = \frac{1}{|M|} \sum_{i \in M} \frac{d_i(t_2) - d_i(t_1)}{t_2 - t_1} $$

where $M$ is the index set of margin boundary cells and $d_i(t)$ is the signed Euclidean distance of cell $i$ to the tumor-stroma interface at time $t$.

4.7 Counterfactual Diffusion Sample Fidelity (Erbium, Module 68)

Erbium evaluates the biological distributional fidelity of generative counterfactual tissue states against observed ground-truth manifolds using the Wasserstein-1 distance and Maximum Mean Discrepancy ($\mathrm{MMD}^2$):

$$ W_1(P, Q) = \inf_{\gamma \in \Gamma(P, Q)} \int |x - y| , d\gamma(x, y) $$

$$ \mathrm{MMD}^2(P, Q) = \mathbb{E}_{x, x' \sim P} [k(x, x')] + \mathbb{E}_{y, y' \sim Q} [k(y, y')] - 2 , \mathbb{E}_{x \sim P, y \sim Q} [k(x, y)] $$

where $\Gamma(P, Q)$ represents all joint probability couplings with marginal distributions $P$ and $Q$, and $k(x, y) = \exp(-|x - y|^2 / 2\sigma^2)$ is the characteristic Gaussian radial basis function kernel.


5. Benchmarking and Scalability Standards

RPuGB enforces automated nightly benchmarking via Thulium (rpugb.tm) against single-cell and spatial baselines:

  1. Comparative Accuracy: Demonstrates a minimum 35% improvement in True Positive Causal Gene Detection over non-spatial baseline frameworks (Mixscape, scMAGeCK linear modeling, Pertpy GLMs) under spatially autocorrelated noise.
  2. Computational Throughput:
    • 10,000 cells: Sub-second graph construction and causal decomposition (< 0.8 seconds on standard GPU).
    • 100,000 cells: Complete pipeline execution under 45 seconds using Ytterbium (Yb, Module 70) GPU acceleration.
  3. Memory Footprint: Strict peak VRAM ceiling of 4.2 GB during full counterfactual diffusion passes on 100,000-cell spatial graphs.

6. Statutory, Regulatory, and Nordic Governance Compliance

The rpugb.compliance subpackage programmatically audits and enforces 51 binding European Union regulations, Finnish national acts, and Nordic cross-border governance frameworks:

  • European Union Acts: EU AI Act (Regulation (EU) 2024/1689), EuroHPC Joint Undertaking (Regulation (EU) 2021/1173), EuroHPC AI Factories Amendment (Regulation (EU) 2024/1732), Cyber Resilience Act (Regulation (EU) 2024/2847), GDPR (Regulation (EU) 2016/679), EHDS (Regulation (EU) 2025/327), EU Data Act (Regulation (EU) 2023/2854), Data Governance Act (Regulation (EU) 2022/868), SoHO Regulation (Regulation (EU) 2024/1938), Contained Use GMM Directive (Directive 2009/41/EC), Nagoya Protocol (Regulation (EU) No 511/2014), Biological Agents Directive (Directive 2000/54/EC), IVDR (Regulation (EU) 2017/746), MDR (Regulation (EU) 2017/745), CTR (Regulation (EU) No 536/2014), EMA Proposal (COM(2023) 193), Human Medicinal Products Proposal (COM(2023) 192), Animal Protection 3Rs Directive (Directive 2010/63/EU), DSM Copyright TDM Directive (Directive (EU) 2019/790), Biotech Patents Directive (Directive 98/44/EC), EU Dual-Use Export Controls (Regulation (EU) 2021/821), STEP Regulation (Regulation (EU) 2024/795), EU Biotech Communication (COM(2024) 137), Horizon Europe (Regulation (EU) 2021/695).
  • Finnish National Legislation: Biopankkilaki (688/2012), Toisiolaki (552/2019), Geeniteknologialaki (377/1995), Tietosuojalaki (1050/2018), Kudoslaki (101/2001), Laki laakinnallisista laitteista (719/2021), Laki laaketieteellisesta tutkimuksesta (488/1999), Laki kliinisesta laaketutkimuksesta (983/2021), Laki tieteellisiin tarkoituksiin kaytettavien elainten suojelusta (497/2013), Asetus geenitekniikan suljetusta kaytosta (1053/2005), Tekijanoikeuslaki (404/1961 amended 1259/2022), Laki kaksikayttotuotteiden vientivalvonnasta (500/2024), Asiakastietolaki (703/2023), Tartuntatautilaki (1227/2016).
  • Nordic Governance Frameworks: Helsinki Treaty (1962), Kalmar II Declaration (2023), Nordic Commons Vision 2030, Nordic Commons Policy Board Decision (AK-S 2021), Tryggve Sensitive Data Code of Conduct, Heilsa Tryggvedottir Collaboration Framework, Nordic Biotechnology Framework, NCBio Ethical Biobanking Guidelines, BBMRI-Nordic Infrastructure Framework, Nordic Ethical AI and Data Roadmap, NACG Clinical Genomics Consensus, LUMI Supercomputer Consortium Agreement, Norecopa Nordic 3Rs Platform.

All 51 instruments correspond one-to-one with physical statutory PDF documents stored in rpugb/compliance/statutes/. Verification is enforced at package import and during continuous integration:

from rpugb.compliance.statutes_registry import verify_statute_text_corpus

# Programmatic verification of the 51 statutory PDF instruments
is_compliant, audit_message = verify_statute_text_corpus()
print(audit_message)

7. High-Performance Computing and EuroHPC LUMI Deployment

RPuGB provides native optimization for AMD Instinct MI250X GPUs on the LUMI supercomputer (CSC, Kajaani, Finland) via rpugb.yb.rocm_lumi_backend and automated Slurm batch synthesis:

from rpugb.yb.slurm_generator import generate_lumi_slurm_script

# Generate a validated Slurm submission script for LUMI-G AI Factory partition
script_path = generate_lumi_slurm_script(
    job_name="rpugb_spatial_screen",
    account="project_462000000",
    partition="standard-g",
    nodes=2,
    gpus_per_node=8,
    time_limit="04:00:00",
    output_script="submit_lumi.sh",
)

8. Editorial Policies, Data Availability, and Code Availability

8.1 Data Availability Statement

All demonstration datasets included in RPuGB for unit testing and tutorials are procedurally generated synthetic fixtures (tests/data/synthetic_xenium_sample.h5ad and tests/data/synthetic_merscope_sample.h5ad) created via rpugb.utils.datasets. No real, re-identifiable human donor data or patient health records are contained in version control. Tutorials referencing public benchmarks (10x Genomics Xenium breast cancer, Vizgen MERSCOPE mouse brain, NanoString CosMx lung) download raw data directly from vendor open-access portals at runtime.

8.2 Code Availability Statement

The complete source code for RPuGB is permanently hosted at https://github.com/olaflaitinen/rpugb. Archived release snapshots receive persistent Digital Object Identifiers (DOI) through the Zenodo integration (10.5281/zenodo.rpugb). All software releases adhere to the Nature Biotechnology Software Submission Checklist located at docs/software_submission_checklist.rst.

8.3 Competing Interests Statement

The author declares no competing financial or non-financial interests.

8.4 Artificial Intelligence Disclosure

Portions of the introductory tutorial narratives and documentation markup were drafted with the assistance of artificial intelligence tools, and were subsequently fact-checked, corrected, and approved for release by the Principal Investigator, consistent with Nature Portfolio policy on artificial intelligence.


9. Authorship, Academic Attribution, and License

  • Principal Investigator and Lead Architect: Gustav Olaf Yunus Laitinen-Fredriksson Lundstrom-Imanov
  • Researcher Identifier (ORCID iD): 0009-0006-5184-0810
  • Academic Department: School of Information and Communication Technology
  • Higher Education Institution: Metropolia University of Applied Sciences (Metropolia Ammattikorkeakoulu)
  • Campus Facility: Karamalmi Campus, Karaportti 2, FI-02610 Espoo, Finland
  • Direct Telephone: +358 (0)46 583 8095 | Switchboard: +358 9 7424 5000
  • Official Institutional Email: yunus.imanov@metropolia.fi
  • Software License: European Union Public Licence version 1.2 (EUPL-1.2)

10. References and Scholarly Citations

  1. Chernozhukov, V. et al. Double/debiased machine learning for treatment and structural parameters. Econom. J. 21, C1-C68 (2018).
  2. Moffitt, J. R. et al. Molecular, spatial, and functional single-cell profiling of the hypothalamic preoptic region. Science 362, eaau5324 (2018).
  3. Janesick, A. et al. High-resolution mapping of the tumor microenvironment using spatial transcriptomics. Nat. Commun. 14, 2453 (2023).
  4. Dixit, A. et al. Perturb-Seq: Dissecting molecular circuits with scalable single-cell RNA profiling of pooled genetic screens. Cell 167, 1853-1866 (2016).
  5. Laitinen-Fredriksson Lundstrom-Imanov, G. O. Y. Spatial perturbation and tissue simulation library for functional genomics. Nat. Biotechnol. Under Review (2026).

About

RPuGB (Raeumliche Perturbations- und Gewebesimulations-Bibliothek) is a scientific Python library for spatial perturbation analysis, causal bystander decoupling, and in silico tissue simulation in functional genomics.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages