Skip to content

Turn any AI agent into an AI Scientist. The #1 Agent Skills library for science, used by 250,000+ scientists worldwide. 177 ready-to-use validated skills plus 100+ scientific databases covering biology, chemistry, medicine, and drug discovery. Compatible with Cursor, Claude Code, Codex, Pi, Antigravity, and the open Agent Skills standard.

Add steady-state 13C metabolic flux analysis skill

Timothy Kassis65d6e786832e
diff --git a/README.md b/README.md
index 29b9261a..6ff87f31 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE.md)
[![arXiv](https://img.shields.io/badge/arXiv-2609.00065-b31b1b.svg)](https://arxiv.org/abs/2609.00065)
[![Version](https://img.shields.io/badge/Version-2.70.0-blue.svg)](pyproject.toml)
-[![Skills](https://img.shields.io/badge/Skills-167-brightgreen.svg)](#-whats-included)
+[![Skills](https://img.shields.io/badge/Skills-168-brightgreen.svg)](#-whats-included)
[![Databases](https://img.shields.io/badge/Databases-100%2B-orange.svg)](#-whats-included)
[![Agent Skills](https://img.shields.io/badge/Standard-Agent_Skills-blueviolet.svg)](https://agentskills.io/)
[![Agent Plugins](https://img.shields.io/badge/Standard-Agent_Plugins-0A7A72.svg)](https://agent-plugins.org/)
@@ -17,7 +17,7 @@
> **🔔 Claude Scientific Skills is now Scientific Agent Skills.** Same skills, broader compatibility — now works with any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, not just Claude.
-> **New: [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok)** — A free, open-source AI co-scientist that runs on your desktop, powered by Scientific Agent Skills. Bring your own API keys, pick from 40+ models, and get a full research workspace with web search, file handling, 100+ scientific databases, and access to all 167 skills in this repo. Your data stays on your computer, and you can optionally scale to cloud compute via [Modal](https://modal.com/) for heavy workloads. [Get started here.](https://github.com/K-Dense-AI/k-dense-byok)
+> **New: [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok)** — A free, open-source AI co-scientist that runs on your desktop, powered by Scientific Agent Skills. Bring your own API keys, pick from 40+ models, and get a full research workspace with web search, file handling, 100+ scientific databases, and access to all 168 skills in this repo. Your data stays on your computer, and you can optionally scale to cloud compute via [Modal](https://modal.com/) for heavy workloads. [Get started here.](https://github.com/K-Dense-AI/k-dense-byok)
> **🎥 Webinar recording — [Getting Started with K-Dense BYOK](https://youtu.be/Du3BIE48DKc?si=9dPpETKSc2PeQbvU)**
> A hands-on walkthrough of [K-Dense BYOK](https://github.com/K-Dense-AI/k-dense-byok), our free, open-source AI co-scientist that runs locally on your own machine and is powered by Scientific Agent Skills. We cover how to set it up, bring your own API keys, and run real research workflows with these skills. No prior technical experience needed. **[Watch the recording →](https://youtu.be/Du3BIE48DKc?si=9dPpETKSc2PeQbvU)**
@@ -26,7 +26,7 @@
> **📄 Paper:** Scientific Agent Skills is described in [*Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents*](https://arxiv.org/abs/2609.00065) (arXiv:2609.00065). If you use these skills in your research, please [cite the paper](#-citation).
-A comprehensive collection of **167 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, genome-wide precomputed variant effects from the AlphaGenome Atlas, hosted regulatory-sequence prediction, live pathogen-variant surveillance, analytical method validation, PK/PD modelling and dose selection, full-text biomedical and regulatory literature retrieval, drug-target binding, bounded biomedical knowledge graph search, custom lab-part fabrication quotes and orders through Fictiv, molecular dynamics, RNA velocity, microbiome foundation models, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). The repository is also a portable [Agent Plugins](https://agent-plugins.org/) package (`plugin.json` + `skills/`), so plugin-capable clients can load the whole collection as one plugin. Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.
+A comprehensive collection of **168 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, genome-wide precomputed variant effects from the AlphaGenome Atlas, hosted regulatory-sequence prediction, live pathogen-variant surveillance, analytical method validation, PK/PD modelling and dose selection, full-text biomedical and regulatory literature retrieval, drug-target binding, bounded biomedical knowledge graph search, custom lab-part fabrication quotes and orders through Fictiv, molecular dynamics, RNA velocity, microbiome foundation models, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). The repository is also a portable [Agent Plugins](https://agent-plugins.org/) package (`plugin.json` + `skills/`), so plugin-capable clients can load the whole collection as one plugin. Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.
> ⭐ **Help make AI for science easier to discover:** If Scientific Agent Skills saves you time, teaches your agent a workflow, or helps your lab move faster, please [star this repository](https://github.com/K-Dense-AI/scientific-agent-skills). A star is a public signal that these open, reusable research skills are worth maintaining: it helps scientists, engineers, and open-source contributors find the project, shows which agent-skill standards are gaining real adoption, and gives us a clear reason to keep expanding the collection for the community.
@@ -74,7 +74,7 @@ Recorded walkthroughs of these skills on real research tasks, from the [K-Dense
## 📦 What's Included
-This repository provides **167 scientific and research skills** organized into the following categories:
+This repository provides **168 scientific and research skills** organized into the following categories:
- **100+ Scientific & Financial Databases** - A unified database-lookup skill provides deterministic, provenance-rich access to 78 public databases (PubChem, ChEMBL, UniProt, COSMIC, ClinicalTrials.gov, FRED, USPTO, and more), plus dedicated skills for DepMap, Imaging Data Commons, PrimeKG, NCATS ARAX, U.S. Treasury Fiscal Data, Hugging Science, OneKGPd, Genomic Intelligence, and AlphaGenome (Atlas lookups and model scoring). Multi-database packages like BioServices (~40 bioinformatics services), BioPython (39 NCBI sub-databases via Entrez), and gget (20+ genomics databases) add further coverage
- **70+ Optimized Python Package Skills** - Explicitly defined, version-aware workflows for RDKit, Scanpy, PyTorch Lightning, scikit-learn, PyTDC, PathML, pydicom, NeuroKit2, PufferLib, QuTiP, GeoPandas, pymatgen, BioPython, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), and others. The agent can still use *any* Python package; these skills provide stronger, safer guidance for the packages listed
@@ -121,7 +121,7 @@ Each skill includes:
- **Multi-Step Workflows** - Execute complex pipelines with a single prompt
### 🎯 **Comprehensive Coverage**
-- **167 Skills** - Extensive coverage across all major scientific domains
+- **168 Skills** - Extensive coverage across all major scientific domains
- **100+ Databases** - Unified access to 78+ databases via database-lookup, plus dedicated data access skills and multi-database packages like BioServices, BioPython, and gget
- **70+ Optimized Python Package Skills** - Current, version-scoped guidance for packages including RDKit, Scanpy, PyTorch Lightning, scikit-learn, PyTDC, pydicom, PufferLib, QuTiP, GeoPandas, pymatgen, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), scVelo, and TimesFM (the agent can use any Python package; these are the pre-documented paths)
@@ -228,7 +228,7 @@ For Hermes versions that support skill taps, add the repository as a tap:
hermes skills tap add K-Dense-AI/scientific-agent-skills
```
-Every `SKILL.md` has YAML frontmatter, but legacy and community skills vary in `metadata` formatting (block or flow style) and optional extension fields. Repository updates must keep `metadata.version` as a quoted numeric string and pass canonical `skills-ref validate ./skills/<skill-name>` checks. Hosts may interpret optional metadata and credential prompts differently, so verify behavior on the target host. Because 167 skills add up to a lot of standing context, consider installing a topical subset rather than the whole collection.
+Every `SKILL.md` has YAML frontmatter, but legacy and community skills vary in `metadata` formatting (block or flow style) and optional extension fields. Repository updates must keep `metadata.version` as a quoted numeric string and pass canonical `skills-ref validate ./skills/<skill-name>` checks. Hosts may interpret optional metadata and credential prompts differently, so verify behavior on the target host. Because 168 skills add up to a lot of standing context, consider installing a topical subset rather than the whole collection.
> **NemoClaw note:** NemoClaw runs agents inside NVIDIA OpenShell with default-deny outbound networking. Skills are discovered and loaded normally, but any skill that needs the network — package installs via `uv`, or API calls (Exa, Parallel, Benchling, NCBI, Materials Project, …) — only works once the operator pre-approves the relevant domains in the OpenShell TUI.
@@ -469,7 +469,7 @@ networks, and search GEO for similar patterns.
## 📚 Available Skills
-This repository contains **167 scientific and research skills** organized across multiple domains. Each skill provides comprehensive documentation, code examples, and best practices for working with scientific libraries, databases, and tools.
+This repository contains **168 scientific and research skills** organized across multiple domains. Each skill provides comprehensive documentation, code examples, and best practices for working with scientific libraries, databases, and tools.
### Skill Categories
@@ -567,9 +567,10 @@ This repository contains **167 scientific and research skills** organized across
- Protocol management: bounded protocols.io reads across documented v3/v4 endpoints and non-executing write plans
- LIMS/ELN integration: Benchling and the separate LabArchives legacy ELN and Inventory v1 APIs
-#### 🔬 **Multi-omics & Systems Biology** (3 skills)
+#### 🔬 **Multi-omics & Systems Biology** (4 skills)
- Pathway analysis: via Database Lookup (KEGG, Reactome, STRING) and PrimeKG
- Data management: LaminDB
+- Carbon-13 metabolic flux inference: [13C Metabolic Flux](skills/13c-metabolic-flux/SKILL.md) (validated atom maps, steady-state isotope simulation, constrained fitting, and flux-identifiability profiles)
#### 🧬 **Protein Engineering & Design** (4 skills)
- Protein language models: ESM
@@ -924,7 +925,7 @@ If you also need to cite a specific version of the repository itself (for exampl
title = {Scientific Agent Skills: A Comprehensive Collection of Scientific Tools for AI Agents},
year = {2026},
url = {https://github.com/K-Dense-AI/scientific-agent-skills},
- note = {167 skills covering databases, packages, integrations, and analysis tools}
+ note = {168 skills covering databases, packages, integrations, and analysis tools}
}
```
diff --git a/skills/13c-metabolic-flux/SKILL.md b/skills/13c-metabolic-flux/SKILL.md
new file mode 100644
index 00000000..e2aa2418
--- /dev/null
+++ b/skills/13c-metabolic-flux/SKILL.md
@@ -0,0 +1,208 @@
+---
+name: 13c-metabolic-flux
+description: Estimates intracellular metabolic fluxes from steady-state carbon-13 isotope-tracing measurements using validated atom maps, mfapy isotope simulation, constrained multistart fitting, and flux-profile diagnostics. Use for 13C-MFA, carbon tracing, mass isotopomer distributions (MDVs/MIDs), positional isotopomers, parallel tracer experiments, and determining whether labeling data constrain a pathway flux. Distinguishes measured-label inference from COBRA flux balance analysis and flags experiments requiring nonstationary MFA.
+license: MIT
+compatibility: Python 3.11 with uv and Git for installation. Tested with mfapy 0.6.3 at a10433af16682386548b360297e2476152d46ede, NumPy 2.4.6, SciPy 1.17.1, and NLopt 2.11.0. Network access is needed only to install public dependencies. Inference runs locally without credentials; inputs are JSON.
+metadata:
+ version: "1.0"
+ skill-author: K-Dense Inc.
+ last-reviewed: "2026-09-29"
+---
+
+# Carbon-13 metabolic flux inference
+
+Turn reviewed carbon maps, explicit tracer mixtures, and corrected labeling measurements
+into feasible flux estimates and evidence about which fluxes the experiment constrains.
+Use the bundled solver rather than reconstructing isotope balances or fitting each
+reaction independently. It runs mfapy's EMU forward simulator and fits fluxes in the
+mass-balanced feasible space with SciPy. It does not use an FBA objective.
+
+## Scope and required evidence
+
+This implementation supports **metabolic and isotopic steady state**, a single shared
+flux state across one or more tracer experiments, nonnegative one-way reaction fluxes,
+and carbon-subset mass distributions. Reversible reactions are two separately mapped
+directions. Measurement error is Gaussian with a supplied covariance or a disclosed
+diagonal approximation.
+
+Before fitting, obtain:
+
+- The carbon network and the source of each atom assignment. Stoichiometry alone does
+ not specify where labeled atoms go. Record compartments as separate metabolite IDs.
+- Evidence for both steady-state assumptions. Stable metabolite abundance does not
+ establish isotopic steady state. Time-course labeling requires INST-MFA with pool
+ sizes and initial labeling; do not average it into this solver.
+- Every carbon input's positional isotopomer distribution, including unlabeled
+ supplements, bicarbonate/CO2 when assimilated, and tracer impurity.
+- Fragment carbon assignments, natural-abundance correction history, and uncertainty
+ of the **reported mean**. Raw peak intensities, derivatized spectra, and MS/MS
+ transitions require validated preprocessing before these inputs can be constructed.
+- Flux units, extracellular rate measurements or a stated relative-flux reference,
+ and biologically justified bounds. Label fractions alone cannot set an absolute rate.
+
+If necessary information is missing, name it and prepare the input template; do not
+invent a fragment assignment, atom map, isotope correction, or measurement error.
+Read [references/input-contract.md](references/input-contract.md) when preparing inputs.
+Read [references/inference.md](references/inference.md) before interpreting an actual fit.
+
+## Install the tested engine
+
+Run in the user's analysis directory. Set `SKILL_DIR` to this skill's installed directory,
+using the actual resolved path. Keep environments and generated results outside the skill.
+
+```bash
+uv venv --python 3.11 .venv-mfa
+uv pip install --python .venv-mfa/bin/python -r "$SKILL_DIR/assets/requirements.txt"
+```
+
+The following commands use `.venv-mfa/bin/python`; on Windows use the environment's
+`Scripts/python.exe`. mfapy is installed from an immutable Git revision because it is
+not distributed on PyPI. Installation executes dependency build code; model inputs
+are data, not user-supplied Python. The adapter restricts identifiers and atom-map
+syntax before they reach mfapy's internally generated numerical functions.
+
+## Workflow
+
+1. **Prepare explicit inputs.** Copy a relevant model asset into the analysis directory,
+ then replace its scientific content only from reviewed evidence. The bundled models
+ are demonstrations, not validated organism-specific reconstructions. Use a separate
+ dataset for each biological condition; jointly fit tracer replicates only when their
+ biological flux state is defensibly shared.
+2. **Check the contract and feasibility.**
+
+ ```bash
+ .venv-mfa/bin/python "$SKILL_DIR/scripts/mfa.py" check \
+ --model model.json --data measurements.json --output input-check.json
+ ```
+
+ This checks atom counts and conservation, fragments, tracer sums, uncertainty
+ matrices, bounds, and steady-state mass-balance feasibility. It cannot verify that a
+ chemically consistent atom map is biologically correct or that a sample reached steady state.
+3. **Exercise the forward model.** Supply one mass-balanced flux vector in the declared
+ units. Compare predicted labeling with a reference or independently derived limits.
+
+ ```bash
+ .venv-mfa/bin/python "$SKILL_DIR/scripts/mfa.py" simulate \
+ --model model.json --data measurements.json --fluxes fluxes.json \
+ --output simulated-mdvs.json
+ ```
+
+4. **Fit and profile the fluxes relevant to the question.**
+
+ ```bash
+ .venv-mfa/bin/python "$SKILL_DIR/scripts/mfa.py" fit \
+ --model model.json --data measurements.json --starts 12 --seed 2026 \
+ --profile v3 --profile v7 --profile-points 31 --profile-starts 6 \
+ --output fit.json
+ ```
+
+ Replace `v3` and `v7` with actual reaction IDs. Each profile point fixes that reaction
+ and reoptimizes nuisance fluxes. For nonlinear networks, repeat with a different seed
+ and more starts before interpreting a profile. A small residual is not an
+ identifiability result.
+5. **Inspect the evidence.** Check failed starts, residual patterns, mass balance,
+ active bounds, local sensitivity rank, and profile status. Report threshold-crossing
+ brackets at their actual grid resolution. Refine the grid if they are too coarse.
+ If a profile finds a better solution than the baseline, rerun the fit; do not publish
+ the stale intervals. A failed profile point is unknown, not excluded by the data.
+6. **Deliver a bounded scientific result.** Include model and data hashes, package
+ versions, source/correction provenance, units and reference flux, fitted predictions,
+ residual diagnostics, profile plots or a table, and the unresolved flux combinations.
+ Retain the JSON artifact. Separate point estimates supported by the data from arbitrary
+ optimizer choices along a flat direction. Suggest additional measurements only after
+ testing that their predicted labeling changes along that direction.
+
+## Worked examples
+
+These executable examples use synthetic, tracer-only data. There is no hidden natural-
+abundance correction, and the tracer proportions already include unlabeled material.
+
+### Recover a pathway split; then remove the informative measurement
+
+The analytical two-route model sends a two-carbon substrate through either a
+carbon-preserving or a carbon-swapping route. Uptake is fixed to 100. An 80% carbon-1
+labeled feed and a carbon-1 fragment with M+1 = 0.56 determine the preserving route
+as 70 and the swapping route as 30.
+
+```bash
+.venv-mfa/bin/python "$SKILL_DIR/scripts/mfa.py" fit \
+ --model "$SKILL_DIR/assets/branch-model.json" \
+ --data "$SKILL_DIR/assets/branch-identifiable.json" \
+ --profile straight --profile-points 41 --output branch-fit.json
+
+.venv-mfa/bin/python "$SKILL_DIR/scripts/mfa.py" fit \
+ --model "$SKILL_DIR/assets/branch-model.json" \
+ --data "$SKILL_DIR/assets/branch-unresolved.json" \
+ --profile straight --output unresolved-fit.json
+```
+
+The first fit recovers approximately 70/30. Under its declared Gaussian error model,
+the analytical 95% interval for `straight` is about 67.55–72.45; the script reports
+grid brackets enclosing the threshold crossings. The second fit has only the whole-
+molecule distribution, which is identical for the two routes. Expect local rank zero
+and `unresolved_within_bounds`; its returned split is an arbitrary optimum.
+
+`assets/branch-fluxes.json` supplies the 70/30 forward-simulation vector.
+
+### Reproduce a published cyclic-network calculation
+
+```bash
+.venv-mfa/bin/python "$SKILL_DIR/scripts/mfa.py" simulate \
+ --model "$SKILL_DIR/assets/tca-model.json" \
+ --data "$SKILL_DIR/assets/tca-tracer.json" \
+ --fluxes "$SKILL_DIR/assets/tca-fluxes.json" --output tca-simulation.json
+
+.venv-mfa/bin/python "$SKILL_DIR/scripts/mfa.py" fit \
+ --model "$SKILL_DIR/assets/tca-model.json" \
+ --data "$SKILL_DIR/assets/tca-reference-mdv.json" \
+ --profile v3 --profile v7 --output tca-fit.json
+```
+
+The first command reproduces the published rounded glutamate MDV
+`[0.3464, 0.2695, 0.2708, 0.0807, 0.0286, 0.0039]`.
+The second uses synthetic reference measurements to recover the glutamate branch
+flux near 50, while recognizing that this labeling does not resolve the
+fumarate/oxaloacetate exchange. A constraint-induced upper edge is not evidence of
+a measurement-determined exchange interval.
+
+## Interpretation boundaries
+
+- A positional isotopomer string runs **carbon 1 to carbon N from left to right**.
+ `"100000"` means carbon-1 labeled glucose. A mass distribution alone cannot specify
+ that positional mixture. The adapter handles mfapy's reversed integer-bit ordering.
+- Natural-abundance correction and tracer-purity correction are different operations.
+ Inputs must be in the documented tracer-only basis, with tracer impurity represented
+ consistently in source mixtures. Do not correct the same contribution twice.
+- An N-carbon mass distribution has at most N independent components because it sums
+ to one. The tool removes one bin and uses the reduced covariance. Retain cross-bin
+ correlations when available. Diagonal SEM fits are explicitly approximate.
+- The `symmetric` flag means equal averaging of identity and **complete carbon-order
+ reversal**, as in the bundled fumarate/succinate map. It is not arbitrary molecular
+ symmetry. Other permutations need an explicitly supported model representation.
+- Unsupported in this CLI: nonstationary MFA, isotope effects on reaction rates,
+ unmodeled pools or compartments, MS/MS joint distributions, multi-element isotope
+ correction, fractional carbon stoichiometry/pseudo-reactions, and organism-scale
+ performance guarantees. For these, use a validated specialized model/engine and
+ retain the same input/provenance and identifiability discipline.
+
+## Implementation and validation
+
+`scripts/mfa.py` is the CLI. `scripts/_mfa_model.py` validates inputs and adapts them to
+the mfapy EMU simulator; `scripts/_mfa_fit.py` handles feasible flux coordinates,
+multistart optimization, diagnostic rank, and profile calculations.
+The engine is pinned in [assets/requirements.txt](assets/requirements.txt).
+
+The repository suite at `tests/13c-metabolic-flux/` checks the published reference,
+analytical split recovery and likelihood profiles, unresolved routes and exchange,
+omitted-bin invariance with correlated errors, parallel tracers, absolute-rate
+anchoring, repeated-substrate condensation, symmetry, invalid maps, and CLI behavior.
+These checks establish the tested numerical behavior, not biological validation of a
+user's model or a measured advantage over any particular language model.
+
+## Sources
+
+- [mfapy source at the tested revision](https://github.com/fumiomatsuda/mfapy/tree/a10433af16682386548b360297e2476152d46ede), version 0.6.3; [API documentation](https://fumiomatsuda.github.io/mfapy-document/mfapy.html).
+- Matsuda et al. (2021), [mfapy: An open-source Python package for 13C-based metabolic flux analysis](https://doi.org/10.1016/j.mec.2021.e00177).
+- Antoniewicz, Kelleher, and Stephanopoulos (2007), [Elementary metabolite units (EMU): A novel framework for modeling isotopic distributions](https://doi.org/10.1016/j.ymben.2006.09.001).
+- The TCA network is adapted from mfapy's MIT-licensed example files; the attribution
+ and full notice are in [assets/mfapy-license.txt](assets/mfapy-license.txt).
diff --git a/skills/13c-metabolic-flux/assets/branch-fluxes.json b/skills/13c-metabolic-flux/assets/branch-fluxes.json
new file mode 100644
index 00000000..c508ae96
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/branch-fluxes.json
@@ -0,0 +1,6 @@
+{
+ "uptake": 100,
+ "straight": 70,
+ "swap": 30,
+ "export": 100
+}
diff --git a/skills/13c-metabolic-flux/assets/branch-identifiable.json b/skills/13c-metabolic-flux/assets/branch-identifiable.json
new file mode 100644
index 00000000..8c37baab
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/branch-identifiable.json
@@ -0,0 +1,41 @@
+{
+ "schema_version": 1,
+ "steady_state": {
+ "metabolic": true,
+ "isotopic": true
+ },
+ "shared_fluxes": true,
+ "mdv_basis": "tracer_only",
+ "correction_notes": "Synthetic tracer-only probabilities; no natural-abundance correction applied. Isotopomer mixtures explicitly include unlabeled material.",
+ "experiments": [
+ {
+ "id": "C1label",
+ "substrates": {
+ "S": {
+ "10": 0.8,
+ "00": 0.2
+ }
+ },
+ "measurements": [
+ {
+ "fragment": "Bfirst",
+ "mdv": [
+ 0.44,
+ 0.56
+ ],
+ "covariance": [
+ [
+ 0.0001,
+ -0.0001
+ ],
+ [
+ -0.0001,
+ 0.0001
+ ]
+ ],
+ "omit": 1
+ }
+ ]
+ }
+ ]
+}
diff --git a/skills/13c-metabolic-flux/assets/branch-model.json b/skills/13c-metabolic-flux/assets/branch-model.json
new file mode 100644
index 00000000..0b8585ed
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/branch-model.json
@@ -0,0 +1,122 @@
+{
+ "schema_version": 1,
+ "name": "Two-route positional-label demonstration",
+ "flux_unit": "relative units; uptake fixed to 100",
+ "provenance": "Original analytical demonstration. Generic carbon rearrangement, not an organism-specific pathway.",
+ "metabolites": [
+ {
+ "id": "S",
+ "carbons": 2,
+ "boundary": "source",
+ "symmetric": false
+ },
+ {
+ "id": "A",
+ "carbons": 2,
+ "boundary": "internal",
+ "symmetric": false
+ },
+ {
+ "id": "B",
+ "carbons": 2,
+ "boundary": "internal",
+ "symmetric": false
+ },
+ {
+ "id": "Out",
+ "carbons": 2,
+ "boundary": "sink",
+ "symmetric": false
+ }
+ ],
+ "reactions": [
+ {
+ "id": "uptake",
+ "substrates": [
+ [
+ "S",
+ "AB"
+ ]
+ ],
+ "products": [
+ [
+ "A",
+ "AB"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 200,
+ "fixed": 100
+ },
+ {
+ "id": "straight",
+ "substrates": [
+ [
+ "A",
+ "AB"
+ ]
+ ],
+ "products": [
+ [
+ "B",
+ "AB"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "swap",
+ "substrates": [
+ [
+ "A",
+ "AB"
+ ]
+ ],
+ "products": [
+ [
+ "B",
+ "BA"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "export",
+ "substrates": [
+ [
+ "B",
+ "AB"
+ ]
+ ],
+ "products": [
+ [
+ "Out",
+ "AB"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ }
+ ],
+ "fragments": [
+ {
+ "id": "Bfirst",
+ "metabolite": "B",
+ "carbons": [
+ 1
+ ],
+ "provenance": "Synthetic position-specific carbon-1 measurement; not an experimentally established fragment assignment."
+ },
+ {
+ "id": "Bwhole",
+ "metabolite": "B",
+ "carbons": [
+ 1,
+ 2
+ ],
+ "provenance": "Synthetic complete two-carbon pool measurement."
+ }
+ ]
+}
diff --git a/skills/13c-metabolic-flux/assets/branch-unresolved.json b/skills/13c-metabolic-flux/assets/branch-unresolved.json
new file mode 100644
index 00000000..75d2893e
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/branch-unresolved.json
@@ -0,0 +1,49 @@
+{
+ "schema_version": 1,
+ "steady_state": {
+ "metabolic": true,
+ "isotopic": true
+ },
+ "shared_fluxes": true,
+ "mdv_basis": "tracer_only",
+ "correction_notes": "Synthetic tracer-only probabilities; no natural-abundance correction applied. Isotopomer mixtures explicitly include unlabeled material.",
+ "experiments": [
+ {
+ "id": "C1label",
+ "substrates": {
+ "S": {
+ "10": 0.8,
+ "00": 0.2
+ }
+ },
+ "measurements": [
+ {
+ "fragment": "Bwhole",
+ "mdv": [
+ 0.2,
+ 0.8,
+ 0
+ ],
+ "covariance": [
+ [
+ 0.0002,
+ -0.0001,
+ -0.0001
+ ],
+ [
+ -0.0001,
+ 0.0002,
+ -0.0001
+ ],
+ [
+ -0.0001,
+ -0.0001,
+ 0.0002
+ ]
+ ],
+ "omit": 2
+ }
+ ]
+ }
+ ]
+}
diff --git a/skills/13c-metabolic-flux/assets/mfapy-license.txt b/skills/13c-metabolic-flux/assets/mfapy-license.txt
new file mode 100644
index 00000000..87a23a77
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/mfapy-license.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2018 Fumio Matsuda
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
\ No newline at end of file
diff --git a/skills/13c-metabolic-flux/assets/requirements.txt b/skills/13c-metabolic-flux/assets/requirements.txt
new file mode 100644
index 00000000..0d5f33c9
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/requirements.txt
@@ -0,0 +1,4 @@
+mfapy @ git+https://github.com/fumiomatsuda/mfapy.git@a10433af16682386548b360297e2476152d46ede
+numpy==2.4.6
+scipy==1.17.1
+nlopt==2.11.0
diff --git a/skills/13c-metabolic-flux/assets/tca-fluxes.json b/skills/13c-metabolic-flux/assets/tca-fluxes.json
new file mode 100644
index 00000000..145e8390
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/tca-fluxes.json
@@ -0,0 +1,11 @@
+{
+ "v1": 100,
+ "v2": 100,
+ "v3": 50,
+ "v4": 50,
+ "v5": 50,
+ "v6": 125,
+ "v7": 75,
+ "v8": 50,
+ "v9": 50
+}
diff --git a/skills/13c-metabolic-flux/assets/tca-model.json b/skills/13c-metabolic-flux/assets/tca-model.json
new file mode 100644
index 00000000..27672327
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/tca-model.json
@@ -0,0 +1,250 @@
+{
+ "schema_version": 1,
+ "name": "Published EMU TCA demonstration",
+ "flux_unit": "relative units; citrate synthase v1 fixed to 100",
+ "provenance": "Carbon network adapted from mfapy Example_0/1_toymodel_model.txt at a10433af16682386548b360297e2476152d46ede (MIT; see mfapy-license.txt). Numerical reference in Antoniewicz et al. 2007, Metabolic Engineering 9:68-86, DOI 10.1016/j.ymben.2006.09.001. Demonstration network, not a complete organism model.",
+ "metabolites": [
+ {
+ "id": "CO2ex",
+ "carbons": 1,
+ "boundary": "sink",
+ "symmetric": false
+ },
+ {
+ "id": "AcCoA",
+ "carbons": 2,
+ "boundary": "source",
+ "symmetric": false
+ },
+ {
+ "id": "OAC",
+ "carbons": 4,
+ "boundary": "internal",
+ "symmetric": false
+ },
+ {
+ "id": "Cit",
+ "carbons": 6,
+ "boundary": "internal",
+ "symmetric": false
+ },
+ {
+ "id": "AKG",
+ "carbons": 5,
+ "boundary": "internal",
+ "symmetric": false
+ },
+ {
+ "id": "Suc",
+ "carbons": 4,
+ "boundary": "internal",
+ "symmetric": true
+ },
+ {
+ "id": "Fum",
+ "carbons": 4,
+ "boundary": "internal",
+ "symmetric": true
+ },
+ {
+ "id": "Glu",
+ "carbons": 5,
+ "boundary": "internal",
+ "symmetric": false
+ },
+ {
+ "id": "Gluex",
+ "carbons": 5,
+ "boundary": "sink",
+ "symmetric": false
+ },
+ {
+ "id": "Asp",
+ "carbons": 4,
+ "boundary": "source",
+ "symmetric": false
+ }
+ ],
+ "reactions": [
+ {
+ "id": "v1",
+ "substrates": [
+ [
+ "AcCoA",
+ "AB"
+ ],
+ [
+ "OAC",
+ "CDEF"
+ ]
+ ],
+ "products": [
+ [
+ "Cit",
+ "FEDBAC"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300,
+ "fixed": 100
+ },
+ {
+ "id": "v2",
+ "substrates": [
+ [
+ "Cit",
+ "ABCDEF"
+ ]
+ ],
+ "products": [
+ [
+ "AKG",
+ "ABCDE"
+ ],
+ [
+ "CO2ex",
+ "F"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "v3",
+ "substrates": [
+ [
+ "AKG",
+ "ABCDE"
+ ]
+ ],
+ "products": [
+ [
+ "Glu",
+ "ABCDE"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "v4",
+ "substrates": [
+ [
+ "AKG",
+ "ABCDE"
+ ]
+ ],
+ "products": [
+ [
+ "Suc",
+ "BCDE"
+ ],
+ [
+ "CO2ex",
+ "A"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "v5",
+ "substrates": [
+ [
+ "Suc",
+ "ABCD"
+ ]
+ ],
+ "products": [
+ [
+ "Fum",
+ "ABCD"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "v6",
+ "substrates": [
+ [
+ "Fum",
+ "ABCD"
+ ]
+ ],
+ "products": [
+ [
+ "OAC",
+ "ABCD"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "v7",
+ "substrates": [
+ [
+ "OAC",
+ "ABCD"
+ ]
+ ],
+ "products": [
+ [
+ "Fum",
+ "ABCD"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "v8",
+ "substrates": [
+ [
+ "Asp",
+ "ABCD"
+ ]
+ ],
+ "products": [
+ [
+ "OAC",
+ "ABCD"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ },
+ {
+ "id": "v9",
+ "substrates": [
+ [
+ "Glu",
+ "ABCDE"
+ ]
+ ],
+ "products": [
+ [
+ "Gluex",
+ "ABCDE"
+ ]
+ ],
+ "lower": 0.001,
+ "upper": 300
+ }
+ ],
+ "fragments": [
+ {
+ "id": "GluWhole",
+ "metabolite": "Glu",
+ "carbons": [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5
+ ],
+ "provenance": "All five glutamate carbons, matching the published EMU demonstration; not a derivatized GC-MS formula."
+ }
+ ]
+}
diff --git a/skills/13c-metabolic-flux/assets/tca-reference-mdv.json b/skills/13c-metabolic-flux/assets/tca-reference-mdv.json
new file mode 100644
index 00000000..574d1778
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/tca-reference-mdv.json
@@ -0,0 +1,89 @@
+{
+ "schema_version": 1,
+ "steady_state": {
+ "metabolic": true,
+ "isotopic": true
+ },
+ "shared_fluxes": true,
+ "mdv_basis": "tracer_only",
+ "correction_notes": "Synthetic tracer-only probabilities; no natural-abundance correction applied. Isotopomer mixtures explicitly include unlabeled material.",
+ "experiments": [
+ {
+ "id": "published",
+ "substrates": {
+ "AcCoA": {
+ "11": 0.25,
+ "00": 0.5,
+ "01": 0.25
+ },
+ "Asp": {
+ "0000": 1
+ }
+ },
+ "measurements": [
+ {
+ "fragment": "GluWhole",
+ "mdv": [
+ 0.3463541666666666,
+ 0.26953124999999994,
+ 0.27083333333333326,
+ 0.08072916666666666,
+ 0.028645833333333332,
+ 0.00390625
+ ],
+ "omit": 5,
+ "covariance": [
+ [
+ 8.333333333333334e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06
+ ],
+ [
+ -1.6666666666666667e-06,
+ 8.333333333333334e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06
+ ],
+ [
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ 8.333333333333334e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06
+ ],
+ [
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ 8.333333333333334e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06
+ ],
+ [
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ 8.333333333333334e-06,
+ -1.6666666666666667e-06
+ ],
+ [
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ -1.6666666666666667e-06,
+ 8.333333333333334e-06
+ ]
+ ]
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/skills/13c-metabolic-flux/assets/tca-tracer.json b/skills/13c-metabolic-flux/assets/tca-tracer.json
new file mode 100644
index 00000000..334e6336
--- /dev/null
+++ b/skills/13c-metabolic-flux/assets/tca-tracer.json
@@ -0,0 +1,26 @@
+{
+ "schema_version": 1,
+ "steady_state": {
+ "metabolic": true,
+ "isotopic": true
+ },
+ "shared_fluxes": true,
+ "mdv_basis": "tracer_only",
+ "correction_notes": "Synthetic tracer-only probabilities; no natural-abundance correction applied. Isotopomer mixtures explicitly include unlabeled material.",
+ "experiments": [
+ {
+ "id": "published",
+ "substrates": {
+ "AcCoA": {
+ "11": 0.25,
+ "00": 0.5,
+ "01": 0.25
+ },
+ "Asp": {
+ "0000": 1
+ }
+ },
+ "measurements": []
+ }
+ ]
+}
diff --git a/skills/13c-metabolic-flux/references/inference.md b/skills/13c-metabolic-flux/references/inference.md
new file mode 100644
index 00000000..6f245047
--- /dev/null
+++ b/skills/13c-metabolic-flux/references/inference.md
@@ -0,0 +1,123 @@
+# Inference and interpretation
+
+## What is fitted
+
+The adapter constructs internal carbon-pool balances S v = 0 and exact reference
+constraints. Linear programming checks feasibility in normalized flux units and
+explicitly verifies the returned vector. A null-space basis parameterizes
+the equalities, while linear inequalities preserve every directional flux bound.
+Bounds that force a reaction to a single value on a feasible face are promoted to
+equalities using a tolerance relative to each reaction's own feasible values. Thus a
+flux profile endpoint can correctly have fewer free dimensions. Optimizer constraints
+also use normalized units; an unrelated loose bound does not define this tolerance.
+
+mfapy evaluates the steady-state isotope model using elementary metabolite units.
+The pinned mfapy generator drops EMU rows with absolute turnover <= 0.001. The
+adapter uniformly rescales positive directional fluxes so the smallest is 1 for
+forward simulation only. Steady-state isotope distributions are invariant under
+this rescaling; reported fluxes and measured-rate residuals retain their original
+units. This avoids unit-dependent disappearance of slowly turning-over pools.
+Exact zero-throughput pools can still be undefined and are not repaired by rescaling.
+The fitting code does not use mfapy's built-in optimizer, confidence intervals, or
+natural-abundance correction. It uses SciPy SLSQP with multiple feasible starts,
+constructed from convex combinations of linear-programming vertices. This is a local
+optimization strategy; no global optimum is guaranteed. Seeds control starting-point
+generation, not bit-identical behavior across numerical libraries or machines.
+
+For each normalized distribution, omit one bin and minimize
+
+ RSS = sum_b (prediction_b - mean_b)^T covariance_b^-1 (prediction_b - mean_b)
+ + sum_k ((predicted_flux_k - measured_flux_k) / SEM_k)^2
+
+The implementation uses a Cholesky solve rather than explicitly inverting covariance.
+With a consistent full compositional covariance, changing the omitted bin leaves this
+quadratic form invariant. A diagonal SEM approximation does not have that property.
+Covariance validation checks row/column sums relative to each row/column's magnitude
+and positive semidefiniteness after variance scaling, so large-variance bins cannot
+hide invalid rare-bin uncertainty. MDV normalization error must be negligible relative
+to the declared measurement error as well as small in absolute terms.
+
+## Read the JSON results
+
+- `fluxes`: one best converged feasible point, including arbitrary coordinates along
+ unresolved directions. Preserve the declared `flux_unit` and exact reference.
+- `rss`, `predictions`: weighted residual sum and observed/predicted distributions.
+ A low residual can reflect an uninformative experiment or an overflexible model.
+- `optimizer_starts`: success, residual, iterations, and termination message for every
+ start. Failed numerical evaluations are penalized during optimization; a result is
+ accepted only if its final simulation is finite, constraints hold, and the optimizer
+ reports convergence. No converged solution makes the command fail with exit code 2.
+- `free_flux_dimensions`: affine feasible flux dimension, not parameter count guessed
+ from a reaction list. `independent_measurements` counts retained bins and rates.
+- `local_sensitivity_rank`: numerical rank of the whitened residual Jacobian in
+ normalized feasible coordinates. Finite differences use step 1e-5 and a singular-
+ value cutoff max(1e-4, largest singular value * 1e-6). This is a local diagnostic,
+ not a proof of structural identifiability. Poor scaling, bounds, near-zero pools,
+ and strongly nonlinear behavior can affect it. A null value means feasible
+ perturbations could not be evaluated.
+- `weak_flux_directions`: relative reaction changes along locally insensitive
+ directions, normalized to maximum absolute component 1. These are local directions,
+ not permissible finite flux changes without another feasibility check.
+- `active_bounds`: estimated reactions at imposed bounds, excluding declared fixed
+ reactions. Inspect why the bound is active before making a biological claim.
+- `goodness_of_fit`: approximate chi-square tail probability only when local rank is
+ full, residual degrees of freedom are positive, and no nonfixed bound is active.
+ Known Gaussian covariance, an adequate observation model, interior parameters,
+ and asymptotic regularity are assumptions. Estimated SEMs, low counts, inequality
+ boundaries, or nonlinearity can invalidate this approximation. A high p-value is not
+ evidence that a biological mechanism is true.
+
+## Flux profiles
+
+Every requested reaction is fixed at each grid value across its feasible range;
+all nuisance fluxes are refitted. The grid includes the best fitted reaction value.
+Acceptance uses RSS(profile) - RSS(best) <= chi-square(confidence, 1). This is an
+asymptotic likelihood-ratio approximation for the declared Gaussian observation
+model, not a universal MFA confidence formula. Profiles of parameter combinations
+or exact finite-sample coverage require a different analysis.
+
+| Status | Meaning and next action |
+| --- | --- |
+| `threshold_crossings_bracketed` | Grid points bracket threshold crossings. Report the brackets; increase resolution and repeat starts if precise limits matter. Inspect all crossings because disconnected accepted regions are possible. |
+| `bound_limited` | At least one feasible-range edge remains accepted. Report that edge as constraint-limited, not measurement-determined. |
+| `unresolved_within_bounds` | All sampled points across the feasible range remain accepted. Do not report the arbitrary optimum as an identified pathway rate. This finite grid is not a global structural proof. |
+| `incomplete_profile` | At least one point failed. Missing points are unknown. Improve starts, numerical conditioning, or model specification before interpreting limits. |
+| `baseline_not_optimal_refit_required` | A profile found a materially smaller RSS. Refit the baseline before using any confidence claim. |
+| `fixed_by_constraints` | The reaction is fixed by exact constraints; it has no data-estimated profile interval. |
+
+Even a flat reaction can acquire an apparent bound through coupling to a different
+bounded reaction. In the TCA demonstration, increasing `v7` also increases `v6`, and
+`v6` has an imposed upper bound. This can create an upper profile edge even though
+the isotope measurements do not determine exchange. Record such bound sensitivity.
+
+## Troubleshooting by evidence
+
+**Excellent fit, weak rank or broad profiles:** examine tracer position and measured
+carbon subsets, symmetric pools, reversible exchange, absolute flux scale, compartments,
+and dilution. Simulate candidate measurements at distinct feasible fluxes along the
+weak direction. Do not add more measurements of an invariant whole-molecule MDV.
+
+**Large structured residuals:** examine atom maps, input-label purity, missing carbon
+sources, fragment assignments, isotope correction, compartment mixing, and steady-state
+assumptions before increasing error bars or adding free reactions.
+
+**Negative corrected fractions or singular covariance:** revisit the upstream peak
+and correction model. Clipping and renormalization change both the mean and its error
+structure. The CLI intentionally rejects such inputs rather than silently changing them.
+
+**Different answers across starts:** compare RSS, feasibility and profiles. Increase
+starts and repeat seeds. Report competing optima when both explain the data.
+
+**Singular forward model:** look for zero-throughput/unfed pools or mappings outside
+the supported representation. An isotopic steady-state distribution may be undefined.
+Do not impose positive flux solely to conceal an inactive pool.
+
+## Evidence and applicability
+
+The bundled cyclic-network calculation reproduces a published EMU numerical reference.
+The branch experiment has an independently calculable optimum and likelihood profile.
+The TCA measurement asset uses those simulated reference probabilities and a declared
+synthetic covariance; it is not an experimental dataset. Tests also verify isotope
+limits, repeated-substrate condensation, reversed-label conventions, compositional
+likelihood invariance, and non-identifiability. Larger organism models, unusual symmetry,
+or new measurement types require independent validation before scientific use.
diff --git a/skills/13c-metabolic-flux/references/input-contract.md b/skills/13c-metabolic-flux/references/input-contract.md
new file mode 100644
index 00000000..d5308470
--- /dev/null
+++ b/skills/13c-metabolic-flux/references/input-contract.md
@@ -0,0 +1,170 @@
+# Input contract, schema version 1
+
+Use the bundled JSON assets as runnable templates. The CLI rejects unknown fields,
+duplicate JSON keys, nonfinite numbers, negative fractions, and incomplete mixtures.
+All files are local. No Python expressions, model scripts, pickles, or remote URLs
+are evaluated from input data.
+
+## Model
+
+Required top-level fields: `schema_version` (integer 1), `name`, `flux_unit`,
+`provenance`, `metabolites`, `reactions`, `fragments`.
+The three text fields must be nonempty. IDs start with an ASCII letter and contain
+only ASCII letters/digits, at most 40 characters. This avoids upstream renaming and
+protects the mfapy code generator. Use distinct IDs for compartments, such as `CitM`
+and `CitC`; explain their meaning in provenance.
+
+### Metabolites
+
+Each has `id`, integer `carbons` (1–12), `boundary` (`source`, `internal`, `sink`),
+and optional boolean `symmetric` (default false).
+
+- Sources are external carbon inputs with explicitly prescribed labeling. They may
+ only appear on the substrate side. They are not steady-state-balanced pools.
+- Sinks are external products, may only appear on the product side, and are not balanced.
+- Internal pools must have a net-producing and a net-consuming reaction. Their
+ steady-state stoichiometric balances are imposed for every fit and simulation.
+- Symmetry is only the average of the given ordering and its complete reversal.
+ It is allowed only for internal pools. Carbon numbering must make that reversal
+ the correct physical permutation.
+
+Limits are 100 metabolites, 200 reactions, 100 fragments. They bound the supported
+input surface, not runtime: EMU construction can still be expensive for a complex
+network. Begin with the smallest scientifically adequate model.
+
+### Reactions
+
+Each has `id`, `substrates`, `products`, `lower`, `upper`, and optional `fixed`.
+Bounds are finite with `0 <= lower < upper`; `fixed` must lie inside them. All
+reaction fluxes are nonnegative one-way event rates in `flux_unit`. A reversible
+reaction is two reactions with inverse atom maps; their difference is the net flux.
+
+Each reaction side is a list of `[metabolite_id, atom_labels]` pairs. For example:
+
+```json
+{
+ "id": "condense",
+ "substrates": [["AcCoA", "AB"], ["OAC", "CDEF"]],
+ "products": [["Cit", "FEDBAC"]],
+ "lower": 0.001,
+ "upper": 300,
+ "fixed": 100
+}
+```
+
+Letters identify individual carbon atoms **within one reaction**, not globally.
+Their order is the declared carbon numbering of each metabolite. Every letter on
+the substrate side must occur exactly once on the product side. Include carbon
+lost to CO2 as an explicit product; include fixed carbon as an explicit substrate.
+
+Repeated molecules are separate occurrences: `[["Pyr","ABC"],["Pyr","DEF"]]`
+means two pyruvates per reaction event, and the adapter builds coefficient 2 in
+the mass balance. Fractional stoichiometry and untracked carbon-bearing cofactors
+are not supported. Noncarbon balancing chemistry is outside this representation;
+carbon conservation does not prove full elemental/charge conservation.
+
+Positive lower bounds in demonstrations keep internal pools turning over. Do not
+copy these bounds to real biology merely to obtain convergence. A truly inactive
+pool may have no unique steady-state isotope distribution; remove it only when
+scientifically justified, or model its transient behavior.
+
+### Fragments
+
+Each has `id`, `metabolite`, `carbons`, and nonempty `provenance`.
+`carbons` is a unique list of **1-based positions** in an internal metabolite.
+The prediction is the distribution of the number of labeled carbons in this subset,
+ordered M+0 through M+N. Position order within the subset does not affect mass counts.
+
+This is not a GC-MS chemical-formula parser. Derivatization atoms, natural heavy
+isotopes of other elements, adducts, and MS/MS precursor/product selection must be
+handled in a validated upstream measurement model. An arbitrary fragment name does
+not establish its carbon assignment.
+
+## Experiment and measurement file
+
+Required fields:
+
+```json
+{
+ "schema_version": 1,
+ "steady_state": {"metabolic": true, "isotopic": true},
+ "shared_fluxes": true,
+ "mdv_basis": "tracer_only",
+ "correction_notes": "Describe actual correction and tracer-purity handling here.",
+ "experiments": []
+}
+```
+
+The empty list above documents the envelope; at least one experiment is required.
+Each experiment has a unique `id`, `substrates`, `measurements`, and optional
+`flux_measurements`. An empty measurement list is useful for simulation only.
+
+`substrates` maps **every** source ID to a dictionary of positional isotopomer
+fractions. `{"100000": 0.98, "000000": 0.02}` describes a six-carbon feed with
+98% carbon-1 labeling and 2% unlabeled molecules. All fractions must be nonnegative
+and sum to one within 1e-10. Strings run carbon 1 to carbon N left to right.
+Do not derive a positional distribution from whole-molecule mass counts alone.
+
+`mdv_basis: "tracer_only"` asserts that nontracer natural abundance has already been
+handled consistently. The simulator neither adds nor removes natural abundance.
+If preprocessing also corrected tracer purity to an ideal tracer, do not encode
+that impurity a second time. Record the basis and method explicitly; obtain the
+upstream correction matrix or corrected covariance when needed.
+
+### Mass-distribution measurements
+
+Every measurement has `fragment`, full `mdv`, integer `omit`, and exactly one of
+`covariance` or `sem`:
+
+```json
+{
+ "fragment": "Bfirst",
+ "mdv": [0.44, 0.56],
+ "omit": 1,
+ "covariance": [[0.0001, -0.0001], [-0.0001, 0.0001]]
+}
+```
+
+For an N-carbon fragment, supply all N+1 fractions, nonnegative, summing to one
+within the smaller of 1e-10 and 1e-5 times the smallest retained-bin standard error.
+Supply sufficient precision from upstream normalization; the CLI does not silently
+renormalize rounded measurements. `omit` is the **0-based mass-bin index**, not a carbon position.
+Omit one bin because normalized fractions are linearly dependent. Missing measured
+bins are not zeros: this schema requires a complete, justified distribution.
+
+`covariance` is the (N+1)-square covariance of the **reported mean MDV**, in squared
+fraction units. It must be symmetric with zero row/column sums and positive definite
+after the omitted bin is removed. This preserves the sum constraint and supports
+correlated errors. For independent replicate vectors, an estimate for the covariance
+of their mean is sample covariance divided by replicate count. A rank-deficient
+estimate needs a scientifically justified error model or more replicates; the CLI
+does not silently add regularization.
+
+Alternatively `sem` is an N+1-vector of strictly positive standard errors of the
+reported fractions. The retained bins are treated as independent. This is an explicit
+approximation; fit/profile results can depend on which bin is omitted. Distinguish SD
+from SEM, analytical replicates from biological variability, and count noise from
+uncertainty introduced by correction. Zero uncertainty is not an exact observation.
+
+Different measurement blocks are treated as independent. Do not duplicate fragments
+within an experiment or include overlapping fragments as independent measurements
+without assessing their cross-fragment error correlation. A full cross-block covariance
+is not supported. Analyze correlated blocks with an appropriate external likelihood.
+
+### Extracellular flux measurements
+
+```json
+{"reaction": "uptake", "value": 100.0, "sem": 0.2}
+```
+
+Add these to `flux_measurements` using the same flux units as the network. They are
+Gaussian observations, not exact constraints, and can anchor absolute scale. An
+exact reference belongs in a reaction's `fixed` field. Do not copy the same measured
+rate into every parallel tracer block: it would be counted repeatedly. Measurements
+from independent cultures can be combined only if the common-flux assumption is valid.
+
+## Forward-simulation flux file
+
+A JSON object mapping every reaction ID to a finite numerical flux. No omitted
+reactions or additional fields. The vector must satisfy internal balances, fixed
+constraints, and bounds. Use the bundled flux files as examples.
diff --git a/skills/13c-metabolic-flux/scripts/_mfa_fit.py b/skills/13c-metabolic-flux/scripts/_mfa_fit.py
new file mode 100644
index 00000000..4430fb54
--- /dev/null
+++ b/skills/13c-metabolic-flux/scripts/_mfa_fit.py
@@ -0,0 +1,254 @@
+"""Constrained multistart fitting and nuisance-reoptimized flux profiles."""
+from __future__ import annotations
+
+import numpy as np
+from scipy.linalg import null_space
+from scipy.optimize import Bounds, LinearConstraint, linprog, minimize
+from scipy.stats import chi2
+
+from _mfa_model import InputError, require
+
+
+def fixed_range(low, high):
+ """Compare a feasible range to its own magnitude, independent of flux units."""
+ return high - low <= 1e-10 * max(abs(low), abs(high), np.finfo(float).tiny)
+
+
+class FluxSpace:
+ def __init__(self, network, fixed=None):
+ self.network = network
+ self.a = network.equalities.copy()
+ self.b = network.rhs.copy()
+ if fixed:
+ for rid, value in fixed.items():
+ row = np.eye(len(network.ids))[network.ids.index(rid)]
+ self.a = np.vstack((self.a, row))
+ self.b = np.append(self.b, value)
+ anchors = np.abs(self.b[self.b != 0])
+ self.scale = float(np.median(anchors)) if len(anchors) else float(np.median(network.upper))
+ self.bounds = list(zip(network.lower / self.scale, network.upper / self.scale))
+ feasible = self.linear(np.zeros(len(network.ids)))
+ require(feasible.success, "Flux constraints are infeasible")
+ # A profile endpoint can collapse a face of the feasible polytope.
+ # Promote bounds that fix a reaction throughout this face to equalities.
+ initial_basis = null_space(self.a)
+ for i in range(len(network.ids)):
+ if np.linalg.norm(initial_basis[i]) < 1e-10:
+ continue
+ axis = np.eye(len(network.ids))[i]
+ low, high = self.linear(axis), self.linear(-axis)
+ require(low.success and high.success, "Cannot determine feasible flux ranges")
+ if fixed_range(low.x[i], high.x[i]):
+ self.a = np.vstack((self.a, axis))
+ self.b = np.append(self.b, (high.x[i] + low.x[i]) / 2)
+ feasible = self.linear(np.zeros(len(network.ids)))
+ require(feasible.success, "Flux constraints are infeasible after reducing fixed ranges")
+ self.base = feasible.x
+ self.basis = null_space(self.a) * self.scale
+ self.dimension = self.basis.shape[1]
+
+ def linear(self, objective):
+ result = linprog(objective, A_eq=self.a, b_eq=self.b / self.scale, bounds=self.bounds,
+ method="highs", options={"time_limit": 10., "primal_feasibility_tolerance": 1e-9,
+ "dual_feasibility_tolerance": 1e-9})
+ if result.success:
+ result.x = result.x * self.scale
+ if not self.feasible(result.x):
+ result.success = False
+ result.message = "LP returned a vector that fails explicit feasibility checks"
+ return result
+
+ def coordinates(self, flux):
+ return self.basis.T @ (flux - self.base) / self.scale ** 2
+
+ def flux(self, coordinates):
+ return self.base + self.basis @ coordinates
+
+ def feasible(self, flux):
+ scale = max(float(np.max(np.abs(flux))), float(np.max(np.abs(self.b))), 1e-300)
+ return self.network.feasible(flux) and np.max(np.abs(self.a @ flux - self.b)) < 1e-8 * scale
+
+ def starting_points(self, count, rng, warm=None):
+ if not self.dimension:
+ return [self.base]
+ vertices = [self.base]
+ for _ in range(max(12, 3 * self.dimension)):
+ result = self.linear(rng.normal(size=len(self.base)))
+ if result.success:
+ vertices.append(result.x)
+ vertices = np.array(vertices)
+ center = vertices.mean(axis=0)
+ starts = [center]
+ if warm is not None:
+ projected = self.flux(self.coordinates(warm))
+ if self.feasible(projected):
+ starts[0] = projected
+ for _ in range(count - 1):
+ weights = rng.dirichlet(np.ones(len(vertices)) * .3)
+ starts.append(.05 * center + .95 * weights @ vertices)
+ return starts
+
+
+def fit(observations, starts=8, seed=2026, maxiter=1000, fixed=None, warm=None):
+ require(type(starts) is int and 1 <= starts <= 100, "starts must be 1..100")
+ require(type(maxiter) is int and 1 <= maxiter <= 10000, "maxiter must be 1..10000")
+ require(observations.size > 0, "Fitting needs measurements")
+ network = observations.network
+ space = FluxSpace(network, fixed)
+ rng = np.random.default_rng(seed)
+ records, solutions = [], []
+ numerical_errors = (InputError, np.linalg.LinAlgError, FloatingPointError, ZeroDivisionError)
+
+ def rss(flux):
+ residual = observations.residuals(flux)
+ value = float(residual @ residual)
+ require(np.isfinite(value), "Nonfinite objective")
+ return value
+
+ if not space.dimension:
+ value = rss(space.base)
+ return dict(vector=space.base, rss=value, space=space,
+ starts=[dict(success=True, rss=value, message="All fluxes fixed by constraints")])
+ varying = np.linalg.norm(space.basis / space.scale, axis=1) > 1e-10
+ linear = LinearConstraint(space.basis[varying] / space.scale,
+ (network.lower - space.base)[varying] / space.scale,
+ (network.upper - space.base)[varying] / space.scale)
+ # Loose finite coordinate bounds limit excursions while the linear constraint
+ # enforces all actual reaction bounds. They cannot exclude a feasible vector.
+ radius = np.linalg.norm(network.upper - network.lower) / space.scale + 1
+ for initial in space.starting_points(starts, rng, warm):
+ try:
+ scale = max(1., rss(initial))
+
+ def objective(z):
+ try:
+ return rss(space.flux(z)) / scale
+ except numerical_errors:
+ return 1e20
+
+ result = minimize(objective, space.coordinates(initial), method="SLSQP",
+ bounds=Bounds(-radius, radius), constraints=[linear],
+ options={"maxiter": maxiter, "ftol": 1e-12})
+ vector = space.flux(result.x)
+ value = rss(vector)
+ success = bool(result.success and space.feasible(vector) and np.isfinite(value))
+ records.append(dict(success=success, rss=value, message=str(result.message),
+ iterations=int(result.nit)))
+ if success:
+ solutions.append((value, vector))
+ except numerical_errors as exc:
+ records.append(dict(success=False, rss=None, message=str(exc)))
+ require(bool(solutions), "No converged feasible fit; check flux bounds, zero-throughput pools, and starting conditions")
+ value, vector = min(solutions, key=lambda item: item[0])
+ return dict(vector=vector, rss=value, space=space, starts=records)
+
+
+def diagnostics(observations, fitted):
+ network, vector, space = observations.network, fitted["vector"], fitted["space"]
+ residual, predictions = observations.residuals(vector, details=True)
+ columns = []
+ z = space.coordinates(vector)
+ for i in range(space.dimension):
+ step = np.eye(space.dimension)[i] * 1e-5
+ plus, minus = space.flux(z + step), space.flux(z - step)
+ if space.feasible(plus) and space.feasible(minus):
+ columns.append((observations.residuals(plus) - observations.residuals(minus)) / 2e-5)
+ elif space.feasible(plus):
+ columns.append((observations.residuals(plus) - residual) / 1e-5)
+ elif space.feasible(minus):
+ columns.append((residual - observations.residuals(minus)) / 1e-5)
+ else:
+ columns = None
+ break
+ rank, singular, null_directions = None, [], []
+ if columns is not None:
+ jacobian = np.column_stack(columns) if columns else np.empty((observations.size, 0))
+ _, values, vh = np.linalg.svd(jacobian, full_matrices=True)
+ threshold = max(1e-4, (float(values[0]) if len(values) else 0.) * 1e-6)
+ rank = int(np.sum(values > threshold))
+ singular = values.tolist()
+ for direction in vh[rank:]:
+ flux_direction = space.basis @ direction
+ flux_direction /= np.max(np.abs(flux_direction))
+ null_directions.append({rid: float(v) for rid, v in zip(network.ids, flux_direction)
+ if abs(v) > 1e-5})
+ active = [rid for i, rid in enumerate(network.ids) if rid not in network.fixed and
+ (abs(vector[i] - network.lower[i]) < 1e-6 * space.scale or
+ abs(vector[i] - network.upper[i]) < 1e-6 * space.scale)]
+ dof = observations.size - space.dimension
+ regular = rank == space.dimension and dof > 0 and not active
+ warnings = list(observations.warnings)
+ if rank is None:
+ warnings.append("Sensitivity rank could not be evaluated along feasible directions; inspect profiles")
+ elif rank < space.dimension:
+ warnings.append("Locally rank-deficient fit: some flux combinations are not constrained by these measurements")
+ if active:
+ warnings.append("Active flux bounds invalidate ordinary interior asymptotic confidence claims")
+ if any(not record["success"] for record in fitted["starts"]):
+ warnings.append("Some optimizer starts failed; inspect start records and repeat with more starts")
+ return dict(
+ fluxes={rid: float(v) for rid, v in zip(network.ids, vector)}, flux_unit=network.spec["flux_unit"],
+ rss=fitted["rss"], independent_measurements=observations.size,
+ free_flux_dimensions=space.dimension, local_sensitivity_rank=rank,
+ sensitivity_singular_values=singular, weak_flux_directions=null_directions,
+ active_bounds=active, max_mass_balance_error=float(np.max(np.abs(network.balance @ vector))),
+ goodness_of_fit=dict(degrees_of_freedom=dof,
+ approximate_p_value=float(chi2.sf(fitted["rss"], dof)) if regular else None,
+ interpretation="Asymptotic Gaussian diagnostic; not evidence that the biological model is correct"
+ if regular else "Not reported: rank, bounds, or degrees of freedom violate regular assumptions"),
+ predictions=predictions, optimizer_starts=fitted["starts"], warnings=warnings)
+
+
+def profile(observations, fitted, reaction, points=21, starts=4, seed=2026,
+ maxiter=1000, confidence=.95):
+ network, space = observations.network, fitted["space"]
+ require(reaction in network.ids, f"Unknown profile reaction {reaction}")
+ require(type(points) is int and 5 <= points <= 201, "profile points must be 5..201")
+ require(0 < confidence < 1, "confidence must be between zero and one")
+ index = network.ids.index(reaction)
+ objective = np.eye(len(network.ids))[index]
+ lower = space.linear(objective)
+ upper = space.linear(-objective)
+ require(lower.success and upper.success, "Cannot compute feasible profile range")
+ lo, hi = float(lower.x[index]), float(upper.x[index])
+ if fixed_range(lo, hi):
+ return dict(reaction=reaction, status="fixed_by_constraints", feasible_range=[lo, hi], points=[])
+ grid = np.unique(np.append(np.linspace(lo, hi, points), fitted["vector"][index]))
+ records = []
+ cutoff = float(chi2.ppf(confidence, 1))
+ for i, value in enumerate(grid):
+ try:
+ result = fit(observations, starts=starts, seed=seed + i, maxiter=maxiter,
+ fixed={reaction: float(value)}, warm=fitted["vector"])
+ delta = result["rss"] - fitted["rss"]
+ records.append(dict(flux=float(value), rss=result["rss"], delta_rss=float(delta),
+ accepted=bool(delta <= cutoff), converged=True,
+ failed_starts=sum(not start["success"] for start in result["starts"])))
+ except (InputError, np.linalg.LinAlgError, FloatingPointError) as exc:
+ records.append(dict(flux=float(value), rss=None, delta_rss=None,
+ accepted=None, converged=False, error=str(exc)))
+ valid = [r for r in records if r["converged"]]
+ better = any(r["delta_rss"] < -max(1e-5, abs(fitted["rss"]) * 1e-5) for r in valid)
+ failed = any(not r["converged"] for r in records)
+ all_accepted = len(valid) == len(records) and all(r["accepted"] for r in valid)
+ crossings = []
+ for left, right in zip(records, records[1:]):
+ if left["converged"] and right["converged"] and left["accepted"] != right["accepted"]:
+ crossings.append([left["flux"], right["flux"]])
+ if better:
+ status = "baseline_not_optimal_refit_required"
+ elif failed:
+ status = "incomplete_profile"
+ elif all_accepted:
+ status = "unresolved_within_bounds"
+ elif records[0]["accepted"] or records[-1]["accepted"]:
+ status = "bound_limited"
+ else:
+ status = "threshold_crossings_bracketed"
+ return dict(reaction=reaction, status=status, feasible_range=[lo, hi],
+ confidence=confidence, delta_rss_cutoff=cutoff,
+ threshold_crossing_brackets=crossings,
+ lower_bound_accepted=records[0]["accepted"], upper_bound_accepted=records[-1]["accepted"],
+ note="Grid profile with nuisance fluxes reoptimized. Crossings are brackets, not exact confidence limits. "
+ "Chi-square threshold is asymptotic and requires a suitable error model and regularity; "
+ "a flat finite profile is not proof of global structural non-identifiability.", points=records)
diff --git a/skills/13c-metabolic-flux/scripts/_mfa_model.py b/skills/13c-metabolic-flux/scripts/_mfa_model.py
new file mode 100644
index 00000000..87907d8f
--- /dev/null
+++ b/skills/13c-metabolic-flux/scripts/_mfa_model.py
@@ -0,0 +1,354 @@
+"""Validated carbon maps and a pinned mfapy steady-state forward model."""
+from __future__ import annotations
+
+from collections import Counter
+import contextlib
+import io
+import json
+import math
+from pathlib import Path
+import re
+
+import numpy as np
+from scipy.linalg import cholesky, solve_triangular
+
+
+class InputError(ValueError):
+ """A scientific input contract was not met."""
+
+
+def require(condition, message):
+ if not condition:
+ raise InputError(message)
+
+
+def fields(value, required, optional=()):
+ require(isinstance(value, dict), "Expected an object")
+ require(set(required) <= value.keys(), f"Missing fields: {set(required) - value.keys()}")
+ require(value.keys() <= set(required) | set(optional),
+ f"Unknown fields: {value.keys() - set(required) - set(optional)}")
+
+
+def number(value, label):
+ require(isinstance(value, (int, float)) and not isinstance(value, bool)
+ and math.isfinite(value), f"{label} must be a finite number")
+ return float(value)
+
+
+def identifier(value):
+ # mfapy generates numerical code internally; only these identifiers reach it.
+ require(isinstance(value, str) and re.fullmatch(r"[A-Za-z][A-Za-z0-9]{0,39}", value),
+ f"Invalid identifier {value!r}; use ASCII letters/digits, starting with a letter")
+ return value
+
+
+def unique(items, label):
+ require(len(set(items)) == len(items), f"Duplicate {label}")
+
+
+def read_json(path):
+ def pairs(items):
+ result = {}
+ for key, value in items:
+ require(key not in result, f"Duplicate JSON key: {key}")
+ result[key] = value
+ return result
+
+ def invalid_constant(value):
+ raise InputError(f"Non-finite JSON constant: {value}")
+
+ return json.loads(Path(path).read_text(encoding="utf-8"), object_pairs_hook=pairs,
+ parse_constant=invalid_constant)
+
+
+class Network:
+ def __init__(self, spec):
+ fields(spec, {"schema_version", "name", "flux_unit", "provenance", "metabolites",
+ "reactions", "fragments"})
+ require(type(spec["schema_version"]) is int and spec["schema_version"] == 1,
+ "Only schema_version 1 is supported")
+ for key in ("name", "flux_unit", "provenance"):
+ require(isinstance(spec[key], str) and bool(spec[key].strip()), f"Missing {key}")
+ for key, maximum in (("metabolites", 100), ("reactions", 200), ("fragments", 100)):
+ require(isinstance(spec[key], list) and 0 < len(spec[key]) <= maximum,
+ f"{key} must be a nonempty list with at most {maximum} entries")
+ self.spec = spec
+ self.metabolites = {}
+ for m in spec["metabolites"]:
+ fields(m, {"id", "carbons", "boundary"}, {"symmetric"})
+ name = identifier(m["id"])
+ require(name not in self.metabolites, f"Duplicate metabolite {name}")
+ require(type(m["carbons"]) is int and 1 <= m["carbons"] <= 12,
+ f"{name}: carbon count must be 1..12")
+ require(m["boundary"] in ("source", "internal", "sink"), f"{name}: invalid boundary")
+ require(type(m.get("symmetric", False)) is bool, f"{name}: symmetric must be boolean")
+ require(not m.get("symmetric") or m["boundary"] == "internal",
+ "Reversal symmetry is supported only for internal pools")
+ self.metabolites[name] = m
+ self.ids = []
+ self.lower, self.upper, self.fixed = [], [], {}
+ balance = {name: [] for name, m in self.metabolites.items() if m["boundary"] == "internal"}
+ self.reactions = {}
+ used = set()
+ for i, r in enumerate(spec["reactions"]):
+ fields(r, {"id", "substrates", "products", "lower", "upper"}, {"fixed"})
+ rid = identifier(r["id"])
+ require(rid not in self.ids, f"Duplicate reaction {rid}")
+ self.ids.append(rid)
+ lo, hi = number(r["lower"], rid), number(r["upper"], rid)
+ require(0 <= lo < hi, f"{rid}: require 0 <= lower < upper; use fixed for fixed fluxes")
+ self.lower.append(lo)
+ self.upper.append(hi)
+ if "fixed" in r:
+ fixed = number(r["fixed"], rid)
+ require(lo <= fixed <= hi, f"{rid}: fixed flux outside bounds")
+ self.fixed[rid] = fixed
+ names, labels = [], []
+ for side in ("substrates", "products"):
+ require(isinstance(r[side], list) and bool(r[side]), f"{rid}: empty {side}")
+ side_names, side_labels = [], []
+ for term in r[side]:
+ require(isinstance(term, list) and len(term) == 2, f"{rid}: expected [metabolite, atoms]")
+ metabolite, atoms = term
+ require(isinstance(metabolite, str) and metabolite in self.metabolites,
+ f"{rid}: unknown metabolite {metabolite!r}")
+ m = self.metabolites[metabolite]
+ require(isinstance(atoms, str) and re.fullmatch(r"[A-Za-z]+", atoms)
+ and len(atoms) == m["carbons"], f"{rid}: atom count mismatch for {metabolite}")
+ require(not (side == "substrates" and m["boundary"] == "sink"),
+ f"{rid}: a sink cannot be consumed")
+ require(not (side == "products" and m["boundary"] == "source"),
+ f"{rid}: a source cannot be produced")
+ side_names.append(metabolite)
+ side_labels.append(atoms)
+ used.add(metabolite)
+ all_atoms = "".join(side_labels)
+ unique(all_atoms, f"carbon atoms on {rid} {side}")
+ names.append(side_names)
+ labels.append(side_labels)
+ require(set("".join(labels[0])) == set("".join(labels[1])),
+ f"{rid}: carbon atoms are lost or created; include CO2 and other carbon products")
+ left, right = Counter(names[0]), Counter(names[1])
+ for name in balance:
+ balance[name].append(right[name] - left[name])
+
+ def stoichiometry(parts):
+ return "+".join((f"{{{count}}}" if count > 1 else "") + name
+ for name, count in Counter(parts).items())
+
+ self.reactions[rid] = dict(
+ order=i, stoichiometry="-->".join(stoichiometry(side) for side in names),
+ reaction="-->".join("+".join(side) for side in names),
+ atommap="-->".join("+".join(side) for side in labels),
+ externalids="", lb=lo, ub=hi)
+ require(used == self.metabolites.keys(), "Unused metabolites must be removed")
+ require(bool(balance), "At least one internal metabolite is required")
+ for name, row in balance.items():
+ require(any(v > 0 for v in row) and any(v < 0 for v in row),
+ f"{name}: internal pool needs production and consumption")
+ self.sources = {name for name, m in self.metabolites.items() if m["boundary"] == "source"}
+ require(bool(self.sources), "At least one carbon source is required")
+ # Catalytic cycles require an initial pool but can receive labeled carbon;
+ # connectivity is checked on the undirected graph below, not reachability.
+ connected = set(self.sources)
+ for _ in self.metabolites:
+ for r in spec["reactions"]:
+ members = {term[0] for term in r["substrates"] + r["products"]}
+ if members & connected:
+ connected.update(members)
+ require(connected == self.metabolites.keys(), "Network contains a pool disconnected from all sources")
+ self.balance = np.array(list(balance.values()), dtype=float)
+ rows, rhs = list(self.balance), [0.] * len(self.balance)
+ for rid, value in self.fixed.items():
+ rows.append(np.eye(len(self.ids))[self.ids.index(rid)])
+ rhs.append(value)
+ self.equalities = np.array(rows)
+ self.rhs = np.array(rhs)
+ self.lower, self.upper = np.array(self.lower), np.array(self.upper)
+ self.fragments = {}
+ for f in spec["fragments"]:
+ fields(f, {"id", "metabolite", "carbons", "provenance"})
+ fid = identifier(f["id"])
+ require(fid not in self.fragments, f"Duplicate fragment {fid}")
+ require(isinstance(f["metabolite"], str) and f["metabolite"] in self.metabolites,
+ f"{fid}: unknown metabolite")
+ m = self.metabolites[f["metabolite"]]
+ require(m["boundary"] == "internal", f"{fid}: fragment must reference an internal pool")
+ require(isinstance(f["carbons"], list) and bool(f["carbons"]), f"{fid}: empty carbon positions")
+ require(all(type(c) is int and 1 <= c <= m["carbons"] for c in f["carbons"]),
+ f"{fid}: carbon positions are 1-based and must exist")
+ unique(f["carbons"], f"positions in {fid}")
+ require(isinstance(f["provenance"], str) and bool(f["provenance"].strip()),
+ f"{fid}: document the measured carbon assignment")
+ self.fragments[fid] = f
+ self._engine = None
+
+ def check_flux(self, flux):
+ require(isinstance(flux, dict) and set(flux) == set(self.ids), "Supply exactly one flux for every reaction")
+ vector = np.array([number(flux[rid], rid) for rid in self.ids])
+ require(self.feasible(vector), "Fluxes violate mass balance, fixed constraints, or bounds")
+ return vector
+
+ def feasible(self, vector, tolerance=1e-8):
+ tolerance *= max(float(np.max(np.abs(vector))), float(np.max(np.abs(self.rhs))), 1e-300)
+ return bool(np.all(np.isfinite(vector)) and np.all(vector >= self.lower - tolerance)
+ and np.all(vector <= self.upper + tolerance)
+ and np.max(np.abs(self.equalities @ vector - self.rhs)) <= tolerance)
+
+ def engine(self):
+ if self._engine is None:
+ import mfapy
+ metabolites = {
+ name: dict(C_number=m["carbons"], order=i,
+ symmetry="symmetry" if m.get("symmetric") else "no",
+ carbonsource="carbonsource" if m["boundary"] == "source" else "no",
+ excreted="excreted" if m["boundary"] == "sink" else "no",
+ externalids="", lb=0., ub=1000.)
+ for i, (name, m) in enumerate(self.metabolites.items())}
+ fragments = {
+ fid: dict(atommap=f["metabolite"] + "_" + ":".join(map(str, sorted(f["carbons"]))),
+ type="intermediate", formula="", use="use", order=i)
+ for i, (fid, f) in enumerate(self.fragments.items())}
+ # The upstream constructor prints diagnostics. Return clean JSON from the CLI.
+ with contextlib.redirect_stdout(io.StringIO()):
+ self._engine = mfapy.metabolicmodel.MetabolicModel(self.reactions, {}, metabolites, fragments)
+ require(hasattr(self._engine, "func"), "mfapy could not construct this carbon network")
+ return self._engine
+
+ def predict(self, vector, experiment):
+ engine = self.engine()
+ # mfapy's generated steady-state solver drops rows with absolute turnover
+ # <= 0.001. MIDs are invariant to uniform flux scaling: keep every positive
+ # reaction at least 1 in the forward solver, without changing fitted units.
+ vector = np.asarray(vector, dtype=float)
+ require(np.all(np.isfinite(vector)) and np.min(vector) >= 0,
+ "Isotope simulation requires finite nonnegative directional fluxes")
+ positive = vector[vector > 0]
+ require(len(positive) > 0, "Isotope steady state is undefined with all fluxes zero")
+ forward = vector / positive.min()
+ cs = engine.generate_carbon_source_template()
+ for name, distribution in experiment["substrates"].items():
+ # Direct arrays avoid upstream set_each_isotopomer's exact sum > 1 check.
+ values = [0.] * (2 ** self.metabolites[name]["carbons"])
+ for bits, fraction in distribution.items():
+ values[int(bits[::-1], 2)] = fraction
+ require(cs.set_all_isotopomers(name, values, correction="no"), f"Invalid source {name}")
+ state = {"reaction": {rid: {"value": value} for rid, value in zip(self.ids, forward)},
+ "metabolite": {name: {"value": 1.} for name in self.metabolites}, "reversible": {}}
+ with np.errstate(all="raise"):
+ mdv = engine.generate_mdv(state, cs)
+ result = {}
+ for fid, f in self.fragments.items():
+ values = np.asarray(mdv.get_fragment_mdv(fid), dtype=float)
+ require(len(values) == len(f["carbons"]) + 1 and np.all(np.isfinite(values))
+ and np.min(values) >= -1e-8 and np.max(values) <= 1 + 1e-8
+ and abs(values.sum() - 1) < 1e-6,
+ f"Invalid simulated MDV for {fid}; check zero-throughput pools and mapping")
+ result[fid] = values
+ return result
+
+
+class Observations:
+ def __init__(self, spec, network):
+ fields(spec, {"schema_version", "steady_state", "shared_fluxes", "mdv_basis",
+ "correction_notes", "experiments"})
+ require(type(spec["schema_version"]) is int and spec["schema_version"] == 1, "Unsupported schema")
+ require(spec["steady_state"] == {"metabolic": True, "isotopic": True}
+ and all(type(v) is bool for v in spec["steady_state"].values()),
+ "This solver requires metabolic AND isotopic steady state; use an INST-MFA engine for time courses")
+ require(spec["shared_fluxes"] is True, "Experiments in a joint fit must share the same flux state")
+ require(spec["mdv_basis"] == "tracer_only", "Correct natural abundance externally; raw MDVs are not accepted")
+ require(isinstance(spec["correction_notes"], str) and bool(spec["correction_notes"].strip()),
+ "Record the correction method and how tracer purity was handled")
+ require(isinstance(spec["experiments"], list) and bool(spec["experiments"]), "No experiments")
+ self.spec, self.network, self.blocks, self.flux_blocks = spec, network, [], []
+ self.warnings = []
+ ids = []
+ for exp in spec["experiments"]:
+ fields(exp, {"id", "substrates", "measurements"}, {"flux_measurements"})
+ ids.append(identifier(exp["id"]))
+ require(isinstance(exp["substrates"], dict) and set(exp["substrates"]) == network.sources,
+ "Every experiment must explicitly describe every source, including unlabeled inputs")
+ for name, distribution in exp["substrates"].items():
+ require(isinstance(distribution, dict) and bool(distribution), f"{name}: missing isotopomers")
+ total = 0.
+ for bits, fraction in distribution.items():
+ require(isinstance(bits, str) and re.fullmatch(r"[01]+", bits)
+ and len(bits) == network.metabolites[name]["carbons"], f"{name}: invalid positional isotopomer")
+ total += number(fraction, name)
+ require(fraction >= 0, f"{name}: negative fraction")
+ require(abs(total - 1) < 1e-10, f"{name}: isotopomer fractions must sum to one; no implicit unlabeled remainder")
+ require(isinstance(exp["measurements"], list), "measurements must be a list")
+ seen = []
+ for obs in exp["measurements"]:
+ fields(obs, {"fragment", "mdv", "omit"}, {"sem", "covariance"})
+ fid = obs["fragment"]
+ require(isinstance(fid, str) and fid in network.fragments, f"Unknown fragment {fid!r}")
+ seen.append(fid)
+ n = len(network.fragments[fid]["carbons"]) + 1
+ require(isinstance(obs["mdv"], list) and len(obs["mdv"]) == n, f"{fid}: expected M+0 through M+{n-1}")
+ y = np.array([number(v, fid) for v in obs["mdv"]])
+ require(np.all(y >= 0) and np.all(y <= 1) and abs(y.sum() - 1) < 1e-6,
+ f"{fid}: MDV must be nonnegative and sum to one; do not silently clip or renormalize")
+ omit = obs["omit"]
+ require(type(omit) is int and 0 <= omit < n, f"{fid}: invalid omitted bin")
+ keep = np.array([i for i in range(n) if i != omit])
+ require(("sem" in obs) != ("covariance" in obs), f"{fid}: supply exactly one of sem or covariance")
+ if "covariance" in obs:
+ cov = np.asarray(obs["covariance"], dtype=float)
+ require(cov.shape == (n, n) and np.all(np.isfinite(cov)), f"{fid}: invalid covariance shape/values")
+ require(np.all(np.diag(cov) > 0), f"{fid}: covariance of retained bins must be positive definite")
+ std = np.sqrt(np.diag(cov))
+ correlation = cov / np.outer(std, std)
+ require(np.max(np.abs(correlation - correlation.T)) <= 1e-10
+ and np.all(np.abs(cov.sum(axis=0)) <= np.sum(np.abs(cov), axis=0) * 1e-10)
+ and np.all(np.abs(cov.sum(axis=1)) <= np.sum(np.abs(cov), axis=1) * 1e-10),
+ f"{fid}: full MDV covariance must be symmetric with zero row/column sums")
+ require(np.linalg.eigvalsh(correlation).min() >= -1e-10,
+ f"{fid}: full MDV covariance must be positive semidefinite")
+ reduced = cov[np.ix_(keep, keep)]
+ else:
+ require(isinstance(obs["sem"], list) and len(obs["sem"]) == n, f"{fid}: invalid sem length")
+ sem = np.array([number(v, fid) for v in obs["sem"]])
+ require(np.all(sem > 0), f"{fid}: sem values must be positive")
+ reduced = np.diag(sem[keep] ** 2)
+ self.warnings.append(f"{exp['id']}/{fid}: diagonal SEM approximation; correlations ignored, intervals and goodness-of-fit approximate")
+ uncertainty = float(np.sqrt(np.diag(reduced)).min())
+ require(abs(y.sum() - 1) <= min(1e-10, uncertainty * 1e-5),
+ f"{fid}: MDV normalization error exceeds numerical/error-scale tolerance; revisit upstream normalization")
+ try:
+ chol = cholesky(reduced, lower=True)
+ except np.linalg.LinAlgError as exc:
+ raise InputError(f"{fid}: covariance of retained bins must be positive definite") from exc
+ self.blocks.append((exp, fid, y, keep, chol))
+ unique(seen, f"fragment measurements in {exp['id']}; combine replicates with an explicit error model")
+ flux_obs = exp.get("flux_measurements", [])
+ require(isinstance(flux_obs, list), "flux_measurements must be a list")
+ flux_ids = []
+ for obs in flux_obs:
+ fields(obs, {"reaction", "value", "sem"})
+ require(obs["reaction"] in network.ids, "Unknown measured reaction")
+ require(number(obs["sem"], "flux sem") > 0, "Flux sem must be positive")
+ number(obs["value"], "measured flux")
+ flux_ids.append(obs["reaction"])
+ self.flux_blocks.append((exp["id"], network.ids.index(obs["reaction"]), obs))
+ unique(flux_ids, f"flux measurements in {exp['id']}")
+ unique(ids, "experiment IDs")
+ self.size = sum(len(block[3]) for block in self.blocks) + len(self.flux_blocks)
+
+ def residuals(self, vector, details=False):
+ predictions = {exp["id"]: self.network.predict(vector, exp) for exp in self.spec["experiments"]}
+ residuals, records = [], []
+ for exp, fid, observed, keep, chol in self.blocks:
+ predicted = predictions[exp["id"]][fid]
+ white = solve_triangular(chol, (predicted - observed)[keep], lower=True)
+ residuals.extend(white)
+ records.append(dict(experiment=exp["id"], fragment=fid, observed=observed.tolist(),
+ predicted=predicted.tolist(), retained_bins=keep.tolist(),
+ whitened_residuals=white.tolist()))
+ for exp_id, index, obs in self.flux_blocks:
+ value = (vector[index] - obs["value"]) / obs["sem"]
+ residuals.append(value)
+ records.append(dict(experiment=exp_id, reaction=obs["reaction"], observed=obs["value"],
+ predicted=float(vector[index]), standardized_residual=float(value)))
+ return (np.array(residuals), records) if details else np.array(residuals)
diff --git a/skills/13c-metabolic-flux/scripts/mfa.py b/skills/13c-metabolic-flux/scripts/mfa.py
new file mode 100644
index 00000000..7b2de18d
--- /dev/null
+++ b/skills/13c-metabolic-flux/scripts/mfa.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+"""Check, simulate, fit, and profile steady-state 13C metabolic flux models."""
+from __future__ import annotations
+
+import argparse
+import hashlib
+import importlib.metadata
+import json
+from pathlib import Path
+import sys
+
+sys.dont_write_bytecode = True
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ sub = parser.add_subparsers(dest="command", required=True)
+ for name in ("check", "simulate", "fit"):
+ p = sub.add_parser(name)
+ p.add_argument("--model", type=Path, required=True)
+ p.add_argument("--data", type=Path, required=True, help="Experiment/measurement JSON")
+ p.add_argument("--output", type=Path, help="JSON output; defaults to stdout")
+ if name == "simulate":
+ p.add_argument("--fluxes", type=Path, required=True, help="JSON mapping of reaction IDs to fluxes")
+ if name == "fit":
+ p.add_argument("--starts", type=int, default=8)
+ p.add_argument("--seed", type=int, default=2026)
+ p.add_argument("--maxiter", type=int, default=1000)
+ p.add_argument("--profile", action="append", default=[], help="Reaction to profile; repeat for multiple reactions")
+ p.add_argument("--profile-points", type=int, default=21)
+ p.add_argument("--profile-starts", type=int, default=4)
+ p.add_argument("--confidence", type=float, default=.95)
+ args = parser.parse_args()
+ from _mfa_model import InputError, Network, Observations, read_json, require
+ from _mfa_fit import FluxSpace, diagnostics, fit, profile
+ import numpy as np
+ try:
+ inputs = [args.model, args.data]
+ if args.command == "simulate":
+ inputs.append(args.fluxes)
+ require(args.output is None or all(args.output.resolve() != path.resolve() for path in inputs),
+ "Output must not overwrite an input file")
+ network = Network(read_json(args.model))
+ observations = Observations(read_json(args.data), network)
+ space = FluxSpace(network)
+ versions = {}
+ for package in ("mfapy", "numpy", "scipy"):
+ try:
+ versions[package] = importlib.metadata.version(package)
+ except importlib.metadata.PackageNotFoundError:
+ versions[package] = "not installed"
+ result = dict(command=args.command, model=network.spec["name"], versions=versions,
+ input_sha256={str(path): hashlib.sha256(path.read_bytes()).hexdigest() for path in inputs})
+ if args.command == "check":
+ result.update(status="input_contract_valid", free_flux_dimensions=space.dimension,
+ independent_measurements=observations.size, warnings=observations.warnings,
+ note="Checks declared mapping consistency and feasibility, not biological correctness or isotope steady state")
+ elif args.command == "simulate":
+ vector = network.check_flux(read_json(args.fluxes))
+ result["predictions"] = {exp["id"]: {key: value.tolist() for key, value in network.predict(vector, exp).items()}
+ for exp in observations.spec["experiments"]}
+ else:
+ fitted = fit(observations, args.starts, args.seed, args.maxiter)
+ result.update(diagnostics(observations, fitted))
+ result["settings"] = dict(starts=args.starts, seed=args.seed, maxiter=args.maxiter,
+ profile_points=args.profile_points, profile_starts=args.profile_starts,
+ confidence=args.confidence)
+ result["profiles"] = [profile(observations, fitted, rid, args.profile_points,
+ args.profile_starts, args.seed, args.maxiter, args.confidence)
+ for rid in dict.fromkeys(args.profile)]
+ text = json.dumps(result, indent=2, allow_nan=False) + "\n"
+ if args.output:
+ args.output.write_text(text, encoding="utf-8")
+ else:
+ print(text, end="")
+ return 0
+ except (InputError, ValueError, TypeError, KeyError, OSError, np.linalg.LinAlgError,
+ FloatingPointError, ZeroDivisionError) as exc:
+ print(f"mfa: {exc}", file=sys.stderr)
+ return 2
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/tests/13c-metabolic-flux/evals.json b/tests/13c-metabolic-flux/evals.json
new file mode 100644
index 00000000..642e583b
--- /dev/null
+++ b/tests/13c-metabolic-flux/evals.json
@@ -0,0 +1,21 @@
+{
+ "skill_name": "13c-metabolic-flux",
+ "evals": [
+ {
+ "id": 0,
+ "prompt": "Analyze the supplied steady-state 13C tracing experiment. Estimate flux v3 and assess whether flux v7 can be determined from the measurements. Fit the complete model using the stated measurement covariance and constraints, perform a nuisance-reoptimized profile for each target, and distinguish data-supported limits from imposed bounds. Return fit.json with numerical evidence and assessment.json with estimates, identifiability conclusions, assumptions, and limitations. Inputs are synthetic tracer-only MDVs; do not invent biological validation. An isolated Python 3.11 environment with mfapy 0.6.3, NumPy and SciPy is available; shell and internet access are available. Work only in your output directory; do not modify the repository. Spend at most six minutes on this task, and report any incomplete steps honestly.",
+ "expected_output": "Numerical fit and scientifically qualified flux-identifiability assessment",
+ "files": [
+ "assets/tca-model.json",
+ "assets/tca-reference-mdv.json"
+ ],
+ "assertions": [
+ "Recover v3 near 50 within 0.1 relative flux units.",
+ "Recognize that v7 is not determined by the isotope measurements, with numerical supporting evidence.",
+ "Preserve mass balance and the fixed reference flux.",
+ "Use the declared compositional covariance without counting all six bins as independent.",
+ "Reoptimize nuisance fluxes at each profile point and distinguish bounds from measurement information."
+ ]
+ }
+ ]
+}
diff --git a/tests/13c-metabolic-flux/evaluation.md b/tests/13c-metabolic-flux/evaluation.md
new file mode 100644
index 00000000..3ab1602b
--- /dev/null
+++ b/tests/13c-metabolic-flux/evaluation.md
@@ -0,0 +1,36 @@
+# Validation record
+
+Checked on 2026-09-29 using the environment pinned in `tests/skill-requirements.toml`.
+
+- Skill specification validation passed.
+- Isolated numerical/CLI suite: 45 tests and one shared-contract subtest passed.
+- Repository guard: 11 tests and 4,206 structural subtests passed.
+- Documented installation, simulation, branch fits and TCA fits/profiles ran successfully.
+- An independent reviewer reproduced and verified fixes for three numerical edge cases:
+ unrelated loose bounds, very small flux units, and inconsistent rare-bin covariance.
+- Security scan: no medium, high or critical findings. Two low informational findings
+ were reviewed: omission of the optional `allowed-tools` field, and installation of
+ upstream mfapy from its pinned Git commit. The installation source and build-code
+ execution are disclosed; the environment is isolated. The scanner's suggested YAML
+ list for `allowed-tools` is not compatible with this repository's string-only rule.
+
+## Initial paired agent evaluation
+
+The prompt and five assertions are in `evals.json`. One independent agent with the
+skill and one without it received the same synthetic TCA inputs, input schema, and
+preinstalled scientific dependencies, with a six-minute task budget.
+
+| Configuration | Assertions passed | Result |
+| --- | --- | --- |
+| With skill | 5/5 | Used the CLI, recovered v3 near 50, profiled both targets, and verified v7's apparent upper limit comes from the v6 bound. |
+| Without skill | 5/5 | Derived an independent positional-isotopomer solver, recovered the same limits, and checked the complete 176-state isotope balances. |
+
+Both obtained an approximate v3 profile interval of 48.6201–51.4002 and recognized
+that the isotope measurements do not determine v7. This single comparison provides
+no evidence of a model-performance advantage or that the skill is necessary. Agent
+time/token telemetry was unavailable; no efficiency claim is made. The paired runs
+preceded the numerical edge-case fixes, which were subsequently covered by regression
+tests, independent review, and rerunning every documented example.
+
+The numerical tests verify implementation behavior on the listed cases. They do not
+validate a biological model or establish reliability on organism-scale networks.
diff --git a/tests/13c-metabolic-flux/test_scripts.py b/tests/13c-metabolic-flux/test_scripts.py
new file mode 100644
index 00000000..ee085577
--- /dev/null
+++ b/tests/13c-metabolic-flux/test_scripts.py
@@ -0,0 +1,336 @@
+"""Scientific regression tests, using analytical cases and a published EMU result."""
+from __future__ import annotations
+
+import copy
+import json
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+import skill_contract
+
+np = pytest.importorskip("numpy")
+pytest.importorskip("scipy")
+pytest.importorskip("mfapy")
+
+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "13c-metabolic-flux"
+sys.path.insert(0, str(SKILL_ROOT / "scripts"))
+sys.dont_write_bytecode = True
+from _mfa_model import InputError, Network, Observations, read_json
+from _mfa_fit import FluxSpace, diagnostics, fit, profile
+
+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
+
+
+def asset(name):
+ return read_json(SKILL_ROOT / "assets" / name)
+
+
+def branch(data="branch-identifiable.json"):
+ network = Network(asset("branch-model.json"))
+ return network, Observations(asset(data), network)
+
+
+def test_published_emu_reference_and_positional_bit_order():
+ network = Network(asset("tca-model.json"))
+ data = asset("tca-tracer.json")
+ vector = network.check_flux(asset("tca-fluxes.json"))
+ result = network.predict(vector, data["experiments"][0])["GluWhole"]
+ # Independently published values, NOT generated as the expected result by this engine.
+ np.testing.assert_allclose(result, [.3464, .2695, .2708, .0807, .0286, .0039], atol=5e-5)
+ data["experiments"][0]["substrates"]["AcCoA"] = {"00": .5, "10": .25, "11": .25}
+ changed = network.predict(vector, data["experiments"][0])["GluWhole"]
+ assert abs(changed[0] - result[0]) > .03
+
+
+def test_analytical_split_recovery_and_profile_cutoff():
+ network, obs = branch()
+ fitted = fit(obs, starts=4)
+ result = diagnostics(obs, fitted)
+ assert result["fluxes"]["straight"] == pytest.approx(70., abs=2e-5)
+ assert result["fluxes"]["swap"] == pytest.approx(30., abs=2e-5)
+ assert result["local_sensitivity_rank"] == 1
+ assert result["max_mass_balance_error"] < 1e-9
+ p = profile(obs, fitted, "straight", points=41, starts=2)
+ assert p["status"] == "threshold_crossings_bracketed"
+ # y = 0.8*v/100, SEM = 0.01: exact Gaussian 95% interval.
+ expected = [70 - 1.9599639845 * .01 / .008, 70 + 1.9599639845 * .01 / .008]
+ assert all(any(a <= value <= b for a, b in p["threshold_crossing_brackets"]) for value in expected)
+ for point in p["points"]:
+ assert point["rss"] == pytest.approx(((point["flux"] - 70) * .8) ** 2, abs=1e-7)
+
+
+def test_whole_molecule_data_cannot_resolve_positional_routes():
+ _, obs = branch("branch-unresolved.json")
+ fitted = fit(obs, starts=3)
+ result = diagnostics(obs, fitted)
+ assert result["rss"] < 1e-15
+ assert result["local_sensitivity_rank"] == 0
+ assert result["goodness_of_fit"]["approximate_p_value"] is None
+ assert result["weak_flux_directions"]
+ p = profile(obs, fitted, "straight", points=7, starts=2)
+ assert p["status"] == "unresolved_within_bounds"
+ assert p["lower_bound_accepted"] and p["upper_bound_accepted"]
+
+
+def test_realistic_tca_exchange_is_not_recovered_from_an_uninformative_fragment():
+ network = Network(asset("tca-model.json"))
+ obs = Observations(asset("tca-reference-mdv.json"), network)
+ fitted = fit(obs, starts=4)
+ result = diagnostics(obs, fitted)
+ assert result["fluxes"]["v3"] == pytest.approx(50, abs=.03)
+ assert result["free_flux_dimensions"] == 2
+ assert result["local_sensitivity_rank"] == 1
+ # A different exchange flux has the same labeled-carbon prediction.
+ flux1 = asset("tca-fluxes.json")
+ flux2 = {**flux1, "v6": 250, "v7": 200}
+ for exp in obs.spec["experiments"]:
+ np.testing.assert_allclose(network.predict(network.check_flux(flux1), exp)["GluWhole"],
+ network.predict(network.check_flux(flux2), exp)["GluWhole"], atol=1e-10)
+ p = profile(obs, fitted, "v7", points=7, starts=3)
+ assert p["status"] in {"bound_limited", "unresolved_within_bounds"}
+ # The upper feasible bound may force branch flux v3 away from its optimum.
+ assert p["lower_bound_accepted"] is True
+
+
+def test_correlated_mdv_likelihood_invariant_to_omitted_bin():
+ n, _ = branch()
+ spec = asset("branch-unresolved.json")
+ spec["experiments"][0]["measurements"][0]["mdv"] = [.21, .78, .01]
+ scores = []
+ for omit in range(3):
+ spec["experiments"][0]["measurements"][0]["omit"] = omit
+ residual = Observations(copy.deepcopy(spec), n).residuals(n.check_flux(asset("branch-fluxes.json")))
+ scores.append(float(residual @ residual))
+ np.testing.assert_allclose(scores, [2., 2., 2.], atol=1e-10)
+
+
+def test_heteroscedastic_covariance_preserves_omitted_bin_invariance():
+ n, _ = branch()
+ data = asset("branch-unresolved.json")
+ measurement = data["experiments"][0]["measurements"][0]
+ measurement["mdv"] = [.1999995, .7999995, .000001]
+ measurement["covariance"] = [[1e-4 + 1e-12, -1e-4, -1e-12],
+ [-1e-4, 1e-4 + 1e-12, -1e-12],
+ [-1e-12, -1e-12, 2e-12]]
+ scores = []
+ for omit in range(3):
+ measurement["omit"] = omit
+ residual = Observations(copy.deepcopy(data), n).residuals(n.check_flux(asset("branch-fluxes.json")))
+ scores.append(float(residual @ residual))
+ np.testing.assert_allclose(scores, [.5, .5, .5], rtol=1e-7)
+
+
[email protected]("omit", [0, 1, 2])
+def test_rare_bin_covariance_error_is_rejected(omit):
+ n, _ = branch()
+ data = asset("branch-unresolved.json")
+ measurement = data["experiments"][0]["measurements"][0]
+ measurement["omit"] = omit
+ measurement["covariance"] = [[1e-4, -1e-4 + 1e-12, -1e-12],
+ [-1e-4 + 1e-12, 1e-4, -1e-12],
+ [-1e-12, -1e-12, 1e-12]]
+ with pytest.raises(InputError, match="zero row/column sums"):
+ Observations(data, n)
+
+
+def test_mdv_rounding_cannot_dominate_measurement_error():
+ n, _ = branch()
+ data = asset("branch-identifiable.json")
+ measurement = data["experiments"][0]["measurements"][0]
+ measurement["mdv"][0] += 1e-8
+ with pytest.raises(InputError, match="normalization error"):
+ Observations(data, n)
+
+
+def test_parallel_tracers_share_fluxes_and_measured_flux_can_anchor_scale():
+ spec = asset("branch-model.json")
+ del spec["reactions"][0]["fixed"]
+ network = Network(spec)
+ data = asset("branch-identifiable.json")
+ first = data["experiments"][0]
+ first["flux_measurements"] = [{"reaction": "uptake", "value": 100., "sem": .2}]
+ second = copy.deepcopy(first)
+ second["id"] = "C2label"
+ second["substrates"]["S"] = {"01": .8, "00": .2}
+ second["measurements"][0]["mdv"] = [.76, .24]
+ second.pop("flux_measurements")
+ data["experiments"].append(second)
+ obs = Observations(data, network)
+ result = diagnostics(obs, fit(obs, starts=5))
+ assert result["fluxes"]["straight"] == pytest.approx(70., abs=.01)
+ assert result["fluxes"]["uptake"] == pytest.approx(100., abs=.01)
+ assert result["local_sensitivity_rank"] == 2
+ assert result["goodness_of_fit"]["approximate_p_value"] > .99
+
+
+def test_condensation_of_repeated_substrate_matches_binomial():
+ spec = dict(schema_version=1, name="Condensation", flux_unit="relative", provenance="Analytical binomial test",
+ metabolites=[dict(id="S", carbons=1, boundary="source"),
+ dict(id="A", carbons=2, boundary="internal"),
+ dict(id="Out", carbons=2, boundary="sink")],
+ reactions=[dict(id="join", substrates=[["S", "A"], ["S", "B"]], products=[["A", "AB"]],
+ lower=.001, upper=200., fixed=100.),
+ dict(id="export", substrates=[["A", "AB"]], products=[["Out", "AB"]], lower=.001, upper=200.)],
+ fragments=[dict(id="Awhole", metabolite="A", carbons=[1, 2], provenance="All carbons")])
+ n = Network(spec)
+ p = n.predict(n.check_flux(dict(join=100., export=100.)), dict(substrates={"S": {"0": .75, "1": .25}}))
+ np.testing.assert_allclose(p["Awhole"], [.5625, .375, .0625], atol=1e-12)
+
+
+def test_symmetric_pool_averages_reversed_positions():
+ spec = asset("branch-model.json")
+ spec["metabolites"][2]["symmetric"] = True
+ n = Network(spec)
+ p = n.predict(n.check_flux(asset("branch-fluxes.json")), asset("branch-identifiable.json")["experiments"][0])
+ np.testing.assert_allclose(p["Bfirst"], [.6, .4], atol=1e-12)
+
+
+def test_unlabeled_and_fully_labeled_limits():
+ n, _ = branch()
+ for bits, expected in [("00", [1., 0., 0.]), ("11", [0., 0., 1.])]:
+ p = n.predict(n.check_flux(asset("branch-fluxes.json")), dict(substrates={"S": {bits: 1.}}))
+ np.testing.assert_allclose(p["Bwhole"], expected, atol=1e-12)
+
+
+def test_forward_prediction_is_invariant_to_uniform_flux_units():
+ n = Network(asset("tca-model.json"))
+ exp = asset("tca-tracer.json")["experiments"][0]
+ v = n.check_flux(asset("tca-fluxes.json"))
+ expected = n.predict(v, exp)["GluWhole"]
+ for factor in [1e-10, 1e-5, 1e5]:
+ np.testing.assert_allclose(n.predict(v * factor, exp)["GluWhole"], expected, atol=1e-10)
+
+
+def test_small_turnover_profile_endpoint_does_not_drop_emu_rows():
+ n = Network(asset("tca-model.json"))
+ space = FluxSpace(n, {"v7": 299.999})
+ assert space.dimension == 0
+ p = n.predict(space.base, asset("tca-tracer.json")["experiments"][0])["GluWhole"]
+ assert p.sum() == pytest.approx(1, abs=1e-10)
+
+
[email protected]("mutation,match", [
+ (lambda s: s["reactions"][1]["products"][0].__setitem__(1, "AC"), "lost or created"),
+ (lambda s: s["reactions"][1]["products"][0].__setitem__(1, "AA"), "Duplicate carbon"),
+ (lambda s: s["reactions"][1].__setitem__("id", "bad_name"), "Invalid identifier"),
+ (lambda s: s["reactions"][1].__setitem__("lower", -1), "lower"),
+ (lambda s: s["fragments"][0].__setitem__("carbons", [0]), "1-based"),
+ (lambda s: s["fragments"][0].__setitem__("carbons", [1, 1]), "Duplicate positions"),
+ (lambda s: s["metabolites"][0].__setitem__("carbons", 0), "carbon count"),
+ (lambda s: s["reactions"][0].__setitem__("upper", float("nan")), "finite"),
+])
+def test_invalid_networks_rejected(mutation, match):
+ spec = asset("branch-model.json")
+ mutation(spec)
+ with pytest.raises(InputError, match=match):
+ Network(spec)
+
+
[email protected]("mutation,match", [
+ (lambda s: s["steady_state"].__setitem__("isotopic", False), "steady state"),
+ (lambda s: s.__setitem__("mdv_basis", "raw"), "natural abundance"),
+ (lambda s: s.__setitem__("shared_fluxes", False), "same flux state"),
+ (lambda s: s["experiments"][0].__setitem__("substrates", {}), "every source"),
+ (lambda s: s["experiments"][0]["substrates"]["S"].__setitem__("00", .1), "sum to one"),
+ (lambda s: s["experiments"][0]["measurements"][0].__setitem__("mdv", [.2, .3]), "sum to one"),
+ (lambda s: s["experiments"][0]["measurements"][0].__setitem__("mdv", [-.1, 1.1]), "nonnegative"),
+ (lambda s: s["experiments"][0]["measurements"][0].__setitem__("covariance", [[1., 0.], [0., 1.]]), "zero row"),
+ (lambda s: s["experiments"][0]["measurements"][0].__setitem__("covariance", [[0., 0.], [0., 0.]]), "positive definite"),
+ (lambda s: s["experiments"][0]["measurements"].append(copy.deepcopy(s["experiments"][0]["measurements"][0])), "Duplicate fragment"),
+])
+def test_invalid_observations_rejected(mutation, match):
+ network, _ = branch()
+ data = asset("branch-identifiable.json")
+ mutation(data)
+ with pytest.raises(InputError, match=match):
+ Observations(data, network)
+
+
+def test_sem_approximation_disclosed():
+ n, _ = branch()
+ data = asset("branch-identifiable.json")
+ m = data["experiments"][0]["measurements"][0]
+ m.pop("covariance")
+ m["sem"] = [.01, .01]
+ assert "approximate" in Observations(data, n).warnings[0]
+
+
+def test_infeasible_fixed_fluxes_and_unbalanced_simulation():
+ spec = asset("branch-model.json")
+ spec["reactions"][-1]["fixed"] = 99.
+ with pytest.raises(InputError, match="infeasible"):
+ FluxSpace(Network(spec))
+ network, _ = branch()
+ with pytest.raises(InputError, match="mass balance"):
+ network.check_flux({**asset("branch-fluxes.json"), "export": 99.})
+
+
+def test_loose_bound_on_fixed_reaction_does_not_fix_free_fluxes():
+ spec = asset("branch-model.json")
+ spec["reactions"][0]["upper"] = 1e12
+ network = Network(spec)
+ obs = Observations(asset("branch-identifiable.json"), network)
+ fitted = fit(obs, starts=3)
+ assert fitted["space"].dimension == 1
+ assert fitted["vector"][network.ids.index("straight")] == pytest.approx(70, abs=1e-4)
+ assert profile(obs, fitted, "straight", points=7, starts=2)["status"] != "fixed_by_constraints"
+
+
[email protected]("factor", [1e-10, 1e-8, 1e5])
+def test_fitting_profiles_and_infeasibility_are_invariant_to_flux_units(factor):
+ spec = asset("branch-model.json")
+ for reaction in spec["reactions"]:
+ for key in ("lower", "upper", "fixed"):
+ if key in reaction:
+ reaction[key] *= factor
+ network = Network(spec)
+ obs = Observations(asset("branch-identifiable.json"), network)
+ fitted = fit(obs, starts=3)
+ result = diagnostics(obs, fitted)
+ assert result["free_flux_dimensions"] == result["local_sensitivity_rank"] == 1
+ assert result["fluxes"]["straight"] / factor == pytest.approx(70, abs=1e-4)
+ assert profile(obs, fitted, "straight", points=7, starts=2)["status"] == "threshold_crossings_bracketed"
+ spec["reactions"][-1]["fixed"] = 99 * factor
+ with pytest.raises(InputError, match="infeasible"):
+ FluxSpace(Network(spec))
+
+
+def test_all_fixed_model_and_fixed_profile():
+ spec = asset("branch-model.json")
+ spec["reactions"][1]["fixed"] = 70.
+ network = Network(spec)
+ obs = Observations(asset("branch-identifiable.json"), network)
+ fitted = fit(obs)
+ assert fitted["rss"] < 1e-20
+ assert profile(obs, fitted, "straight")["status"] == "fixed_by_constraints"
+
+
+def test_duplicate_json_keys_are_rejected(tmp_path):
+ path = tmp_path / "duplicate.json"
+ path.write_text('{"S": 1, "S": 2}')
+ with pytest.raises(InputError, match="Duplicate JSON"):
+ read_json(path)
+
+
+def test_cli_end_to_end_and_input_protection(tmp_path):
+ command = [sys.executable, str(SKILL_ROOT / "scripts" / "mfa.py"), "fit",
+ "--model", str(SKILL_ROOT / "assets" / "branch-model.json"),
+ "--data", str(SKILL_ROOT / "assets" / "branch-identifiable.json"), "--starts", "3"]
+ result = subprocess.run(command, capture_output=True, text=True, timeout=60)
+ assert result.returncode == 0, result.stderr
+ payload = json.loads(result.stdout)
+ assert payload["fluxes"]["straight"] == pytest.approx(70., abs=.001)
+ assert len(payload["input_sha256"]) == 2
+ data = tmp_path / "data.json"
+ data.write_text(json.dumps(asset("branch-identifiable.json")))
+ original = data.read_bytes()
+ bad = subprocess.run(command + ["--data", str(data), "--output", str(data)], capture_output=True, text=True)
+ assert bad.returncode == 2 and data.read_bytes() == original
+
+
+def test_optimizer_failure_not_reported_as_a_fit():
+ _, obs = branch()
+ with pytest.raises(InputError, match="No converged feasible fit"):
+ fit(obs, starts=1, maxiter=1)
diff --git a/tests/skill-requirements.toml b/tests/skill-requirements.toml
index 38b7f936..f824a10d 100644
--- a/tests/skill-requirements.toml
+++ b/tests/skill-requirements.toml
@@ -578,6 +578,16 @@ packages = ["pytdc", "setuptools"]
[skills.cobrapy]
packages = ["cobra", "matplotlib", "pandas", "seaborn"]
+[skills.13c-metabolic-flux]
+python = "3.11"
+# mfapy is GitHub-only; pin the reviewed source, not a moving branch.
+packages = [
+ "mfapy @ git+https://github.com/fumiomatsuda/mfapy.git@a10433af16682386548b360297e2476152d46ede",
+ "numpy==2.4.6",
+ "scipy==1.17.1",
+ "nlopt==2.11.0",
+]
+
# --- medical imaging and clinical data ------------------------------------
[skills.pydicom]