### Install spectrafit-core with pip or uv Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Install the spectrafit-core package from PyPI using pip or uv. The uv command is an alternative to pip. ```bash pip install spectrafit-core # or: uv add spectrafit-core ``` -------------------------------- ### Install dependencies and start Vite dev server Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Installs npm dependencies and starts the Vite dev server on port 5173, which proxies /api requests to the FastAPI service on port 8000. Run from the web/ directory. ```bash npm install npm run dev # Vite dev server on :5173, proxies /api -> :8000 ``` -------------------------------- ### Expected output from Gaussian fit Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Example output from the quick start fit. Shows the fitted parameter values and the r_squared value. The block is reformatted for readability; actual print output is one long line and dict ordering may vary. ```text {'peak1.sigma': ParameterResult(value=1.2024163241228947, ..., stderr=0.004211511681961483), 'peak1.center': ParameterResult(value=0.49756589193680784, ..., stderr=0.004211469158787863), 'peak1.amplitude': ParameterResult(value=2.997594452290324, ..., stderr=0.00909249987508253)} 0.9979075074894731 ``` -------------------------------- ### Start FastAPI service with uv run poe serve Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Starts the FastAPI service on port 8000, which serves the /api/report endpoint. Run this from the repo root before starting the Vite dev server. ```bash uv run poe serve # FastAPI on :8000, serves /api/report ``` -------------------------------- ### Install pre-commit hooks with uv run pre-commit install Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/setup.md Run this command after a fresh clone to activate the git hooks. It wires 29 hooks into .git/hooks/ across the pre-commit, commit-msg, and pre-push stages. 27 of the 29 run automatically; the other two (rrt-doctor, rrt-release-check) are manual-stage only and must be invoked explicitly. ```bash uv run pre-commit install ``` -------------------------------- ### Run benchmark and regression gate Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Commands for running the benchmark and regression gate. `uv run poe benchmark` produces `results.json` and `manifest.json`; `benchmark_quick` uses lean repetitions for fast local iteration; `serve` starts a FastAPI server on http://localhost:8000; `gate` checks spectrafit-vs-lmfit regressions. The CLI alternatives use `oracles.cli` with `--reps` and `--mc` options. ```bash uv run poe benchmark # full run → results.json + manifest.json uv run poe benchmark_quick # lean reps, fast local iteration uv run poe serve # serve the latest report over FastAPI (http://localhost:8000) uv run poe benchmark_gate # spectrafit-vs-lmfit regression gate on the latest run # or the CLI directly PYTHONPATH=python uv run python -m oracles.cli run --reps 10 --mc 30 PYTHONPATH=python uv run python -m oracles.cli gate ``` -------------------------------- ### Run web report and generate TypeScript contract Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Commands to run the web report locally. Start the FastAPI backend with `uv run poe serve` in another shell, then `npm install` and `npm run dev` for the dev server (proxies /api to localhost:8000). Use `npm run build` for production, `npm run test` (or `npm run smoke`) for vitest rendering from fixtures, and `npm run contract` to regenerate TypeScript types from `/openapi.json`. ```bash uv run poe serve # serve the latest report over FastAPI (in another shell) cd web && npm install npm run dev # dev server; proxies /api → http://localhost:8000 (the FastAPI app) npm run build # production build → dist/ (fetches /api/report at runtime) npm run test # vitest: render all views from fixtures, no browser/API (alias: npm run smoke) npm run contract # regenerate src/openapi.gen.ts from the live /openapi.json ``` -------------------------------- ### Build spectrafit-core from source with uv and maturin Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Build spectrafit-core from source. Requires Rust toolchain and maturin. The `uv sync` command installs dev tooling (benchmark extra) and `uv run maturin develop` compiles the Rust extension. ```bash git clone https://github.com/Anselmoo/SpectraFit-Core.git cd SpectraFit-Core uv sync --extra benchmark # dev tooling is a dependency-group, installed by default uv run maturin develop ``` -------------------------------- ### Fit a single Gaussian peak with spectrafit_core Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/getting-started/quickstart.md Uses only the public spectrafit_core API: gaussian(), compose(), MeasurementData, and fit(). Requires spectrafit-core to be installed and importable; a ModuleNotFoundError on import means the installation step is missing. ```python import numpy as np from spectrafit_core import MeasurementData, compose, fit, gaussian # Synthetic "measured" data: a Gaussian peak plus a little noise. x = np.linspace(-5, 5, 200) y = 3.0 * np.exp(-0.5 * ((x - 0.5) / 1.2) ** 2) + np.random.default_rng(0).normal( 0, 0.05, x.size ) # Build the model graph: one Gaussian node with initial guesses. graph = compose([gaussian("peak1", amplitude=1.0, center=0.0, sigma=1.0)]) ``` -------------------------------- ### Run benchmark tasks with poe (bench_bg, bench_bg_status, bench_bg_collect, bench_bg_stop) Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/project-configuration.md Commands to start, monitor, collect, and stop the background benchmark ladder. The default rungs are 1, 2, 5, 10, 25. The citation-grade rung uses --reps 100 and takes roughly 6.8 hours. Rungs run sequentially to avoid core contention. ```bash uv run poe bench_bg # start (default rungs 1,2,5,10,25) uv run poe bench_bg -- --reps 100 # the citation-grade rung on its own uv run poe bench_bg_status # alive? how far along? uv run poe bench_bg_collect # rungs -> artifacts/deep/reps-N/ uv run poe bench_bg_stop ``` -------------------------------- ### Run end-to-end Playwright tests with poe web_e2e Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Runs 'cd web && npx playwright test' against a live API and Vite dev server. Install the browser once with 'npx playwright install chromium'. ```bash uv run poe web_e2e ``` -------------------------------- ### Fit a Gaussian peak with spectrafit_core Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Fit a single Gaussian peak to synthetic data using the public spectrafit_core API. The example is deterministic (seeded RNG) and recovers the true parameters (3.0, 0.5, 1.2) to within about one standard error. ```python import numpy as np from spectrafit_core import MeasurementData, compose, fit, gaussian # Synthetic "measured" data: a Gaussian peak plus a little noise. x = np.linspace(-5, 5, 200) y = 3.0 * np.exp(-0.5 * ((x - 0.5) / 1.2) ** 2) + np.random.default_rng(0).normal( 0, 0.05, x.size ) # Build the model graph: one Gaussian node with initial guesses. graph = compose([gaussian("peak1", amplitude=1.0, center=0.0, sigma=1.0)]).build() # Run the fit. result = fit(graph, MeasurementData(x=x.tolist(), y=y.tolist())) print(result.parameters) # fitted amplitude/center/sigma, keyed "peak1." print(result.r_squared) # goodness of fit ``` -------------------------------- ### Run benchmark suite with release profile Source: https://github.com/anselmoo/spectrafit-core/blob/main/reproducibility/figures/fig_code_benchmark.pdf Runs the benchmark suite after syncing the benchmark extra and building the extension in release mode. The release profile is required because a debug build is one to two orders of magnitude slower and would measure the build profiler rather than the solver. ```bash uv sync --extra benchmark && uv run maturin develop --release ``` -------------------------------- ### Reproduce NIST tables and figures with uv Source: https://github.com/anselmoo/spectrafit-core/blob/main/reproducibility/figures/README.md Run from a checkout of the repository. First syncs the benchmark extra, then sets MPLBACKEND and SOURCE_DATE_EPOCH, and runs the NIST head-to-head and table scripts plus the figure scripts. The scripts write next to themselves, overwriting committed files; compare with `git diff`. SOURCE_DATE_EPOCH fixes PDF timestamps so unchanged figures stay byte-identical, and on other hosts the last digits of `nist_table2.json` may differ by design. ```bash uv sync --extra benchmark cd reproducibility/figures export MPLBACKEND=Agg SOURCE_DATE_EPOCH=1700000000 PYTHONPATH=../../python uv run --no-sync python nist_head_to_head.py PYTHONPATH=../../python uv run --no-sync python nist_table2.py PYTHONPATH=../../python uv run --no-sync python nist_table2.py --tolerance 1e-15 for f in fig_nist_dual fig_nist_head_to_head fig_weighted_win fig_nist_catalogue fig_architecture; do PYTHONPATH=../../python uv run --no-sync python $f.py done ``` -------------------------------- ### PyO3 Entrypoints Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/reference/rust/binding-audit.md List of Python-callable functions exposed via PyO3 from the Rust core library. ```APIDOC ## PyO3 Entrypoints ### evaluate Forward model evaluation: graph + params + data -> JSON array of values. ### evaluate_components Per-component decomposition of the fitted model -> JSON object keyed by node id. ### fit Pydantic-validated FitGraph + MeasurementData + FitOptions -> fit result JSON. ### fit_arrays Array fast path for fit(): flat x/y/sigma buffers instead of MeasurementInput. ### fit_arrays_numpy Zero-copy numpy variant of fit_arrays for hot loops. ### model_type_wire_strings Canonical model-type wire strings generated from the model manifest; pins the Python ModelType enum to the Rust source. ``` -------------------------------- ### Build wheel locally with uv run maturin develop Source: https://github.com/anselmoo/spectrafit-core/blob/main/CONTRIBUTING.md Builds the wheel locally for the PyO3 extension. Requires Python ≥ 3.13, the Rust toolchain (stable), and maturin. ```shell uv run maturin develop ``` -------------------------------- ### Run benchmark suite and regression gate Source: https://github.com/anselmoo/spectrafit-core/blob/main/reproducibility/figures/fig_code_benchmark.tex Commands to run the benchmark suite, which writes a run directory holding per-case results and a manifest. The release profile is required for timing runs; a debug build is one to two orders of magnitude slower. The suite phase runs half the requested repetitions, so pass --reps 100 to reproduce the depth-50 rung. ```bash # The release profile is not optional for a timing run: a debug build of # the extension is one to two orders of magnitude slower, and measures the # build profile rather than the solver. uv sync --extra benchmark && uv run maturin develop --release # --reps and --mc set the depth. The suite phase runs HALF the requested # repetitions, so 2, 4 and 10 time each case 1, 2 and 5 times; both counts # are recorded per rung as reps_requested and reps_effective, and the # figures in Validation are indexed by the effective value -- to reproduce # the reported depth-50 rung, pass --reps 100. uv run python -m oracles.cli run --reps 2 # Four-axis regression gate against the pinned baseline. uv run python -m oracles.cli gate ``` -------------------------------- ### Run benchmark with reps and gate Source: https://github.com/anselmoo/spectrafit-core/blob/main/reproducibility/figures/fig_code_benchmark.pdf Runs the benchmark with a requested repetition count and then the four-axis regression gate. The suite runs HALF the requested repetitions, so --reps 2, 4, and 10 run each case 1, 2, and 5 times; both counts are recorded per run as reps_requested and reps_effective, and the figures in Validation are indexed by the effective value. To reproduce the reported depth-50 run, pass --reps 100. ```bash uv run python -m oracles.cli run --reps 2 ``` ```bash uv run python -m oracles.cli gate ``` -------------------------------- ### Compose and fit a Gaussian model with spectrafit_core Source: https://github.com/anselmoo/spectrafit-core/blob/main/reproducibility/figures/fig_code_compose.tex Builds a single-component model graph with a Gaussian named 'peak1' and fits it to measured x/y data. The result exposes parameters keyed by 'peak1.', each with .value and .stderr, plus an r_squared goodness-of-fit measure. The solver family is derived automatically when 'auto' is requested. ```python from spectrafit_core import MeasurementData, compose, fit, gaussian # x, y are the measured abscissa and ordinate. graph = compose([gaussian("peak1", amplitude=1.0, center=0.0, sigma=1.0)]).build() result = fit(graph, MeasurementData(x=list(x), y=list(y))) result.parameters # keyed "peak1."; each carries .value and .stderr result.r_squared # goodness of fit, as $R^2$ against the data ``` ```latex from spectrafit_core import MeasurementData, compose, fit, gaussian # x, y are the measured abscissa and ordinate. graph = compose([gaussian("peak1", amplitude=1.0, center=0.0, sigma=1.0)]).build() result = fit(graph, MeasurementData(x=list(x), y=list(y))) result.parameters # keyed "peak1."; each carries .value and .stderr result.r_squared # goodness of fit, as $R^2$ against the data ``` -------------------------------- ### Run dashboard panel tests with npm run test Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Run the vitest suite to verify panel titles are stable and no hardcoded backend IDs appear. ```bash npm run test ``` -------------------------------- ### Run offline report bundling with poe report_html Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Runs the benchmark and bundles the latest run into a self-contained, data-inlined report.html. Equivalent to 'npm run build:html' with BENCH_JSON set to the run's results. ```bash uv run poe report_html ``` -------------------------------- ### Reproduce paper figures with uv reproducibility group Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/project-configuration.md Reproduces the paper's figures from a clean clone using the self-contained, version-pinned reproducibility dependency group. The first command syncs the group; the second runs a specific figure script within it. ```bash uv sync --group reproducibility uv run --group reproducibility python reproducibility/figures/.py ``` -------------------------------- ### Pre-push validation commands Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/extending.md Run these commands for every stack your change touches. Rebuilding the extension with maturin is essential; otherwise Python tests may run against stale code. ```bash uv run --with maturin maturin develop --release # Python won't see Rust changes without this uv run poe lint_ci uv run poe scenario_smoke # fast cross-stack check uv run poe benchmark_gate # spectrafit-vs-lmfit regression gate ``` -------------------------------- ### Run full pre-push smoke check with poe web_smoke Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Runs 'cd web && npm ci && npm run typecheck && npm run smoke && npm run build' to perform typechecking, vitest (smoke is an alias for vitest run), and a production build that re-runs tsc --noEmit. ```bash uv run poe web_smoke ``` -------------------------------- ### Use FitOptions(solver="auto") to select a solver automatically Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/how-to/choosing-a-solver.md Use this snippet when you want the default solver selection. "auto" picks "varpro" when the model graph is separable (amplitudes are the only linear parameters, no tied parameters, no bound constraints on the nonlinear parameters) and otherwise falls back to "trf" (Coleman–Li bound-scaled Levenberg-Marquardt). The fallback is a deliberate choice, but its evidence is narrower than ```python from spectrafit_core import FitOptions options = FitOptions(solver="auto") ``` -------------------------------- ### Run all Rust unit tests with cargo test --workspace --lib Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/reference/rust/overview.md Runs all Rust unit tests in the workspace. Requires the PYO3_PYTHON environment variable to point to the Python interpreter from the uv-managed environment. ```bash PYO3_PYTHON="$(uv run python -c 'import sys; print(sys.executable)')" \ cargo test --workspace --lib ``` -------------------------------- ### Run tests with npx vitest run Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Runs the Vitest test suite. Alternatively, use npm run test. ```bash npx vitest run # or: npm run test ``` -------------------------------- ### Compose and fit a single Gaussian model Source: https://github.com/anselmoo/spectrafit-core/blob/main/reproducibility/figures/fig_code_compose.pdf Build a model graph with one Gaussian component named 'peak1', fit it to measurement data, and access the fitted parameters and R-squared value. The parameter keys follow the pattern 'peak1.' and each carries .value and .stderr. ```python fromspectrafit_coreimportMeasurementData, compose, fit, gaussian #x,yarethemeasuredabscissaandordinate. graph = compose([gaussian("peak1", amplitude=1.0, center=0.0, sigma=1.0)]).build() result = fit(graph, MeasurementData(x=list(x), y=list(y))) result.parameters#keyed"peak1.";eachcarries.valueand.stderr result.r_squared#goodnessoffit,asR² againstthedata ``` -------------------------------- ### Run fast checks with uv run poe and cargo test Source: https://github.com/anselmoo/spectrafit-core/blob/main/CONTRIBUTING.md Runs the fast checks: ruff CI-strict + ty via lint_ci, scenario smoke tests, and Rust tests for the specified crate. Replace with the actual crate name. ```shell uv run poe lint_ci ``` ```shell uv run poe scenario_smoke ``` ```shell cargo test -p spectrafit- ``` -------------------------------- ### Generate self-contained HTML report Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Single command to build a self-contained HTML report. Executes the benchmark and bundles everything into one offline `report.html` with all JS/CSS inlined and the report data as `window.__BENCH__`. The file can be tens of MB and its size scales with the backend roster and case catalog. ```bash uv run poe report_html # → .spectrafit_reports/benchmark//report.html (one file, tens of MB; # size scales with the backend roster and case catalog) ``` -------------------------------- ### Check stale GitHub branches and backport with uv run poe Source: https://github.com/anselmoo/spectrafit-core/blob/main/CONTRIBUTING.md Lists stale GitHub branches with un-backported commits older than 14 days (tune with --min-age-days, exit non-zero with --strict) and prints the recipe to backport a branch to GitLab. Replace with the branch name. ```shell uv run poe check_stale_github_branches ``` ```shell uv run poe backport_github ``` -------------------------------- ### Regenerate FAIR bundle and checksums Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/releasing.md Run these commands to regenerate the FAIR bundle and checksums after updating datePublished in CITATION.cff and codemeta.json. The bundle reads date-released from CITATION.cff. ```bash uv run poe fair bundle uv run --no-sync python scripts/fair.py checksums ``` -------------------------------- ### Run benchmark gate Source: https://github.com/anselmoo/spectrafit-core/blob/main/CONTRIBUTING.md Commands to run the benchmark gate, which must stay green for pull requests. The first uses Poe, the second runs the gate directly via Python. ```shell uv run poe benchmark_gate ``` ```shell uv run python -m oracles.cli gate ``` -------------------------------- ### Run workspace tests with cargo Source: https://github.com/anselmoo/spectrafit-core/blob/main/crates/README.md Runs the test suite for the spectrafit-core workspace. Use from the repository root to execute all crate tests. ```shell cargo test --workspace ``` -------------------------------- ### Module structure tree for python/oracles Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Directory tree showing the layout of the python/oracles module, including cases.py, models.py, backends/, engine.py, and other files. ```text python/oracles/ # was python/benchmark/, then python/extras/bench/ — merged F13 ├── cases.py # CategoryDef registry + CaseSpec/CaseFamily + build_catalog/materialize ├── models.py # MODEL_REGISTRY — numpy formulas (the parity oracle for the Rust kernels) ├── backends/ # spectrafit (the SUBJECT) + lmfit, jax/optimistix (cross-check oracles) ├── engine.py # build_report: run_suite (all 160) + run_featured (deep-dive every case); │ # re-imports _multidim/_global_fit from _engine_multidim (see below) ├── _engine_base.py, _engine_multidim.py, _engine_nested.py, _engine_profile.py │ # engine.py facade split (G27) — _engine_multidim.py's _multidim() fits │ # a genuine ≥3-D gaussian_nd recovery (real subject, not a 2-D map); │ # _global_fit() runs a GlobalFitGraph shared-model multi-spectrum joint fit ├── metrics.py # timing / accuracy / ECDF / spread / pull statistics ├── synth.py # deterministic synthetic BenchReport (test fixture; never served) ├── bench_contract.py # the FROZEN BenchReport contract (Pydantic) — single source of truth ├── contract.py # small shared-leaf module (SolverMeta, _Contract base) — NOT the BenchReport home ├── api.py # FastAPI: GET /api/report (latest), /api/runs, /api/report/{run_id} ├── reports.py # run-centric output: .spectrafit_reports//_run_NNN/ └── cli.py # `run` (write results.json + manifest.json) · `gate` (regression gate) ``` -------------------------------- ### Benchmark report folder layout Source: https://github.com/anselmoo/spectrafit-core/blob/main/README.md Directory layout created by each benchmark run. `results.json` contains the BenchReport contract payload served by the FastAPI app; `manifest.json` holds run metadata plus headline stats (geomean speedup, max |Δr²|, win-rate). `index.json` tracks all runs, newest first, and the latest run is resolvable via `oracles.reports.latest_results(category)`. ```text .spectrafit_reports//_run_NNN/ results.json # the BenchReport contract payload (served by the FastAPI app) manifest.json # run metadata + headline stats (geomean speedup, max |Δr²|, win-rate) .spectrafit_reports/index.json # all runs, newest first ``` -------------------------------- ### Regenerate OpenAPI contract with npm run contract Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Run this command with the API running to regenerate src/openapi.gen.ts from the live OpenAPI schema using openapi-typescript. ```bash npm run contract # openapi-typescript -> src/openapi.gen.ts ``` -------------------------------- ### Run full Python test suite with pytest Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/reference/rust/overview.md Runs the full Python test suite. Requires PYTHONPATH to be set to the python directory. ```bash PYTHONPATH=python uv run pytest -q tests/ ``` -------------------------------- ### Check repository structure with rrt folder check Source: https://github.com/anselmoo/spectrafit-core/blob/main/CONTRIBUTING.md Command to enforce the repository structure. It is run by pre-commit and CI, and required root files or directories must not be removed. ```shell rrt folder check ``` -------------------------------- ### Check all crates with cargo check --workspace Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/reference/rust/overview.md Runs cargo check across the entire workspace to verify all crates compile without errors. ```bash cargo check --workspace ``` -------------------------------- ### Architecture dependency graph (Mermaid flowchart) Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Shows the high-level build/data-flow view of the repository. The crate-level dependency DAG is documented separately in the Rust crate overview and is not duplicated here. ```mermaid flowchart LR crates["crates/
Rust workspace, 11 crates"] --> python["python/
pyo3 binding + oracles"] python --> web["web/
dashboard + report.html"] tests["tests/"] -. validates .-> crates tests -. validates .-> python benchmark["benchmark/"] --> web benchmark --> perf["docs/performance/"] docs["docs/"] -. consumes .-> crates docs -. consumes .-> python docs -. consumes .-> web ``` -------------------------------- ### Graph Jacobian pseudo-code with tie handling Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Pseudo-code for the Jacobian computation. It zeroes the Jacobian matrix, then for each node resolves parameters, obtains the node's analytical Jacobian (or finite-difference fallback) for each x-value coordinate, and accumulates the relevant entries into the global Jacobian columns using the per-node free-column mapping. When `tied_plan` is non-empty, ties are re-applied before each evaluation and the analytical Jacobian is replaced with a finite-difference one to capture tied-parameter chain-rule terms. ```text jac[i][j] = 0.0 for each node n in compiled.nodes: p = resolve params node_jac = n.model.jacobian(&x_vals[i], &p) // analytical (or FD fallback), coord slice for each (local_idx, jac_col) in node_free_cols[node_idx]: jac[i][jac_col] += node_jac[local_idx] ``` -------------------------------- ### Solver Dispatch Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/reference/rust/binding-audit.md List of Solver::Variant options available for the solver dispatch. ```APIDOC ## Solver Dispatch ### Solver::Auto Chooses VarPro or the faer LM family from the graph shape at run time. ### Solver::Dogleg Powell's dogleg trust-region method. ### Solver::Geodesic Geodesic acceleration on the faer LM core. ### Solver::Global Differential Evolution (global search); DE seed pinned at 0. ### Solver::Irls Iteratively-reweighted least squares (robust loss); weight fn selectable via 'irls:'. ### Solver::Lm Default faer Levenberg-Marquardt. ### Solver::LmLegacy nalgebra levenberg-marquardt parity oracle, retained for regression comparison. ### Solver::NewtonCg Matrix-free Newton-CG (Steihaug-Toint) trust-region method. ### Solver::Trf Trust-Region-Reflective (Coleman-Li bound scaling on the faer LM core). ### Solver::Varpro Variable Projection (separable nonlinear least squares). ``` -------------------------------- ### Add DOI badge to README.md Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/releasing.md Markdown snippet to add a Zenodo DOI badge to README.md, placed next to existing badges. The DOI is a placeholder. ```markdown [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.XXXXXXX.svg)](https://doi.org/10.5281/zenodo.XXXXXXX) ``` -------------------------------- ### Run Playwright pass on bundled report with poe report_e2e Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Runs a Playwright pass against the bundled report.html file. REPORT_HTML_PATH overrides the auto-detected path. ```bash uv run poe report_e2e ``` -------------------------------- ### Reproduce significant-digits measurement with uv run Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/explanation/verification-measurements.md Runs the significant-digits measurement script with 50 trials and a fixed seed for reproducibility. The full method and result tables are not included in the repository, so this command regenerates the data. ```bash uv run python scripts/measure_significant_digits.py --trials 50 --seed 20260821 ``` -------------------------------- ### Free port 8000 with lsof and xargs Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Use this one-liner to kill any process listening on TCP port 8000, which is needed when a stale 'serve' process is blocking the port. The same command is used internally by 'contract_regen'. ```bash lsof -tiTCP:8000 -sTCP:LISTEN | xargs kill ``` -------------------------------- ### Implement Model trait with eval and param_names Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/how-to/adding-a-model.md Required skeleton for a new model kernel. Implement eval and param_names; jacobian is provided by default via finite differences. Override jacobian for analytical derivatives. ```rust use crate::Model; /// Example skeleton — replace `MyModel`, the formula, and the parameter /// names with your own. /// /// Parameters (in order): `[a, b]`. pub struct MyModel; impl Model for MyModel { fn eval(&self, x: &[f64], params: &[f64]) -> f64 { let (a, b) = (params[0], params[1]); a * x[0].powi(2) + b } fn param_names(&self) -> Vec> { vec!["a".into(), "b".into()] } } ``` -------------------------------- ### Rust public API: evaluate, evaluate_components, jacobian Source: https://github.com/anselmoo/spectrafit-core/blob/main/ARCHITECTURE.md Typed Rust API in spectrafit-graph/src/lib.rs taking real Rust values (not JSON strings), usable as an rlib dependency without pyo3. Returns Result types with CoreError on failure. ```rust pub fn evaluate( graph: &FitGraphSpec, params_flat: &HashMap, x: &[f64], ) -> Result, CoreError>; pub fn evaluate_components( graph: &FitGraphSpec, params_flat: &HashMap, x: &[f64], ) -> Result>, CoreError>; pub fn jacobian( graph: &FitGraphSpec, params_flat: &HashMap, x: &[f64], ) -> Result, CoreError>; ``` -------------------------------- ### Register Gaussian model type in model_manifest! table Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/how-to/adding-a-model.md Adds the Gaussian model to the model_manifest! table in crates/spectrafit-types/src/types.rs. This single line generates the ModelTypeStr enum variant, its as_str() match arm, VARIANT_COUNT, and the ALL enumeration. The serde rename and as_str() return value must agree, pinned by the model_type_as_str_matches_serde_wire_for_every_variant test. ```rust Gaussian => "gaussian", ``` -------------------------------- ### Regenerate API contracts with poe contract_regen Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md After any FastAPI schema change, prefer this over the manual 'npm run contract' step. It drives one live API instance and regenerates all three checked-in schema mirrors: web/src/openapi.gen.ts, web/openapi.snapshot.json, and the Python golden. ```bash uv run poe contract_regen ``` -------------------------------- ### Python: Evaluate compiled graph at given parameters Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Evaluates the compiled graph at given parameters without fitting. Returns the model output as a NumPy array. Use this when you need model predictions for fixed parameters outside the fitting workflow. ```python # Evaluate compiled graph at given parameters, no fitting y_model: np.ndarray = graph.eval(params, data) # Per-node component outputs ``` -------------------------------- ### Define a Rust model kernel with the Model trait Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Defines the core trait for all model kernels. Implementations must provide eval and param_names; jacobian defaults to forward-difference finite differences, but most built-in kernels override with analytical formulas, while 11 models (asym_ir, breit_wigner, harmonic_ir, kww, log_normal, moffat, pearson7, split_gaussian, split_pearson7, students_t, tauc) use a hand-written central-difference FD loop instead. param_names returns an owned Vec> to support runtime-generated models like GaussianND{d}. ```rust pub trait Model: Send + Sync { /// x is a coordinate slice: len=1 for 1-D models, len>=n_dims() for nD models. fn eval(&self, x: &[f64], params: &[f64]) -> f64; /// Default: forward-difference finite differences. Most built-in kernels /// override with an analytical formula; 11 currently don't (asym_ir, /// breit_wigner, harmonic_ir, kww, log_normal, moffat, pearson7, /// split_gaussian, split_pearson7, students_t, tauc — each overrides /// with a hand-written central-difference FD loop instead, tracked as a /// follow-up to give them analytical Jacobians too). fn jacobian(&self, x: &[f64], params: &[f64]) -> Vec { /* FD fallback */ } /// Owned Vec> — not a static slice, so runtime-generated /// models (e.g. GaussianND{d}'s indexed center_0..center_{d-1}) can name /// their own params without a compile-time-static list. fn param_names(&self) -> Vec>; fn n_dims(&self) -> usize { 1 } // override for nD models } ``` -------------------------------- ### Rust structs for compiled DAG graph and node entries Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Core data structures for the compiled DAG graph. `CompiledGraph` holds node entries, sorted free parameter keys, per-node Jacobian column mappings, a dependency-ordered tie plan, and dataset offsets for global fits. `NodeEntry` stores the node ID, model trait object, parameter names, a free mask (vary=true and no expression), and an optional dataset index. Note that `ParamBinding`/`CompiledNode` names from earlier drafts do not exist in the current compiler. ```rust struct CompiledGraph { nodes: Vec, free_keys: Vec, // "node_id.param_name", sorted node_free_cols: Vec>, // per-node (local_param_idx, jac_col) tied_plan: TiedPlan, // dependency-ordered expr_edge plan dataset_offsets: Vec, // per-dataset point boundaries (global fits) } struct NodeEntry { id: String, model: Box, param_names: Vec, free_mask: Vec, // vary=true AND no expr, per param dataset_index: Option, // None = global node; Some(i) = dataset-local } ``` -------------------------------- ### FitResult data model with ParameterResult and DatasetSlice Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Defines the Pydantic models for a fit result. ParameterResult holds a single parameter's value, bounds, and metadata; DatasetSlice stores per-dataset model output and residuals; FitResult aggregates all fit statistics and arrays. Use when serializing or validating fit output from spectrafit-core. ```python class ParameterResult(BaseModel): value: float min: float max: float vary: bool expr: str | None scale: float | None # inherited from Parameter; solver step-size hint name: str | None = None # dotted "node_id.param" name, if known stderr: float | None # None if fit did not converge class DatasetSlice(BaseModel): label: str | None # from MeasurementData.label n_points: int best_fit: list[float] # model output for this dataset residuals: list[float] # (y - f) for this dataset, unweighted chi2: float # partial chi2 contribution class FitResult(BaseModel): schema_version: str = "0.1" parameters: dict[str, ParameterResult] covariance: list[list[float | None]] | None chi2: float reduced_chi2: float r_squared: float dof: int aic: float bic: float n_iter: int n_func_evals: int | None # None if unavailable n_jac_evals: int | None # None if unavailable success: bool message: str best_fit: list[float] # concatenated across all datasets ``` -------------------------------- ### Add a new panel record to PANELS[] Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/web-dashboard.md Add this record to the PANELS[] array in src/panels/registry.tsx to register a new dashboard panel. The make function calls your body function with the report and context. ```typescript { id: "my-new-panel", dest: "evidence", scope: "overview", section: "sec-compare", title: "My panel title", caption: "Description shown below the title", make: (r, ctx) => myBodyFunction(r, ctx), } ``` -------------------------------- ### Check rrt semver parsing with Version.parse Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/project-configuration.md Verifies that rrt's strict semver 2.0 parser rejects PEP 440 pre-release spellings like '0.1.0b1' with ValueError, while accepting plain '0.1.0' and semver-style '0.1.1-beta.1'. Use this to confirm upstream behavior before relying on rrt bump. ```python from repo_release_tools.version.semver import Version Version.parse("0.1.0") # OK Version.parse("0.1.0b1") # ValueError: Invalid semver: '0.1.0b1' Version.parse("0.1.1-beta.1") # OK ``` -------------------------------- ### Disable GitHub push URL for a remote Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/setup.md Disables the push URL of the GitHub remote so a hand-pushed branch cannot bypass the pre-push guard. Repeat for origin / SpectraFit-Core. The comment marks the command as repeatable for each GitHub remote. ```bash git remote set-url --push github DISABLED # repeat for origin / SpectraFit-Core ``` -------------------------------- ### Demotion rule for failed fits in postfit.rs Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/tutorials/gallery/failed_fit.md Checks whether a converged fit with r² < 0 is demoted to a failure. The condition triggers only when a free parameter key ends with .amplitude or .height and its absolute value is below 1% of the maximum absolute y value. This single threshold is the entire difference between reported and silent failures. ```rust (lk.ends_with(".amplitude") || lk.ends_with(".height")) && final_flat.get(k).is_some_and(|&v| v.abs() / y_max_abs < 1e-2) ``` -------------------------------- ### MeasurementData Pydantic model for multi-dimensional x, y, sigma Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Defines the MeasurementData schema with x as a flat or (N, D) matrix, y as shape (N,), optional sigma for uniform weighting, and an optional label. A before-validator promotes flat x input to (N, 1); D=1 for 1-D data. ```python class MeasurementData(BaseModel): schema_version: str = "0.1" x: list[list[float]] | list[float] # (N, D) matrix, OR flat (N,) — a # before-validator promotes flat # input to (N, 1); D=1 for 1-D data y: list[float] # shape (N,) sigma: list[float] | None # shape (N,) or None → uniform weight label: str | None = None # optional dataset identifier ``` -------------------------------- ### Parameter Pydantic model with constraint and scale fields Source: https://github.com/anselmoo/spectrafit-core/blob/main/ARCHITECTURE.md Defines the Parameter model for optimization parameters. The `expr` field, when set, makes the engine derive the value from the expression every solver iteration and causes `vary` to be ignored; `scale` defaults to |value| or 1.0 when None. Bounds (min, max) are enforced by the optimizer. ```python class Parameter(BaseModel): value: float # initial value min: float = -inf max: float = inf vary: bool = True # False → fixed constant; ignored when expr is set expr: str | None = None # constraint expression; evaluated every solver iteration scale: float | None = None # solver step-size hint; None → |value| or 1.0 ``` -------------------------------- ### Python: Evaluate compiled graph without fitting Source: https://github.com/anselmoo/spectrafit-core/blob/main/ARCHITECTURE.md Use FitGraph.eval() to evaluate the compiled graph at given parameters without invoking the LM solver. eval_components() returns per-node component outputs as a dict of numpy arrays. Both serialise graph, params, and data to JSON and call the Rust evaluate pyfunction. ```python # Evaluate compiled graph at given parameters, no fitting y_model: np.ndarray = graph.eval(params, data) # Per-node component outputs components: dict[str, np.ndarray] = graph.eval_components(params, data) ``` -------------------------------- ### FitResult and supporting Pydantic models Source: https://github.com/anselmoo/spectrafit-core/blob/main/ARCHITECTURE.md Defines the data models for a fit result: ParameterResult holds per-parameter bounds, variance, and expression; DatasetSlice stores per-dataset best fit, residuals, and partial chi2; FitResult aggregates parameters, covariance, statistics, and fit arrays. Use when serializing or validating fit output from spectrafit-core. ```python class ParameterResult(BaseModel): name: str value: float min: float max: float vary: bool expr: str | None stderr: float | None # None if fit did not converge class DatasetSlice(BaseModel): label: str | None # from MeasurementData.label n_points: int best_fit: list[float] # model output for this dataset residuals: list[float] # (y - f) / sigma for this dataset chi2: float # partial chi2 contribution class FitResult(BaseModel): schema_version: str = ``` -------------------------------- ### Parameter model definition in Python Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Defines the Pydantic Parameter model with fields for initial value, bounds, variation flag, constraint expression, and solver step-size hint. The `vary` flag is ignored whenever `expr` is set; the engine always derives the value from the expression and excludes the parameter from the free set. `name` is the dict key in `ModelNodeSpec.parameters`, not a field. ```python class Parameter(BaseModel): value: float # initial value min: float = -inf max: float = inf vary: bool = True # False → fixed constant; ignored when expr is set expr: str | None = None # constraint expression; evaluated every solver iteration scale: float | None = None # solver step-size hint; None → 1.0 (identity, no-op) ``` -------------------------------- ### Graph evaluation pseudo-code Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/architecture.md Pseudo-code for the graph evaluation routine. It initializes each output element to zero, then for every compiled node resolves its parameters using the free mask and parameter names, and accumulates each model's evaluation over all x-value coordinates. The comment notes that `coord` is a slice of length D. ```text output[i] = 0.0 for each node n in compiled.nodes: p = resolve params via n.free_mask / n.param_names for each i, coord in x_vals: // coord = &x_vals[i] (len D) output[i] += n.model.eval(coord, &p) ``` -------------------------------- ### Define ModelNodeSpec and ExprEdge Pydantic models Source: https://github.com/anselmoo/spectrafit-core/blob/main/ARCHITECTURE.md Defines the Pydantic models for graph nodes and edges. ModelNodeSpec represents a typed model instance with named parameters and optional dataset scoping; ExprEdge encodes parameter constraints (ties) with an expression string evaluated in Rust. ```python class ModelNodeSpec(BaseModel): id: str # unique within graph model_type: ModelType # Gaussian | Lorentzian | ... parameters: dict[str, Parameter] dataset_index: int | None = None # None = global node; multi-dataset scoping ``` ```python class ExprEdge(BaseModel): target_node: str target_param: str expression: str # e.g. "0.5 * peak1.amplitude" ``` -------------------------------- ### Add concept DOI to CITATION.cff Source: https://github.com/anselmoo/spectrafit-core/blob/main/docs/contributor-guide/releasing.md YAML snippet to add the concept DOI under the 'identifiers' key in CITATION.cff. The value is a placeholder and should be replaced with the actual concept DOI. ```yaml identifiers: - type: doi value: "10.5281/zenodo.XXXXXXX" description: "Concept DOI: always resolves to the latest archived version." ``` -------------------------------- ### Disable GitHub remote push URL Source: https://github.com/anselmoo/spectrafit-core/blob/main/CONTRIBUTING.md Disables the push URL of a GitHub remote to prevent accidental pushes, even with --no-verify. Replace with the remote name. ```shell git remote set-url --push DISABLED ```