SciForge

A comprehensive scientific computing library written in pure Rust — zero dependencies, 11 modules, 48 600+ lines of code.

Rust Edition 2024 MIT License Zero Dependencies 306 Tests Passing
11
Modules
131
Submodules
5074
Public APIs
575
Source Files
48 612
Lines of Code
306
Tests
118
Elements
0
Dependencies

Key Features

Pure Rust, Zero Dependencies
Built entirely from scratch using only the standard library — no external crates, no hidden costs, fully auditable.
🧬
11 Scientific Domains
Constants, Mathematics, Physics, Chemistry, Biology, Geology, Astronomy, Meteorology, Hub, Benchmark, and Parser.
🌌
Cosmology + Hub Dispatch
Direct E(z) models, H(z), and comoving/luminosity/angular-diameter distances are available and wired through Hub astronomy dispatch.
🧪
5074 Public APIs
Comprehensive function coverage across all scientific domains — from matrix operations to protein folding, orbital mechanics to enzyme kinetics.
⚛️
118 Elements — IUPAC 2024
Complete periodic table with atomic mass, electron configuration, isotopes, oxidation states, and physical properties.
📊
Benchmark Pipeline
Full engine with encode/decode, simulation, reporting, and interactive HTML export with SVG charts and dark theme.
📄
Multi-Format Parser
CSV, JSON, YAML, Markdown, and HTML parsing — all from scratch, zero dependencies, with a unified API surface.

Architecture

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/`).

Module Size (Public APIs)

Constants57Mathematics977Physics636Chemistry462Biology2474Geology44Astronomy49Meteorology44Hub212Benchmark29Parser90

Submodule Distribution

5 17 11 26 44 4 4 4 5 6 5 Constants (5) Mathematics (17) Physics (11) Chemistry (26) Biology (44) Geology (4) Astronomy (4) Meteorology (4) Hub (5) Benchmark (6) Parser (5)

Design Philosophy

Every line of SciForge follows these non-negotiable principles:

  • Zero external dependencies — only std
  • Zero comments — the code speaks for itself
  • Zero clippy warnings — strict lint compliance
  • No #[allow] attributes — ever
  • Rust Edition 2024 — latest language features
  • All tests must pass before any commit
  • Pure functions when possible — minimal side effects
  • No unsafe code — full memory safety guaranteed

All Modules

Constants
5 submodules57 public APIs30 tests
Tested
Mathematics
17 submodules977 public APIs21 tests
Tested
Physics
11 submodules636 public APIs33 tests
Tested
Chemistry
26 submodules462 public APIs24 tests
Tested
Biology
44 submodules2474 public APIs18 tests
Tested
Geology
4 submodules44 public APIs17 tests
Tested
Astronomy
4 submodules49 public APIs21 tests
Tested
Meteorology
4 submodules44 public APIs18 tests
Tested
Hub
5 submodules212 public APIs30 tests
Tested
Benchmark
6 submodules29 public APIs28 tests
Tested
Parser
5 submodules90 public APIs66 tests
Tested

Module Details

ModuleSubmodulesPublic APIsTestsDocumentationSemver
Constants55730
Mathematics1797721
Physics1163633
Chemistry2646224
Biology44247418
Geology44417
Astronomy44921
Meteorology44418
Hub521230
Benchmark62928
Parser59066

Project Progress

Tracking semver validation, documentation coverage, and test coverage across all 11 modules.

100%

Tests

11/11 modules

100%

Documentation

11/11 modules

0%

Semver

0/11 modules

Module Readiness

ModuleSubmodulesPublic APIsTestsDocumentationSemverScore
Constants557✓ 30✓ done✗ pending2/3
Mathematics17977✓ 21✓ done✗ pending2/3
Physics11636✓ 33✓ done✗ pending2/3
Chemistry26462✓ 24✓ done✗ pending2/3
Biology442474✓ 18✓ done✗ pending2/3
Geology444✓ 17✓ done✗ pending2/3
Astronomy449✓ 21✓ done✗ pending2/3
Meteorology444✓ 18✓ done✗ pending2/3
Hub5212✓ 30✓ done✗ pending2/3
Benchmark629✓ 28✓ done✗ pending2/3
Parser590✓ 66✓ done✗ pending2/3

Milestone Targets

Test Coverage
11 / 11 modules (306 tests)
Documentation
11 / 11 modules
Semver Validation
0 / 11 modules
Total Tests
306 / 1 000 target
Public APIs
5074 / 5000 target (reached)
Periodic Table
118 / 118 elements
Tested Documented Semver Validated Implemented

Project Documentation

Interactive documentation viewer: select a tab, then choose a document from the left panel to render it directly in this page.

SciForge

A comprehensive scientific computing library written in pure Rust.

License: MIT

Rust Edition

Dependencies

Overview

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.

  • Zero external dependencies
  • 629 Rust source files across library code, tests, and tooling
  • Expanded test coverage across benchmark, parser, scientific domains, Hub, and validation suites
  • 118 elements — full periodic table dataset (IUPAC 2024)

SciForge currently targets crate version 0.0.2.

Cosmology Highlights

The astronomy cosmology stack now includes:

  • Direct E(z) parameterizations: general, flat LCDM, LCDM with radiation, wCDM, and CPL (w0-wa)
  • Hubble parameter evaluation at redshift: H(z) = H0 * E(z) (general and LCDM helpers)
  • Comoving, luminosity, and angular-diameter distances from redshift (LCDM, general curved models, wCDM/CPL variants)
  • LCDM analytical shortcuts where applicable (for example, analytical age of the universe in flat LCDM)
  • Direct Hub dispatch wiring for all these cosmology functions via DomainType::Astronomy

This enables running cosmology workflows through the unified Hub execution path without bypassing domain dispatch.

Modules

ModuleSubmodulesDescription
Constants5Fundamental, astrophysical, atomic constants, unit conversions, element data
Mathematics17Complex numbers, tensors, linear algebra, FFT, ODE/PDE solvers, statistics, optimization
Physics11Relativity, quantum mechanics, thermodynamics, electrodynamics, optics, acoustics
Chemistry26Kinetics, electrochemistry, organic/inorganic, spectroscopy, polymers, quantum chemistry
Biology44Genetics, neuroscience, ecology, evolution, pharmacology, genomics, proteomics
Geology4Seismology, radiometric dating, petrology, plate tectonics
Astronomy4Orbital mechanics, stellar astrophysics, cosmology, celestial mechanics
Meteorology4Atmospheric modeling, radiation transfer, dynamics, precipitation
Hub5Central dispatch API, domain engine, tools, prelude
Benchmark6Benchmark engine, binary encode/decode, simulation, reporting, multi-format export
Parser5CSV, JSON, YAML, Markdown, HTML parsing and validation

Quick Start

Add SciForge to your Cargo.toml:

[dependencies]
sciforge = "0.0.2"

Example

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)?;

Documentation

SciForge documentation is split into two complementary layers:

  • docs/modules/ — scientific explanations, assumptions, and equations
  • docs/code/ — source layout, API surfaces, and execution flow
  • docs/Summary.md — entry point mapping each module guide to its matching code guide

Use docs/modules/ first for scientific context, then docs/code/ for implementation-level details.

Benchmark Export

The benchmark module generates a complete interactive HTML dashboard featuring:

  • IUPAC 2024 periodic table grid with category-colored gradient cells
  • Click-to-detail element cards with full metrics
  • SVG chart visualizations (category distribution, timing analysis, top 10 fastest/slowest)
  • Tabbed file browser for CSV, JSON, YAML, TOML exports
  • Markdown summary report

Periodic Table Data

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/

Building

cargo build

Testing

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.

Linting

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.

Project Structure

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

Contributing

See Contributing.md for guidelines.

Roadmap

See ComingSoon.md for the 0.0.1 roadmap baseline.

Changelog

See ChangeLog.md for version history.

License

MIT

Changelog

All notable changes to SciForge are documented in this file.

[0.0.2] - 2026-03-24

Documentation

  • Consolidated and normalized documentation under docs/
  • Structured the documentation into paired guides:
  • docs/modules/ for scientific model explanations
  • docs/code/ for source and API explanations
  • Updated docs/Summary.md to serve as the documentation entry point

Testing

  • Added dedicated scientific validation and scientific property-based suites
  • Expanded integration coverage across constants, maths, physics, chemistry, biology, geology, astronomy, meteorology, and Hub workflows
  • Added validation artifacts under output/validation/

Astronomy and Hub

  • Extended cosmology coverage with direct E(z) parameterizations and H(z) helpers
  • Expanded redshift-distance cosmology utilities and Hub astronomy dispatch integration

Project Metadata

  • Bumped crate version to 0.0.2
  • Updated top-level project documentation to reflect the current version and test architecture

[0.0.1] - 2026-03-23

Project Foundation

  • Initialized sciforge crate (Rust edition 2024, zero external dependencies)
  • Established 11-module architecture: constants, maths, physics, chemistry, biology, geology, astronomy, meteorology, benchmark, parser, hub
  • 575 source files, 48 600+ lines of Rust across all modules

Constants

  • Fundamental physical constants (CODATA values)
  • Astrophysical constants
  • Atomic constants
  • Unit conversion factors
  • Full periodic table element data (118 elements)

Mathematics (17 submodules)

  • Complex number arithmetic
  • Tensor, vector, polynomial types
  • Linear algebra and sparse matrix operations
  • Non-Euclidean geometry
  • Graph theory
  • Interpolation and numerical integration
  • ODE and PDE solvers
  • FFT (Fast Fourier Transform)
  • Optimization algorithms
  • Statistics and probability distributions
  • Signal processing

Physics (11 submodules)

  • Special and general relativity
  • Quantum mechanics
  • Thermodynamics
  • Classical electrodynamics
  • Fluid and solid mechanics
  • Optics and acoustics
  • Nucleosynthesis
  • Electronics
  • Materials science

Chemistry (26 submodules)

  • Reaction kinetics and chemical equilibrium
  • Electrochemistry and thermochemistry
  • Molecular and organic/inorganic chemistry
  • Analytical and quantum chemistry
  • Solutions, gas laws, acid-base equilibria
  • Nuclear chemistry and photochemistry
  • Polymers, spectroscopy, surface chemistry
  • Crystallography and stoichiometry
  • Colloids, solid-state, computational chemistry
  • Reaction engineering and transport phenomena
  • Environmental and green chemistry

Biology (44 submodules)

  • Population dynamics, genetics, genomics, proteomics
  • Enzyme kinetics, cell biology, developmental biology
  • Neuroscience, pharmacology, immunology
  • Ecology, evolution, phylogenetics, ethology
  • Biomechanics, biophysics, bioenergetics, biostatistics
  • Structural biology, systems biology, synthetic biology
  • Epigenetics, bioinformatics, biogeography
  • Microbiology, virology, parasitology, mycology
  • Endocrinology, physiology, plant biology, chronobiology
  • Toxicology, radiobiology, cryobiology, nutrition
  • Cancer biology, marine biology, aging, reproduction
  • Stem cell biology, bioelectricity, tissue engineering, paleobiology

Geology (4 submodules)

  • Seismology
  • Radiometric dating
  • Petrology
  • Plate tectonics

Astronomy (4 submodules)

  • Orbital mechanics
  • Stellar astrophysics
  • Cosmology
  • Celestial mechanics

Meteorology (4 submodules)

  • Atmospheric modeling
  • Radiation transfer
  • Atmospheric dynamics
  • Precipitation

Hub

  • Central dispatch API with api, domain, engine, tools submodules
  • Prelude module for ergonomic imports

Benchmark (6 submodules)

  • engine — benchmark runner with BenchmarkMetrics (iterations, timing, throughput)
  • encode / decode — compact binary .bmk format for benchmark results
  • simulation — deterministic benchmark simulation for all 118 elements
  • report — JSON, YAML, TOML report generation with tagged metadata
  • export — multi-format export pipeline:
  • Per-element and aggregate CSV, JSON, YAML, TOML, BMK files
  • Per-category grouped exports
  • Interactive HTML dashboard:
  • IUPAC 2024 periodic table grid (La/Ac in main body, groups 1-18)
  • Dark gradient theme with category-colored element cells
  • Hover zoom, click-to-detail card with full metrics
  • CSV displayed as interactive HTML table
  • SVG chart visualizations (category distribution, timing, top 10 fastest/slowest, statistics)
  • Tabbed file browser for all export formats
  • Legend with gradient swatches
  • Markdown summary report
  • 28 tests covering engine, encode/decode roundtrip, simulation, report, and export

Parser (5 submodules)

  • csv — CSV reader/writer with configurable delimiters and quoting
  • json — JSON parser and validator
  • yaml — YAML parser and validator
  • markdown — Markdown parser and validator
  • html — HTML parser and validator
  • 66 tests covering parsing, validation, edge cases, and file generation
  • Generated sample files: CSV (20 elements), JSON, YAML, Markdown, HTML (dark gradient theme)

Periodic Table Data

  • 118 element data files organized by category under tableau-periodique/:
  • Non-metals, noble gases, halogens, metalloids
  • Alkali metals, alkaline earth metals
  • Transition metals, post-transition metals
  • Lanthanides, actinides, superheavy elements

Testing

  • 94 total tests (28 benchmark + 66 parser), all passing
  • Zero clippy warnings
  • Zero `#[allow]` directives

Coming Soon

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.

Legend

  • Implemented: delivered and used in the codebase
  • Partial: present but incomplete or not generalized
  • Remaining: not finalized yet

Current State (According to 0.0.1 Version)

AreaItemStatusCode/Docs EvidenceRemaining Coverage
DocumentationFull API reference with input/output examples for every public functionPartialdocs/code/*.md, docs/modules/*.mdGenerate an exhaustive reference for all public functions (benchmark, hub, parser) with runnable examples
DocumentationTutorials and guided workflows (simulation, data analysis, cross-domain)PartialREADME.md, docs/Add end-to-end scenario tutorials with expected inputs/outputs
DocumentationModule-level scientific model guidesImplementeddocs/modules/Astronomy.md, docs/modules/Physics.md, docs/modules/Biology.md, and othersOngoing maintenance and enrichment
Extended TestingUnit and integration tests for all scientific modulesPartialtests/constants/*, tests/maths/*, tests/physics/*, tests/chemistry/*, tests/biology/*, tests/geology/*, tests/astronomy/*, tests/meteorology/*Close remaining coverage gaps in less-tested submodules
Extended TestingProperty-style testing and edge-case validationImplementedtests/scientific_properties.rs, tests/scientific_validation.rsExpand invariant coverage per domain
Extended TestingCross-module integration testsImplementedtests/hub/cross_domain.rs, tests/hub/main.rsAdd more multi-step cross-domain scenarios
Hub ExpansionUnified dispatch API through HubImplementedsrc/hub/engine/dispatch/*.rsContinue signature normalization
Hub ExpansionErgonomic prelude re-exportsImplementedsrc/hub/prelude.rsStabilize naming conventions
Hub ExpansionDomain query engine and tool pipelinesImplementedsrc/hub/engine/query.rs, src/hub/engine/pipeline/flow.rs, src/hub/engine/worker/scheduler.rsAdd more predefined pipeline templates
Computational EnhancementsPerformance benchmarking across scientific modulesPartialsrc/benchmark/*, tests/benchmark.rs, output/*/bmk/Complete a benchmark matrix for all major subdomains
Computational EnhancementsMemory-optimized structures for large-scale workloadsPartialsrc/hub/tools/arena.rs, src/hub/tools/profiler.rsAdd systematic memory/performance evidence
Computational EnhancementsDeterministic and reproducible execution pathsImplementedsrc/hub/tools/deterministic.rsExtend reproducibility assertions in tests
Future FeaturesInteractive visualization utilitiesImplementedsrc/hub/tools/visualization.rs, src/benchmark/export.rsAdd more visualization templates
Future FeaturesExtended cross-domain analysis tools (astrochem, geophysics, bioinformatics, etc.)Partialsrc/biology/bioinformatics/*, cross-domain dispatch paths in src/hub/engine/dispatch/*Expand explicit coupled-domain coverage (astrochem/geophysics)
Future FeaturesAdditional export formats and reportingImplementedHTML/MD/CSV/JSON/YAML/TOML export via src/benchmark/export.rs and output/Add cross-format validation schemas
Future FeaturesAutomated scientific validation pipelinePartialtests/scientific_validation.rs + output/validation/ artifactsFormalize a single pipeline command with gating thresholds

Quantitative Summary

StatusCount
Implemented9
Partial8
Remaining0

Priority Backlog (Remaining Work For 0.0.3 Version)

  1. Refactor files containing more than 600 lines to improve maintainability, readability, and long-term evolution (split 'src/benchmark/*/', 'tests/parsersrs' 'and tests/benchmark.rs').
  2. Produce a complete API reference focused on real public functions.
  3. Add reproducible guided tutorials (Hub + Parser + Benchmark).
  4. Complete test coverage in less-covered scientific submodules.
  5. Define a single "scientific validation pipeline" command with blocking thresholds.
  6. Expand coupled cross-domain scenarios (astrochemistry/geophysics) with numeric validations.
  7. Readable .bmk into html files.
  8. Small demo usable to test all the crate.

Next Priorities (0.0.4 Version)

  1. Add uncertainty quantification workflows (Monte Carlo, bootstrap, error propagation) for scientific models.
  2. Add heuristic optimization algorithms (simulated annealing, genetic algorithms, particle swarm optimization).
  3. Add wavelet and spectral analysis tools for astronomy, seismology, meteorology, and signal-heavy domains.
  4. Add lightweight Bayesian inference utilities for data exploration and inverse-problem workflows.
  5. Add PCA and clustering utilities for dimensionality reduction, structure discovery, and exploratory analysis.
  6. Adding all the following constants and functions:

1️⃣ Fundamental / Quantum Physics

ConstantSymbolValueUnitModule
Fermi constantG_F1.1663787×10⁻⁵GeV⁻²fundamental
Strong coupling constantALPHA_S0.1181dimensionlessfundamental
Muon massMUON_MASS1.883531627×10⁻²⁸kgatomic
Tau massTAU_MASS3.16747×10⁻²⁷kgatomic
Neutrino massNEUTRINO_MASS≤2.2×10⁻³⁶kgatomic
Rydberg constantR_INF10973731.56816m⁻¹atomic

2️⃣ Astronomy / Cosmology

ConstantSymbolValueUnitModule
Solar densitySOLAR_DENSITY1.408g/cm³astro
Solar surface gravitySOLAR_GRAVITY274m/s²astro
Earth surface gravityEARTH_GRAVITY9.80665m/s²astro
Mars radiusMARS_RADIUS3.3895×10⁶mastro
Mars massMARS_MASS6.417×10²³kgastro
Cosmological constantCOSMOLOGICAL_LAMBDA1.1056×10⁻⁵²m⁻²astro
DayDAY86400sunits
Julian yearJULIAN_YEAR365.25×DAYsunits

3️⃣ Chemistry / Elements

PropertySymbolValueUnitModule
Standard densityELEMENT_DENSITY_Zvariableg/cm³elements
Melting pointELEMENT_MELTING_ZvariableKelements
Boiling pointELEMENT_BOILING_ZvariableKelements
Standard stateELEMENT_STATE_Zvariableelements
Electron configurationELEMENT_ECONFIG_Zvariableelements

4️⃣ Units / Additional Conversions

ConversionSymbolValueModule
kWh to JKWH_TO_J3.6×10⁶units
MeV to JMEV_TO_J1.60218×10⁻¹³units
Day to sDAY86400units
Year to sYEAR365.25×DAYunits

Contributing to SciForge

**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

Project Overview

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.

How to Contribute

  1. Propose your change or idea — describe the problem you want to solve or the improvement you envision.
  2. Include your suggestions for APIs — indicate what functions, structs, or modules you think are necessary or redundant.
  3. Provide examples or code snippets where possible — even small snippets or pseudocode help.

I will review your proposal and provide feedback. If approved, we can coordinate how I'll integrate it.

Types of Contributions

  • Bug fixes — identify and propose solutions to issues.
  • Optimizations — suggest ways to improve performance, memory usage, or runtime behavior.
  • New features — propose additional analysis capabilities, APIs, or tools.
  • Documentation — help clarify usage, examples, or internal logic.
  • Testing — provide sample files, expected outputs, or validation scripts.
  • Logo & visual identity — if you can improve or refine the SciForge logo, your contribution is very welcome.

Code Conventions

SciForge follows strict conventions. All contributions must adhere to:

  • Zero dependencies — no external crates allowed.
  • Zero comments — code must be self-explanatory through clear naming and structure.
  • **No `#[allow]` directives** — all clippy and compiler warnings must be resolved, not suppressed.
  • Edition 2024 — use current Rust idioms and features.
  • **Zero clippy warnings** — cargo clippy must pass cleanly.
  • **All tests pass** — cargo test must succeed (currently 94 tests: 28 benchmark + 66 parser).

Proposal Guidelines

When proposing improvements, please include:

  • A clear description of the problem or opportunity
  • The API surface you envision (functions, structs, modules)
  • Any considerations about backward compatibility or potential side effects
  • Optional: performance trade-offs or optimizations you foresee

Even rough ideas or pseudocode are welcome — detailed implementation can come later.

API Discussion

I value input on:

  • Which APIs should be public and necessary
  • Which APIs are redundant or unnecessary
  • Any abstractions that could simplify usage or improve performance

Your suggestions help shape a stable and ergonomic API for SciForge.

Testing & Validation

  • Whenever possible, provide example files and expected outputs
  • Suggest how proposed changes can be validated in sandbox or test environments
  • Testing helps ensure new contributions integrate safely and correctly

Reporting Issues

If you encounter a bug or unexpected behavior:

  1. Describe the steps to reproduce it
  2. Provide expected vs. actual behavior
  3. Include relevant environment details (OS, Rust version, platform)

Please send reports via email or the discord.

Code of Conduct

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 — Documentation

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.


Chapter 1 - Documentation Scope

Purpose

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.

Reading Strategy

  1. Start with the module page in docs/modules/ to understand the scientific scope and models.
  2. Continue with the matching page in docs/code/ to inspect the implementation layout and public-facing API.
  3. Use the repository structure overview at the end of this page to locate the relevant files quickly.

Reading Guide

Goal

This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.

How To Read This Document

  • Use the module summaries below to identify the relevant scientific area.
  • Open the paired modules/ and code/ pages depending on whether you need theory or implementation details.
  • Use the repository tree at the end as a navigation shortcut.

Conventions

  • modules/ pages focus on scientific models, assumptions, and equations.
  • code/ pages focus on source layout, exported APIs, and execution flow.
  • Paths are written relative to the repository root.

Each module has two complementary pages:

  • Modules/ — describes the scientific concepts, formulas, and phenomena the module covers. Start here to understand *what* a module models.
  • Code/ — describes the Rust API: structs, functions, inputs/outputs. Go here when you want to *use* a module.

Chapter 2 - Modules at a Glance

Astronomy

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


Benchmark

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


Biology

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


Chemistry

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


Constants

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


Geology

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


Hub

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


Mathematics

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


Meteorology

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


Parser

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


Physics

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


Chapter 3 - Repository Structure

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 — Documentation

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.


Chapter 1 - Documentation Scope

Purpose

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.

Reading Strategy

  1. Start with the module page in docs/modules/ to understand the scientific scope and models.
  2. Continue with the matching page in docs/code/ to inspect the implementation layout and public-facing API.
  3. Use the repository structure overview at the end of this page to locate the relevant files quickly.

Reading Guide

Goal

This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.

How To Read This Document

  • Use the module summaries below to identify the relevant scientific area.
  • Open the paired modules/ and code/ pages depending on whether you need theory or implementation details.
  • Use the repository tree at the end as a navigation shortcut.

Conventions

  • modules/ pages focus on scientific models, assumptions, and equations.
  • code/ pages focus on source layout, exported APIs, and execution flow.
  • Paths are written relative to the repository root.

Each module has two complementary pages:

  • Modules/ — describes the scientific concepts, formulas, and phenomena the module covers. Start here to understand *what* a module models.
  • Code/ — describes the Rust API: structs, functions, inputs/outputs. Go here when you want to *use* a module.

Chapter 2 - Modules at a Glance

Astronomy

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


Benchmark

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


Biology

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


Chemistry

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


Constants

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


Geology

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


Hub

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


Mathematics

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


Meteorology

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


Parser

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


Physics

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


Chapter 3 - Repository Structure

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

Astronomy Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Orbits

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.


2. Stellar Physics

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.


3. Cosmology

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.


4. Celestial Mechanics

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.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Benchmark Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

1. Engine

Core benchmark execution framework.

The engine defines the BenchmarkMetrics struct that captures all measurable dimensions of an experiment:

FieldTypeDescription
experiment_name&strIdentifier for the benchmark
precision&strNumeric precision label (e.g. "f64", "f32")
elapsed_msu64Total wall-clock time in milliseconds
iterationsu64Number of measured iterations
avg_time_nsf32Mean time per iteration (ns)
min_time_ns / max_time_nsf32Min/max iteration time
time_stddevf32Standard deviation of iteration times
iterations_per_secf32Throughput: $1 / \bar{t}$
samples_per_secf32Data throughput
total_flopsu64Floating-point operations counted
eval_errorf32Numerical error metric
eval_accuracyf32Accuracy score
eval_r_squaredf32Coefficient of determination $R^2$
eval_maef32Mean absolute error
logical_coresu32System 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.


2. Encode

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:

OffsetSizeField
0–34 bytesMagic number (BENCHMARK_MAGIC)
4–52 bytesFormat version (little-endian u16)
8–158 byteselapsed_ms (LE u64)
16–238 bytesiterations (LE u64)
24–318 bytesinput_samples (LE u64)
32–354 bytesavg_time_ns (LE f32)
......(all metrics fields in sequence)
164–1652 bytesexperiment name length
166–1672 bytesprecision string length
header+variableexperiment 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.


3. Decode

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:

  • Minimum buffer size ≥ BENCHMARK_HEADER_SIZE
  • Magic bytes match BENCHMARK_MAGIC
  • Version matches BENCHMARK_VERSION
  • String length fields do not exceed buffer bounds

BenchmarkMetricsView borrows string slices directly from the input buffer (zero-copy), returning &'a str references with lifetime tied to the source bytes.


4. Simulation

Physics simulation benchmarking with configurable N-body state.

The simulation framework provides:

  • **`SimState`** — Positions and velocities for $N$ bodies in 3D: `positions: Vec<[f64; 3]>`, `velocities: Vec<[f64; 3]>`, plus current simulation time and step count.
  • **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:

  • Wall-clock time per simulation step
  • Total elapsed time for the full run
  • Throughput: steps per second, bodies × steps per second
  • Scaling behavior: execution time vs. $N$ (expected $O(N^2)$ for direct N-body)

5. Report

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:

  • Summary table (all metrics as key-value rows)
  • FLOPS, accuracy, $R^2$ (when nonzero)
  • Fenced code block for the result output

HTML. Self-contained single-file report embedding the Markdown content, with inline CSS for readability.

Structured data. Additional generators produce:

  • **JSON** (generate_json_tagged): tagged key-value output with custom metadata
  • **YAML** (generate_yaml_tagged): human-readable structured output
  • **TOML** (generate_toml_tagged): configuration-style output

All string output uses safe escaping (push_escaped) to prevent injection in generated reports.


6. Export

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:

  • CSV directory with per-experiment CSV files
  • **Markdown directory** with individual .md reports
  • **HTML dashboard** with a grid layout (using grid_row/grid_col placement)
  • **Binary .bench files** with encoded metrics for machine consumption

The 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.).


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Biology Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Aging

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.


2. Bioelectricity

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.


3. Bioenergetics

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.


4. Biogeography

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.


5. Bioinformatics

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.


6. Biomechanics

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:

  • Kelvin–Voigt: $\sigma = E\varepsilon + \eta \dot{\varepsilon}$ (creep behavior)
  • Maxwell: $\dot{\varepsilon} = \dot{\sigma}/E + \sigma/\eta$ (stress relaxation)
  • Standard linear solid: combines both for realistic tissue response

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.


7. Biophysics

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.


8. Biostatistics

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$.


9. Cancer Biology

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}$.


10. Cell Biology

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).


11. Chronobiology

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.


12. Cryobiology

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.


13. Developmental Biology

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}}$.


14. Ecology

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$.


15. Endocrinology

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}]$.


16. Enzyme Kinetics

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:

  • **Competitive**: $v = V_{\max}[S] / (K_m(1 + [I]/K_i) + [S])$
  • **Uncompetitive**: $v = V_{\max}S] / (K_m + [S)$
  • **Noncompetitive**: $v = V_{\max}[S] / ((K_m + [S])(1 + [I]/K_i))$
  • Mixed: both $K_i$ and $K_i'$ differ

**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.


17. Epigenetics

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.


18. Ethology

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.


19. Evolution

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:

  • $\omega < 1$: purifying selection
  • $\omega = 1$: neutral evolution
  • $\omega > 1$: positive selection

**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).


20. Genetics

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$.


21. Genomics

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.


22. Immunology

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).


23. Marine Biology

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$$


24. Microbiology

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)$.


25. Mycology

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.


26. Neuroscience

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}}$.


27. Nutrition

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$.


28. Paleobiology

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.


29. Parasitology

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)$.


30. Pharmacology

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)$.


31. Phylogenetics

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.


32. Physiology

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.


33. Plant Biology

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).


34. Population Biology

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.


35. Proteomics

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.


36. Radiobiology

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.


37. Reproduction

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$.


38. Stem Cell Biology

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.


39. Structural Biology

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}$.


40. Synthetic Biology

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$.


41. Systems Biology

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.


42. Tissue Engineering

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}$.


43. Toxicology

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).


44. Virology

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}}$.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Chemistry Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Acid-Base Chemistry

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.


2. Analytical Chemistry

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.


3. Colloids

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.


4. Computational Chemistry

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.


5. Crystallography

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.


6. Electrochemistry

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.


7. Environmental Chemistry

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.


8. Equilibrium

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}$).


9. Gas Laws

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.


10. Green Chemistry

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.


11. Inorganic Chemistry

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.


12. Kinetics

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.


13. Molecular Chemistry

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.


14. Nuclear Chemistry

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$.


15. Organic Chemistry

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).


16. Photochemistry

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.


17. Polymers

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.


18. Quantum Chemistry

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.


19. Reaction Engineering

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.


20. Solid-State Chemistry

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.


21. Solutions

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.


22. Spectroscopy

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)$.


23. Stoichiometry

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.


24. Surface Chemistry

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).


25. Thermochemistry

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$).


26. Transport Phenomena

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).


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Constants Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Fundamental Constants

Core physical constants used across all scientific domains. These form the foundation of the SI system and appear throughout every SciForge module.

ConstantSymbolValueUnit
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$:

  • Planck length: $\ell_P = \sqrt{\hbar G / c^3} = 1.616\,255 \times 10^{-35}$ m
  • Planck mass: $m_P = \sqrt{\hbar c / G} = 2.176\,434 \times 10^{-8}$ kg
  • Planck time: $t_P = \ell_P / c = 5.391\,247 \times 10^{-44}$ s
  • Planck temperature: $T_P = m_P c^2 / k_B = 1.416\,784 \times 10^{32}$ K

These represent the scales where quantum gravity effects become significant.


2. Astronomical Constants

Constants for astrophysics, celestial mechanics, and cosmology.

ConstantSymbolValueUnit
Astronomical unitAU$1.495\,978\,707 \times 10^{11}$m
Parsecpc$3.085\,677\,581 \times 10^{16}$m
Light-yearly$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².


3. Atomic Constants

Atomic and subatomic scale constants for quantum mechanics and spectroscopy.

ConstantSymbolValueUnit
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 unitu$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.


4. Elements (Periodic Table)

Complete data for all **118 elements**, parsed at compile time from YAML files in the tableau-periodique/ directory.

Each element provides:

  • Atomic number ($Z$) and symbol
  • Standard atomic mass (IUPAC recommended, in u)
  • Electronegativity (Pauling scale, where available)
  • Group and period in the periodic table

The elements are loaded using SciForge's built-in YAML parser from 118 source files organized into 11 IUPAC categories:

CategoryDirectoryCount
Alkali metalsmetaux-alcalins/6
Alkaline earth metalsmetaux-alcalino-terreux/6
Transition metalsmetaux-de-transition/38
Post-transition metalsmetaux-post-transition/13
Metalloidsmetalloides/7
Nonmetalsnon-metaux/7
Halogenshalogenes/5
Noble gasesgaz-nobles/7
Lanthanideslanthanides/15
Actinidesactinides/15
Superheavy elementselements-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.


5. Unit Conversions

Conversion factors between common scientific unit systems.

Energy conversions:

  • $1 \text{ eV} = 1.602\,176\,634 \times 10^{-19}$ J
  • $1 \text{ J} = 6.241\,509\,074 \times 10^{18}$ eV
  • $1 \text{ keV} = 1.160\,452 \times 10^7$ K (thermal equivalence via $E = k_B T$)
  • $1 \text{ cal} = 4.184$ J (thermochemical calorie)

Pressure conversions:

  • $1 \text{ atm} = 101\,325$ Pa
  • $1 \text{ bar} = 10^5$ Pa

Angular conversions:

  • $1° = \pi / 180$ rad ≈ 0.017453 rad
  • $1 \text{ rad} = 180 / \pi$ ° ≈ 57.2958°

Length scales:

  • $1 \text{ Å} = 10^{-10}$ m (atomic scale)
  • $1 \text{ fm} = 10^{-15}$ m (nuclear scale, also called "fermi")
  • $1 \text{ barn} = 10^{-28}$ m² (nuclear cross-section unit)

All conversion factors are defined as pub const f64 for zero-cost compile-time use.

  • Energy conversions (joule, eV, calorie, erg, hartree)
  • Pressure conversions (pascal, atm, bar, torr)
  • Temperature conversions (kelvin, celsius, fahrenheit)

Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Geology Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Dating

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.


2. Petrology

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.


3. Seismology

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.


4. Tectonics

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.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Hub Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Architecture

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

1. API

External interface layer for interacting with SciForge computations.

HTTP Server

A minimal TCP-based HTTP server built on std::net::TcpListener (no framework dependencies). The server:

  • Binds to a configurable address
  • Parses raw HTTP requests (method, path, body)
  • Delegates to a handler function Fn(&str, &str, &str) -> HttpResponse
  • Returns responses with proper HTTP/1.1 headers (status, content-type, content-length)
pub struct HttpResponse {
    pub status_code: u16,
    pub status_text: String,
    pub content_type: String,  // "application/json" by default
    pub body: String,
}

DTOs (Data Transfer Objects)

**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().

Routes

  • **formatter.rs** — Formats ComputeResponse into different output targets (JSON, plain text, etc.)
  • **params.rs** — Parses and validates incoming request parameters with type coercion

2. Domain

Shared domain concepts used across the Hub.

Units

Strongly typed unit system with enumerations for physical quantities:

QuantityVariants
LengthUnitMeter, Kilometer, Mile, AU, Parsec, LightYear, ...
MassUnitKilogram, Gram, SolarMass, ElectronMass, AMU, ...
TimeUnitSecond, Minute, Hour, Day, Year, ...
TemperatureUnitKelvin, Celsius, Fahrenheit
EnergyUnitJoule, eV, keV, MeV, Calorie, ...
PressureUnitPascal, Atmosphere, Bar, ...
AngleUnitRadian, Degree

Errors

Unified error handling: HubError enum with variants for invalid input, dispatch failures, simulation errors, etc. HubResult<T> = Result<T, HubError>.


3. Engine

The computational core of the Hub.

Dispatch

Routes experiment requests to the correct scientific module. One dispatcher per domain:

DispatcherModuleDescription
astronomy.rsAstronomyStellar, orbital, cosmology functions
biology.rsBiology44 submodules, 176 source files
chemistry.rsChemistry26 submodules
geology.rsGeologyDating, petrology, seismology, tectonics
maths.rsMathematics17 submodules
meteorology.rsMeteorologyAtmosphere, dynamics, precipitation, radiation
physics.rsPhysics11 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_v(params, "name")` → `HubResult<&[f64]>` (vector)
  • `get_m(params, "name")` → `HubResult<&[Vec<f64>]>` (matrix)
  • get_c(params, "name")HubResult<Complex> (complex number)

Experiment

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.

Simulation

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 dynamics
  • **SimpleModel**: generic system from a boxed closure

The **Integrator** advances the state forward using numerical methods (Euler, RK4, adaptive RK45). The **Solver** orchestrates the integration loop and collects SimulationResult time series.

Pipeline

Multi-step computation workflows via the Flow module. Allows chaining computations where the output of one step feeds as input to the next.

Worker

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 management
  • **Executor** — Dispatches tasks sequentially or in parallel
  • **Context** — Carries execution state, parameters, and result collection

4. Campaign

Multi-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.


5. Tools

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.

6. Prelude

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.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Mathematics Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Complex Numbers

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.


2. FFT (Fast Fourier Transform)

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)$.


3. Graph Theory

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.


4. Integration

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$.


5. Interpolation

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.


6. Linear Algebra

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.


7. Non-Euclidean Geometry

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$.


8. ODE (Ordinary Differential Equations)

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.


9. Optimization

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.


10. PDE (Partial Differential Equations)

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.


11. Polynomial

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.


12. Probability

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.


13. Signal Processing

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.


14. Sparse Matrices

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.


15. Statistics

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.


16. Tensor

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.


17. Vector Calculus

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.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Meteorology Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Atmosphere

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).


2. Dynamics

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.


3. Precipitation

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.


4. Radiation

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.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Parser Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Architecture

Each format implementation follows an identical layered pattern across 4–5 source files:

LayerFileRole
Lexerlexer.rsByte-level cursor over `&[u8]` input. Advances through raw bytes, tracks position, handles whitespace skipping and token boundary detection.
Parserparser.rsRecursive-descent parser consuming tokens from the lexer to build a typed value tree.
Valuevalue.rsEnum representing parsed data nodes (strings, numbers, booleans, containers). All values borrow from the input (&'a str) — zero-copy where possible.
Errorerror.rsFormat-specific error type with byte position and error kind for precise diagnostics.

Shared design principles:

  • **Zero-allocation parsing** — values borrow slices from the input buffer via lifetime 'a. String values are &'a str referencing the original bytes, avoiding heap copies.
  • **Cursor-based lexing** — every lexer wraps a 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.

1. CSV

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.


2. JSON

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 parsing** (number.rs): integers, floats, and scientific notation (1.23e-4), parsed via a dedicated module that handles all edge cases.
  • **String parsing** (string.rs): full Unicode escape sequences (\uXXXX, including surrogate pairs for supplementary plane characters), plus standard escapes (\n, \t, \\, \", etc.).
  • Nested structures: recursive descent with arbitrary nesting depth for objects and arrays.

Error reporting includes byte offset for precise Location of syntax errors.


3. YAML

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"Bool
  • Numeric patterns → Number(f64)
  • Everything else → String

The YAML parser is used internally by the constants module to load all 118 periodic table element files at compile time.


4. HTML

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 (&amp;&, &lt;<, &gt;>, &quot;", etc.) and numeric character references (&#123;, &#x7B;).

The lexer tracks open/close tags, self-closing tags, and attributes. Used by the benchmark export module to generate self-contained HTML dashboards.


5. Markdown

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.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

Physics Module

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.


Chapter 1 - Module Scope

Scientific Purpose

This section defines the scope: which problem this module solves, which abstraction level it targets, and which outputs are expected.

Modeling Assumptions

  • The equations are numerical models, not analytical proofs.
  • Inputs must respect the documented units.
  • Validity domains (linear regime, local approximation, and so on) should be verified by the reader.

Reading Strategy

  1. Read the module structure.
  2. Identify equations and their conditions.
  3. Map these equations to Rust functions in docs/code/.

Reading Guide

Goal

This page explains the module from a scientific perspective: assumptions, models, equations, and usage limits.

How To Read This Document

  • Start with the domain section relevant to your case.
  • Identify key equations and their usage conditions.
  • Then verify the corresponding Rust signatures in docs/code/.

Conventions

  • Units: SI unless explicitly stated.
  • Variables: standard mathematical notation for the domain.
  • Equations are presented as reference models, not formal proofs.

Chapter 2 - Submodules and Models

1. Acoustics

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.


2. Electrodynamics

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.


3. Electronics

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.


4. Fluid Mechanics

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.


5. Materials Science

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.


6. Nucleosynthesis

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.


7. Optics

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$.


8. Quantum Mechanics

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.


9. Relativity

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.


10. Solid Mechanics

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).


11. Thermodynamics

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.


Chapter 3 - Limits, Precision, and Validation

Numerical Limits

  • f64 rounding errors can accumulate in long simulations.
  • Extreme regimes (very large or very small scales) require explicit numerical stability checks.

Recommended Verification

  • Compare against a simple analytical case when available.
  • Check the order of magnitude of results.
  • Run sensitivity analysis on dominant parameters.

Transition to Implementation

For concrete function calls, Rust signatures and module paths are documented in docs/code/.

SciForge — Documentation

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.


Chapter 1 - Documentation Scope

Purpose

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.

Reading Strategy

  1. Start with the module page in docs/modules/ to understand the scientific scope and models.
  2. Continue with the matching page in docs/code/ to inspect the implementation layout and public-facing API.
  3. Use the repository structure overview at the end of this page to locate the relevant files quickly.

Reading Guide

Goal

This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.

How To Read This Document

  • Use the module summaries below to identify the relevant scientific area.
  • Open the paired modules/ and code/ pages depending on whether you need theory or implementation details.
  • Use the repository tree at the end as a navigation shortcut.

Conventions

  • modules/ pages focus on scientific models, assumptions, and equations.
  • code/ pages focus on source layout, exported APIs, and execution flow.
  • Paths are written relative to the repository root.

Each module has two complementary pages:

  • Modules/ — describes the scientific concepts, formulas, and phenomena the module covers. Start here to understand *what* a module models.
  • Code/ — describes the Rust API: structs, functions, inputs/outputs. Go here when you want to *use* a module.

Chapter 2 - Modules at a Glance

Astronomy

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


Benchmark

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


Biology

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


Chemistry

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


Constants

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


Geology

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


Hub

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


Mathematics

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


Meteorology

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


Parser

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


Physics

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


Chapter 3 - Repository Structure

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 — Documentation

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.


Chapter 1 - Documentation Scope

Purpose

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.

Reading Strategy

  1. Start with the module page in docs/modules/ to understand the scientific scope and models.
  2. Continue with the matching page in docs/code/ to inspect the implementation layout and public-facing API.
  3. Use the repository structure overview at the end of this page to locate the relevant files quickly.

Reading Guide

Goal

This page acts as the entry point for the documentation set and maps each scientific area to its conceptual guide and code guide.

How To Read This Document

  • Use the module summaries below to identify the relevant scientific area.
  • Open the paired modules/ and code/ pages depending on whether you need theory or implementation details.
  • Use the repository tree at the end as a navigation shortcut.

Conventions

  • modules/ pages focus on scientific models, assumptions, and equations.
  • code/ pages focus on source layout, exported APIs, and execution flow.
  • Paths are written relative to the repository root.

Each module has two complementary pages:

  • Modules/ — describes the scientific concepts, formulas, and phenomena the module covers. Start here to understand *what* a module models.
  • Code/ — describes the Rust API: structs, functions, inputs/outputs. Go here when you want to *use* a module.

Chapter 2 - Modules at a Glance

Astronomy

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


Benchmark

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


Biology

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


Chemistry

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


Constants

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


Geology

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


Hub

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


Mathematics

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


Meteorology

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


Parser

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


Physics

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


Chapter 3 - Repository Structure

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

Astronomy Source Code Guide

This page documents the source implementation behind sciforge::astronomy, including file layout and Hub dispatch wiring.

Source Coverage

What is explained

  • File-level implementation layout in src/astronomy/.
  • Main computation groups and where they are implemented.
  • Runtime call path when astronomy functions are executed through Hub dispatch.

Visibility and external access

  • This domain module is pub(crate) in src/lib.rs and is not part of the external crate API.
  • External consumers should use the public sciforge::hub API for these computations.
  • Direct module paths shown here are for internal development and source-level understanding.

Source Code Explanation

Relevant file structure

  • Main implementation: src/astronomy/
  • Module entry point: src/astronomy/mod.rs
  • Hub routing: src/hub/engine/dispatch/astronomy.rs

Internal logic

  1. Public functions are grouped by scientific subdomain (orbits, stellar, cosmology, celestial).
  2. Each .rs file implements a coherent set of equations and helpers.
  3. Hub dispatch resolves function names and forwards normalized parameters to domain functions.

What to verify in source code

  • Exact signature and argument ordering.
  • Unit assumptions (especially distances, velocities, and Hubble constants).
  • Domain constraints (e.g. non-negative redshift, valid density parameters).

Modules

  • orbits
  • stellar
  • cosmology
  • celestial

Cosmology API (selected)

E(z) parameterizations

  • e_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 parameter at redshift

  • hubble_at_z(h0, omega_m, omega_r, omega_k, omega_de, z)
  • hubble_at_z_lcdm(h0, omega_m, z)

Distances from redshift

  • 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(...)

LCDM-oriented shortcuts

  • age_lcdm(h0, omega_m) (analytical flat LCDM age)
  • deceleration_parameter(omega_m, z)
  • deceleration_parameter_today(omega_m)

Hub dispatch mapping

All cosmology functions above are wired through the astronomy dispatcher in:

  • src/hub/engine/dispatch/astronomy.rs

Usage 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)?;

Benchmark Source Code Guide

This page documents the source implementation behind sciforge::benchmark, including benchmark engine internals, encoding/decoding, simulation flow, report generation, and exporters.

Source Coverage

What is explained

  • File-level implementation layout in src/benchmark/.
  • Main algorithms and where they are implemented.
  • Runtime call path for benchmark execution, reporting, and exports.

Visibility and external access

  • Visibility: public (pub mod benchmark; in src/lib.rs).
  • External direct path: sciforge::benchmark::*.
  • Hub integration is optional for orchestration workflows.

Source Code Explanation

Relevant file structure

  • Main implementation: src/benchmark/
  • Module entry point: src/benchmark/mod.rs
  • Hub routing (when applicable): (n/a - benchmark is direct)

Internal logic

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent block of equations and functions.
  3. Hub integration is optional for orchestration workflows.

What to verify in source code

  • Exact signature: input/output types and argument order.
  • Numerical preconditions: divisions, roots, logarithms, and validity ranges.
  • Implicit conventions: units, normalization, bounds, and tolerances.

Modules

  • engine — core benchmarking loop (bench, run, run_headless)
  • simulation — deterministic simulation runner (SimConfig, SimState, SimResult)
  • encode — serialization of benchmark metrics to multiple formats
  • decode — deserialization of encoded benchmark data
  • report — human-readable report generation from metrics
  • export — file export of benchmark results (CSV, JSON, TOML, YAML)

Core Structs

StructDescription
BenchmarkMetrics<'a>Timing, iteration count, name, and statistical summary for a benchmark run
BenchmarkMetricsView<'a>Borrowed view of BenchmarkMetrics for formatting
BenchmarkReportHuman-readable text report generated from metrics
Entry<'a>A single benchmark entry (name + metrics reference)
ExportSummarySummary of all exported file paths
SimConfigConfiguration for a deterministic simulation (steps, dt, parameters)
SimStateRuntime mutable state of a simulation
SimResultFinal output after a complete simulation run

Engine API

bench

pub 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.

run

pub 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_headless

pub fn run_headless<S: StepFn>(config: &SimConfig, step: S) -> SimResult

Same as run but discards rendered output — suitable for pure benchmarking.

sanitize_filename

pub fn sanitize_filename(name: &str) -> String

Converts a benchmark name to a safe filesystem name (removes special characters, lowercases).


Encode API

Serializes BenchmarkMetrics to text formats:

  • encode(metrics: &BenchmarkMetrics<'_>) -> String — canonical format (TOML)
  • encoded_size(metrics: &BenchmarkMetrics<'_>) -> Option<usize> — byte size of encoded output

Decode API

Deserializes previously encoded benchmark data:

  • decode<'a>(bytes: &'a str) -> BenchmarkMetrics<'a> — parse canonical encoded format

Report API

Generates text reports from benchmark results:

  • generate(metrics: &BenchmarkMetrics<'_>, result: &str) -> BenchmarkReport — full report
  • generate_csv(metrics: &BenchmarkMetrics<'_>, result: &str) -> String
  • generate_json(metrics: &BenchmarkMetrics<'_>, result: &str) -> String
  • generate_json_tagged(metrics, result, tag) — JSON with extra tag field
  • generate_toml(metrics: &BenchmarkMetrics<'_>, result: &str) -> String
  • generate_toml_tagged(metrics, result, tag) — TOML with extra tag field
  • generate_yaml(metrics: &BenchmarkMetrics<'_>, result: &str) -> String
  • generate_yaml_tagged(metrics, result, tag) — YAML with extra tag field

Export API

Writes benchmark reports to the output/ directory tree:

  • export(metrics: &BenchmarkMetrics<'_>, result: &str, base_dir: &str) -> ExportSummary

Automatically creates subdirectories and writes CSV, JSON, TOML, and YAML files. Returns an ExportSummary listing all written paths.


Typical Usage

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);

Biology Source Code Guide

This page documents the source implementation behind sciforge::biology, including file layout, execution flow, and Hub dispatch integration.

Source Coverage

What is explained

  • File-level implementation layout in src/biology/.
  • Main computation groups and where they are implemented.
  • Runtime call path when biology functions are executed through Hub dispatch.

Visibility and external access

  • Visibility: internal (pub(crate) in src/lib.rs).
  • External consumers should use sciforge::hub as the public entry point.
  • Paths in this page are for source reading and internal crate development.

Source Code Explanation

Relevant file structure

  • Main implementation: src/biology/
  • Module entry point: src/biology/mod.rs
  • Hub routing (when applicable): src/hub/engine/dispatch/biology.rs

Internal logic

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent block of equations and functions.
  3. The Hub invokes these functions through the domain dispatcher when execution goes through ExperimentRunner.

What to verify in source code

  • Exact signature: input/output types and argument order.
  • Numerical preconditions: divisions, roots, logarithms, and validity ranges.
  • Implicit conventions: units, normalization, bounds, and tolerances.

Modules

  • aging — telomere dynamics, senescence models, Gompertz mortality
  • bioelectricity — membrane potential, Hodgkin-Huxley model, action potential
  • bioenergetics — ATP yield, metabolic rate, efficiency, caloric value
  • biogeography — species-area relationships, island biogeography, dispersal
  • bioinformatics — sequence alignment, edit distance, GC content, codon usage
  • biomechanics — joint forces, muscle force, gait analysis, stress on tissues
  • biophysics — diffusion in cells, membrane transport, molecular motors
  • biostatistics — survival analysis, dose-response, clinical trial statistics
  • cancer_biology — tumor growth models, mutation rate, somatic evolution
  • cell — cell cycle, division, membrane area/volume, receptor kinetics
  • chronobiology — circadian rhythms, entrainment, ultradian oscillations
  • cryobiology — cryoprotection, ice nucleation, viability models
  • developmental — growth stages, allometric scaling, pattern formation
  • ecology — Lotka-Volterra, competitive exclusion, food webs, biodiversity
  • endocrinology — hormone kinetics, feedback loops, receptor occupancy
  • enzyme — Michaelis-Menten, inhibition, enzyme efficiency, kcat/Km
  • immunology — antibody kinetics, clonal expansion, immune response models
  • marine_biology — salinity effects, pressure adaptation, tidal models
  • microbiology — bacterial growth, doubling time, kill curves, MIC
  • mycology — fungal growth models, spore dispersal, mycelial networks
  • neuroscience — Hodgkin-Huxley, cable equation, synaptic models, neural coding
  • nutrition — BMR, macronutrient metabolism, energy balance
  • paleobiology — fossil dating, phylogenetic divergence, extinction rates
  • parasitology — host-parasite dynamics, transmission, parasite load
  • pharmacology — PK/PD models, bioavailability, clearance, drug-receptor binding
  • phylogenetics — distance matrices, UPGMA, neighbor-joining, GTR model
  • physiology — cardiac output, respiratory mechanics, renal function
  • plant_biology — photosynthesis rate, stomatal conductance, transpiration
  • population — logistic growth, age-structured models, Leslie matrix
  • proteomics — isoelectric point, molecular weight from sequence, peptide properties
  • radiobiology — linear-quadratic model, survival fraction, RBE
  • reproduction — fertility models, gestational dynamics, reproductive rate R₀
  • stem_cell — differentiation kinetics, self-renewal, niche occupancy
  • structural — protein secondary structure propensities, folding energy
  • synthetic_biology — toggle switch, oscillator, genetic circuit Hill functions
  • systems_biology — flux balance, stoichiometric matrix, metabolic control
  • tissue_engineering — scaffold porosity, seeding efficiency, degradation
  • toxicology — LD50, dose-response curves, NOAEL, therapeutic index
  • virology — viral replication kinetics, burst size, within-host dynamics

Selected API Reference

Aging

  • gompertz_mortality(a, b, age) — Gompertz-Makeham mortality rate
  • telomere_length(initial_length, division_rate, time)

Bioelectricity

  • 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)

Bioenergetics

  • atp_yield_glucose() — theoretical max ATP from glycolysis + TCA + ETC
  • metabolic_rate_kleiber(mass) — Kleiber's law: BMR ∝ M^0.75
  • respiratory_quotient(co2_produced, o2_consumed)

Bioinformatics

  • gc_content(sequence: &str) → fraction
  • edit_distance(s1: &str, s2: &str) — Levenshtein distance
  • needleman_wunsch(seq1, seq2, match_score, mismatch, gap) → alignment score
  • smith_waterman(seq1, seq2, match_score, mismatch, gap) → local alignment
  • codon_frequency(sequence: &str) → codon count map

Biomechanics

  • muscle_force(pcsa, specific_tension)
  • joint_reaction_force(external_force, moment_arm_ratio)
  • bending_stress_bone(moment, radius, moment_of_inertia)

Cell Biology

  • cell_division_time(initial_count, final_count, time_span)
  • receptor_occupancy(ligand_concentration, kd)
  • surface_area_to_volume_ratio(radius) — sphere approximation

Ecology

  • lotka_volterra_prey(prey, predator, alpha, beta, dt)
  • lotka_volterra_predator(prey, predator, gamma, delta, dt)
  • logistic_growth(n, r, k) — dN/dt
  • shannon_diversity(abundances)
  • species_area_relationship(area, c, z) — S = C × A^z

Enzyme Kinetics

  • michaelis_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)

Microbiology

  • bacterial_growth(n0, growth_rate, time) — exponential phase
  • doubling_time(growth_rate)
  • logistic_bacterial_growth(n0, r, k, time)
  • minimum_inhibitory_concentration(kill_rate, dose_response_params)

Neuroscience

  • 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 variation

Pharmacology

  • one_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)

Phylogenetics

  • jukes_cantor_distance(p_distance)
  • upgma(distance_matrix) → tree structure
  • neighbor_joining(distance_matrix) → tree structure

Plant Biology

  • photosynthesis_rate_farquhar(vcmax, jmax, ci, temperature)
  • stomatal_conductance_ball_berry(a_net, rh, cs, g0, g1)
  • beer_lambert_canopy(k, lai)

Population Dynamics

  • 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)

Radiobiology

  • linear_quadratic_survival(alpha, beta, dose)
  • equivalent_dose(dose, rbe)
  • brachytherapy_dose_rate(activity, dose_constant, distance)

Systems Biology

  • flux_balance_analysis(stoich_matrix, lower_bounds, upper_bounds) → optimal fluxes
  • metabolic_control_coefficient(flux, enzyme_activity_change)
  • elasticity_coefficient(reaction_rate, metabolite_conc)

Toxicology

  • ld50_probit(dose, probit_params)
  • therapeutic_index(ld50, ed50)
  • no_observed_adverse_effect(dose_response_data)

Virology

  • 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)

Hub dispatch mapping

All biology functions are wired through:

  • src/hub/engine/dispatch/biology.rs
use 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)?;

Chemistry Source Code Guide

This page documents the source implementation behind sciforge::chemistry, including file layout and Hub dispatch wiring.

Source Coverage

What is explained

  • File-level implementation layout in src/chemistry/.
  • Main computation groups and where they are implemented.
  • Runtime call path when chemistry functions are executed through Hub dispatch.

Visibility and external access

  • Visibility: internal (pub(crate) in src/lib.rs).
  • External consumers should use sciforge::hub as the public entry point.
  • Paths in this page are for source reading and internal crate development.

Source Code Explanation

Relevant file structure

  • Main implementation: src/chemistry/
  • Module entry point: src/chemistry/mod.rs
  • Hub routing (when applicable): src/hub/engine/dispatch/chemistry.rs

Internal logic

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent block of equations and functions.
  3. The Hub invokes these functions through the domain dispatcher when execution goes through ExperimentRunner.

What to verify in source code

  • Exact signature: input/output types and argument order.
  • Numerical preconditions: divisions, roots, logarithms, and validity ranges.
  • Implicit conventions: units, normalization, bounds, and tolerances.

Modules

  • acid_base
  • analytical
  • colloids
  • computational
  • crystallography
  • electrochemistry
  • environmental
  • equilibrium
  • gas_laws
  • green_chemistry
  • inorganic
  • kinetics
  • molecular
  • nuclear
  • organic
  • photochemistry
  • polymers
  • quantum_chem
  • reaction_engineering
  • solid_state
  • solutions
  • spectroscopy
  • stoichiometry
  • surface
  • thermochemistry
  • transport

Acid-Base API

Submodules

  • equilibria — pH, pOH, Ka/Kb, buffer capacity, Henderson-Hasselbalch
  • titrations — equivalence point, titration curve, indicator selection

Selected functions

  • ph_from_concentration(concentration, ka)
  • henderson_hasselbalch(pka, ca, cb)
  • buffer_capacity(ca, cb, ka)
  • titration_curve(ca, va, cb, vb_range, ka)

Analytical Chemistry API

Submodules

  • chromatography — retention factor, resolution, theoretical plates
  • quantitative — calibration curves, detection limits, recovery
  • spectrophotometry — Beer-Lambert law, absorbance, transmittance

Selected functions

  • beer_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)

Colloids API

Submodules

  • properties — zeta potential, particle size, surface area
  • stability — DLVO theory, coagulation, sedimentation

Selected functions

  • zeta_potential_to_stability(zeta)
  • debye_huckel_kappa(ionic_strength, temperature)
  • settling_velocity(radius, density_particle, density_fluid, viscosity)

Computational Chemistry API

Submodules

  • dft — density functional theory utilities, DFT energy approximations
  • basis_sets — Gaussian basis set evaluations, overlap integrals

Selected functions

  • lda_exchange_energy(density)
  • gga_exchange_energy(density, grad_density)
  • gaussian_overlap(alpha1, alpha2, r1, r2)

Crystallography API

Submodules

  • lattice — lattice parameters, unit cell volume, Bravais lattices
  • diffraction — Bragg's law, structure factor, powder diffraction pattern

Selected functions

  • bragg_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)

Electrochemistry API

Submodules

  • cells — Nernst equation, cell potential, electrode potentials
  • transport — ionic conductivity, diffusion, transference numbers

Selected functions

  • nernst_equation(e0, n, q, temperature)
  • cell_potential(e_cathode, e_anode)
  • ionic_conductivity(lambda_ions, concentrations)
  • diffusion_limiting_current(d, c, n, area, delta)

Environmental Chemistry API

Submodules

  • atmosphere — Henry's law, atmospheric partitioning, ppm/ppb conversion
  • water — BOD, COD, dissolved oxygen, water hardness

Selected functions

  • henry_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)

Equilibrium API

Submodules

  • constants — Keq, Kp, Kc, Ksp calculations
  • ionic — activity coefficients, Debye-Hückel, ionic strength

Selected functions

  • equilibrium_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)

Gas Laws API

Submodules

  • ideal — ideal gas law, partial pressures, Dalton's law, Graham's law
  • real — van der Waals, Redlich-Kwong, virial equation

Selected functions

  • ideal_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)

Green Chemistry API

Submodules

  • metrics — atom economy, E-factor, reaction mass efficiency
  • principles — solvent selection, waste minimization metrics

Selected functions

  • atom_economy(mw_desired, sum_mw_reactants)
  • e_factor(mass_waste, mass_product)
  • reaction_mass_efficiency(actual_yield, theoretical_yield, atom_economy)

Inorganic Chemistry API

Submodules

  • bonding — bond order, electronegativity difference, bond polarity
  • coordination — crystal field splitting, coordination number, CFSE
  • crystal_field — d-orbital splitting, high-spin/low-spin energies

Selected functions

  • bond_polarity(electronegativity1, electronegativity2)
  • crystal_field_stabilization(d_electrons, geometry, delta)
  • coordination_geometry_energy(geometry, delta)

Kinetics API

Submodules

  • rates — first/second/nth-order rate laws, integrated rate equations
  • mechanisms — Arrhenius equation, activation energy, pre-exponential factor

Selected functions

  • first_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)

Molecular Chemistry API

Submodules

  • bonding — Lewis structure bond orders, hybridization, resonance
  • geometry — VSEPR geometry prediction, bond angles

Selected functions

  • vsepr_geometry(bonding_pairs, lone_pairs)
  • hybridization(bonding_pairs, lone_pairs)
  • dipole_moment(charge, distance)

Nuclear Chemistry API

Submodules

  • decay — alpha, beta, gamma decay, decay series
  • energy — Q-value, binding energy per nucleon, mass excess

Selected functions

  • nuclear_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)

Organic Chemistry API

Submodules

  • reactions — reaction type classification, yield prediction
  • structure — molecular formula, degree of unsaturation, functional groups
  • descriptors — lipophilicity (LogP), molecular weight, polar surface area

Selected functions

  • degree_of_unsaturation(c, h, n, x)
  • molecular_weight(formula) — parses simple formulae
  • logp_estimate(descriptor_values, logp_model)

Photochemistry API

Submodules

  • kinetics — photostationary state, quantum yield, actinometry
  • quantum_yield — primary vs secondary quantum yield, sensitization

Selected functions

  • quantum_yield(n_products, n_photons_absorbed)
  • photostationary_state(k_forward, k_reverse, phi_forward, phi_reverse)
  • einstein_to_photons(energy_per_mole, wavelength)

Polymers API

Submodules

  • distributions — number/weight-average molecular weight, dispersity
  • properties — glass transition temperature, viscosity, degree of polymerization

Selected functions

  • number_average_mw(ni, mi)
  • weight_average_mw(ni, mi)
  • dispersity(mw, mn)
  • degree_of_polymerization(mw, m0)
  • glass_transition_estimate(backbone_flexibility)

Quantum Chemistry API

Submodules

  • orbitals — AO basis functions, hydrogen-like wavefunctions
  • huckel — Hückel MO theory, secular determinant, π-electron energy

Selected functions

  • hydrogen_wavefunction(n, l, m, r, theta, phi)
  • huckel_eigenvalues(adjacency_matrix, alpha, beta)
  • pi_electron_energy(eigenvalues, n_pi_electrons, alpha, beta)

Reaction Engineering API

Submodules

  • reactors — CSTR, PFR, batch reactor design equations
  • design — conversion, selectivity, residence time

Selected functions

  • cstr_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)

Solid State Chemistry API

Submodules

  • band_theory — band gap, effective mass, density of states
  • defects — point defects, Schottky/Frenkel concentrations

Selected functions

  • density_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)

Solutions API

Submodules

  • colligative — boiling point elevation, freezing point depression, osmotic pressure
  • mixtures — Raoult's law, Henry's law, activity coefficients

Selected functions

  • boiling_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)

Spectroscopy API

Submodules

  • nmr — chemical shift, coupling constants, relaxation times
  • ir — vibrational frequencies, group frequencies, IR intensity
  • mass_spec — m/z, isotope patterns, fragmentation

Selected functions

  • nmr_chemical_shift(frequency, reference_frequency)
  • ir_stretching_frequency(force_constant, reduced_mass)
  • monoisotopic_mass(formula)
  • isotope_pattern(formula, max_isotopes)

Stoichiometry API

Submodules

  • calculations — molar mass, limiting reagent, theoretical yield
  • balancing — equation balancing via matrix method

Selected functions

  • limiting_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 coefficients

Surface Chemistry API

Submodules

  • adsorption — Langmuir, Freundlich, BET isotherms
  • tension — surface tension, contact angle, capillary pressure

Selected functions

  • langmuir_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)

Thermochemistry API

Submodules

  • enthalpy — Hess's law, standard enthalpy of reaction, Kirchhoff's law
  • entropy — standard entropy, Gibbs energy, spontaneity

Selected functions

  • hess_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)

Transport Properties API

Submodules

  • diffusion — Fick's laws, Stefan-Maxwell, diffusion coefficients
  • mass_transfer — mass transfer coefficient, Sherwood number, film theory

Selected functions

  • diffusion_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)

Hub dispatch mapping

All chemistry functions are wired through:

  • src/hub/engine/dispatch/chemistry.rs
use 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)?;

Constants Source Code Guide

This page documents the source implementation behind sciforge::constants, including constant tables and lookup helpers.

Source Coverage

What is explained

  • File-level implementation layout in src/constants/.
  • Main constant groups and lookup mechanisms.
  • Runtime usage path through Hub when constants are consumed in domain dispatch.

Visibility and external access

  • This domain module is pub(crate) in src/lib.rs and is not part of the external crate API.
  • External consumers should use the public sciforge::hub API for these computations.
  • Direct module paths shown here are for internal development and source-level understanding.

Source Code Explanation

Relevant file structure

  • Main implementation: src/constants/
  • Module entry point: src/constants/mod.rs
  • Hub routing (when applicable): (n/a - constants are direct)

Internal execution flow

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent constants or lookup block.
  3. Domain dispatchers and Hub prelude re-exports consume these constants internally.

What to verify in source code

  • Exact signature: input/output types and argument order.
  • Numerical preconditions: divisions, roots, logarithms, and validity ranges.
  • Implicit conventions: units, normalization, bounds, and tolerances.

Modules

  • 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 factors
  • elements — periodic table data (118 elements)

Fundamental Constants

All constants are pub const f64 accessible as sciforge::constants::CONSTANT_NAME.

Universal

ConstantSymbolValue
CSpeed of light2.99792458×10⁸ m/s
GGravitational constant6.674×10⁻¹¹ m³ kg⁻¹ s⁻²
HPlanck constant6.62607015×10⁻³⁴ J·s
HBARReduced Planck constantH / 2π
K_BBoltzmann constant1.380649×10⁻²³ J/K
N_AAvogadro number6.02214076×10²³ mol⁻¹
R_GASIdeal gas constant8.314462 J/(mol·K)
SIGMA_SBStefan–Boltzmann constant5.670374×10⁻⁸ W m⁻² K⁻⁴

Electromagnetic

ConstantDescription
E_CHARGEElementary charge (C)
EPSILON_0Vacuum permittivity (F/m)
MU_0Vacuum permeability (H/m)
K_COULOMBCoulomb constant (N·m²/C²)
ALPHA_FINEFine-structure constant (dimensionless)

Atomic / Quantum

ConstantDescription
BOHR_RADIUSBohr radius (m)
COMPTON_WAVELENGTHCompton wavelength of the electron (m)
RYDBERG_ENERGYRydberg energy (J)
BOHR_MAGNETONBohr magneton (J/T)
NUCLEAR_MAGNETONNuclear magneton (J/T)
PROTON_MASS_KGProton mass (kg)
NEUTRON_MASS_KGNeutron mass (kg)
ELECTRON_MASS_KGElectron mass (kg)
AMU_TO_KGAtomic mass unit → kg
AMU_TO_MEVAtomic mass unit → MeV/c²

Astronomical Constants

ConstantDescription
SOLAR_MASSSolar mass (kg)
SOLAR_RADIUSSolar radius (m)
SOLAR_LUMINOSITYSolar luminosity (W)
EARTH_MASSEarth mass (kg)
EARTH_RADIUSEarth radius (m)
AUAstronomical unit (m)
PARSECParsec (m)
LIGHT_YEARLight-year (m)
HUBBLE_CONSTANTHubble constant H₀ (km/s/Mpc)
CMB_TEMPERATURECMB temperature (K)

Planck Units

ConstantDescription
PLANCK_LENGTHPlanck length (m)
PLANCK_MASSPlanck mass (kg)
PLANCK_TIMEPlanck time (s)
PLANCK_TEMPPlanck temperature (K)

Unit Conversion Factors

ConstantConversion
EV_TO_JOULEeV → J
JOULE_TO_EVJ → eV
KELVIN_TO_KEVK → keV
KEV_TO_KELVINkeV → K
CALORIE_TO_JOULEcal → J
ATM_TO_PASCALatm → Pa
BAR_TO_PASCALbar → Pa
ANGSTROMÅngström in meters
FERMIFermi (fm) in meters
BARNBarn (b) in m²
DEGREE_TO_RAD° → rad
RAD_TO_DEGREErad → °

Elements API

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 z
  • electronegativity(z: u32) -> Option<f64> — Pauling electronegativity; returns None if not available
use 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));

Geology Source Code Guide

This page documents the source implementation behind sciforge::geology, including file layout and Hub dispatch wiring.

Source Coverage

What is explained

  • File-level implementation layout in src/geology/.
  • Main computation groups and where they are implemented.
  • Runtime call path when geology functions are executed through Hub dispatch.

Visibility and external access

  • This domain module is pub(crate) in src/lib.rs and is not part of the external crate API.
  • External consumers should use the public sciforge::hub API for these computations.
  • Direct module paths shown here are for internal development and source-level understanding.

Source Code Explanation

Relevant file structure

  • Main implementation: src/geology/
  • Module entry point: src/geology/mod.rs
  • Hub routing (when applicable): src/hub/engine/dispatch/geology.rs

Internal execution flow

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent block of equations and functions.
  3. The Hub invokes these functions through the domain dispatcher when execution goes through ExperimentRunner.

What to check while reading code

  • Exact signature: input/output types and argument order.
  • Numerical preconditions: divisions, roots, logarithms, and validity ranges.
  • Implicit conventions: units, normalization, bounds, and tolerances.

Modules

  • dating — geochronology and radiometric dating methods
  • petrology — rock classification, magma composition, igneous petrology
  • seismology — seismic waves, earthquake magnitude, aftershock statistics
  • tectonics — plate tectonics, isostasy, heat flow, flexure

Dating API

  • radioactive_decay(n0, lambda, t) — remaining parent nuclei at time t
  • half_life(lambda) — half-life from decay constant
  • decay_constant(half_life) — decay constant from half-life
  • age_from_ratio(ratio_daughter_parent, lambda) — generic radiometric age
  • carbon14_age(ratio) — ¹⁴C age from ¹⁴C/¹²C ratio
  • potassium_argon_age(ar40, k40) — K-Ar age
  • uranium_lead_age(pb206, u238) — U-Pb age (²³⁸U → ²⁰⁶Pb)
  • isochron_age(slope, lambda) — age from isochron slope
  • fission_track_age(rho_s, rho_i, rho_d, lambda) — fission track dating
  • luminescence_dose(natural_signal, dose_rate) — OSL/TL equivalent dose
  • cosmogenic_exposure_age(concentration, production_rate, lambda) — surface exposure dating

Petrology API

  • cipw_quartz_norm(sio2, feldspars, mafics) — CIPW normative quartz content
  • mg_number(mgo, feo) — Mg# = MgO / (MgO + FeO) × 100 (wt%)
  • differentiation_index(q, or_val, ab, ne) — Thornton-Tuttle differentiation index
  • total_alkali_silica(na2o, k2o) — TAS diagram x-axis (Na₂O + K₂O)
  • alumina_saturation_index(al2o3, cao, na2o, k2o) — A/CNK ratio
  • color_index(mafic_minerals) — modal % of mafic minerals (M value)
  • liquidus_temperature(composition, t_melt_a, t_melt_b) — linear liquidus interpolation
  • solidus_depression(water_content, base_solidus, k) — H₂O-induced solidus depression
  • crystal_settling_velocity(delta_rho, g, r, mu) — Stokes settling in magma
  • viscosity_arrhenius(a, ea, t) — Arrhenius viscosity model

Seismology API

  • p_wave_velocity(k, g, rho) — P-wave speed from bulk/shear moduli and density
  • s_wave_velocity(g, rho) — S-wave speed
  • richter_magnitude(amplitude, distance_km) — local Richter scale ML
  • moment_magnitude(seismic_moment) — Mw from seismic moment
  • seismic_moment(mw) — seismic moment from Mw
  • epicenter_distance(vp, vs, ts_tp) — distance from P-S arrival time difference
  • travel_time(distance, velocity) — seismic wave arrival time
  • snell_seismic(v1, theta1, v2) — refracted ray angle (Snell's law for seismic)
  • gutenberg_richter(a, b, magnitude) — log N = a − b·M frequency-magnitude
  • omori_aftershock(k, c, p, t) — Omori-Utsu aftershock decay rate
  • seismic_energy(magnitude) — energy released from magnitude
  • peak_ground_acceleration(a, b, magnitude, distance) — empirical PGA attenuation

Tectonics API

  • plate_velocity(distance, time) — average plate velocity
  • euler_pole_velocity(omega, radius, colatitude) — surface velocity from Euler pole
  • isostatic_equilibrium(rho_crust, thickness, rho_mantle) — crustal root / buoyancy
  • pratt_isostasy(rho_ref, d_ref, elevation) — Pratt isostasy column density
  • airy_root(elevation, rho_crust, rho_mantle) — Airy isostasy crustal root depth
  • thermal_subsidence(e0, t, tau) — McKenzie thermal subsidence
  • mckenzie_stretching(beta, rho_m, rho_c, alpha, tl, tc) — stretching factor subsidence
  • heat_flow(k, dt_dz) — Fourier heat flow (W/m²)
  • geothermal_gradient(surface_temp, depth, gradient) — temperature at depth
  • flexural_rigidity(e, te, nu) — lithospheric flexural rigidity D
  • elastic_thickness_from_rigidity(d, e, nu) — effective elastic thickness Te

Hub dispatch mapping

All geology functions are wired through:

  • src/hub/engine/dispatch/geology.rs
use sciforge::hub::prelude::*;

let exp = Experiment::new(DomainType::Geology, "carbon14_age")
	.param("ratio", ParameterValue::Scalar(0.5));

let out = ExperimentRunner::new().run(&exp)?;

Hub Source Code Guide

This page documents the source implementation behind sciforge::hub, including API layer, engine internals, dispatch routing, and tooling modules.

Source Coverage

What is explained

  • File-level implementation layout in src/hub/.
  • Main orchestration components and where they are implemented.
  • Runtime call path from API entry points to domain dispatchers.

Visibility and external access

  • hub is public from src/lib.rs (pub mod hub;).
  • External consumers should prefer sciforge::hub::prelude::* for stable entry points.
  • This is the recommended external path to reach pub(crate) science domains.

Source Code Explanation

Relevant file structure

  • Main implementation: src/hub/
  • Module entry point: src/hub/mod.rs
  • Hub routing (when applicable): src/hub/engine/dispatch/*.rs

Internal execution flow

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent orchestration or tooling block.
  3. The engine dispatchers route computation requests to domain implementations.

What to check while reading code

  • Exact signature: input/output types and argument order.
  • Routing logic and parameter coercion in dispatch modules.
  • Error propagation paths and domain boundary assumptions.

Modules

  • api — HTTP and CLI interfaces, DTOs, routes
  • domainDomainType enum and domain metadata
  • engine — experiment execution, pipelines, task scheduling
  • experienceExperiment / ExperimentRunner
  • pipelinePipeline / Stage composition
  • workerScheduler, TaskQueue, Executor, ExecutionContext
  • dispatch — domain-specific dispatch handlers (astronomy, biology, chemistry, geology, maths, meteorology, physics)
  • tools — numerical utilities, visualization, profiling, validation, logging
  • prelude — convenience re-exports

Prelude

use sciforge::hub::prelude::*;

Exports: Experiment, ExperimentRunner, DomainType, ParameterValue, Pipeline, Stage, Scheduler, TaskQueue, Executor.


Engine — Experiment API

Structs

StructDescription
ExperimentA named experiment with a domain, function name, and parameter map
ExperimentRunnerRuns an Experiment by dispatching to the correct domain handler

Usage

let exp = Experiment::new(DomainType::Physics, "lorentz_factor")
				.param("velocity", ParameterValue::Scalar(2.0e8));

let result = ExperimentRunner::new().run(&exp)?;

Engine — Pipeline API

Structs

StructDescription
PipelineAn ordered sequence of Stage transforms applied to a data vector
StageA single named transform step (function Vec<f64> -> Vec<f64>)

Built-in stage constructors

  • `normalize_stage()` — normalizes vector to [0, 1]
  • filter_positive_stage() — keeps only positive values
  • scale_stage(factor: f64) — multiplies each element by factor

Usage

let pipeline = Pipeline::new()
		.add(normalize_stage())
		.add(scale_stage(100.0));

let output = pipeline.run(input_data);

Engine — Worker / Scheduler API

Structs

StructDescription
SchedulerManages a queue of ScheduledTask with priority and timing
ScheduledTaskA task with an execution time and priority
TaskA named unit of work with associated TaskResult
TaskQueueFIFO/priority queue of tasks
TaskResultOutput and status of a completed task
ExecutionContextRuntime context passed to each task during execution
ExecutorDrives task execution loop, dispatching from a TaskQueue

Tools — Visualization

Generate ASCII/text-based plots for quick inspection:

  • `line_chart(data: &[f64], title: &str)` — ASCII line chart
  • `bar_chart(data: &[f64], labels: &[&str])` — ASCII bar chart
  • `scatter_plot(xs: &[f64], ys: &[f64])` — ASCII scatter plot
  • `histogram(data: &[f64], bins: usize)` — ASCII histogram
  • `heatmap(matrix: &[Vec<f64>])` — ASCII heatmap

Tools — Numerical Utilities

  • `kahan_sum(data: &[f64])` — compensated summation (Kahan)
  • `kahan_dot(a: &[f64], b: &[f64])` — compensated dot product
  • `fingerprint(data: &[f64])` — u64 hash fingerprint of a float slice
  • fingerprint_scalar(v: f64) — u64 hash of a scalar
  • linspace(start, end, n)Vec<f64> — evenly spaced points
  • logspace(start_exp, end_exp, n)Vec<f64> — logarithmically spaced points
  • `normalize(data: &[f64])` → `Vec<f64>` — rescale to [0, 1]
  • `moving_average(data: &[f64], window: usize)Vec<f64>`
  • `clamp_vec(data: &[f64], min, max)Vec<f64>`
  • `cumulative_sum(data: &[f64])Vec<f64>`
  • relative_error(computed, reference)f64
  • scalar_value(v: f64) — wraps a scalar for use with the pipeline

Tools — Formatting

  • format_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 duration

Tools — Profiling

  • profile_experiment(exp: &Experiment, runner: &ExperimentRunner) — time a single experiment
  • `profile_batch(exps: &[Experiment], runner: &ExperimentRunner)` — time multiple experiments
  • quick_profile<F: Fn()>(f: F)Duration — time any closure
  • run_timed<F: Fn() -> T>(f: F)(T, Duration) — run and return result + duration

Tools — Validation

  • `run_validation(data: &[f64])` — run standard suite of checks
  • `check_monotonicity(data: &[f64])` — assert data is non-decreasing
  • `check_nan_safety(data: &[f64])` — assert no NaN or Inf values
  • assert_reproducible(f: F, n: usize) — run f n times, assert identical results
  • `compare_entries(a: &[f64], b: &[f64], tol: f64)` — element-wise comparison
  • approx_equal(a: f64, b: f64, tol: f64)bool

Tools — Logging

Thread-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 call
  • set_level(level: LogLevel) — configure minimum log level
  • current_level()LogLevel
  • usage() — print module usage summary

Tools — Reporting

  • report_to_latex(metrics)String — LaTeX table from benchmark metrics
  • report_to_tsv(metrics)String — TSV table from benchmark metrics

Domain Dispatch

The DomainType enum routes function calls to the correct scientific module:

VariantDispatches to
DomainType::Astronomysrc/hub/engine/dispatch/astronomy.rs
DomainType::Biologysrc/hub/engine/dispatch/biology.rs
DomainType::Chemistrysrc/hub/engine/dispatch/chemistry.rs
DomainType::Geologysrc/hub/engine/dispatch/geology.rs
DomainType::Mathssrc/hub/engine/dispatch/maths.rs
DomainType::Meteorologysrc/hub/engine/dispatch/meteorology.rs
DomainType::Physicssrc/hub/engine/dispatch/physics.rs

Mathematics Source Code Guide

This page documents the source implementation behind sciforge::maths, including module layout and Hub dispatch wiring.

Source Coverage

What is explained

  • File-level implementation layout in src/maths/.
  • Main algorithm families and where they are implemented.
  • Runtime call path when maths functions are executed through Hub dispatch.

Visibility and external access

  • This domain module is pub(crate) in src/lib.rs and is not part of the external crate API.
  • External consumers should use the public sciforge::hub API for these computations.
  • Direct module paths shown here are for internal development and source-level understanding.

Source Code Explanation

Relevant file structure

  • Main implementation: src/maths/
  • Module entry point: src/maths/mod.rs
  • Hub routing: src/hub/engine/dispatch/maths.rs

Internal logic

  1. The module is split into algorithmic families (linalg, ode, pde, statistics, etc.).
  2. Each submodule groups related numerical methods behind public functions.
  3. Hub dispatch maps experiment function names to direct Rust calls with typed parameters.

What to verify in source code

  • Numeric preconditions (matrix shape compatibility, positive step sizes, tolerances).
  • Stability conditions (CFL-like constraints in PDE solvers, convergence criteria).
  • Complexity and allocation behavior for large inputs.

Modules

  • complex
  • fft
  • graph
  • integration
  • interpolation
  • linalg
  • non_euclidean
  • ode
  • optimization
  • pde
  • polynomial
  • probability
  • signal
  • sparse
  • statistics
  • tensor
  • vector

Complex API (26 functions)

Submodules

  • typesComplex<f64> type, constructors, polar/rectangular forms
  • ops — arithmetic, exp, log, trig, hyperbolic functions on complex numbers
  • quaternionQuaternion type, Hamilton product, rotation, normalization

Selected functions

  • Complex::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)

FFT API (51 functions)

Submodules

  • radix2 — Cooley-Tukey FFT/IFFT for power-of-two sizes
  • dct — Discrete Cosine Transform (types I–IV)
  • bluestein — Chirp-Z / Bluestein FFT for arbitrary sizes

Selected functions

  • fft(signal) → complex spectrum
  • ifft(spectrum) → time-domain signal
  • dct_ii(signal), dct_iii(signal), dct_iv(signal)
  • bluestein_fft(signal, n_out) — arbitrary-length DFT
  • power_spectrum(signal)

Graph API (58 functions)

Submodules

  • traversal — BFS, DFS, topological sort, connected components
  • shortest_path — Dijkstra, Bellman-Ford, Floyd-Warshall, A*
  • spanning_tree — Kruskal, Prim, minimum/maximum spanning tree
  • flow — Ford-Fulkerson, Edmonds-Karp, max-flow/min-cut

Selected functions

  • dijkstra(graph, source) → distances
  • bellman_ford(graph, source) → distances (handles negative weights)
  • floyd_warshall(graph) → all-pairs shortest paths
  • kruskal_mst(graph), prim_mst(graph, start)
  • bfs(graph, start), dfs(graph, start)
  • ford_fulkerson(graph, source, sink)

Integration API (47 functions)

Submodules

  • quadrature — trapezoidal, Simpson, Gauss-Legendre, Romberg
  • adaptive — adaptive Simpson, adaptive Gauss-Kronrod (GK15, GK21)
  • multidim — double/triple integrals, Monte Carlo integration

Selected functions

  • trapezoidal(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)

Interpolation API (34 functions)

Submodules

  • lagrange — Lagrange polynomial interpolation, Neville's algorithm
  • methods — linear, bilinear, cubic, nearest-neighbor
  • spline — natural cubic spline, clamped spline, B-spline

Selected functions

  • lagrange_interpolate(xs, ys, x)
  • neville(xs, ys, x)
  • linear_interpolate(x0, y0, x1, y1, x)
  • cubic_spline(xs, ys) → spline object
  • spline_eval(spline, x)
  • bspline_basis(i, k, t, knots)

Linear Algebra API (57 functions)

Submodules

  • decomposition — LU, QR, Cholesky, SVD decompositions
  • eigenvalue — power iteration, QR algorithm, Jacobi method
  • factorization — LDL^T, Schur, polar decomposition
  • least_squares — normal equations, QR least squares, pseudoinverse

Selected functions

  • lu_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 LU
  • pseudoinverse(matrix)
  • least_squares_qr(a, b)

Non-Euclidean Geometry API (56 functions)

Submodules

  • metric — metric tensors (Minkowski, Schwarzschild, Kerr, FRW)
  • geodesic — geodesic equations, numerical integration
  • curvature — Riemann tensor, Ricci scalar, Christoffel symbols
  • cosmology — scale factor, Friedmann equations
  • black_hole — Schwarzschild radius, Hawking temperature, ergosphere

Selected functions

  • schwarzschild_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)

ODE API (35 functions)

Submodules

  • solvers — Euler, RK4, RK45, Adams-Bashforth, implicit methods
  • systems — system of ODEs interface
  • bvp — boundary value problems (shooting method, collocation)

Selected functions

  • 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)

Optimization API (53 functions)

Submodules

  • gradient — gradient descent, Adam, L-BFGS, conjugate gradient
  • constrained — Lagrangian, interior-point, sequential quadratic programming
  • evolutionary — genetic algorithm, differential evolution, CMA-ES
  • metaheuristic — simulated annealing, particle swarm, tabu search

Selected functions

  • gradient_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 solver
  • genetic_algorithm(fitness, bounds, pop_size, generations)
  • simulated_annealing(f, x0, t_init, cooling)
  • particle_swarm(f, bounds, n_particles, max_iter)

PDE API (71 functions)

Submodules

  • finite_diff — finite difference schemes (explicit, implicit, Crank-Nicolson)
  • diffusion — heat equation (1D/2D/3D), reaction-diffusion
  • wave — wave equation (1D/2D), SH waves
  • laplace — Laplace/Poisson equation, SOR, multigrid

Selected functions

  • heat_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)

Polynomial API (29 functions)

Submodules

  • polyPolynomial type, evaluation, arithmetic, derivative, integral
  • roots — root finding (Durand-Kerner, Jenkins-Traub, Bairstow)
  • special — Legendre, Hermite, Laguerre, Chebyshev polynomials

Selected functions

  • Polynomial::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 roots
  • legendre(n, x), hermite(n, x), chebyshev_t(n, x), laguerre(n, x)

Probability API (69 functions)

Submodules

  • distributions — PDF, CDF, quantile for Normal, Poisson, Binomial, etc.
  • sampling — Box-Muller, rejection sampling, inverse CDF
  • markov — transition matrices, stationary distribution, MCMC
  • monte_carlo — MC estimation, variance reduction, quasi-random

Selected functions

  • normal_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)

Signal Processing API (70 functions)

Submodules

  • filters — FIR/IIR filters, Butterworth, Chebyshev, window functions
  • spectral — power spectral density, spectrogram, periodogram
  • convolution — 1D/2D linear/circular convolution, cross-correlation
  • wavelets — DWT, IDWT, Daubechies, Haar wavelets

Selected functions

  • fir_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)

Sparse Matrix API (24 functions)

Submodules

  • csr — Compressed Sparse Row matrix storage
  • ops — sparse matrix arithmetic, transpose, norms
  • solvers — CG, GMRES, sparse LU, iterative solvers

Selected functions

  • CsrMatrix::new(rows, cols, data, indices, indptr)
  • sparse_add(a, b), sparse_mul(a, b)
  • sparse_mv(matrix, vec) — matrix-vector product
  • sparse_transpose(matrix)
  • conjugate_gradient_sparse(a, b, x0, tol)
  • gmres(a, b, x0, restart, tol)

Statistics API (71 functions)

Submodules

  • descriptive — mean, variance, skewness, kurtosis, quantiles
  • distributions — t, chi², F, KS distributions and tests
  • hypothesis — t-test, ANOVA, chi-square test, Wilcoxon
  • regression — linear, polynomial, logistic regression, R²

Selected functions

  • 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)

Tensor API (27 functions)

Submodules

  • storage — N-dimensional dense tensor storage
  • ops — element-wise arithmetic, contraction, outer product
  • linalg — tensor norms, trace, symmetric/antisymmetric parts
  • decompose — Tucker decomposition, CP decomposition
  • display — pretty-print tensors

Selected functions

  • Tensor::new(shape, data), Tensor::zeros(shape), Tensor::ones(shape)
  • tensor_add(a, b), tensor_mul_scalar(t, s)
  • tensor_contract(a, b, axes) — Einstein summation
  • tensor_outer(a, b), tensor_transpose(t, perm)
  • tucker_decompose(tensor, ranks), cp_decompose(tensor, rank)

Vector Fields API (41 functions)

Submodules

  • typesVec2, Vec3, VecN with arithmetic operators
  • ops — dot product, cross product, norm, normalization
  • fields — gradient, divergence, curl, Laplacian
  • integrators — Euler, RK4 integration of vector field ODEs
  • sim — particle simulation utilities

Selected functions

  • Vec3::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)

Hub dispatch mapping

All mathematics functions are wired through:

  • src/hub/engine/dispatch/maths.rs
use 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)?;

Meteorology Source Code Guide

This page documents the source implementation behind sciforge::meteorology, including file layout and Hub dispatch wiring.

Source Coverage

What is explained

  • File-level implementation layout in src/meteorology/.
  • Main computation groups and where they are implemented.
  • Runtime call path when meteorology functions are executed through Hub dispatch.

Visibility and external access

  • This domain module is pub(crate) in src/lib.rs and is not part of the external crate API.
  • External consumers should use the public sciforge::hub API for these computations.
  • Direct module paths shown here are for internal development and source-level understanding.

Source Code Explanation

Relevant file structure

  • Main implementation: src/meteorology/
  • Module entry point: src/meteorology/mod.rs
  • Hub routing (when applicable): src/hub/engine/dispatch/meteorology.rs

Internal execution flow

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent block of equations and functions.
  3. The Hub invokes these functions through the domain dispatcher when execution goes through ExperimentRunner.

What to check while reading code

  • Exact signature: input/output types and argument order.
  • Numerical preconditions: divisions, roots, logarithms, and validity ranges.
  • Implicit conventions: units, normalization, bounds, and tolerances.

Modules

  • atmosphere — atmospheric structure, thermodynamic properties
  • dynamics — mesoscale and synoptic dynamics, Coriolis effects
  • precipitation — rainfall statistics, evapotranspiration, runoff
  • radiation — solar and terrestrial radiation, climate forcing

Atmosphere API

  • barometric_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 rate
  • potential_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 / es
  • dew_point(t, rh) — dew point from temperature and relative humidity
  • density_altitude(pressure_altitude, temperature_c) — density altitude (aviation)
  • brunt_vaisala_frequency(g, theta, dtheta_dz) — atmospheric buoyancy frequency N

Atmospheric Dynamics API

  • coriolis_parameter(latitude, omega) — f = 2Ω sin(φ)
  • geostrophic_wind(dp_dx, dp_dy, rho, f) → (u_g, v_g) geostrophic wind components
  • rossby_number(u, l, f) — Ro = U / (fL)
  • rossby_wave_speed(beta, k) — phase speed of Rossby wave
  • thermal_wind(f, delta_t, delta_x, t_mean) — thermal wind shear
  • potential_vorticity(f, dtheta_dp) — Ertel potential vorticity
  • ekman_depth(nu, f) — Ekman layer depth
  • richardson_number(n2, du_dz) — Ri = N² / (∂u/∂z)²
  • rossby_deformation_radius(n, h, f) — Ld = NH / f
  • cyclone_gradient_wind(r, f, dp_dr, rho) — gradient wind balance in a cyclone

Precipitation API

  • rain_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 speed
  • thornthwaite_pet(t_mean, heat_index, day_length_hours) — Thornthwaite PET
  • penman_evaporation(delta, rn, gamma, ea, u) — Penman open-water evaporation
  • intensity_duration_frequency(a, b, duration, return_period) — IDF curve value
  • scs_curve_number_runoff(p, cn) — SCS-CN runoff depth from rainfall depth
  • rational_method_runoff(c, i, a) — Q = CiA peak discharge
  • unit_hydrograph_peak(a, tp) — SCS synthetic unit hydrograph peak
  • antecedent_precipitation_index(prev_api, rainfall, k) — API decay model

Radiation API

  • stefan_boltzmann_flux(t) — F = σT⁴ (W/m²)
  • solar_constant() — Solar constant S₀ ≈ 1361 W/m²
  • albedo_reflected(solar_flux, albedo) — reflected shortwave radiation
  • effective_temperature(solar_flux, albedo) — planetary equilibrium temperature
  • greenhouse_effect(t_surface, t_effective) — greenhouse warming ΔT
  • optical_depth(absorption_coeff, path_length) — τ = k × dz
  • beer_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⁴

Hub dispatch mapping

All meteorology functions are wired through:

  • src/hub/engine/dispatch/meteorology.rs
use 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)?;

Parser Source Code Guide

This page documents the source implementation behind sciforge::parser, including lexer/parser/value/error layering per format.

Source Coverage

What is explained

  • File-level implementation layout in src/parser/.
  • Main parsing algorithms and where they are implemented.
  • Runtime parse flow from byte cursor to typed value tree.

Visibility and external access

  • parser is public from src/lib.rs (pub mod parser;).
  • It can be consumed directly as sciforge::parser::{csv,json,yaml,markdown,html}.
  • Limit-based parse variants are recommended for untrusted inputs.

Source Code Explanation

Relevant file structure

  • Main implementation: src/parser/
  • Module entry point: src/parser/mod.rs
  • Hub routing (when applicable): (n/a - parser is direct)

Internal execution flow

  1. The module exposes format subdomains through mod.rs and targeted pub use exports.
  2. Each format combines lexer/parser/value/error files into a coherent parsing pipeline.
  3. Callers invoke parse or validate functions directly; no Hub dispatcher is required.

What to check while reading code

  • Exact signature: input/output types and argument order.
  • Lifetime and borrowing rules for zero-copy values.
  • Depth/size limit enforcement for untrusted inputs.

Modules

  • csv — RFC-4180 CSV parser
  • json — RFC-8259 JSON parser
  • yaml — YAML 1.2 subset parser
  • markdown — CommonMark Markdown parser
  • html — HTML5-like parser

All parsers share the same design philosophy:

  • Parse from `&[u8]` bytes without copying
  • Return a Result<*Value<'_>, *Error> with lifetime tied to input
  • Provide validate_* for syntax checking without full allocation
  • Provide *_with_limits variants for resource-bounded parsing

CSV API

Structs

StructDescription
CsvParser<'a>Streaming parser state over a byte slice
CsvLimitsConfigurable limits: max rows, max columns, max cell length
CsvErrorParse error with position info
CsvErrorPositionLine and column of the parse error
Cursor<'a>Low-level byte cursor used internally

Functions

  • `parse_csv(bytes: &[u8]) -> Result<CsvValue<'_>, CsvError>` — parse with default limits
  • `parse_csv_with_limits(bytes: &[u8], limits: CsvLimits) -> Result<CsvValue<'_>, CsvError>` — parse with custom limits
  • `validate_csv(bytes: &[u8]) -> Result<(), CsvError>` — validate syntax only
  • `write_csv(header: &[&str], rows: &[Vec<String>]) -> String` — serialize to CSV text

Example

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);

JSON API

Structs

StructDescription
JsonParser<'a>Recursive descent JSON parser
JsonLimitsMax nesting depth, max string length, max array/object size
JsonErrorParse error
JsonErrorPositionByte offset of the error

Functions

  • `parse_json(bytes: &[u8]) -> Result<JsonValue<'_>, JsonError>` — parse with default limits
  • `parse_json_with_max_depth(bytes: &[u8], max_depth: usize) -> Result<JsonValue<'_>, JsonError>`
  • `parse_json_with_limits(bytes: &[u8], limits: JsonLimits) -> Result<JsonValue<'_>, JsonError>`
  • `validate_json(bytes: &[u8]) -> Result<(), JsonError>` — syntax check only

Example

use sciforge::parser::json::parse_json;

let data = b"{\"x\": 3.14, \"label\": \"pi\"}";
let val = parse_json(data)?;

YAML API

Structs

StructDescription
YamlParser<'a>Line-oriented YAML parser
YamlLimitsMax nesting, max line count
YamlErrorParse error
YamlErrorPositionLine number of the error
YamlLine<'a>Parsed representation of a single YAML line
LineCursor<'a>Low-level cursor over lines

Functions

  • `parse_yaml(bytes: &[u8]) -> Result<YamlValue<'_>, YamlError>`
  • `parse_yaml_with_max_depth(bytes: &[u8], max_depth: usize) -> Result<YamlValue<'_>, YamlError>`
  • `parse_yaml_with_limits(bytes: &[u8], limits: YamlLimits) -> Result<YamlValue<'_>, YamlError>`
  • `validate_yaml(bytes: &[u8]) -> Result<(), YamlError>`
  • parse_scalar<'a>(raw: &'a str, offset: usize) -> Result<YamlValue<'a>, YamlError> — parse a bare scalar string

Markdown API

Structs

StructDescription
MdParser<'a>CommonMark Markdown parser (block + inline)
MdLimitsMax heading depth, max nesting, max line count
MdErrorParse error
MdErrorPositionLine and column of the error
MdLine<'a>Parsed line-level Markdown element
LineCursor<'a>Low-level line cursor

Functions

  • `parse_md(bytes: &[u8]) -> Result<MdValue<'_>, MdError>`
  • `parse_md_with_max_depth(bytes: &[u8], max_depth: usize) -> Result<MdValue<'_>, MdError>`
  • `parse_md_with_limits(bytes: &[u8], limits: MdLimits) -> Result<MdValue<'_>, MdError>`
  • `validate_md(bytes: &[u8]) -> Result<(), MdError>`
  • validate_inline(text: &str, base_offset: usize) -> Result<(), MdError> — validate inline markup only

HTML API

Structs

StructDescription
HtmlParser<'a>Tag-based HTML parser (DOM-tree output)
HtmlLimitsMax nesting depth, max attribute count
HtmlErrorParse error
HtmlErrorPositionLine and column of the error
Cursor<'a>Low-level byte cursor

Functions

  • `parse_html(bytes: &[u8]) -> Result<HtmlValue<'_>, HtmlError>`
  • `parse_html_with_max_depth(bytes: &[u8], max_depth: usize) -> Result<HtmlValue<'_>, HtmlError>`
  • `parse_html_with_limits(bytes: &[u8], limits: HtmlLimits) -> Result<HtmlValue<'_>, HtmlError>`
  • `validate_html(bytes: &[u8]) -> Result<(), HtmlError>`
  • validate_entity(cursor: &mut Cursor<'_>) -> Result<(), HtmlError> — validate a single HTML entity

Physics Source Code Guide

This page documents the source implementation behind sciforge::physics, including module layout and Hub dispatch wiring.

Source Coverage

What is explained

  • File-level implementation layout in src/physics/.
  • Main computation groups and where they are implemented.
  • Runtime call path when physics functions are executed through Hub dispatch.

Visibility and external access

  • This domain module is pub(crate) in src/lib.rs and is not part of the external crate API.
  • External consumers should use the public sciforge::hub API for these computations.
  • Direct module paths shown here are for internal development and source-level understanding.

Source Code Explanation

Relevant file structure

  • Main implementation: src/physics/
  • Module entry point: src/physics/mod.rs
  • Hub routing (when applicable): src/hub/engine/dispatch/physics.rs

Internal execution flow

  1. The module exposes subdomains through mod.rs and targeted pub use exports.
  2. Each .rs file implements a coherent block of equations and functions.
  3. The Hub invokes these functions through the domain dispatcher when execution goes through ExperimentRunner.

What to check while reading code

  • Exact signature: input/output types and argument order.
  • Numerical preconditions: divisions, roots, logarithms, and validity ranges.
  • Implicit conventions: units, normalization, bounds, and tolerances.

Modules

  • acoustics
  • electrodynamics
  • electronics
  • fluid_mechanics
  • materials
  • nucleosynthesis
  • optics
  • quantum
  • relativity
  • solid_mechanics
  • thermodynamics

Acoustics API (41 functions)

Submodules

  • absorption — sound absorption coefficients, acoustic impedance
  • doppler — Doppler shift, observer/source velocity effects
  • propagation — wave propagation, attenuation, speed in media
  • resonance — standing waves, resonance frequencies, Q-factor

Selected functions

  • doppler_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)

Electrodynamics API (49 functions)

Submodules

  • circuits — RC/RL/RLC, impedance, power
  • fields — electric/magnetic field computations
  • waves — electromagnetic wave properties, Poynting vector

Selected functions

  • capacitor_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)

Electronics API (76 functions)

Submodules

  • amplifiers — gain, bandwidth, noise figure
  • circuits — Kirchhoff laws, node analysis, thevenin/norton
  • digital — logic gates, binary operations
  • semiconductor_devices — diodes, transistors, MOSFET

Selected functions

  • voltage_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)

Fluid Mechanics API (47 functions)

Submodules

  • boundary_layer — Blasius, Reynolds, displacement/momentum thickness
  • flow — continuity, Bernoulli, pipe flow, Poiseuille
  • turbulence — Reynolds stress, turbulence intensity, mixing length
  • waves — surface waves, dispersion, wave speed

Selected functions

  • reynolds_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)

Materials API (44 functions)

Submodules

  • crystallography — lattice parameters, Miller indices, diffraction
  • diffusion — Fick's laws, diffusion coefficient
  • phases — phase diagrams, lever rule, Gibbs phase rule
  • semiconductors — carrier density, bandgap, doping

Selected functions

  • bragg_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)

Nucleosynthesis API (77 functions)

Submodules

  • decay — radioactive decay, half-life, activity
  • nuclide — binding energy, nuclear radius, separation energy
  • processes — pp-chain, CNO cycle, r/s-process rates
  • reactions — Q-value, cross-section, reaction rates
  • stellar — nuclear burning stages, energy generation

Selected functions

  • radioactive_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)

Optics API (45 functions)

Submodules

  • diffraction — single/double slit, grating equation
  • interference — thin film, Michelson, Young's experiment
  • polarization — Malus's law, Brewster angle, Stokes parameters
  • refraction — Snell's law, critical angle, refractive index dispersion

Selected functions

  • snell_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)

Quantum API (91 functions)

Submodules

  • angular — angular momentum, Clebsch-Gordan, ladder operators
  • information — density matrix, entanglement entropy, fidelity
  • operators — expectation values, commutators, Hermitian operators
  • perturbation — first/second-order energy corrections
  • spin — spin operators, Pauli matrices, spin states
  • systems — harmonic oscillator, hydrogen atom, particle in a box
  • wavefunctions — normalization, probability density, overlap integrals

Selected functions

  • particle_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)

Relativity API (31 functions)

Submodules

  • dynamics — relativistic energy, momentum, four-vectors
  • kinematics — time dilation, length contraction, velocity addition
  • lorentz — Lorentz factor, boosts, transformations

Selected functions

  • lorentz_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)

Solid Mechanics API (48 functions)

Submodules

  • elasticity — Hooke's law, Young's modulus, Poisson ratio
  • fracture — stress intensity factor, fracture toughness, crack growth
  • plasticity — yield criteria, strain hardening, plastic deformation
  • stress — stress/strain tensors, principal stresses, von Mises

Selected functions

  • hookes_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)

Thermodynamics API (54 functions)

Submodules

  • equations — equations of state (ideal gas, van der Waals, Redlich-Kwong)
  • processes — isothermal, adiabatic, isobaric, isochoric work/heat
  • statistical — Boltzmann factor, partition function, entropy

Selected functions

  • ideal_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)

Hub dispatch mapping

All physics functions are wired through:

  • src/hub/engine/dispatch/physics.rs
use sciforge::hub::prelude::*;

let exp = Experiment::new(DomainType::Physics, "lorentz_factor")
        .param("velocity", ParameterValue::Scalar(2.0e8));

let out = ExperimentRunner::new().run(&exp)?;
⚖️

MIT License

Copyright © 2026 Rayan

✅ Permission

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:

📋 Condition

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

⚠ Disclaimer

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.

Export Examples

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/.

Download Files

Astronomy (136 files)

Astronomy (136 files)

Benchmark (381 files)

Biology (81 files)

Chemistry (99 files)

Constants (111 files)

Geology (76 files)

Hub (109 files)

Maths (90 files)

Meteorology (79 files)

Physics (128 files)