A comprehensive scientific computing library written in pure Rust — zero dependencies, 11 modules, 48 600+ lines of code.
SciForge is organized into 8 scientific domain modules, a central Hub dispatch, a Benchmark pipeline, and a multi-format Parser — all under a single crate with zero external dependencies.
Note: this UI is currently a project presentation layer. The executable HTML artifacts generated by source code are available in the Examples page (from `output/`).
Every line of SciForge follows these non-negotiable principles:
std#[allow] attributes — ever| Module | Submodules | Public APIs | Tests | Documentation | Semver |
|---|---|---|---|---|---|
| Constants | 5 | 57 | 30 | ✔ | ✖ |
| Mathematics | 17 | 977 | 21 | ✔ | ✖ |
| Physics | 11 | 636 | 33 | ✔ | ✖ |
| Chemistry | 26 | 462 | 24 | ✔ | ✖ |
| Biology | 44 | 2474 | 18 | ✔ | ✖ |
| Geology | 4 | 44 | 17 | ✔ | ✖ |
| Astronomy | 4 | 49 | 21 | ✔ | ✖ |
| Meteorology | 4 | 44 | 18 | ✔ | ✖ |
| Hub | 5 | 212 | 30 | ✔ | ✖ |
| Benchmark | 6 | 29 | 28 | ✔ | ✖ |
| Parser | 5 | 90 | 66 | ✔ | ✖ |
Tracking semver validation, documentation coverage, and test coverage across all 11 modules.
11/11 modules
11/11 modules
0/11 modules
| Module | Submodules | Public APIs | Tests | Documentation | Semver | Score |
|---|---|---|---|---|---|---|
| Constants | 5 | 57 | ✓ 30 | ✓ done | ✗ pending | 2/3 |
| Mathematics | 17 | 977 | ✓ 21 | ✓ done | ✗ pending | 2/3 |
| Physics | 11 | 636 | ✓ 33 | ✓ done | ✗ pending | 2/3 |
| Chemistry | 26 | 462 | ✓ 24 | ✓ done | ✗ pending | 2/3 |
| Biology | 44 | 2474 | ✓ 18 | ✓ done | ✗ pending | 2/3 |
| Geology | 4 | 44 | ✓ 17 | ✓ done | ✗ pending | 2/3 |
| Astronomy | 4 | 49 | ✓ 21 | ✓ done | ✗ pending | 2/3 |
| Meteorology | 4 | 44 | ✓ 18 | ✓ done | ✗ pending | 2/3 |
| Hub | 5 | 212 | ✓ 30 | ✓ done | ✗ pending | 2/3 |
| Benchmark | 6 | 29 | ✓ 28 | ✓ done | ✗ pending | 2/3 |
| Parser | 5 | 90 | ✓ 66 | ✓ done | ✗ pending | 2/3 |
Interactive documentation viewer: select a tab, then choose a document from the left panel to render it directly in this page.
A comprehensive scientific computing library written in pure Rust.
SciForge provides a wide range of scientific computing tools spanning mathematics, physics, chemistry, biology, geology, astronomy, and meteorology — all in a single, dependency-free Rust crate.
SciForge currently targets crate version 0.0.2.
The astronomy cosmology stack now includes:
E(z) parameterizations: general, flat LCDM, LCDM with radiation, wCDM, and CPL (w0-wa)H(z) = H0 * E(z) (general and LCDM helpers)DomainType::AstronomyThis enables running cosmology workflows through the unified Hub execution path without bypassing domain dispatch.
| Module | Submodules | Description |
|---|---|---|
| Constants | 5 | Fundamental, astrophysical, atomic constants, unit conversions, element data |
| Mathematics | 17 | Complex numbers, tensors, linear algebra, FFT, ODE/PDE solvers, statistics, optimization |
| Physics | 11 | Relativity, quantum mechanics, thermodynamics, electrodynamics, optics, acoustics |
| Chemistry | 26 | Kinetics, electrochemistry, organic/inorganic, spectroscopy, polymers, quantum chemistry |
| Biology | 44 | Genetics, neuroscience, ecology, evolution, pharmacology, genomics, proteomics |
| Geology | 4 | Seismology, radiometric dating, petrology, plate tectonics |
| Astronomy | 4 | Orbital mechanics, stellar astrophysics, cosmology, celestial mechanics |
| Meteorology | 4 | Atmospheric modeling, radiation transfer, dynamics, precipitation |
| Hub | 5 | Central dispatch API, domain engine, tools, prelude |
| Benchmark | 6 | Benchmark engine, binary encode/decode, simulation, reporting, multi-format export |
| Parser | 5 | CSV, JSON, YAML, Markdown, HTML parsing and validation |
Add SciForge to your Cargo.toml:
[dependencies]
sciforge = "0.0.2"
use sciforge::hub::prelude::*;
let experiment = Experiment::new(DomainType::Astronomy, "hubble_at_z_lcdm")
.param("h0", ParameterValue::Scalar(67.4))
.param("omega_m", ParameterValue::Scalar(0.315))
.param("z", ParameterValue::Scalar(1.0));
let result = ExperimentRunner::new().run(&experiment)?;
SciForge documentation is split into two complementary layers:
docs/modules/ — scientific explanations, assumptions, and equationsdocs/code/ — source layout, API surfaces, and execution flowdocs/Summary.md — entry point mapping each module guide to its matching code guideUse docs/modules/ first for scientific context, then docs/code/ for implementation-level details.
The benchmark module generates a complete interactive HTML dashboard featuring:
118 element data files organized by IUPAC category under tableau-periodique/:
tableau-periodique/
├── actinides/
├── elements-superlourds/
├── gaz-nobles/
├── halogenes/
├── lanthanides/
├── metalloides/
├── metaux-alcalino-terreux/
├── metaux-alcalins/
├── metaux-de-transition/
├── metaux-post-transition/
└── non-metaux/
cargo build
cargo test
Dedicated integration targets include benchmark, parser, constants, maths, physics, chemistry, biology, geology, astronomy, meteorology, hub, scientific_validation, and scientific_properties.
This layout separates domain-level coverage, orchestration tests, and scientific validation suites.
cargo clippy
The project targets zero warnings and zero `#[allow]` directives.
For consistent quality checks, run cargo fmt, cargo clippy, and cargo test before publishing changes.
src/
├── lib.rs
├── constants/ # Physical constants and element data
├── maths/ # Mathematical computing (17 submodules)
├── physics/ # Physics simulations (11 submodules)
├── chemistry/ # Chemical modeling (26 submodules)
├── biology/ # Biological computing (44 submodules)
├── geology/ # Earth sciences (4 submodules)
├── astronomy/ # Astrophysics (4 submodules)
├── meteorology/ # Atmospheric sciences (4 submodules)
├── hub/ # Central dispatch API
├── benchmark/ # Benchmarking and export pipeline
└── parser/ # Multi-format file parsing
tests/
├── benchmark.rs # benchmark integration target
├── parser.rs # parser integration target
├── scientific_validation.rs # scientific reference validation suite
├── scientific_properties.rs # property/invariant validation suite
├── hub/ # Hub orchestration and cross-domain tests
├── constants/ # constants integration suites
├── maths/ # maths integration suites
├── physics/ # physics integration suites
├── chemistry/ # chemistry integration suites
├── biology/ # biology integration suites
├── geology/ # geology integration suites
├── astronomy/ # astronomy integration suites
└── meteorology/ # meteorology integration suites
tableau-periodique/ # 118 element data files
See Contributing.md for guidelines.
See ComingSoon.md for the 0.0.1 roadmap baseline.
See ChangeLog.md for version history.
All notable changes to SciForge are documented in this file.
docs/docs/modules/ for scientific model explanationsdocs/code/ for source and API explanationsdocs/Summary.md to serve as the documentation entry pointoutput/validation/E(z) parameterizations and H(z) helpers0.0.2sciforge crate (Rust edition 2024, zero external dependencies)constants, maths, physics, chemistry, biology, geology, astronomy, meteorology, benchmark, parser, hubapi, domain, engine, tools submodulesengine — benchmark runner with BenchmarkMetrics (iterations, timing, throughput)encode / decode — compact binary .bmk format for benchmark resultssimulation — deterministic benchmark simulation for all 118 elementsreport — JSON, YAML, TOML report generation with tagged metadataexport — multi-format export pipeline:csv — CSV reader/writer with configurable delimiters and quotingjson — JSON parser and validatoryaml — YAML parser and validatormarkdown — Markdown parser and validatorhtml — HTML parser and validatortableau-periodique/:SciForge is an ambitious, single-author scientific computing library written in pure Rust (edition 2024, zero dependencies). It aims to provide a comprehensive, reliable, and efficient ecosystem spanning multiple scientific domains.
The project is maintained solely by the author. Contributions, suggestions, and collaboration requests should follow the Contributing guide.
Implemented: delivered and used in the codebasePartial: present but incomplete or not generalizedRemaining: not finalized yet| Area | Item | Status | Code/Docs Evidence | Remaining Coverage |
|---|---|---|---|---|
| Documentation | Full API reference with input/output examples for every public function | Partial | docs/code/*.md, docs/modules/*.md | Generate an exhaustive reference for all public functions (benchmark, hub, parser) with runnable examples |
| Documentation | Tutorials and guided workflows (simulation, data analysis, cross-domain) | Partial | README.md, docs/ | Add end-to-end scenario tutorials with expected inputs/outputs |
| Documentation | Module-level scientific model guides | Implemented | docs/modules/Astronomy.md, docs/modules/Physics.md, docs/modules/Biology.md, and others | Ongoing maintenance and enrichment |
| Extended Testing | Unit and integration tests for all scientific modules | Partial | tests/constants/*, tests/maths/*, tests/physics/*, tests/chemistry/*, tests/biology/*, tests/geology/*, tests/astronomy/*, tests/meteorology/* | Close remaining coverage gaps in less-tested submodules |
| Extended Testing | Property-style testing and edge-case validation | Implemented | tests/scientific_properties.rs, tests/scientific_validation.rs | Expand invariant coverage per domain |
| Extended Testing | Cross-module integration tests | Implemented | tests/hub/cross_domain.rs, tests/hub/main.rs | Add more multi-step cross-domain scenarios |
| Hub Expansion | Unified dispatch API through Hub | Implemented | src/hub/engine/dispatch/*.rs | Continue signature normalization |
| Hub Expansion | Ergonomic prelude re-exports | Implemented | src/hub/prelude.rs | Stabilize naming conventions |
| Hub Expansion | Domain query engine and tool pipelines | Implemented | src/hub/engine/query.rs, src/hub/engine/pipeline/flow.rs, src/hub/engine/worker/scheduler.rs | Add more predefined pipeline templates |
| Computational Enhancements | Performance benchmarking across scientific modules | Partial | src/benchmark/*, tests/benchmark.rs, output/*/bmk/ | Complete a benchmark matrix for all major subdomains |
| Computational Enhancements | Memory-optimized structures for large-scale workloads | Partial | src/hub/tools/arena.rs, src/hub/tools/profiler.rs | Add systematic memory/performance evidence |
| Computational Enhancements | Deterministic and reproducible execution paths | Implemented | src/hub/tools/deterministic.rs | Extend reproducibility assertions in tests |
| Future Features | Interactive visualization utilities | Implemented | src/hub/tools/visualization.rs, src/benchmark/export.rs | Add more visualization templates |
| Future Features | Extended cross-domain analysis tools (astrochem, geophysics, bioinformatics, etc.) | Partial | src/biology/bioinformatics/*, cross-domain dispatch paths in src/hub/engine/dispatch/* | Expand explicit coupled-domain coverage (astrochem/geophysics) |
| Future Features | Additional export formats and reporting | Implemented | HTML/MD/CSV/JSON/YAML/TOML export via src/benchmark/export.rs and output/ | Add cross-format validation schemas |
| Future Features | Automated scientific validation pipeline | Partial | tests/scientific_validation.rs + output/validation/ artifacts | Formalize a single pipeline command with gating thresholds |
| Status | Count |
|---|---|
| Implemented | 9 |
| Partial | 8 |
| Remaining | 0 |
| Constant | Symbol | Value | Unit | Module |
|---|---|---|---|---|
| Fermi constant | G_F | 1.1663787×10⁻⁵ | GeV⁻² | fundamental |
| Strong coupling constant | ALPHA_S | 0.1181 | dimensionless | fundamental |
| Muon mass | MUON_MASS | 1.883531627×10⁻²⁸ | kg | atomic |
| Tau mass | TAU_MASS | 3.16747×10⁻²⁷ | kg | atomic |
| Neutrino mass | NEUTRINO_MASS | ≤2.2×10⁻³⁶ | kg | atomic |
| Rydberg constant | R_INF | 10973731.56816 | m⁻¹ | atomic |
| Constant | Symbol | Value | Unit | Module |
|---|---|---|---|---|
| Solar density | SOLAR_DENSITY | 1.408 | g/cm³ | astro |
| Solar surface gravity | SOLAR_GRAVITY | 274 | m/s² | astro |
| Earth surface gravity | EARTH_GRAVITY | 9.80665 | m/s² | astro |
| Mars radius | MARS_RADIUS | 3.3895×10⁶ | m | astro |
| Mars mass | MARS_MASS | 6.417×10²³ | kg | astro |
| Cosmological constant | COSMOLOGICAL_LAMBDA | 1.1056×10⁻⁵² | m⁻² | astro |
| Day | DAY | 86400 | s | units |
| Julian year | JULIAN_YEAR | 365.25×DAY | s | units |
| Property | Symbol | Value | Unit | Module |
|---|---|---|---|---|
| Standard density | ELEMENT_DENSITY_Z | variable | g/cm³ | elements |
| Melting point | ELEMENT_MELTING_Z | variable | K | elements |
| Boiling point | ELEMENT_BOILING_Z | variable | K | elements |
| Standard state | ELEMENT_STATE_Z | variable | — | elements |
| Electron configuration | ELEMENT_ECONFIG_Z | variable | — | elements |
| Conversion | Symbol | Value | Module |
|---|---|---|---|
| kWh to J | KWH_TO_J | 3.6×10⁶ | units |
| MeV to J | MEV_TO_J | 1.60218×10⁻¹³ | units |
| Day to s | DAY | 86400 | units |
| Year to s | YEAR | 365.25×DAY | units |
**Email:** The email associated with my [crates.io] account : https://crates.io/users/rayanmorel4498-ai
Discord: The official discod's servor ascociated wiith the SciForge project : https://discord.gg/PtEHcJAruj
SciForge is a pure Rust (edition 2024) scientific computing library with zero external dependencies. It currently spans 11 modules, 575 source files, and 48 600+ lines of code covering mathematics, physics, chemistry, biology, geology, astronomy, meteorology, benchmarking, parsing, and a central hub.
I will review your proposal and provide feedback. If approved, we can coordinate how I'll integrate it.
SciForge follows strict conventions. All contributions must adhere to:
cargo clippy must pass cleanly.cargo test must succeed (currently 94 tests: 28 benchmark + 66 parser).When proposing improvements, please include:
Even rough ideas or pseudocode are welcome — detailed implementation can come later.
I value input on:
Your suggestions help shape a stable and ergonomic API for SciForge.
If you encounter a bug or unexpected behavior:
Please send reports via email or the discord.
I value respect, collaboration, and constructive feedback. Keep discussions professional and welcoming.
Thank you for helping make SciForge better. Your contributions — big or small — are always appreciated.
SciForge is a scientific computing library written in pure Rust, with no external dependencies. It covers a wide range of domains — from classical physics to molecular biology — organized into independent modules, each exposing both a domain specification and a Rust implementation.
This page explains how the documentation is organized, what each section is meant to provide, and how to move between scientific explanations and Rust APIs.
docs/modules/ to understand the scientific scope and models.docs/code/ to inspect the implementation layout and public-facing API.This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.
modules/ and code/ pages depending on whether you need theory or implementation details.modules/ pages focus on scientific models, assumptions, and equations.code/ pages focus on source layout, exported APIs, and execution flow.Each module has two complementary pages:
Celestial mechanics, astrophysics, and cosmology (4 submodules). Covers orbital dynamics (Kepler's laws, vis-viva, Hohmann transfers, orbital perturbations), stellar physics (HR diagram, luminosity-mass-radius relations, main-sequence lifetime, stellar nucleosynthesis), cosmology (direct E(z) parameterizations, H(z) evaluation, comoving/luminosity/angular-diameter distances in LCDM/general/wCDM/CPL, dark-energy equation-of-state models, analytical LCDM shortcuts), and celestial mechanics (ecliptic/equatorial/galactic coordinate transforms, Julian date, sidereal time, nutation).
→ Module spec · Rust API
Performance measurement infrastructure for SciForge (6 submodules). Covers a 30+ field BenchmarkMetrics engine with statistical aggregation and CSV export, a compact binary encoding format (magic header, LE layout, 168+ byte records), zero-copy decoding via BenchmarkMetricsView, a simulation framework with SimState/SimConfig/StepFn traits, multi-format report generation (CSV, Markdown, HTML, JSON, YAML, TOML), and a file-based export orchestrator with periodic-table-themed CSS.
→ Module spec · Rust API
The largest scientific module (44 submodules, 176 source files). Covers aging (Gompertz/Weibull mortality, telomere dynamics), bioelectricity (Nernst, Goldman–Hodgkin–Katz, Hodgkin–Huxley), bioenergetics (ATP yield, Kleiber's law), biomechanics (Poiseuille flow, Hill muscle model), biophysics (Helfrich membrane, WLC, FRET), biostatistics (Kaplan–Meier, meta-analysis), ecology (Lotka–Volterra, Rosenzweig–MacArthur), enzyme kinetics (Michaelis–Menten, Hill, inhibition), evolution (molecular clock, dN/dS, coalescent), genetics (Hardy–Weinberg, $F_{ST}$), immunology (affinity maturation), neuroscience (integrate-and-fire), pharmacology (PK/PD, hepatic clearance), population dynamics (Leslie matrix, SIR/SEIR), synthetic biology (toggle switch, repressilator, FBA), virology (quasispecies, error catastrophe), and 28 more submodules.
→ Module spec · Rust API
Physical, analytical, inorganic, and computational chemistry (26 submodules). Covers acid–base equilibria (Henderson–Hasselbalch, polyprotic titrations), kinetics (Arrhenius, Eyring, Lindemann), electrochemistry (Nernst, Butler–Volmer, Tafel), thermochemistry (Hess's law, Kirchhoff), gas laws (van der Waals, virial, compressibility), quantum chemistry (Hartree–Fock, DFT concepts, Slater determinants), crystallography (Bragg's law, Miller indices, 14 Bravais lattices), molecular modeling (Lennard-Jones, Morse potential, VSEPR), colloids (DLVO theory, Stokes–Einstein), green chemistry (atom economy, E-factor), and environmental chemistry (Henry's law, BOD/COD).
→ Module spec · Rust API
Curated registry of physical constants, astronomical data, atomic properties, and unit conversions (5 submodules). Includes 16 CODATA fundamental constants ($c$, $G$, $h$, $\hbar$, $k_B$, $N_A$, $e$, $\varepsilon_0$, $\mu_0$, $\sigma_{SB}$, $\alpha$, Planck units), 10 astronomical constants (AU, parsec, solar/Earth parameters, Hubble constant), 13 atomic constants (particle masses, Bohr radius, Rydberg energy, magnetons), the full periodic table (118 elements loaded from YAML with OnceLock), and 12 unit conversion factors (eV↔J, cal↔J, atm↔Pa, deg↔rad, barn, ångström, fermi).
→ Module spec · Rust API
Earth sciences and geophysics (4 submodules). Covers radiometric dating (decay law $N(t) = N_0 e^{-\lambda t}$, half-life conversion, isochron method, $^{14}$C calibration), petrology (CIPW norm, magma viscosity, Stokes settling, crystallization sequences), seismology (P/S/surface wave propagation, Gutenberg–Richter, Omori aftershock law, magnitude scales $M_L$/$M_W$/$m_b$, focal mechanisms), and tectonics (plate velocity on a sphere, Euler poles, Byerlee's friction law, thermal subsidence).
→ Module spec · Rust API
Central orchestration layer (5 areas: API, Domain, Engine, Tools, Prelude — 35 source files). Provides a zero-dependency HTTP server (TcpListener-based), structured DTOs (ComputeRequest/ComputeResponse with 8 result types), domain dispatchers for all 7 scientific modules, direct astronomy-cosmology routing (E(z), H(z), and distance functions) through the Hub, an Experiment builder with 15 ParameterValue variants (Scalar through Tensor), a DynamicalSystem trait for ODE simulations (with built-in HarmonicOscillator/LotkaVolterra), priority-based task scheduling with dependency-aware topological sort, campaign batch execution, and tooling (Config, Logger, Metrics).
→ Module spec · Rust API
Numerical methods and pure mathematics (17 submodules). Covers complex arithmetic, linear algebra (Gauss elimination, LU/Cholesky decomposition, eigenvalues), calculus (symbolic differentiation, Simpson/Gauss quadrature, automatic differentiation), ODE solvers (Euler, RK4, adaptive RK45), Fourier and Laplace transforms, statistics (descriptive, distributions, hypothesis testing), probability, number theory (primes, GCD, modular arithmetic), combinatorics, set theory, graph theory (BFS, DFS, Dijkstra, Kruskal), geometry (2D/3D transforms, convex hull), trigonometry, polynomial operations, vector calculus (gradient, divergence, curl, Stokes' theorem), and special functions (Gamma, Beta, Bessel, error function).
→ Module spec · Rust API
Atmospheric science and weather physics (4 submodules). Covers atmosphere (barometric formula, ISA standard layers, pressure altitude, scale height, lapse rates), dynamics (geostrophic/gradient wind, Rossby number, vorticity, thermal wind, Ekman spiral, CAPE/CIN, Richardson number), precipitation (Clausius–Clapeyron, Köhler theory, Marshall–Palmer DSD, $Z$–$R$ relations, terminal velocity, Bergeron process), and radiation (Planck blackbody, Wien's law, Stefan–Boltzmann, solar zenith angle, Beer–Lambert atmospheric extinction, albedo, greenhouse radiative forcing $\Delta F = 5.35 \ln(C/C_0)$).
→ Module spec · Rust API
Multi-format data parsing library with zero dependencies (5 formats, 26 source files). Covers CSV (RFC 4180, CsvValue enum with Table/Record/Field, quoted field handling, writer), JSON (RFC 8259, JsonValue with 6 variants, number/string submodules), YAML (YamlValue with indent-based LineCursor, scalar type auto-detection for booleans/numbers/null — used by the Constants module for periodic table data), HTML (HtmlValue with Document/Element/Text/Comment, named entity decoding — used by Benchmark export), and Markdown (MdValue with 9 block-level variants, inline emphasis/links/code processing). All formats share a layered Cursor<'a> architecture with zero-copy &'a str borrowing and const fn constructors.
→ Module spec · Rust API
Classical and modern physics (11 submodules). Covers acoustics (wave equation, Doppler, decibel scale, resonance), electrodynamics (Maxwell's equations, Lorentz force, electromagnetic waves, Poynting vector), electronics (Ohm's law, RC/RL/RLC circuits, transistor models, op-amp configurations), fluid mechanics (Navier–Stokes, Bernoulli, Reynolds number, drag), materials science (stress–strain, Young's modulus, Hooke's law, creep), nucleosynthesis (binding energy, decay chains, cross-sections, pp-chain, CNO cycle), optics (Snell's law, thin lens, diffraction, interference, polarization), quantum mechanics (Schrödinger equation, particle-in-a-box, harmonic oscillator, hydrogen atom, tunneling), relativity (Lorentz transforms, $E = mc^2$, time dilation, gravitational redshift, Schwarzschild metric), solid mechanics (beam bending, torsion, Mohr's circle, buckling), and thermodynamics (laws of thermodynamics, Carnot cycle, entropy, heat transfer, blackbody radiation).
→ Module spec · Rust API
docs/
├── Summary.md # This file
├── modules/ # Scientific domain documentation (concepts & formulas)
│ ├── Astronomy.md
│ ├── Benchmark.md
│ ├── Biology.md
│ ├── Chemistry.md
│ ├── Constants.md
│ ├── Geology.md
│ ├── Hub.md
│ ├── Mathematics.md
│ ├── Meteorology.md
│ ├── Parser.md
│ └── Physics.md
└── code/ # Rust implementation documentation (API reference)
├── Astronomy.md
├── Benchmark.md
├── Biology.md
├── Chemistry.md
├── Constants.md
├── Geology.md
├── Hub.md
├── Mathematics.md
├── Meteorology.md
├── Parser.md
└── Physics.md
SciForge is a scientific computing library written in pure Rust, with no external dependencies. It covers a wide range of domains — from classical physics to molecular biology — organized into independent modules, each exposing both a domain specification and a Rust implementation.
This page explains how the documentation is organized, what each section is meant to provide, and how to move between scientific explanations and Rust APIs.
docs/modules/ to understand the scientific scope and models.docs/code/ to inspect the implementation layout and public-facing API.This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.
modules/ and code/ pages depending on whether you need theory or implementation details.modules/ pages focus on scientific models, assumptions, and equations.code/ pages focus on source layout, exported APIs, and execution flow.Each module has two complementary pages:
Celestial mechanics, astrophysics, and cosmology (4 submodules). Covers orbital dynamics (Kepler's laws, vis-viva, Hohmann transfers, orbital perturbations), stellar physics (HR diagram, luminosity-mass-radius relations, main-sequence lifetime, stellar nucleosynthesis), cosmology (direct E(z) parameterizations, H(z) evaluation, comoving/luminosity/angular-diameter distances in LCDM/general/wCDM/CPL, dark-energy equation-of-state models, analytical LCDM shortcuts), and celestial mechanics (ecliptic/equatorial/galactic coordinate transforms, Julian date, sidereal time, nutation).
→ Module spec · Rust API
Performance measurement infrastructure for SciForge (6 submodules). Covers a 30+ field BenchmarkMetrics engine with statistical aggregation and CSV export, a compact binary encoding format (magic header, LE layout, 168+ byte records), zero-copy decoding via BenchmarkMetricsView, a simulation framework with SimState/SimConfig/StepFn traits, multi-format report generation (CSV, Markdown, HTML, JSON, YAML, TOML), and a file-based export orchestrator with periodic-table-themed CSS.
→ Module spec · Rust API
The largest scientific module (44 submodules, 176 source files). Covers aging (Gompertz/Weibull mortality, telomere dynamics), bioelectricity (Nernst, Goldman–Hodgkin–Katz, Hodgkin–Huxley), bioenergetics (ATP yield, Kleiber's law), biomechanics (Poiseuille flow, Hill muscle model), biophysics (Helfrich membrane, WLC, FRET), biostatistics (Kaplan–Meier, meta-analysis), ecology (Lotka–Volterra, Rosenzweig–MacArthur), enzyme kinetics (Michaelis–Menten, Hill, inhibition), evolution (molecular clock, dN/dS, coalescent), genetics (Hardy–Weinberg, $F_{ST}$), immunology (affinity maturation), neuroscience (integrate-and-fire), pharmacology (PK/PD, hepatic clearance), population dynamics (Leslie matrix, SIR/SEIR), synthetic biology (toggle switch, repressilator, FBA), virology (quasispecies, error catastrophe), and 28 more submodules.
→ Module spec · Rust API
Physical, analytical, inorganic, and computational chemistry (26 submodules). Covers acid–base equilibria (Henderson–Hasselbalch, polyprotic titrations), kinetics (Arrhenius, Eyring, Lindemann), electrochemistry (Nernst, Butler–Volmer, Tafel), thermochemistry (Hess's law, Kirchhoff), gas laws (van der Waals, virial, compressibility), quantum chemistry (Hartree–Fock, DFT concepts, Slater determinants), crystallography (Bragg's law, Miller indices, 14 Bravais lattices), molecular modeling (Lennard-Jones, Morse potential, VSEPR), colloids (DLVO theory, Stokes–Einstein), green chemistry (atom economy, E-factor), and environmental chemistry (Henry's law, BOD/COD).
→ Module spec · Rust API
Curated registry of physical constants, astronomical data, atomic properties, and unit conversions (5 submodules). Includes 16 CODATA fundamental constants ($c$, $G$, $h$, $\hbar$, $k_B$, $N_A$, $e$, $\varepsilon_0$, $\mu_0$, $\sigma_{SB}$, $\alpha$, Planck units), 10 astronomical constants (AU, parsec, solar/Earth parameters, Hubble constant), 13 atomic constants (particle masses, Bohr radius, Rydberg energy, magnetons), the full periodic table (118 elements loaded from YAML with OnceLock), and 12 unit conversion factors (eV↔J, cal↔J, atm↔Pa, deg↔rad, barn, ångström, fermi).
→ Module spec · Rust API
Earth sciences and geophysics (4 submodules). Covers radiometric dating (decay law $N(t) = N_0 e^{-\lambda t}$, half-life conversion, isochron method, $^{14}$C calibration), petrology (CIPW norm, magma viscosity, Stokes settling, crystallization sequences), seismology (P/S/surface wave propagation, Gutenberg–Richter, Omori aftershock law, magnitude scales $M_L$/$M_W$/$m_b$, focal mechanisms), and tectonics (plate velocity on a sphere, Euler poles, Byerlee's friction law, thermal subsidence).
→ Module spec · Rust API
Central orchestration layer (5 areas: API, Domain, Engine, Tools, Prelude — 35 source files). Provides a zero-dependency HTTP server (TcpListener-based), structured DTOs (ComputeRequest/ComputeResponse with 8 result types), domain dispatchers for all 7 scientific modules, direct astronomy-cosmology routing (E(z), H(z), and distance functions) through the Hub, an Experiment builder with 15 ParameterValue variants (Scalar through Tensor), a DynamicalSystem trait for ODE simulations (with built-in HarmonicOscillator/LotkaVolterra), priority-based task scheduling with dependency-aware topological sort, campaign batch execution, and tooling (Config, Logger, Metrics).
→ Module spec · Rust API
Numerical methods and pure mathematics (17 submodules). Covers complex arithmetic, linear algebra (Gauss elimination, LU/Cholesky decomposition, eigenvalues), calculus (symbolic differentiation, Simpson/Gauss quadrature, automatic differentiation), ODE solvers (Euler, RK4, adaptive RK45), Fourier and Laplace transforms, statistics (descriptive, distributions, hypothesis testing), probability, number theory (primes, GCD, modular arithmetic), combinatorics, set theory, graph theory (BFS, DFS, Dijkstra, Kruskal), geometry (2D/3D transforms, convex hull), trigonometry, polynomial operations, vector calculus (gradient, divergence, curl, Stokes' theorem), and special functions (Gamma, Beta, Bessel, error function).
→ Module spec · Rust API
Atmospheric science and weather physics (4 submodules). Covers atmosphere (barometric formula, ISA standard layers, pressure altitude, scale height, lapse rates), dynamics (geostrophic/gradient wind, Rossby number, vorticity, thermal wind, Ekman spiral, CAPE/CIN, Richardson number), precipitation (Clausius–Clapeyron, Köhler theory, Marshall–Palmer DSD, $Z$–$R$ relations, terminal velocity, Bergeron process), and radiation (Planck blackbody, Wien's law, Stefan–Boltzmann, solar zenith angle, Beer–Lambert atmospheric extinction, albedo, greenhouse radiative forcing $\Delta F = 5.35 \ln(C/C_0)$).
→ Module spec · Rust API
Multi-format data parsing library with zero dependencies (5 formats, 26 source files). Covers CSV (RFC 4180, CsvValue enum with Table/Record/Field, quoted field handling, writer), JSON (RFC 8259, JsonValue with 6 variants, number/string submodules), YAML (YamlValue with indent-based LineCursor, scalar type auto-detection for booleans/numbers/null — used by the Constants module for periodic table data), HTML (HtmlValue with Document/Element/Text/Comment, named entity decoding — used by Benchmark export), and Markdown (MdValue with 9 block-level variants, inline emphasis/links/code processing). All formats share a layered Cursor<'a> architecture with zero-copy &'a str borrowing and const fn constructors.
→ Module spec · Rust API
Classical and modern physics (11 submodules). Covers acoustics (wave equation, Doppler, decibel scale, resonance), electrodynamics (Maxwell's equations, Lorentz force, electromagnetic waves, Poynting vector), electronics (Ohm's law, RC/RL/RLC circuits, transistor models, op-amp configurations), fluid mechanics (Navier–Stokes, Bernoulli, Reynolds number, drag), materials science (stress–strain, Young's modulus, Hooke's law, creep), nucleosynthesis (binding energy, decay chains, cross-sections, pp-chain, CNO cycle), optics (Snell's law, thin lens, diffraction, interference, polarization), quantum mechanics (Schrödinger equation, particle-in-a-box, harmonic oscillator, hydrogen atom, tunneling), relativity (Lorentz transforms, $E = mc^2$, time dilation, gravitational redshift, Schwarzschild metric), solid mechanics (beam bending, torsion, Mohr's circle, buckling), and thermodynamics (laws of thermodynamics, Carnot cycle, entropy, heat transfer, blackbody radiation).
→ Module spec · Rust API
docs/
├── Summary.md # This file
├── modules/ # Scientific domain documentation (concepts & formulas)
│ ├── Astronomy.md
│ ├── Benchmark.md
│ ├── Biology.md
│ ├── Chemistry.md
│ ├── Constants.md
│ ├── Geology.md
│ ├── Hub.md
│ ├── Mathematics.md
│ ├── Meteorology.md
│ ├── Parser.md
│ └── Physics.md
└── code/ # Rust implementation documentation (API reference)
├── Astronomy.md
├── Benchmark.md
├── Biology.md
├── Chemistry.md
├── Constants.md
├── Geology.md
├── Hub.md
├── Mathematics.md
├── Meteorology.md
├── Parser.md
└── Physics.md
The Astronomy module covers 4 submodules providing computational tools for astrophysics, from the mechanics of planetary orbits to the large-scale structure and evolution of the universe. Every function works in SI units unless stated otherwise, and all constants (G, c, σ) are embedded as compile-time literals.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Orbital mechanics — the mathematical description of how bodies move under gravity — is the backbone of mission planning, satellite operations, and planetary science.
Kepler's Laws — The orbital period of a body on an elliptical path is $T = 2\pi\sqrt{a^3/\mu}$, where $a$ is the semi-major axis and $\mu = GM$ is the gravitational parameter. The vis-viva equation $v^2 = \mu(2/r - 1/a)$ gives the instantaneous speed at any orbital radius, unifying circular ($a = r$), elliptical, parabolic ($a \to \infty$), and hyperbolic cases. The module computes circular velocity $v_c = \sqrt{\mu/r}$, escape velocity $v_e = \sqrt{2\mu/r}$, specific orbital energy $\varepsilon = -\mu/2a$, and specific angular momentum $h = \sqrt{\mu a(1-e^2)}$.
Orbit Geometry — Periapsis $r_p = a(1-e)$ and apoapsis $r_a = a(1+e)$ define the extremes. The conic section equation $r(\theta) = a(1-e^2)/(1+e\cos\theta)$ maps true anomaly to radius. These are the building blocks for trajectory design.
Transfer Orbits — The Hohmann transfer between two circular orbits requires two impulsive burns: $\Delta v = |v_{t1} - v_1| + |v_2 - v_{t2}|$, where $v_{t}$ comes from vis-viva evaluated on the transfer ellipse with $a_t = (r_1+r_2)/2$. This is the most fuel-efficient two-impulse transfer in a central field.
Gravitational Domains — The sphere of influence $r_{SOI} = a(m/M)^{2/5}$ defines the region where a planet's gravity dominates over the star's. The Hill sphere $r_H = a(1-e)(m/3M)^{1/3}$ bounds the region where stable satellite orbits can exist. The Roche limit $d = 2.456\,R_p(\rho_p/\rho_s)^{1/3}$ is the minimum orbital distance before tidal forces tear a fluid satellite apart.
Stellar astrophysics characterizes stars by their observable and intrinsic properties, connecting luminosity, temperature, mass, and evolutionary state.
Luminosity and Temperature — A star radiates as an approximate blackbody: $L = 4\pi R^2 \sigma T_{\text{eff}}^4$ (Stefan-Boltzmann law). Wien's displacement law $\lambda_{\max} = 2.898 \times 10^{-3}/T$ gives the peak emission wavelength. The module computes luminosity from radius and temperature, and the inverse.
Magnitude System — Absolute magnitude $M = m - 5\log_{10}(d/10)$ standardizes brightness at 10 pc. The distance modulus inverts this to give distance from apparent and absolute magnitudes. Stellar flux follows the inverse-square law $F = L/(4\pi d^2)$. Bolometric corrections convert visual magnitudes to total luminosity.
Mass-Luminosity Relation — On the main sequence, luminosity scales steeply with mass: $L \propto M^{2.3}$ for $M < 0.43\,M_\odot$, $L \propto M^4$ for solar-type stars, $L \propto M^{3.5}$ for intermediate masses, and $L \propto M$ for the most massive stars. Main-sequence lifetime follows as $\tau \approx 10^{10}\,M/L$ years — massive stars burn out in millions of years, while red dwarfs last trillions.
Spectral Classification — An empirical relation maps spectral index to effective temperature: $T_{\text{eff}} \approx 42000/(n+0.92)$, bridging the O-B-A-F-G-K-M sequence to physical temperature.
Compact Objects — The Schwarzschild radius $r_s = 2GM/c^2$ defines the event horizon of a non-rotating black hole. The Chandrasekhar limit ($1.4\,M_\odot$) is the maximum mass for a white dwarf supported by electron degeneracy pressure. The Eddington luminosity $L_E = 4\pi GMc/\kappa$ is the maximum luminosity before radiation pressure overcomes gravity, limiting accretion rates.
Cosmology studies the origin, structure, and evolution of the universe on the largest scales, grounded in general relativity and the Friedmann-Lemaître-Robertson-Walker metric.
Hubble's Law and H(z) — The expansion of the universe produces a recession velocity proportional to distance: $v = H_0 d$. Beyond local linear expansion, the module exposes redshift-dependent Hubble rates via $H(z) = H_0 E(z)$, including general and flat-LCDM helpers.
Redshift — Cosmological redshift $z = a_{\text{obs}}/a_{\text{emit}} - 1$ relates the scale factor at emission to the observed wavelength stretching. The scale factor is $a = 1/(1+z)$. For low redshift, $z \approx v/c$ (non-relativistic approximation).
**Friedmann and E(z) parameterizations** — The expansion rate $H(a) = H_0\sqrt{\Omega_r/a^4 + \Omega_m/a^3 + \Omega_\Lambda}$ governs cosmic dynamics. The module provides direct E(z) implementations for general models and common parameterizations: flat LCDM, LCDM with radiation, constant-$w$ dark energy (wCDM), and CPL ($w_0$-$w_a$).
Distances — Cosmological distances are not unique. The module computes line-of-sight and transverse comoving distance, luminosity distance $d_L = d_C(1+z)$, and angular diameter distance $d_A = d_C/(1+z)$ from redshift using numerical integration. Implementations are available for flat LCDM, general curved models, and flat wCDM/CPL variants.
Time and LCDM shortcuts — The module keeps approximate legacy formulas, but also includes LCDM-focused utilities such as analytical flat-LCDM age where applicable, plus numerical lookback/age functions for more general models.
CMB Temperature — The cosmic microwave background temperature scales with redshift: $T(z) = T_0(1+z)$, where $T_0 \approx 2.725$ K today.
**Hub wiring** — Cosmology APIs are directly exposed through the Hub astronomy dispatcher, so these calculations are available from Experiment::new(DomainType::Astronomy, ...) without bypassing the unified dispatch layer.
Celestial mechanics applies Newtonian gravity to multi-body systems, covering forces, tidal interactions, and observable geometry.
Gravitational Force — Newton's law $F = Gm_1m_2/r^2$ and the tidal force $F_t = 2Gm\,\Delta r/r^3$ (differential gravity across an extended body). Tidal forces explain ocean tides, tidal locking, and the Roche limit.
Two-Body Geometry — The barycenter of two masses lies at $d \cdot m_2/(m_1+m_2)$ from $m_1$. The synodic period $P_{\text{syn}} = 1/|1/P_1 - 1/P_2|$ gives the recurrence time of alignments (e.g., planetary conjunctions). Sidereal-to-solar day conversion accounts for orbital motion.
Lagrange Points and Hill Sphere — The L1 point $r_{L1} \approx d(m_2/3m_1)^{1/3}$ is the equilibrium between gravitational pulls, used for solar observatories (e.g., SOHO). The Hill sphere bounds stable satellite orbits.
Surface Properties — Surface gravity $g = GM/R^2$ determines atmospheric retention and landing dynamics. The apparent angular size $\theta = 2\arctan(d_{\text{phys}}/2D)$ gives how large an object appears in the sky. Parallax distance $d = 1/p''$ (in parsecs) is the fundamental distance ladder rung.
Habitable Zone — The circumstellar habitable zone bounds are estimated from stellar luminosity: inner edge $r_{\text{in}} = \sqrt{L/1.1}$ AU and outer edge $r_{\text{out}} = \sqrt{L/0.53}$ AU, where $L$ is in solar luminosities. These correspond to the range where liquid water can exist on a rocky surface.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The benchmark module provides 6 submodules for performance measurement, binary encoding, simulation profiling, and multi-format report generation. It serves as SciForge's internal benchmarking infrastructure.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Core benchmark execution framework.
The engine defines the BenchmarkMetrics struct that captures all measurable dimensions of an experiment:
| Field | Type | Description |
|---|---|---|
experiment_name | &str | Identifier for the benchmark |
precision | &str | Numeric precision label (e.g. "f64", "f32") |
elapsed_ms | u64 | Total wall-clock time in milliseconds |
iterations | u64 | Number of measured iterations |
avg_time_ns | f32 | Mean time per iteration (ns) |
min_time_ns / max_time_ns | f32 | Min/max iteration time |
time_stddev | f32 | Standard deviation of iteration times |
iterations_per_sec | f32 | Throughput: $1 / \bar{t}$ |
samples_per_sec | f32 | Data throughput |
total_flops | u64 | Floating-point operations counted |
eval_error | f32 | Numerical error metric |
eval_accuracy | f32 | Accuracy score |
eval_r_squared | f32 | Coefficient of determination $R^2$ |
eval_mae | f32 | Mean absolute error |
logical_cores | u32 | System CPU core count |
The runner uses std::hint::black_box to prevent compiler dead-code elimination, and std::time::Instant for nanosecond-precision timing. A CSV header is provided for direct row export:
experiment_name,precision,elapsed_ms,iterations,avg_time_ns,min_time_ns,max_time_ns,time_stddev,iterations_per_sec,result
Statistical aggregation. The standard deviation of timing samples quantifies measurement noise:
$$\sigma_t = \sqrt{\frac{1}{N-1} \sum_{i=1}^{N} (t_i - \bar{t})^2}$$
Coefficient of variation $\text{CV} = \sigma_t / \bar{t}$ indicates benchmark stability — values below 5% suggest reliable measurements.
Binary serialization of benchmark metrics into a compact binary format.
The encoding uses a **fixed-size header** (BENCHMARK_HEADER_SIZE) followed by variable-length experiment name and precision strings. The binary layout:
| Offset | Size | Field |
|---|---|---|
| 0–3 | 4 bytes | Magic number (BENCHMARK_MAGIC) |
| 4–5 | 2 bytes | Format version (little-endian u16) |
| 8–15 | 8 bytes | elapsed_ms (LE u64) |
| 16–23 | 8 bytes | iterations (LE u64) |
| 24–31 | 8 bytes | input_samples (LE u64) |
| 32–35 | 4 bytes | avg_time_ns (LE f32) |
| ... | ... | (all metrics fields in sequence) |
| 164–165 | 2 bytes | experiment name length |
| 166–167 | 2 bytes | precision string length |
| header+ | variable | experiment name + precision bytes |
All multi-byte fields are **little-endian**. The encoded_size() function computes the exact buffer requirement via checked arithmetic to prevent overflow. Encode returns the number of bytes written.
Deserialization of binary benchmark data back into BenchmarkMetricsView.
Decoding attempts two strategies: full format (with magic+version header validation) and compact format (fallback). The decoder validates:
BENCHMARK_HEADER_SIZEBENCHMARK_MAGICBENCHMARK_VERSIONBenchmarkMetricsView borrows string slices directly from the input buffer (zero-copy), returning &'a str references with lifetime tied to the source bytes.
Physics simulation benchmarking with configurable N-body state.
The simulation framework provides:
SimConfig** — Timestep $\Delta t$, maximum steps, body count.StepFn trait** — Integration interface: fn integrate(&self, state: &mut SimState, dt: f64). Any ODE integrator (Euler, RK4, Verlet) can be plugged in.RenderSink trait** — Frame callback for visualization or data collection during simulation.The benchmark runner measures:
Multi-format benchmark report generation.
From a BenchmarkMetrics instance, the report module generates three synchronized outputs:
CSV. Single-row data suitable for spreadsheet import or time-series tracking:
header_row
metrics_row,result
Markdown. Structured report with:
HTML. Self-contained single-file report embedding the Markdown content, with inline CSS for readability.
Structured data. Additional generators produce:
generate_json_tagged): tagged key-value output with custom metadatagenerate_yaml_tagged): human-readable structured outputgenerate_toml_tagged): configuration-style outputAll string output uses safe escaping (push_escaped) to prevent injection in generated reports.
File-based export orchestrator for benchmark suites.
The export() function takes a title, a slice of Entry records (each wrapping a BenchmarkMetrics with optional tags, labels, and grid coordinates), and an output directory. It produces:
.md reportsgrid_row/grid_col placement).bench files** with encoded metrics for machine consumptionThe ExportSummary struct reports: files written, HTML size (bytes), Markdown size (bytes).
Element category CSS mapping supports periodic table visualization in exported HTML dashboards, with classes for each IUPAC element category (nonmetal, noble-gas, alkali, transition, lanthanide, actinide, etc.).
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The biology module is the largest in SciForge, spanning 44 submodules across 176 source files. It provides computational models for molecular biology, cellular processes, organismal physiology, population dynamics, and ecological systems — from the scale of individual molecules to entire ecosystems.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Models of biological aging, senescence, and mortality across the lifespan.
Telomere dynamics. Telomeres shorten with each cell division. SciForge models linear attrition:
$$L(n) = L_0 - \delta \cdot n$$
where $L_0$ is the initial telomere length, $\delta$ the loss per division, and $n$ the number of divisions. The Hayflick limit (maximum replicative capacity) is:
$$n_{\max} = \frac{L_0 - L_{\text{crit}}}{\delta}$$
When telomerase is active, an equilibrium length emerges from the balance of shortening rate $k_s$ and elongation rate $k_e$:
$$L_{\text{eq}} = \frac{k_e}{k_s}, \qquad L(t) = L_{\text{eq}} + (L_0 - L_{\text{eq}}) e^{-k_s t}$$
Mortality models. The Gompertz law describes the exponential increase of mortality with age:
$$\mu(x) = a \, e^{bx}$$
where $a$ is the baseline mortality and $b$ the rate of aging. The Gompertz–Makeham extension adds an age-independent term $c$:
$$\mu(x) = c + a \, e^{bx}$$
The mortality rate doubling time (MRDT) is $\ln 2 / b$. Survival probability follows:
$$S(x) = \exp\!\Bigl(-\frac{a}{b}(e^{bx} - 1)\Bigr)$$
The Weibull alternative gives $h(x) = \lambda k (\lambda x)^{k-1}$ with survival $S(x) = e^{-(\lambda x)^k}$.
Oxidative stress. ROS production depends on metabolic rate and mitochondrial coupling efficiency:
$$\dot{R} = M \cdot (1 - \eta)$$
Antioxidant capacity integrates SOD, catalase, and glutathione: $A = [\text{SOD}] k_1 + [\text{Cat}] k_2 + [\text{GSH}] k_3$. Net oxidative damage rate is $(\dot{R} - A)^+$. Lipid peroxidation follows a two-step initiation-propagation model, and protein carbonylation is modeled as second-order kinetics.
Electrical phenomena in biological membranes and tissues.
Nernst equation. The equilibrium potential for a single ion species:
$$E_{\text{ion}} = \frac{RT}{zF} \ln \frac{[\text{ion}]_{\text{out}}}{[\text{ion}]_{\text{in}}}$$
Goldman–Hodgkin–Katz equation. The resting membrane potential considering multiple permeant ions (Na⁺, K⁺, Cl⁻):
$$V_m = \frac{RT}{F} \ln \frac{P_{\text{K}}[\text{K}^+]_o + P_{\text{Na}}[\text{Na}^+]_o + P_{\text{Cl}}[\text{Cl}^-]_i}{P_{\text{K}}[\text{K}^+]_i + P_{\text{Na}}[\text{Na}^+]_i + P_{\text{Cl}}[\text{Cl}^-]_o}$$
Action potential. SciForge implements the Hodgkin–Huxley model with gating variables $m$, $h$, $n$:
$$C_m \frac{dV}{dt} = -g_{\text{Na}} m^3 h (V - E_{\text{Na}}) - g_{\text{K}} n^4 (V - E_{\text{K}}) - g_L (V - E_L) + I_{\text{ext}}$$
Propagation velocity depends on fiber diameter $d$ and membrane properties. Cable equation analysis gives the length constant $\lambda = \sqrt{r_m / r_i}$.
Bioimpedance. Tissue impedance is modeled with the Cole equation: $Z(\omega) = R_\infty + \frac{R_0 - R_\infty}{1 + (j\omega\tau)^\alpha}$, used in body composition analysis and tissue characterization.
Energy transformation in living systems.
ATP synthesis. The rate of mitochondrial ATP production depends on proton motive force and the P/O ratio. Energy charge quantifies the adenylate pool status:
$$\text{EC} = \frac{[\text{ATP}] + \frac{1}{2}[\text{ADP}]}{[\text{ATP}] + [\text{ADP}] + [\text{AMP}]}$$
Cells maintain EC near 0.85–0.90 for normal function.
Metabolic scaling. Basal metabolic rate scales allometrically with body mass:
$$B = B_0 M^{3/4}$$
(Kleiber's law). The metabolic theory of ecology extends this to temperature with an Arrhenius-type activation:
$$B = B_0 M^{3/4} e^{-E_a / kT}$$
Photosynthesis. Light reactions are modeled with quantum yield $\Phi$: the ratio of CO₂ fixed to photons absorbed. The light response curve follows a rectangular hyperbola:
$$A = \frac{A_{\max} \cdot I}{K_I + I} - R_d$$
where $A_{\max}$ is maximum assimilation rate, $K_I$ the half-saturation light intensity, and $R_d$ the dark respiration. Calvin cycle efficiency depends on RuBisCO kinetics (Michaelis–Menten with CO₂/O₂ competition).
Respiration. Aerobic yield: ~30–32 ATP per glucose. ATP yield from substrate-level and oxidative phosphorylation is computed stoichiometrically. Anaerobic glycolysis yields 2 ATP per glucose with lactate as end product.
Geographic distribution of species.
Island biogeography. MacArthur and Wilson's equilibrium theory models species richness as the balance of immigration rate $I$ and extinction rate $E$:
$$\frac{dS}{dt} = I_0 \left(1 - \frac{S}{P}\right) - E_0 \frac{S}{P}$$
where $P$ is the mainland species pool and $S$ the island species count. Equilibrium: $\hat{S} = P \cdot I_0 / (I_0 + E_0)$.
Species–area relationship: $S = c A^z$, where $z \approx 0.25$ for islands and $z \approx 0.15$ for continental samples.
Climate envelope models. Species occurrence probability is computed from temperature, precipitation, and altitude using Gaussian suitability functions, enabling range shift predictions under climate scenarios.
Computational analysis of biological sequences.
Sequence alignment. The Needleman–Wunsch algorithm (global alignment) fills a dynamic programming matrix $F$ with:
$$F_{i,j} = \max \begin{cases} F_{i-1,j-1} + s(a_i, b_j) \\ F_{i-1,j} + d \\ F_{i,j-1} + d \end{cases}$$
where $s(a_i, b_j)$ is the substitution score (from BLOSUM/PAM matrices) and $d$ the gap penalty. Smith–Waterman provides local alignment with a zero floor.
Assembly metrics. Genome assembly quality is assessed via N50 (the contig length at which 50% of the total assembly is contained in contigs of that length or longer) and coverage depth:
$$\text{Coverage} = \frac{N \cdot L}{G}$$
where $N$ is the number of reads, $L$ the read length, and $G$ the genome size.
Phred quality scores. Base-calling confidence: $Q = -10 \log_{10} P_e$. A Phred score of 30 means $P_e = 0.001$ (99.9% accuracy). SciForge converts between Phred scores and error probabilities for read filtering pipelines.
Gene expression. Fold change is $\text{FC} = \bar{X}_{\text{treated}} / \bar{X}_{\text{control}}$, typically reported as $\log_2 \text{FC}$. FPKM/TPM normalization accounts for gene length and sequencing depth.
Mechanics of biological structures and movement.
Blood flow. The Hagen–Poiseuille law governs laminar flow in vessels:
$$Q = \frac{\pi r^4 \Delta P}{8 \mu L}$$
Wall shear stress: $\tau_w = \frac{4 \mu Q}{\pi r^3}$. Non-Newtonian effects (shear-thinning of blood) are captured via power-law or Carreau models.
Muscle mechanics. The Hill muscle model relates force and velocity:
$$(F + a)(v + b) = (F_0 + a) b$$
where $F_0$ is the isometric force, $a$ and $b$ are Hill constants. The force-length relationship follows a Gaussian around optimal sarcomere length.
Viscoelasticity. Biological tissues are modeled as:
Locomotion. Metabolic cost of transport (COT) is energy per unit distance per unit mass. Stride frequency scales with limb length $l$: $f \propto \sqrt{g/l}$ (pendulum model). Froude number $\text{Fr} = v^2/(g l)$ determines gait transitions.
Physical principles applied to biological systems.
Membrane mechanics. The Helfrich bending energy of a lipid bilayer:
$$E = \frac{\kappa}{2} \oint (2H - C_0)^2 \, dA + \kappa_G \oint K \, dA$$
where $\kappa$ is the bending modulus, $H$ the mean curvature, $C_0$ the spontaneous curvature, $K$ the Gaussian curvature, and $\kappa_G$ the Gaussian modulus. This governs vesicle shapes, budding, and membrane fusion.
Molecular forces. The Lennard-Jones potential for van der Waals interactions:
$$V(r) = 4\varepsilon \left[\left(\frac{\sigma}{r}\right)^{12} - \left(\frac{\sigma}{r}\right)^6\right]$$
with well depth $\varepsilon$ and size parameter $\sigma$.
Polymer models. The worm-like chain (WLC) force-extension relation (Marko–Siggia interpolation):
$$F = \frac{k_B T}{L_p} \left[\frac{1}{4(1 - x/L_c)^2} - \frac{1}{4} + \frac{x}{L_c}\right]$$
where $L_p$ is persistence length, $L_c$ contour length. The freely jointed chain (FJC) uses the Langevin function: $\langle x \rangle / L_c = \coth(Fb/k_BT) - k_BT/(Fb)$.
FRET. Förster resonance energy transfer efficiency:
$$E = \frac{1}{1 + (r/R_0)^6}$$
where $R_0$ is the Förster radius (typically 2–7 nm). Used to measure intramolecular distances in proteins.
Protein folding. Two-state folding free energy: $\Delta G = -RT \ln K_{\text{eq}}$, with Ramachandran-based steric energies for backbone conformations.
Statistical methods for biological and clinical data.
Survival analysis. The Kaplan–Meier estimator of the survival function:
$$\hat{S}(t) = \prod_{t_i \le t} \left(1 - \frac{d_i}{n_i}\right)$$
where $d_i$ is the number of events at time $t_i$ and $n_i$ the number at risk. Median survival is $t$ at $\hat{S}(t) = 0.5$.
**Clinical statistics.** Odds ratio: $\text{OR} = (a \cdot d) / (b \cdot c)$ from a 2×2 contingency table. Relative risk: $\text{RR} = [a/(a+b)] / [c/(c+d)]$. Number needed to treat: $\text{NNT} = 1/\text{ARR}$.
Meta-analysis. Combined effect size via inverse-variance weighting: $\hat{\theta} = \sum w_i \theta_i / \sum w_i$ with $w_i = 1/\sigma_i^2$. Heterogeneity is assessed with $I^2 = \max(0, (Q - \text{df})/Q \times 100\%)$, where $Q$ is Cochran's Q statistic.
Logistic regression. Probability of event: $P = 1 / (1 + e^{-(\beta_0 + \beta_1 x)})$. Log-odds: $\ln(P/(1-P)) = \beta_0 + \beta_1 x$.
Tumor growth, immune surveillance, and therapy modeling.
Tumor–immune dynamics. SciForge models the interaction between tumor cells $T$ and immune cells $I$:
$$\frac{dT}{dt} = r T \left(1 - \frac{T}{K}\right) - \alpha T I, \qquad \frac{dI}{dt} = s + \frac{\rho T I}{\eta + T} - \delta I$$
where $r$ is the tumor growth rate, $K$ carrying capacity, $\alpha$ the kill rate, $s$ the basal immune influx, $\rho$ the immune stimulation, $\eta$ the half-saturation constant, and $\delta$ immune cell death.
Immunoediting. The three phases (elimination, equilibrium, escape) are captured through varying $\alpha$ and $\rho$ parameters. Immunotherapy is modeled by boosting $s$ or $\alpha$.
**Gompertzian tumor growth.** $V(t) = V_0 \exp\!\left[\frac{a}{b}(1 - e^{-bt})\right]$, where growth decelerates as the tumor approaches its limiting size $V_\infty = V_0 e^{a/b}$.
Cellular structure, division, signaling, and transport.
Cell cycle. Doubling time: $t_d = \ln 2 / \mu$, where $\mu$ is the specific growth rate. Checkpoint models use threshold concentrations of cyclins and CDKs.
**Receptor–ligand binding.** At equilibrium: $[RL] = \frac{[R]_T [L]}{K_d + [L]}$, following Michaelis–Menten-type saturation. Hill cooperativity extends this for multivalent receptors.
Fick's diffusion. Molecular transport across membranes: $J = -D \frac{dC}{dx}$. For facilitated diffusion through channels, the Goldman constant field assumption applies.
Cell adhesion. Adhesion energy is computed from contact area and surface energy density. Focal adhesion density depends on substrate stiffness (mechanotransduction).
Biological rhythms and timing systems.
Circadian oscillators. The Goodwin oscillator models mRNA ($m$), protein ($p$), and repressor ($r$):
$$\frac{dm}{dt} = \frac{k_1}{1 + (r/K_i)^n} - d_1 m, \quad \frac{dp}{dt} = k_2 m - d_2 p, \quad \frac{dr}{dt} = k_3 p - d_3 r$$
Sustained oscillations require $n \ge 8$ for the Goodwin model. Coupled oscillators synchronize via diffusive coupling with phase-dependent coupling strengths.
Entrainment. Light pulses shift the oscillator phase according to a phase response curve (PRC). Entrainment range depends on the zeitgeber strength and the oscillator's natural period.
Low-temperature biology and preservation.
Freezing point depression. For an ideal dilute solution: $\Delta T_f = K_f \cdot m$, where $K_f$ is the cryoscopic constant and $m$ the molality. Cryoprotectant (DMSO, glycerol) concentration modulates both osmotic stress and ice nucleation.
Ice formation. Intracellular ice formation probability follows an Arrhenius-type nucleation rate: $J = J_0 \exp(-\Delta G^* / k_B T)$. Rapid cooling increases intracellular ice risk; slow cooling causes osmotic dehydration.
Viability. Cell survival after cryopreservation follows: $V = V_0 \exp(-k \cdot t_{\text{exposure}})$, with optimal cooling rates balancing ice damage and solution effects.
Embryonic development and pattern formation.
Waddington landscape. Cell fate is modeled as a ball rolling on an epigenetic potential surface $U(x)$. Commitment is: $\text{CI} = 1 - \exp(-|U(x) - U(x_{\text{uncommitted}})|)$, increasing as cells descend into deep valleys.
Morphogen gradients. Exponential gradient from a localized source with diffusion $D$ and degradation $\mu$:
$$C(x) = C_0 \, e^{-x/\lambda}, \qquad \lambda = \sqrt{D/\mu}$$
The French flag model interprets positional information via threshold concentrations defining distinct cell fates.
Turing patterns. Two-component reaction–diffusion generating spatial patterns:
$$\frac{\partial u}{\partial t} = D_u \nabla^2 u + f(u,v), \qquad \frac{\partial v}{\partial t} = D_v \nabla^2 v + g(u,v)$$
Instability requires $D_v \gg D_u$ (long-range inhibition, short-range activation).
Somitogenesis clock. Periodic segmentation with period $T_{\text{clock}}$ and wavefront velocity $v_{\text{front}}$ gives somite length $L = v_{\text{front}} \times T_{\text{clock}}$.
Community and ecosystem dynamics.
Lotka–Volterra competition. Two-species competitive dynamics:
$$\frac{dN_1}{dt} = r_1 N_1 \left(\frac{K_1 - N_1 - \alpha_{12} N_2}{K_1}\right), \qquad \frac{dN_2}{dt} = r_2 N_2 \left(\frac{K_2 - N_2 - \alpha_{21} N_1}{K_2}\right)$$
Coexistence requires $\alpha_{12} < K_1/K_2$ and $\alpha_{21} < K_2/K_1$ (each species more limited by intraspecific competition).
Predator–prey. The Rosenzweig–MacArthur model with saturating functional response:
$$\frac{dN}{dt} = rN\left(1 - \frac{N}{K}\right) - \frac{aNP}{1 + ahN}, \qquad \frac{dP}{dt} = e \frac{aNP}{1 + ahN} - mP$$
Functional responses. Type I: $f = aN$; Type II: $f = aN/(1+ahN)$; Type III: $f = aN^2/(1+ahN^2)$.
Diversity indices. Shannon entropy: $H' = -\sum p_i \ln p_i$. Simpson: $D = \sum p_i^2$. Evenness: $J = H'/\ln S$.
Hormonal regulation and signaling.
Hormone clearance. First-order elimination: $C(t) = C_0 e^{-k_e t}$, with half-life $t_{1/2} = \ln 2 / k_e$. Metabolic clearance rate: $\text{MCR} = k_e \cdot V_d$.
Pulsatile secretion. Hormones like GnRH are released in pulses. Each pulse is modeled as a bolus: $C(t) = \frac{D}{V_d} e^{-k_e t}$, with interpulse interval $T_p$. The cumulative concentration from multiple pulses is the sum of decaying exponentials.
**Negative feedback.** HPA axis: cortisol suppresses ACTH release. Modeled as: $\frac{d[\text{ACTH}]}{dt} = S_0 / (1 + [\text{Cortisol}]/K_i) - k_d [\text{ACTH}]$.
Catalytic mechanisms and regulation.
Michaelis–Menten kinetics. The fundamental equation of enzyme kinetics:
$$v = \frac{V_{\max} [S]}{K_m + [S]}$$
where $V_{\max} = k_{\text{cat}} [E]_T$ and $K_m = (k_{-1} + k_{\text{cat}})/k_1$. Catalytic efficiency: $k_{\text{cat}}/K_m$.
Inhibition modes. All four modes are implemented:
**Lineweaver–Burk linearization.** $\frac{1}{v} = \frac{K_m}{V_{\max}} \cdot \frac{1}{[S]} + \frac{1}{V_{\max}}$.
**Hill equation.** For cooperative enzymes: $v = V_{\max} [S]^n / (K_{0.5}^n + [S]^n)$. Hill coefficient $n > 1$ indicates positive cooperativity.
Heritable modifications beyond DNA sequence.
Histone modification kinetics. Dynamic balance of writers and erasers:
$$\frac{d[\text{mark}]}{dt} = k_{\text{write}} (1 - [\text{mark}]) - k_{\text{erase}} [\text{mark}]$$
Steady-state mark level: $[\text{mark}]_{\text{eq}} = k_{\text{write}} / (k_{\text{write}} + k_{\text{erase}})$.
DNA methylation. CpG methylation dynamics involve maintenance methyltransferase (DNMT1) fidelity and de novo methylation rates. Methylation clocks correlate cumulative CpG changes with biological age.
Animal behavior and decision-making.
Optimal foraging theory. The marginal value theorem determines optimal patch residence time: leave when the marginal intake rate in the current patch drops to the average rate for the habitat:
$$\frac{\partial g(t)}{\partial t} = \frac{g^*}{t^* + \bar{T}}$$
where $g(t)$ is cumulative gain in the patch and $\bar{T}$ is average travel time between patches.
Optimal diet model. Prey type $i$ should be included if its profitability $e_i / h_i$ exceeds the average return from higher-ranked items. Energy per item: $e_i$; handling time: $h_i$.
Ideal free distribution. Animals distribute across habitats proportionally to resource availability: $n_i / N = r_i / R$, equalizing per-capita intake.
Evolutionary processes at the molecular and population level.
Molecular clock. Substitution rate: $r = k / (2t)$, where $k$ is the observed substitutions and $t$ the divergence time. For protein-coding genes, the dN/dS ratio ($\omega$) distinguishes selection regimes:
**Coalescent theory.** Expected coalescence time for two lineages in a population of effective size $N_e$: $E[T_2] = 2 N_e$ generations. Neutral diversity: $\pi = 4 N_e \mu$.
Watterson's theta. Estimated from the number of segregating sites $S$:
$$\hat{\theta}_W = \frac{S}{\sum_{i=1}^{n-1} 1/i}$$
Fixation probability. For a new mutation with selection coefficient $s$ in a diploid population: $P_{\text{fix}} \approx 2s$ (Haldane's approximation for beneficial mutations).
Classical and molecular genetics.
Hardy–Weinberg equilibrium. Allele frequencies remain constant in the absence of evolutionary forces. For alleles $p$ and $q = 1-p$: genotype frequencies $p^2 : 2pq : q^2$.
F-statistics. Wright's $F_{ST}$ measures population differentiation:
$$F_{ST} = \frac{H_T - H_S}{H_T}$$
where $H_T$ is total expected heterozygosity and $H_S$ the mean within-subpopulation heterozygosity.
Nucleotide diversity. $\pi = \frac{n}{n-1} \sum_{i<j} 2 p_i p_j d_{ij}$, the average number of pairwise differences per site.
Watterson's theta from segregating sites provides an alternative estimate of $4 N_e \mu$.
Genome-scale analysis.
Gene density. Genes per megabase: $\rho = n_{\text{genes}} / (L_{\text{genome}} / 10^6)$.
CpG enrichment. Observed/expected CpG ratio:
$$\text{CpG}_{o/e} = \frac{N_{\text{CpG}} \cdot L}{N_C \cdot N_G}$$
Ratios > 0.6 indicate CpG islands (associated with promoter regions).
Codon adaptation index (CAI). Measures synonymous codon usage bias relative to a reference set of highly expressed genes:
$$\text{CAI} = \exp\!\left(\frac{1}{L} \sum_{i=1}^{L} \ln w_i\right)$$
where $w_i$ is the relative adaptiveness of the $i$-th codon. High CAI correlates with high expression.
Immune system modeling.
Somatic hypermutation and affinity maturation. B-cell receptor affinity evolves through iterative mutation and selection in germinal centers. Affinity after $n$ rounds: $A_n = A_0 (1 + \delta)^n$, where $\delta$ is the mean fractional improvement per round.
Antibody titer. Concentration doubling during acute response: $T(t) = T_0 \cdot 2^{t / t_d}$ during the expansion phase, followed by exponential decay: $T(t) = T_{\text{peak}} e^{-k t}$.
**Neutralization.** The fraction of pathogen neutralized: $f = \frac{[Ab]^n}{K_d^n + [Ab]^n}$ (Hill-type dose–response).
Isotype switching. Class-switch recombination probabilities depend on cytokine milieu signals (IL-4 → IgE, IFN-γ → IgG).
Ocean ecosystems and organisms.
Phytoplankton growth. Nutrient-limited growth with Monod kinetics:
$$\mu = \mu_{\max} \frac{N}{K_N + N}$$
with extensions for light limitation (Smith function) and temperature dependence (Eppley curve: $\mu_{\max} = 0.59 e^{0.0633 T}$).
Sverdrup critical depth. A spring bloom occurs when the mixed layer depth $Z_m$ is shallower than the critical depth $Z_{cr}$:
$$Z_{cr} = \frac{I_0 (1 - e^{-k Z_{cr}})}{k \cdot I_c}$$
where $I_c$ is the compensation irradiance and $k$ the extinction coefficient.
NPZ model. Nutrient–Phytoplankton–Zooplankton coupled ODEs:
$$\frac{dN}{dt} = -\mu P + \gamma Z + m P, \quad \frac{dP}{dt} = \mu P - g P Z - m P, \quad \frac{dZ}{dt} = g P Z - \gamma Z$$
Microbial growth and interactions.
Quorum sensing. Autoinducer (AHL) dynamics:
$$\frac{d[\text{AHL}]}{dt} = k_{\text{prod}} \cdot n_{\text{cells}} - k_{\text{deg}} [\text{AHL}]$$
When $[\text{AHL}]$ exceeds a threshold $K_T$, target gene activation is: $f = [\text{AHL}]^h / (K_T^h + [\text{AHL}]^h)$ (Hill function).
Monod growth kinetics. $\mu = \mu_{\max} S / (K_s + S)$, where $S$ is the limiting substrate and $K_s$ the half-saturation constant.
Chemostat steady state. Dilution rate $D$ sets the wash-out threshold: at steady state, $\mu = D$, giving $S^* = K_s D / (\mu_{\max} - D)$.
Fungal biology and ecology.
Saprotrophic decomposition. First-order exponential decay of substrate: $M(t) = M_0 e^{-k t}$, with carbon release rate $\dot{C} = k \cdot M(t)$. Decomposition rate constants $k$ vary with temperature (Q₁₀ models) and moisture.
Spore germination. Germination percentage as a function of time: $G(t) = G_{\max}(1 - e^{-r t})$. Optimal conditions are moisture > threshold and temperature in a species-specific range.
Hyphal growth. Colony radius expansion follows linear kinetics: $r(t) = r_0 + v t$. Branching frequency determines mycelial density.
Computational neuroscience and neural systems.
Spike analysis. Mean firing rate: $\bar{r} = n_{\text{spikes}} / T$. Interspike interval (ISI) distribution characterizes regularity. The Fano factor measures spike count variability:
$$F = \frac{\text{Var}(N)}{\langle N \rangle}$$
$F = 1$ for Poisson spiking; $F < 1$ indicates regularity; $F > 1$ clustering.
Coefficient of variation of ISI: $\text{CV} = \sigma_{\text{ISI}} / \mu_{\text{ISI}}$.
Integrate-and-fire. $\tau_m \frac{dV}{dt} = -(V - V_{\text{rest}}) + R I_{\text{ext}}$. Spike when $V = V_{\text{threshold}}$; reset to $V_{\text{reset}}$.
Nutrient metabolism and dietary analysis.
First-order absorption. Plasma concentration after oral intake:
$$C(t) = \frac{D \cdot k_a}{V_d (k_a - k_e)} (e^{-k_e t} - e^{-k_a t})$$
where $k_a$ is the absorption rate, $k_e$ elimination rate, and $D$ the dose.
Gastric emptying. Exponential emptying: $V(t) = V_0 e^{-k_g t}$ for liquids; power-exponential for solids.
Glycemic index. $\text{GI} = (\text{AUC}_{\text{food}} / \text{AUC}_{\text{reference}}) \times 100$. Glycemic load: $\text{GL} = \text{GI} \times g_{\text{carb}} / 100$.
Ancient life and deep time.
Background extinction rate. Expressed in extinctions per million species-years (E/MSY):
$$\dot{E}_{\text{bg}} = \frac{\text{extinctions}}{N \cdot \Delta t}$$
Mass extinction magnitude. Kill curve: percentage of taxa lost. $M = 1 - S_{\text{after}} / S_{\text{before}}$ where $S$ is species richness. The "Big Five" events exceeded 75% genus-level extinction.
Origination rate. $\hat{o} = \ln(N_{t+1} / N_t + E) / \Delta t$, accounting for both new appearances and losses.
Host–parasite interactions.
Anderson–May model. Macroparasite dynamics with mean burden $P$ in host population $H$:
$$\frac{dH}{dt} = (b - d) H - \alpha P, \qquad \frac{dP}{dt} = \beta H - (\mu + d + \alpha) P - \alpha \frac{k+1}{k} \frac{P^2}{H}$$
where $k$ is the negative binomial aggregation parameter (lower $k$ = more aggregated parasites).
Negative binomial distribution. Parasite burdens are overdispersed: $\text{Var} = \mu (1 + \mu/k)$. Proportion of hosts with > $n$ parasites: $P(X > n) = 1 - \text{NB}(n; k, \mu)$.
Drug action and disposition.
Oral bioavailability. $F = f_{\text{abs}} \cdot (1 - E_{\text{gut}}) \cdot (1 - E_{\text{hepatic}})$, where $E$ represents extraction ratios.
Noyes–Whitney dissolution. $\frac{dm}{dt} = D \frac{A}{h}(C_s - C_t)$, where $A$ is surface area, $h$ diffusion layer thickness, $C_s$ solubility, $C_t$ bulk concentration.
Hepatic clearance. The well-stirred model: $CL_{\text{H}} = \frac{Q_H \cdot f_u \cdot CL_{\text{int}}}{Q_H + f_u \cdot CL_{\text{int}}}$, where $Q_H$ is hepatic blood flow, $f_u$ the unbound fraction, and $CL_{\text{int}}$ the intrinsic clearance.
One-compartment PK. IV bolus: $C(t) = (D/V_d) e^{-k_e t}$. Half-life: $t_{1/2} = 0.693 / k_e$. AUC: $D / (V_d \cdot k_e)$.
Evolutionary relationships and tree construction.
Jukes–Cantor distance. Corrects for multiple substitutions at the same site:
$$d = -\frac{3}{4} \ln\!\left(1 - \frac{4p}{3}\right)$$
where $p$ is the observed fraction of differing sites.
Kimura 2-parameter. Separates transitions ($P$) and transversions ($Q$):
$$d = -\frac{1}{2} \ln(1 - 2P - Q) - \frac{1}{4} \ln(1 - 2Q)$$
Tree construction. Distance matrices feed into neighbor-joining or UPGMA algorithms. Likelihood methods evaluate tree topologies using substitution model parameters.
Organ system function modeling.
Frank–Starling mechanism. Stroke volume increases with end-diastolic volume:
$$SV = SV_{\max} \cdot (1 - e^{-k \cdot V_{\text{ED}}})$$
Cardiac output. $CO = HR \times SV$. Ejection fraction: $EF = SV / V_{\text{ED}}$.
Mean arterial pressure. $\text{MAP} = \text{DBP} + \frac{1}{3}(\text{SBP} - \text{DBP})$. Vascular resistance: $R = \text{MAP} / CO$.
Renal function. GFR estimation, tubular reabsorption rates, and clearance calculations.
Oxygen dissociation. Hill equation for hemoglobin: $Y = \frac{pO_2^n}{P_{50}^n + pO_2^n}$ with $n \approx 2.8$ and $P_{50} \approx 26.6$ mmHg.
Plant physiology and ecology.
Tilman competition. Two species competing for a single resource: the species with the lower $R^*$ (minimum resource requirement) wins: $R^* = K_s \cdot m / (\mu_{\max} - m)$.
**Allelopathy.** Chemical inhibition between plants: $G = G_0 e^{-\alpha \cdot [\text{toxin}]}$.
Canopy light extinction. Beer–Lambert law through leaf layers:
$$I(L) = I_0 \, e^{-k \cdot \text{LAI}}$$
where $\text{LAI}$ is leaf area index and $k$ the extinction coefficient (~0.5 for broadleaf).
Population dynamics and structure.
Logistic growth. Density-dependent growth:
$$\frac{dN}{dt} = rN\left(1 - \frac{N}{K}\right)$$
Solution: $N(t) = K / (1 + (K/N_0 - 1)e^{-rt})$.
SIR epidemiological model. Compartmental disease dynamics solved with RK4:
$$\frac{dS}{dt} = -\frac{\beta S I}{N}, \quad \frac{dI}{dt} = \frac{\beta S I}{N} - \gamma I, \quad \frac{dR}{dt} = \gamma I$$
Basic reproduction number: $R_0 = \beta / \gamma$. Herd immunity threshold: $1 - 1/R_0$. SciForge also implements SEIR (with exposed compartment, latency rate $\sigma$).
Leslie matrix. Age-structured population projection: $\mathbf{n}_{t+1} = \mathbf{L} \cdot \mathbf{n}_t$, where $\mathbf{L}$ contains fecundities in the first row and survival probabilities on the subdiagonal. The dominant eigenvalue $\lambda$ gives the asymptotic growth rate.
Protein-level analysis.
Peptide molecular weight. Computed from amino acid residue masses:
$$M_{\text{peptide}} = \sum_i n_i \cdot M_{\text{residue},i} + M_{\text{H}_2\text{O}}$$
where the water molecule accounts for the uncondensed termini. SciForge provides a complete table of 20 amino acid average and monoisotopic masses (e.g., Gly = 57.021 Da, Trp = 186.079 Da).
Isoelectric point. Estimated by finding the pH at which net charge is zero, summing Henderson–Hasselbalch contributions from all ionizable residues.
Radiation effects on biological systems.
DNA damage. Single-strand break probability per gray: $P_{\text{SSB}} = 1 - e^{-\alpha_{\text{SSB}} D}$. DSB probability: $P_{\text{DSB}} = 1 - e^{-\alpha_{\text{DSB}} D}$. DSBs are the critical lethal lesion.
Chromosome aberrations. Dicentric yield: $Y = \alpha D + \beta D^2$ (linear-quadratic model). This underlies biological dosimetry.
Linear-quadratic cell survival. $S(D) = e^{-\alpha D - \beta D^2}$, with $\alpha/\beta$ ratio distinguishing early-responding ($\alpha/\beta \approx 10$ Gy) from late-responding ($\alpha/\beta \approx 3$ Gy) tissues.
Reproductive biology and embryogenesis.
Cleavage timing. Embryonic cell count at time $t$: $N(t) = 2^{\lfloor t / T_{\text{cycle}} \rfloor}$, where $T_{\text{cycle}}$ is the cleavage cycle duration (~12–24 hours in mammals).
Morphogen gradients. Exponential decay from a source (see Developmental Biology). Threshold-dependent cell fate commitment determines tissue patterning.
Somitogenesis clock. Periodic gene expression drives segmentation with period $T$. Somite size $= v_{\text{wavefront}} \times T$.
Stem cell dynamics and engineering.
Waddington potential. The multipotency index quantifies a cell's distance from committed states:
$$\text{MI} = 1 - \frac{|U(x) - U_{\text{peak}}|}{U_{\text{peak}} - U_{\text{valley}}}$$
$\text{MI} = 1$ at the hilltop (fully multipotent); $\text{MI} = 0$ at a valley (fully committed).
Differentiation commitment. Commitment index: $\text{CI} = 1 - \exp(-|U(x) - U_{\text{uncommitted}}|)$.
Self-renewal vs. differentiation. Balance determines stem cell pool maintenance. Symmetric division: two stem cells or two differentiated cells. Asymmetric: one of each.
Macromolecular structure analysis.
3D molecular geometry. Bond angles from three atomic positions using the dot product:
$$\theta = \arccos\!\left(\frac{\vec{BA} \cdot \vec{BC}}{|\vec{BA}||\vec{BC}|}\right)$$
Dihedral (torsion) angles from four atoms using the cross-product method. Ramachandran plots map backbone $\phi/\psi$ angles to identify allowed conformational regions.
RMSD. Root mean square deviation between two structures: $\text{RMSD} = \sqrt{\frac{1}{N}\sum_{i=1}^{N} d_i^2}$.
Engineered biological systems.
Toggle switch. Gardner's bistable genetic circuit with mutual repression:
$$\frac{du}{dt} = \frac{\alpha_1}{1 + v^n} - \beta u, \qquad \frac{dv}{dt} = \frac{\alpha_2}{1 + u^n} - \gamma v$$
Two stable steady states exist when $n > 1$ and $\alpha_1, \alpha_2$ are sufficiently large relative to $\beta, \gamma$.
Repressilator. Three-gene ring oscillator (Elowitz & Leibler):
$$\frac{dx_i}{dt} = \frac{\alpha}{1 + x_{(i+2)\bmod 3}^n} + \alpha_0 - \beta x_i$$
Sustained oscillations emerge for appropriate parameter regimes.
CRISPR scoring. On-target efficiency depends on GC content, position-specific scores, and PAM strength: $S = S_{\text{pos}} \times f_{\text{GC}} \times \text{PAM}$. Off-target CFD (cutting frequency determination) score: $\text{CFD} = \prod (1 - p_{\text{mismatch},i})$.
Metabolic engineering. The flux balance objective maximizes a linear function: $Z = \mathbf{c}^T \mathbf{v}$ subject to stoichiometric constraints $\mathbf{S} \mathbf{v} = 0$. Theoretical yield: $Y = (\text{substrate carbons} / \text{product carbons}) \times \eta$.
Stochastic gene expression. Mean protein level: $\langle P \rangle = (k_{\text{txn}} k_{\text{tln}}) / (\delta_m \delta_p)$. Fano factor: $F = 1 + b$, where burst size $b = k_{\text{tln}} / (\delta_m + \delta_p)$. Intrinsic noise: $\eta^2_{\text{int}} = (1+b)/\langle P \rangle$.
Whole-system modeling of biological networks.
Bistability. Toggle switch dynamics (same formalism as synthetic biology) produce hysteresis and ultrasensitivity in signaling cascades.
Flux balance analysis (FBA). Steady-state metabolic flux through stoichiometric matrix $\mathbf{S}$: $\mathbf{S} \mathbf{v} = 0$. Feasibility requires all metabolic production/consumption rates to balance within tolerance.
Boolean networks. Gene regulatory networks with discrete ON/OFF states. State update: $x_i(t+1) = f_i(x_{j_1}(t), x_{j_2}(t), \ldots)$ where $f_i$ is a Boolean rule. Attractor analysis reveals stable cell states.
Goodwin oscillator. Negative feedback loop with cooperative repression (Hill coefficient $n$). Simulated with Euler integration. The repressilator extends this to three-gene ring topology.
Sensitivity analysis. Local sensitivity: normalized partial derivative. Morris method: elementary effects screening. Sobol indices: first-order $S_i = V_i / V_T$, total-order $S_{Ti} = 1 - V_{-i}/V_T$, and partial rank correlation coefficient (PRCC) for monotonic relationships.
Engineering biological tissues.
Bioreactor design. Perfusion rate: $D = Q / V$. Shear stress in parallel-plate bioreactor:
$$\tau = \frac{6 \mu Q}{w h^2}$$
where $\mu$ is viscosity, $Q$ flow rate, $w$ width, $h$ height. Oxygen transfer rate: $\text{OTR} = k_L a \cdot (C^* - C)$.
Scaffold degradation. Bulk erosion: $M(t) = M_0 e^{-kt}$. Surface erosion: $M(t) = M_0 - r \cdot A \cdot t$. Porosity: $\phi = V_{\text{void}} / V_{\text{total}}$. Mechanical stiffness degrades as $E(t) = E_0 (1 - f_d)^n$.
Krogh cylinder. Oxygen distribution around a capillary:
$$pO_2(r) = pO_{2,\text{cap}} - \frac{Q_0}{4D}(r^2 - r_c^2 - 2r_c^2 \ln(r/r_c))$$
Nutrient penetration depth: $L = \sqrt{2 D C_s / Q_0}$, limiting maximum engineered tissue thickness without vascularization.
Vascularization. VEGF concentration follows exponential decay from source: $C(x) = C_0 e^{-x/\lambda}$. Sprouting probability: Hill function of VEGF level. Optimal vessel spacing: $2\sqrt{2 D \cdot pO_{2,a} / Q_0}$.
Effects of toxic substances.
Bioconcentration factor (BCF). $\text{BCF} = C_{\text{organism}} / C_{\text{water}}$. Biomagnification factor: $\text{BMF} = C_{\text{predator}} / C_{\text{prey}}$. One-compartment toxicokinetics:
$$\frac{dC}{dt} = k_{\text{uptake}} \cdot C_{\text{exposure}} - k_{\text{elim}} \cdot C$$
LD50 estimation. Probit analysis: transform dose–response data via probit($p$) vs. $\ln(\text{dose})$, then linear regression to find the dose at probit = 5 (50% mortality).
Dose–response. Hill model: $E = E_{\max} D^n / (EC_{50}^n + D^n)$. Benchmark dose (BMD): the dose producing a specified benchmark response above background.
**Oxidative stress mechanisms.** Oxidative stress index: $\text{OSI} = \text{ROS production} / \text{antioxidant capacity}$. DNA adduct formation: $\dot{A} = k [M][DNA]$. Lipid peroxidation and protein carbonylation follow second-order kinetics.
Ecotoxicology. Species sensitivity distributions (SSD) rank species NOEC/EC50 values to derive protective concentrations (HC5 = hazardous concentration for 5% of species).
Virus biology and dynamics.
Target-cell limited model. Within-host viral dynamics:
$$\frac{dx}{dt} = -\beta x v, \qquad \frac{dy}{dt} = \beta x v - \delta y, \qquad \frac{dv}{dt} = p y - c v$$
where $x$ = uninfected target cells, $y$ = infected cells, $v$ = free virus, $\beta$ = infection rate, $\delta$ = infected cell death, $p$ = virus production, $c$ = clearance.
Basic reproduction number. $R_0 = \frac{\beta p x_0}{\delta c}$. Infection establishes when $R_0 > 1$. Burst size: $N = p / \delta$.
Viral load decay. Under therapy: $v(t) = v_0 e^{-ct}$, with half-life $t_{1/2} = \ln 2 / c$ (typically 6 hours for HIV).
Quasispecies theory. Fitness of the master sequence with mutation rate $\mu$ per base and genome length $L$:
$$W = w_0 (1 - \mu)^L$$
Error threshold. Maximum mutation rate compatible with selection: $\mu_{\max} = 1 - (1/\sigma)^{1/L}$ where $\sigma$ is the superiority of the master sequence.
Epidemiology. SIR and SEIR models (see Population Biology). Epidemic doubling time, generation time, and serial interval are computed for emerging pathogens.
Capsid geometry. Caspar–Klug theory: T-number triangulation gives $60T$ subunits per icosahedral capsid. Capsid radius: $R = \sqrt{N \cdot A_{\text{sub}} / (4\pi)}$. Genome packaging density: $\rho = L_{\text{genome}} / V_{\text{capsid}}$.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The Chemistry module spans 26 submodules across 56 source files, covering analytical, physical, organic, inorganic, and computational chemistry. It provides tools for reaction modeling, equilibrium calculations, spectroscopic analysis, and materials characterization.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Proton transfer equilibria govern pH, buffer behavior, and titration analysis — central to biology, environmental chemistry, and industrial processes.
**Equilibria** — The Henderson-Hasselbalch equation $\text{pH} = \text{p}K_a + \log_{10}([A^-]/[HA])$ predicts pH of buffer solutions. The module computes pH of strong acids ($\text{pH} = -\log c$), strong bases ($\text{pH} = 14 + \log c$), weak acids ($\text{pH} = \frac{1}{2}(\text{p}K_a - \log c)$), and weak bases. Interconversion between $K_a$, $\text{p}K_a$, and $\text{p}K_b$ is provided ($\text{p}K_a + \text{p}K_b = \text{p}K_w$). For polyprotic systems, the alpha fraction $\alpha_i$ gives the proportion of each protonation state as a function of [H⁺] and the successive $K_a$ values. The amphiprotic pH formula $\text{pH} \approx (\text{p}K_{a1} + \text{p}K_{a2})/2$ handles zwitterionic species.
Titrations — Equivalence point determination, half-equivalence pH (equals $\text{p}K_a$), and complete titration curve modeling for mono- and polyprotic acids.
Quantitative and qualitative techniques for chemical characterization.
Chromatography — The van Deemter equation $H = A + B/u + Cu$ models plate height as a function of mobile-phase velocity, combining eddy diffusion ($A$), longitudinal diffusion ($B/u$), and mass transfer resistance ($Cu$). Resolution $R_s$, capacity factor, retention factor, selectivity, and number of theoretical plates are all computed.
Quantitative Analysis — Gravimetric yield, volumetric titration calculations, standard addition method, and calibration curve regression.
Spectrophotometry — Beer-Lambert law $A = \varepsilon \ell c$ relates absorbance to molar absorptivity, path length, and concentration. Transmittance $T = 10^{-A}$, multi-component analysis via linear superposition of absorptivities.
Chemistry of dispersed systems (nanoparticles, emulsions, foams) where interface effects dominate bulk properties.
Properties — Particle size distribution statistics, specific surface area, sedimentation rate (Stokes' law $v = 2r^2\Delta\rho g/(9\mu)$), and Brownian motion.
Stability — DLVO theory combines van der Waals attraction and electric double-layer repulsion to predict colloidal stability. The module computes zeta potential, coagulation kinetics, Schulze-Hardy rule (critical coagulation concentration scales as $z^{-6}$ for the ion valence), and flocculation rates.
Numerical approaches to molecular electronic structure.
Basis Sets — Construction of Gaussian-type orbital (GTO) and Slater-type orbital (STO) basis sets for molecular calculations. Primitive and contracted Gaussian parameters.
Density Functional Theory — DFT total energy calculations using exchange-correlation functionals. Energy decomposition into kinetic, Coulomb, exchange, and correlation contributions.
Solid-state structural analysis using diffraction and lattice geometry.
Diffraction — Bragg's law $n\lambda = 2d\sin\theta$ for constructive interference of X-rays. Structure factor $F_{hkl}$ calculation, powder diffraction peak positions, reciprocal lattice vectors.
Lattice — Unit cell parameters (a, b, c, α, β, γ), the seven crystal systems, packing fractions (FCC 0.74, BCC 0.68, SC 0.52), Miller index determination, and interplanar distances $d_{hkl} = a/\sqrt{h^2+k^2+l^2}$ for cubic systems.
Electron transfer processes, from batteries to corrosion to electroplating.
**Cells** — The Nernst equation $E = E^0 - \frac{RT}{nF}\ln Q$ gives the cell potential under non-standard conditions. Standard electrode potentials combine as $E_{\text{cell}} = E_{\text{cathode}} - E_{\text{anode}}$. Gibbs free energy $\Delta G = -nFE$. Faraday's law of electrolysis $m = ItM/(nF)$ gives the mass deposited. The Tafel equation $\eta = a + b\log|j|$ models overpotential. The Butler-Volmer equation $j = j_0[\exp(\alpha_a F\eta/RT) - \exp(-\alpha_c F\eta/RT)]$ describes full current-overpotential behavior. Battery metrics: open-circuit voltage, energy density (Wh/kg), Faradaic efficiency, and coulombic efficiency.
Transport — Ionic conductivity, transference numbers, Debye-Hückel limiting law $\log\gamma_\pm = -A|z_+z_-|\sqrt{I}$ for activity coefficients in dilute electrolytes.
Chemistry of natural systems and pollutant fate.
Atmosphere — Ozone formation and destruction cycles, photochemical smog kinetics, greenhouse gas atmospheric lifetimes, and radiative forcing.
Water — Dissolved oxygen modeling, biological and chemical oxygen demand (BOD/COD), water hardness (Ca²⁺ + Mg²⁺ equivalents), and composite water quality indices.
Chemical equilibrium thermodynamics.
**Constants** — Equilibrium constant expressions $K = \prod [P]^{n_p}/\prod [R]^{n_r}$, reaction quotient $Q$, Le Chatelier's principle (qualitative), and $K_p/K_c$ interconversion via $K_p = K_c(RT)^{\Delta n}$.
Ionic Equilibria — Solubility product $K_{sp}$, common ion effect on solubility, complex ion formation constants, and precipitation criteria ($Q > K_{sp}$).
Behavior of ideal and real gases under varying conditions.
Ideal — $PV = nRT$, combined gas law $P_1V_1/T_1 = P_2V_2/T_2$, Dalton's law of partial pressures $P_{\text{total}} = \sum P_i$, Graham's law of effusion $\text{rate} \propto 1/\sqrt{M}$, and molar volume at STP.
Real — Van der Waals equation $(P + a/V_m^2)(V_m - b) = RT$ corrects for molecular attractions ($a$) and finite molecular volume ($b$). Compressibility factor $Z = PV/(nRT)$ quantifies departure from ideality. Virial coefficients for systematic correction.
Sustainability metrics for chemical process evaluation.
Metrics — Atom economy $= M_{\text{product}}/M_{\text{reactants}} \times 100\%$, E-factor (mass of waste per mass of product), and process mass intensity (total mass input per mass of product).
Principles — The twelve principles of green chemistry (prevention, atom economy, less hazardous synthesis, etc.) encoded as a decision framework, with solvent selection guidelines.
Non-carbon-based chemical systems, coordination compounds, and crystal field theory.
Bonding — Ionic bond energy, Born-Landé lattice energy $U = \frac{N_A M z^+ z^- e^2}{4\pi\varepsilon_0 r_0}(1-1/n)$, and electronegativity difference classification (ionic vs. covalent).
Coordination — Complex geometry (octahedral, tetrahedral, square planar), chelate effect thermodynamics, stability constants, and isomer enumeration.
Crystal Field Theory — Octahedral splitting $\Delta_{\text{oct}} = 10Dq$, tetrahedral splitting $\Delta_{\text{tet}} = \frac{4}{9}\Delta_{\text{oct}}$. Crystal field stabilization energy (CFSE) accounting for electron occupation and pairing energy. Spin-only magnetic moment $\mu = \sqrt{n(n+2)}\,\mu_B$. Spectrochemical series (ligand $f$ × metal $g$ product). Jahn-Teller distortion prediction. Nephelauxetic ratio $\beta = B_{\text{complex}}/B_{\text{free ion}}$ measures covalency. Racah parameter extraction from electronic transitions.
Rates and mechanisms of chemical reactions — essential for reactor design, pharmacology, and environmental fate modeling.
**Rate Laws** — The Arrhenius equation $k = A e^{-E_a/RT}$ connects rate constant to activation energy. Integrated rate laws: zero-order $[A] = [A]_0 - kt$, first-order $[A] = [A]_0 e^{-kt}$, second-order $1/[A] - 1/[A]_0 = kt$, and the general $n$th-order form. Half-lives: $t_{1/2} = \ln 2/k$ (first-order), $t_{1/2} = 1/(k[A]_0)$ (second-order), $t_{1/2} = [A]_0/(2k)$ (zero-order). Activation energy extraction from two temperatures: $E_a = R\ln(k_2/k_1)/(1/T_1 - 1/T_2)$.
**Advanced Kinetics** — Eyring equation $k = \kappa(k_BT/h)\exp(-\Delta G^\ddagger/RT)$ from transition-state theory. Collision frequency from kinetic molecular theory. General rate law $r = k\prod [A_i]^{n_i}$.
Mechanisms — Elementary step analysis, rate-determining step identification, steady-state approximation for reactive intermediates.
Molecular structure, bonding, and geometry prediction.
Bonding — VSEPR theory, hybridization assignment (sp, sp², sp³, etc.), bond order, and electronegativity (Pauling, Mulliken).
Geometry — Bond angle prediction, molecular shape from electron-pair geometry, and dipole moment vector summation.
Radioactive processes and nuclear energy.
Decay — Alpha, beta, gamma decay rate laws, decay series modeling, and nuclear transmutation calculations.
Energy — Binding energy per nucleon from mass defect, fission and fusion energy release, and mass-energy equivalence $E = \Delta m \cdot c^2$.
Carbon-based molecular systems — the foundation of biochemistry and materials science.
Descriptors — Molecular weight, degree of unsaturation $\text{DoU} = (2C+2+N-H)/2$, and functional group classification.
**Reactions** — SN1 (rate $= k[\text{substrate}]$), SN2 (rate $= k[\text{substrate}][\text{nucleophile}]$), E1, and E2 kinetics. The Hammett equation $\log(k/k_0) = \rho\sigma$ quantifies substituent electronic effects via $\sigma$ constants and reaction sensitivity $\rho$. The Taft equation separates steric from electronic contributions: $\log(k/k_0) = \rho^*\sigma^* + \delta E_s$.
Structure — Constitutional and stereoisomerism, chirality, conformational analysis (Newman projections, ring strain).
Light-driven chemical processes, fundamental to photosynthesis, solar cells, and photocatalysis.
Kinetics — Photochemical reaction rates, photosensitization, and dynamic quenching.
**Quantum Yield** — Fluorescence ($\Phi_f$) and phosphorescence yields, Stern-Volmer analysis $I_0/I = 1 + K_{SV}[Q]$ for quencher concentration dependence.
Macromolecular chemistry governing plastics, fibers, and biological polymers.
Distributions — Number-average ($M_n$) and weight-average ($M_w$) molecular weight, polydispersity index $PDI = M_w/M_n$, and degree of polymerization.
**Properties** — Mark-Houwink equation $[\eta] = KM^a$ for intrinsic viscosity. End-to-end distance of a freely-jointed chain $R = l\sqrt{N}$. Radius of gyration $R_g = R/\sqrt{6}$. Fox equation for glass transition of blends. Carothers equation $\bar{X}_n = 2/(2 - p\bar{f})$ for step-growth polymerization degree.
Quantum mechanical treatment of molecular electronic structure.
Hückel MO Theory — Secular determinant construction for linear and cyclic conjugated systems. The $\alpha + x\beta$ Hamiltonian matrix encodes nearest-neighbor interactions. $\pi$-electron energies, delocalization energy, and charge density distributions from MO coefficients and occupation numbers.
Orbitals — Atomic orbital energies, electron configurations, molecular orbital construction, and orbital symmetry.
Chemical reactor analysis and design for industrial-scale processes.
Design — CSTR (continuous stirred-tank reactor) design equation $V = F_{A0}X/(-r_A)$ and PFR (plug flow reactor) equation $V = F_{A0}\int_0^X dX'/(-r_A)$. Residence time, space velocity, and conversion calculations.
Reactors — Batch, continuous, and semi-batch reactor models, selectivity, and yield optimization for parallel and series reactions.
Electronic and defect structure of crystalline materials.
Band Theory — Band gap determination, classification of conductors, insulators, and semiconductors, and Fermi level positioning.
Defects — Point defects (vacancies, interstitials), Schottky pairs ($n_s = N\exp(-E_s/2k_BT)$), Frenkel defects, and defect equilibrium thermodynamics.
Dissolved species behavior and mixture thermodynamics.
Colligative Properties — Boiling point elevation $\Delta T_b = iK_bm$, freezing point depression $\Delta T_f = iK_fm$, osmotic pressure $\Pi = iMRT$, and vapor pressure lowering (Raoult's law). Molar mass determination from ebullioscopy and cryoscopy.
Mixtures — Raoult's law $P_i = x_i P_i^0$ for ideal solutions, Henry's law $P = K_H x$ for dilute solutes, activity coefficients for real mixtures, and excess Gibbs energy.
Interaction of electromagnetic radiation with matter for structural determination.
IR Spectroscopy — Infrared absorption frequencies mapped to functional groups. Selection rules (dipole moment change required). Characteristic group frequencies for O-H, N-H, C=O, C-H, etc.
Mass Spectrometry — Mass-to-charge ratio analysis, isotope pattern computation, fragmentation pattern prediction, and molecular ion identification.
NMR Spectroscopy — Chemical shift $\delta = (f - f_{\text{ref}})/f_{\text{spec}} \times 10^6$ ppm. Spin-spin coupling constants. Multiplicity from $n+1$ rule. Larmor frequency $\nu = \gamma B_0/(2\pi)$. Relaxation: $T_1$ (inversion recovery $M = M_0(1 - 2e^{-t/T_1})$) and $T_2$ (spin echo $M = M_0 e^{-t/T_2}$). Linewidth $\Delta\nu = 1/(\pi T_2)$. Nuclear Overhauser enhancement $\eta = 1 + \gamma_I/(2\gamma_S)$.
Quantitative relationships in chemical reactions.
Balancing — Chemical equation balancing using oxidation number methods and half-reaction approaches.
Calculations — Mole ratios from balanced equations, limiting reagent identification, theoretical yield, and percent yield.
Interfacial phenomena controlling catalysis, adsorption, and wetting.
**Adsorption** — Langmuir isotherm $\theta = K P/(1+KP)$ (monolayer, uniform surface), Freundlich isotherm $q = K_f P^{1/n}$ (heterogeneous surface), BET isotherm $V = V_m c x/[(1-x)(1-x+cx)]$ for multilayer adsorption ($x = P/P_0$). Temkin isotherm (heat of adsorption decreases linearly with coverage). Dissociative Langmuir adsorption. BET surface area determination from monolayer volume.
Surface Tension — Surface tension, capillarity, Young-Laplace equation $\Delta P = 2\gamma/r$, and contact angle (Young's equation).
Energy changes in chemical processes.
Enthalpy — Hess's law (additivity of enthalpies), standard enthalpies of formation, bond enthalpies (average bond dissociation energies), and calorimetry calculations.
Entropy — Standard molar entropy, Gibbs free energy $\Delta G = \Delta H - T\Delta S$, and spontaneity criteria ($\Delta G < 0$).
Mass and momentum transfer in chemical systems.
Diffusion — Fick's first law $J = -D\,dc/dx$ (steady-state flux) and second law $\partial c/\partial t = D\,\partial^2 c/\partial x^2$ (transient). Diffusion coefficients in gases and liquids.
Mass Transfer — Convective mass transfer coefficients, film theory (stagnant film model), and penetration theory (surface renewal model).
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The constants module provides **5 submodules** of curated scientific constants, element data, and unit conversion factors. All values are compile-time const declarations with full precision, sourced from CODATA 2018 and IUPAC recommendations. No runtime overhead — every constant is inlined at compilation.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Core physical constants used across all scientific domains. These form the foundation of the SI system and appear throughout every SciForge module.
| Constant | Symbol | Value | Unit |
|---|---|---|---|
| Speed of light | $c$ | $2.997\,924\,58 \times 10^8$ | m/s |
| Gravitational constant | $G$ | $6.674\,30 \times 10^{-11}$ | m³ kg⁻¹ s⁻² |
| Planck constant | $h$ | $6.626\,070\,15 \times 10^{-34}$ | J·s |
| Reduced Planck constant | $\hbar$ | $1.054\,571\,817 \times 10^{-34}$ | J·s |
| Boltzmann constant | $k_B$ | $1.380\,649 \times 10^{-23}$ | J/K |
| Avogadro number | $N_A$ | $6.022\,140\,76 \times 10^{23}$ | mol⁻¹ |
| Elementary charge | $e$ | $1.602\,176\,634 \times 10^{-19}$ | C |
| Vacuum permittivity | $\varepsilon_0$ | $8.854\,187\,812\,8 \times 10^{-12}$ | F/m |
| Vacuum permeability | $\mu_0$ | $1.256\,637\,062\,12 \times 10^{-6}$ | H/m |
| Coulomb constant | $k_e$ | $8.987\,551\,787 \times 10^9$ | N·m²/C² |
| Stefan–Boltzmann constant | $\sigma$ | $5.670\,374\,419 \times 10^{-8}$ | W m⁻² K⁻⁴ |
| Gas constant | $R$ | $8.314\,462\,618$ | J mol⁻¹ K⁻¹ |
| Fine-structure constant | $\alpha$ | $7.297\,352\,569\,3 \times 10^{-3}$ | dimensionless |
Planck units. Natural units where $c = G = \hbar = k_B = 1$:
These represent the scales where quantum gravity effects become significant.
Constants for astrophysics, celestial mechanics, and cosmology.
| Constant | Symbol | Value | Unit |
|---|---|---|---|
| Astronomical unit | AU | $1.495\,978\,707 \times 10^{11}$ | m |
| Parsec | pc | $3.085\,677\,581 \times 10^{16}$ | m |
| Light-year | ly | $9.460\,730\,473 \times 10^{15}$ | m |
| Solar mass | $M_\odot$ | $1.989\,1 \times 10^{30}$ | kg |
| Solar radius | $R_\odot$ | $6.957 \times 10^8$ | m |
| Solar luminosity | $L_\odot$ | $3.828 \times 10^{26}$ | W |
| Earth mass | $M_\oplus$ | $5.972\,37 \times 10^{24}$ | kg |
| Earth radius | $R_\oplus$ | $6.371\,0 \times 10^6$ | m |
| Hubble constant | $H_0$ | $67.4$ | km s⁻¹ Mpc⁻¹ |
| CMB temperature | $T_{\text{CMB}}$ | $2.725$ | K |
Key relationships. The Hubble constant determines the age of the universe in the simplest model: $t_H = 1/H_0 \approx 14.5$ Gyr. The parsec is defined geometrically: 1 pc = 1 AU / $\tan(1'')$ ≈ 3.26 ly. Solar gravitational parameter $\mu_\odot = G M_\odot \approx 1.327 \times 10^{20}$ m³/s².
Atomic and subatomic scale constants for quantum mechanics and spectroscopy.
| Constant | Symbol | Value | Unit |
|---|---|---|---|
| Proton mass | $m_p$ | $1.672\,621\,924 \times 10^{-27}$ | kg |
| Neutron mass | $m_n$ | $1.674\,927\,498 \times 10^{-27}$ | kg |
| Electron mass | $m_e$ | $9.109\,383\,702 \times 10^{-31}$ | kg |
| Atomic mass unit | u | $1.660\,539\,067 \times 10^{-27}$ | kg |
| AMU to MeV | $931.494$ | MeV/c² | |
| Bohr radius | $a_0$ | $5.291\,772\,109 \times 10^{-11}$ | m |
| Rydberg energy | $Ry$ | $13.606$ | eV |
| Bohr magneton | $\mu_B$ | $9.274\,010\,078 \times 10^{-24}$ | J/T |
| Nuclear magneton | $\mu_N$ | $5.050\,783\,746 \times 10^{-27}$ | J/T |
| Compton wavelength | $\lambda_C$ | $2.426\,310\,239 \times 10^{-12}$ | m |
Key relationships. The Bohr radius is $a_0 = \hbar / (m_e c \alpha) = 4\pi\varepsilon_0 \hbar^2 / (m_e e^2)$. The Rydberg energy is $Ry = m_e e^4 / (8 \varepsilon_0^2 h^2) = 13.606$ eV. Hydrogen energy levels: $E_n = -Ry / n^2$. The mass–energy equivalence $1 \text{ u} = 931.494 \text{ MeV}/c^2$ is central to nuclear binding energy calculations.
Complete data for all **118 elements**, parsed at compile time from YAML files in the tableau-periodique/ directory.
Each element provides:
The elements are loaded using SciForge's built-in YAML parser from 118 source files organized into 11 IUPAC categories:
| Category | Directory | Count |
|---|---|---|
| Alkali metals | metaux-alcalins/ | 6 |
| Alkaline earth metals | metaux-alcalino-terreux/ | 6 |
| Transition metals | metaux-de-transition/ | 38 |
| Post-transition metals | metaux-post-transition/ | 13 |
| Metalloids | metalloides/ | 7 |
| Nonmetals | non-metaux/ | 7 |
| Halogens | halogenes/ | 5 |
| Noble gases | gaz-nobles/ | 7 |
| Lanthanides | lanthanides/ | 15 |
| Actinides | actinides/ | 15 |
| Superheavy elements | elements-superlourds/ | varies |
The element database is lazily initialized via OnceLock for thread-safe, zero-cost access after first use. Lookup functions allow querying by atomic number, symbol, or name.
Conversion factors between common scientific unit systems.
Energy conversions:
Pressure conversions:
Angular conversions:
Length scales:
All conversion factors are defined as pub const f64 for zero-cost compile-time use.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The Geology module spans 4 submodules focused on Earth sciences: seismology, radiometric dating, petrology, and plate tectonics. It provides tools for seismic wave analysis, rock classification, age determination, and geodynamic modeling.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Radiometric and geochronological methods for determining the age of rocks, minerals, and organic remains. These techniques exploit the predictable decay of radioactive isotopes to anchor Earth's geological timescale.
Radioactive Decay — The fundamental law $N(t) = N_0 e^{-\lambda t}$ describes the exponential decrease of a parent isotope, where $\lambda = \ln 2 / t_{1/2}$ is the decay constant. The general radiometric age from a daughter-to-parent ratio is $t = \frac{1}{\lambda}\ln\!\left(1 + \frac{D}{P}\right)$.
Carbon-14 Dating — For organic materials up to ~50 ka, the age follows $t = -8267\,\ln(R)$ where $R$ is the measured ¹⁴C/¹²C ratio relative to the modern standard. The mean life $\tau = 8267$ years corresponds to the Libby half-life of 5730 years.
Potassium-Argon (K-Ar) — Used for volcanic rocks, with $t = \frac{1}{\lambda}\ln\!\left(1 + \frac{{}^{40}\text{Ar}}{f \cdot {}^{40}\text{K}}\right)$ where $\lambda = 5.543 \times 10^{-10}\,\text{yr}^{-1}$ and $f = 0.1048$ is the electron capture branching ratio.
Uranium-Lead (U-Pb) — The most precise chronometer for ancient rocks. Age from $t = \frac{1}{\lambda_{238}}\ln\!\left(1 + \frac{{}^{206}\text{Pb}}{{}^{238}\text{U}}\right)$ with $\lambda_{238} = 1.55125 \times 10^{-10}\,\text{yr}^{-1}$. Concordia diagrams combine both U decay chains for discordance analysis.
Isochron Method — Linear regression on a plot of daughter/stable vs. parent/stable isotope ratios: the slope $m$ gives $t = \frac{1}{\lambda}\ln(1+m)$, and the y-intercept gives the initial ratio, eliminating the need for assumptions about initial daughter abundance.
Fission Track Dating — Counts spontaneous fission tracks of ²³⁸U in minerals: $t = \frac{1}{\lambda}\ln\!\left(1 + \frac{\lambda\,\rho_s\,\rho_d}{\rho_i}\right)$ where $\rho_s$, $\rho_i$, $\rho_d$ are spontaneous, induced, and dosimeter track densities.
Luminescence Dating — Equivalent dose from accumulated radiation: $\text{Age} = \text{Natural Signal} / \text{Dose Rate}$. Applicable to quartz and feldspar grains in sediments (OSL/TL).
Cosmogenic Nuclide Exposure — Surface exposure age from in-situ production of cosmogenic isotopes (¹⁰Be, ²⁶Al): $t = -\frac{1}{\lambda}\ln\!\left(1 - \frac{C\lambda}{P}\right)$ where $C$ is concentration and $P$ is the local production rate.
Rock classification, igneous geochemistry, and magmatic process modeling.
CIPW Normative Mineralogy — The Cross-Iddings-Pirsson-Washington norm recasts whole-rock oxide analyses (SiO₂, Al₂O₃, FeO, MgO, CaO, Na₂O, K₂O…) into hypothetical mineral assemblages. The quartz norm $Q = \text{SiO}_2 - \text{feldspars} - \text{mafics}$ determines silica saturation (positive Q → quartz-normative; negative → nepheline-normative).
Mg Number — An index of magmatic differentiation: $\text{Mg\#} = \frac{\text{MgO}/40.3}{\text{MgO}/40.3 + \text{FeO}/71.85} \times 100$. Primitive basalts have Mg# > 70; evolved magmas < 50.
Total Alkali-Silica (TAS) — Classification of volcanic rocks by plotting $(\text{Na}_2\text{O} + \text{K}_2\text{O})$ vs. SiO₂, delineating fields for basalt, andesite, dacite, rhyolite, etc.
Alumina Saturation Index — $\text{ASI} = \frac{\text{Al}_2\text{O}_3/102}{\text{CaO}/56 + \text{Na}_2\text{O}/62 + \text{K}_2\text{O}/94}$ in molar proportions. ASI < 1 → metaluminous; ASI = 1 → peraluminous boundary; ASI > 1 → peraluminous (cordierite/garnet-bearing granites).
Differentiation Index — $DI = Q + Or + Ab + Ne$ from the CIPW norm, quantifying degree of magmatic evolution (high DI → granitic; low DI → gabbroic).
Liquidus & Solidus — Liquidus temperature interpolation from a binary phase diagram. Solidus depression by water: $T_{\text{solidus}} = T_0 - k \cdot w^{0.6}$ where $w$ is water content (wt.%).
Crystal Settling — Stokes' velocity for crystals sinking through magma: $v = \frac{2\Delta\rho\,g\,r^2}{9\mu}$. Magma viscosity follows an Arrhenius relation $\mu = A\exp(E_a/RT)$, strongly dependent on SiO₂ content and temperature.
Earthquake characterization and seismic wave propagation through Earth's interior.
Body Waves — P-wave velocity $V_P = \sqrt{(K + \frac{4}{3}G)/\rho}$ and S-wave velocity $V_S = \sqrt{G/\rho}$, where $K$ is the bulk modulus, $G$ the shear modulus, and $\rho$ the density. S-waves cannot propagate in liquids ($G = 0$), which constrains the outer core to be fluid.
Magnitude Scales — The local (Richter) magnitude $M_L = \log_{10} A + 3\log_{10} d - 2.92$ relates to the amplitude $A$ (µm) and epicentral distance $d$ (km). The moment magnitude $M_w = (\log_{10} M_0 - 9.1)/1.5$ is based on the seismic moment $M_0 = \mu A D$ (rigidity × fault area × slip). Seismic energy $E = 10^{1.5M+4.8}$ (Gutenberg-Richter energy-magnitude relation).
Epicenter Location — Triangulation from $S - P$ arrival time: $\Delta = \frac{(t_S - t_P) \cdot V_P \cdot V_S}{V_P - V_S}$ requires three or more station readings.
Snell's Law (Seismic) — Refraction at layer boundaries: $\frac{\sin\theta_1}{V_1} = \frac{\sin\theta_2}{V_2}$, critical for ray-tracing through Earth's velocity structure and detecting discontinuities (Mohorovičić, Gutenberg).
Gutenberg-Richter Law — Earthquake frequency-magnitude distribution: $\log_{10} N = a - bM$ where $N$ is the annual number of earthquakes ≥ magnitude $M$, $a$ measures total seismicity and $b \approx 1$ globally.
Omori's Law — Aftershock decay rate: $n(t) = K/(t+c)^p$ where $t$ is time after the mainshock, $c$ avoids the singularity at $t = 0$, and $p \approx 1$ empirically.
Peak Ground Acceleration — Ground motion prediction equation $\text{PGA} = a \cdot e^{bM}/d$ relating magnitude and hypocentral distance to hazard, used for seismic building codes.
Plate motion, lithospheric mechanics, and thermal evolution of sedimentary basins.
Plate Velocity — Average velocity $v = d/t$ from hotspot tracks or magnetic anomaly offsets. Velocity at any point from an Euler pole: $v = \omega R \sin\theta$ where $\omega$ is the angular velocity, $R$ the Earth's radius, and $\theta$ the angular distance (colatitude) from the rotation pole.
Isostasy — Airy model: a topographic elevation $h$ is compensated by a crustal root of depth $r = h\rho_c/(\rho_m - \rho_c)$. Pratt model: density varies laterally so that $\rho(D + h) = \rho_{\text{ref}} D_{\text{ref}}$ for constant compensation depth. General isostatic equilibrium: free-board $= t_c(1 - \rho_c/\rho_m)$.
McKenzie Stretching Model — Initial subsidence of a rift basin under uniform lithospheric thinning (stretching factor $\beta$):
$$S_i = t_c \frac{\rho_m \alpha T_l}{2(\rho_m - \rho_c)}\left(1 - \frac{1}{\beta}\right)$$
where $\alpha$ is the thermal expansion coefficient and $T_l$ the basal lithosphere temperature. Subsequent thermal subsidence follows $e(t) = e_0(1 - e^{-t/\tau})$ with a thermal time constant $\tau \approx 60$ Myr.
Heat Flow — Fourier's law $q = -k\,dT/dz$ links surface heat flow to thermal conductivity and the geothermal gradient. Temperature at depth: $T(z) = T_s + \nabla T \cdot z$.
Flexural Rigidity — The bending resistance of the lithosphere: $D = \frac{E\,T_e^3}{12(1-\nu^2)}$ where $E$ is Young's modulus, $T_e$ the effective elastic thickness, and $\nu$ Poisson's ratio. Inverse calculation of $T_e$ from observed flexure constrains lithospheric strength.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The Hub is SciForge's central orchestration layer. It connects all scientific modules through a unified API, providing experiment dispatch, simulation execution, campaign management, and tooling infrastructure. It is the entry point for running computations programmatically or via HTTP.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.The Hub follows a layered hexagonal architecture:
Hub
├── API — External interface (CLI, HTTP, DTOs)
├── Domain — Shared domain concepts (constants, errors, units)
├── Engine — Computation core (dispatch, experiments, simulations, workers)
├── Tools — Infrastructure (benchmarking, config, logging, metrics)
└── Prelude — Ergonomic re-exports for common usage
The data flow for a computation request:
ComputeRequest → Router → Domain Dispatcher → Scientific Module → ComputeResponse
External interface layer for interacting with SciForge computations.
A minimal TCP-based HTTP server built on std::net::TcpListener (no framework dependencies). The server:
Fn(&str, &str, &str) -> HttpResponsepub struct HttpResponse {
pub status_code: u16,
pub status_text: String,
pub content_type: String, // "application/json" by default
pub body: String,
}
**ComputeRequest** — Structured experiment request:
pub struct ComputeRequest {
pub domain: String, // "physics", "chemistry", etc.
pub function: String, // "projectile_motion", "nernst_potential", etc.
pub params: HashMap<String, ParamValue>,
}
Parameter types: Scalar(f64), Integer(i64), Text(String), Boolean(bool), Array(Vec<f64>). Builder pattern: ComputeRequest::new("physics", "free_fall").with_scalar("height", 100.0).
**ComputeResponse** — Structured computation result:
pub struct ComputeResponse {
pub success: bool,
pub result: Option<ResultData>,
pub error: Option<String>,
pub elapsed_ms: f64,
}
Result variants: Scalar, Pair, Triple, Vector, Matrix, TimeSeries { times, values }, Text, Boolean. Factory methods: ok_scalar(), ok_vector(), ok_time_series(), err().
formatter.rs** — Formats ComputeResponse into different output targets (JSON, plain text, etc.)params.rs** — Parses and validates incoming request parameters with type coercionShared domain concepts used across the Hub.
Strongly typed unit system with enumerations for physical quantities:
| Quantity | Variants |
|---|---|
LengthUnit | Meter, Kilometer, Mile, AU, Parsec, LightYear, ... |
MassUnit | Kilogram, Gram, SolarMass, ElectronMass, AMU, ... |
TimeUnit | Second, Minute, Hour, Day, Year, ... |
TemperatureUnit | Kelvin, Celsius, Fahrenheit |
EnergyUnit | Joule, eV, keV, MeV, Calorie, ... |
PressureUnit | Pascal, Atmosphere, Bar, ... |
AngleUnit | Radian, Degree |
Unified error handling: HubError enum with variants for invalid input, dispatch failures, simulation errors, etc. HubResult<T> = Result<T, HubError>.
The computational core of the Hub.
Routes experiment requests to the correct scientific module. One dispatcher per domain:
| Dispatcher | Module | Description |
|---|---|---|
astronomy.rs | Astronomy | Stellar, orbital, cosmology functions |
biology.rs | Biology | 44 submodules, 176 source files |
chemistry.rs | Chemistry | 26 submodules |
geology.rs | Geology | Dating, petrology, seismology, tectonics |
maths.rs | Mathematics | 17 submodules |
meteorology.rs | Meteorology | Atmosphere, dynamics, precipitation, radiation |
physics.rs | Physics | 11 submodules |
The astronomy dispatcher directly exposes the cosmology stack (for example e_z, e_z_lcdm, e_z_wcdm, hubble_at_z, hubble_at_z_lcdm, comoving_distance_from_z, luminosity_distance_from_z, angular_diameter_distance_from_z, and general/wCDM/CPL distance variants), so redshift-expansion and distance workflows are available through the standard Hub API.
**Parameter extraction** (params.rs) provides typed accessors from the parameter list:
get_f(params, "name") → HubResult<f64> (scalar)get_i(params, "name") → HubResult<i64> (integer)get_u(params, "name") → HubResult<usize> (unsigned)get_c(params, "name") → HubResult<Complex> (complex number)The Experiment struct is a chainable builder for computation requests:
pub enum DomainType { Math, Physics, Chemistry, Biology, Astronomy, Geology, Meteorology }
pub enum ParameterValue {
Scalar(f64), Integer(i64), Vector(Vec<f64>), Matrix(Vec<Vec<f64>>),
Boolean(bool), Text(String), Complex(f64, f64), ComplexVector(Vec<(f64, f64)>),
Polynomial(Vec<f64>), IntVector(Vec<usize>), IntMatrix(Vec<Vec<usize>>),
EdgeList(Vec<(usize, usize, f64)>),
Sparse { rows, cols, row_ptr, col_idx, values },
Tensor { data: Vec<f64>, shape: Vec<usize> },
}
// Usage:
let exp = Experiment::new(DomainType::Physics, "projectile_range")
.param("velocity", ParameterValue::Scalar(50.0))
.param("angle", ParameterValue::Scalar(45.0));
The **Runner** executes experiments and returns typed RunOutput variants.
Time-stepping numerical simulation framework.
**DynamicalSystem trait** — interface for any ODE system:
pub trait DynamicalSystem {
fn dimension(&self) -> usize;
fn derivatives(&self, t: f64, state: &[f64], out: &mut [f64]);
fn initial_state(&self) -> Vec<f64>;
fn time_span(&self) -> (f64, f64);
}
Built-in models:
HarmonicOscillator**: $\ddot{x} = -\omega^2 x$ (2D state: position + velocity)LotkaVolterra**: predator-prey dynamicsSimpleModel**: generic system from a boxed closureThe **Integrator** advances the state forward using numerical methods (Euler, RK4, adaptive RK45). The **Solver** orchestrates the integration loop and collects SimulationResult time series.
Multi-step computation workflows via the Flow module. Allows chaining computations where the output of one step feeds as input to the next.
Concurrent execution infrastructure:
Scheduler** — Priority-based task scheduling with dependency resolution. Tasks have Priority levels (Low, Normal, High, Critical) and dependency lists. The scheduler performs topological sorting with priority ordering.Queue** — Task queue managementExecutor** — Dispatches tasks sequentially or in parallelContext** — Carries execution state, parameters, and result collectionMulti-experiment batch execution. A campaign collects multiple Experiment instances for sequential dispatch and result aggregation. Enables parameter sweeps (varying one parameter across a range) and combinatorial experiment generation.
Infrastructure utilities.
Config** — Key-value configuration store backed by HashMap<String, String>. Typed accessors: get_f64(), get_usize(), get_bool(). Builder: Config::new().set("key", "value").Logger** — Structured logging with severity levels (Debug, Info, Warn, Error). Prefixed output with timestamps for experiment tracing.Metrics** — Runtime metrics collection: execution time, iteration counts, throughput measurements.Benchmark** — Integration point with the Benchmark module for performance profiling of Hub operations.Utils** — General-purpose utility functions.Convenience re-exports for ergonomic API usage:
pub use crate::hub::domain::common::errors::{HubError, HubResult};
pub use crate::hub::domain::common::units::*;
pub use crate::hub::tools::config::Config;
pub use crate::hub::tools::logger::Level;
pub use crate::hub::engine::experience::experiment::{DomainType, Experiment, ParameterValue};
pub use crate::hub::engine::simulation::model::DynamicalSystem;
pub use crate::hub::engine::simulation::result::SimulationResult;
pub use crate::hub::api::dto::request::ComputeRequest;
pub use crate::hub::api::dto::response::ComputeResponse;
Import with use sciforge::hub::prelude::* for immediate access to all Hub types.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The Mathematics module provides 17 submodules across 63 source files, covering core computational mathematics from linear algebra and calculus through graph theory, signal processing, and non-Euclidean geometry.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Arithmetic and analysis on the complex plane, including quaternion extensions for 3D rotation.
Arithmetic — Full complex algebra: addition, subtraction, multiplication, division, conjugation, modulus $|z| = \sqrt{a^2+b^2}$, and argument $\arg(z) = \text{atan2}(b,a)$. Polar form interconversion: $z = r e^{i\theta}$.
Complex Functions — Complex exponential $e^z = e^a(\cos b + i\sin b)$, complex logarithm $\ln z = \ln|z| + i\arg(z)$, and complex polynomial evaluation via Horner's scheme in $\mathbb{C}$.
Fractals — Mandelbrot iteration $z_{n+1} = z_n^2 + c$ (escape-time algorithm with bailout $|z|^2 > 4$), Julia set iteration, and Newton fractal step $z \leftarrow z - f(z)/f'(z)$ for polynomial root basins.
Roots of Unity — The $n$ roots $e^{2\pi i k/n}$ for $k = 0, \ldots, n-1$, essential for FFT twiddle factors and cyclic group generators.
Complex Linear Algebra — Complex matrix multiplication and determinant (Laplace expansion), extending the linear algebra toolbox to $\mathbb{C}^{n \times n}$.
Quaternions — Hamilton's four-dimensional extension $q = w + xi + yj + zk$ with quaternion multiplication, conjugation, norm, and SLERP interpolation for smooth 3D rotations without gimbal lock.
Efficient frequency-domain transforms for spectral analysis, filtering, and convolution.
Radix-2 FFT — Cooley-Tukey recursive butterfly algorithm: the $N$-point DFT $X_k = \sum_{n=0}^{N-1} x_n e^{-2\pi i kn/N}$ is computed in $O(N \log N)$ by splitting into even/odd halves with twiddle factor $W_N^k = e^{-2\pi i k/N}$. Input length must be a power of two; the module pads automatically. Inverse FFT scales by $1/N$.
Bluestein (Chirp-Z) — Extends FFT to arbitrary-length sequences by rewriting the DFT as a convolution: $X_k = W_N^{k^2/2}\sum_n x_n W_N^{n^2/2}\cdot W_N^{-(k-n)^2/2}$, then applying radix-2 FFT on zero-padded sequences.
**DCT** — Discrete Cosine Transform (type-II): $X_k = \sum_{n=0}^{N-1} x_n \cos\!\left[\frac{\pi}{N}\left(n + \tfrac{1}{2}\right)k\right]$, used for signal compression (JPEG, MP3). The module also provides the inverse DCT.
Power Spectrum — $|X_k|^2$ from the FFT output gives the power spectral density. Frequency bin spacing: $\Delta f = f_s/N$ where $f_s$ is the sample rate.
FFT-Based Convolution — Circular convolution via the convolution theorem: $h = \text{IFFT}(\text{FFT}(a) \cdot \text{FFT}(b))$, and cross-correlation by conjugation: $R_{ab} = \text{IFFT}(\overline{A} \cdot B)$.
Classical algorithms on weighted and unweighted graph structures.
Shortest Paths — Dijkstra's algorithm (non-negative weights, $O(V^2)$ without priority queue), Bellman-Ford (handles negative weights, detects negative cycles), Floyd-Warshall (all-pairs, $O(V^3)$), A* (heuristic-guided search with admissible heuristic). Path reconstruction is available for all single-source algorithms.
Network Flow — Ford-Fulkerson maximum flow via augmenting paths, and min-cut extraction from the residual graph.
Spanning Trees — Kruskal's and Prim's algorithms for minimum spanning tree (MST) on weighted graphs.
Traversal — BFS (breadth-first) and DFS (depth-first) traversal with connected component identification, topological sort, and cycle detection.
Numerical computation of definite integrals $\int_a^b f(x)\,dx$.
**Newton-Cotes Rules** — Trapezoidal rule $\int \approx \frac{h}{2}[f(a)+f(b)+2\sum f(x_i)]$ with error $O(h^2)$. Simpson's rule $\int \approx \frac{h}{3}[f(a)+4\sum_\text{odd}+2\sum_\text{even}+f(b)]$ with error $O(h^4)$. Simpson's 3/8 rule and Boole's rule for higher-order accuracy. Midpoint rule.
Romberg Integration — Richardson extrapolation on the trapezoidal rule to build a triangular table of superior approximations, achieving high accuracy without changing quadrature type.
Gaussian Quadrature — Exact for polynomials of degree $\le 2n-1$ using optimal node placement and weight coefficients, via Gauss-Legendre rules.
Adaptive Quadrature — Recursive interval bisection with local error estimation (adaptive Simpson), automatically concentrating effort where the integrand varies rapidly.
Multidimensional — Monte Carlo integration $\int_\Omega f \approx V \cdot \frac{1}{N}\sum f(x_i)$ and cubature methods for integrals over arbitrary domains in $\mathbb{R}^d$.
Constructing smooth approximations through known data points.
Lagrange Interpolation — Polynomial through $n$ points: $P(x) = \sum_{i=0}^{n-1} y_i \prod_{j\neq i}\frac{x-x_j}{x_i-x_j}$. Barycentric form for efficient repeated evaluation without recomputing products.
Cubic Splines — Natural cubic spline: piecewise $S_i(x) = y_i + b_i(x-x_i) + c_i(x-x_i)^2 + d_i(x-x_i)^3$ with $C^2$ continuity throughout. Coefficients determined by a tridiagonal system solved via Thomas algorithm. Integration and differentiation on the spline are also supported.
Other Methods — Linear interpolation, nearest-neighbor, and Newton's divided difference polynomial.
Matrix and vector computations forming the backbone of scientific computing.
Decompositions — LU decomposition (with partial pivoting for numerical stability), QR factorization (Gram-Schmidt), and Cholesky decomposition $A = LL^T$ for symmetric positive-definite matrices. Each decomposition is used to solve $Ax = b$ by back-substitution.
Eigenvalues — Power iteration for the dominant eigenvalue and eigenvector: $v^{(k+1)} = Av^{(k)}/\|Av^{(k)}\|$ with convergence rate proportional to $|\lambda_2/\lambda_1|$. Inverse iteration for eigenvalues near a shift $\sigma$. Rayleigh quotient $\rho = v^TAv/(v^Tv)$ for refined eigenvalue estimates. Gershgorin disks for bounding eigenvalue locations. Spectral radius, trace, and condition number $\kappa = |\lambda_{\max}|/|\lambda_{\min}|$.
Least Squares — Ordinary least squares $\hat{x} = (A^TA)^{-1}A^Tb$ via the normal equations or QR factorization. Weighted least squares, pseudoinverse, and SVD-based rank-deficient solutions.
Curved-space geometry for general relativity, cosmology, and differential geometry.
Metric Tensors — Definition of the metric $g_{\mu\nu}$ in arbitrary coordinates (Schwarzschild, FLRW, Kerr). Line element $ds^2 = g_{\mu\nu}dx^\mu dx^\nu$, metric inverse $g^{\mu\nu}$, metric determinant, and coordinate transformations.
Christoffel Symbols — Numerical computation $\Gamma^\sigma_{\mu\nu} = \frac{1}{2}g^{\sigma\rho}(\partial_\mu g_{\nu\rho} + \partial_\nu g_{\rho\mu} - \partial_\rho g_{\mu\nu})$ via finite differences at configurable step size.
Geodesics — Integration of the geodesic equation $\frac{d^2x^\sigma}{d\tau^2} + \Gamma^\sigma_{\mu\nu}\frac{dx^\mu}{d\tau}\frac{dx^\nu}{d\tau} = 0$ using a symplectic (leapfrog) integrator. Full trajectory output for visualization of light bending, orbital precession, etc.
Curvature — Ricci scalar, Gaussian curvature of 2-surfaces, and Riemann tensor components for measuring manifold curvature.
Black Holes — Schwarzschild metric solutions: photon sphere at $r = 3M$, innermost stable circular orbit (ISCO) at $r = 6M$, and gravitational redshift $z = (1-r_s/r)^{-1/2} - 1$.
Numerical solvers for initial and boundary value problems $y' = f(t, y)$.
Euler Method — First-order explicit: $y_{n+1} = y_n + h\,f(t_n, y_n)$. Simple but with $O(h)$ global error; serves as a baseline.
Runge-Kutta 4 — The classical fourth-order method: $y_{n+1} = y_n + \frac{h}{6}(k_1 + 2k_2 + 2k_3 + k_4)$ with four function evaluations per step and $O(h^4)$ global error.
Adaptive Methods — Runge-Kutta-Fehlberg (RK45) with embedded error estimation for automatic step-size control, maintaining a target local error tolerance.
Systems — All solvers accept vector-valued ODEs $\vec{y}' = \vec{f}(t,\vec{y})$ for coupled systems (e.g., Lotka-Volterra, orbital mechanics, coupled oscillators).
Boundary Value Problems — Shooting method: convert a BVP into an IVP by guessing initial conditions and iterating (bisection or Newton) until boundary conditions are satisfied.
Algorithms for minimizing (or maximizing) objective functions.
Gradient Descent — $x_{k+1} = x_k - \alpha\nabla f(x_k)$ with fixed or line-search learning rate. Momentum variant $v_{k+1} = \beta v_k - \alpha\nabla f$, $x_{k+1} = x_k + v_{k+1}$ for faster convergence through ravines.
Adam Optimizer — Adaptive moment estimation: bias-corrected first ($\hat{m}$) and second ($\hat{v}$) moment estimates with update $x \leftarrow x - \alpha\hat{m}/(\sqrt{\hat{v}}+\varepsilon)$. Default $\beta_1 = 0.9$, $\beta_2 = 0.999$.
Newton's Method — Second-order: $x_{k+1} = x_k - f(x_k)/f'(x_k)$ for root-finding (1D); quadratic convergence near the root.
Constrained — Penalty methods and Lagrange multiplier approach for constrained optimization.
Evolutionary — Genetic algorithms (selection, crossover, mutation) and differential evolution for global optimization over non-smooth landscapes.
Metaheuristic — Simulated annealing (acceptance probability $e^{-\Delta E/T}$) and particle swarm optimization.
Numerical solvers for diffusion, wave propagation, and potential problems on grids.
Heat/Diffusion Equation — $\partial T/\partial t = \alpha\nabla^2 T$ solved by three finite-difference schemes: explicit (forward-time central-space, CFL $r = \alpha\Delta t/\Delta x^2 \le 1/2$), implicit (backward Euler, unconditionally stable via Thomas tridiagonal solve), and Crank-Nicolson (second-order in time, average of explicit and implicit operators). 2D extension available.
**Wave Equation** — $\partial^2 u/\partial t^2 = c^2\nabla^2 u$ solved by central-difference leapfrog in 1D and 2D. D'Alembert analytical solution $u = \frac{1}{2}[f(x-ct)+f(x+ct)]$ for validation. Courant number $C = c\Delta t/\Delta x \le 1$ for stability. Energy density and absorbing boundary conditions.
Laplace/Poisson — $\nabla^2\phi = \rho$ solved by Jacobi and Gauss-Seidel iterative relaxation on a grid, with configurable tolerance and boundary conditions.
Polynomial algebra and numerical root-finding.
Polynomial Struct — Evaluation (Horner's method), addition, multiplication, differentiation, and integration of polynomials with real coefficients.
Root-Finding — Newton-Raphson $x_{n+1} = x_n - f(x_n)/f'(x_n)$ (quadratic convergence), bisection (robust, linear convergence), secant method (superlinear, no derivative needed), and Brent's method (combining bisection, secant, and inverse quadratic interpolation for guaranteed convergence).
Special Polynomials — Legendre $P_n(x)$, Chebyshev $T_n(x) = \cos(n\arccos x)$, Hermite $H_n(x)$, and Laguerre $L_n(x)$ — orthogonal polynomial families used in quadrature, approximation theory, and quantum mechanics.
Distributions, stochastic processes, and simulation.
Distributions — PDF, CDF, and quantiles for: Uniform, Normal $f(x) = \frac{1}{\sigma\sqrt{2\pi}}e^{-z^2/2}$, Exponential $f(x) = \lambda e^{-\lambda x}$, Poisson $P(k) = e^{-\lambda}\lambda^k/k!$, Binomial $\binom{n}{k}p^k(1-p)^{n-k}$, Geometric, Gamma, Beta, Cauchy, Chi-squared, Student's $t$, and $F$-distribution.
Markov Chains — Transition matrix representation, $n$-step transition $P^n$, stationary distribution $\pi P = \pi$ (eigenvector method), and absorbing chain analysis.
Monte Carlo — Random sampling, Monte Carlo integration, and variance reduction techniques (importance sampling, stratification).
Sampling — Inverse transform sampling, rejection sampling, and Box-Muller transform for normal variates.
Time-series analysis, filtering, and spectral methods.
Filters — RC low-pass $y_n = \alpha x_n + (1-\alpha)y_{n-1}$ with $\alpha = \Delta t/(RC+\Delta t)$ and RC high-pass $y_n = \alpha(y_{n-1}+x_n-x_{n-1})$. Moving average (simple and exponential EMA). Median filter for impulse noise removal.
**Convolution** — Discrete linear convolution $(f*g)[n] = \sum_k f[k]\,g[n-k]$ both directly and via FFT for $O(N\log N)$ performance. Cross-correlation for lag detection.
Spectral Analysis — Power spectral density estimation, periodogram, Welch's method, and spectral peak detection.
Wavelets — Discrete wavelet transform (Haar, Daubechies), multiresolution analysis, and wavelet decomposition/reconstruction for time-frequency localization.
Memory-efficient representation and operations for large matrices with mostly zero entries.
**CSR Format** — Compressed Sparse Row: storage via three arrays (row_ptr, col_idx, values). Construction from triplet lists $(i,j,v)$, identity matrix, random sparse generation. Element access $O(\text{nnz per row})$.
Operations — Sparse matrix-vector product $y = Ax$ in $O(\text{nnz})$, sparse-sparse addition, transposition, and Frobenius norm.
Iterative Solvers — Conjugate gradient method for symmetric positive-definite sparse systems: convergence in at most $n$ iterations for exact arithmetic, with practical convergence rate determined by the condition number. GMRES and Jacobi iteration for non-symmetric systems.
Descriptive analysis, hypothesis testing, and regression.
Descriptive — Mean, median, mode, variance (sample and population), standard deviation, skewness, kurtosis, percentiles, and interquartile range.
Hypothesis Testing — One-sample and two-sample $t$-tests, paired $t$-test, chi-squared goodness-of-fit and independence tests, $p$-value computation, and confidence interval construction.
Regression — Simple linear regression $y = \beta_0 + \beta_1 x$ via $\beta_1 = \frac{n\sum xy - \sum x\sum y}{n\sum x^2 - (\sum x)^2}$. Multiple linear regression, polynomial regression, coefficient of determination $R^2 = 1 - \text{SS}_\text{res}/\text{SS}_\text{tot}$, standard error of estimate, and residual analysis.
Multi-dimensional array algebra for physics and machine learning.
**Storage** — Row-major contiguous storage with shape and stride arrays. Construction from nested data, functional initialization (from_fn), zeros, ones, and random tensors. Arbitrary rank support.
Operations — Element-wise arithmetic, scalar operations, broadcasting, reshaping, slicing, and transposition via axis permutation.
Contraction — Generalized tensor contraction $C_{i\ldots k\ldots} = \sum_m A_{i\ldots m\ldots}\,B_{k\ldots m\ldots}$ along specified axes — the foundation for matrix multiplication, inner products, and Einstein summation.
Decomposition — CP (CANDECOMP/PARAFAC) and Tucker decomposition for low-rank tensor approximation.
Differential operators and integral calculus on vector fields in $\mathbb{R}^3$.
Vec3 Type — Three-dimensional vectors with dot product $\vec{a}\cdot\vec{b} = \sum a_ib_i$, cross product $\vec{a}\times\vec{b}$, magnitude, normalization, and scalar multiplication.
Operations — Linear interpolation (lerp), spherical linear interpolation (slerp) for smooth direction transitions, projection $\text{proj}_{\vec{b}}\vec{a} = \frac{\vec{a}\cdot\vec{b}}{\vec{b}\cdot\vec{b}}\vec{b}$, rejection, reflection $\vec{v} - 2(\vec{v}\cdot\hat{n})\hat{n}$, angle between vectors, scalar triple product $\vec{a}\cdot(\vec{b}\times\vec{c})$ (parallelepiped volume), and vector triple product.
Differential Operators — Numerical gradient $\nabla f$, divergence $\nabla\cdot\vec{F}$, curl $\nabla\times\vec{F}$, and Laplacian $\nabla^2 f$ on 3D vector fields via central differences.
Integration — Line integrals along parameterized curves, surface integrals, and flux computation $\iint \vec{F}\cdot d\vec{A}$.
Simulation — Vector field flow visualization, streamline tracing, and field evolution.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The Meteorology module spans 4 submodules covering atmospheric science: thermodynamics and composition, radiative transfer, atmospheric dynamics, and precipitation hydrology. It provides computational tools for weather analysis, climate modeling, and hydrological engineering.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Vertical structure, thermodynamics, and moisture physics of the troposphere and stratosphere.
Barometric Formula — Pressure decreases exponentially with altitude: $P(h) = P_0\exp\!\left(-\frac{Mgh}{R^*T}\right)$ where $M$ is the mean molar mass of air, $g$ is gravity, and $R^* = 8.314\;\text{J mol}^{-1}\text{K}^{-1}$. The atmospheric scale height $H = R^*T/(Mg) \approx 8.5\;\text{km}$ is the e-folding length for pressure.
Lapse Rates — The dry adiabatic lapse rate $\Gamma_d = g/c_p \approx 9.8\;\text{K/km}$ applies to unsaturated air. The moist (saturated) adiabatic lapse rate is lower because latent heat release partially offsets cooling:
$$\Gamma_m = g\,\frac{1 + L_v r_s/(R_d T)}{1 + L_v^2 r_s/(c_p R_v T^2)}$$
where $L_v$ is the latent heat of vaporization, $r_s$ the saturation mixing ratio, $R_d$ and $R_v$ the gas constants for dry air and water vapor.
Potential Temperature — $\theta = T\left(\frac{P_0}{P}\right)^{R_d/c_p}$ is conserved for adiabatic displacements and serves as the natural vertical coordinate for stability analysis.
Virtual Temperature — $T_v = T(1 + 0.608\,r)$ accounts for the reduced density of moist air, where $r$ is the mixing ratio.
Moisture Variables — Mixing ratio $r = 0.622\,e/(P-e)$, saturation vapor pressure (Magnus formula) $e_s = 6.112\exp(17.67\,T_C/(T_C+243.5))$ hPa, relative humidity $\text{RH} = e/e_s \times 100\%$, and dew point from the inverse Magnus equation.
Density Altitude — Corrects pressure altitude for non-standard temperature: $h_\rho = h_P + 120(T - T_{\text{ISA}})$, critical for aviation performance.
Brunt-Väisälä Frequency — $N = \sqrt{(g/\theta)\,d\theta/dz}$ measures the static stability of the atmosphere. $N^2 > 0$ → stable (oscillatory); $N^2 < 0$ → unstable (convective).
Large-scale atmospheric motion governed by the balance between pressure gradient, Coriolis, and inertial forces.
Coriolis Parameter — $f = 2\Omega\sin\phi$ where $\Omega = 7.292 \times 10^{-5}\;\text{rad/s}$ and $\phi$ is the latitude. $f = 0$ at the equator and maximal at the poles.
Geostrophic Wind — In the free atmosphere where friction is negligible, the pressure gradient is balanced by the Coriolis force:
$$u_g = -\frac{1}{\rho f}\frac{\partial P}{\partial y}, \qquad v_g = \frac{1}{\rho f}\frac{\partial P}{\partial x}$$
The wind blows parallel to isobars with low pressure to the left (Northern Hemisphere).
Rossby Number — $Ro = U/(fL)$ compares inertial to Coriolis accelerations. $Ro \ll 1$ → quasi-geostrophic regime (synoptic scale); $Ro \sim 1$ → mesoscale (tornadoes, sea breezes).
Rossby Waves — Planetary-scale waves with phase speed $c = -\beta/k^2$ where $\beta = df/dy$ is the meridional gradient of Coriolis. These waves control teleconnection patterns and jet-stream meanders.
Thermal Wind — Vertical shear of the geostrophic wind due to horizontal temperature gradients: $\frac{\partial \vec{v}_g}{\partial \ln p} = \frac{R_d}{f}\hat{k} \times \nabla_p T$. This links upper-level jet streams to surface temperature contrasts.
Potential Vorticity — Ertel's PV $q = -g\,f\,\partial\theta/\partial p$ is conserved for adiabatic, frictionless flow — a powerful diagnostic for tropopause dynamics and stratospheric intrusions.
Ekman Layer — Friction-influenced boundary layer of depth $D_E = \pi\sqrt{2\nu/|f|}$, within which winds cross isobars toward low pressure (surface convergence in cyclones).
Richardson Number — $Ri = N^2/(du/dz)^2$ balances buoyancy suppression against shear production of turbulence. $Ri < 0.25$ → onset of Kelvin-Helmholtz instability and turbulent mixing.
Rossby Deformation Radius — $L_R = NH/|f|$ is the horizontal scale at which rotation becomes as important as buoyancy, controlling the width of fronts and the size of baroclinic eddies.
Gradient Wind — Curved-flow solution including centrifugal acceleration: $V = -\frac{fR}{2} + \sqrt{\frac{f^2R^2}{4} + \frac{R}{\rho}\frac{\partial P}{\partial r}}$, applicable to tightly curved cyclones and anticyclones.
Rainfall characterization, evapotranspiration, and surface hydrology.
Marshall-Palmer Distribution — Radar reflectivity $Z$ to rain rate $R$ conversion: $Z = 200\,R^{1.6}$ (mm⁶/m³) or equivalently $R = (Z/200)^{1/1.6}$ mm/h. An empirical relation foundational to weather radar operations.
Raindrop Terminal Velocity — $v_t = 9.65 - 10.3\,e^{-0.6D}$ m/s where $D$ is the drop diameter in mm, capturing the transition from Stokes drag (small drops) to turbulent drag (large drops).
Thornthwaite PET — Monthly potential evapotranspiration from temperature alone: $\text{PET} = 16\,(N/12)(10T/I)^a$ mm/month, where $I$ is the annual heat index and $a$ a polynomial function of $I$.
Penman Equation — Combines energy balance and aerodynamic mass transfer: $E = \frac{\Delta\,R_n + \gamma\,f(u)\,e_a}{\Delta + \gamma}$ where $\Delta$ is the slope of the saturation vapor pressure curve, $\gamma$ the psychrometric constant, $R_n$ the net radiation, and $f(u)$ a wind function.
Intensity-Duration-Frequency (IDF) — Engineering design curves: $i = \frac{a\ln T_r}{t_d + b}$ where $T_r$ is the return period (years) and $t_d$ the storm duration. Used for storm sewer, culvert, and dam design.
SCS Curve Number — USDA runoff model: $Q = (P - I_a)^2/(P - I_a + S)$ where $S = 25400/CN - 254$ mm is the potential maximum retention and $I_a = 0.2S$ is the initial abstraction. $CN$ ranges from 30 (permeable forest) to 98 (impervious surface).
Rational Method — Peak runoff $Q_p = CiA$ for small catchments ($< 80$ ha), where $C$ is the runoff coefficient, $i$ the rainfall intensity for the time of concentration, and $A$ the drainage area.
Unit Hydrograph — Peak discharge $Q_p = 2.08\,A/t_p$ (SCS triangular approximation) where $A$ is the basin area (km²) and $t_p$ the time to peak (hours).
Antecedent Precipitation Index — $\text{API}_n = k \cdot \text{API}_{n-1} + P_n$ with decay factor $k \approx 0.85$–$0.95$, tracking soil moisture from recent rainfall history.
Solar and terrestrial radiation budgets governing Earth's energy balance and climate.
Stefan-Boltzmann Law — Total radiative flux from a surface: $F = \sigma T^4$ where $\sigma = 5.67 \times 10^{-8}\;\text{W m}^{-2}\text{K}^{-4}$. For a non-blackbody: $F = \varepsilon\sigma T^4$ (emissivity $0 < \varepsilon \le 1$).
Solar Constant — Total solar irradiance at the top of the atmosphere: $S_0 = 1361\;\text{W/m}^2$ (mean Earth-Sun distance).
Planetary Energy Balance — Absorbed solar radiation balances outgoing longwave: $\frac{S_0(1-\alpha)}{4} = \sigma T_e^4$, giving the effective temperature $T_e = \left(\frac{S_0(1-\alpha)}{4\sigma}\right)^{1/4} \approx 255\;\text{K}$ for Earth ($\alpha \approx 0.3$).
Greenhouse Effect — The difference $\Delta T = T_s - T_e$ between the actual surface temperature ($T_s \approx 288\;\text{K}$) and the effective radiating temperature quantifies the warming by greenhouse gases ($\Delta T \approx 33\;\text{K}$).
Beer-Lambert Atmospheric Extinction — $I = I_0\,e^{-\tau}$ where the optical depth $\tau = \kappa\,\ell$ is the product of absorption/scattering coefficient and path length. Governs visibility, solar dimming, and radiative transfer through clouds.
Planck Function — Spectral radiance of a blackbody:
$$B(\lambda, T) = \frac{C_1}{\lambda^5\left(\exp\!\left(\frac{C_2}{\lambda T}\right) - 1\right)}$$
with $C_1 = 3.742 \times 10^{-16}\;\text{W m}^2$ and $C_2 = 1.4388 \times 10^{-2}\;\text{m K}$. The peak wavelength follows Wien's law $\lambda_{\max} = 2898/T$ µm.
Solar Zenith Angle — $\cos\theta_z = \sin\phi\sin\delta + \cos\phi\cos\delta\cos h$ where $\phi$ is latitude, $\delta$ the solar declination, and $h$ the hour angle. Controls the diurnal and seasonal variation of insolation.
CO₂ Radiative Forcing — The logarithmic dependence $\Delta F = 5.35\ln(C/C_0)\;\text{W/m}^2$ gives the additional downward infrared forcing from a change in atmospheric CO₂ concentration. The climate sensitivity parameter $\lambda = \Delta T/\Delta F$ (K per W/m²) links forcing to equilibrium temperature response.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The parser module provides 5 complete format parsers, each built from scratch with zero dependencies. Every parser follows a consistent three-stage architecture: lexer → parser → typed value tree. This module enables SciForge to read and write structured data in all common scientific exchange formats.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Each format implementation follows an identical layered pattern across 4–5 source files:
| Layer | File | Role |
|---|---|---|
| Lexer | lexer.rs | Byte-level cursor over `&[u8]` input. Advances through raw bytes, tracks position, handles whitespace skipping and token boundary detection. |
| Parser | parser.rs | Recursive-descent parser consuming tokens from the lexer to build a typed value tree. |
| Value | value.rs | Enum representing parsed data nodes (strings, numbers, booleans, containers). All values borrow from the input (&'a str) — zero-copy where possible. |
| Error | error.rs | Format-specific error type with byte position and error kind for precise diagnostics. |
Shared design principles:
'a. String values are &'a str referencing the original bytes, avoiding heap copies.Cursor<'a> (or LineCursor<'a> for line-oriented formats) with peek(), advance(n), is_eof(), and position() methods.const fn accessors** — type-checking methods (is_object(), as_str(), as_number()) are const fn for compile-time usability.Comma-separated values for tabular scientific data.
Value types:
enum CsvValue<'a> {
Table, // Root document node
Record, // One row
Field(&'a str), // One cell (zero-copy reference)
}
The lexer operates on raw bytes with a simple Cursor tracking position. Fields are delimited by commas; records by newlines. Quoted fields (RFC 4180) handle embedded commas, newlines, and escaped double-quotes.
Writer. The CSV writer module generates properly escaped output from structured data — quoting fields that contain delimiters, quotes, or line breaks.
JavaScript Object Notation — full RFC 8259 compliance.
Value types:
enum JsonValue<'a> {
Null,
Bool(bool),
Number(f64),
String(&'a str),
Array, // Container node
Object, // Container node
}
The parser handles:
number.rs): integers, floats, and scientific notation (1.23e-4), parsed via a dedicated module that handles all edge cases.string.rs): full Unicode escape sequences (\uXXXX, including surrogate pairs for supplementary plane characters), plus standard escapes (\n, \t, \\, \", etc.).Error reporting includes byte offset for precise Location of syntax errors.
YAML Ain't Markup Language — indentation-based human-readable format.
Value types:
enum YamlValue<'a> {
Null,
Bool(bool),
Number(f64),
String(&'a str),
Sequence, // Array/list container
Mapping, // Key-value container
}
The YAML lexer uses a **line-oriented cursor** (LineCursor) that tracks both byte position and indentation level. Each YamlLine carries indent, content, and offset.
**Scalar parsing** (scalar.rs): determines the type of an unquoted scalar:
"null", "~" → Null"true", "false" → BoolNumber(f64)StringThe YAML parser is used internally by the constants module to load all 118 periodic table element files at compile time.
HyperText Markup Language parsing for document generation and analysis.
Value types:
enum HtmlValue<'a> {
Document, // Root node
Element, // HTML tag
Text(&'a str), // Text content
Comment, // <!-- ... -->
Doctype, // <!DOCTYPE ...>
}
**Entity decoding** (entity.rs): handles both named entities (& → &, < → <, > → >, " → ", etc.) and numeric character references ({, {).
The lexer tracks open/close tags, self-closing tags, and attributes. Used by the benchmark export module to generate self-contained HTML dashboards.
Lightweight markup parsing for documentation and report generation.
Value types:
enum MdValue<'a> {
Document, // Root node
Heading(u8), // h1–h6, level stored as u8
Paragraph,
CodeBlock, // Fenced (```) or indented
ThematicBreak, // --- or ***
BlockQuote, // > prefixed blocks
List, // Ordered or unordered
Table, // GFM-style tables
Text(&'a str), // Inline text content
}
**Inline processing** (`inline.rs`): parses bold (`**`), italic (`*`), inline code (`` ` ``), links (`text`), and other inline formatting.
The Markdown lexer uses a LineCursor similar to YAML, processing input line-by-line with indent tracking. Headings are detected by leading # characters (1–6 levels). Fenced code blocks delimit by triple backticks.
Used by the benchmark report module to generate Markdown summaries, and can parse SciForge's own documentation files for programmatic analysis.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
The Physics module of SciForge covers a broad spectrum of classical and modern physics, organized into 11 submodules and 45 source files. It provides computational tools for fundamental laws, field equations, wave phenomena, materials science, and quantum mechanics.
This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.
docs/code/.This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.
docs/code/.Acoustics studies the propagation of mechanical waves through material media (gases, liquids, solids). SciForge models this domain along four axes:
Propagation — Sound waves are pressure perturbations that travel at a speed dependent on the medium: $c = \sqrt{\gamma R T / M}$ in an ideal gas, $c = \sqrt{E/\rho}$ in a solid. The module computes acoustic impedance $Z = \rho c$, transmission and reflection coefficients at interfaces (analogous to Fresnel coefficients in optics), attenuation by geometric divergence (inverse-square law for spherical waves), and sound pressure level in dB SPL.
Doppler Effect — When a source and observer are in relative motion, the perceived frequency shifts according to $f' = f_0 \frac{c + v_\text{obs}}{c + v_\text{src}}$. The module implements the classical cases (approaching/receding source), the relativistic Doppler $f' = f_0 \sqrt{(1+\beta)/(1-\beta)}$, radar Doppler (round-trip: factor of 2), and the Mach cone angle $\theta = \arcsin(c/v)$ for supersonic objects.
Absorption — Sound energy is absorbed exponentially: $I(x) = I_0 e^{-\alpha x}$. The module computes atmospheric absorption (dependent on frequency, humidity, and temperature), A-weighting (standardized psychoacoustic filter), NRC (Noise Reduction Coefficient), transmission loss (mass law), dB level addition, and room constant.
Resonance — Acoustic systems resonate at discrete frequencies. The module calculates the fundamental frequency of a vibrating string $f_1 = \frac{1}{2L}\sqrt{T/\mu}$, harmonics of open and closed pipes, the Helmholtz resonator $f = \frac{c}{2\pi}\sqrt{A/(Vl)}$, beats, quality factor, Sabine reverberation time ($T_{60} = 0.161 V/A$), room eigenmodes for a rectangular enclosure, and Schroeder frequency.
Classical electrodynamics, grounded in Maxwell's equations, describes the interaction between electric and magnetic fields. SciForge structures this domain across three files:
Fields — The electric field of a point charge follows Coulomb's law: $\vec{E} = \frac{kq}{r^2}\hat{r}$, with $k = 1/(4\pi\epsilon_0)$. The module computes electric potential, the magnetic field of an infinite wire (Ampère's theorem: $B = \mu_0 I / 2\pi r$), of a solenoid ($B = \mu_0 n I$), of a current loop, and the Biot-Savart field for an arbitrary segment $d\vec{B} = \frac{\mu_0 I}{4\pi} \frac{d\vec{l} \times \hat{r}}{r^2}$. The Lorentz force $\vec{F} = q(\vec{E} + \vec{v}\times\vec{B})$ unifies electric and magnetic effects. The Poynting vector $\vec{S} = \frac{1}{\mu_0}\vec{E}\times\vec{B}$ gives the electromagnetic energy flux, and the energy density combines contributions: $u = \frac{1}{2}(\epsilon_0 E^2 + B^2/\mu_0)$.
EM Waves — Wave solutions of Maxwell's equations propagate at $c = 1/\sqrt{\mu_0\epsilon_0}$. The module computes the impedance of free space $Z_0 = \sqrt{\mu_0/\epsilon_0} \approx 377\,\Omega$, wave number, wavelength, phase velocity in a medium $v = c/\sqrt{\epsilon_r\mu_r}$, group velocity in a dispersive medium, skin depth (penetration into conductors), Fresnel coefficients $r_s$ and $r_p$, Brewster's angle, critical angle for total internal reflection, Snell's law, radiation pressure (absorbed $P=I/c$ and reflected $P=2I/c$), Larmor power (radiation from an accelerated charge), radiation resistance of a dipole, and a 1D FDTD (Finite-Difference Time-Domain) solver for direct simulation of wave propagation.
Circuits — The series RLC circuit is modeled as a complete structure: resonant frequency $f_0 = 1/(2\pi\sqrt{LC})$, quality factor $Q = (1/R)\sqrt{L/C}$, complex impedance $Z(\omega) = R + j(\omega L - 1/\omega C)$, damping coefficient, bandwidth, and transient response (underdamped, overdamped, critically damped). The module also provides RC and RL time constants and AC regime analysis.
Applied electronics uses the laws of physics to design practical circuits. SciForge covers four sub-areas:
Circuits — Fundamental laws: Ohm's law ($V = IR$), resistors in series/parallel, voltage and current dividers, DC power, RC and RL charge/discharge (exponentials), RLC circuit (resonance, Q factor, bandwidth), capacitive and inductive impedance, stored energy $E = \frac{1}{2}CV^2$ and $\frac{1}{2}LI^2$, Wheatstone bridge, Thévenin/Norton theorems, and maximum power transfer.
Amplifiers — Inverting amplifier gain ($-R_f/R_{in}$), non-inverting ($1 + R_f/R_{in}$), differential, summing. Op-amp integrator and differentiator. Gain-bandwidth product. Common-emitter gain, transconductance $g_m = I_C/V_T$, thermal voltage $V_T = k_B T/q \approx 26\,\text{mV}$ at 300 K. Conversion to dB (voltage and power), cascade gain, noise figure, and Friis formula for cascaded stages.
Semiconductor Devices — Shockley diode equation $I = I_s(e^{V/nV_T} - 1)$, Zener regulator, bipolar transistor ($I_C = \beta I_B$, $\alpha$ factor), MOSFET in saturation and linear regimes, body effect, solar cell (I-V model), LED (current-limiting resistor calculation), photodiode, tunnel diode, PN junction capacitance, Early effect, and DIBL (Drain-Induced Barrier Lowering).
Digital Logic — Fundamental gates (AND, OR, NOT, NAND, NOR, XOR, XNOR), half/full adder, ripple-carry adder, multiplexer, demultiplexer, decoder/encoder, SR/D/JK flip-flops, and binary↔Gray code conversion.
Fluid mechanics describes the behavior of liquids and gases in motion. SciForge organizes this domain across four files:
Flow — Reynolds number $Re = \rho v D / \mu$ (laminar/turbulent transition), Bernoulli equation $P + \frac{1}{2}\rho v^2 + \rho g h = \text{const}$, Poiseuille flow in a pipe (parabolic profile, flow rate $Q = \pi \Delta P r^4 / 8\mu L$), Mach number, drag coefficient, drag force $F_D = \frac{1}{2}\rho v^2 C_D A$, lift (coefficient $C_L$), Froude number, Weber number, mass flow rate, and terminal velocity.
Boundary Layer — Laminar boundary layer thickness on a flat plate (Blasius solution $\delta \propto \sqrt{x/Re_x}$), local and global friction coefficients, laminar-to-turbulent transition, turbulent boundary layer thickness ($\delta \propto x \cdot Re_x^{-1/5}$), displacement thickness, momentum thickness, Nusselt number ($Nu = 0.332\sqrt{Re}\cdot Pr^{1/3}$ for laminar plate), and Stanton number.
Turbulence — Turbulence modeling via Kolmogorov scales: length scale $\eta = (\nu^3/\epsilon)^{1/4}$, time scale $\tau = (\nu/\epsilon)^{1/2}$, velocity scale $v = (\nu\epsilon)^{1/4}$. Turbulent kinetic energy $k = \frac{1}{2}(u'^2 + v'^2 + w'^2)$. Taylor microscale, integral scale, friction velocity $u_\tau = \sqrt{\tau_w/\rho}$, law of the wall (viscous sublayer, buffer, logarithmic), mixing length, turbulent viscosity, turbulence intensity, and Kolmogorov energy spectrum $E(k) \propto \epsilon^{2/3} k^{-5/3}$.
Fluid Waves — Surface waves: dispersion relation $\omega^2 = gk\tanh(kh)$, phase and group velocity, significant wave height, period, power per unit wave front. Deep-water approximation ($c = \sqrt{g/k}$) and shallow-water approximation ($c = \sqrt{gh}$). Ursell number (nonlinearity), Stokes wave, and solitary wave.
This submodule deals with physical properties of condensed matter, at the intersection of physics and engineering.
Crystallography — Bragg's law $n\lambda = 2d\sin\theta$ for X-ray diffraction, interplanar spacings in cubic systems $d = a/\sqrt{h^2+k^2+l^2}$, planar density, packing fractions (BCC: $\pi\sqrt{3}/8 \approx 0.68$, FCC: $\pi\sqrt{2}/6 \approx 0.74$), structure factor (BCC/FCC extinction rules), lattice parameter from density, Debye temperature, Debye specific heat, and vacancy concentration $c_v = e^{-E_v/k_BT}$.
Diffusion — Fick's first law $J = -D \nabla c$ (steady state) and second law $\partial c/\partial t = D \nabla^2 c$ (transient, error-function solution). Arrhenius diffusion coefficient $D = D_0 e^{-Q/RT}$, diffusion length $\sqrt{2Dt}$, interdiffusion coefficient, Kirkendall effect (vacancy flux), grain-boundary diffusion, permeability, carburization depth, and mean free path.
Phases — Gibbs phase rule $F = C - P + 2$ (degrees of freedom), lever rule for phase diagrams, Clausius-Clapeyron slope $dP/dT = \Delta H / (T \Delta V)$, Gibbs free energy of mixing (regular solution), spinodal temperature, nucleation barrier $\Delta G^* = 16\pi\gamma^3/(3\Delta G_v^2)$, critical nucleus radius, nucleation rate, coarsening kinetics (LSW theory), JMAK transformation (Johnson-Mehl-Avrami-Kolmogorov $f = 1 - e^{-kt^n}$), partition coefficient, and Scheil equation for non-equilibrium solidification.
Semiconductors — Fermi energy, Fermi-Dirac distribution, intrinsic carrier concentration $n_i = \sqrt{N_c N_v} e^{-E_g/2k_BT}$, conductivity $\sigma = q(n\mu_e + p\mu_h)$, Hall coefficient, drift velocity, depletion width, built-in potential, diode current, bandgap variation with temperature (Varshni model), and dopant ionization.
Nucleosynthesis deals with the formation of atomic nuclei, primarily inside stars. This submodule is one of the richest in the Physics module.
Nuclides — Liquid-drop model (Bethe-Weizsäcker semi-empirical mass formula): $B = a_V A - a_S A^{2/3} - a_C Z(Z-1)/A^{1/3} - a_A(N-Z)^2/A \pm \delta$, with volume, surface, Coulomb, asymmetry, and pairing terms. Nuclear radius $R = r_0 A^{1/3}$, binding energy per nucleon, atomic mass, and nuclear stability.
Decay — Exponential decay law $N(t) = N_0 \cdot 2^{-t/t_{1/2}}$, decay constant $\lambda = \ln 2 / t_{1/2}$, activity in Bq and Ci, mean lifetime, decay chains (Bateman equations for radioactive series), secular and transient equilibrium, branching ratio, Geiger-Nuttall law for alpha decay, and Q-value calculation.
Nuclear Reactions — Reaction Q-value (mass balance), Coulomb barrier $E_C = 1.44 Z_1 Z_2 / (r_0(A_1^{1/3}+A_2^{1/3}))$ MeV, Gamow peak $E_0 = (E_G k_B^2 T^2/4)^{1/3}$ (most probable energy for thermonuclear reactions), Gamow window, reduced mass, astrophysical S-factor, Sommerfeld parameter, barrier penetration factor, thermonuclear rate (integrating over Maxwell-Boltzmann distribution × cross-section), estimates for pp, triple-alpha, and $^{12}$C($\alpha$,$\gamma$) rates, and reaction mean free path.
Stellar Processes — Complete classification of processes: pp chain (4 H → He, 26.7 MeV, $T > 4 \times 10^6$ K), CNO cycle (same product, catalyzed by C/N/O, $T > 15 \times 10^6$ K), triple-alpha (3 He → C, $T > 10^8$ K), carbon burning, neon burning, oxygen burning, silicon burning, and slow (s) and rapid (r) neutron-capture processes for synthesis of heavy elements beyond iron. Each process includes its threshold temperature and energy released.
**Stellar Physics** — StellarCore structure: luminosity ($L \propto M^{3.5}$), main-sequence lifetime ($\tau \propto M^{-2.5} \times 10^{10}$ years), dominant processes as a function of core temperature, temporal evolution (hydrogen consumption → helium → metals). Chandrasekhar limit (1.4 $M_\odot$), Tolman-Oppenheimer-Volkoff limit (~2.17 $M_\odot$), Eddington luminosity, maximum binding energy at the iron peak.
Optics describes the behavior of light, viewed as an electromagnetic wave in the visible range and beyond.
Refraction — Snell's law $n_1 \sin\theta_1 = n_2 \sin\theta_2$, critical angle $\theta_c = \arcsin(n_2/n_1)$ for total internal reflection, Brewster's angle $\theta_B = \arctan(n_2/n_1)$, Fresnel reflectance coefficients (s and p polarizations), thin-lens equation $1/f = 1/d_o + 1/d_i$, magnification, lensmaker's equation, numerical aperture, optical path length, Cauchy dispersion $n(\lambda) = A + B/\lambda^2$, and Abbe number.
Diffraction — Single-slit intensity (sinc²: $I = (\sin\beta/\beta)^2$), double-slit (interference term $\cos^2$), grating maxima ($d\sin\theta = m\lambda$), resolving power ($R = mN$), Rayleigh criterion $\theta = 1.22\lambda/D$, Airy disk radius, Fraunhofer distance, grating dispersion, Bragg condition, and first zero of a circular aperture.
Interference — Resultant intensity of two beams $I = I_1 + I_2 + 2\sqrt{I_1 I_2}\cos\delta$, thin-film phase shift, constructive condition, fringe spacing $\Delta y = \lambda L / d$, fringe visibility, coherence length and time, Fabry-Pérot transmittance (Airy function), finesse $\mathcal{F} = \pi\sqrt{R}/(1-R)$, free spectral range, Michelson path difference, and Newton's rings.
Polarization — Malus's law $I = I_0\cos^2\theta$, Stokes parameters $(S_0, S_1, S_2, S_3)$, degree of polarization, Jones matrix (rotation), quarter-wave plate, specific rotatory power, ellipticity, circular dichroism, birefringence $\Delta n = n_e - n_o$, and phase retardation $\Gamma = 2\pi\Delta n \cdot d / \lambda$.
The heart of modern physics. SciForge implements the mathematical formalisms using its own Complex type for complex arithmetic.
Wave Functions — Plane wave $\psi = e^{i(kx - \omega t)}$, Gaussian wave packet (localized superposition), normalization $\int|\psi|^2 dx = 1$, probability density, expectation values of position $\langle x \rangle$ and momentum $\langle p \rangle = -i\hbar \int \psi^* \frac{d\psi}{dx} dx$. Time evolution via the split-step (Fourier) method: alternation between real space (potential) and momentum space (kinetic energy).
**Operators** — Commutator $[A,B] = AB - BA$ and anticommutator $\{A,B\}$, expectation value $\langle A \rangle = \langle\psi|A|\psi\rangle$, variance $\sigma_A^2 = \langle A^2\rangle - \langle A\rangle^2$, uncertainty product $\sigma_A \sigma_B \geq \frac{1}{2}|\langle[A,B]\rangle|$ (Heisenberg's uncertainty principle), Hermiticity test, trace, and determinant.
Angular Momentum — Associated Legendre polynomials $P_l^m(\cos\theta)$, spherical harmonics $Y_l^m(\theta,\phi) = N_{lm} P_l^m(\cos\theta) e^{im\phi}$ (eigenfunctions of $L^2$ and $L_z$), Clebsch-Gordan coefficients (coupling of two angular momenta), and the Wigner formalism.
Spin — Pauli matrices $\sigma_x, \sigma_y, \sigma_z$ (2×2), up/down and $\pm x$, $\pm y$ spinors, Dirac gamma matrices (4×4) for relativistic theory, and the 2×2 identity.
Perturbation Theory — Stationary perturbation theory: first-order energy correction $E_n^{(1)} = \langle n|V|n\rangle$, second-order correction $E_n^{(2)} = \sum_{k\neq n} |V_{kn}|^2/(E_n-E_k)$, and first-order state correction. These corrections enable treatment of the Stark effect (electric field) and the Zeeman effect (magnetic field).
**Quantum Systems** — Hydrogen atom: energy levels $E_n = -13.6/n^2$ eV, radial functions $R_{10}$, $R_{20}$, $R_{21}$. Harmonic oscillator: $E_n = \hbar\omega(n+1/2)$, wave functions via Hermite polynomials. Infinite potential well: $E_n = n^2\pi^2\hbar^2/(2mL^2)$. Quantum tunneling $T = [1 + V_0^2\sinh^2(\kappa a)/(4E(V_0-E))]^{-1}$, Bohr radius $a_0 = \hbar^2/(me^2)$, Landau levels (magnetic field), and Zeeman effect.
Quantum Information — Von Neumann entropy $S = -\text{Tr}(\rho\ln\rho)$, purity $\text{Tr}(\rho^2)$, fidelity of pure and mixed states, concurrence of 2 qubits (entanglement measure), Bell states ($|\Phi^\pm\rangle$, $|\Psi^\pm\rangle$), and tensor product for composite systems.
Einstein's special relativity transforms our understanding of space and time at velocities approaching $c$.
Lorentz Transformations — Lorentz factor $\gamma = 1/\sqrt{1-v^2/c^2}$, 4×4 boost matrix (in all three spatial directions), rapidity parameter $\phi = \text{arctanh}(v/c)$, and space-time interval invariant $s^2 = c^2\Delta t^2 - \Delta x^2 - \Delta y^2 - \Delta z^2$.
Kinematics — Time dilation $\Delta t' = \gamma \Delta t$, length contraction $L' = L/\gamma$, relativistic velocity addition $v = (v_1+v_2)/(1+v_1 v_2/c^2)$, proper time along a trajectory, and relativistic aberration $\cos\theta' = (\cos\theta - \beta)/(1-\beta\cos\theta)$.
Dynamics — Relativistic momentum $p = \gamma m v$, total energy $E = \gamma mc^2$, kinetic energy $K = (\gamma-1)mc^2$, energy-momentum relation $E^2 = (pc)^2 + (mc^2)^2$, four-momentum, invariant mass of two bodies, Mandelstam variables, Compton shift $\Delta\lambda = (h/m_e c)(1-\cos\theta)$, particle-production threshold energy, synchrotron radiation, and classical Bremsstrahlung.
Solid mechanics studies the deformation and failure of materials under stress.
Elasticity — Hooke's law $\sigma = E\varepsilon$, Poisson's ratio $\nu$, shear modulus $G = E/(2(1+\nu))$, bulk modulus $K = E/(3(1-2\nu))$, first Lamé parameter, plane stress/strain, strain energy density $u = \frac{1}{2}\sigma\varepsilon$, thermal strain $\varepsilon = \alpha\Delta T$, volumetric strain, and hydrostatic stress.
Stress Analysis — 2D principal stresses (eigenvalues of the stress tensor), maximum shear stress, Mohr's circle (radius and center), stress tensor rotation, deviatoric tensor, second invariant $J_2$, beam bending $\sigma = My/I$, cantilever deflection $\delta = PL^3/3EI$, torsional shear $\tau = Tr/J$, Euler buckling $P_{cr} = \pi^2 EI/L^2$, and Hertzian contact pressure.
Plasticity — Offset yield strength, Ramberg-Osgood model (nonlinear stress-strain curve), true vs. engineering stress/strain, power-law hardening $\sigma = K\varepsilon_p^n$, Von Mises and Tresca yield criteria, isotropic hardening, Bauschinger effect, plastic work, necking criterion ($n$), and strain-rate sensitivity.
Fracture — Stress intensity factor $K_I = Y\sigma\sqrt{\pi a}$, Griffith critical stress $\sigma_c = \sqrt{2E\gamma/\pi a}$, energy release rate $G = K^2/E$, J-integral, crack-tip plastic zone (Irwin estimate), Paris law for fatigue crack growth $da/dN = C(\Delta K)^m$, fatigue life (Basquin for stress, Coffin-Manson for strain), Miner's cumulative damage rule, plane-strain fracture toughness, stress-corrosion cracking, and CTOD (Crack Tip Opening Displacement).
Thermodynamics studies energy transformations and the macroscopic properties of matter, complemented by statistical mechanics at the microscopic level.
Equations of State — Ideal gas law $PV = nRT$, Van der Waals $(P + a/V_m^2)(V_m - b) = RT$ (corrections for molecular interactions and volume), Redlich-Kwong, virial equation (density series), compressibility factor $Z = PV/(nRT)$. Internal energy $U = nC_vT$, enthalpy $H = nC_pT$, entropy $\Delta S = nC_v\ln(T_2/T_1) + nR\ln(V_2/V_1)$, Gibbs free energy $G = H - TS$ and Helmholtz free energy $F = U - TS$, chemical potential, Clausius-Clapeyron equation (vapor pressure), heat capacity ratio $\gamma = C_p/C_v$, speed of sound $c = \sqrt{\gamma RT/M}$, Maxwell speed distribution (three characteristic speeds: most probable, mean, and root-mean-square).
Processes — Carnot efficiency $\eta = 1 - T_c/T_h$, heating and cooling COP, isothermal/adiabatic/isobaric work, adiabatic relations ($TV^{\gamma-1} = \text{const}$, $PV^\gamma = \text{const}$), Otto efficiency, Diesel efficiency, Joule-Thomson coefficient, thermal conduction (Fourier's law $q = -kA\,dT/dx$), 1D thermal diffusion (explicit FTCS scheme), entropy of mixing, reaction free energy $\Delta G = \Delta G^0 + RT\ln Q$, equilibrium constant, and Van't Hoff equation.
Statistical Mechanics — Boltzmann distribution $P \propto e^{-E/k_BT}$, partition function $Z = \sum_i e^{-E_i/k_BT}$, harmonic oscillator partition function, canonical average energy and entropy. Quantum distributions: Fermi-Dirac $f = 1/(e^{(E-\mu)/k_BT}+1)$ (fermions) and Bose-Einstein $f = 1/(e^{(E-\mu)/k_BT}-1)$ (bosons). Blackbody radiation: Planck's law (in frequency and wavelength), Wien's displacement law $\lambda_{\max} T = 2898\,\mu\text{m·K}$, Stefan-Boltzmann law $P = \sigma A T^4$. Specific heat of solids: Debye model (numerical integration) and Einstein model. Sackur-Tetrode entropy for the ideal monoatomic gas.
f64 rounding errors can accumulate in long simulations.For concrete function calls, Rust signatures and module paths are documented in docs/code/.
SciForge is a scientific computing library written in pure Rust, with no external dependencies. It covers a wide range of domains — from classical physics to molecular biology — organized into independent modules, each exposing both a domain specification and a Rust implementation.
This page explains how the documentation is organized, what each section is meant to provide, and how to move between scientific explanations and Rust APIs.
docs/modules/ to understand the scientific scope and models.docs/code/ to inspect the implementation layout and public-facing API.This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.
modules/ and code/ pages depending on whether you need theory or implementation details.modules/ pages focus on scientific models, assumptions, and equations.code/ pages focus on source layout, exported APIs, and execution flow.Each module has two complementary pages:
Celestial mechanics, astrophysics, and cosmology (4 submodules). Covers orbital dynamics (Kepler's laws, vis-viva, Hohmann transfers, orbital perturbations), stellar physics (HR diagram, luminosity-mass-radius relations, main-sequence lifetime, stellar nucleosynthesis), cosmology (direct E(z) parameterizations, H(z) evaluation, comoving/luminosity/angular-diameter distances in LCDM/general/wCDM/CPL, dark-energy equation-of-state models, analytical LCDM shortcuts), and celestial mechanics (ecliptic/equatorial/galactic coordinate transforms, Julian date, sidereal time, nutation).
→ Module spec · Rust API
Performance measurement infrastructure for SciForge (6 submodules). Covers a 30+ field BenchmarkMetrics engine with statistical aggregation and CSV export, a compact binary encoding format (magic header, LE layout, 168+ byte records), zero-copy decoding via BenchmarkMetricsView, a simulation framework with SimState/SimConfig/StepFn traits, multi-format report generation (CSV, Markdown, HTML, JSON, YAML, TOML), and a file-based export orchestrator with periodic-table-themed CSS.
→ Module spec · Rust API
The largest scientific module (44 submodules, 176 source files). Covers aging (Gompertz/Weibull mortality, telomere dynamics), bioelectricity (Nernst, Goldman–Hodgkin–Katz, Hodgkin–Huxley), bioenergetics (ATP yield, Kleiber's law), biomechanics (Poiseuille flow, Hill muscle model), biophysics (Helfrich membrane, WLC, FRET), biostatistics (Kaplan–Meier, meta-analysis), ecology (Lotka–Volterra, Rosenzweig–MacArthur), enzyme kinetics (Michaelis–Menten, Hill, inhibition), evolution (molecular clock, dN/dS, coalescent), genetics (Hardy–Weinberg, $F_{ST}$), immunology (affinity maturation), neuroscience (integrate-and-fire), pharmacology (PK/PD, hepatic clearance), population dynamics (Leslie matrix, SIR/SEIR), synthetic biology (toggle switch, repressilator, FBA), virology (quasispecies, error catastrophe), and 28 more submodules.
→ Module spec · Rust API
Physical, analytical, inorganic, and computational chemistry (26 submodules). Covers acid–base equilibria (Henderson–Hasselbalch, polyprotic titrations), kinetics (Arrhenius, Eyring, Lindemann), electrochemistry (Nernst, Butler–Volmer, Tafel), thermochemistry (Hess's law, Kirchhoff), gas laws (van der Waals, virial, compressibility), quantum chemistry (Hartree–Fock, DFT concepts, Slater determinants), crystallography (Bragg's law, Miller indices, 14 Bravais lattices), molecular modeling (Lennard-Jones, Morse potential, VSEPR), colloids (DLVO theory, Stokes–Einstein), green chemistry (atom economy, E-factor), and environmental chemistry (Henry's law, BOD/COD).
→ Module spec · Rust API
Curated registry of physical constants, astronomical data, atomic properties, and unit conversions (5 submodules). Includes 16 CODATA fundamental constants ($c$, $G$, $h$, $\hbar$, $k_B$, $N_A$, $e$, $\varepsilon_0$, $\mu_0$, $\sigma_{SB}$, $\alpha$, Planck units), 10 astronomical constants (AU, parsec, solar/Earth parameters, Hubble constant), 13 atomic constants (particle masses, Bohr radius, Rydberg energy, magnetons), the full periodic table (118 elements loaded from YAML with OnceLock), and 12 unit conversion factors (eV↔J, cal↔J, atm↔Pa, deg↔rad, barn, ångström, fermi).
→ Module spec · Rust API
Earth sciences and geophysics (4 submodules). Covers radiometric dating (decay law $N(t) = N_0 e^{-\lambda t}$, half-life conversion, isochron method, $^{14}$C calibration), petrology (CIPW norm, magma viscosity, Stokes settling, crystallization sequences), seismology (P/S/surface wave propagation, Gutenberg–Richter, Omori aftershock law, magnitude scales $M_L$/$M_W$/$m_b$, focal mechanisms), and tectonics (plate velocity on a sphere, Euler poles, Byerlee's friction law, thermal subsidence).
→ Module spec · Rust API
Central orchestration layer (5 areas: API, Domain, Engine, Tools, Prelude — 35 source files). Provides a zero-dependency HTTP server (TcpListener-based), structured DTOs (ComputeRequest/ComputeResponse with 8 result types), domain dispatchers for all 7 scientific modules, direct astronomy-cosmology routing (E(z), H(z), and distance functions) through the Hub, an Experiment builder with 15 ParameterValue variants (Scalar through Tensor), a DynamicalSystem trait for ODE simulations (with built-in HarmonicOscillator/LotkaVolterra), priority-based task scheduling with dependency-aware topological sort, campaign batch execution, and tooling (Config, Logger, Metrics).
→ Module spec · Rust API
Numerical methods and pure mathematics (17 submodules). Covers complex arithmetic, linear algebra (Gauss elimination, LU/Cholesky decomposition, eigenvalues), calculus (symbolic differentiation, Simpson/Gauss quadrature, automatic differentiation), ODE solvers (Euler, RK4, adaptive RK45), Fourier and Laplace transforms, statistics (descriptive, distributions, hypothesis testing), probability, number theory (primes, GCD, modular arithmetic), combinatorics, set theory, graph theory (BFS, DFS, Dijkstra, Kruskal), geometry (2D/3D transforms, convex hull), trigonometry, polynomial operations, vector calculus (gradient, divergence, curl, Stokes' theorem), and special functions (Gamma, Beta, Bessel, error function).
→ Module spec · Rust API
Atmospheric science and weather physics (4 submodules). Covers atmosphere (barometric formula, ISA standard layers, pressure altitude, scale height, lapse rates), dynamics (geostrophic/gradient wind, Rossby number, vorticity, thermal wind, Ekman spiral, CAPE/CIN, Richardson number), precipitation (Clausius–Clapeyron, Köhler theory, Marshall–Palmer DSD, $Z$–$R$ relations, terminal velocity, Bergeron process), and radiation (Planck blackbody, Wien's law, Stefan–Boltzmann, solar zenith angle, Beer–Lambert atmospheric extinction, albedo, greenhouse radiative forcing $\Delta F = 5.35 \ln(C/C_0)$).
→ Module spec · Rust API
Multi-format data parsing library with zero dependencies (5 formats, 26 source files). Covers CSV (RFC 4180, CsvValue enum with Table/Record/Field, quoted field handling, writer), JSON (RFC 8259, JsonValue with 6 variants, number/string submodules), YAML (YamlValue with indent-based LineCursor, scalar type auto-detection for booleans/numbers/null — used by the Constants module for periodic table data), HTML (HtmlValue with Document/Element/Text/Comment, named entity decoding — used by Benchmark export), and Markdown (MdValue with 9 block-level variants, inline emphasis/links/code processing). All formats share a layered Cursor<'a> architecture with zero-copy &'a str borrowing and const fn constructors.
→ Module spec · Rust API
Classical and modern physics (11 submodules). Covers acoustics (wave equation, Doppler, decibel scale, resonance), electrodynamics (Maxwell's equations, Lorentz force, electromagnetic waves, Poynting vector), electronics (Ohm's law, RC/RL/RLC circuits, transistor models, op-amp configurations), fluid mechanics (Navier–Stokes, Bernoulli, Reynolds number, drag), materials science (stress–strain, Young's modulus, Hooke's law, creep), nucleosynthesis (binding energy, decay chains, cross-sections, pp-chain, CNO cycle), optics (Snell's law, thin lens, diffraction, interference, polarization), quantum mechanics (Schrödinger equation, particle-in-a-box, harmonic oscillator, hydrogen atom, tunneling), relativity (Lorentz transforms, $E = mc^2$, time dilation, gravitational redshift, Schwarzschild metric), solid mechanics (beam bending, torsion, Mohr's circle, buckling), and thermodynamics (laws of thermodynamics, Carnot cycle, entropy, heat transfer, blackbody radiation).
→ Module spec · Rust API
docs/
├── Summary.md # This file
├── modules/ # Scientific domain documentation (concepts & formulas)
│ ├── Astronomy.md
│ ├── Benchmark.md
│ ├── Biology.md
│ ├── Chemistry.md
│ ├── Constants.md
│ ├── Geology.md
│ ├── Hub.md
│ ├── Mathematics.md
│ ├── Meteorology.md
│ ├── Parser.md
│ └── Physics.md
└── code/ # Rust implementation documentation (API reference)
├── Astronomy.md
├── Benchmark.md
├── Biology.md
├── Chemistry.md
├── Constants.md
├── Geology.md
├── Hub.md
├── Mathematics.md
├── Meteorology.md
├── Parser.md
└── Physics.md
SciForge is a scientific computing library written in pure Rust, with no external dependencies. It covers a wide range of domains — from classical physics to molecular biology — organized into independent modules, each exposing both a domain specification and a Rust implementation.
This page explains how the documentation is organized, what each section is meant to provide, and how to move between scientific explanations and Rust APIs.
docs/modules/ to understand the scientific scope and models.docs/code/ to inspect the implementation layout and public-facing API.This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.
modules/ and code/ pages depending on whether you need theory or implementation details.modules/ pages focus on scientific models, assumptions, and equations.code/ pages focus on source layout, exported APIs, and execution flow.Each module has two complementary pages:
Celestial mechanics, astrophysics, and cosmology (4 submodules). Covers orbital dynamics (Kepler's laws, vis-viva, Hohmann transfers, orbital perturbations), stellar physics (HR diagram, luminosity-mass-radius relations, main-sequence lifetime, stellar nucleosynthesis), cosmology (direct E(z) parameterizations, H(z) evaluation, comoving/luminosity/angular-diameter distances in LCDM/general/wCDM/CPL, dark-energy equation-of-state models, analytical LCDM shortcuts), and celestial mechanics (ecliptic/equatorial/galactic coordinate transforms, Julian date, sidereal time, nutation).
→ Module spec · Rust API
Performance measurement infrastructure for SciForge (6 submodules). Covers a 30+ field BenchmarkMetrics engine with statistical aggregation and CSV export, a compact binary encoding format (magic header, LE layout, 168+ byte records), zero-copy decoding via BenchmarkMetricsView, a simulation framework with SimState/SimConfig/StepFn traits, multi-format report generation (CSV, Markdown, HTML, JSON, YAML, TOML), and a file-based export orchestrator with periodic-table-themed CSS.
→ Module spec · Rust API
The largest scientific module (44 submodules, 176 source files). Covers aging (Gompertz/Weibull mortality, telomere dynamics), bioelectricity (Nernst, Goldman–Hodgkin–Katz, Hodgkin–Huxley), bioenergetics (ATP yield, Kleiber's law), biomechanics (Poiseuille flow, Hill muscle model), biophysics (Helfrich membrane, WLC, FRET), biostatistics (Kaplan–Meier, meta-analysis), ecology (Lotka–Volterra, Rosenzweig–MacArthur), enzyme kinetics (Michaelis–Menten, Hill, inhibition), evolution (molecular clock, dN/dS, coalescent), genetics (Hardy–Weinberg, $F_{ST}$), immunology (affinity maturation), neuroscience (integrate-and-fire), pharmacology (PK/PD, hepatic clearance), population dynamics (Leslie matrix, SIR/SEIR), synthetic biology (toggle switch, repressilator, FBA), virology (quasispecies, error catastrophe), and 28 more submodules.
→ Module spec · Rust API
Physical, analytical, inorganic, and computational chemistry (26 submodules). Covers acid–base equilibria (Henderson–Hasselbalch, polyprotic titrations), kinetics (Arrhenius, Eyring, Lindemann), electrochemistry (Nernst, Butler–Volmer, Tafel), thermochemistry (Hess's law, Kirchhoff), gas laws (van der Waals, virial, compressibility), quantum chemistry (Hartree–Fock, DFT concepts, Slater determinants), crystallography (Bragg's law, Miller indices, 14 Bravais lattices), molecular modeling (Lennard-Jones, Morse potential, VSEPR), colloids (DLVO theory, Stokes–Einstein), green chemistry (atom economy, E-factor), and environmental chemistry (Henry's law, BOD/COD).
→ Module spec · Rust API
Curated registry of physical constants, astronomical data, atomic properties, and unit conversions (5 submodules). Includes 16 CODATA fundamental constants ($c$, $G$, $h$, $\hbar$, $k_B$, $N_A$, $e$, $\varepsilon_0$, $\mu_0$, $\sigma_{SB}$, $\alpha$, Planck units), 10 astronomical constants (AU, parsec, solar/Earth parameters, Hubble constant), 13 atomic constants (particle masses, Bohr radius, Rydberg energy, magnetons), the full periodic table (118 elements loaded from YAML with OnceLock), and 12 unit conversion factors (eV↔J, cal↔J, atm↔Pa, deg↔rad, barn, ångström, fermi).
→ Module spec · Rust API
Earth sciences and geophysics (4 submodules). Covers radiometric dating (decay law $N(t) = N_0 e^{-\lambda t}$, half-life conversion, isochron method, $^{14}$C calibration), petrology (CIPW norm, magma viscosity, Stokes settling, crystallization sequences), seismology (P/S/surface wave propagation, Gutenberg–Richter, Omori aftershock law, magnitude scales $M_L$/$M_W$/$m_b$, focal mechanisms), and tectonics (plate velocity on a sphere, Euler poles, Byerlee's friction law, thermal subsidence).
→ Module spec · Rust API
Central orchestration layer (5 areas: API, Domain, Engine, Tools, Prelude — 35 source files). Provides a zero-dependency HTTP server (TcpListener-based), structured DTOs (ComputeRequest/ComputeResponse with 8 result types), domain dispatchers for all 7 scientific modules, direct astronomy-cosmology routing (E(z), H(z), and distance functions) through the Hub, an Experiment builder with 15 ParameterValue variants (Scalar through Tensor), a DynamicalSystem trait for ODE simulations (with built-in HarmonicOscillator/LotkaVolterra), priority-based task scheduling with dependency-aware topological sort, campaign batch execution, and tooling (Config, Logger, Metrics).
→ Module spec · Rust API
Numerical methods and pure mathematics (17 submodules). Covers complex arithmetic, linear algebra (Gauss elimination, LU/Cholesky decomposition, eigenvalues), calculus (symbolic differentiation, Simpson/Gauss quadrature, automatic differentiation), ODE solvers (Euler, RK4, adaptive RK45), Fourier and Laplace transforms, statistics (descriptive, distributions, hypothesis testing), probability, number theory (primes, GCD, modular arithmetic), combinatorics, set theory, graph theory (BFS, DFS, Dijkstra, Kruskal), geometry (2D/3D transforms, convex hull), trigonometry, polynomial operations, vector calculus (gradient, divergence, curl, Stokes' theorem), and special functions (Gamma, Beta, Bessel, error function).
→ Module spec · Rust API
Atmospheric science and weather physics (4 submodules). Covers atmosphere (barometric formula, ISA standard layers, pressure altitude, scale height, lapse rates), dynamics (geostrophic/gradient wind, Rossby number, vorticity, thermal wind, Ekman spiral, CAPE/CIN, Richardson number), precipitation (Clausius–Clapeyron, Köhler theory, Marshall–Palmer DSD, $Z$–$R$ relations, terminal velocity, Bergeron process), and radiation (Planck blackbody, Wien's law, Stefan–Boltzmann, solar zenith angle, Beer–Lambert atmospheric extinction, albedo, greenhouse radiative forcing $\Delta F = 5.35 \ln(C/C_0)$).
→ Module spec · Rust API
Multi-format data parsing library with zero dependencies (5 formats, 26 source files). Covers CSV (RFC 4180, CsvValue enum with Table/Record/Field, quoted field handling, writer), JSON (RFC 8259, JsonValue with 6 variants, number/string submodules), YAML (YamlValue with indent-based LineCursor, scalar type auto-detection for booleans/numbers/null — used by the Constants module for periodic table data), HTML (HtmlValue with Document/Element/Text/Comment, named entity decoding — used by Benchmark export), and Markdown (MdValue with 9 block-level variants, inline emphasis/links/code processing). All formats share a layered Cursor<'a> architecture with zero-copy &'a str borrowing and const fn constructors.
→ Module spec · Rust API
Classical and modern physics (11 submodules). Covers acoustics (wave equation, Doppler, decibel scale, resonance), electrodynamics (Maxwell's equations, Lorentz force, electromagnetic waves, Poynting vector), electronics (Ohm's law, RC/RL/RLC circuits, transistor models, op-amp configurations), fluid mechanics (Navier–Stokes, Bernoulli, Reynolds number, drag), materials science (stress–strain, Young's modulus, Hooke's law, creep), nucleosynthesis (binding energy, decay chains, cross-sections, pp-chain, CNO cycle), optics (Snell's law, thin lens, diffraction, interference, polarization), quantum mechanics (Schrödinger equation, particle-in-a-box, harmonic oscillator, hydrogen atom, tunneling), relativity (Lorentz transforms, $E = mc^2$, time dilation, gravitational redshift, Schwarzschild metric), solid mechanics (beam bending, torsion, Mohr's circle, buckling), and thermodynamics (laws of thermodynamics, Carnot cycle, entropy, heat transfer, blackbody radiation).
→ Module spec · Rust API
docs/
├── Summary.md # This file
├── modules/ # Scientific domain documentation (concepts & formulas)
│ ├── Astronomy.md
│ ├── Benchmark.md
│ ├── Biology.md
│ ├── Chemistry.md
│ ├── Constants.md
│ ├── Geology.md
│ ├── Hub.md
│ ├── Mathematics.md
│ ├── Meteorology.md
│ ├── Parser.md
│ └── Physics.md
└── code/ # Rust implementation documentation (API reference)
├── Astronomy.md
├── Benchmark.md
├── Biology.md
├── Chemistry.md
├── Constants.md
├── Geology.md
├── Hub.md
├── Mathematics.md
├── Meteorology.md
├── Parser.md
└── Physics.md
This page documents the source implementation behind sciforge::astronomy, including file layout and Hub dispatch wiring.
src/astronomy/.pub(crate) in src/lib.rs and is not part of the external crate API.sciforge::hub API for these computations.src/astronomy/src/astronomy/mod.rssrc/hub/engine/dispatch/astronomy.rsorbits, stellar, cosmology, celestial)..rs file implements a coherent set of equations and helpers.orbitsstellarcosmologycelestiale_z(omega_m, omega_r, omega_k, omega_de, z)e_z_lcdm(omega_m, z)e_z_lcdm_rad(omega_m, omega_r, z)e_z_wcdm(omega_m, omega_de, w, z)e_z_w0wa(omega_m, omega_de, w0, wa, z)hubble_at_z(h0, omega_m, omega_r, omega_k, omega_de, z)hubble_at_z_lcdm(h0, omega_m, z)comoving_distance_from_z(h0, omega_m, z)luminosity_distance_from_z(h0, omega_m, z)angular_diameter_distance_from_z(h0, omega_m, z)General curved-model variants:
comoving_distance_general(h0, omega_m, omega_r, omega_k, omega_de, z)transverse_comoving_distance(h0, omega_m, omega_r, omega_k, omega_de, z)luminosity_distance_general(h0, omega_m, omega_r, omega_k, omega_de, z)angular_diameter_distance_general(h0, omega_m, omega_r, omega_k, omega_de, z)Dark-energy model variants:
comoving_distance_wcdm(...), luminosity_distance_wcdm(...)comoving_distance_w0wa(...), luminosity_distance_w0wa(...)age_lcdm(h0, omega_m) (analytical flat LCDM age)deceleration_parameter(omega_m, z)deceleration_parameter_today(omega_m)All cosmology functions above are wired through the astronomy dispatcher in:
src/hub/engine/dispatch/astronomy.rsUsage pattern:
use sciforge::hub::prelude::*;
let exp = Experiment::new(DomainType::Astronomy, "hubble_at_z_lcdm")
.param("h0", ParameterValue::Scalar(67.4))
.param("omega_m", ParameterValue::Scalar(0.315))
.param("z", ParameterValue::Scalar(1.0));
let out = ExperimentRunner::new().run(&exp)?;
This page documents the source implementation behind sciforge::benchmark, including benchmark engine internals, encoding/decoding, simulation flow, report generation, and exporters.
src/benchmark/.pub mod benchmark; in src/lib.rs).sciforge::benchmark::*.src/benchmark/src/benchmark/mod.rs(n/a - benchmark is direct)mod.rs and targeted pub use exports..rs file implements a coherent block of equations and functions.engine — core benchmarking loop (bench, run, run_headless)simulation — deterministic simulation runner (SimConfig, SimState, SimResult)encode — serialization of benchmark metrics to multiple formatsdecode — deserialization of encoded benchmark datareport — human-readable report generation from metricsexport — file export of benchmark results (CSV, JSON, TOML, YAML)| Struct | Description |
|---|---|
BenchmarkMetrics<'a> | Timing, iteration count, name, and statistical summary for a benchmark run |
BenchmarkMetricsView<'a> | Borrowed view of BenchmarkMetrics for formatting |
BenchmarkReport | Human-readable text report generated from metrics |
Entry<'a> | A single benchmark entry (name + metrics reference) |
ExportSummary | Summary of all exported file paths |
SimConfig | Configuration for a deterministic simulation (steps, dt, parameters) |
SimState | Runtime mutable state of a simulation |
SimResult | Final output after a complete simulation run |
benchpub fn bench<'a, T, F: Fn() -> T>(name: &'a str, f: F, iterations: usize) -> BenchmarkMetrics<'a>
Runs f for iterations repetitions and records min/max/mean/std timing.
runpub fn run<S: StepFn, R: RenderSink>(config: &SimConfig, step: S, sink: R) -> SimResult
Drives a full deterministic simulation using step at each tick, streaming output to sink.
run_headlesspub fn run_headless<S: StepFn>(config: &SimConfig, step: S) -> SimResult
Same as run but discards rendered output — suitable for pure benchmarking.
sanitize_filenamepub fn sanitize_filename(name: &str) -> String
Converts a benchmark name to a safe filesystem name (removes special characters, lowercases).
Serializes BenchmarkMetrics to text formats:
encode(metrics: &BenchmarkMetrics<'_>) -> String — canonical format (TOML)encoded_size(metrics: &BenchmarkMetrics<'_>) -> Option<usize> — byte size of encoded outputDeserializes previously encoded benchmark data:
decode<'a>(bytes: &'a str) -> BenchmarkMetrics<'a> — parse canonical encoded formatGenerates text reports from benchmark results:
generate(metrics: &BenchmarkMetrics<'_>, result: &str) -> BenchmarkReport — full reportgenerate_csv(metrics: &BenchmarkMetrics<'_>, result: &str) -> Stringgenerate_json(metrics: &BenchmarkMetrics<'_>, result: &str) -> Stringgenerate_json_tagged(metrics, result, tag) — JSON with extra tag fieldgenerate_toml(metrics: &BenchmarkMetrics<'_>, result: &str) -> Stringgenerate_toml_tagged(metrics, result, tag) — TOML with extra tag fieldgenerate_yaml(metrics: &BenchmarkMetrics<'_>, result: &str) -> Stringgenerate_yaml_tagged(metrics, result, tag) — YAML with extra tag fieldWrites benchmark reports to the output/ directory tree:
export(metrics: &BenchmarkMetrics<'_>, result: &str, base_dir: &str) -> ExportSummaryAutomatically creates subdirectories and writes CSV, JSON, TOML, and YAML files. Returns an ExportSummary listing all written paths.
use sciforge::benchmark::{bench, generate, export};
let metrics = bench("fft_1024", || {
sciforge::maths::fft::radix2::fft(&signal)
}, 1000);
let report = generate(&metrics, "ok");
println!("{}", report);
let summary = export(&metrics, "ok", "output/maths");
println!("Exported: {:?}", summary);
This page documents the source implementation behind sciforge::biology, including file layout, execution flow, and Hub dispatch integration.
src/biology/.pub(crate) in src/lib.rs).sciforge::hub as the public entry point.src/biology/src/biology/mod.rssrc/hub/engine/dispatch/biology.rsmod.rs and targeted pub use exports..rs file implements a coherent block of equations and functions.ExperimentRunner.aging — telomere dynamics, senescence models, Gompertz mortalitybioelectricity — membrane potential, Hodgkin-Huxley model, action potentialbioenergetics — ATP yield, metabolic rate, efficiency, caloric valuebiogeography — species-area relationships, island biogeography, dispersalbioinformatics — sequence alignment, edit distance, GC content, codon usagebiomechanics — joint forces, muscle force, gait analysis, stress on tissuesbiophysics — diffusion in cells, membrane transport, molecular motorsbiostatistics — survival analysis, dose-response, clinical trial statisticscancer_biology — tumor growth models, mutation rate, somatic evolutioncell — cell cycle, division, membrane area/volume, receptor kineticschronobiology — circadian rhythms, entrainment, ultradian oscillationscryobiology — cryoprotection, ice nucleation, viability modelsdevelopmental — growth stages, allometric scaling, pattern formationecology — Lotka-Volterra, competitive exclusion, food webs, biodiversityendocrinology — hormone kinetics, feedback loops, receptor occupancyenzyme — Michaelis-Menten, inhibition, enzyme efficiency, kcat/Kmimmunology — antibody kinetics, clonal expansion, immune response modelsmarine_biology — salinity effects, pressure adaptation, tidal modelsmicrobiology — bacterial growth, doubling time, kill curves, MICmycology — fungal growth models, spore dispersal, mycelial networksneuroscience — Hodgkin-Huxley, cable equation, synaptic models, neural codingnutrition — BMR, macronutrient metabolism, energy balancepaleobiology — fossil dating, phylogenetic divergence, extinction ratesparasitology — host-parasite dynamics, transmission, parasite loadpharmacology — PK/PD models, bioavailability, clearance, drug-receptor bindingphylogenetics — distance matrices, UPGMA, neighbor-joining, GTR modelphysiology — cardiac output, respiratory mechanics, renal functionplant_biology — photosynthesis rate, stomatal conductance, transpirationpopulation — logistic growth, age-structured models, Leslie matrixproteomics — isoelectric point, molecular weight from sequence, peptide propertiesradiobiology — linear-quadratic model, survival fraction, RBEreproduction — fertility models, gestational dynamics, reproductive rate R₀stem_cell — differentiation kinetics, self-renewal, niche occupancystructural — protein secondary structure propensities, folding energysynthetic_biology — toggle switch, oscillator, genetic circuit Hill functionssystems_biology — flux balance, stoichiometric matrix, metabolic controltissue_engineering — scaffold porosity, seeding efficiency, degradationtoxicology — LD50, dose-response curves, NOAEL, therapeutic indexvirology — viral replication kinetics, burst size, within-host dynamicsgompertz_mortality(a, b, age) — Gompertz-Makeham mortality ratetelomere_length(initial_length, division_rate, time)nernst_potential(z, t_in, t_out, temperature)goldman_equation(permeabilities, concentrations_in, concentrations_out, temperature)hodgkin_huxley_step(v, m, h, n, i_ext, dt) → (v_next, m, h, n)atp_yield_glucose() — theoretical max ATP from glycolysis + TCA + ETCmetabolic_rate_kleiber(mass) — Kleiber's law: BMR ∝ M^0.75respiratory_quotient(co2_produced, o2_consumed)gc_content(sequence: &str) → fractionedit_distance(s1: &str, s2: &str) — Levenshtein distanceneedleman_wunsch(seq1, seq2, match_score, mismatch, gap) → alignment scoresmith_waterman(seq1, seq2, match_score, mismatch, gap) → local alignmentcodon_frequency(sequence: &str) → codon count mapmuscle_force(pcsa, specific_tension)joint_reaction_force(external_force, moment_arm_ratio)bending_stress_bone(moment, radius, moment_of_inertia)cell_division_time(initial_count, final_count, time_span)receptor_occupancy(ligand_concentration, kd)surface_area_to_volume_ratio(radius) — sphere approximationlotka_volterra_prey(prey, predator, alpha, beta, dt)lotka_volterra_predator(prey, predator, gamma, delta, dt)logistic_growth(n, r, k) — dN/dtshannon_diversity(abundances)species_area_relationship(area, c, z) — S = C × A^zmichaelis_menten(vmax, km, substrate)competitive_inhibition(vmax, km, substrate, ki, inhibitor)noncompetitive_inhibition(vmax, km, substrate, ki, inhibitor)turnover_number(vmax, enzyme_concentration)catalytic_efficiency(kcat, km)bacterial_growth(n0, growth_rate, time) — exponential phasedoubling_time(growth_rate)logistic_bacterial_growth(n0, r, k, time)minimum_inhibitory_concentration(kill_rate, dose_response_params)cable_equation_steady_state(injected_current, r_in, lambda, distance)action_potential_threshold(sodium_conductance, potassium_conductance)synapse_strength_hebbian(pre_rate, post_rate, lr)isi_cv(inter_spike_intervals) — coefficient of variationone_compartment_pk(dose, volume, kel, time)bioavailability(auc_oral, auc_iv, dose_oral, dose_iv)clearance(dose, auc)half_life_from_elimination(kel)hill_equation(emax, ec50, n, concentration)jukes_cantor_distance(p_distance)upgma(distance_matrix) → tree structureneighbor_joining(distance_matrix) → tree structurephotosynthesis_rate_farquhar(vcmax, jmax, ci, temperature)stomatal_conductance_ball_berry(a_net, rh, cs, g0, g1)beer_lambert_canopy(k, lai)malthusian_growth(n0, r, t)logistic_growth_population(n0, r, k, t)leslie_matrix_projection(leslie_matrix, initial_population, steps)net_reproductive_rate(lx, mx) — R₀ = Σ(lx × mx)linear_quadratic_survival(alpha, beta, dose)equivalent_dose(dose, rbe)brachytherapy_dose_rate(activity, dose_constant, distance)flux_balance_analysis(stoich_matrix, lower_bounds, upper_bounds) → optimal fluxesmetabolic_control_coefficient(flux, enzyme_activity_change)elasticity_coefficient(reaction_rate, metabolite_conc)ld50_probit(dose, probit_params)therapeutic_index(ld50, ed50)no_observed_adverse_effect(dose_response_data)basic_reproduction_number(beta, delta, gamma)viral_burst_size(total_virions, infected_cells)within_host_viral_dynamics(t0, v0, i0, beta, delta, p, c, dt)All biology functions are wired through:
src/hub/engine/dispatch/biology.rsuse sciforge::hub::prelude::*;
let exp = Experiment::new(DomainType::Biology, "michaelis_menten")
.param("vmax", ParameterValue::Scalar(10.0))
.param("km", ParameterValue::Scalar(0.5))
.param("substrate", ParameterValue::Scalar(2.0));
let out = ExperimentRunner::new().run(&exp)?;
This page documents the source implementation behind sciforge::chemistry, including file layout and Hub dispatch wiring.
src/chemistry/.pub(crate) in src/lib.rs).sciforge::hub as the public entry point.src/chemistry/src/chemistry/mod.rssrc/hub/engine/dispatch/chemistry.rsmod.rs and targeted pub use exports..rs file implements a coherent block of equations and functions.ExperimentRunner.acid_baseanalyticalcolloidscomputationalcrystallographyelectrochemistryenvironmentalequilibriumgas_lawsgreen_chemistryinorganickineticsmolecularnuclearorganicphotochemistrypolymersquantum_chemreaction_engineeringsolid_statesolutionsspectroscopystoichiometrysurfacethermochemistrytransportequilibria — pH, pOH, Ka/Kb, buffer capacity, Henderson-Hasselbalchtitrations — equivalence point, titration curve, indicator selectionph_from_concentration(concentration, ka)henderson_hasselbalch(pka, ca, cb)buffer_capacity(ca, cb, ka)titration_curve(ca, va, cb, vb_range, ka)chromatography — retention factor, resolution, theoretical platesquantitative — calibration curves, detection limits, recoveryspectrophotometry — Beer-Lambert law, absorbance, transmittancebeer_lambert(molar_absorptivity, concentration, path_length)retention_factor(tr, tm)resolution_chromatography(tr1, tr2, w1, w2)detection_limit(blank_signal, std_dev, k)calibration_curve(xs, ys) → (slope, intercept)properties — zeta potential, particle size, surface areastability — DLVO theory, coagulation, sedimentationzeta_potential_to_stability(zeta)debye_huckel_kappa(ionic_strength, temperature)settling_velocity(radius, density_particle, density_fluid, viscosity)dft — density functional theory utilities, DFT energy approximationsbasis_sets — Gaussian basis set evaluations, overlap integralslda_exchange_energy(density)gga_exchange_energy(density, grad_density)gaussian_overlap(alpha1, alpha2, r1, r2)lattice — lattice parameters, unit cell volume, Bravais latticesdiffraction — Bragg's law, structure factor, powder diffraction patternbragg_angle(n, lambda, d_spacing)d_spacing_cubic(a, h, k, l)d_spacing_tetragonal(a, c, h, k, l)structure_factor(atom_positions, miller_indices)unit_cell_volume(a, b, c, alpha, beta, gamma)cells — Nernst equation, cell potential, electrode potentialstransport — ionic conductivity, diffusion, transference numbersnernst_equation(e0, n, q, temperature)cell_potential(e_cathode, e_anode)ionic_conductivity(lambda_ions, concentrations)diffusion_limiting_current(d, c, n, area, delta)atmosphere — Henry's law, atmospheric partitioning, ppm/ppb conversionwater — BOD, COD, dissolved oxygen, water hardnesshenry_constant(kh, temperature)atmospheric_ppm_to_concentration(ppm, molar_mass, temperature, pressure)dissolved_oxygen_saturation(temperature, salinity)bod_calculation(do_initial, do_final, dilution_factor)constants — Keq, Kp, Kc, Ksp calculationsionic — activity coefficients, Debye-Hückel, ionic strengthequilibrium_constant_from_gibbs(delta_g, temperature)kc_to_kp(kc, delta_n, temperature)ionic_strength(concentrations, charges)activity_coefficient_dhll(z, ionic_strength)debye_huckel_extended(z, ionic_strength, a, b, diameter)ideal — ideal gas law, partial pressures, Dalton's law, Graham's lawreal — van der Waals, Redlich-Kwong, virial equationideal_gas_pressure(n, temperature, volume)van_der_waals_pressure(n, a, b, temperature, volume)redlich_kwong(n, a, b, temperature, volume)partial_pressure(mole_fraction, total_pressure)effusion_rate_ratio(molar_mass1, molar_mass2)metrics — atom economy, E-factor, reaction mass efficiencyprinciples — solvent selection, waste minimization metricsatom_economy(mw_desired, sum_mw_reactants)e_factor(mass_waste, mass_product)reaction_mass_efficiency(actual_yield, theoretical_yield, atom_economy)bonding — bond order, electronegativity difference, bond polaritycoordination — crystal field splitting, coordination number, CFSEcrystal_field — d-orbital splitting, high-spin/low-spin energiesbond_polarity(electronegativity1, electronegativity2)crystal_field_stabilization(d_electrons, geometry, delta)coordination_geometry_energy(geometry, delta)rates — first/second/nth-order rate laws, integrated rate equationsmechanisms — Arrhenius equation, activation energy, pre-exponential factorfirst_order_concentration(c0, k, time)second_order_concentration(c0, k, time)arrhenius(a, ea, temperature)half_life_first_order(k)activation_energy_from_rates(k1, k2, t1, t2)michaelis_menten(vmax, km, substrate_conc)bonding — Lewis structure bond orders, hybridization, resonancegeometry — VSEPR geometry prediction, bond anglesvsepr_geometry(bonding_pairs, lone_pairs)hybridization(bonding_pairs, lone_pairs)dipole_moment(charge, distance)decay — alpha, beta, gamma decay, decay seriesenergy — Q-value, binding energy per nucleon, mass excessnuclear_decay_activity(n0, decay_constant, time)alpha_decay_q(parent_mass, daughter_mass, alpha_mass)beta_decay_q(parent_mass, daughter_mass)binding_energy_per_nucleon(mass_number, total_binding_energy)reactions — reaction type classification, yield predictionstructure — molecular formula, degree of unsaturation, functional groupsdescriptors — lipophilicity (LogP), molecular weight, polar surface areadegree_of_unsaturation(c, h, n, x)molecular_weight(formula) — parses simple formulaelogp_estimate(descriptor_values, logp_model)kinetics — photostationary state, quantum yield, actinometryquantum_yield — primary vs secondary quantum yield, sensitizationquantum_yield(n_products, n_photons_absorbed)photostationary_state(k_forward, k_reverse, phi_forward, phi_reverse)einstein_to_photons(energy_per_mole, wavelength)distributions — number/weight-average molecular weight, dispersityproperties — glass transition temperature, viscosity, degree of polymerizationnumber_average_mw(ni, mi)weight_average_mw(ni, mi)dispersity(mw, mn)degree_of_polymerization(mw, m0)glass_transition_estimate(backbone_flexibility)orbitals — AO basis functions, hydrogen-like wavefunctionshuckel — Hückel MO theory, secular determinant, π-electron energyhydrogen_wavefunction(n, l, m, r, theta, phi)huckel_eigenvalues(adjacency_matrix, alpha, beta)pi_electron_energy(eigenvalues, n_pi_electrons, alpha, beta)reactors — CSTR, PFR, batch reactor design equationsdesign — conversion, selectivity, residence timecstr_volume(fa0, conversion, rate)pfr_volume(fa0, conversion_range, rate_fn)batch_reactor_time(c0, conversion, rate_fn)residence_time(volume, volumetric_flow)selectivity(rate_desired, rate_undesired)band_theory — band gap, effective mass, density of statesdefects — point defects, Schottky/Frenkel concentrationsdensity_of_states_3d(energy, band_edge, effective_mass)schottky_defect_concentration(n_sites, delta_h, temperature)frenkel_defect_concentration(n_sites, delta_h, temperature)intrinsic_carrier_density(nc, nv, band_gap, temperature)colligative — boiling point elevation, freezing point depression, osmotic pressuremixtures — Raoult's law, Henry's law, activity coefficientsboiling_point_elevation(kb, molality)freezing_point_depression(kf, molality)osmotic_pressure(molarity, temperature)raoults_law(mole_fraction, vapor_pressure_pure)vapor_pressure_lowering(mole_fraction_solvent, p_pure)nmr — chemical shift, coupling constants, relaxation timesir — vibrational frequencies, group frequencies, IR intensitymass_spec — m/z, isotope patterns, fragmentationnmr_chemical_shift(frequency, reference_frequency)ir_stretching_frequency(force_constant, reduced_mass)monoisotopic_mass(formula)isotope_pattern(formula, max_isotopes)calculations — molar mass, limiting reagent, theoretical yieldbalancing — equation balancing via matrix methodlimiting_reagent(amounts, stoich_coefficients)theoretical_yield(limiting_amount, stoich_ratio, molar_mass)percent_yield(actual_yield, theoretical_yield)moles_from_mass(mass, molar_mass)balance_equation(reactants, products) → balanced coefficientsadsorption — Langmuir, Freundlich, BET isothermstension — surface tension, contact angle, capillary pressurelangmuir_coverage(k, concentration)freundlich_adsorption(kf, n, concentration)bet_surface_area(vm, a_molecule)laplace_pressure(surface_tension, radius)contact_angle_young(gamma_sl, gamma_sv, gamma_lv)enthalpy — Hess's law, standard enthalpy of reaction, Kirchhoff's lawentropy — standard entropy, Gibbs energy, spontaneityhess_law(enthalpies, coefficients)kirchhoff_correction(delta_h_298, delta_cp, temperature)gibbs_energy(delta_h, temperature, delta_s)equilibrium_temperature(delta_h, delta_s)standard_entropy_change(s_products, s_reactants)diffusion — Fick's laws, Stefan-Maxwell, diffusion coefficientsmass_transfer — mass transfer coefficient, Sherwood number, film theorydiffusion_coefficient_chapman_enskog(mw1, mw2, temperature, pressure)sherwood_number(k_c, length, diffusivity)overall_mass_transfer(k1, k2, henry_constant)film_theory_flux(concentration_bulk, concentration_surface, k_c)All chemistry functions are wired through:
src/hub/engine/dispatch/chemistry.rsuse sciforge::hub::prelude::*;
let exp = Experiment::new(DomainType::Chemistry, "arrhenius")
.param("a", ParameterValue::Scalar(1e13))
.param("ea", ParameterValue::Scalar(75000.0))
.param("temperature", ParameterValue::Scalar(500.0));
let out = ExperimentRunner::new().run(&exp)?;
This page documents the source implementation behind sciforge::constants, including constant tables and lookup helpers.
src/constants/.pub(crate) in src/lib.rs and is not part of the external crate API.sciforge::hub API for these computations.src/constants/src/constants/mod.rs(n/a - constants are direct)mod.rs and targeted pub use exports..rs file implements a coherent constants or lookup block.fundamental — physical constants (speed of light, Planck, Boltzmann, …)astro — astronomical constants (solar/planetary masses, distances, CMB, …)atomic — atomic/nuclear constants (masses, radii, energy scales, …)units — unit conversion factorselements — periodic table data (118 elements)All constants are pub const f64 accessible as sciforge::constants::CONSTANT_NAME.
| Constant | Symbol | Value |
|---|---|---|
C | Speed of light | 2.99792458×10⁸ m/s |
G | Gravitational constant | 6.674×10⁻¹¹ m³ kg⁻¹ s⁻² |
H | Planck constant | 6.62607015×10⁻³⁴ J·s |
HBAR | Reduced Planck constant | H / 2π |
K_B | Boltzmann constant | 1.380649×10⁻²³ J/K |
N_A | Avogadro number | 6.02214076×10²³ mol⁻¹ |
R_GAS | Ideal gas constant | 8.314462 J/(mol·K) |
SIGMA_SB | Stefan–Boltzmann constant | 5.670374×10⁻⁸ W m⁻² K⁻⁴ |
| Constant | Description |
|---|---|
E_CHARGE | Elementary charge (C) |
EPSILON_0 | Vacuum permittivity (F/m) |
MU_0 | Vacuum permeability (H/m) |
K_COULOMB | Coulomb constant (N·m²/C²) |
ALPHA_FINE | Fine-structure constant (dimensionless) |
| Constant | Description |
|---|---|
BOHR_RADIUS | Bohr radius (m) |
COMPTON_WAVELENGTH | Compton wavelength of the electron (m) |
RYDBERG_ENERGY | Rydberg energy (J) |
BOHR_MAGNETON | Bohr magneton (J/T) |
NUCLEAR_MAGNETON | Nuclear magneton (J/T) |
PROTON_MASS_KG | Proton mass (kg) |
NEUTRON_MASS_KG | Neutron mass (kg) |
ELECTRON_MASS_KG | Electron mass (kg) |
AMU_TO_KG | Atomic mass unit → kg |
AMU_TO_MEV | Atomic mass unit → MeV/c² |
| Constant | Description |
|---|---|
SOLAR_MASS | Solar mass (kg) |
SOLAR_RADIUS | Solar radius (m) |
SOLAR_LUMINOSITY | Solar luminosity (W) |
EARTH_MASS | Earth mass (kg) |
EARTH_RADIUS | Earth radius (m) |
AU | Astronomical unit (m) |
PARSEC | Parsec (m) |
LIGHT_YEAR | Light-year (m) |
HUBBLE_CONSTANT | Hubble constant H₀ (km/s/Mpc) |
CMB_TEMPERATURE | CMB temperature (K) |
| Constant | Description |
|---|---|
PLANCK_LENGTH | Planck length (m) |
PLANCK_MASS | Planck mass (kg) |
PLANCK_TIME | Planck time (s) |
PLANCK_TEMP | Planck temperature (K) |
| Constant | Conversion |
|---|---|
EV_TO_JOULE | eV → J |
JOULE_TO_EV | J → eV |
KELVIN_TO_KEV | K → keV |
KEV_TO_KELVIN | keV → K |
CALORIE_TO_JOULE | cal → J |
ATM_TO_PASCAL | atm → Pa |
BAR_TO_PASCAL | bar → Pa |
ANGSTROM | Ångström in meters |
FERMI | Fermi (fm) in meters |
BARN | Barn (b) in m² |
DEGREE_TO_RAD | ° → rad |
RAD_TO_DEGREE | rad → ° |
Functions to query static periodic-table data:
by_symbol(sym: &str) -> Option<&'static Element> — look up an element by its chemical symbol (e.g. "Fe")by_atomic_number(z: u32) -> Option<&'static Element> — look up by atomic number (1–118)atomic_mass(z: u32) -> f64 — atomic mass in u; returns 0.0 for unknown zelectronegativity(z: u32) -> Option<f64> — Pauling electronegativity; returns None if not availableuse sciforge::constants::{by_symbol, atomic_mass, electronegativity};
let fe = by_symbol("Fe").unwrap();
println!("{} — mass: {} u", fe.name, atomic_mass(26));
println!("electronegativity: {:?}", electronegativity(26));
This page documents the source implementation behind sciforge::geology, including file layout and Hub dispatch wiring.
src/geology/.pub(crate) in src/lib.rs and is not part of the external crate API.sciforge::hub API for these computations.src/geology/src/geology/mod.rssrc/hub/engine/dispatch/geology.rsmod.rs and targeted pub use exports..rs file implements a coherent block of equations and functions.ExperimentRunner.dating — geochronology and radiometric dating methodspetrology — rock classification, magma composition, igneous petrologyseismology — seismic waves, earthquake magnitude, aftershock statisticstectonics — plate tectonics, isostasy, heat flow, flexureradioactive_decay(n0, lambda, t) — remaining parent nuclei at time thalf_life(lambda) — half-life from decay constantdecay_constant(half_life) — decay constant from half-lifeage_from_ratio(ratio_daughter_parent, lambda) — generic radiometric agecarbon14_age(ratio) — ¹⁴C age from ¹⁴C/¹²C ratiopotassium_argon_age(ar40, k40) — K-Ar ageuranium_lead_age(pb206, u238) — U-Pb age (²³⁸U → ²⁰⁶Pb)isochron_age(slope, lambda) — age from isochron slopefission_track_age(rho_s, rho_i, rho_d, lambda) — fission track datingluminescence_dose(natural_signal, dose_rate) — OSL/TL equivalent dosecosmogenic_exposure_age(concentration, production_rate, lambda) — surface exposure datingcipw_quartz_norm(sio2, feldspars, mafics) — CIPW normative quartz contentmg_number(mgo, feo) — Mg# = MgO / (MgO + FeO) × 100 (wt%)differentiation_index(q, or_val, ab, ne) — Thornton-Tuttle differentiation indextotal_alkali_silica(na2o, k2o) — TAS diagram x-axis (Na₂O + K₂O)alumina_saturation_index(al2o3, cao, na2o, k2o) — A/CNK ratiocolor_index(mafic_minerals) — modal % of mafic minerals (M value)liquidus_temperature(composition, t_melt_a, t_melt_b) — linear liquidus interpolationsolidus_depression(water_content, base_solidus, k) — H₂O-induced solidus depressioncrystal_settling_velocity(delta_rho, g, r, mu) — Stokes settling in magmaviscosity_arrhenius(a, ea, t) — Arrhenius viscosity modelp_wave_velocity(k, g, rho) — P-wave speed from bulk/shear moduli and densitys_wave_velocity(g, rho) — S-wave speedrichter_magnitude(amplitude, distance_km) — local Richter scale MLmoment_magnitude(seismic_moment) — Mw from seismic momentseismic_moment(mw) — seismic moment from Mwepicenter_distance(vp, vs, ts_tp) — distance from P-S arrival time differencetravel_time(distance, velocity) — seismic wave arrival timesnell_seismic(v1, theta1, v2) — refracted ray angle (Snell's law for seismic)gutenberg_richter(a, b, magnitude) — log N = a − b·M frequency-magnitudeomori_aftershock(k, c, p, t) — Omori-Utsu aftershock decay rateseismic_energy(magnitude) — energy released from magnitudepeak_ground_acceleration(a, b, magnitude, distance) — empirical PGA attenuationplate_velocity(distance, time) — average plate velocityeuler_pole_velocity(omega, radius, colatitude) — surface velocity from Euler poleisostatic_equilibrium(rho_crust, thickness, rho_mantle) — crustal root / buoyancypratt_isostasy(rho_ref, d_ref, elevation) — Pratt isostasy column densityairy_root(elevation, rho_crust, rho_mantle) — Airy isostasy crustal root depththermal_subsidence(e0, t, tau) — McKenzie thermal subsidencemckenzie_stretching(beta, rho_m, rho_c, alpha, tl, tc) — stretching factor subsidenceheat_flow(k, dt_dz) — Fourier heat flow (W/m²)geothermal_gradient(surface_temp, depth, gradient) — temperature at depthflexural_rigidity(e, te, nu) — lithospheric flexural rigidity Delastic_thickness_from_rigidity(d, e, nu) — effective elastic thickness TeAll geology functions are wired through:
src/hub/engine/dispatch/geology.rsuse sciforge::hub::prelude::*;
let exp = Experiment::new(DomainType::Geology, "carbon14_age")
.param("ratio", ParameterValue::Scalar(0.5));
let out = ExperimentRunner::new().run(&exp)?;
This page documents the source implementation behind sciforge::hub, including API layer, engine internals, dispatch routing, and tooling modules.
src/hub/.hub is public from src/lib.rs (pub mod hub;).sciforge::hub::prelude::* for stable entry points.pub(crate) science domains.src/hub/src/hub/mod.rssrc/hub/engine/dispatch/*.rsmod.rs and targeted pub use exports..rs file implements a coherent orchestration or tooling block.api — HTTP and CLI interfaces, DTOs, routesdomain — DomainType enum and domain metadataengine — experiment execution, pipelines, task schedulingexperience — Experiment / ExperimentRunnerpipeline — Pipeline / Stage compositionworker — Scheduler, TaskQueue, Executor, ExecutionContextdispatch — domain-specific dispatch handlers (astronomy, biology, chemistry, geology, maths, meteorology, physics)tools — numerical utilities, visualization, profiling, validation, loggingprelude — convenience re-exportsuse sciforge::hub::prelude::*;
Exports: Experiment, ExperimentRunner, DomainType, ParameterValue, Pipeline, Stage, Scheduler, TaskQueue, Executor.
| Struct | Description |
|---|---|
Experiment | A named experiment with a domain, function name, and parameter map |
ExperimentRunner | Runs an Experiment by dispatching to the correct domain handler |
let exp = Experiment::new(DomainType::Physics, "lorentz_factor")
.param("velocity", ParameterValue::Scalar(2.0e8));
let result = ExperimentRunner::new().run(&exp)?;
| Struct | Description |
|---|---|
Pipeline | An ordered sequence of Stage transforms applied to a data vector |
Stage | A single named transform step (function Vec<f64> -> Vec<f64>) |
filter_positive_stage() — keeps only positive valuesscale_stage(factor: f64) — multiplies each element by factorlet pipeline = Pipeline::new()
.add(normalize_stage())
.add(scale_stage(100.0));
let output = pipeline.run(input_data);
| Struct | Description |
|---|---|
Scheduler | Manages a queue of ScheduledTask with priority and timing |
ScheduledTask | A task with an execution time and priority |
Task | A named unit of work with associated TaskResult |
TaskQueue | FIFO/priority queue of tasks |
TaskResult | Output and status of a completed task |
ExecutionContext | Runtime context passed to each task during execution |
Executor | Drives task execution loop, dispatching from a TaskQueue |
Generate ASCII/text-based plots for quick inspection:
fingerprint_scalar(v: f64) — u64 hash of a scalarlinspace(start, end, n) → Vec<f64> — evenly spaced pointslogspace(start_exp, end_exp, n) → Vec<f64> — logarithmically spaced points → Vec<f64>` → Vec<f64>` → Vec<f64>`relative_error(computed, reference) → f64scalar_value(v: f64) — wraps a scalar for use with the pipelineformat_scientific(v: f64, precision: usize) → String — e.g. "3.14e+00"format_si(v: f64, unit: &str) → String — SI prefix scaling (k, M, G, …)format_ns(duration_ns: u64) → String — nanoseconds as human-readable durationprofile_experiment(exp: &Experiment, runner: &ExperimentRunner) — time a single experimentquick_profile<F: Fn()>(f: F) → Duration — time any closurerun_timed<F: Fn() -> T>(f: F) → (T, Duration) — run and return result + durationassert_reproducible(f: F, n: usize) — run f n times, assert identical resultsapprox_equal(a: f64, b: f64, tol: f64) → boolThread-safe, level-gated logger:
info(msg: &str), warn(msg: &str), error(msg: &str)debug(msg: &str), trace(msg: &str)log(level: LogLevel, msg: &str) — generic log callset_level(level: LogLevel) — configure minimum log levelcurrent_level() → LogLevelusage() — print module usage summaryreport_to_latex(metrics) → String — LaTeX table from benchmark metricsreport_to_tsv(metrics) → String — TSV table from benchmark metricsThe DomainType enum routes function calls to the correct scientific module:
| Variant | Dispatches to |
|---|---|
DomainType::Astronomy | src/hub/engine/dispatch/astronomy.rs |
DomainType::Biology | src/hub/engine/dispatch/biology.rs |
DomainType::Chemistry | src/hub/engine/dispatch/chemistry.rs |
DomainType::Geology | src/hub/engine/dispatch/geology.rs |
DomainType::Maths | src/hub/engine/dispatch/maths.rs |
DomainType::Meteorology | src/hub/engine/dispatch/meteorology.rs |
DomainType::Physics | src/hub/engine/dispatch/physics.rs |
This page documents the source implementation behind sciforge::maths, including module layout and Hub dispatch wiring.
src/maths/.pub(crate) in src/lib.rs and is not part of the external crate API.sciforge::hub API for these computations.src/maths/src/maths/mod.rssrc/hub/engine/dispatch/maths.rslinalg, ode, pde, statistics, etc.).complexfftgraphintegrationinterpolationlinalgnon_euclideanodeoptimizationpdepolynomialprobabilitysignalsparsestatisticstensorvectortypes — Complex<f64> type, constructors, polar/rectangular formsops — arithmetic, exp, log, trig, hyperbolic functions on complex numbersquaternion — Quaternion type, Hamilton product, rotation, normalizationComplex::new(re, im), Complex::from_polar(r, theta)complex_exp(z), complex_ln(z), complex_sqrt(z)complex_sin(z), complex_cos(z), complex_tan(z)Quaternion::new(w, x, y, z), quaternion_rotate(q, v)radix2 — Cooley-Tukey FFT/IFFT for power-of-two sizesdct — Discrete Cosine Transform (types I–IV)bluestein — Chirp-Z / Bluestein FFT for arbitrary sizesfft(signal) → complex spectrumifft(spectrum) → time-domain signaldct_ii(signal), dct_iii(signal), dct_iv(signal)bluestein_fft(signal, n_out) — arbitrary-length DFTpower_spectrum(signal)traversal — BFS, DFS, topological sort, connected componentsshortest_path — Dijkstra, Bellman-Ford, Floyd-Warshall, A*spanning_tree — Kruskal, Prim, minimum/maximum spanning treeflow — Ford-Fulkerson, Edmonds-Karp, max-flow/min-cutdijkstra(graph, source) → distancesbellman_ford(graph, source) → distances (handles negative weights)floyd_warshall(graph) → all-pairs shortest pathskruskal_mst(graph), prim_mst(graph, start)bfs(graph, start), dfs(graph, start)ford_fulkerson(graph, source, sink)quadrature — trapezoidal, Simpson, Gauss-Legendre, Rombergadaptive — adaptive Simpson, adaptive Gauss-Kronrod (GK15, GK21)multidim — double/triple integrals, Monte Carlo integrationtrapezoidal(f, a, b, n)simpsons(f, a, b, n)gauss_legendre(f, a, b, n_points)romberg(f, a, b, max_iter, tol)adaptive_simpson(f, a, b, tol)monte_carlo_integral(f, domain, n_samples)double_integral(f, ax, bx, ay, by, n)lagrange — Lagrange polynomial interpolation, Neville's algorithmmethods — linear, bilinear, cubic, nearest-neighborspline — natural cubic spline, clamped spline, B-splinelagrange_interpolate(xs, ys, x)neville(xs, ys, x)linear_interpolate(x0, y0, x1, y1, x)cubic_spline(xs, ys) → spline objectspline_eval(spline, x)bspline_basis(i, k, t, knots)decomposition — LU, QR, Cholesky, SVD decompositionseigenvalue — power iteration, QR algorithm, Jacobi methodfactorization — LDL^T, Schur, polar decompositionleast_squares — normal equations, QR least squares, pseudoinverselu_decompose(matrix) → (L, U, P)qr_decompose(matrix) → (Q, R)cholesky(matrix) → L (lower triangular)svd(matrix) → (U, Σ, V^T)eigenvalues_qr(matrix, tol, max_iter)solve_linear(a, b) — Ax = b via LUpseudoinverse(matrix)least_squares_qr(a, b)metric — metric tensors (Minkowski, Schwarzschild, Kerr, FRW)geodesic — geodesic equations, numerical integrationcurvature — Riemann tensor, Ricci scalar, Christoffel symbolscosmology — scale factor, Friedmann equationsblack_hole — Schwarzschild radius, Hawking temperature, ergosphereschwarzschild_radius(mass)hawking_temperature(mass)christoffel_symbols(metric, coord)riemann_tensor(metric, coord)ricci_scalar(metric, coord)geodesic_equation(metric, initial_pos, initial_vel, tau_span)solvers — Euler, RK4, RK45, Adams-Bashforth, implicit methodssystems — system of ODEs interfacebvp — boundary value problems (shooting method, collocation)euler(f, y0, t0, tf, dt)rk4(f, y0, t0, tf, dt)rk45_adaptive(f, y0, t0, tf, tol, dt_init)adams_bashforth4(f, y0, t_span, dt)shooting_method(f, ya, yb, t_span)solve_bvp(f, bc, t_span, n_points)gradient — gradient descent, Adam, L-BFGS, conjugate gradientconstrained — Lagrangian, interior-point, sequential quadratic programmingevolutionary — genetic algorithm, differential evolution, CMA-ESmetaheuristic — simulated annealing, particle swarm, tabu searchgradient_descent(f, grad_f, x0, lr, max_iter)adam_optimizer(f, grad_f, x0, params)lbfgs(f, grad_f, x0, max_iter)conjugate_gradient(a, b) — linear system solvergenetic_algorithm(fitness, bounds, pop_size, generations)simulated_annealing(f, x0, t_init, cooling)particle_swarm(f, bounds, n_particles, max_iter)finite_diff — finite difference schemes (explicit, implicit, Crank-Nicolson)diffusion — heat equation (1D/2D/3D), reaction-diffusionwave — wave equation (1D/2D), SH waveslaplace — Laplace/Poisson equation, SOR, multigridheat_equation_1d_explicit(u0, alpha, dx, dt, steps)heat_equation_2d_adi(u0, alpha, dx, dy, dt, steps)crank_nicolson_diffusion(u0, alpha, dx, dt, steps)wave_equation_1d(u0, v0, c, dx, dt, steps)laplace_2d_sor(boundary, omega, tol)poisson_2d(rhs, dx, dy, boundary)poly — Polynomial type, evaluation, arithmetic, derivative, integralroots — root finding (Durand-Kerner, Jenkins-Traub, Bairstow)special — Legendre, Hermite, Laguerre, Chebyshev polynomialsPolynomial::new(coeffs), poly_eval(poly, x)poly_add(p, q), poly_mul(p, q), poly_div(p, q)poly_derivative(poly), poly_integral(poly)poly_roots(poly) → complex rootslegendre(n, x), hermite(n, x), chebyshev_t(n, x), laguerre(n, x)distributions — PDF, CDF, quantile for Normal, Poisson, Binomial, etc.sampling — Box-Muller, rejection sampling, inverse CDFmarkov — transition matrices, stationary distribution, MCMCmonte_carlo — MC estimation, variance reduction, quasi-randomnormal_pdf(x, mu, sigma), normal_cdf(x, mu, sigma)poisson_pmf(k, lambda), binomial_pmf(k, n, p)sample_normal(mu, sigma), sample_poisson(lambda)metropolis_hastings(target, proposal, x0, n_samples)markov_stationary(transition_matrix)filters — FIR/IIR filters, Butterworth, Chebyshev, window functionsspectral — power spectral density, spectrogram, periodogramconvolution — 1D/2D linear/circular convolution, cross-correlationwavelets — DWT, IDWT, Daubechies, Haar waveletsfir_filter(signal, coeffs), iir_filter(signal, b, a)butterworth_lowpass(order, cutoff_freq)hamming_window(n), hann_window(n), blackman_window(n)psd_welch(signal, fs, nperseg)convolve(signal, kernel), correlate(x, y)dwt(signal, wavelet), idwt(coeffs, wavelet)csr — Compressed Sparse Row matrix storageops — sparse matrix arithmetic, transpose, normssolvers — CG, GMRES, sparse LU, iterative solversCsrMatrix::new(rows, cols, data, indices, indptr)sparse_add(a, b), sparse_mul(a, b)sparse_mv(matrix, vec) — matrix-vector productsparse_transpose(matrix)conjugate_gradient_sparse(a, b, x0, tol)gmres(a, b, x0, restart, tol)descriptive — mean, variance, skewness, kurtosis, quantilesdistributions — t, chi², F, KS distributions and testshypothesis — t-test, ANOVA, chi-square test, Wilcoxonregression — linear, polynomial, logistic regression, R²mean(data), variance(data), std_dev(data)median(data), percentile(data, p), iqr(data)skewness(data), kurtosis(data)t_test_one_sample(data, mu0), t_test_two_sample(a, b)chi_square_test(observed, expected)linear_regression(xs, ys) → (slope, intercept, r_squared)pearson_correlation(x, y), spearman_correlation(x, y)storage — N-dimensional dense tensor storageops — element-wise arithmetic, contraction, outer productlinalg — tensor norms, trace, symmetric/antisymmetric partsdecompose — Tucker decomposition, CP decompositiondisplay — pretty-print tensorsTensor::new(shape, data), Tensor::zeros(shape), Tensor::ones(shape)tensor_add(a, b), tensor_mul_scalar(t, s)tensor_contract(a, b, axes) — Einstein summationtensor_outer(a, b), tensor_transpose(t, perm)tucker_decompose(tensor, ranks), cp_decompose(tensor, rank)types — Vec2, Vec3, VecN with arithmetic operatorsops — dot product, cross product, norm, normalizationfields — gradient, divergence, curl, Laplacianintegrators — Euler, RK4 integration of vector field ODEssim — particle simulation utilitiesVec3::new(x, y, z), dot(a, b), cross(a, b), norm(v)gradient(f, point, h), divergence(f, point, h)curl(f, point, h), laplacian(f, point, h)euler_step(field, pos, dt), rk4_step(field, pos, dt)All mathematics functions are wired through:
src/hub/engine/dispatch/maths.rsuse sciforge::hub::prelude::*;
let exp = Experiment::new(DomainType::Maths, "linear_regression")
.param("xs", ParameterValue::Vector(vec![1.0, 2.0, 3.0]))
.param("ys", ParameterValue::Vector(vec![2.1, 4.0, 5.9]));
let out = ExperimentRunner::new().run(&exp)?;
This page documents the source implementation behind sciforge::meteorology, including file layout and Hub dispatch wiring.
src/meteorology/.pub(crate) in src/lib.rs and is not part of the external crate API.sciforge::hub API for these computations.src/meteorology/src/meteorology/mod.rssrc/hub/engine/dispatch/meteorology.rsmod.rs and targeted pub use exports..rs file implements a coherent block of equations and functions.ExperimentRunner.atmosphere — atmospheric structure, thermodynamic propertiesdynamics — mesoscale and synoptic dynamics, Coriolis effectsprecipitation — rainfall statistics, evapotranspiration, runoffradiation — solar and terrestrial radiation, climate forcingbarometric_formula(p0, m, g, h, t) — pressure at altitude h (hypsometric equation)scale_height(t, m, g) — atmospheric scale height H = RT/(Mg)lapse_rate_dry() — dry adiabatic lapse rate (9.8 K/km, constant)lapse_rate_moist(t, l_v, r_s) — saturated adiabatic lapse ratepotential_temperature(t, p, p0) — θ = T(p₀/p)^(R/cp)virtual_temperature(t, r) — Tv = T(1 + 0.608r)mixing_ratio(e, p) — water vapor mixing ratio ω = 0.622 e/(p − e)saturation_vapor_pressure(t_celsius) — Magnus formula es(T)relative_humidity(e, es) — RH = e / esdew_point(t, rh) — dew point from temperature and relative humiditydensity_altitude(pressure_altitude, temperature_c) — density altitude (aviation)brunt_vaisala_frequency(g, theta, dtheta_dz) — atmospheric buoyancy frequency Ncoriolis_parameter(latitude, omega) — f = 2Ω sin(φ)geostrophic_wind(dp_dx, dp_dy, rho, f) → (u_g, v_g) geostrophic wind componentsrossby_number(u, l, f) — Ro = U / (fL)rossby_wave_speed(beta, k) — phase speed of Rossby wavethermal_wind(f, delta_t, delta_x, t_mean) — thermal wind shearpotential_vorticity(f, dtheta_dp) — Ertel potential vorticityekman_depth(nu, f) — Ekman layer depthrichardson_number(n2, du_dz) — Ri = N² / (∂u/∂z)²rossby_deformation_radius(n, h, f) — Ld = NH / fcyclone_gradient_wind(r, f, dp_dr, rho) — gradient wind balance in a cyclonerain_rate_marshall_palmer(z) — rainfall rate R from radar reflectivity Z (Marshall-Palmer)radar_reflectivity(rain_rate) — Z from R (inverse Marshall-Palmer)terminal_velocity_raindrop(diameter_mm) — drop terminal fall speedthornthwaite_pet(t_mean, heat_index, day_length_hours) — Thornthwaite PETpenman_evaporation(delta, rn, gamma, ea, u) — Penman open-water evaporationintensity_duration_frequency(a, b, duration, return_period) — IDF curve valuescs_curve_number_runoff(p, cn) — SCS-CN runoff depth from rainfall depthrational_method_runoff(c, i, a) — Q = CiA peak dischargeunit_hydrograph_peak(a, tp) — SCS synthetic unit hydrograph peakantecedent_precipitation_index(prev_api, rainfall, k) — API decay modelstefan_boltzmann_flux(t) — F = σT⁴ (W/m²)solar_constant() — Solar constant S₀ ≈ 1361 W/m²albedo_reflected(solar_flux, albedo) — reflected shortwave radiationeffective_temperature(solar_flux, albedo) — planetary equilibrium temperaturegreenhouse_effect(t_surface, t_effective) — greenhouse warming ΔToptical_depth(absorption_coeff, path_length) — τ = k × dzbeer_lambert(i0, tau) — I = I₀ × e^(-τ)planck_function(wavelength, t) — Planck spectral radiance Bλ(T)solar_zenith_angle(lat, declination, hour_angle) — cos(θz)radiative_forcing_co2(c, c0) — ΔF = 5.35 ln(c/c₀) W/m²climate_sensitivity(delta_t, delta_f) — λ = ΔT/ΔF (K per W/m²)outgoing_longwave_radiation(t, emissivity) — OLR = ε σ T⁴All meteorology functions are wired through:
src/hub/engine/dispatch/meteorology.rsuse sciforge::hub::prelude::*;
let exp = Experiment::new(DomainType::Meteorology, "saturation_vapor_pressure")
.param("t_celsius", ParameterValue::Scalar(25.0));
let out = ExperimentRunner::new().run(&exp)?;
This page documents the source implementation behind sciforge::parser, including lexer/parser/value/error layering per format.
src/parser/.parser is public from src/lib.rs (pub mod parser;).sciforge::parser::{csv,json,yaml,markdown,html}.src/parser/src/parser/mod.rs(n/a - parser is direct)mod.rs and targeted pub use exports.csv — RFC-4180 CSV parserjson — RFC-8259 JSON parseryaml — YAML 1.2 subset parsermarkdown — CommonMark Markdown parserhtml — HTML5-like parserAll parsers share the same design philosophy:
Result<*Value<'_>, *Error> with lifetime tied to inputvalidate_* for syntax checking without full allocation*_with_limits variants for resource-bounded parsing| Struct | Description |
|---|---|
CsvParser<'a> | Streaming parser state over a byte slice |
CsvLimits | Configurable limits: max rows, max columns, max cell length |
CsvError | Parse error with position info |
CsvErrorPosition | Line and column of the parse error |
Cursor<'a> | Low-level byte cursor used internally |
use sciforge::parser::csv::{parse_csv, write_csv};
let data = b"name,value\nfoo,1.0\nbar,2.5";
let csv = parse_csv(data)?;
let out = write_csv(&["name", "value"], &rows);
| Struct | Description |
|---|---|
JsonParser<'a> | Recursive descent JSON parser |
JsonLimits | Max nesting depth, max string length, max array/object size |
JsonError | Parse error |
JsonErrorPosition | Byte offset of the error |
use sciforge::parser::json::parse_json;
let data = b"{\"x\": 3.14, \"label\": \"pi\"}";
let val = parse_json(data)?;
| Struct | Description |
|---|---|
YamlParser<'a> | Line-oriented YAML parser |
YamlLimits | Max nesting, max line count |
YamlError | Parse error |
YamlErrorPosition | Line number of the error |
YamlLine<'a> | Parsed representation of a single YAML line |
LineCursor<'a> | Low-level cursor over lines |
parse_scalar<'a>(raw: &'a str, offset: usize) -> Result<YamlValue<'a>, YamlError> — parse a bare scalar string| Struct | Description |
|---|---|
MdParser<'a> | CommonMark Markdown parser (block + inline) |
MdLimits | Max heading depth, max nesting, max line count |
MdError | Parse error |
MdErrorPosition | Line and column of the error |
MdLine<'a> | Parsed line-level Markdown element |
LineCursor<'a> | Low-level line cursor |
validate_inline(text: &str, base_offset: usize) -> Result<(), MdError> — validate inline markup only| Struct | Description |
|---|---|
HtmlParser<'a> | Tag-based HTML parser (DOM-tree output) |
HtmlLimits | Max nesting depth, max attribute count |
HtmlError | Parse error |
HtmlErrorPosition | Line and column of the error |
Cursor<'a> | Low-level byte cursor |
validate_entity(cursor: &mut Cursor<'_>) -> Result<(), HtmlError> — validate a single HTML entityThis page documents the source implementation behind sciforge::physics, including module layout and Hub dispatch wiring.
src/physics/.pub(crate) in src/lib.rs and is not part of the external crate API.sciforge::hub API for these computations.src/physics/src/physics/mod.rssrc/hub/engine/dispatch/physics.rsmod.rs and targeted pub use exports..rs file implements a coherent block of equations and functions.ExperimentRunner.acousticselectrodynamicselectronicsfluid_mechanicsmaterialsnucleosynthesisopticsquantumrelativitysolid_mechanicsthermodynamicsabsorption — sound absorption coefficients, acoustic impedancedoppler — Doppler shift, observer/source velocity effectspropagation — wave propagation, attenuation, speed in mediaresonance — standing waves, resonance frequencies, Q-factordoppler_frequency(f0, v_sound, v_observer, v_source)acoustic_impedance(density, speed)sound_intensity_level(intensity, reference)resonance_frequency(length, mode, speed)absorption_coefficient(frequency, medium_params)circuits — RC/RL/RLC, impedance, powerfields — electric/magnetic field computationswaves — electromagnetic wave properties, Poynting vectorcapacitor_charge(capacitance, voltage)inductor_energy(inductance, current)rc_time_constant(resistance, capacitance)rlc_resonance(inductance, capacitance)electric_field_point_charge(charge, distance)magnetic_field_wire(current, distance)poynting_vector(e_field, b_field)amplifiers — gain, bandwidth, noise figurecircuits — Kirchhoff laws, node analysis, thevenin/nortondigital — logic gates, binary operationssemiconductor_devices — diodes, transistors, MOSFETvoltage_divider(r1, r2, vin)op_amp_gain_inverting(rf, rin)op_amp_gain_non_inverting(rf, rin)bjt_current_gain(ic, ib)diode_shockley(is, vd, vt)mosfet_drain_current(k, vgs, vth, vds)boundary_layer — Blasius, Reynolds, displacement/momentum thicknessflow — continuity, Bernoulli, pipe flow, Poiseuilleturbulence — Reynolds stress, turbulence intensity, mixing lengthwaves — surface waves, dispersion, wave speedreynolds_number(density, velocity, length, viscosity)bernoulli_pressure(density, v1, v2, h1, h2)hagen_poiseuille(viscosity, length, radius, delta_p)drag_force(cd, density, velocity, area)froude_number(velocity, length)darcy_weisbach(f, length, diameter, velocity, g)crystallography — lattice parameters, Miller indices, diffractiondiffusion — Fick's laws, diffusion coefficientphases — phase diagrams, lever rule, Gibbs phase rulesemiconductors — carrier density, bandgap, dopingbragg_diffraction(n, lambda, d_spacing)ficks_first_law(diffusivity, gradient)ficks_second_law_1d(diffusivity, concentration, dx, dt)carrier_density(nc, energy_gap, temperature)debye_length(epsilon, temperature, carrier_density)decay — radioactive decay, half-life, activitynuclide — binding energy, nuclear radius, separation energyprocesses — pp-chain, CNO cycle, r/s-process ratesreactions — Q-value, cross-section, reaction ratesstellar — nuclear burning stages, energy generationradioactive_decay(n0, half_life, time)decay_constant(half_life)activity(n_atoms, decay_constant)binding_energy(mass_number, proton_number, mass)q_value(mass_reactants, mass_products)nuclear_radius(mass_number)gamow_energy(z1, z2, reduced_mass)diffraction — single/double slit, grating equationinterference — thin film, Michelson, Young's experimentpolarization — Malus's law, Brewster angle, Stokes parametersrefraction — Snell's law, critical angle, refractive index dispersionsnell_refraction(n1, theta1, n2)critical_angle(n1, n2)brewster_angle(n1, n2)malus_law(i0, theta)double_slit_intensity(a, d, lambda, theta)diffraction_grating(m, lambda, d)thin_film_condition(n, thickness, lambda)angular — angular momentum, Clebsch-Gordan, ladder operatorsinformation — density matrix, entanglement entropy, fidelityoperators — expectation values, commutators, Hermitian operatorsperturbation — first/second-order energy correctionsspin — spin operators, Pauli matrices, spin statessystems — harmonic oscillator, hydrogen atom, particle in a boxwavefunctions — normalization, probability density, overlap integralsparticle_in_box_energy(n, length, mass)harmonic_oscillator_energy(n, omega)hydrogen_energy_level(n)expectation_value(wavefunction, operator)commutator(op_a, op_b)first_order_energy_correction(psi, h_prime)entanglement_entropy(density_matrix)dynamics — relativistic energy, momentum, four-vectorskinematics — time dilation, length contraction, velocity additionlorentz — Lorentz factor, boosts, transformationslorentz_factor(velocity)time_dilation(proper_time, velocity)length_contraction(proper_length, velocity)relativistic_energy(mass, velocity)relativistic_momentum(mass, velocity)velocity_addition(v1, v2)doppler_relativistic(frequency, velocity)elasticity — Hooke's law, Young's modulus, Poisson ratiofracture — stress intensity factor, fracture toughness, crack growthplasticity — yield criteria, strain hardening, plastic deformationstress — stress/strain tensors, principal stresses, von Miseshookes_law(youngs_modulus, strain)von_mises_stress(s11, s22, s33, s12, s23, s13)principal_stresses_2d(sx, sy, txy)stress_intensity_factor(stress, crack_length)strain_energy_density(stress, strain)thermal_stress(youngs_modulus, alpha, delta_t)equations — equations of state (ideal gas, van der Waals, Redlich-Kwong)processes — isothermal, adiabatic, isobaric, isochoric work/heatstatistical — Boltzmann factor, partition function, entropyideal_gas_pressure(n, r, temperature, volume)van_der_waals(n, a, b, temperature, volume)isothermal_work(n, r, temperature, v1, v2)adiabatic_work(gamma, p1, v1, v2)carnot_efficiency(t_hot, t_cold)boltzmann_factor(energy, temperature)partition_function(energies, temperature)All physics functions are wired through:
src/hub/engine/dispatch/physics.rsuse sciforge::hub::prelude::*;
let exp = Experiment::new(DomainType::Physics, "lorentz_factor")
.param("velocity", ParameterValue::Scalar(2.0e8));
let out = ExperimentRunner::new().run(&exp)?;
Copyright © 2026 Rayan
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
📦 This license applies to the entire SciForge crate and all its modules.
Interactive HTML dashboards generated by the Benchmark and Parser modules.
These outputs are tied to the test pipeline: running cargo test produces and validates result artifacts under output/.