Generated banner for Marine Carbonate Chemistry
Generated logo for Marine Carbonate Chemistry

Marine Carbonate Chemistry

K-DenseCommunityCreated by K-Dense Inc.

  • Skill
  • Tool integration
  • Science and research
  • MIT
  • Low risk
  • Has scripts

From the author

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.
— the description by K-Dense Inc.

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured workflow for chemical oceanography and carbon-cycle research. It uses the PyCO2SYS library to convert paired seawater carbonate measurements into a comprehensive speciation table. The tool handles calculations for total alkalinity, DIC, pH, and pCO2/fCO2, while providing corrections for temperature and pressure, as well as uncertainty propagation. It is designed for researchers needing reproducible carbonate system analysis from bottle samples or shipboard measurements, ensuring that all assumptions and calculation parameters are documented in a provenance record.

What it does

  • Calculates carbonate speciation, mineral saturation states, and Revelle factors.
  • Performs temperature and pressure corrections for closed-sample carbonate systems.
  • Propagates measurement uncertainties to calculated parameters.
  • Validates input data against chemical constant ranges.
  • Generates a structured CSV result table and a JSON provenance file.
  • Supports multiple carbonic-acid constant parameterizations.

When to use it

  • When analyzing shipboard or laboratory seawater carbonate measurements.
  • To convert carbonate system parameters from laboratory conditions to in-situ ocean conditions.
  • When quantifying the impact of measurement uncertainty on carbonate system results.
  • To ensure reproducible and documented carbonate chemistry calculations for research publications.

Advantages

  • Provides a standardized, reproducible workflow for complex chemical calculations.
  • Includes automated flagging for data points outside validated constant ranges.
  • Maintains a detailed provenance record for every calculation run.
  • Supports rigorous uncertainty propagation for independent input errors.

Usage examples

“Solve the carbonate system for a set of samples with alkalinity and DIC measurements at 25C, correcting to 10C and 1000 dbar.”
The script processes the input CSV, applies the requested temperature and pressure corrections, and outputs a carbonate.csv file with the calculated speciation and a provenance.json file.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/k-dense-ai/marine-carbonate-chemistry/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip marine-carbonate-chemistry.zip -d .agents/skills

Documentation by K-Dense Inc.

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.3. As reviewed on 2026-10-01, this remains the stable PyPI release. The v2 documentation is for a beta with breaking changes; use the v1 documentation for 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.

QuantityRequired convention
Total alkalinity (TA), DIC, nutrientsmicromol per kg seawater, not per litre or kg water
SalinityPractical Salinity, not Absolute Salinity in g/kg
TemperatureIn-situ/measurement temperature in degrees Celsius, not potential or Conservative Temperature
PressureSea pressure in dbar; surface sample is 0, not 1 atmosphere
pHDeclared total, seawater, free, or NBS scale, at the declared measurement conditions
pCO2 / fCO2Seawater 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:

uv venv --python 3.13 .venv
uv pip install --python .venv/bin/python "PyCO2SYS==1.8.3.4" "numpy==2.5.3"

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. 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 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 calibration-range and gas-pressure 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. Gas results retain the helper's uncorrected hydrostatic gas convention (see below). 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.

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:

.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. Both rows carry gas_pressure_correction_disabled_output: the output pH and mineral saturation include pressure effects, but the reported pCO2/fCO2 do not include the hydrostatic corrections to CO2 solubility and fugacity. Do not compare those gas values directly with a pressure-corrected subsurface sensor measurement.

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

Repository tests exercise the pinned solver, independent-pair round trips, carbon balance, pH-scale equivalence, condition correction, Revelle-factor derivatives, gas-pressure conventions, uncertainty quadrature, CSV errors, and the worked example. The helper calls the local pyco2.sys Python API; it has no HTTP endpoints or authentication. Tests establish software behavior, not independent field-data validation; upstream's validation page also contains historical examples, including a removed pyco2.test interface.

Files

scripts/solve_carbonate.py

#!/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 ("",):
            label = "output" if suffix else "input"
            if not (tmin < row["temperature" + suffix] < tmax and smin < row["salinity"] < smax):
                flags.append(f"outside_k_carbonic_{label}_range")
            if row["pressure" + suffix] > 0:
                flags.append(f"gas_pressure_correction_disabled_{label}")
        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.1",
        "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",
        "gas_pressure_convention": (
            "CO2 solubility and fugacity use 1 atm atmospheric pressure without hydrostatic "
            "gas corrections (opt_pressured_kCO2=0). Other pressure-dependent equilibria "
            "still use the supplied sea pressure; nonzero-pressure pCO2/fCO2 must not be "
            "interpreted as fully pressure-corrected in situ gas values."),
        "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 QC 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()

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Python

The author says: 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.

Security

What our scanner noticed· Low risk

  • Instructions that use the network
  • Scripts that your agent may run

This skill includes scripts that your agent may run. Read them before you use it.

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
K-Dense Inc.
Publisher
K-Dense (Community)
Source
K-Dense-AI/scientific-agent-skills · skills/marine-carbonate-chemistry · commit a25cf9e
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download marine-carbonate-chemistry.zip