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.

Update README and skills documentation to reflect new skill additions

Timothy Kassis75a42eff978c
diff --git a/README.md b/README.md
index df7365ce..6ba37aca 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-170-brightgreen.svg)](#-whats-included)
+[![Skills](https://img.shields.io/badge/Skills-171-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 170 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 171 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 **170 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 **171 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.
@@ -45,6 +45,7 @@ These skills enable your AI agent to seamlessly work with specialized scientific
- 🌌 Physics & Astronomy - Astronomical data analysis, coordinate transformations, cosmological calculations, symbolic mathematics, physics computations
- ⚙️ Engineering & Simulation - Lab hardware CAD and custom-part fabrication, discrete-event simulation, multi-objective optimization, metabolic engineering, systems modeling, process optimization
- 📊 Data Analysis & Visualization - Statistical analysis, network analysis, time series, publication-quality figures, large-scale data processing, EDA
+- 🌊 Chemical Oceanography - Seawater carbonate chemistry, ocean acidification, mineral saturation, and measurement uncertainty
- 🌍 Geospatial Science & Remote Sensing - Satellite imagery processing, GIS analysis, spatial statistics, terrain analysis, machine learning for Earth observation
- 🧪 Laboratory Automation - Liquid handling protocols, lab equipment control, workflow automation, LIMS integration
- 📚 Scientific Communication - Evidence-traceable writing, confidential authorized peer review, literature synthesis, document processing, macro-free PPTX posters, slides, schematics, and citation management
@@ -74,7 +75,7 @@ Recorded walkthroughs of these skills on real research tasks, from the [K-Dense
## 📦 What's Included
-This repository provides **170 scientific and research skills** organized into the following categories:
+This repository provides **171 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 +122,7 @@ Each skill includes:
- **Multi-Step Workflows** - Execute complex pipelines with a single prompt
### 🎯 **Comprehensive Coverage**
-- **170 Skills** - Extensive coverage across all major scientific domains
+- **171 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 +229,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 170 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 171 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 +470,7 @@ networks, and search GEO for similar patterns.
## 📚 Available Skills
-This repository contains **170 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 **171 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
@@ -549,6 +550,10 @@ This repository contains **170 scientific and research skills** organized across
- Discrete-event simulation: SimPy 4.1.2 with replication, warm-up, and output-analysis guidance
- Symbolic math: SymPy
+#### 🌊 **Chemical Oceanography** (1 skill)
+
+- [Marine Carbonate Chemistry](skills/marine-carbonate-chemistry/SKILL.md): paired seawater measurements with PyCO2SYS, carbonate speciation, pH-scale handling, lab-to-in-situ corrections, aragonite/calcite saturation, and uncertainty propagation
+
#### 📊 **Data Analysis & Visualization** (22 skills)
- Visualization: Matplotlib, Seaborn, Scientific Visualization
- Geospatial analysis: GeoPandas 1.1.4 and GeoMaster (remote sensing, GIS, satellite imagery, spatial ML, 500+ examples)
@@ -927,7 +932,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 = {170 skills covering databases, packages, integrations, and analysis tools}
+ note = {171 skills covering databases, packages, integrations, and analysis tools}
}
```
diff --git a/docs/skills.md b/docs/skills.md
index 434a6b67..ea7f9494 100644
--- a/docs/skills.md
+++ b/docs/skills.md
@@ -1,6 +1,6 @@
# Scientific Skills
-This checkout contains **169 skills**. The catalog below groups skills by domain. Summaries mirror each skill's
+This checkout contains **171 skills**. The catalog below groups skills by domain. Summaries mirror each skill's
current `description`; open its linked `SKILL.md` for setup, tested versions, workflows,
and limitations. See [workflow examples](examples.md) for ways to combine them.
@@ -150,6 +150,10 @@ and limitations. See [workflow examples](examples.md) for ways to combine them.
- **[Transformers](../skills/transformers/SKILL.md)** - Hugging Face Transformers for loading Hub models, running pipeline inference, text generation, and Trainer fine-tuning on NLP, vision, audio, and multimodal tasks. Use when working with AutoModel, pipelines, tokenizers, or TrainingArguments—not for general ML outside the Transformers library.
- **[UMAP-learn](../skills/umap-learn/SKILL.md)** - Use UMAP-learn for nonlinear dimensionality reduction, 2D/3D embeddings, clustering preprocessing, supervised or semi-supervised UMAP, DensMAP, AlignedUMAP, and Parametric UMAP workflows.
+### Chemical Oceanography
+
+- **[Marine Carbonate Chemistry](../skills/marine-carbonate-chemistry/SKILL.md)** - Solves seawater carbonate chemistry with PyCO2SYS for chemical oceanography, ocean acidification, and marine carbon-cycle research. Use for paired total alkalinity, dissolved inorganic carbon, pH, or seawater pCO2/fCO2 measurements; carbonate speciation; aragonite and calcite saturation; Revelle factors; lab-to-in-situ temperature and pressure corrections; and measurement uncertainty propagation. Applies to carbonate-system calculations, not general aqueous speciation or air-sea gas-flux estimation.
+
### Materials Science & Chemistry
- **[Astropy](../skills/astropy/SKILL.md)** - Core Python library for astronomy and astrophysics workflows that need Astropy APIs, including units/quantities, coordinates, FITS I/O, tables, time systems, WCS, and cosmology. Use when implementing or debugging astronomical data analysis code with Astropy.
- **[COBRApy](../skills/cobrapy/SKILL.md)** - Constraint-based metabolic modeling (COBRA). FBA, FVA, gene knockouts, flux sampling, SBML models, for systems biology and metabolic engineering analysis.
diff --git a/skills/marine-carbonate-chemistry/SKILL.md b/skills/marine-carbonate-chemistry/SKILL.md
new file mode 100644
index 00000000..20948a91
--- /dev/null
+++ b/skills/marine-carbonate-chemistry/SKILL.md
@@ -0,0 +1,148 @@
+---
+name: marine-carbonate-chemistry
+description: Solves seawater carbonate chemistry with PyCO2SYS for chemical oceanography, ocean acidification, and marine carbon-cycle research. Use for paired total alkalinity, dissolved inorganic carbon, pH, or seawater pCO2/fCO2 measurements; carbonate speciation; aragonite and calcite saturation; Revelle factors; lab-to-in-situ temperature and pressure corrections; and measurement uncertainty propagation. Applies to carbonate-system calculations, not general aqueous speciation or air-sea gas-flux estimation.
+license: MIT
+compatibility: Requires Python 3.13 with PyCO2SYS 1.8.3.4 and NumPy. Network access is needed only to install packages or obtain external data; bundled calculations run locally without credentials.
+metadata:
+ version: "1.0"
+ skill-author: K-Dense Inc.
+ upstream-version: "PyCO2SYS 1.8.3.4"
+---
+
+# Marine Carbonate Chemistry
+
+Turn two independent seawater carbonate measurements into a reproducible speciation
+table, mineral saturation estimates, and a record of the calculation assumptions.
+Targets **PyCO2SYS 1.8.3.4**, tested with Python 3.13 and NumPy 2.5.1. The PyCO2SYS
+v2 beta uses a different implementation; do not mix its examples with this pin.
+
+## When to use
+
+- Analyze bottle samples, shipboard carbonate measurements, or acidification experiments.
+- Calculate total-scale pH, seawater pCO2/fCO2, carbonate ion, aragonite/calcite
+ saturation state, or the Revelle factor from a valid measured pair.
+- Convert a system determined at laboratory conditions to specified ocean conditions.
+- Quantify how stated measurement uncertainties affect the calculated results.
+
+This workflow concerns seawater carbonate equilibria. Freshwater, porewaters with
+substantial uncharacterized alkalinity, brines outside the selected calibration range,
+and reaction/transport models require additional chemistry and validation. Do not
+infer an air-sea flux or atmospheric carbon removal from a carbonate equilibrium alone.
+
+## Establish the measurement contract
+
+Before running a solver, identify the two measured variables, their units, quality flags,
+and their temperature/pressure basis. Retain a separate source table containing station,
+depth, timestamps, methods, reference materials, and original QC codes, joined by sample ID.
+Do not turn missing values or rejected measurements into zero.
+
+| Quantity | Required convention |
+|---|---|
+| Total alkalinity (TA), DIC, nutrients | micromol per **kg seawater**, not per litre or kg water |
+| Salinity | Practical Salinity, not Absolute Salinity in g/kg |
+| Temperature | In-situ/measurement temperature in degrees Celsius, not potential or Conservative Temperature |
+| Pressure | Sea pressure in dbar; surface sample is 0, not 1 atmosphere |
+| pH | Declared total, seawater, free, or NBS scale, at the declared measurement conditions |
+| pCO2 / fCO2 | Seawater partial pressure / fugacity in microatm; these are distinct quantities |
+
+TA and DIC remain constant during the solver's temperature/pressure conversion for a
+closed sample. pH and gas parameters change. Two inputs measured at different conditions
+cannot simply share one `temperature` value. Establish a consistent measurement basis
+first. Temperature correction does not repair sample changes caused by gas exchange,
+biology, evaporation, or mineral dissolution/precipitation.
+
+Use two independent carbonate parameters. pCO2 plus fCO2 is not an independent pair.
+Three or more measurements enable an overdetermination check: solve independent pairs
+and compare predicted versus measured third parameters, including their uncertainty.
+Do not average inconsistent solutions to hide a calibration or scale mismatch.
+
+## Install
+
+Create a dedicated environment in the user's working directory:
+
+```bash
+uv venv --python 3.13 .venv
+uv pip install --python .venv/bin/python "PyCO2SYS==1.8.3.4" "numpy==2.5.1"
+```
+
+On Windows the environment's interpreter is `.venv/Scripts/python.exe`. The commands
+below use the POSIX interpreter path. Set the shell variable `SKILL_DIR` to this installed
+skill's directory. Keep inputs and generated outputs in the working directory.
+
+## Workflow
+
+1. **Prepare paired measurements.** Use the schema in
+ [references/input-and-results.md](references/input-and-results.md). Resolve units and
+ quality flags before creating the input file. Supply phosphate and silicate explicitly;
+ zero is an assumption to justify, not a missing-data code.
+2. **Choose equilibrium constants.** Read
+ [references/chemistry-decisions.md](references/chemistry-decisions.md) for pH scales,
+ carbonic-acid constants, borate, saturation interpretation, and uncertainty limits.
+ Match the study's validated convention and report it. The helper supports carbonic-acid
+ options 10 and 15; other systems require a separately verified direct PyCO2SYS call.
+3. **Solve with `scripts/solve_carbonate.py`.** It validates the full input table, solves
+ the pair, checks finite outputs and DIC species balance, then writes `carbonate.csv`
+ and `provenance.json` into a new output directory.
+4. **Review flags and consistency.** Inspect input and output calibration-range flags,
+ carbonate balance, measured-third-parameter residuals when available, and controls.
+ A successful solve does not validate the sample, constants, or measurement method.
+5. **Report at the intended conditions.** Results ending `_out` describe the supplied
+ output temperature/pressure. Unsuffixed results describe input conditions. Include
+ parameter pair, pH scale, units, constants, nutrient assumptions, uncertainty scope,
+ software versions, and excluded/flagged samples with the result table.
+
+## Worked example: closed-sample condition correction
+
+The following values are synthetic, not field observations. Save this as `samples.csv`
+in a working directory. The two samples differ only in DIC; the second represents a
+fixed-alkalinity CO2-addition comparison. Their measurements are at 25 C and 0 dbar;
+results are also requested at 10 C and 1000 dbar.
+
+```csv
+sample_id,par1,par2,salinity,temperature,pressure,total_phosphate,total_silicate,temperature_out,pressure_out,u_par1,u_par2
+baseline,2300,2000,35,25,0,0,0,10,1000,2,2
+added_co2,2300,2100,35,25,0,0,0,10,1000,2,2
+```
+
+Run from that working directory:
+
+```bash
+.venv/bin/python "$SKILL_DIR/scripts/solve_carbonate.py" samples.csv \
+ --par1-type alkalinity --par2-type dic --k-carbonic 10 \
+ --output-dir carbonate-results
+```
+
+For the baseline, the tested version gives input-condition total pH **8.045886**,
+pCO2 **396.958 microatm**, and aragonite saturation **3.386201**. At the specified output
+conditions, total pH is **8.241241** and aragonite saturation **2.605691**. These rounded
+values are regression checks for this exact setup, not universal seawater benchmarks.
+With independent 2 micromol/kg uncertainties in TA and DIC only, `u_pH_total` is about
+**0.004580**. This excludes equilibrium-constant and other input uncertainty.
+
+For TA + measured pH, use `--par2-type ph --ph-scale total` only if the source explicitly
+identifies total-scale pH; replace `par2` and `u_par2` with the measured pH and its absolute
+standard uncertainty. A column named merely `pH` is insufficient to establish its scale.
+
+## Uncertainty and interpretation
+
+Optional `u_` input columns contain absolute **one-standard-deviation** uncertainties.
+They propagate to total pH, pCO2, and aragonite saturation at each requested condition.
+The helper assumes independent errors and treats unlisted inputs/constants as exact.
+For covariance, constants uncertainty, or strongly nonlinear uncertainty, follow the
+decision guide and validate a tailored propagation instead of calling these outputs a
+complete uncertainty budget.
+
+Omega < 1 indicates thermodynamic undersaturation with respect to the named mineral.
+It does not establish a dissolution rate or an organism's response. A lower pH across
+unmatched samples is not by itself evidence of an anthropogenic acidification trend.
+
+## Sources and validation boundary
+
+- [PyCO2SYS v1 arguments, units, settings, and result keys](https://pyco2sys.readthedocs.io/en/latest/co2sys_nd/)
+- [Uncertainty propagation](https://pyco2sys.readthedocs.io/en/latest/uncertainty/)
+- [Upstream validation](https://pyco2sys.readthedocs.io/en/latest/validate/)
+- [Humphreys et al. (2022), PyCO2SYS v1.8](https://doi.org/10.5194/gmd-15-15-2022)
+
+Repository tests exercise the pinned solver, independent-pair round trips, carbon balance,
+pH-scale equivalence, condition correction, uncertainty quadrature, CSV errors, and the
+worked example. They establish software behavior, not independent field-data validation.
diff --git a/skills/marine-carbonate-chemistry/references/chemistry-decisions.md b/skills/marine-carbonate-chemistry/references/chemistry-decisions.md
new file mode 100644
index 00000000..40d5912a
--- /dev/null
+++ b/skills/marine-carbonate-chemistry/references/chemistry-decisions.md
@@ -0,0 +1,85 @@
+# Chemistry decisions that affect the answer
+
+## Constant sets and seawater composition
+
+The helper requires `--k-carbonic`; it does not infer a constant set from the dataset.
+Its two supported options are:
+
+| Option | Carbonic-acid parameterization | Documented calibration interval |
+|---|---|---|
+| 10 | Lueker, Dickson & Keeling (2000) | 2 < T < 35 C; 19 < Practical Salinity < 43 |
+| 15 | Waters, Millero & Woosley (2014) | 0 < T < 45 C; 0 < Practical Salinity < 45 |
+
+These temperature/salinity intervals come from the [PyCO2SYS v1 settings documentation](https://pyco2sys.readthedocs.io/en/latest/co2sys_nd/).
+They are checks on one part of the model, not proof that all chemical assumptions are
+valid. Pressure corrections do not remove the need to assess constants and sample
+composition. Boundary values are flagged conservatively. Both measurement and output
+conditions are checked.
+
+Choose the convention established for the study, and explain changes. The helper's
+`--total-borate 1` uses Uppstrom (1974); `2` uses Lee et al. (2010). Neither automatically
+handles an altered boron-to-salinity ratio. Calcium, sulfate, and fluoride are inferred
+by the library's seawater relationships. Freshwater mixing, unusual ionic composition,
+and substantial organic alkalinity can violate these assumptions even if the selected
+carbonic-acid constants permit that salinity. Use direct composition-aware calculations
+when those terms matter; do not substitute salinity zero into a normal-seawater recipe.
+
+## Measurement-scale checks
+
+Total, seawater, free, and NBS pH are not interchangeable. The scale belongs to the
+method and calibration record, not a numerical guess. NBS electrode readings in
+seawater warrant particular attention to calibration and activity conventions.
+PyCO2SYS accepts the declared input scale; the bundled report consistently emits total pH.
+
+Gas measurements must specify seawater pCO2 or fCO2 and the equilibrator/measurement
+temperature. Atmospheric mole fraction in ppm is not a seawater pCO2 observation.
+The helper intentionally omits gas-flux calculations: a flux additionally requires
+consistent air/water gas quantities and an appropriate gas-transfer model.
+
+For a closed sample, convert both known parameters at their actual input conditions
+and request output temperature/pressure. Never set laboratory-measured pH's input
+temperature to the ocean temperature just because the desired result is in situ.
+
+## Uncertainty that matches the claim
+
+The helper forwards explicitly supplied standard uncertainties to PyCO2SYS v1's
+finite-difference propagation. Its reported u values assume independent input errors.
+Missing u columns imply zero uncertainty for that input. Constant uncertainty,
+method bias, preservation error, and unmodeled solutes are absent from that budget.
+
+For a more complete analysis:
+
+1. Define which measured quantities share calibration or preparation errors. TA and
+ DIC errors may covary; also avoid treating the same temperature measurement as two
+ independent uncertain inputs merely because input/output columns both exist.
+2. With independent errors, a tailored `pyco2.sys` call can use
+ `uncertainty_into` and `uncertainty_from`, including suitable equilibrium-constant
+ uncertainties. Upstream provides `pyco2.uncertainty_OEDG18`; inspect its assumptions
+ before adopting it. Input/output constant uncertainties require deliberate treatment
+ of their shared errors; see upstream's `_both` keys.
+3. With covariance or appreciable nonlinearity, use a scientifically justified joint
+ error model, propagate paired Monte Carlo draws through the solver, and check output
+ quantiles and invalid draws. Document distributions, correlations, seed, convergence,
+ and any truncation. This extension is not implemented by the bundled helper.
+4. Compare replicate precision and certified-reference-material results with the
+ assumed uncertainties. Numerical propagation cannot recover unknown measurement bias.
+
+Read the [upstream uncertainty guide](https://pyco2sys.readthedocs.io/en/latest/uncertainty/)
+when implementing those extensions. Keep helper u values labeled as **conditional,
+independent-input uncertainty**, not a complete accuracy claim.
+
+## Interpret at the right level
+
+- Saturation state describes thermodynamics relative to a named mineral; it is not a
+ kinetic dissolution model, coral health score, or universal biological threshold.
+- The Revelle factor describes the local relative pCO2 sensitivity to relative DIC
+ change at constant TA and conditions. Use an explicit new equilibrium for a large
+ perturbation rather than extending a local linear sensitivity indefinitely.
+- A controlled increase in DIC at fixed TA can illustrate a carbonate response to CO2
+ addition. It does not reproduce all drivers of a real ocean acidification time series.
+- Alkalinity addition scenarios require mixing, precipitation, and gas-exchange
+ accounting before making carbon-removal claims; the closed-equilibrium solver alone
+ establishes none of these budgets.
+
+For methods context and solver validation, cite [Humphreys et al. (2022)](https://doi.org/10.5194/gmd-15-15-2022)
+and the relevant constants/measurement-method references for the actual study.
diff --git a/skills/marine-carbonate-chemistry/references/input-and-results.md b/skills/marine-carbonate-chemistry/references/input-and-results.md
new file mode 100644
index 00000000..4b7f6602
--- /dev/null
+++ b/skills/marine-carbonate-chemistry/references/input-and-results.md
@@ -0,0 +1,70 @@
+# Input table and output contract
+
+## Input CSV
+
+Use UTF-8 CSV with one row per sample, a header, and a unique nonempty `sample_id`.
+All numeric cells must be finite; blanks, NaN, infinity, duplicate headers/IDs, extra
+fields, and unknown columns are errors. Convert source missing-value codes before
+selecting valid rows; a sentinel such as -999 is not recognized as missing.
+
+Required numeric columns:
+
+| Column | Meaning |
+|---|---|
+| `par1`, `par2` | Measurements identified by `--par1-type` and `--par2-type` |
+| `salinity` | Practical Salinity, dimensionless |
+| `temperature`, `pressure` | Input-condition temperature (C) and sea pressure (dbar) |
+| `total_phosphate`, `total_silicate` | Total nutrients in micromol/kg seawater |
+
+Parameter types are `alkalinity`, `dic`, `ph`, `pco2`, and `fco2`. Concentrations are
+micromol/kg seawater, gas parameters microatm, and pH is on `--ph-scale`. A batch has
+one parameter-pair definition and one pH-scale definition. Split mixed-method tables
+when their measurement conventions differ. DIC and gas inputs must be positive;
+this marine helper supports 0 < input pH < 14. TA may be signed, but a mathematical
+solution still requires inspection for chemical plausibility.
+
+Optional numeric columns:
+
+- `temperature_out` **and** `pressure_out`: provide both or neither, for every row.
+ Requiring both avoids accidentally retaining laboratory pressure during an ocean
+ temperature correction. Output salinity is the input salinity.
+- `total_ammonia`, `total_sulfide`: default to zero if absent, recorded in provenance.
+ Use measured values when relevant; the helper does not model unspecified organic
+ alkalinity. Anoxic and nonstandard waters need additional assessment.
+- `u_` followed by any supplied numeric input name: absolute 1-sigma uncertainty in
+ that variable's units. All uncertainty values must be nonnegative. `u_temperature_out`
+ and `u_pressure_out` are accepted only when their corresponding inputs are supplied.
+
+The helper does not infer units, source QC meanings, pH scales, depth-to-pressure
+conversions, or which measurements to discard. Keep extra survey metadata in a
+separate table linked by `sample_id`; unknown input columns are rejected to catch typos.
+
+## Results
+
+`carbonate.csv` retains `sample_id` and every supplied input prefixed with `input_`.
+Calculated columns use PyCO2SYS v1 names:
+
+- `alkalinity`, `dic`, `aqueous_CO2`, `bicarbonate`, `carbonate`: micromol/kg seawater.
+- `pH_total`: total-scale pH, regardless of the supplied input pH scale.
+- `pCO2`, `fCO2`: microatm; never equate the two.
+- `saturation_aragonite`, `saturation_calcite`, `revelle_factor`: dimensionless.
+- `_out` versions of the condition-dependent columns when output conditions exist.
+ TA and DIC have no `_out` columns because this is a closed-sample correction.
+- `u_pH_total`, `u_pCO2`, `u_saturation_aragonite` and their `_out` forms when any
+ uncertainties were supplied. These are standard uncertainties, not 95% intervals.
+- `qc_flags`: semicolon-separated carbonic-constant calibration-range flags.
+
+An empty flag field means only that the range checks passed; it is not a measurement
+QC grade. Values outside a range are retained and visibly flagged so the analyst can
+reconsider the constant set. They should not be reported as validated predictions.
+
+`provenance.json` records the input filename and SHA-256, sample count, software versions,
+parameter types, explicit solver options, zero-solute assumptions, uncertainty sources,
+units, and sample-specific range flags. Archive it with the input and output tables.
+All rows are validated before output creation. Existing output directories are refused.
+
+The helper's fixed options are bisulfate 1, fluoride 1, gas constant 3, buffer mode 1,
+atmospheric pressure 1 atm, and `opt_pressured_kCO2=0`. It records these explicitly.
+The last option follows the v1 default convention for CO2 solubility; if a study requires
+hydrostatic-pressure-corrected solubility or different atmospheric pressure, use a
+separately tested direct call and document that difference when comparing gas results.
diff --git a/skills/marine-carbonate-chemistry/scripts/solve_carbonate.py b/skills/marine-carbonate-chemistry/scripts/solve_carbonate.py
new file mode 100644
index 00000000..d2d51a57
--- /dev/null
+++ b/skills/marine-carbonate-chemistry/scripts/solve_carbonate.py
@@ -0,0 +1,215 @@
+#!/usr/bin/env python3
+"""Solve paired seawater carbonate measurements with a recorded PyCO2SYS setup."""
+
+from __future__ import annotations
+
+import argparse
+import csv
+import hashlib
+import io
+import json
+import math
+from pathlib import Path
+import platform
+
+TYPES = {"alkalinity": 1, "dic": 2, "ph": 3, "pco2": 4, "fco2": 5}
+SCALES = {"total": 1, "seawater": 2, "free": 3, "nbs": 4}
+REQUIRED = ("par1", "par2", "salinity", "temperature", "pressure",
+ "total_phosphate", "total_silicate")
+OPTIONAL = ("temperature_out", "pressure_out", "total_ammonia", "total_sulfide")
+RESULTS = ("alkalinity", "dic", "pH_total", "pCO2", "fCO2", "aqueous_CO2",
+ "bicarbonate", "carbonate", "saturation_aragonite", "saturation_calcite",
+ "revelle_factor")
+UNCERTAINTY_RESULTS = ("pH_total", "pCO2", "saturation_aragonite")
+# Published calibration ranges from the PyCO2SYS v1 argument documentation.
+RANGES = {10: (2, 35, 19, 43), 15: (0, 45, 0, 45)}
+SETTINGS = {"opt_k_bisulfate": 1, "opt_k_fluoride": 1, "opt_gas_constant": 3,
+ "opt_buffers_mode": 1, "opt_pressured_kCO2": 0,
+ "pressure_atmosphere": 1.0, "pressure_atmosphere_out": 1.0}
+
+
+def read_samples(path: Path):
+ """Reject ambiguous schemas and invalid numbers before any computation."""
+ raw = path.read_bytes()
+ reader = csv.DictReader(io.StringIO(raw.decode("utf-8-sig")))
+ fields = reader.fieldnames or []
+ if len(fields) != len(set(fields)):
+ raise ValueError("Duplicate CSV column names")
+ missing = {"sample_id", *REQUIRED} - set(fields)
+ if missing:
+ raise ValueError(f"Missing required columns: {sorted(missing)}")
+ allowed = {"sample_id", *REQUIRED, *OPTIONAL}
+ allowed.update("u_" + key for key in (*REQUIRED, *OPTIONAL))
+ unknown = set(fields) - allowed
+ if unknown:
+ raise ValueError(f"Unknown columns: {sorted(unknown)}; use the documented schema")
+ if ("temperature_out" in fields) != ("pressure_out" in fields):
+ raise ValueError("Provide both temperature_out and pressure_out, or neither")
+ for key in fields:
+ if key.startswith("u_") and key[2:] not in fields:
+ raise ValueError(f"{key} requires the corresponding {key[2:]} column")
+ rows, seen = [], set()
+ for line, row in enumerate(reader, 2):
+ if None in row or any(value is None for value in row.values()):
+ raise ValueError(f"Row {line}: wrong number of fields")
+ identifier = row["sample_id"].strip()
+ if not identifier or identifier in seen:
+ raise ValueError(f"Row {line}: empty or duplicate sample_id {identifier!r}")
+ seen.add(identifier)
+ parsed = {"sample_id": identifier}
+ for key, value in row.items():
+ if key == "sample_id":
+ continue
+ try:
+ number = float(value)
+ except ValueError as exc:
+ raise ValueError(f"Row {line}: {key} must be numeric, got {value!r}") from exc
+ if not math.isfinite(number):
+ raise ValueError(f"Row {line}: {key} must be finite")
+ nonnegative = (key.startswith(("u_", "total_", "pressure")) or key == "salinity")
+ if nonnegative and number < 0:
+ raise ValueError(f"Row {line}: {key} must be nonnegative")
+ if key.startswith("temperature") and number <= -273.15:
+ raise ValueError(f"Row {line}: {key} must exceed absolute zero")
+ parsed[key] = number
+ rows.append(parsed)
+ if not rows:
+ raise ValueError("CSV contains no samples")
+ return rows, fields, hashlib.sha256(raw).hexdigest()
+
+
+def solve(path: Path, output_dir: Path, *, par1_type: str, par2_type: str,
+ k_carbonic: int, ph_scale: str | None = None, total_borate: int = 1):
+ """Write results only after all rows produce finite, carbon-balanced solutions."""
+ if output_dir.exists():
+ raise FileExistsError(f"Output directory already exists: {output_dir}")
+ if par1_type not in TYPES or par2_type not in TYPES:
+ raise ValueError("Unsupported carbonate parameter type")
+ if par1_type == par2_type or {par1_type, par2_type} == {"pco2", "fco2"}:
+ raise ValueError("Provide two independent carbonate parameters")
+ if "ph" in (par1_type, par2_type) and ph_scale is None:
+ raise ValueError("pH input requires an explicit --ph-scale")
+ if ph_scale is not None and ph_scale not in SCALES:
+ raise ValueError("Unsupported pH scale")
+ if k_carbonic not in RANGES or total_borate not in (1, 2):
+ raise ValueError("Unsupported equilibrium-constant or total-borate option")
+ rows, fields, digest = read_samples(path)
+ for row in rows:
+ for key, kind in (("par1", par1_type), ("par2", par2_type)):
+ value = row[key]
+ if kind in ("dic", "pco2", "fco2") and value <= 0:
+ raise ValueError(f"{row['sample_id']}: {kind} must be positive")
+ if kind == "ph" and not 0 < value < 14:
+ raise ValueError(f"{row['sample_id']}: helper supports only 0 < pH < 14")
+
+ import numpy as np
+ import PyCO2SYS as pyco2
+
+ if pyco2.__version__ != "1.8.3.4":
+ raise ValueError("This helper targets PyCO2SYS==1.8.3.4; use the pinned environment")
+ settings = {**SETTINGS, "opt_k_carbonic": k_carbonic,
+ "opt_total_borate": total_borate, "opt_pH_scale": SCALES[ph_scale or "total"],
+ "par1_type": TYPES[par1_type], "par2_type": TYPES[par2_type]}
+ numeric_fields = [key for key in fields if key != "sample_id" and not key.startswith("u_")]
+ kwargs = {key: np.array([row[key] for row in rows]) for key in numeric_fields}
+ # Explicitly record the two optional zero assumptions, not library defaults.
+ for key in ("total_ammonia", "total_sulfide"):
+ kwargs.setdefault(key, np.zeros(len(rows)))
+ uncertainties = {key[2:]: np.array([row[key] for row in rows])
+ for key in fields if key.startswith("u_")}
+ has_output = "temperature_out" in fields
+ result_keys = list(RESULTS)
+ uncertainty_keys = list(UNCERTAINTY_RESULTS)
+ if has_output:
+ result_keys.extend(key + "_out" for key in RESULTS if key not in ("alkalinity", "dic"))
+ uncertainty_keys.extend(key + "_out" for key in UNCERTAINTY_RESULTS)
+ uncertainty_options = ({"uncertainty_from": uncertainties, "uncertainty_into": uncertainty_keys}
+ if uncertainties else {})
+ calculated = pyco2.sys(**kwargs, **settings, **uncertainty_options)
+ if uncertainties:
+ result_keys.extend("u_" + key for key in uncertainty_keys)
+ arrays = {key: np.broadcast_to(np.asarray(calculated[key], dtype=float), (len(rows),))
+ for key in result_keys}
+ for key, values in arrays.items():
+ if not np.all(np.isfinite(values)):
+ bad = [rows[i]["sample_id"] for i in np.flatnonzero(~np.isfinite(values))]
+ raise ValueError(f"Non-finite result {key} for {bad}; inspect the input pair and conditions")
+ for suffix in ("", "_out") if has_output else ("",):
+ components = sum(arrays[key + suffix] for key in ("aqueous_CO2", "bicarbonate", "carbonate"))
+ if not np.allclose(components, arrays["dic"], rtol=1e-8, atol=1e-6):
+ raise ValueError("Dissolved inorganic carbon mass balance failed")
+ if np.any(arrays["dic"] <= 0) or any(
+ np.any(arrays[key + suffix] < 0)
+ for key in ("aqueous_CO2", "bicarbonate", "carbonate")
+ ):
+ raise ValueError("Solution has nonphysical carbon concentrations")
+
+ warnings = []
+ tmin, tmax, smin, smax = RANGES[k_carbonic]
+ result_rows = []
+ for index, row in enumerate(rows):
+ flags = []
+ for suffix in ("", "_out") if has_output else ("",):
+ if not (tmin < row["temperature" + suffix] < tmax and smin < row["salinity"] < smax):
+ label = "output" if suffix else "input"
+ flags.append(f"outside_k_carbonic_{label}_range")
+ if flags:
+ warnings.append({"sample_id": row["sample_id"], "flags": flags})
+ result_rows.append({"sample_id": row["sample_id"],
+ **{"input_" + key: row[key] for key in fields if key != "sample_id"},
+ **{key: float(values[index]) for key, values in arrays.items()},
+ "qc_flags": ";".join(flags)})
+ assumptions = [f"{key}=0 micromol/kg seawater" for key in ("total_ammonia", "total_sulfide")
+ if key not in fields]
+ manifest = {
+ "schema_version": "1.0", "skill_version": "1.0",
+ "software": {"PyCO2SYS": pyco2.__version__, "numpy": np.__version__,
+ "python": platform.python_version()},
+ "input_file": path.name, "input_sha256": digest, "sample_count": len(rows),
+ "parameter_types": {"par1": par1_type, "par2": par2_type}, "settings": settings,
+ "output_conditions": "provided per row" if has_output else "input conditions only",
+ "units": {"carbon_and_nutrients": "micromol/kg seawater", "pCO2_and_fCO2": "microatm",
+ "temperature": "degrees Celsius", "pressure": "dbar, sea pressure",
+ "salinity": "Practical Salinity, dimensionless", "pH_total": "total scale",
+ "saturation_and_revelle": "dimensionless",
+ "uncertainties": "absolute 1-sigma, in the corresponding parameter units"},
+ "uncertainty_sources": sorted(uncertainties),
+ "uncertainty_scope": ("Independent input uncertainties only; unspecified inputs and "
+ "equilibrium constants treated as exact; no covariance or model error."),
+ "assumptions": assumptions, "warnings": warnings,
+ }
+ output_dir.mkdir(parents=True, exist_ok=False)
+ with (output_dir / "carbonate.csv").open("w", newline="", encoding="utf-8") as handle:
+ writer = csv.DictWriter(handle, fieldnames=list(result_rows[0]))
+ writer.writeheader()
+ writer.writerows(result_rows)
+ (output_dir / "provenance.json").write_text(json.dumps(manifest, indent=2, allow_nan=False) + "\n")
+ return manifest
+
+
+def main():
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("input_csv", type=Path)
+ parser.add_argument("--output-dir", type=Path, required=True, help="New directory for CSV and provenance")
+ parser.add_argument("--par1-type", choices=TYPES, required=True)
+ parser.add_argument("--par2-type", choices=TYPES, required=True)
+ parser.add_argument("--ph-scale", choices=SCALES, help="Required when either input is pH")
+ parser.add_argument("--k-carbonic", type=int, choices=RANGES, required=True,
+ help="10: Lueker et al. 2000; 15: Waters et al. 2014")
+ parser.add_argument("--total-borate", type=int, choices=(1, 2), default=1,
+ help="1: Uppstrom 1974 (default); 2: Lee et al. 2010")
+ args = parser.parse_args()
+ try:
+ manifest = solve(args.input_csv, args.output_dir, par1_type=args.par1_type,
+ par2_type=args.par2_type, ph_scale=args.ph_scale,
+ k_carbonic=args.k_carbonic, total_borate=args.total_borate)
+ except (ValueError, OSError, UnicodeError) as exc:
+ parser.exit(2, f"error: {exc}\n")
+ print(f"Solved {manifest['sample_count']} samples; {len(manifest['warnings'])} with range flags.")
+ for entry in manifest["warnings"]:
+ print(f"WARNING {entry['sample_id']}: {', '.join(entry['flags'])}")
+ print(f"Results: {args.output_dir / 'carbonate.csv'}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/marine-carbonate-chemistry/test_scripts.py b/tests/marine-carbonate-chemistry/test_scripts.py
new file mode 100644
index 00000000..c33b6a85
--- /dev/null
+++ b/tests/marine-carbonate-chemistry/test_scripts.py
@@ -0,0 +1,256 @@
+"""Numerical invariants and input-boundary checks for marine carbonate chemistry."""
+
+from __future__ import annotations
+
+import csv
+import hashlib
+import itertools
+import json
+from pathlib import Path
+import re
+import subprocess
+import sys
+
+import pytest
+import skill_contract
+
+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "marine-carbonate-chemistry"
+sys.path.insert(0, str(SKILL_ROOT / "scripts"))
+import solve_carbonate as solver
+
+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)
+pyco2 = pytest.importorskip("PyCO2SYS")
+np = pytest.importorskip("numpy")
+
+BASE = {"sample_id": "reference", "par1": 2300, "par2": 2000, "salinity": 35,
+ "temperature": 25, "pressure": 0, "total_phosphate": 0, "total_silicate": 0}
+
+
+def write_csv(tmp_path, rows):
+ path = tmp_path / "samples.csv"
+ with path.open("w", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=list(rows[0]))
+ writer.writeheader()
+ writer.writerows(rows)
+ return path
+
+
+def run(tmp_path, rows=None, **options):
+ path = write_csv(tmp_path, rows or [BASE])
+ output = tmp_path / "output"
+ settings = dict(par1_type="alkalinity", par2_type="dic", k_carbonic=10)
+ settings.update(options)
+ manifest = solver.solve(path, output, **settings)
+ with (output / "carbonate.csv").open() as handle:
+ result = list(csv.DictReader(handle))
+ return manifest, result
+
+
+def direct(**kwargs):
+ settings = dict(par1=2300, par2=2000, par1_type=1, par2_type=2, salinity=35,
+ temperature=25, pressure=0, total_phosphate=0, total_silicate=0,
+ opt_k_carbonic=10, opt_total_borate=1, opt_pH_scale=1, **solver.SETTINGS)
+ settings.update(kwargs)
+ return pyco2.sys(**settings)
+
+
+def test_pinned_regression_and_carbon_species_balance(tmp_path):
+ _, rows = run(tmp_path)
+ row = rows[0]
+ # Fixed regression values from PyCO2SYS 1.8.3.4, not independent reference chemistry.
+ assert float(row["pH_total"]) == pytest.approx(8.045886180900592, abs=1e-9)
+ assert float(row["pCO2"]) == pytest.approx(396.9581630249643, rel=1e-9)
+ assert float(row["saturation_aragonite"]) == pytest.approx(3.3862008130878753, rel=1e-9)
+ assert sum(float(row[key]) for key in ("aqueous_CO2", "bicarbonate", "carbonate")) == pytest.approx(2000)
+ assert "pH_total_out" not in row
+ assert row["qc_flags"] == ""
+
+
+PAIRS = [pair for pair in itertools.combinations(solver.TYPES, 2)
+ if set(pair) != {"pco2", "fco2"}]
+
+
[email protected]("pair", PAIRS)
+def test_every_supported_independent_pair_recovers_same_system(tmp_path, pair):
+ reference = direct(total_phosphate=2, total_silicate=15)
+ keys = {"alkalinity": "alkalinity", "dic": "dic", "ph": "pH_total", "pco2": "pCO2", "fco2": "fCO2"}
+ row = {**BASE, "par1": float(reference[keys[pair[0]]]), "par2": float(reference[keys[pair[1]]]),
+ "total_phosphate": 2, "total_silicate": 15}
+ _, results = run(tmp_path, [row], par1_type=pair[0], par2_type=pair[1], ph_scale="total")
+ assert float(results[0]["alkalinity"]) == pytest.approx(2300, rel=1e-8)
+ assert float(results[0]["dic"]) == pytest.approx(2000, rel=1e-8)
+ assert float(results[0]["pH_total"]) == pytest.approx(float(reference["pH_total"]), abs=1e-8)
+
+
[email protected]("scale,key", [("total", "pH_total"), ("seawater", "pH_sws"),
+ ("free", "pH_free"), ("nbs", "pH_nbs")])
+def test_declared_ph_scales_yield_same_dic(tmp_path, scale, key):
+ reference = direct()
+ _, rows = run(tmp_path, [{**BASE, "par2": float(reference[key])}], par2_type="ph", ph_scale=scale)
+ assert float(rows[0]["dic"]) == pytest.approx(2000, rel=1e-8)
+ assert float(rows[0]["pH_total"]) == pytest.approx(float(reference["pH_total"]), abs=1e-8)
+
+
+def test_output_conditions_match_independent_closed_system_solution(tmp_path):
+ _, rows = run(tmp_path, [{**BASE, "temperature_out": 10, "pressure_out": 1000}])
+ reference = direct(temperature=10, pressure=1000)
+ for key in ("pH_total", "pCO2", "saturation_aragonite", "revelle_factor"):
+ assert float(rows[0][key + "_out"]) == pytest.approx(float(reference[key]), rel=1e-9)
+ assert sum(float(rows[0][key + "_out"]) for key in ("aqueous_CO2", "bicarbonate", "carbonate")) == pytest.approx(2000)
+
+
+def test_added_dic_lowers_ph_and_saturation_at_fixed_alkalinity(tmp_path):
+ _, rows = run(tmp_path, [BASE, {**BASE, "sample_id": "added", "par2": 2100}])
+ first, second = rows
+ assert float(second["pH_total"]) < float(first["pH_total"])
+ assert float(second["saturation_aragonite"]) < float(first["saturation_aragonite"])
+ assert float(second["pCO2"]) > float(first["pCO2"])
+ assert float(second["dic"]) == pytest.approx(2100)
+
+
+def test_input_uncertainties_agree_with_central_difference_quadrature(tmp_path):
+ row = {**BASE, "u_par1": 2, "u_par2": 2, "temperature_out": 10, "pressure_out": 1000}
+ manifest, rows = run(tmp_path, [row])
+ for suffix in ("", "_out"):
+ for key in solver.UNCERTAINTY_RESULTS:
+ terms = []
+ for parameter, center in (("par1", 2300), ("par2", 2000)):
+ plus = direct(**{parameter: center + 0.01}, temperature_out=10, pressure_out=1000)
+ minus = direct(**{parameter: center - 0.01}, temperature_out=10, pressure_out=1000)
+ derivative = float(plus[key + suffix] - minus[key + suffix]) / 0.02
+ terms.append((derivative * 2) ** 2)
+ assert float(rows[0]["u_" + key + suffix]) == pytest.approx(sum(terms) ** 0.5, rel=0.002)
+ assert manifest["uncertainty_sources"] == ["par1", "par2"]
+
+
+def test_nonzero_nutrients_are_used(tmp_path):
+ _, rows = run(tmp_path, [BASE, {**BASE, "sample_id": "nutrients", "total_phosphate": 3,
+ "total_silicate": 50}])
+ assert float(rows[1]["pH_total"]) < float(rows[0]["pH_total"])
+
+
+def test_nutrient_and_borate_settings_change_the_solution(tmp_path):
+ row = {**BASE, "total_phosphate": 3, "total_silicate": 50, "total_ammonia": 2, "total_sulfide": 1}
+ manifest, rows = run(tmp_path, [row], k_carbonic=15, total_borate=2)
+ expected = direct(total_phosphate=3, total_silicate=50, total_ammonia=2, total_sulfide=1,
+ opt_k_carbonic=15, opt_total_borate=2)
+ assert float(rows[0]["pH_total"]) == pytest.approx(float(expected["pH_total"]))
+ assert float(rows[0]["pH_total"]) != pytest.approx(float(direct()["pH_total"]))
+ assert manifest["assumptions"] == []
+ assert manifest["settings"]["opt_total_borate"] == 2
+
+
+def test_range_flags_cover_input_and_output_conditions(tmp_path):
+ manifest, rows = run(tmp_path, [{**BASE, "salinity": 15, "temperature_out": 1, "pressure_out": 1000}])
+ assert rows[0]["qc_flags"] == "outside_k_carbonic_input_range;outside_k_carbonic_output_range"
+ assert manifest["warnings"][0]["sample_id"] == "reference"
+
+
+def test_only_output_range_is_flagged(tmp_path):
+ _, rows = run(tmp_path, [{**BASE, "temperature_out": 1, "pressure_out": 1000}])
+ assert rows[0]["qc_flags"] == "outside_k_carbonic_output_range"
+
+
[email protected]("change,match", [
+ ({"par1": "NaN"}, "finite"), ({"par2": "inf"}, "finite"),
+ ({"par1": ""}, "numeric"), ({"salinity": -1}, "nonnegative"),
+ ({"pressure": -1}, "nonnegative"), ({"total_phosphate": -1}, "nonnegative"),
+ ({"temperature": -274}, "absolute zero"), ({"u_par1": -1}, "nonnegative"),
+ ({"par2": 0}, "positive"), ({"temperature_out": 10}, "both"),
+ ({"u_pressure_out": 1}, "corresponding"), ({"phosphate": 1}, "Unknown"),
+])
+def test_bad_inputs_fail_before_creating_outputs(tmp_path, change, match):
+ with pytest.raises(ValueError, match=match):
+ run(tmp_path, [{**BASE, **change}])
+ assert not (tmp_path / "output").exists()
+
+
[email protected]("options,match", [
+ ({"par2_type": "alkalinity"}, "independent"),
+ ({"par1_type": "pco2", "par2_type": "fco2"}, "independent"),
+ ({"par2_type": "ph"}, "explicit"), ({"k_carbonic": 8}, "Unsupported"),
+])
+def test_ambiguous_or_unsupported_configuration_fails(tmp_path, options, match):
+ with pytest.raises(ValueError, match=match):
+ run(tmp_path, **options)
+
+
[email protected]("identifier", ["reference", " reference ", ""])
+def test_sample_identity_is_preserved(tmp_path, identifier):
+ with pytest.raises(ValueError, match="sample_id"):
+ run(tmp_path, [BASE, {**BASE, "sample_id": identifier}])
+
+
[email protected]("kind", ["duplicate", "short", "long", "empty", "missing"])
+def test_malformed_csv(tmp_path, kind):
+ path = write_csv(tmp_path, [BASE])
+ lines = path.read_text().splitlines()
+ if kind == "duplicate":
+ lines[0] += ",par1"
+ lines[1] += ",2300"
+ elif kind == "short":
+ lines[1] = lines[1].rsplit(",", 1)[0]
+ elif kind == "long":
+ lines[1] += ",1"
+ elif kind == "empty":
+ lines = lines[:1]
+ else:
+ lines[0] = lines[0].replace("salinity", "salinitty")
+ path.write_text("\n".join(lines) + "\n")
+ with pytest.raises(ValueError):
+ solver.read_samples(path)
+
+
+def test_provenance_hash_and_no_clobber(tmp_path):
+ manifest, _ = run(tmp_path)
+ assert manifest == json.loads((tmp_path / "output/provenance.json").read_text())
+ assert manifest["input_sha256"] == hashlib.sha256((tmp_path / "samples.csv").read_bytes()).hexdigest()
+ assert manifest["software"]["PyCO2SYS"] == "1.8.3.4"
+ original = (tmp_path / "output/carbonate.csv").read_bytes()
+ with pytest.raises(FileExistsError):
+ run(tmp_path)
+ assert (tmp_path / "output/carbonate.csv").read_bytes() == original
+
+
[email protected]("mode,match", [("nan", "Non-finite"), ("balance", "mass balance")])
+def test_invalid_solver_output_is_not_published(tmp_path, monkeypatch, mode, match):
+ real_sys = pyco2.sys
+
+ def broken_sys(**kwargs):
+ result = real_sys(**kwargs)
+ if mode == "nan":
+ result["pH_total"] = np.nan
+ else:
+ result["carbonate"] = result["carbonate"] + 50
+ return result
+
+ monkeypatch.setattr(pyco2, "sys", broken_sys)
+ with pytest.raises(ValueError, match=match):
+ run(tmp_path)
+ assert not (tmp_path / "output").exists()
+
+
+def test_different_library_version_requires_revalidation(tmp_path, monkeypatch):
+ monkeypatch.setattr(pyco2, "__version__", "2.0.0")
+ with pytest.raises(ValueError, match="pinned environment"):
+ run(tmp_path)
+ assert not (tmp_path / "output").exists()
+
+
+def test_documented_csv_and_cli(tmp_path):
+ text = (SKILL_ROOT / "SKILL.md").read_text()
+ example = re.search(r"```csv\n(.*?)\n```", text, re.S).group(1)
+ path = tmp_path / "samples.csv"
+ path.write_text(example + "\n")
+ result = subprocess.run(
+ [sys.executable, str(SKILL_ROOT / "scripts/solve_carbonate.py"), str(path),
+ "--par1-type", "alkalinity", "--par2-type", "dic", "--k-carbonic", "10",
+ "--output-dir", str(tmp_path / "cli-results")],
+ capture_output=True, text=True, timeout=60,
+ )
+ assert result.returncode == 0, result.stderr
+ assert "Solved 2 samples; 0 with range flags" in result.stdout
+ with (tmp_path / "cli-results/carbonate.csv").open() as handle:
+ rows = list(csv.DictReader(handle))
+ assert float(rows[0]["pH_total_out"]) == pytest.approx(8.241241, abs=5e-7)
+ assert float(rows[0]["u_pH_total"]) == pytest.approx(0.004580, abs=5e-7)
diff --git a/tests/skill-requirements.toml b/tests/skill-requirements.toml
index 956d9c9e..59d2603d 100644
--- a/tests/skill-requirements.toml
+++ b/tests/skill-requirements.toml
@@ -722,6 +722,12 @@ packages = ["build123d", "matplotlib"]
# syntax-checked with node when it is on PATH.
packages = []
+# --- chemical oceanography ------------------------------------------------
+
+[skills.marine-carbonate-chemistry]
+python = "3.13"
+packages = ["PyCO2SYS==1.8.3.4", "numpy==2.5.1"]
+
# --- geospatial -----------------------------------------------------------
[skills.geopandas]