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.
Python agent-skillsai-scientistbioinformaticschemoinformaticsclaudeclaude-skillsclaudecodeclinical-researchcomputational-biologydata-analysisdrug-discoverygenomicsmaterials-sciencemetabolomicsproteomicsscientific-computingscientific-visualization
Added nmrglue, cellprofiler, mageck, qiime2-amplicon, nwb-conversion, pybamm, tellurium, cantera, pycalphad, relion
Timothy Kassis9c044a12ea21
diff --git a/README.md b/README.mdindex 6ba37aca..50bb113f 100644--- a/README.md+++ b/README.md@@ -3,7 +3,7 @@[](LICENSE.md)[](https://arxiv.org/abs/2609.00065)[](pyproject.toml)-[](#-whats-included)+[](#-whats-included)[](#-whats-included)[](https://agentskills.io/)[](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 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)+> **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 181 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 **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.+A comprehensive collection of **181 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.@@ -75,7 +75,7 @@ Recorded walkthroughs of these skills on real research tasks, from the [K-Dense## 📦 What's Included-This repository provides **171 scientific and research skills** organized into the following categories:+This repository provides **181 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@@ -122,7 +122,7 @@ Each skill includes:- **Multi-Step Workflows** - Execute complex pipelines with a single prompt### 🎯 **Comprehensive Coverage**-- **171 Skills** - Extensive coverage across all major scientific domains+- **181 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)@@ -229,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 171 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 181 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.@@ -470,13 +470,13 @@ networks, and search GEO for similar patterns.## 📚 Available Skills-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.+This repository contains **181 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> **Note:** The Python package and integration skills listed below are *explicitly defined* skills — curated with documentation, examples, and best practices for stronger, more reliable performance. They are not a ceiling: the agent can install and use *any* Python package or call *any* API, even without a dedicated skill. The skills listed simply make common workflows faster and more dependable.-#### 🧬 **Bioinformatics & Genomics** (30 skills)+#### 🧬 **Bioinformatics & Genomics** (32 skills)- RNA-seq pipelines: Bulk RNA-seq (end-to-end FASTQ -> counts -> DE -> enrichment orchestrator)- Sequence analysis: BioPython, pysam, scikit-bio, BioServices- PCR assay design: [Primer Design](skills/primer-design/SKILL.md) (Primer3 candidates, thermodynamics, variant masking, tails, and bounded local or BLAST-assisted specificity screening)@@ -487,12 +487,15 @@ This repository contains **171 scientific and research skills** organized across- Population and sequence intelligence: OneKGPd (individual-level 1000 Genomes cohort queries) and Genomic Intelligence (hosted regulatory/gene-expression predictions; research only)- Variant effect prediction: AlphaGenome (DeepMind's AlphaGenome Atlas of precomputed effects for every GRCh38 SNV — AVI score with Phred rank and 18 SHAP feature attributions, plus raw and quantile scores across 9,440 RNA-seq, DNase, ATAC, ChIP, CAGE, splicing and contact-map tracks — and on-demand model scoring, in silico mutagenesis and REF-vs-ALT track prediction for human and mouse; research only, not clinical)- Differential expression: PyDESeq2+- Pooled CRISPR screens: [MAGeCK](skills/mageck/SKILL.md) (guide counting, replicate QC, explicit contrasts, and gene hit ranking)+- Amplicon microbiomes: [QIIME 2 Amplicon](skills/qiime2-amplicon/SKILL.md) (paired-end 16S import, primer trimming, denoising, taxonomy, and read-retention checks)- Functional enrichment: Pathway Enrichment (ORA, GSEA/preranked, ssGSEA via gseapy + g:Profiler; GO, KEGG, Reactome, WikiPathways, MSigDB)- Phylogenetics: ETE Toolkit, Phylogenetics (MAFFT, IQ-TREE 2, FastTree)- Microbiome foundation models: Waypoint (Outpost Bio's open Waypoint-6m/45m/170m checkpoints, the Atlas 539k-sample MGnify pretraining corpus, and the eight-task Compass benchmark — embedding, fine-tuning, benchmarking, and pretraining on taxonomic abundance profiles, with MetaPhlAn/Kraken2/QIIME 2 conversion)-#### 🧪 **Cheminformatics & Drug Discovery** (10 skills)+#### 🧪 **Cheminformatics & Drug Discovery** (11 skills)- Molecular manipulation: RDKit, Datamol, Molfeat+- NMR processing: [nmrglue](skills/nmrglue/SKILL.md) (calibrated 1D FIDs, phase/baseline correction, peak candidates, and signed integration)- Deep learning: DeepChem, TorchDrug- Docking & screening: DiffDock- Molecular dynamics: OpenMM + MDAnalysis (MD simulation & trajectory analysis)@@ -515,14 +518,16 @@ This repository contains **171 scientific and research skills** organized across#### 🐭 **Preclinical Research & Animal Welfare** (1 skill)- Severity assessment: RELSA Severity Assessment (multivariate RELSA scores from body weight, temperature, clinical/nesting scores, biomarkers, activity, heart rate, burrowing and wheel running; ARIMA humane-endpoint forecasting with 95% prediction intervals; KDE-derived attention and danger zones for 3Rs/refinement and EU Directive 2010/63/EU severity reporting) — an aid to severity assessment, never a decision rule-#### 🖼️ **Medical Imaging & Digital Pathology** (4 skills)+#### 🖼️ **Microscopy, Medical Imaging & Digital Pathology** (5 skills)- DICOM processing: pydicom 3.0.2 with privacy-first local preflight and no diagnostic or de-identification-compliance claims- Whole slide imaging: histolab and research-only PathML 3.0.5+- Quantitative microscopy: [CellProfiler](skills/cellprofiler/SKILL.md) (reusable nuclei-measurement pipeline, channel manifests, segmentation overlays, and measurement checks)- Virtual spatial transcriptomics: noncommercial DeepSpot-M for transcriptome-wide spatial gene expression from 224x224 H&E tiles-#### 🧠 **Neuroscience & Electrophysiology** (3 skills)+#### 🧠 **Neuroscience & Electrophysiology** (4 skills)- Data standards: BIDS (Brain Imaging Data Structure for neuroscience and biomedical datasets; pairs with DataLad for retrieval — OpenNeuro at github.com/OpenNeuroDatasets and DANDI at github.com/dandisets publish their holdings as DataLad datasets — and for BIDS-App runs under recorded provenance, with BEP028 the extension proposal for provenance records in derivatives)- Neural recordings: Neuropixels-Analysis (extracellular spikes, silicon probes, spike sorting)+- Data conversion: [NWB Conversion](skills/nwb-conversion/SKILL.md) (two-photon TIFF and behavioral positions, clock alignment, round-trip preservation, and NWB validation)- Physiological signals: NeuroKit2 0.2.13 for reproducible research workflows—not diagnosis, monitoring decisions, or medical-device validation#### 🤖 **Machine Learning & AI** (14 core skills)@@ -535,19 +540,22 @@ This repository contains **171 scientific and research skills** organized across- Dimensionality reduction: UMAP-learn- Statistical modeling: statsmodels-#### 🔮 **Materials Science, Chemistry & Physics** (7 skills)+#### 🔮 **Materials Science, Chemistry & Physics** (8 skills)- Materials: current split pymatgen wrapper/core plus explicitly bounded Materials Project queries+- Alloy thermodynamics: [pycalphad](skills/pycalphad/SKILL.md) (TDB-driven phase equilibria, phase fractions, composition checks, and database provenance)- Metabolic modeling: COBRApy- Astronomy: Astropy- Quantum computing: Cirq, PennyLane, Qiskit, QuTiP 5.3-#### ⚙️ **Engineering & Simulation** (7 skills)+#### ⚙️ **Engineering & Simulation** (9 skills)- Lab hardware CAD: parametric build123d 0.11.1 models for microfluidic chips and molds, optomechanical mounts, microplate and cuvette adapters, and behavior rigs, checked against ANSI/SLAS and optical-table dimensional standards and reviewed with mandatory multi-view renders- Custom-part fabrication: Fictiv (browser-driven CNC, 3D printing, sheet metal, urethane casting and molding quotes, DFM review, lead-time and region tiers, and checkout, with CAD pre-flight checks and an explicit approval gate before any order, quote request or share)- Numerical computing: proprietary MATLAB R2026a and distinct GNU Octave 11.3 planning/review workflows- Computational fluid dynamics: bounded FluidSim 0.9 simulations with numerical-validity and HPC checks- Experimental flow measurement: OpenPIV (velocity fields from PIV image pairs, interrogation-window cross-correlation, spurious-vector validation, vorticity/strain-rate/turbulence statistics)- Discrete-event simulation: SimPy 4.1.2 with replication, warm-up, and output-analysis guidance+- Chemical kinetics: [Cantera](skills/cantera/SKILL.md) (homogeneous ignition delay, mechanism snapshots, numerical refinement, and conservation checks)+- Battery experiments: [PyBaMM](skills/pybamm/SKILL.md) (charge/discharge protocols, parameter provenance, numerical checks, and measured-curve comparisons)- Symbolic math: SymPy#### 🌊 **Chemical Oceanography** (1 skill)@@ -574,13 +582,15 @@ This repository contains **171 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** (4 skills)+#### 🔬 **Multi-omics & Systems Biology** (5 skills)- Pathway analysis: via Database Lookup (KEGG, Reactome, STRING) and PrimeKG- Data management: LaminDB+- Biochemical dynamics: [Tellurium](skills/tellurium/SKILL.md) (kinetic models, time-course simulations, perturbations, and reproducible model exchange)- 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 Engineering & Design** (5 skills)- Protein language models: ESM+- Experimental structure reconstruction: [RELION](skills/relion/SKILL.md) (extracted-particle refinement, optics/STAR validation, and half-map/FSC checks)- Glycoengineering: Glycoengineering (N/O-glycosylation prediction, therapeutic antibody optimization)- Cloud laboratory platform: Adaptyv (automated protein testing and validation)- Cloud structure & design platform: Tamarind (managed-GPU access to AlphaFold, Boltz, Chai, ESMFold, RFdiffusion, ProteinMPNN, BoltzGen, antibody/nanobody design, DiffDock/Vina docking, binding affinity, and MSA generation via REST API or MCP)@@ -932,7 +942,7 @@ If you also need to cite a specific version of the repository itself (for exampltitle = {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 = {171 skills covering databases, packages, integrations, and analysis tools}+ note = {181 skills covering databases, packages, integrations, and analysis tools}}```diff --git a/docs/skills.md b/docs/skills.mdindex ea7f9494..2c99b64a 100644--- a/docs/skills.md+++ b/docs/skills.md@@ -1,10 +1,10 @@# Scientific Skills-This checkout contains **171 skills**. The catalog below groups skills by domain. Summaries mirror each skill's+This checkout contains **181 skills**. The catalog below groups skills by domain. Summaries mirror each skill'scurrent `description`; open its linked `SKILL.md` for setup, tested versions, workflows,and limitations. See [workflow examples](examples.md) for ways to combine them.-**Catalog reviewed:** 2026-09-13.+**Catalog reviewed:** 2026-09-30.## Scientific Databases & Data Access@@ -49,6 +49,9 @@ and limitations. See [workflow examples](examples.md) for ways to combine them.## Scientific Packages### Bioinformatics & Genomics++- **[MAGeCK](../skills/mageck/SKILL.md)** - Analyzes pooled CRISPR screen FASTQ reads and guide-count matrices with MAGeCK, validates guide libraries and contrasts, measures replicate and library QC, and produces gene hit rankings with effect sizes and FDR. Use for new knockout, CRISPRi, or CRISPRa screen analysis, enrichment or depletion contrasts, and MAGeCK count/test workflows; existing public dependency-score lookup belongs to DepMap.+- **[QIIME 2 Amplicon](../skills/qiime2-amplicon/SKILL.md)** - Processes paired-end 16S amplicon reads into QIIME 2 ASVs and taxonomy with retained artifact provenance. Validates paired FASTQ manifests, primer orientation, post-trimming read overlap, sample metadata, classifier compatibility, and per-sample read retention.- **[AlphaGenome](../skills/alphagenome/SKILL.md)** - Look up precomputed AlphaGenome Atlas effects for any GRCh38 single-nucleotide variant (AVI score with Phred and 18 SHAP feature attributions, plus raw and quantile scores for RNA-seq, DNase, ATAC, ChIP-TF, ChIP-histone, CAGE, PRO-cap, splicing, polyadenylation and contact-map tracks), score variants or scan windows on demand with the AlphaGenome model for human and mouse (variant scoring, in silico mutagenesis, REF-versus-ALT track prediction), and build Atlas website deep links. Use when the user mentions AlphaGenome, AlphaGenome Atlas, AVI or AlphaGenome Variant Impact, DeepMind variant effect prediction, or wants to prioritise or mechanistically interpret non-coding, regulatory, splicing, enhancer, promoter, or chromatin-accessibility effects of SNVs from a VCF, credible set, or region. Research use only; not a clinical tool.- **[AnnData](../skills/anndata/SKILL.md)** - Data structure for annotated matrices in single-cell analysis. Use when working with .h5ad files or integrating with the scverse ecosystem. This is the data format skill—for analysis workflows use scanpy; for probabilistic models use scvi-tools; for population-scale queries use cellxgene-census.- **[Arboreto](../skills/arboreto/SKILL.md)** - Infer gene regulatory networks (GRNs) from gene expression data using scalable algorithms (GRNBoost2, GENIE3). Use when analyzing transcriptomics data (bulk RNA-seq, single-cell RNA-seq) to identify transcription factor-target gene relationships and regulatory interactions. Supports distributed computation for large-scale datasets.@@ -84,6 +87,8 @@ and limitations. See [workflow examples](examples.md) for ways to combine them.- **[Optimize for GPU](../skills/optimize-for-gpu/SKILL.md)** - GPU-accelerates scientific Python on NVIDIA hardware and verifies that the result is correct and faster. Use for CUDA/GPU optimization; CPU-bound NumPy, SciPy, pandas, scikit-learn, NetworkX, scikit-image, vector-search, image-processing, graph, simulation, or file-I/O workloads; CuPy, cuDF, cuML, cuGraph, cuVS, cuCIM, KvikIO, Warp, Newton, Numba-CUDA, or RAFT questions; and profiling, memory-transfer, kernel, or multi-GPU bottlenecks. Also use when large data-parallel Python code is slow and GPU acceleration is a plausible option, even if the user does not name CUDA.### Cheminformatics & Drug Discovery++- **[nmrglue](../skills/nmrglue/SKILL.md)** - Processes calibrated one-dimensional complex NMR free-induction decays with nmrglue into phased spectra, peak candidates, and signed integration regions. Use for raw 1D NMR processing, ppm-axis verification, apodization, Fourier transformation, manual phasing, baseline correction, or reproducible spectral integration.- **[Datamol](../skills/datamol/SKILL.md)** - Pythonic wrapper around RDKit with simplified interface and sensible defaults. Preferred for standard drug discovery including SMILES parsing, standardization, descriptors, fingerprints, clustering, 3D conformers, parallel processing. Returns native rdkit.Chem.Mol objects. For advanced control or custom parameters, use rdkit directly.- **[DeepChem](../skills/deepchem/SKILL.md)** - Molecular ML with diverse featurizers and pre-built datasets. Use for property prediction (ADMET, toxicity) with traditional ML or GNNs when you want extensive featurization options and MoleculeNet benchmarks. Best for quick experiments with pre-trained models, diverse molecular representations. For graph-first PyTorch workflows use torchdrug; for benchmark datasets use pytdc.- **[DiffDock](../skills/diffdock/SKILL.md)** - DiffDock and DiffDock-L molecular docking. Use for protein-small-molecule pose prediction from PDB or sequence plus SMILES/SDF/MOL2, batch docking, virtual screening, and pose-confidence interpretation. Not for binding affinity prediction.@@ -104,7 +109,9 @@ and limitations. See [workflow examples](examples.md) for ways to combine them.- **[matchms](../skills/matchms/SKILL.md)** - Process, clean, compare, and search tandem mass spectra with matchms. Use for MS/MS file I/O, metadata harmonization, peak filtering, spectral similarity, library matching, score matrices, and molecular-similarity networks. Use pyopenms instead for LC-MS feature detection or proteomics pipelines.- **[pyOpenMS](../skills/pyopenms/SKILL.md)** - Complete mass spectrometry analysis platform. Use for proteomics and metabolomics workflows—feature detection, peptide/protein identification, label-free and isobaric quantification, adduct/accurate-mass annotation, and complex LC-MS/MS pipelines. Supports extensive file formats and algorithms. For simple spectral comparison and small-molecule library matching use matchms.-### Medical Imaging & Digital Pathology+### Microscopy, Medical Imaging & Digital Pathology++- **[CellProfiler](../skills/cellprofiler/SKILL.md)** - Runs reproducible CellProfiler microscopy pipelines for nuclear segmentation, cell counts, and per-object fluorescence measurements. Supports image/channel manifests, headless batch execution, segmentation overlays, and measurement QC for 2D fluorescence assays.- **[DeepSpot-M](../skills/deepspot-m/SKILL.md)** - Generate transcriptome-wide virtual spatial transcriptomics from H&E histology with DeepSpot-M. Use when you need spatial gene expression in log1p-CPM for 224x224 tiles at about 20x, want to query protein-coding genes by symbol instead of a fixed panel, or want to run prediction across a whole slide after tiling with histolab.- **[histolab](../skills/histolab/SKILL.md)** - Lightweight WSI tile extraction and preprocessing. Use for basic slide processing, tissue detection, tile extraction, and stain normalization for H&E images. Best for simple pipelines, dataset preparation, and quick tile-based analysis. For advanced spatial proteomics, multiplexed imaging, or deep learning pipelines use pathml.- **[PathML](../skills/pathml/SKILL.md)** - Use PathML for local, research-only computational pathology workflows: load and tile slides, build preprocessing and QC pipelines, manage h5path data, quantify multiplex images, construct spatial graphs, and plan bounded model inference.@@ -119,17 +126,25 @@ and limitations. See [workflow examples](examples.md) for ways to combine them.- **[Treatment Plans](../skills/treatment-plans/SKILL.md)** - Format and structurally validate local treatment-plan documentation after clinical decisions have already been supplied and verified by authorized licensed professionals. Use for source traceability, clinician-authored intervention records, goals and checkpoints, shared-decision records, reconciliation handoffs, and release gates—not for clinical decision-making.### Neuroscience & Electrophysiology++- **[NWB Conversion](../skills/nwb-conversion/SKILL.md)** - Converts neuroscience acquisition data to Neurodata Without Borders files with NeuroConv and PyNWB, preserves metadata and timebases, checks evidence-based clock alignment, and produces schema validation, NWB Inspector findings and round-trip checks. Use for NWB conversion and synchronization of planar single-channel two-photon TIFF imaging plus timestamped behavioral position CSV; this skill does not perform spike sorting or claim tested support for arbitrary acquisition formats.- **[BIDS](../skills/bids/SKILL.md)** - Use this skill when working with Brain Imaging Data Structure (BIDS) datasets: organizing neuroscience and biomedical data (MRI, EEG, MEG, iEEG, PET, microscopy, NIRS, motion capture, EMG, MR spectroscopy, behavioral), querying BIDS layouts, validating compliance, converting DICOM to BIDS, writing metadata sidecars, or creating BIDS derivatives.- **[NeuroKit2](../skills/neurokit2/SKILL.md)** - Use NeuroKit2 to build or audit reproducible research workflows for physiological time-series preprocessing, event/interval analysis, multimodal alignment, variability, and complexity. Trigger when code imports neurokit2 or needs its current APIs, schemas, and method-aware validation—not for diagnosis or device validation.- **[Neuropixels-Analysis](../skills/neuropixels-analysis/SKILL.md)** - Analyze Neuropixels extracellular recordings end-to-end with SpikeInterface. Covers loading SpikeGLX/Open Ephys/NWB data, preprocessing, drift/motion correction, Kilosort4 (and CPU) spike sorting, quality metrics, and unit curation (threshold-based, model-based UnitRefine, and AI-assisted visual review). Use when working with Neuropixels 1.0/2.0 recordings, spike sorting, or extracellular electrophysiology analysis.### Protein Engineering & Design++- **[RELION](../skills/relion/SKILL.md)** - Validates and executes RELION single-particle cryo-EM refinement and half-map postprocessing. Supports STAR optics/acquisition checks, particle-stack consistency, gold-standard half sets, soft-mask validation, diagnostic Fourier shell correlation, and restart guidance.- **[Adaptyv](../skills/adaptyv/SKILL.md)** - How to use the Adaptyv Bio Foundry API and Python SDK for protein experiment design, submission, and results retrieval. Use this skill whenever the user mentions Adaptyv, Foundry API, protein binding assays, protein screening experiments, BLI/SPR assays, thermostability assays, or wants to submit protein sequences for experimental characterization. Also trigger when code imports `adaptyv`, `adaptyv_sdk`, or `FoundryClient`, or references `foundry-api-public.adaptyvbio.com`.- **[ESM (Evolutionary Scale Modeling)](../skills/esm/SKILL.md)** - Use when working directly with the `esm` Python SDK, ESM3 or ESMC model IDs, Forge/Biohub inference clients, or ESMFold2 folding workflows.- **[Glycoengineering](../skills/glycoengineering/SKILL.md)** - Analyze and engineer protein glycosylation. Scan sequences for N-glycosylation sequons (N-X-S/T), predict O-glycosylation hotspots, and access curated glycoengineering tools (NetOGlyc, GlycoShield, GlycoWorkbench). For glycoprotein engineering, therapeutic antibody optimization, and vaccine design.- **[Molecular Dynamics](../skills/molecular-dynamics/SKILL.md)** - Run and analyze molecular dynamics simulations with OpenMM and MDAnalysis. Set up protein/small molecule systems, define force fields, run energy minimization and production MD, analyze trajectories (RMSD, RMSF, contact maps, free energy surfaces). For structural biology, drug binding, and biophysics.- **[Tamarind](../skills/tamarind/SKILL.md)** - Access a collection of open-source molecular design and structural biology tools on the Tamarind Bio platform, via its REST API or MCP server — no local GPUs required. Tamarind bundles popular open-source models for structure prediction (AlphaFold, Boltz, Chai, ESMFold), protein, binder, and de novo design (RFdiffusion, ProteinMPNN, BoltzGen), antibody and nanobody design and developability, protein-ligand docking (DiffDock, Autodock Vina), binding-affinity prediction, MSA generation, and molecular dynamics. Use when the user mentions Tamarind or tamarind.bio, wants to run any of these open-source tools in the cloud, references app.tamarind.bio/api or the x-api-key header, or needs to submit batches of sequences for structural or biophysical characterization.+### Systems Biology & Kinetic Modeling++- **[Tellurium](../skills/tellurium/SKILL.md)** - Simulates biochemical kinetic models from SBML or Antimony with Tellurium and libRoadRunner, checks model units, compares deterministic parameter perturbations, and exports and replays SBML plus SED-ML COMBINE archives. Use for reaction-network time courses, kinetic parameters, concentration dynamics and reproducible simulation experiments; steady-state constraint-based metabolic flux analysis belongs to cobrapy.+### Machine Learning & Deep Learning- **[aeon](../skills/aeon/SKILL.md)** - This skill should be used for time series machine learning tasks including classification, regression, clustering, forecasting, anomaly detection, segmentation, and similarity search. Use when working with temporal data, sequential patterns, or time-indexed observations requiring specialized algorithms beyond standard ML approaches. Particularly suited for univariate and multivariate time series analysis with scikit-learn compatible APIs.- **[Cirq](../skills/cirq/SKILL.md)** - Google quantum computing framework. Use when targeting Google Quantum AI hardware, designing noise-aware circuits, or running quantum characterization experiments. Best for Google hardware, noise modeling, and low-level circuit design. For IBM hardware use qiskit; for quantum ML with autodiff use pennylane; for physics simulations use qutip.@@ -155,11 +170,16 @@ and limitations. See [workflow examples](examples.md) for ways to combine them.- **[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++- **[pycalphad](../skills/pycalphad/SKILL.md)** - Computes finite-temperature CALPHAD equilibria, phase fractions, and phase compositions from thermodynamic TDB databases using pycalphad. Use for alloy phase stability, equilibrium temperature sweeps, tie lines, lever-rule checks, or reproducible phase-fraction calculations with explicit components and mole-fraction conditions.- **[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.- **[Pymatgen](../skills/pymatgen/SKILL.md)** - Analyze, validate, convert, and transform materials structures and computed materials data with current pymatgen APIs, including local phase diagrams, symmetry sensitivity, electronic-structure I/O, and explicitly bounded Materials Project queries.### Engineering & Simulation++- **[Cantera](../skills/cantera/SKILL.md)** - Runs Cantera homogeneous chemical reactors and evaluates ignition delay with mechanism provenance, conservation checks, and numerical refinement. Use for combustion kinetics, closed adiabatic ideal-gas constant-volume or constant-pressure ignition, temperature histories, or mechanism-specific ignition-delay comparisons.+- **[PyBaMM](../skills/pybamm/SKILL.md)** - Simulates lithium-ion battery charge, discharge and rest experiments with PyBaMM, records parameter-set provenance, checks mesh and solver sensitivity, and compares predicted voltage curves with measured cycling data. Use for SPM or DFN electrochemical battery modeling, C-rate protocols, voltage cutoffs, parameter studies and numerical validation of battery simulations.- **[Lab Hardware CAD](../skills/lab-hardware-cad/SKILL.md)** - Design custom laboratory hardware as parametric build123d models and export fabrication-ready STEP, STL, and DXF files - microfluidic chips and molds, optomechanical mounts and breadboard adapters, cuvette and microplate holders, tube racks, animal-behavior rigs, and 3D-printed instrument fixtures. Use when a research task needs a physical part that must mate with standardized labware, an optical table, a cage system, or a printer, CNC, or laser process.- **[Fictiv](../skills/fictiv/SKILL.md)** - Operate Fictiv (app.fictiv.com), the on-demand manufacturing platform, end to end in the user's browser. Covers uploading CAD parts, configuring process, material, finish, threads, tolerances and inspections, getting instant or manual quotes, reading and fixing DFM feedback, choosing lead time and region, checking out and paying (card or PO), tracking orders, reordering, and troubleshooting. Use this skill whenever the user mentions Fictiv, wants a part CNC machined, 3D printed, sheet-metal fabricated, urethane cast, injection or compression molded, or die cast through an online service, asks to "get a quote" or "order parts" for a STEP/SLDPRT/STL file, wants to check a Fictiv quote or order status, or has a problem with a Fictiv upload, DFM warning, price or checkout. Use it even if Fictiv isn't named but the user wants custom parts manufactured and has a Fictiv account.- **[MATLAB/Octave](../skills/matlab/SKILL.md)** - Build, review, migrate, and safely plan MATLAB or GNU Octave numerical workflows, including arrays, tabular/time data, tests, projects, graphics, MAT files, and explicit Python interoperability.diff --git a/skills/cantera/SKILL.md b/skills/cantera/SKILL.mdnew file mode 100644index 00000000..d22b5540--- /dev/null+++ b/skills/cantera/SKILL.md@@ -0,0 +1,124 @@+---+name: cantera+description: Runs Cantera homogeneous chemical reactors and evaluates ignition delay with mechanism provenance, conservation checks, and numerical refinement. Use for combustion kinetics, closed adiabatic ideal-gas constant-volume or constant-pressure ignition, temperature histories, or mechanism-specific ignition-delay comparisons.+license: MIT+compatibility: Requires Python 3.12+, Cantera 3.2.0, and NumPy. Installation needs network access; simulations run locally without credentials. Custom mechanisms must be available as Cantera YAML files.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ tested-package-version: "3.2.0"+---++# Cantera: homogeneous ignition calculations++## When to use++Use for a closed, adiabatic, homogeneous ideal-gas reactor with a known kinetic mechanism,+initial temperature, pressure, and mole composition. The bundled helper runs both constant+volume and constant pressure cases and reports a precisely defined temperature-based delay.+It is not a flame solver or a general reactor-network builder.++A calculation completing successfully establishes numerical execution, not mechanism+validity for the fuel, pressure, temperature, diluent, or measured ignition observable.+Read [references/interpretation.md](references/interpretation.md) when choosing a mechanism,+comparing experiments, or interpreting unresolved/two-stage ignition.++## Workflow++1. Identify the mechanism and its validated condition range. Preserve its source, version,+ citation, and any modifications. Check that its phase is `ideal-gas` and that every+ reactant, diluent, and tracked species exists. For custom YAML with imports, retain the+ original dependency files as well as the generated self-contained phase snapshot.+2. Choose constant volume or constant pressure from the physical experiment. Supply K,+ Pa, seconds, and mole amounts explicitly. `mole_amounts` is normalized to mole fractions;+ it is not a mass-fraction mapping. The report includes the normalized initial composition.+3. Copy [assets/hydrogen-ignition.json](assets/hydrogen-ignition.json) and change its conditions.+ The supplied H2/O2/Ar case uses Cantera's bundled `h2o2.yaml` for an executable numerical+ example; it is not a recommendation for every hydrogen experiment.+4. Set a time horizon long enough to observe the temperature rise and the decline of the+ heating-rate peak. Choose output spacing fine enough to locate that peak. Set a minimum+ temperature rise to distinguish ignition from negligible heating or numerical noise.+5. Run the helper and inspect all four histories and the report. Refine again if the delay+ changes materially, if the maximum approaches a time boundary, or if conservation fails.+ Compare the temperature and tracked-species histories with the actual ignition definition.+6. Report the condition set, mechanism hash, reactor constraint, delay definition, output+ spacing, numerical changes, and scientific limits together with the delay.++## Execute the tested example++From the collection root:++```bash+uv run --no-project --python 3.12 --with cantera==3.2.0 --with numpy==2.5.3 \+ python skills/cantera/scripts/ignition_delay.py \+ skills/cantera/assets/hydrogen-ignition.json hydrogen-result+```++Tested on Python 3.12, Cantera 3.2.0, and NumPy 2.5.3. No external solver executable or+credentials are needed. Local relative mechanism paths resolve against the configuration+file directory before Cantera's built-in data search. Use a new output directory each run.++The 1000 K, 101325 Pa, H2:O2:Ar = 2:1:7 constant-volume example gives about **0.313 ms**+using the stated `max(dT/dt)` definition. At 3 ms its temperature is approximately+2920.67 K and agrees with a separate `UV` equilibrium calculation. These are package+regression values, not experimental validation data.++## Exact delay and refinement contract++Delay is the time of the global maximum of `numpy.gradient(T, time, edge_order=2)` on+a uniform output grid. It is reported only if the maximum temperature rise reaches+`minimum_temperature_rise_k` and the maximum is at least two sample indices from each+boundary. Otherwise `delay_s` is null and a status explains why. No delay beyond the+simulation horizon is extrapolated.++The helper runs four independent fresh reactors:++| Run | Change from configured conditions |+| --- | --- |+| baseline | Original settings |+| finer_output | Half output spacing, same horizon and solver controls |+| tighter_solver | Both solver tolerances divided by ten; maximum internal time step halved |+| longer_horizon | Twice the horizon with the original output spacing |++`numerically_resolved` requires all runs to yield delays, relative delay changes within+`delay_relative_tolerance`, and all conservation checks to pass. Agreement on a discrete+grid is not a statistical error bar: also report the output spacing. The baseline samples+must be between 11 and 50000, leaving room for refinement. Runtime grows with mechanism+size, stiffness, and the chosen horizon; integration failures retain Cantera's error text.++## Outputs and checks++- `report.json`: all input settings, package versions, configuration and mechanism hashes,+ normalized starting composition, four delay estimates, numerical changes, conservation,+ and mechanism thermodynamic temperature bounds.+- `baseline.csv`, `finer_output.csv`, `tighter_solver.csv`, `longer_horizon.csv`: time,+ temperature, pressure, volume, mass, total internal energy, total enthalpy, and requested+ species mole fractions.+- `mechanism.yaml`: a Cantera-written snapshot of the loaded phase, species, and reactions.+ The report hashes this exact file and the located original mechanism file. Imported+ source dependencies are not separately hashed; the snapshot captures the loaded model.++Closed reactors conserve mass and elemental mass fractions. The constant-volume case+checks total internal energy; the constant-pressure case checks total enthalpy. Energy+error is divided by `max(abs(initial_energy_J), 1 J)`. Diagnostic tolerances are mass+relative drift <1e-8, elemental absolute drift <1e-8, energy scaled drift <1e-6, species+mass-fraction sum error <1e-8, and species mass fractions >-1e-10. These checks expose+numerical issues and do not measure kinetic-model uncertainty.++Check `within_thermo_temperature_range` separately: numerical resolution does not mean+species thermodynamic fits were used within their temperature bounds. The helper cannot+assess pressure-dependent kinetic validity from these bounds.++## Scope and upstream references++The suite covers both reactor constraints, conservation, final-state agreement with+independent Cantera equilibrium, nonigniting conditions, unresolved boundary maxima,+refinement, snapshot replay, and invalid composition/conditions. It does not validate+shock-tube heat loss, real-gas effects, surfaces, flow devices, flames, or multistage+experimental ignition definitions. Build those models only with the necessary physics+and their own checks; do not relabel this helper's result as one of them.++- [Reactor model equations](https://cantera.org/stable/reference/reactors/index.html)+- [Python reactor API](https://cantera.org/stable/python/zerodim.html)+- [Thermodynamic properties and equilibrium](https://cantera.org/stable/python/thermo.html)+- [Upstream ignition example](https://cantera.org/stable/examples/python/reactors/non_ideal_shock_tube.html)diff --git a/skills/cantera/assets/hydrogen-ignition.json b/skills/cantera/assets/hydrogen-ignition.jsonnew file mode 100644index 00000000..d2644aee--- /dev/null+++ b/skills/cantera/assets/hydrogen-ignition.json@@ -0,0 +1,16 @@+{+ "mechanism": "h2o2.yaml",+ "phase": "ohmech",+ "reactor": "constant-volume",+ "temperature_k": 1000.0,+ "pressure_pa": 101325.0,+ "mole_amounts": {"H2": 2.0, "O2": 1.0, "AR": 7.0},+ "end_time_s": 0.003,+ "samples": 3001,+ "rtol": 1e-9,+ "atol": 1e-15,+ "max_time_step_s": 1e-5,+ "minimum_temperature_rise_k": 200.0,+ "tracked_species": ["H2", "O2", "H2O", "OH"],+ "delay_relative_tolerance": 0.01+}diff --git a/skills/cantera/references/interpretation.md b/skills/cantera/references/interpretation.mdnew file mode 100644index 00000000..51b321cd--- /dev/null+++ b/skills/cantera/references/interpretation.md@@ -0,0 +1,50 @@+# Model selection and ignition interpretation++## Match the observable++A maximum in dT/dt, a maximum in OH mole fraction, an OH* chemiluminescence onset,+a fixed temperature rise, and a pressure-based delay are different observables. The+helper implements only the global maximum dT/dt, guarded by a specified temperature+rise. Tracked species are exported to support inspection; their maxima do not silently+replace the configured definition. OH and excited OH* are distinct species and may+not both exist in the mechanism.++Two-stage ignition may have an early weak heat-release peak and a later stronger one.+The global-maximum definition selects the strongest heating peak in the modeled horizon.+If the user needs first-stage delay, define and validate a separate event detector and+report both. Extending the horizon can change which peak is largest; the automatic+longer-horizon run checks this possibility but cannot prove no later event exists.++## Numerical diagnosis++An interior derivative maximum can still be sampled coarsely. Inspect peak width,+compare the finer output grid, and increase samples until the uncertainty is adequate+for the intended comparison. Internal solver tolerance and output sampling are distinct:+a tightly integrated trajectory can yield a poorly located derivative on a coarse output+grid. The tighter-solver run also halves the allowed internal time step; its comparison+therefore tests those controls together.++Unreached temperature rise means only that the threshold was not observed in this model+and horizon. It does not establish nonflammability, an infinite physical delay, or a+lower bound under a different ignition definition. Review conditions and extend the+horizon when scientifically justified.++Species thermochemistry extrapolation can produce smooth numerical trajectories. Check+the reported thermodynamic temperature interval and the mechanism's original kinetic+validation sources. Small mass, energy, and element residuals do not detect a poor+reaction mechanism, missing pathways, incorrect third-body efficiencies, or a wrong+composition basis.++## Model boundaries++The helper assumes initially 1 m3, closed adiabatic walls, ideal-gas behavior, homogeneous+composition, and no reacting surfaces. Homogeneous ignition time is independent of+this arbitrary initial volume in the modeled system; extensive energies and mass scale+with it. Constant-pressure volume expansion is allowed, so its conserved energy is+enthalpy. Constant-volume pressure rises, so comparison with a nominal constant-pressure+experiment requires a different reactor setting.++Shock tubes, rapid compression machines, and engines may need measured volume histories,+heat transfer, facility effects, or nonideal equations of state. Those are physics changes,+not tolerance adjustments. Use the appropriate upstream reactor class or customized model+and verify the additional terms before interpreting agreement with an experiment.diff --git a/skills/cantera/scripts/ignition_delay.py b/skills/cantera/scripts/ignition_delay.pynew file mode 100644index 00000000..1d5f722e--- /dev/null+++ b/skills/cantera/scripts/ignition_delay.py@@ -0,0 +1,197 @@+#!/usr/bin/env python3+"""Run closed adiabatic ideal-gas ignition with numerical and conservation checks."""+from __future__ import annotations++import argparse+import csv+import hashlib+import json+from pathlib import Path++import cantera as ct+import numpy as np+++def number(value, name):+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not np.isfinite(value) or value <= 0:+ raise ValueError(f"{name} must be a finite positive number")+ return float(value)+++def validate(config):+ keys = {"mechanism", "phase", "reactor", "temperature_k", "pressure_pa", "mole_amounts",+ "end_time_s", "samples", "rtol", "atol", "max_time_step_s", "minimum_temperature_rise_k",+ "tracked_species", "delay_relative_tolerance"}+ if set(config) != keys:+ raise ValueError(f"Missing settings: {sorted(keys-set(config))}; unknown: {sorted(set(config)-keys)}")+ for name in keys - {"mechanism", "phase", "reactor", "mole_amounts", "samples", "tracked_species"}:+ number(config[name], name)+ n = config["samples"]+ if isinstance(n, bool) or not isinstance(n, int) or not 11 <= n <= 100000:+ raise ValueError("samples must be an integer from 11 through 100000")+ if config["reactor"] not in ("constant-volume", "constant-pressure"):+ raise ValueError("reactor must be constant-volume or constant-pressure")+ if not isinstance(config["mole_amounts"], dict) or not config["mole_amounts"]:+ raise ValueError("mole_amounts must be a nonempty species-to-amount mapping")+ amounts = config["mole_amounts"]+ if any(isinstance(v, bool) or not isinstance(v, (int, float)) or not np.isfinite(v) or v < 0 for v in amounts.values()) or sum(amounts.values()) <= 0:+ raise ValueError("mole_amounts must be finite, nonnegative, and have a positive sum")+ if not isinstance(config["tracked_species"], list) or len(set(config["tracked_species"])) != len(config["tracked_species"]):+ raise ValueError("tracked_species must be a list of unique names")+++def load_gas(config):+ gas = ct.Solution(config["mechanism"], config["phase"])+ if gas.thermo_model != "ideal-gas":+ raise ValueError("This helper supports only ideal-gas phases")+ unknown = (set(config["mole_amounts"]) | set(config["tracked_species"])) - set(gas.species_names)+ if unknown:+ raise ValueError(f"Unknown species: {sorted(unknown)}")+ gas.TPX = config["temperature_k"], config["pressure_pa"], config["mole_amounts"]+ return gas+++def delay_from_history(time, temperature, minimum_rise):+ rise = float(np.max(temperature) - temperature[0])+ rate = np.gradient(temperature, time, edge_order=2)+ index = int(np.argmax(rate))+ status = "resolved"+ if rise < minimum_rise:+ status = "temperature-rise-not-reached"+ elif index < 2 or index >= len(time) - 2:+ status = "derivative-maximum-at-boundary"+ return {"status": status, "delay_s": float(time[index]) if status == "resolved" else None,+ "maximum_temperature_rise_k": rise, "peak_heating_rate_k_per_s": float(rate[index]),+ "output_spacing_s": float(time[1] - time[0])}+++def simulate(config):+ validate(config)+ gas = load_gas(config)+ reactor_type = ct.IdealGasReactor if config["reactor"] == "constant-volume" else ct.IdealGasConstPressureReactor+ reactor = reactor_type(gas, energy="on", volume=1.0, clone=True)+ network = ct.ReactorNet([reactor])+ network.rtol, network.atol = config["rtol"], config["atol"]+ network.max_time_step = config["max_time_step_s"]+ network.max_steps = 100000+ times = np.linspace(0, config["end_time_s"], config["samples"])+ rows, elements = [], []+ species_indices = [gas.species_index(name) for name in config["tracked_species"]]+ minimum_y = 0.0+ normalization_error = 0.0+ for time in times:+ if time:+ network.advance(float(time))+ phase = reactor.phase+ rows.append([time, reactor.T, phase.P, reactor.volume, reactor.mass,+ reactor.mass * phase.int_energy_mass, reactor.mass * phase.enthalpy_mass,+ *phase.X[species_indices]])+ elements.append([phase.elemental_mass_fraction(name) for name in phase.element_names])+ minimum_y = min(minimum_y, float(phase.Y.min()))+ normalization_error = max(normalization_error, abs(float(phase.Y.sum()) - 1))+ history = np.asarray(rows)+ if not np.isfinite(history).all():+ raise ValueError("Integrator returned a nonfinite state")+ energy_col = 5 if config["reactor"] == "constant-volume" else 6+ conserved = history[:, energy_col]+ conservation = {+ "mass_relative_drift": float(np.max(np.abs(history[:, 4] / history[0, 4] - 1))),+ "element_mass_fraction_absolute_drift": float(np.max(np.abs(np.asarray(elements) - elements[0]))),+ "conserved_quantity": "total_internal_energy_j" if energy_col == 5 else "total_enthalpy_j",+ "energy_scaled_drift": float(np.max(np.abs(conserved - conserved[0])) / max(abs(conserved[0]), 1.0)),+ "energy_denominator_j": max(abs(float(conserved[0])), 1.0),+ "minimum_species_mass_fraction": minimum_y,+ "mass_fraction_sum_error": normalization_error,+ }+ conservation["passed"] = (conservation["mass_relative_drift"] < 1e-8 and+ conservation["element_mass_fraction_absolute_drift"] < 1e-8 and+ conservation["energy_scaled_drift"] < 1e-6 and+ minimum_y > -1e-10 and normalization_error < 1e-8)+ result = delay_from_history(history[:, 0], history[:, 1], config["minimum_temperature_rise_k"])+ result.update(conservation=conservation, final_temperature_k=float(history[-1, 1]),+ samples=config["samples"], rtol=config["rtol"], atol=config["atol"],+ max_time_step_s=config["max_time_step_s"], end_time_s=config["end_time_s"],+ thermo_temperature_range_k=[gas.min_temp, gas.max_temp],+ within_thermo_temperature_range=bool(history[:, 1].min() >= gas.min_temp and history[:, 1].max() <= gas.max_temp))+ return history, result+++def run(config_path, output_dir):+ config_path, output_dir = Path(config_path), Path(output_dir)+ if output_dir.exists():+ raise ValueError("Output directory exists; choose a new directory")+ config = json.loads(config_path.read_text())+ validate(config)+ if config["samples"] > 50000:+ raise ValueError("CLI samples must be at most 50000 to permit refinement runs")+ # Local relative mechanism paths resolve against the configuration, before built-in lookup.+ local = config_path.parent / config["mechanism"]+ effective = dict(config)+ if local.is_file():+ effective["mechanism"] = str(local.resolve())+ gas = load_gas(effective)+ snapshot = gas.write_yaml()+ source = next((Path(d) / effective["mechanism"] for d in ct.get_data_directories()+ if (Path(d) / effective["mechanism"]).is_file()), None)+ variants = {+ "baseline": effective,+ "finer_output": {**effective, "samples": 2 * effective["samples"] - 1},+ "tighter_solver": {**effective, "rtol": effective["rtol"] / 10,+ "atol": effective["atol"] / 10,+ "max_time_step_s": effective["max_time_step_s"] / 2},+ "longer_horizon": {**effective, "end_time_s": 2 * effective["end_time_s"],+ "samples": 2 * effective["samples"] - 1},+ }+ results, histories = {}, {}+ for name, conditions in variants.items():+ history, summary = simulate(conditions)+ histories[name], results[name] = history, summary+ baseline_delay = results["baseline"]["delay_s"]+ sensitivity = {}+ for name, result in results.items():+ if name == "baseline":+ continue+ delay = result["delay_s"]+ sensitivity[name] = (abs(delay - baseline_delay) / baseline_delay+ if baseline_delay is not None and delay is not None else None)+ converged = all(value is not None and value <= config["delay_relative_tolerance"] for value in sensitivity.values())+ report = {+ "versions": {"cantera": ct.__version__, "numpy": np.__version__}, "settings": config,+ "config_sha256": hashlib.sha256(config_path.read_bytes()).hexdigest(),+ "mechanism": {"requested": config["mechanism"], "phase": gas.name,+ "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest() if source else None,+ "snapshot_sha256": hashlib.sha256(snapshot.encode()).hexdigest(),+ "species_count": gas.n_species, "reaction_count": gas.n_reactions,+ "initial_normalized_mole_fractions": {name: float(x) for name, x in zip(gas.species_names, gas.X) if x > 0}},+ "definition": "Time of global maximum finite-difference dT/dt on a uniform output grid; requires the specified temperature rise and an interior maximum",+ "runs": results, "delay_relative_changes": sensitivity,+ "numerically_resolved": converged and all(r["conservation"]["passed"] for r in results.values()),+ "mechanism_experimental_validity": "not_assessed",+ }+ output_dir.mkdir(parents=True)+ (output_dir / "mechanism.yaml").write_text(snapshot)+ (output_dir / "report.json").write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")+ for name, history in histories.items():+ with (output_dir / f"{name}.csv").open("w", newline="") as handle:+ writer = csv.writer(handle)+ writer.writerow(["time_s", "temperature_k", "pressure_pa", "volume_m3", "mass_kg",+ "internal_energy_j", "enthalpy_j", *[f"X_{s}" for s in config["tracked_species"]]])+ writer.writerows(history)+ return report+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("config", type=Path)+ parser.add_argument("output", type=Path, help="New output directory")+ args = parser.parse_args()+ try:+ report = run(args.config, args.output)+ except (ValueError, OSError, KeyError, TypeError, ct.CanteraError) as error:+ parser.error(str(error))+ print(json.dumps({"output": str(args.output), "numerically_resolved": report["numerically_resolved"],+ "delay_s": report["runs"]["baseline"]["delay_s"]}))+++if __name__ == "__main__":+ main()diff --git a/skills/cellprofiler/SKILL.md b/skills/cellprofiler/SKILL.mdnew file mode 100644index 00000000..4a057fe1--- /dev/null+++ b/skills/cellprofiler/SKILL.md@@ -0,0 +1,88 @@+---+name: cellprofiler+description: Runs reproducible CellProfiler microscopy pipelines for nuclear segmentation, cell counts, and per-object fluorescence measurements. Supports image/channel manifests, headless batch execution, segmentation overlays, and measurement QC for 2D fluorescence assays.+license: MIT+compatibility: Python 3.10+ with numpy and tifffile for bundled helpers; CellProfiler 4.2.8 executable or its Linux container for segmentation. Network access is needed for installation only. No credentials required.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ upstream-version: "4.2.8"+---++# CellProfiler quantitative microscopy++Use this skill when a user needs a repeatable CellProfiler `.cppipe`, nuclear counts, nuclear+fluorescence, or batch microscopy measurements. The bundled assay accepts **one 2D grayscale+TIFF nuclear channel per field**, with bright nuclei on a dark background. For volumetric+segmentation, multichannel cell painting, or tissue-specific models, design a separate pipeline+and validate those assumptions rather than silently projecting or splitting the images.++## Workflow++1. Establish the acquisition unit: plate, well, site, time point if present, pixel size, nuclear+ channel identity, camera bit depth, exposure, and biological replicate. Keep original image+ intensities. Convert proprietary formats explicitly with Bio-Formats before using this helper.+2. Create the CSV manifest below. `image_path` is absolute or relative to the manifest; sample IDs use letters, digits, dots, dashes, or underscores; sample IDs+ and plate/well/site combinations are unique. TIFFs must be uint8 or uint16, single plane, and+ nonconstant. The helper rejects RGB, z-stacks, and float images rather than guessing channels.+3. Use [assets/nuclei.cppipe](assets/nuclei.cppipe) as a starting pipeline: LoadData →+ IdentifyPrimaryObjects → intensity/size measurements → outline overlay → CSV export.+ The initial diameter range is 8–80 **pixels**, with global Otsu thresholding, no threshold+ smoothing, and border objects excluded. Calibrate this+ range from representative images and acquisition pixel size before comparing conditions.+4. Run a small pilot spanning controls, low/high density, dim images, and plate edges. Inspect+ saved overlays for missed nuclei, splits, merges, and edge exclusions. Adjust thresholding+ and declumping in CellProfiler, export the tuned `.cppipe`, and pass `--pipeline` to preserve+ it. Do not choose settings separately for each treatment to make their counts agree.+5. Freeze the tuned pipeline and analyze the batch. Review input saturation warnings, zero+ counts, count/area distributions, and control behavior. Aggregation for inference belongs at+ the biological replicate level; thousands of cells from one well are not independent wells.++## Run the bounded assay++From this skill directory, create `images.csv`:++```csv+sample_id,image_path,plate,well,site+control_A01_1,images/control_A01_1_DAPI.tif,Plate1,A01,1+```++```bash+python scripts/nuclei_assay.py prepare images.csv load_data.csv+python scripts/nuclei_assay.py run images.csv results --executable cellprofiler+python scripts/nuclei_assay.py summarize results+```++`run` requires a fresh/empty output directory and executes CellProfiler with `-c -r`, an explicit+pipeline, `--data-file`, and output folder. It records the command, pipeline checksum, input image+checksums, and sample QC in `assay_qc.json`; CellProfiler output goes to `cellprofiler.log`.+A failed process stays failed, with its log available for diagnosis. Rerun in a new output folder.++The executable can also be the CellProfiler application launcher or a local container launcher;+see [references/runtime-and-qc.md](references/runtime-and-qc.md) for the tested container,+filesystem mapping, and verification evidence. `prepare` and `summarize` work without CellProfiler.++## Interpret the outputs++- `Image.csv`: one image/field row, including `Count_Nuclei` and acquisition metadata.+- `Nuclei.csv`: one accepted object per row, with mean/integrated DNA intensity, area, and shape.+- `*_nuclei.png`: green nuclear boundaries over the input image for visual QC.+- `assay_qc.json`: count consistency and finite normalized intensity checks, plus saturation flags.++LoadData ignores camera metadata for scaling in this asset and divides by the integer storage+maximum: uint8 → 255, uint16 → 65535. A 12-bit camera stored in uint16 therefore has a maximum+near 0.0625. Do not compare intensities across different bit depths, exposures, gains, or staining+batches without an explicit calibration. A saturated image can pass segmentation while its+intensity measurement is unusable. Illumination correction and background subtraction are+assay-specific additions; this starter does neither.++A count check cannot prove correct segmentation. Inspect overlays and independently annotated+fields; report boundary exclusions and segmentation errors alongside the biological result.+The synthetic integration test validates a known three-nucleus example, not assay performance+on unseen cell types.++## Sources++- [Official example pipelines](https://cellprofiler.org/examples): choose an assay-specific starting point.+- [CellProfiler 4.2.8 manual](https://cellprofiler-manual.s3.amazonaws.com/CellProfiler-4.2.8/index.html): module settings and interpretation.+- [Headless batch processing](https://cellprofiler-manual.s3.amazonaws.com/CellProfiler-4.2.8/help/other_batch.html): command-line execution.diff --git a/skills/cellprofiler/assets/nuclei.cppipe b/skills/cellprofiler/assets/nuclei.cppipenew file mode 100644index 00000000..b14c0a58--- /dev/null+++ b/skills/cellprofiler/assets/nuclei.cppipe@@ -0,0 +1,116 @@+CellProfiler Pipeline: http://www.cellprofiler.org+Version:5+DateRevision:428+GitHash:+ModuleCount:7+HasImagePlaneDetails:False++LoadData:[module_num:1|svn_version:'Unknown'|variable_revision_number:6|show_window:False|notes:[]|batch_state:array([], dtype=uint8)|enabled:True|wants_pause:False]+ Input data file location:Elsewhere...|+ Name of the file:load_data.csv+ Load images based on this data?:Yes+ Base image location:Default Input Folder|+ Process just a range of rows?:No+ Rows to process:1,100000+ Group images by metadata?:No+ Select metadata tags for grouping:+ Rescale intensities?:No++IdentifyPrimaryObjects:[module_num:2|svn_version:'Unknown'|variable_revision_number:15|show_window:False|notes:[]|batch_state:array([], dtype=uint8)|enabled:True|wants_pause:False]+ Select the input image:DNA+ Name the primary objects to be identified:Nuclei+ Typical diameter of objects, in pixel units (Min,Max):8,80+ Discard objects outside the diameter range?:Yes+ Discard objects touching the border of the image?:Yes+ Method to distinguish clumped objects:Shape+ Method to draw dividing lines between clumped objects:Intensity+ Size of smoothing filter:10+ Suppress local maxima that are closer than this minimum allowed distance:7.0+ Speed up by using lower-resolution image to find local maxima?:Yes+ Fill holes in identified objects?:After both thresholding and declumping+ Automatically calculate size of smoothing filter for declumping?:Yes+ Automatically calculate minimum allowed distance between local maxima?:Yes+ Handling of objects if excessive number of objects identified:Continue+ Maximum number of objects:500+ Use advanced settings?:Yes+ Threshold setting version:12+ Threshold strategy:Global+ Thresholding method:Otsu+ Threshold smoothing scale:0.0+ Threshold correction factor:1.0+ Lower and upper bounds on threshold:0.0,1.0+ Manual threshold:0.0+ Select the measurement to threshold with:None+ Two-class or three-class thresholding?:Two classes+ Log transform before thresholding?:No+ Assign pixels in the middle intensity class to the foreground or the background?:Foreground+ Size of adaptive window:50+ Lower outlier fraction:0.05+ Upper outlier fraction:0.05+ Averaging method:Mean+ Variance method:Standard deviation+ # of deviations:2.0+ Thresholding method:Minimum Cross-Entropy++MeasureObjectIntensity:[module_num:3|svn_version:'Unknown'|variable_revision_number:4|show_window:False|notes:[]|batch_state:array([], dtype=uint8)|enabled:True|wants_pause:False]+ Select images to measure:DNA+ Select objects to measure:Nuclei++MeasureObjectSizeShape:[module_num:4|svn_version:'Unknown'|variable_revision_number:3|show_window:False|notes:[]|batch_state:array([], dtype=uint8)|enabled:True|wants_pause:False]+ Select object sets to measure:Nuclei+ Calculate the Zernike features?:Yes+ Calculate the advanced features?:No++OverlayOutlines:[module_num:5|svn_version:'Unknown'|variable_revision_number:4|show_window:False|notes:[]|batch_state:array([], dtype=uint8)|enabled:True|wants_pause:False]+ Display outlines on a blank image?:No+ Select image on which to display outlines:DNA+ Name the output image:NucleiOverlay+ Outline display mode:Color+ Select method to determine brightness of outlines:Max of image+ How to outline:Inner+ Select outline color:Green+ Select objects to display:Nuclei++SaveImages:[module_num:6|svn_version:'Unknown'|variable_revision_number:16|show_window:False|notes:[]|batch_state:array([], dtype=uint8)|enabled:True|wants_pause:False]+ Select the type of image to save:Image+ Select the image to save:NucleiOverlay+ Select method for constructing file names:Single name+ Select image name for file prefix:DNA+ Enter single file name:\g<Sample>_nuclei+ Number of digits:4+ Append a suffix to the image file name?:No+ Text to append to the image name:_nuclei+ Saved file format:png+ Output file location:Default Output Folder|+ Image bit depth:8-bit integer+ Overwrite existing files without warning?:No+ When to save:Every cycle+ Record the file and path information to the saved image?:No+ Create subfolders in the output folder?:No+ Base image folder:Elsewhere...|+ How to save the series:T (Time)+ Save with lossless compression?:Yes++ExportToSpreadsheet:[module_num:7|svn_version:'Unknown'|variable_revision_number:13|show_window:False|notes:[]|batch_state:array([], dtype=uint8)|enabled:True|wants_pause:False]+ Select the column delimiter:Comma (",")+ Add image metadata columns to your object data file?:No+ Add image file and folder names to your object data file?:No+ Select the measurements to export:No+ Calculate the per-image mean values for object measurements?:No+ Calculate the per-image median values for object measurements?:No+ Calculate the per-image standard deviation values for object measurements?:No+ Output file location:Default Output Folder|+ Create a GenePattern GCT file?:No+ Select source of sample row name:Metadata+ Select the image to use as the identifier:None+ Select the metadata to use as the identifier:None+ Export all measurement types?:Yes+ Press button to select measurements:+ Representation of Nan/Inf:NaN+ Add a prefix to file names?:No+ Filename prefix:MyExpt_+ Overwrite existing files without warning?:No+ Data to export:Do not use+ Combine these object measurements with those of the previous object?:No+ File name:DATA.csv+ Use the object name for the file name?:Yesdiff --git a/skills/cellprofiler/references/runtime-and-qc.md b/skills/cellprofiler/references/runtime-and-qc.mdnew file mode 100644index 00000000..f12dd391--- /dev/null+++ b/skills/cellprofiler/references/runtime-and-qc.md@@ -0,0 +1,57 @@+# Runtime and assay verification++## CellProfiler 4.2.8++The pipeline targets the full **CellProfiler 4.2.8**, not merely `cellprofiler-core`:+IdentifyPrimaryObjects and measurement modules live in the full package. The official image+`cellprofiler/cellprofiler:4.2.8` is a Linux amd64 environment. Its tested digest is+`sha256:fec440caa2b44edf80f9bd440a3d8c6b214d72437332ad2586a32d79e2eae2a4`.+Apple Silicon runs that image with `--platform linux/amd64` under emulation.++For containers, run the helper **inside** a mounted working directory or mount input images,+manifest, pipeline, and outputs at the same absolute paths as the host. LoadData CSV file URLs+must resolve inside the container. A relative path inside a manifest is resolved before export;+a host file URL does not automatically become `/work/...` when mounted there.++Example container pattern, from a working directory containing `images.csv`, `images/`, and a+copy of this skill directory called `cellprofiler-skill/`:++```bash+docker run --rm --platform linux/amd64 --entrypoint python \+ -v "$PWD:/work" -w /work cellprofiler/cellprofiler:4.2.8 \+ cellprofiler-skill/scripts/nuclei_assay.py run images.csv results+```++The image already supplies numpy and tifffile. Native helper-only installation can use a+separate environment with `numpy` and `tifffile`. Full native CellProfiler has additional Java,+GUI/build, and database client dependencies; follow the+[official installation instructions](https://github.com/CellProfiler/CellProfiler/wiki).+A local isolated PyPI installation attempted during development stopped on+`mysqlclient==1.4.6` because `mysql_config` was absent; the container provides the tested runtime.++## Scientific checks++- Establish a manually counted set of fields across the acquisition range. Assess precision,+ missed objects, splits, and merges, not only mean count correlation.+- Compare nuclear area distributions with plausible biology. Inflated area may indicate merges+ or illumination background; many tiny objects may be debris or threshold noise.+- Check boundary policy. This starter excludes objects touching an image edge; overlapping+ acquisition tiles need a deliberate deduplication/edge policy.+- Flat-field correction uses a separately estimated illumination function. Do not independently+ normalize each image to its own minimum/maximum before intensity comparisons.+- Review out-of-focus and saturated fields. A >1% saturation warning is a triage heuristic,+ not a universal acceptance limit; set acceptance criteria for the assay.+- Preserve field identities and experimental replicates when aggregating cells to wells.++## Verification scope++The asset was serialized by CellProfiler 4.2.8 module APIs and executed headlessly on a synthetic+uint16 TIFF with three separated disks (radius 10 pixels; intensities 20,000, 30,000, 40,000).+The regression asserts three nuclei, mean normalized intensity near 30,000/65,535, and a saved+outline PNG. Unit tests reject constant/RGB/float images, duplicate acquisition fields,+nonfinite measurements, and mismatched output samples.++To repeat the real integration test in a repository checkout, set+`CELLPROFILER_TEST_EXECUTABLE` to an installed `cellprofiler` executable or a launcher that forwards+all arguments and mounts the paths unchanged. Run only `tests/cellprofiler/` in that pytest+process. The test is explicitly skipped without that executable; helper tests still run.diff --git a/skills/cellprofiler/scripts/nuclei_assay.py b/skills/cellprofiler/scripts/nuclei_assay.pynew file mode 100644index 00000000..d6ec6afa--- /dev/null+++ b/skills/cellprofiler/scripts/nuclei_assay.py@@ -0,0 +1,142 @@+#!/usr/bin/env python3+"""Validate a microscopy manifest, run CellProfiler, and check nuclei measurements."""+from __future__ import annotations++import argparse+import csv+import hashlib+import json+import math+import re+from pathlib import Path+import subprocess+++def prepare(manifest: Path, destination: Path) -> dict:+ """Make LoadData CSV; retain unscaled uint16 data and explicit sample metadata."""+ import numpy as np+ import tifffile++ with manifest.open(newline="", encoding="utf-8-sig") as handle:+ reader = csv.DictReader(handle)+ required = {"sample_id", "image_path", "plate", "well", "site"}+ if not required.issubset(reader.fieldnames or []):+ raise ValueError(f"Manifest requires columns {sorted(required)}")+ rows = list(reader)+ if not rows:+ raise ValueError("Manifest contains no images")+ output, qc, seen, fields_seen, paths_seen = [], [], set(), set(), set()+ for row in rows:+ if any(not row[key].strip() for key in required):+ raise ValueError("Manifest contains empty identifiers or paths")+ sample = row["sample_id"]+ if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", sample):+ raise ValueError("Sample IDs must be filename-safe letters, digits, dots, dashes or underscores")+ field = (row["plate"], row["well"], row["site"])+ if sample in seen or field in fields_seen:+ raise ValueError(f"Duplicate sample or plate/well/site: {sample}")+ seen.add(sample)+ fields_seen.add(field)+ path = Path(row["image_path"])+ path = (manifest.parent / path).resolve() if not path.is_absolute() else path.resolve()+ if path in paths_seen:+ raise ValueError(f"Repeated image file: {path}")+ paths_seen.add(path)+ image = tifffile.imread(path)+ if image.ndim != 2 or image.dtype not in (np.dtype("uint8"), np.dtype("uint16")):+ raise ValueError(f"{sample}: requires single-plane grayscale uint8/uint16 TIFF")+ if min(image.shape) < 16 or np.ptp(image) == 0:+ raise ValueError(f"{sample}: image too small or constant")+ maximum = np.iinfo(image.dtype).max+ qc.append({"sample_id": sample, "shape": list(image.shape), "dtype": str(image.dtype),+ "saturated_fraction": float(np.mean(image == maximum)),+ "sha256": hashlib.sha256(path.read_bytes()).hexdigest()})+ output.append({"URL_DNA": path.as_uri(), "Metadata_Sample": sample,+ "Metadata_Plate": row["plate"], "Metadata_Well": row["well"],+ "Metadata_Site": row["site"]})+ destination.parent.mkdir(parents=True, exist_ok=True)+ with destination.open("w", newline="", encoding="utf-8") as handle:+ writer = csv.DictWriter(handle, fieldnames=list(output[0]))+ writer.writeheader()+ writer.writerows(output)+ return {"images": qc, "intensity_scaling": "integer dtype maximum (255 or 65535)",+ "warnings": [f"{x['sample_id']}: saturated pixels" for x in qc if x["saturated_fraction"] > 0.01]}+++def summarize(directory: Path, expected_samples: list[str] | None = None) -> dict:+ with (directory / "Image.csv").open(newline="") as handle:+ images = list(csv.DictReader(handle))+ with (directory / "Nuclei.csv").open(newline="") as handle:+ objects = list(csv.DictReader(handle))+ if not images:+ raise ValueError("CellProfiler produced no image measurements")+ actual_samples = [r["Metadata_Sample"] for r in images]+ if len(actual_samples) != len(set(actual_samples)):+ raise ValueError("Duplicate image metadata in output")+ if expected_samples is not None and set(actual_samples) != set(expected_samples):+ raise ValueError("Output sample identities differ from the input manifest")+ measurements, warnings = [], []+ for row in images:+ if any(float(value) != 0 for key, value in row.items() if key.startswith("ModuleError_")):+ raise ValueError("CellProfiler reported a failed module; inspect cellprofiler.log")+ subset = [obj for obj in objects if obj["ImageNumber"] == row["ImageNumber"]]+ count = int(float(row["Count_Nuclei"]))+ if count != len(subset):+ raise ValueError("Image count and per-object rows disagree")+ intensities = [float(obj["Intensity_MeanIntensity_DNA"]) for obj in subset]+ if any(not math.isfinite(v) or not 0 <= v <= 1 for v in intensities):+ raise ValueError("Nonfinite or out-of-range normalized intensities")+ if count == 0:+ warnings.append(f"{row['Metadata_Sample']}: zero nuclei; inspect overlay and threshold")+ measurements.append({"sample_id": row["Metadata_Sample"], "nuclei": count,+ "mean_nuclear_intensity": sum(intensities) / count if count else None})+ if sum(item["nuclei"] for item in measurements) != len(objects):+ raise ValueError("Orphan or duplicate object rows")+ return {"measurements": measurements, "warnings": warnings}+++def run(manifest: Path, output: Path, executable: str, pipeline: Path) -> dict:+ if output.exists() and any(output.iterdir()):+ raise ValueError("Use an empty output directory to keep runs distinct")+ output.mkdir(parents=True, exist_ok=True)+ qc = prepare(manifest.resolve(), output / "load_data.csv")+ command = [executable, "-c", "-r", "-p", str(pipeline.resolve()), "--data-file",+ str((output / "load_data.csv").resolve()), "-o", str(output.resolve())]+ with (output / "cellprofiler.log").open("w") as log:+ subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True)+ result = summarize(output, [r["sample_id"] for r in qc["images"]])+ result.update({"input_qc": qc, "command": command,+ "pipeline_sha256": hashlib.sha256(pipeline.read_bytes()).hexdigest()})+ (output / "assay_qc.json").write_text(json.dumps(result, indent=2) + "\n")+ return result+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest="action", required=True)+ prep = sub.add_parser("prepare", help="Validate CSV manifest and create LoadData CSV")+ prep.add_argument("manifest", type=Path)+ prep.add_argument("output_csv", type=Path)+ analysis = sub.add_parser("run", help="Execute CellProfiler and check its exported measurements")+ analysis.add_argument("manifest", type=Path)+ analysis.add_argument("output", type=Path)+ analysis.add_argument("--executable", default="cellprofiler")+ analysis.add_argument("--pipeline", type=Path,+ default=Path(__file__).resolve().parents[1] / "assets" / "nuclei.cppipe")+ summary = sub.add_parser("summarize", help="Check existing Image.csv and Nuclei.csv")+ summary.add_argument("output", type=Path)+ args = parser.parse_args()+ try:+ if args.action == "prepare":+ result = prepare(args.manifest, args.output_csv)+ elif args.action == "run":+ result = run(args.manifest, args.output, args.executable, args.pipeline)+ else:+ result = summarize(args.output)+ except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as exc:+ parser.exit(1, f"Error: {exc}\n")+ print(json.dumps(result, indent=2))+++if __name__ == "__main__":+ main()diff --git a/skills/mageck/SKILL.md b/skills/mageck/SKILL.mdnew file mode 100644index 00000000..7006e136--- /dev/null+++ b/skills/mageck/SKILL.md@@ -0,0 +1,97 @@+---+name: mageck+description: Analyzes pooled CRISPR screen FASTQ reads and guide-count matrices with MAGeCK, validates guide libraries and contrasts, measures replicate and library QC, and produces gene hit rankings with effect sizes and FDR. Use for new knockout, CRISPRi, or CRISPRa screen analysis, enrichment or depletion contrasts, and MAGeCK count/test workflows; existing public dependency-score lookup belongs to DepMap.+license: MIT+compatibility: Requires Python 3.10+ for the helper and MAGeCK 0.5.9.5 with its compiled RRA executable for analysis. Tested runtime uses Python 3.11, NumPy 1.26.4 and SciPy 1.13.1. Source installation needs a C++ compiler; network is needed only for installation. No credentials.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ upstream-version: "0.5.9.5"+---++# MAGeCK pooled-screen analysis++## When to use++Use this skill to count existing sequencing reads against a supplied guide library or compare+already-counted pooled screens. Deliver the count matrix, QC, guide and gene results, contrast+provenance, and a short interpretation of enrichment/depletion. This workflow analyzes screens;+it does not design guides or infer gene function from a hit alone.++## Runtime++The tested source installation and external-runtime caveat are in+[references/runtime.md](references/runtime.md). Verify both `mageck --version` and+`mageck test --help` before an analysis. The bundled Python helper is standard-library only.+MAGeCK itself also needs NumPy, SciPy, and the `RRA` binary. PDF/R reporting is optional and not+needed by the helper.++## Workflow++1. Establish the library version, perturbation modality, sample names, selection direction,+ biological replicates, baseline material, time point, and batch. Separate sequencing lanes+ from independent biological replicates. A plasmid baseline and a cell day-zero baseline+ answer different questions. Require an explicit treatment/control contrast; the helper+ never silently assigns all unused samples to the control group.+2. Validate a **headerless TSV library** containing guide ID, DNA sequence, gene. IDs and+ sequences must be unique. The helper rejects ambiguous sequences and any count/library+ ID or gene mismatch; resolve intentional multi-target guides explicitly upstream.+3. For FASTQ, inspect read structure and known guide sequences to establish trimming and+ orientation. Use MAGeCK `count`, with one space-separated argument per biological sample;+ comma-join lanes only when they are technical replicates of that same sample. Preserve+ unmapped-read and count-summary evidence when mapping is poor. A zero-count guide remains+ in the library; do not drop it to improve QC.+4. Run QC before statistical testing. Review library representation, median reads per guide,+ zero fractions, Gini coefficients, and within-condition replicate correlations. The+ helper's 10% zero and 0.8 correlation flags are review prompts, not universal acceptance+ thresholds. High correlation can coexist with systematic artifacts. Read depth is not+ experimental cell coverage.+5. Choose normalization based on the screen. Median normalization assumes most guides are+ stable. For a strong global shift, supplied validated negative-control guides may support+ `--normalization control`. These must be **guide IDs**, one per line; a gene list is not+ interchangeable. Biological control samples and negative-control guides serve different+ roles. Record their origin and check their count distribution.+6. Use `test` for a two-group comparison. `--paired` requires both lists in corresponding+ biological order and equal length; matching lengths alone do not establish pairing.+ The helper reports genes at the requested FDR in both directions and retains full rankings.+ For a multi-factor design, see [references/design.md](references/design.md); do not collapse+ batches or time courses into an unjustified two-group test.+7. Inspect guide concordance for leading genes, essential-gene recovery where appropriate,+ negative controls, replicate consistency, and copy-number artifacts in nuclease knockout+ screens. Report effect sizes alongside FDR. An enriched guide can indicate resistance,+ growth advantage, or a sampling artifact depending on the selection; depletion need not+ imply universal essentiality. Lack of replication or low-count guides weakens inference.++## Commands++Run paths relative to the installed skill directory. Input and output paths refer to the user's+analysis directory. The helper refuses to reuse an existing results directory.++```bash+# Single-end guide reads; trim and orientation must match the user's library preparation.+mageck count -l library.tsv --fastq c1.fastq.gz c2.fastq.gz t1.fastq.gz t2.fastq.gz \+ --sample-label c1,c2,t1,t2 --trim-5 0 --norm-method none -n counts++python scripts/screen_analysis.py qc --counts counts.count.txt --library library.tsv \+ --control c1 c2 --treatment t1 t2 --output qc.json++python scripts/screen_analysis.py test --counts counts.count.txt --library library.tsv \+ --control c1 c2 --treatment t1 t2 --normalization median --fdr 0.05 --output result+```++The FASTQ command structure was exercised with a synthetic two-guide library: counts of 30 and+12 were recovered exactly. The two-group helper was exercised with 500 guides and two replicates+per condition; the known depleted and enriched genes ranked first in their respective directions+and passed FDR 0.05. These synthetic tests establish execution and signal direction, not statistical+calibration for a real screen. Real-file paths above are illustrative.++`result/report.json` records count/library/control-guide SHA-256, control-guide IDs, MAGeCK version, actual arguments, QC, hit direction,+FDR, log fold change and rank. `screen.gene_summary.txt`, `screen.sgrna_summary.txt`, normalized+counts and the execution log retain the complete evidence. Include the original library, sample+sheet and negative-control list in the analysis handoff; the count checksum cannot reconstruct them.++## Primary references++- [MAGeCK usage and command semantics](https://sourceforge.net/p/mageck/wiki/usage/)+- [Official installation guidance](https://sourceforge.net/p/mageck/wiki/install/)+- [Input formats](https://sourceforge.net/p/mageck/wiki/input/)diff --git a/skills/mageck/references/design.md b/skills/mageck/references/design.mdnew file mode 100644index 00000000..06779b0e--- /dev/null+++ b/skills/mageck/references/design.md@@ -0,0 +1,36 @@+# Contrasts and multi-condition designs++For RRA, explicitly list treatment and control **sample labels**, preserving biological replicate+identity. Do not sum independent cultures; do combine separate sequencing lanes of one library+preparation at counting. The helper checks labels, disjoint groups, paired lengths, negative-control+membership, nonnegative integer counts, duplicate IDs and count/library equality. It cannot verify+whether sample labels represent the biology described by the user.++For a time course, genotype-by-treatment interaction or batch-adjusted comparison, MAGeCK MLE+uses a design matrix. Consult the [official MLE tutorial](https://sourceforge.net/p/mageck/wiki/demo/)+and the installed `mageck mle --help`. This route is documented upstream but was **not executed**+in this skill's tests. An illustrative two-condition design is:++```text+Samples baseline treatment+c1 1 0+c2 1 0+t1 1 1+t2 1 1+```++Write an actual tab-delimited matrix, with its sample rows in exactly the count-table column order.+The baseline column is the intercept; all-zero columns and aliased factors make coefficients+unidentifiable. Compute design rank, inspect condition/batch confounding, and preserve the intended+coefficient interpretation before running. A design matrix cannot recover missing replication or+separate perfectly confounded batch and treatment effects.++```bash+# Illustrative, not part of the exercised count/test helper.+mageck mle -k counts.count.txt -d design.tsv -n mle --norm-method median+```++For either model, retain the complete gene table, direction-specific FDR, effect size, guide support,+normalization choice, sample inclusion and any exclusions. Avoid interpreting FDR as an individual+hit's probability of being false. Validate leading hits using independent evidence rather than+claiming that a synthetic fixture calibrates the experiment.diff --git a/skills/mageck/references/runtime.md b/skills/mageck/references/runtime.mdnew file mode 100644index 00000000..7a1ea186--- /dev/null+++ b/skills/mageck/references/runtime.md@@ -0,0 +1,28 @@+# Tested source runtime++MAGeCK 0.5.9.5 was downloaded from the official SourceForge release and built on macOS ARM64+with Python 3.11, NumPy 1.26.4, SciPy 1.13.1, setuptools 69.5.1, and the system C++ compiler.+Both `count` and `test` (including compiled RRA) ran successfully. MAGeCK is not a PyPI dependency+installed by this repository's isolated test environment; those integration tests skip when the+executable is absent. Put the complete source/conda environment's `bin` on PATH to run them.++The following is the tested installation pattern; choose an environment directory outside the skill.++```bash+uv venv --python 3.11 mageck-env+uv pip install --python mageck-env/bin/python numpy==1.26.4 scipy==1.13.1 setuptools==69.5.1+curl -fL 'https://sourceforge.net/projects/mageck/files/0.5/mageck-0.5.9.5.tar.gz/download' -o mageck.tar.gz+tar -xzf mageck.tar.gz+# This archive contains liulab-mageck-c491c3874dca, not a directory named mageck-0.5.9.5.+cd liulab-mageck-c491c3874dca+../mageck-env/bin/python setup.py install+cd ..+export PATH="$PWD/mageck-env/bin:$PATH"+mageck --version+mageck test --help+```++The upstream installation uses legacy setup.py and emits setuptools deprecation messages. Its+source package compiles RRA and mageckGSEA. A wrapper-only installation without these binaries+cannot perform gene ranking. Bioconda is another upstream-documented route, but was not exercised+for this skill. R/LaTeX rendering and MLE are outside the tested integration surface.diff --git a/skills/mageck/scripts/screen_analysis.py b/skills/mageck/scripts/screen_analysis.pynew file mode 100644index 00000000..69389b98--- /dev/null+++ b/skills/mageck/scripts/screen_analysis.py@@ -0,0 +1,191 @@+"""Validate pooled-screen inputs, quantify QC, and execute MAGeCK RRA testing."""+from __future__ import annotations++import argparse+import csv+from collections import Counter+import hashlib+import itertools+import json+import math+from pathlib import Path+import shutil+import statistics+import subprocess+import tempfile+++def read_counts(path):+ with Path(path).open(newline="") as handle:+ rows = list(csv.reader(handle, delimiter="\t"))+ if len(rows) < 2 or len(rows[0]) < 4:+ raise ValueError("Expected sgRNA, Gene, and at least two sample columns")+ samples = rows[0][2:]+ if len(set(samples)) != len(samples) or any(not x or ',' in x or any(c.isspace() for c in x) for x in samples):+ raise ValueError("Sample labels must be unique, nonempty, and free of commas/whitespace")+ guides, genes, counts = [], [], []+ for line, row in enumerate(rows[1:], 2):+ if len(row) != len(rows[0]) or not row[0] or not row[1]:+ raise ValueError(f"Invalid row {line}: missing fields")+ try:+ values = [int(v) for v in row[2:]]+ except ValueError as error:+ raise ValueError(f"Row {line}: counts must be integers") from error+ if min(values) < 0:+ raise ValueError(f"Row {line}: negative count")+ guides.append(row[0]); genes.append(row[1]); counts.append(values)+ if len(set(guides)) != len(guides):+ raise ValueError("Duplicate guide IDs")+ if any(sum(col) == 0 for col in zip(*counts)):+ raise ValueError("A sample has zero total reads")+ return samples, guides, genes, counts+++def read_library(path):+ """MAGeCK headerless tab-separated guide, sequence, gene library."""+ library, sequences = {}, set()+ with Path(path).open(newline="") as handle:+ for line, row in enumerate(csv.reader(handle, delimiter="\t"), 1):+ if len(row) != 3 or not all(row):+ raise ValueError(f"Library row {line}: expected guide, sequence, gene (no header)")+ guide, seq, gene = row+ seq = seq.upper()+ if set(seq) - set("ACGT") or guide in library or seq in sequences:+ raise ValueError(f"Library row {line}: invalid DNA, duplicate ID, or ambiguous sequence")+ library[guide] = (seq, gene); sequences.add(seq)+ if not library:+ raise ValueError("Empty library")+ return library+++def gini(values):+ ordered = sorted(values)+ return 2 * sum(i * x for i, x in enumerate(ordered, 1)) / (len(ordered) * sum(ordered)) - (len(ordered) + 1) / len(ordered)+++def correlation(a, b):+ a = [math.log2(x + 1) for x in a]; b = [math.log2(x + 1) for x in b]+ mean_a, mean_b = statistics.mean(a), statistics.mean(b)+ ac = [x - mean_a for x in a]; bc = [x - mean_b for x in b]+ denominator = math.sqrt(sum(x*x for x in ac) * sum(x*x for x in bc))+ return sum(x*y for x, y in zip(ac, bc)) / denominator if denominator else None+++def inspect_screen(count_path, control, treatment, library_path=None, controls_path=None, paired=False):+ samples, guides, genes, counts = read_counts(count_path)+ if not control or not treatment or len(set(control + treatment)) != len(control + treatment):+ raise ValueError("Control and treatment must be nonempty, disjoint lists without duplicates")+ if not set(control + treatment) <= set(samples):+ raise ValueError("Unknown sample label in contrast")+ if paired and len(control) != len(treatment):+ raise ValueError("Paired contrasts need equal counts in matching biological order")+ if library_path:+ library = read_library(library_path)+ if set(library) != set(guides):+ raise ValueError("Count/library guide sets differ; retain zero-count library guides")+ if any(library[g][1] != gene for g, gene in zip(guides, genes)):+ raise ValueError("Count/library gene annotations differ")+ control_guides = []+ if controls_path:+ control_guides = Path(controls_path).read_text().splitlines()+ if not control_guides or len(set(control_guides)) != len(control_guides) or not set(control_guides) <= set(guides):+ raise ValueError("Control-guide file must contain unique known IDs, one per line")+ control_rows = [row for guide, row in zip(guides, counts) if guide in set(control_guides)]+ if any(sum(col) == 0 for col in zip(*control_rows)):+ raise ValueError("Control-guide counts are zero in a sample")+ columns = dict(zip(samples, zip(*counts)))+ qc = {s: {"reads": sum(v), "zero_fraction": v.count(0)/len(v),+ "median_reads_per_guide": statistics.median(v), "gini": gini(v)} for s, v in columns.items()}+ replicate_correlations = {f"{a} vs {b}": correlation(columns[a], columns[b])+ for group in (control, treatment) for a, b in itertools.combinations(group, 2)}+ guide_multiplicity = dict(Counter(genes))+ warnings = []+ if min(len(control), len(treatment)) < 2:+ warnings.append("A condition lacks biological replication; dispersion and reproducibility are limited")+ if any(v["zero_fraction"] > .1 for v in qc.values()):+ warnings.append("More than 10% zero-count guides in a sample: review bottlenecks and mapping")+ if any(v is not None and v < .8 for v in replicate_correlations.values()):+ warnings.append("Low within-condition log-count correlation (<0.8): inspect replicate effects")+ if min(guide_multiplicity.values()) < 3:+ warnings.append("Some genes have fewer than three guides; inspect guide concordance")+ return {"samples": qc, "guides": len(guides), "genes": len(guide_multiplicity),+ "guides_per_gene": guide_multiplicity, "within_condition_log2_count_correlations": replicate_correlations,+ "control": control, "treatment": treatment, "paired": paired,+ "control_guides": len(control_guides), "warnings": warnings}+++def run_test(count_path, output, control, treatment, library_path=None, controls_path=None,+ paired=False, normalization="median", executable="mageck", fdr=.05):+ if not 0 < fdr < 1:+ raise ValueError("FDR must lie between zero and one")+ if normalization not in {"median", "total", "control", "none"}:+ raise ValueError("Unsupported normalization")+ if normalization == "control" and not controls_path:+ raise ValueError("Control normalization requires control-guide IDs")+ qc = inspect_screen(count_path, control, treatment, library_path, controls_path, paired)+ binary = shutil.which(executable)+ if binary is None:+ raise RuntimeError("MAGeCK executable not found; install MAGeCK 0.5.9.5 and its RRA binary")+ output = Path(output)+ output.mkdir(parents=True, exist_ok=False)+ version = subprocess.run([binary, "--version"], text=True, capture_output=True, check=True).stdout.strip()+ # Upstream uses shell commands internally. Fixed staging names avoid its path quoting problems.+ with tempfile.TemporaryDirectory(prefix="mageck-analysis-") as temporary:+ work = Path(temporary)+ shutil.copyfile(count_path, work / "counts.tsv")+ command = [binary, "test", "-k", "counts.tsv", "-c", ",".join(control), "-t", ",".join(treatment),+ "--norm-method", normalization, "--normcounts-to-file", "-n", "screen"]+ if paired:+ command.append("--paired")+ if controls_path:+ shutil.copyfile(controls_path, work / "controls.txt")+ command += ["--control-sgrna", "controls.txt"]+ process = subprocess.run(command, cwd=work, capture_output=True, text=True, check=False)+ (output / "execution.log").write_text(process.stdout + process.stderr)+ for artifact in work.glob("screen.*"):+ if artifact.is_file():+ shutil.copyfile(artifact, output / artifact.name)+ if process.returncode or not (output / "screen.gene_summary.txt").is_file():+ raise RuntimeError(f"MAGeCK did not complete; inspect {output / 'execution.log'}")+ with (output / "screen.gene_summary.txt").open() as handle:+ rows = list(csv.DictReader(handle, delimiter="\t"))+ hits = {direction: [{"gene": r["id"], "fdr": float(r[f"{direction}|fdr"]),+ "lfc": float(r[f"{direction}|lfc"]), "rank": int(r[f"{direction}|rank"])}+ for r in rows if float(r[f"{direction}|fdr"]) <= fdr] for direction in ("neg", "pos")}+ report = {"mageck_version": version, "command": command, "count_sha256": hashlib.sha256(Path(count_path).read_bytes()).hexdigest(),+ "library_sha256": hashlib.sha256(Path(library_path).read_bytes()).hexdigest() if library_path else None,+ "control_guides_sha256": hashlib.sha256(Path(controls_path).read_bytes()).hexdigest() if controls_path else None,+ "control_guide_ids": Path(controls_path).read_text().splitlines() if controls_path else [],+ "fdr_threshold": fdr, "qc": qc, "hits": hits}+ (output / "report.json").write_text(json.dumps(report, indent=2) + "\n")+ return report+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("mode", choices=["qc", "test"])+ parser.add_argument("--counts", required=True, type=Path)+ parser.add_argument("--control", nargs="+", required=True)+ parser.add_argument("--treatment", nargs="+", required=True)+ parser.add_argument("--library", type=Path)+ parser.add_argument("--control-guides", type=Path)+ parser.add_argument("--paired", action="store_true")+ parser.add_argument("--normalization", choices=["median", "total", "control", "none"], default="median")+ parser.add_argument("--output", type=Path, help="New directory for test output; JSON path for QC")+ parser.add_argument("--mageck", default="mageck")+ parser.add_argument("--fdr", type=float, default=.05)+ args = parser.parse_args()+ if args.mode == "test":+ if args.output is None:+ parser.error("test requires --output")+ report = run_test(args.counts, args.output, args.control, args.treatment, args.library,+ args.control_guides, args.paired, args.normalization, args.mageck, args.fdr)+ else:+ report = inspect_screen(args.counts, args.control, args.treatment, args.library, args.control_guides, args.paired)+ if args.output:+ args.output.write_text(json.dumps(report, indent=2) + "\n")+ print(json.dumps(report, indent=2))+++if __name__ == "__main__":+ main()diff --git a/skills/nmrglue/SKILL.md b/skills/nmrglue/SKILL.mdnew file mode 100644index 00000000..034fd718--- /dev/null+++ b/skills/nmrglue/SKILL.md@@ -0,0 +1,126 @@+---+name: nmrglue+description: Processes calibrated one-dimensional complex NMR free-induction decays with nmrglue into phased spectra, peak candidates, and signed integration regions. Use for raw 1D NMR processing, ppm-axis verification, apodization, Fourier transformation, manual phasing, baseline correction, or reproducible spectral integration.+license: MIT+compatibility: Requires Python 3.12+, nmrglue, NumPy, and SciPy. Installation needs network access; processing is local and needs no credentials.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ tested-package-version: "0.12"+---++# nmrglue: calibrated 1D FID processing++## When to use++Use for a uniformly sampled complex 1D FID whose acquisition parameters and complex+frequency convention are available. The helper produces a descending ppm spectrum,+positive peak candidates, signed region integrals, and a reproducible processing report.+It does not identify compounds or assign resonances.++The executable accepts a NumPy `.npz` containing exactly one complex `fid` array or a+canonical 1D complex time-domain NMRPipe file. NMRPipe reading is tested with a synthetic+write/read round trip and known-spectrum recovery. Experimental Bruker, Varian, and JEOL+imports are **not verified by this suite**. For those formats, first inspect the relevant+nmrglue reader and acquisition metadata. Opening a converted file does not validate the+original acquisition decoding.+Read [references/acquisition-and-validation.md](references/acquisition-and-validation.md)+for conversion boundaries, axis calibration, and quantitative limits.++## Workflow++1. Preserve the raw FID. Establish spectral width in Hz, positive observation frequency+ in MHz, carrier in ppm, observed nucleus, and the sign convention from the acquisition+ or a known reference. Determine whether digital-filter/group-delay removal has already+ occurred. Do not infer these from array length or typical instrument defaults.+2. Copy [assets/processing.json](assets/processing.json) and replace its synthetic example+ values with the measured parameters and explicit processing choices. Its sign `-i`+ means a resonance at offset `f = (ppm - carrier_ppm) * observation_mhz` has time+ dependence `exp(-2*pi*i*f*t)`. Select `+i` only for the opposite convention; the helper+ conjugates it before processing. Validate with a known reference peak.+3. Choose nonnegative exponential line broadening (Hz), an even zero-filled size at+ least as large as the acquired FID, first-point scaling, and phase angles.+ Zero filling improves interpolation, not acquired spectral resolution.+ First-point scaling `0.5` is suitable for the supplied causal synthetic example;+ acquisition and prior preprocessing may require another value.+4. Run the helper, inspect the real and imaginary spectra, and revise manual phase if+ needed. `phase0_deg + phase1_deg * index / zero_fill_points` is applied after FT;+ index zero is the high-ppm edge. There is no implicit pivot or automatic phase estimate.+5. Only fit a linear baseline when explicitly supplied ppm regions are signal-free.+ Set `baseline` to `linear` and add `baseline_regions_ppm` containing at least two+ regions. Inspect residuals and broad peaks; fitting through signals biases integrals.+6. Compare peak positions with references, inspect peak candidates for artifacts, and+ integrate specified regions. Report overlapped peaks as overlapped. Preserve negative+ areas as diagnostic evidence of phase/baseline problems instead of taking absolute values.++## Execute++Tested with Python 3.12, nmrglue 0.12, NumPy 2.5.3, and SciPy 1.18.1:++```bash+uv run --no-project --python 3.12 --with nmrglue==0.12 --with numpy==2.5.3 --with scipy==1.18.1 \+ python skills/nmrglue/scripts/process_1d.py fid.npz processing.json nmr-result+```++Paths assume the collection root. Adjust them when installed elsewhere. The output+directory must be new, so repeated processing keeps previous results reviewable.++For an existing 1D NMRPipe FID, add `--input-format nmrpipe` and supply its path in place+of `fid.npz`. The helper requires the canonical FDF2 direct dimension, complex quadrature,+a time-domain flag, and agreement between header and JSON spectral width, observation+frequency, and carrier. JSON settings remain explicit; a mismatch fails instead of silently+recalibrating. The nucleus/complex sign and previous digital-filter corrections still need+acquisition evidence. A time-domain flag alone does not establish an unprocessed FID.++This executable synthetic example matches the supplied settings, generates resonances+at 3 and 7 ppm in a 1:2 amplitude ratio, and does not represent an experimental sample:++```python+import numpy as np++t = np.arange(8192) / 4000.0+fid = sum(a * np.exp(-np.pi * 2.0 * t)+ * np.exp(-2j * np.pi * (ppm - 5.0) * 400.0 * t)+ for ppm, a in [(3.0, 1.0), (7.0, 2.0)])+np.savez("fid.npz", fid=fid)+```++Run it with `assets/processing.json` as the settings argument. The repository suite+executes this signal and the CLI, checks both peak locations within 0.001 ppm, checks+integral ratio and analytic area, and checks phase and baseline recovery. The NMRPipe+round-trip test writes this FID using `ng.pipe.create_dic`/`ng.pipe.write`, reads it through+the CLI, and verifies the recovered peaks and integral ratio. Processed frequency-domain+files and conflicting calibration metadata are rejected.++## Deliverables and interpretation++- `spectrum.csv`: descending ppm, real signal after baseline correction, phased imaginary+ signal, and the fitted real baseline. Plot NMR with the high-ppm end on the left.+- `report.json`: input/settings SHA-256, package versions, all settings, acquired duration,+ zero-filled digital spacing, positive peak candidates, and signed region areas.++Integrals use endpoint interpolation and trapezoidal integration along increasing ppm;+area units are arbitrary signal times ppm, independent of display direction. Regions+outside the sampled ppm axis fail rather than being silently clipped. Peak prominence+is a fraction of the largest positive real intensity; it is not a noise-derived detection+limit. Strong solvent signals can obscure weak candidates at the default threshold.++For quantitative NMR, additionally establish relaxation delay, pulse angle, saturation,+receiver behavior, internal/external reference amount, and integration uncertainty.+The helper does not calculate concentrations or correct unequal relaxation. Preserve+these limits with the result rather than converting arbitrary areas to molecule counts.++## Upstream contracts++- [Processing functions](https://nmrglue.readthedocs.io/en/latest/reference/proc_base.html):+ exponential apodization, zero filling, FFT, and phase operations.+- [File and axis utilities](https://nmrglue.readthedocs.io/en/latest/reference/fileiobase.html):+ unit conversion uses spectral width in Hz, observation frequency in MHz, carrier in Hz.+- [NMRPipe reader/writer](https://nmrglue.readthedocs.io/en/latest/reference/pipe.html):+ the validated ingestion path is a synthetic canonical 1D time-domain round trip.+- [nmrglue project](https://github.com/jjhelmus/nmrglue): upstream source and format readers.++The hosted `latest` documentation identified itself as 0.9-dev when checked; the actual+0.12 package APIs and numerical behavior were tested. Multidimensional processing,+nonuniform sampling, automated assignment, and experimental vendor imports remain outside+this helper's validated scope.diff --git a/skills/nmrglue/assets/processing.json b/skills/nmrglue/assets/processing.jsonnew file mode 100644index 00000000..fdc82040--- /dev/null+++ b/skills/nmrglue/assets/processing.json@@ -0,0 +1,15 @@+{+ "spectral_width_hz": 4000.0,+ "observation_mhz": 400.0,+ "carrier_ppm": 5.0,+ "nucleus": "1H",+ "fid_sign": "-i",+ "line_broadening_hz": 1.0,+ "zero_fill_points": 32768,+ "first_point_scale": 0.5,+ "phase0_deg": 0.0,+ "phase1_deg": 0.0,+ "baseline": "none",+ "integration_regions_ppm": [[2.7, 3.3], [6.7, 7.3]],+ "peak_prominence_fraction": 0.05+}diff --git a/skills/nmrglue/references/acquisition-and-validation.md b/skills/nmrglue/references/acquisition-and-validation.mdnew file mode 100644index 00000000..52db15d8--- /dev/null+++ b/skills/nmrglue/references/acquisition-and-validation.md@@ -0,0 +1,63 @@+# Acquisition evidence and integration checks++## Before converting a vendor file++A readable array is not proof that it is a correctly decoded FID. Confirm complex+quadrature, direct-dimension length, acquisition order, digital filtering/group delay,+spectral width, observation frequency, transmitter offset, and observed nucleus from+vendor parameters. Keep the vendor files alongside the conversion record. Hash the+source acquisition files and record the reader/version and any corrections; the helper+hashes the supplied NPZ or NMRPipe file and processing JSON, not an earlier vendor acquisition.++A processed frequency-domain file must not be fed through this FID pipeline. Echo,+nonuniform sampling, real-only acquisition, indirect dimensions, and data requiring+receiver-specific phase cycling need a different processing derivation. The bundled+helper rejects real arrays and multidimensional arrays but cannot distinguish an+incorrectly labeled complex spectrum from a complex FID.++For Bruker, digital-filter removal is an acquisition-specific operation, not a universal+first step. Determine whether it has already been applied; applying it twice distorts+phase. Upstream `bruker.read` and `bruker.remove_digital_filter` are possible building+blocks, but no vendor-reader workflow is claimed as tested here. Consult the+[Bruker reference](https://nmrglue.readthedocs.io/en/latest/reference/bruker.html) before+adapting it and verify against a trusted processed reference.++## Verify frequency sign before fitting phase++The helper pairs `proc_base.fft` with the descending `unit_conversion.ppm_scale()` axis.+The canonical FID therefore uses the negative complex exponential for positive ppm+offsets. If a known reference appears mirrored about the carrier, revisit quadrature+and sign convention. Reversing a plotted axis does not correct the data-to-ppm mapping.+A reference offset correction should update the carrier and be recorded, rather than+moving a plotted label without moving integration limits.++## Processing comparisons that change conclusions++- Reprocess with less line broadening to see whether nearby peaks remain separable.+- Compare no-baseline and justified signal-free baseline regions; broad resonances can+ be mistaken for a baseline. First-order polynomial correction is intentionally narrow.+- Inspect the imaginary channel during manual phase adjustment. A visually positive+ spectrum alone does not establish absorption-mode phase across the full bandwidth.+- Vary integration bounds and baseline anchors to assess area stability. Overlap,+ truncation ringing, solvent suppression, and acquisition dead time may dominate error.+- Treat automatic local maxima as candidate peaks. Negative peaks, multiplet grouping,+ line-shape fitting, isotope patterns, and assignments are not performed.++The synthetic regression signal has two exponentially decaying components with identical+linewidth and known amplitude ratio. Its exact area benchmark is a mathematical processing+check, not external validation of a spectrometer, sample preparation, or quantitative assay.++## Supported NMRPipe boundary++The NMRPipe reader requires one direct FDF2 dimension, complex samples, an untransformed+FTFLAG, and a header size matching the decoded complex array. Spectral width (Hz),+observation frequency (MHz), and carrier (ppm) must match the explicit processing JSON+within float32 header rounding tolerance. Selected header fields are preserved in the+report. The sign convention is still explicit: the file format alone does not establish+the acquisition's physical frequency sign or whether vendor conversion conjugated it.++Only synthetic canonical files generated with nmrglue were round-trip validated. This+exercises the actual binary reader and recovered spectral coordinates, but does not+establish that every experimental converter writes equivalent headers or samples.+Digital-filter removal and earlier apodization are not inferred or undone. Check the+upstream acquisition and conversion record before applying the processing settings.diff --git a/skills/nmrglue/scripts/process_1d.py b/skills/nmrglue/scripts/process_1d.pynew file mode 100644index 00000000..f0446165--- /dev/null+++ b/skills/nmrglue/scripts/process_1d.py@@ -0,0 +1,178 @@+#!/usr/bin/env python3+"""Process a calibrated complex 1D FID; no acquisition settings are inferred."""+from __future__ import annotations++import argparse+import csv+import hashlib+import json+from pathlib import Path++import nmrglue as ng+import numpy as np+import scipy+from scipy.signal import find_peaks+++def finite_number(value, name, positive=False):+ if isinstance(value, bool) or not isinstance(value, (int, float)):+ raise ValueError(f"{name} must be a number")+ number = float(value)+ if not np.isfinite(number) or (positive and number <= 0):+ raise ValueError(f"{name} must be finite" + (" and positive" if positive else ""))+ return number+++def regions_in_axis(regions, ppm):+ result = []+ for region in regions:+ if len(region) != 2:+ raise ValueError("Each region needs two ppm bounds")+ low, high = sorted(finite_number(v, "region bound") for v in region)+ if low == high or low < ppm.min() or high > ppm.max():+ raise ValueError("Region must have width and lie wholly inside the ppm axis")+ result.append((low, high))+ return result+++def process(fid, settings):+ fid = np.asarray(fid)+ if fid.ndim != 1 or len(fid) < 16 or not np.iscomplexobj(fid):+ raise ValueError("fid must be a one-dimensional complex array with at least 16 points")+ if not np.isfinite(fid).all():+ raise ValueError("fid contains nonfinite values")+ allowed = {"spectral_width_hz", "observation_mhz", "carrier_ppm", "nucleus", "fid_sign",+ "line_broadening_hz", "zero_fill_points", "first_point_scale", "phase0_deg",+ "phase1_deg", "baseline", "baseline_regions_ppm", "integration_regions_ppm",+ "peak_prominence_fraction"}+ if set(settings) - allowed:+ raise ValueError(f"Unknown settings: {sorted(set(settings) - allowed)}")+ required = allowed - {"baseline_regions_ppm"}+ if required - set(settings):+ raise ValueError(f"Missing explicit settings: {sorted(required - set(settings))}")+ sw = finite_number(settings["spectral_width_hz"], "spectral_width_hz", True)+ obs = finite_number(settings["observation_mhz"], "observation_mhz", True)+ car = finite_number(settings["carrier_ppm"], "carrier_ppm")+ if not isinstance(settings["nucleus"], str) or not settings["nucleus"].strip():+ raise ValueError("nucleus must identify the observed nucleus")+ if settings["fid_sign"] not in ("-i", "+i"):+ raise ValueError("fid_sign must be '-i' or '+i'")+ lb = finite_number(settings["line_broadening_hz"], "line_broadening_hz")+ if lb < 0:+ raise ValueError("Negative line broadening is unsupported")+ size = settings["zero_fill_points"]+ if isinstance(size, bool) or not isinstance(size, int) or size < len(fid) or size % 2:+ raise ValueError("zero_fill_points must be an even integer at least the FID length")+ first = finite_number(settings["first_point_scale"], "first_point_scale")+ if not 0 <= first <= 1:+ raise ValueError("first_point_scale must be between zero and one")+ p0 = finite_number(settings["phase0_deg"], "phase0_deg")+ p1 = finite_number(settings["phase1_deg"], "phase1_deg")+ fraction = finite_number(settings["peak_prominence_fraction"], "peak_prominence_fraction", True)+ if fraction > 1:+ raise ValueError("peak_prominence_fraction must be at most one")+ data = fid.astype(np.complex128, copy=True)+ if settings["fid_sign"] == "+i":+ data = data.conj()+ data[0] *= first+ data = ng.proc_base.em(data, lb=lb / sw)+ spectrum = ng.proc_base.ps(ng.proc_base.fft(ng.proc_base.zf_size(data, size)), p0=p0, p1=p1)+ ppm = ng.fileiobase.unit_conversion(size, False, sw, obs, car * obs).ppm_scale()+ raw_real = spectrum.real.copy()+ baseline = np.zeros(size)+ regions = regions_in_axis(settings.get("baseline_regions_ppm", []), ppm)+ if settings["baseline"] == "linear":+ mask = np.zeros(size, dtype=bool)+ for low, high in regions:+ mask |= (ppm >= low) & (ppm <= high)+ if mask.sum() < 4 or len(regions) < 2:+ raise ValueError("Linear baseline needs at least two signal-free regions and four points")+ baseline = np.polyval(np.polyfit(ppm[mask], raw_real[mask], 1), ppm)+ elif settings["baseline"] != "none":+ raise ValueError("baseline must be 'none' or 'linear'")+ elif regions:+ raise ValueError("baseline_regions_ppm requires baseline='linear'")+ real = raw_real - baseline+ prominence = fraction * max(float(real.max()), 0)+ indices, properties = find_peaks(real, height=0, prominence=max(prominence, np.finfo(float).tiny))+ peaks = [{"ppm": float(ppm[i]), "height": float(real[i]), "prominence": float(p)}+ for i, p in zip(indices, properties["prominences"])]+ integrals = []+ for low, high in regions_in_axis(settings["integration_regions_ppm"], ppm):+ axis, values = ppm[::-1], real[::-1]+ inside = (axis > low) & (axis < high)+ x = np.concatenate(([low], axis[inside], [high]))+ y = np.concatenate(([np.interp(low, axis, values)], values[inside], [np.interp(high, axis, values)]))+ integrals.append({"low_ppm": low, "high_ppm": high, "area_signal_ppm": float(np.trapezoid(y, x))})+ return {"ppm": ppm, "real": real, "imaginary": spectrum.imag, "baseline": baseline,+ "peaks": peaks, "integrals": integrals, "acquired_points": len(fid),+ "acquisition_time_s": len(fid) / sw, "digital_spacing_hz": sw / size}+++def load_fid(input_path, settings, input_format):+ if input_format == "npz":+ with np.load(input_path, allow_pickle=False) as archive:+ if set(archive.files) != {"fid"}:+ raise ValueError("NPZ archive must contain exactly the complex array 'fid'")+ return archive["fid"], {"format": "npz"}+ if input_format != "nmrpipe":+ raise ValueError("input_format must be npz or nmrpipe")+ header, fid = ng.pipe.read(str(input_path))+ if header["FDDIMCOUNT"] != 1 or header["FDDIMORDER"][0] != 2 or fid.ndim != 1:+ raise ValueError("Only canonical 1D NMRPipe direct-dimension FDF2 files are supported")+ if header["FDF2FTFLAG"] != 0 or header["FDF2QUADFLAG"] != 0 or not np.iscomplexobj(fid):+ raise ValueError("NMRPipe input must be complex and time-domain (FTFLAG=0, QUADFLAG=0)")+ if header["FDSIZE"] != len(fid):+ raise ValueError("NMRPipe header size disagrees with the decoded FID")+ for field, key in (("FDF2SW", "spectral_width_hz"), ("FDF2OBS", "observation_mhz"), ("FDF2CAR", "carrier_ppm")):+ value = finite_number(settings[key], key)+ if not np.isclose(header[field], value, rtol=1e-6, atol=1e-6):+ raise ValueError(f"NMRPipe {field} disagrees with explicit {key}")+ recorded = {key: header[key] for key in ("FDDIMCOUNT", "FDSIZE", "FDF2SW", "FDF2OBS", "FDF2CAR",+ "FDF2LABEL", "FDF2FTFLAG", "FDF2QUADFLAG", "FDF2P0", "FDF2P1")}+ return fid, {"format": "nmrpipe", "header": recorded,+ "reader_validation": "synthetic 1D complex time-domain round trip; no experimental vendor validation"}+++def run(input_path, settings_path, output_dir, input_format="npz"):+ input_path, settings_path, output_dir = map(Path, (input_path, settings_path, output_dir))+ if output_dir.exists():+ raise ValueError("Output directory already exists; choose a new output directory")+ settings = json.loads(settings_path.read_text())+ fid, input_metadata = load_fid(input_path, settings, input_format)+ result = process(fid, settings)+ report = {"schema_version": 1, "input": input_metadata, "input_sha256": hashlib.sha256(input_path.read_bytes()).hexdigest(),+ "settings_sha256": hashlib.sha256(settings_path.read_bytes()).hexdigest(),+ "versions": {"nmrglue": ng.__version__, "numpy": np.__version__, "scipy": scipy.__version__},+ "settings": settings, "acquired_points": result["acquired_points"],+ "acquisition_time_s": result["acquisition_time_s"],+ "digital_spacing_hz": result["digital_spacing_hz"],+ "ppm_order": "descending", "fft_normalization": "unnormalized",+ "phase_law_deg": "phase0_deg + phase1_deg * index / zero_fill_points",+ "peaks": result["peaks"], "integrals": result["integrals"],+ "limits": ["Peak candidates are not assignments", "Integrals are signed arbitrary signal times ppm; no concentration calibration"]}+ output_dir.mkdir(parents=True)+ with (output_dir / "spectrum.csv").open("w", newline="") as handle:+ writer = csv.writer(handle)+ writer.writerow(["ppm", "real", "imaginary", "baseline"])+ writer.writerows(zip(result["ppm"], result["real"], result["imaginary"], result["baseline"]))+ (output_dir / "report.json").write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")+ return report+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("input", type=Path, help="Complex FID: NPZ or canonical 1D NMRPipe")+ parser.add_argument("--input-format", choices=("npz", "nmrpipe"), default="npz")+ parser.add_argument("settings", type=Path, help="Explicit acquisition and processing JSON")+ parser.add_argument("output", type=Path, help="New output directory")+ args = parser.parse_args()+ try:+ report = run(args.input, args.settings, args.output, args.input_format)+ except (ValueError, OSError, KeyError, TypeError) as error:+ parser.error(str(error))+ print(json.dumps({"output": str(args.output), "peak_candidates": len(report["peaks"])}))+++if __name__ == "__main__":+ main()diff --git a/skills/nwb-conversion/SKILL.md b/skills/nwb-conversion/SKILL.mdnew file mode 100644index 00000000..d87a049d--- /dev/null+++ b/skills/nwb-conversion/SKILL.md@@ -0,0 +1,99 @@+---+name: nwb-conversion+description: Converts neuroscience acquisition data to Neurodata Without Borders files with NeuroConv and PyNWB, preserves metadata and timebases, checks evidence-based clock alignment, and produces schema validation, NWB Inspector findings and round-trip checks. Use for NWB conversion and synchronization of planar single-channel two-photon TIFF imaging plus timestamped behavioral position CSV; this skill does not perform spike sorting or claim tested support for arbitrary acquisition formats.+license: MIT+compatibility: Requires Python 3.12 with neuroconv[tiff] 0.10.2, PyNWB 4.2.0, NWB Inspector 0.7.2, roiextractors 0.10.0, tifffile 2026.9.20, zarr 2.18.7 and hdmf-zarr 0.11.3. Local HDF5 file access is required. Network is needed only for installation; no credentials.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ upstream-neuroconv: "0.10.2"+ upstream-pynwb: "4.2.0"+---++# Validated NWB conversion++## Supported streams++The executable workflow covers two explicit input streams in one session:++| Input | NWB representation | Tested constraints |+| --- | --- | --- |+| Two-photon grayscale multi-page TIFF + frame timestamps CSV | Acquisition `TwoPhotonSeries` named `Imaging` through NeuroConv | One channel, one plane, one 2D image per page, fixed shape and dtype |+| Calibrated position CSV (`time_s,x,y`) | Behavior `Position` / `SpatialSeries` through PyNWB | Coordinates in m, cm or mm; converted to meters without temporal resampling |++Other acquisition readers require their own format-specific tests. In particular, this helper does+not decode SpikeGLX, Open Ephys, multichannel TIFF, volumetric TIFF, compressed video, or pixel-to-world+calibration. Do not rename an arbitrary numeric table to a supported stream.++## Install the tested environment++```bash+uv venv --python 3.12 nwb-env+uv pip install --python nwb-env/bin/python 'neuroconv[tiff]==0.10.2' pynwb==4.2.0 \+ nwbinspector==0.7.2 roiextractors==0.10.0 tifffile==2026.9.20 \+ zarr==2.18.7 hdmf-zarr==0.11.3+```++Keep both Zarr pins even for an HDF5-only conversion: NeuroConv 0.10.2 imports its backend+configuration modules at startup, and the tested unconstrained Zarr 3.4.0 installation failed on+`zarr.codec_registry`. The pinned environment ran the real conversion, PyNWB validation and+Inspector successfully on macOS ARM64. The dependency resolver supplies NumPy and HDF5 support.++## Workflow++1. Inventory the actual inputs and acquisition metadata. Identify image plane/channel, optical+ settings, subject/session identifiers, timezone, behavior coordinate system, units and the+ timestamp clock for every stream. Preserve originals. Do not replace missing metadata with+ plausible defaults from a sample config.+2. Copy [assets/session-template.json](assets/session-template.json) beside the raw data and+ replace the explicitly synthetic values. Paths resolve from that JSON file. Read+ [references/input-contract.md](references/input-contract.md) for the exact CSV and metadata+ contract and the pulse-pair variant. TIFF pixels are retained as acquired; a raw arbitrary-unit+ intensity does not become a photon count merely by changing its unit label.+3. Establish the common timebase from acquisition evidence. Frame timestamps must already be+ reference-clock seconds since the timezone-aware session start. For position, provide either+ a documented shared clock or matched synchronization pulses. The helper fits one affine clock+ transform, checks its residual against a specified tolerance, and refuses extrapolation beyond+ the pulse range. It never estimates synchronization from coincident-looking neural/behavioral+ signals. Clock resets or nonlinear drift require an explicitly validated piecewise mapping.+4. Execute the converter. Inputs must have finite, strictly increasing timestamps and matching+ image/timestamp counts. The acquisition samples stay intact; only coordinate units and, when+ evidenced, behavior timestamps are transformed.+5. Read the `.validation.json` alongside the NWB file. Schema compliance, Inspector findings and+ data equality answer different questions. The script exits with an error for schema failures+ and flags critical Inspector findings for review in the report. Review all findings in context;+ successful validation cannot establish that anatomical labels, pulse pairing or calibration+ supplied by the user are correct.+6. Deliver the NWB, validation JSON, original conversion config and an explanation of remaining+ metadata gaps or Inspector findings. No upload or archive submission is part of this workflow.++## Execute++Run the following from the skill directory, with paths to the actual analysis files:++```bash+nwb-env/bin/python scripts/convert_session.py /path/to/session.json --output /path/to/session.nwb+```++`nwb-env` must point to the environment created above; the absolute example input paths are+illustrative. The command refuses to overwrite an existing NWB. Output contains source checksums,+package versions, full supplied metadata, units and clock-fit provenance in both a scratch record+and the validation report. When adapting this command for large data, TIFF writes are iterative+and equality checking loads one frame at a time; position CSV currently loads into memory.++The real-library test converts eight non-square uint16 images with irregular frame timing plus+four position samples, asserts exact pixel and timestamp round trips, and checks centimeter-to-meter+conversion. A second integration test recovers a known 1000-ppm clock drift and 50-ms offset from+three matched pulses. Duplicate timestamps, mismatched frame counts, absent clock evidence,+nonlinear pulse disagreement and missing timezone are rejection cases. The mapping is+TIFF `(time,y,x)` to NWB `(time,x,y)`, explicitly checked against every transposed source page. NWB Inspector flags the short fixture+with a critical orientation heuristic because width exceeds frame count; the report retains that+finding and adds the exact frame/timestamp equality evidence. No transpose is performed merely to+satisfy a longest-axis heuristic.++## Primary references++- [NeuroConv TIFF conversion](https://neuroconv.readthedocs.io/en/stable/conversion_examples_gallery/imaging/tiff.html)+- [NeuroConv temporal alignment](https://neuroconv.readthedocs.io/en/stable/user_guide/temporal_alignment.html)+- [PyNWB](https://github.com/NeurodataWithoutBorders/pynwb)+- [NWB Inspector and its relation to schema validation](https://github.com/NeurodataWithoutBorders/nwbinspector)diff --git a/skills/nwb-conversion/assets/session-template.json b/skills/nwb-conversion/assets/session-template.jsonnew file mode 100644index 00000000..95e7f54b--- /dev/null+++ b/skills/nwb-conversion/assets/session-template.json@@ -0,0 +1,37 @@+{+ "identifier": "synthetic-demonstration-session",+ "session_description": "Synthetic TIFF and position conversion demonstration; replace all experimental metadata",+ "session_start_time": "2020-01-01T12:00:00+00:00",+ "experimenter": [+ "Synthetic Example"+ ],+ "institution": "Synthetic test institution",+ "lab": "Synthetic test lab",+ "subject": {+ "subject_id": "synthetic",+ "species": "Mus musculus",+ "sex": "U",+ "age": "P90D"+ },+ "tiff": "imaging.tif",+ "frame_times_csv": "frames.csv",+ "position_csv": "position.csv",+ "position_unit": "cm",+ "position_reference_frame": "Origin at lower-left arena corner, x right, y up",+ "position_description": "Synthetic calibrated animal position",+ "synchronization": {+ "shared_clock_evidence": "Synthetic fixture: both timestamp vectors generated from one clock"+ },+ "imaging": {+ "device": "SyntheticMicroscope",+ "device_description": "Synthetic two-photon imaging source",+ "description": "Synthetic single-plane single-channel frames",+ "indicator": "synthetic fluorescence",+ "location": "synthetic test plane",+ "unit": "a.u.",+ "excitation_nm": 920.0,+ "emission_nm": 510.0,+ "optical_channel_description": "Synthetic green channel",+ "modality": "two-photon"+ }+}diff --git a/skills/nwb-conversion/references/input-contract.md b/skills/nwb-conversion/references/input-contract.mdnew file mode 100644index 00000000..49b587fc--- /dev/null+++ b/skills/nwb-conversion/references/input-contract.md@@ -0,0 +1,70 @@+# Input contract and clock evidence++Use `assets/session-template.json` as a shape template only. Every experimental field is synthetic.+The helper requires timezone-aware ISO 8601 `session_start_time`, a stable unique `identifier`,+session description, experimenter list, lab, institution and a PyNWB Subject mapping. Keep subject+IDs pseudonymous where the dataset requires it. Do not confuse wall-clock time with elapsed sample+seconds or infer a timezone from the computer running the conversion.++`imaging.modality` must explicitly equal `two-photon`; other or missing modalities are rejected.+`imaging` supplies device name/description, series/plane description, indicator, anatomical location,+intensity unit, excitation and emission wavelengths in **nanometers**, and optical-channel description.+The helper implements a two-photon series; optical metadata must describe that actual acquisition.+Subject fields are passed through to PyNWB and retained in the full provenance config.++Image timestamps CSV has exactly one column:++```csv+time_s+0.0+0.1+0.203+```++There must be one row per grayscale TIFF page. Dropped frames are represented by gaps in the actual+timestamps, not by silently reindexing to a nominal rate. The nominal rate supplied internally to+NeuroConv is only an initial reader parameter; every recorded frame receives its explicit timestamp.+A reordered TIFF must be paired with correspondingly reordered acquisition timestamps before use.++Position CSV has exactly these columns:++```csv+time_s,x,y+0.0,10.0,20.0+0.2,10.3,20.2+0.4,10.8,20.1+```++`position_unit` is `m`, `cm` or `mm`; `position_reference_frame` describes origin and axis directions,+and `position_description` records measurement/calibration context. Pixel inputs are rejected because+a scale, lens correction and coordinate transform cannot be inferred from the CSV alone. Coordinates+are converted once to meters and written with `unit="meters"` and default conversion 1.0.++For a real shared clock, record the acquisition evidence, for example a shared DAQ counter that+actually timestamps both streams. Similar nominal sampling rates and matching file creation dates+are not evidence of shared timing.++```json+"synchronization": {+ "shared_clock_evidence": "Both vectors are acquisition DAQ counter timestamps, converted with its recorded tick rate"+}+```++For separate clocks, provide **already matched** pulse pairs; this helper does not discover+correspondences or correct missing pulses. The CSV columns are `device_time_s,reference_time_s`.+At least three distinct, increasing pairs must span the entire behavior interval. Specify the+maximum acceptable residual in seconds from the experiment's timing precision requirement:++```json+"synchronization": {+ "pulse_pairs_csv": "sync.csv",+ "max_residual_s": 0.001+}+```++The fitted map is `reference_seconds = slope * device_seconds + offset_seconds`.+Inspect residuals and drift over the session before choosing the tolerance. A small least-squares+residual from only three pulses does not rule out unobserved clock jumps between them; record pulse+coverage and acquisition interruptions. Pulse extrapolation is rejected even when a linear fit is+excellent. If pulses fail the model, segment on evidence or use dense event timestamps with an+independently tested converter; do not loosen the tolerance just to make validation pass.diff --git a/skills/nwb-conversion/scripts/convert_session.py b/skills/nwb-conversion/scripts/convert_session.pynew file mode 100644index 00000000..d27854fa--- /dev/null+++ b/skills/nwb-conversion/scripts/convert_session.py@@ -0,0 +1,181 @@+"""Convert planar TIFF imaging and timestamped position CSV to validated NWB."""+from __future__ import annotations++import argparse+import csv+from datetime import datetime+import hashlib+import importlib.metadata+import json+from pathlib import Path+++def digest(path):+ checksum = hashlib.sha256()+ with Path(path).open("rb") as handle:+ for chunk in iter(lambda: handle.read(1024 * 1024), b""):+ checksum.update(chunk)+ return checksum.hexdigest()+++def read_numeric_csv(path, columns):+ import numpy as np+ with Path(path).open(newline="") as handle:+ reader = csv.DictReader(handle)+ if reader.fieldnames != columns:+ raise ValueError(f"{path}: expected exactly {columns}")+ try:+ values = np.asarray([[float(row[k]) for k in columns] for row in reader], dtype=float)+ except (TypeError, ValueError) as error:+ raise ValueError(f"{path}: nonnumeric or missing data") from error+ if values.ndim != 2 or len(values) < 2 or not np.isfinite(values).all():+ raise ValueError(f"{path}: need at least two finite rows")+ if (np.diff(values[:, 0]) <= 0).any():+ raise ValueError(f"{path}: timestamps must be strictly increasing")+ return values+++def align_behavior(times, synchronization, base):+ import numpy as np+ shared = synchronization.get("shared_clock_evidence")+ pulses = synchronization.get("pulse_pairs_csv")+ if bool(shared) == bool(pulses):+ raise ValueError("Supply either shared_clock_evidence or pulse_pairs_csv")+ if shared:+ if not isinstance(shared, str) or not shared.strip():+ raise ValueError("Shared-clock evidence must be a nonempty description")+ return times.copy(), {"method": "shared_clock", "evidence": shared, "slope": 1., "offset_s": 0.}+ pairs = read_numeric_csv(base / pulses, ["device_time_s", "reference_time_s"])+ if len(pairs) < 3 or (np.diff(pairs[:, 1]) <= 0).any():+ raise ValueError("At least three ordered, matched pulse pairs are required")+ tolerance = float(synchronization["max_residual_s"])+ if not np.isfinite(tolerance) or tolerance <= 0:+ raise ValueError("max_residual_s must be finite and positive")+ slope, offset = np.polyfit(pairs[:, 0], pairs[:, 1], 1)+ residual = float(np.max(np.abs(slope * pairs[:, 0] + offset - pairs[:, 1])))+ if slope <= 0 or residual > tolerance:+ raise ValueError(f"Clock fit failed: maximum residual {residual:g} s")+ if times[0] < pairs[0, 0] or times[-1] > pairs[-1, 0]:+ raise ValueError("Behavior times exceed pulse support; affine extrapolation is not validated")+ return slope * times + offset, {"method": "matched_pulse_affine", "slope": float(slope),+ "offset_s": float(offset), "max_residual_s": residual, "tolerance_s": tolerance,+ "pulse_pairs": len(pairs), "pulse_sha256": digest(base / pulses)}+++def convert(config_path, output):+ import numpy as np+ import tifffile+ from neuroconv.datainterfaces import TiffImagingInterface+ from pynwb import NWBFile, NWBHDF5IO, validate+ from pynwb.behavior import Position, SpatialSeries+ from pynwb.file import Subject+ from nwbinspector import inspect_nwbfile++ config_path, output = Path(config_path), Path(output)+ config = json.loads(config_path.read_text())+ base = config_path.resolve().parent+ if output.exists():+ raise FileExistsError(f"Refusing to overwrite {output}")+ start = datetime.fromisoformat(config["session_start_time"])+ if start.utcoffset() is None:+ raise ValueError("session_start_time needs an explicit timezone")+ for field in ("identifier", "session_description", "experimenter", "institution", "lab"):+ if not config.get(field):+ raise ValueError(f"Missing {field}")+ tiff_path = base / config["tiff"]+ frame_times = read_numeric_csv(base / config["frame_times_csv"], ["time_s"])[:, 0]+ behavior = read_numeric_csv(base / config["position_csv"], ["time_s", "x", "y"])+ with tifffile.TiffFile(tiff_path) as tiff:+ if len(tiff.pages) != len(frame_times) or len(tiff.pages[0].shape) != 2:+ raise ValueError("Expected one grayscale 2D TIFF page per frame timestamp")+ shape, dtype = tiff.pages[0].shape, tiff.pages[0].dtype+ if any(p.shape != shape or p.dtype != dtype for p in tiff.pages):+ raise ValueError("TIFF pages differ in shape or dtype")+ position_units = {"m": 1., "cm": .01, "mm": .001}+ if config["position_unit"] not in position_units:+ raise ValueError("Position unit must be m, cm or mm; pixels require calibrated coordinates")+ position_m = behavior[:, 1:] * position_units[config["position_unit"]]+ aligned, alignment = align_behavior(behavior[:, 0], config["synchronization"], base)+ if min(frame_times[0], aligned[0]) < 0:+ raise ValueError("This converter requires nonnegative seconds since session_start_time")+ optics = config["imaging"]+ if optics.get("modality") != "two-photon":+ raise ValueError("imaging.modality must explicitly be two-photon for this converter")+ for key in ("device", "device_description", "description", "indicator", "location", "unit", "optical_channel_description"):+ if not optics.get(key):+ raise ValueError(f"Missing imaging.{key}; do not invent acquisition metadata")+ for key in ("excitation_nm", "emission_nm"):+ if not np.isfinite(float(optics[key])) or float(optics[key]) <= 0:+ raise ValueError(f"imaging.{key} must be positive and finite")+ nwb = NWBFile(session_description=config["session_description"], identifier=config["identifier"],+ session_start_time=start, experimenter=config["experimenter"],+ institution=config["institution"], lab=config["lab"], subject=Subject(**config["subject"]))+ interface = TiffImagingInterface(file_paths=[str(tiff_path)], sampling_frequency=float(1 / np.median(np.diff(frame_times))),+ metadata_key="imaging", verbose=False)+ interface.set_aligned_timestamps(aligned_timestamps=frame_times)+ metadata = interface.get_metadata()+ metadata["Devices"] = {"microscope": {"name": optics["device"], "description": optics["device_description"]}}+ metadata["Ophys"]["ImagingPlanes"] = {"plane": {+ "name": "ImagingPlane", "description": optics["description"], "device_metadata_key": "microscope",+ "excitation_lambda": float(optics["excitation_nm"]), "indicator": optics["indicator"], "location": optics["location"],+ "optical_channel": [{"name": "channel", "description": optics["optical_channel_description"],+ "emission_lambda": float(optics["emission_nm"])}]}}+ metadata["Ophys"]["MicroscopySeries"]["imaging"].update(+ name="Imaging", description=optics["description"], unit=optics["unit"], imaging_plane_metadata_key="plane")+ interface.add_to_nwbfile(nwbfile=nwb, metadata=metadata, always_write_timestamps=True)+ series = SpatialSeries(name="Position", data=position_m, timestamps=aligned,+ unit="meters", reference_frame=config["position_reference_frame"],+ description=f"Source coordinates in {config['position_unit']}; converted to meters. {config['position_description']}")+ nwb.create_processing_module(name="behavior", description="Measured animal position").add(Position(spatial_series=series))+ provenance = {"source_sha256": {key: digest(base / config[key]) for key in ("tiff", "frame_times_csv", "position_csv")},+ "config_sha256": digest(config_path), "configuration": config, "alignment": alignment,+ "axis_mapping": "TIFF (time,y,x) -> NWB (time,x,y)",+ "versions": {name: importlib.metadata.version(name) for name in ("neuroconv", "pynwb", "nwbinspector", "roiextractors", "tifffile", "zarr", "hdmf-zarr")}}+ nwb.add_scratch(json.dumps(provenance), name="conversion_provenance", description="Source metadata, checksums and clock mapping")+ output.parent.mkdir(parents=True, exist_ok=True)+ with NWBHDF5IO(str(output), "w") as io:+ io.write(nwb)+ errors = [str(error) for error in validate(path=str(output))]+ findings = []+ for message in inspect_nwbfile(output, skip_validate=True):+ if message is not None:+ findings.append({"importance": message.importance.name, "check": message.check_function_name,+ "message": message.message, "location": message.location})+ with NWBHDF5IO(str(output), "r") as io, tifffile.TiffFile(tiff_path) as tiff:+ restored = io.read()+ image = restored.acquisition["Imaging"]+ np.testing.assert_array_equal(image.timestamps[:], frame_times)+ for index, page in enumerate(tiff.pages):+ np.testing.assert_array_equal(image.data[index], page.asarray().T)+ restored_position = restored.processing["behavior"]["Position"]["Position"]+ np.testing.assert_array_equal(restored_position.data[:], position_m)+ np.testing.assert_array_equal(restored_position.timestamps[:], aligned)+ if image.unit != optics["unit"] or restored_position.unit != "meters":+ raise ValueError("Units changed during round trip")+ if restored.identifier != config["identifier"] or restored.session_start_time != start:+ raise ValueError("Session metadata changed during round trip")+ for finding in findings:+ if finding["check"] == "check_data_orientation" and finding["location"] == "/acquisition/Imaging":+ finding["review_evidence"] = "Time axis verified against all frame timestamps and every source TIFF page; short recordings can trigger the longest-axis heuristic"+ report = {**provenance, "schema_errors": errors, "inspector_findings": findings,+ "inspector_requires_review": any(f["importance"] in {"ERROR", "PYNWB_VALIDATION", "CRITICAL"} for f in findings),+ "roundtrip": {"all_frames_equal": True, "position_equal": True, "timestamps_equal": True,+ "frame_count": len(frame_times), "position_samples": len(behavior)}}+ output.with_suffix(".validation.json").write_text(json.dumps(report, indent=2) + "\n")+ if errors:+ raise ValueError("NWB schema validation failed; inspect the validation JSON")+ return report+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("config", type=Path)+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ report = convert(args.config, args.output)+ print(json.dumps({"output": str(args.output), "schema_errors": report["schema_errors"],+ "inspector_findings": len(report["inspector_findings"]), "roundtrip": report["roundtrip"]}, indent=2))+++if __name__ == "__main__":+ main()diff --git a/skills/pybamm/SKILL.md b/skills/pybamm/SKILL.mdnew file mode 100644index 00000000..ad97c290--- /dev/null+++ b/skills/pybamm/SKILL.md@@ -0,0 +1,104 @@+---+name: pybamm+description: Simulates lithium-ion battery charge, discharge and rest experiments with PyBaMM, records parameter-set provenance, checks mesh and solver sensitivity, and compares predicted voltage curves with measured cycling data. Use for SPM or DFN electrochemical battery modeling, C-rate protocols, voltage cutoffs, parameter studies and numerical validation of battery simulations.+license: MIT+compatibility: Requires Python 3.12 with PyBaMM 26.9.0.0 and pybammsolvers 0.10.0 (IDAKLU). NumPy and CasADi are supplied by PyBaMM. Network is needed for installation only; simulations and CSV comparisons run locally without credentials.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ upstream-version: "26.9.0.0"+---++# PyBaMM battery experiments++## When to use++Use this skill to model constant-current charge/discharge and rest, examine voltage and charge+trajectories, or compare SPM/DFN predictions to cycling measurements. The helper runs real PyBaMM+experiments and three numerical resolutions; it does not control a battery cycler or establish an+operating envelope for hardware.++## Runtime and tested case++```bash+uv venv --python 3.12 battery-env+uv pip install --python battery-env/bin/python pybamm==26.9.0.0 pybammsolvers==0.10.0+```++The included [assets/chen2020-protocol.json](assets/chen2020-protocol.json) is a synthetic+isothermal 298.15-K SPM case: 80% initial SOC, discharge at 0.5C for 600 s, rest for 120 s,+charge at 0.5C for 600 s. Chen2020 supplies an LG M50 parameterization with 5-Ah nominal capacity;+here 0.5C means 2.5 A. This is an executable reference example, not a claim that an arbitrary+user's cell has those parameters. The helper disables PyBaMM usage telemetry unless the caller+has already explicitly configured that variable.++## Workflow++1. Establish the cell chemistry, geometry, nominal capacity, initial state, temperature and+ current-sign convention. Use an appropriate parameter set and explain its source. Distinguish+ a paper's fitted parameters from measurements of this particular cell. Do not transplant+ degradation parameters without checking their meaning and applicable conditions.+2. Convert the requested protocol to the JSON contract in+ [references/protocol-and-comparison.md](references/protocol-and-comparison.md). Positive+ simulation current discharges; negative current charges. Every step has a finite duration.+ A specified voltage cutoff can end it earlier; the report records actual termination times.+ C-rates use the selected set's nominal capacity. A change in that capacity changes current.+3. Choose SPM when its reduced transport assumptions are adequate; use DFN when resolving+ electrolyte/electrode transport matters. The helper's tested models are isothermal and exclude+ aging, mechanics, plating and pack control. Increasing rate can invalidate SPM predictions+ even if numerical convergence is excellent.+4. Run the helper. It validates protocol fields, rejects unknown parameter overrides, uses+ IDAKLU, and writes complete parameter snapshots. Infeasible or skipped steps are errors,+ rather than silently presenting a partial protocol as complete.+5. Read the two numerical comparisons separately: baseline versus tighter tolerances isolates+ solver error; tight tolerances on the original versus doubled mesh isolates discretization.+ Compare voltage differences and event-time differences against the accuracy the question+ needs. Refine again when these are too large; one doubling does not prove convergence.+6. If measurements are available, check current, time origin, temperature, SOC and capacity+ before interpreting residuals. Supply matching seconds, volts and amps. The helper reports+ voltage RMSE/MAE/bias and current RMSE, preserving residuals. A small voltage error under a+ mismatched input current does not validate the model. This workflow compares curves; it+ does not claim to identify unique kinetic parameters from voltage alone.++## Run and inspect++From the skill directory, point `battery-env/bin/python` at the environment created above:++```bash+battery-env/bin/python scripts/simulate_battery.py assets/chen2020-protocol.json \+ --output battery-reference++# measured.csv is user data with time_s,voltage_V,current_A columns.+battery-env/bin/python scripts/simulate_battery.py protocol.json \+ --measured measured.csv --mesh-points 30 --output battery-comparison+```++The first command was executed as written with an external output location. The second uses+illustrative user filenames; the measurement path was exercised against a frozen synthetic+reference curve in the tests. Output directories must be new.++| Artifact | Interpretation |+| --- | --- |+| `curve.csv` | Baseline time, step, voltage, current and **net** discharge capacity |+| `tight-tolerance.csv` | Same mesh, tighter solver |+| `refined-mesh.csv` | Doubled mesh with tighter solver |+| `parameters.json` | PyBaMM serialization of the effective parameter values |+| `report.json` | Protocol/checksum, package versions, parameter source, numerical comparisons and terminations |+| `measurement-residuals.csv` | Prediction minus measurement and current mismatch, when measurements were supplied |++The reference case conserved integrated charge: 600 s at 2.5 A yielded 0.4166667 Ah, then equal+charge returned net discharge capacity to zero. Voltage stayed within the Chen2020 limits in this+case. Tightening tolerances changed voltage by about 1 microvolt; doubling mesh from 20 to 40+points changed it by about **2.17 mV**, so claiming sub-millivolt mesh accuracy would be unjustified.+A separate real DFN test stopped at the requested 3.9-V event and verified its charge integral.+The frozen reference is numerical regression evidence, not measured-cell validation.++## Primary references++- [PyBaMM experiment API examples](https://docs.pybamm.org/en/v25.10.0/source/examples/notebooks/getting_started/tutorial-5-run-experiments.html)+- [Mesh refinement workflow](https://docs.pybamm.org/en/v25.10.0/source/examples/notebooks/getting_started/tutorial-9-changing-the-mesh.html)+- [IDAKLU solver options](https://docs.pybamm.org/en/v25.4.1/source/api/solvers/idaklu_solver.html)+- [PyBaMM source and parameter sets](https://github.com/pybamm-team/PyBaMM)++The linked versioned manuals describe the workflow; the bundled executable and serialized+parameters were verified against PyBaMM 26.9.0.0.diff --git a/skills/pybamm/assets/chen2020-protocol.json b/skills/pybamm/assets/chen2020-protocol.jsonnew file mode 100644index 00000000..819c4f5c--- /dev/null+++ b/skills/pybamm/assets/chen2020-protocol.json@@ -0,0 +1,13 @@+{+ "model": "SPM",+ "parameter_set": "Chen2020",+ "initial_soc": 0.8,+ "temperature_K": 298.15,+ "sample_period_s": 10.0,+ "parameter_overrides": {},+ "steps": [+ {"kind": "discharge", "c_rate": 0.5, "duration_s": 600.0},+ {"kind": "rest", "duration_s": 120.0},+ {"kind": "charge", "c_rate": 0.5, "duration_s": 600.0}+ ]+}diff --git a/skills/pybamm/references/protocol-and-comparison.md b/skills/pybamm/references/protocol-and-comparison.mdnew file mode 100644index 00000000..028f58c3--- /dev/null+++ b/skills/pybamm/references/protocol-and-comparison.md@@ -0,0 +1,73 @@+# Protocol and curve contract++The helper accepts `model` (`SPM` or `DFN`), `parameter_set` (an installed PyBaMM set),+`initial_soc` in (0,1], positive `temperature_K`, positive `sample_period_s`, a nonempty `steps`+list, and optional numeric `parameter_overrides`. Unknown fields are rejected; there is no implicit+`cycles` or repeated-cycle option. Repeat the desired steps explicitly when needed. The example+set Chen2020 is tested; other sets require chemistry/geometry compatibility checks.++Each step contains `kind` and positive `duration_s`. `charge` and `discharge` also require positive+`c_rate`, and may contain `until_voltage_V` within the set's lower/upper cutoffs. `rest` has no rate+or cutoff. A sample period cannot exceed a step's duration. For example:++```json+{+ "kind": "discharge",+ "c_rate": 0.5,+ "duration_s": 3600,+ "until_voltage_V": 3.0+}+```++Current is ±C-rate times nominal Ah capacity. All duration and timestamp values are seconds;+temperatures are Kelvin, never Celsius. Use `temperature_K` for the uniform isothermal setting;+overrides of initial/ambient temperature are rejected to avoid contradictory settings. Existing+numeric PyBaMM parameter keys may be overridden, and the full effective values are serialized.+Do not use `parameter_overrides` to inject functions or arbitrary executable code.++Voltage holds (CCCV), power control, thermal dynamics and degradation are available in upstream+PyBaMM but are outside this helper's tested protocol. Extend using the upstream step APIs and test+against a physically appropriate case rather than translating a voltage hold into constant current.++## Numerical comparisons++The baseline uses IDAKLU `rtol=1e-6, atol=1e-8`; the tightened run uses `1e-8, 1e-10`. Both use the+same mesh. The third run doubles all `x_n,x_s,x_p,r_n,r_p` point counts at the tightened tolerances.+Only relevant spatial dimensions enter each model (SPM and DFN use different physics).++Voltage is compared at 101 positions over the shared elapsed interval of each corresponding step.+This avoids interpolating across a current discontinuity. Event duration differences are reported+separately because cutoff shifts change later absolute step times. Always check these alongside the+voltage metric, especially near a steep end-of-discharge drop. The output period controls saved+samples, not the adaptive solver's internal step size.++`net_discharge_capacity_Ah` integrates signed current. It decreases during charging and is not+cumulative charge throughput, remaining capacity, a cycle count, or measured state of health.++## Measured curves++The CSV has exactly:++```csv+time_s,voltage_V,current_A+0,3.98,2.5+120,3.93,2.5+300,3.90,2.5+```++Require finite values and strictly increasing time. These rows are illustrative, not measured data.+Convert raw instrument units and polarity explicitly upstream and retain their provenance. The+helper interpolates the baseline at measurement times only inside the simulated interval; it never+extrapolates. If only an overlapping segment is intended, select and document that segment upstream.++Align experiment start from acquisition evidence; do not optimize a time shift solely to improve+fit unless that is an explicit fitting parameter with uncertainty. Samples right at a current switch+can represent either side of an instantaneous ohmic change; align acquisition semantics and inspect+the current-difference column before comparing those voltages. RMSE gives each supplied sample equal+weight, so oversampling a long rest changes its contribution. Resample deliberately if a time-weighted+or phase-balanced score is desired, and retain the original curve.++Report residual structure across charge, rest and discharge, not just a single score. Temperature,+SOC, capacity calibration and hysteresis can dominate mismatches. Parameter fitting should compare+identifiability and uncertainty against independent experiments rather than treating a lower error+on the same curve as sufficient validation.diff --git a/skills/pybamm/scripts/simulate_battery.py b/skills/pybamm/scripts/simulate_battery.pynew file mode 100644index 00000000..b380eb4e--- /dev/null+++ b/skills/pybamm/scripts/simulate_battery.py@@ -0,0 +1,196 @@+"""Run a validated constant-current/rest battery experiment with numerical checks."""+from __future__ import annotations++import argparse+import csv+import hashlib+import importlib.metadata+import json+import math+import os+from pathlib import Path++# Simulation is local; do not send usage telemetry when the library imports.+os.environ.setdefault("PYBAMM_DISABLE_TELEMETRY", "true")+++def validate_protocol(protocol):+ def finite(name, value, low=0, high=math.inf):+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not low < value <= high:+ raise ValueError(f"{name} must be finite and in ({low}, {high}]")+ allowed = {"model", "parameter_set", "initial_soc", "temperature_K", "sample_period_s", "steps", "parameter_overrides"}+ if set(protocol) - allowed:+ raise ValueError(f"Unsupported protocol fields: {sorted(set(protocol) - allowed)}")+ if protocol.get("model") not in {"SPM", "DFN"}:+ raise ValueError("model must be SPM or DFN")+ if not isinstance(protocol.get("parameter_set"), str) or not protocol["parameter_set"]:+ raise ValueError("parameter_set is required")+ finite("initial_soc", protocol.get("initial_soc"), high=1)+ finite("temperature_K", protocol.get("temperature_K"))+ finite("sample_period_s", protocol.get("sample_period_s"))+ steps = protocol.get("steps")+ if not isinstance(steps, list) or not steps:+ raise ValueError("steps must be a nonempty list")+ for index, step in enumerate(steps):+ if set(step) - {"kind", "duration_s", "c_rate", "until_voltage_V"}:+ raise ValueError(f"step {index}: unsupported field")+ if step.get("kind") not in {"discharge", "charge", "rest"}:+ raise ValueError(f"step {index}: kind must be discharge, charge or rest")+ finite(f"step {index} duration_s", step.get("duration_s"))+ if protocol["sample_period_s"] > step["duration_s"]:+ raise ValueError("sample_period_s exceeds a step duration")+ if step["kind"] != "rest":+ finite(f"step {index} c_rate", step.get("c_rate"))+ if "until_voltage_V" in step:+ finite(f"step {index} until_voltage_V", step["until_voltage_V"])+ elif "c_rate" in step or "until_voltage_V" in step:+ raise ValueError("Rest steps cannot specify c_rate or voltage cutoff")+ for key, value in protocol.get("parameter_overrides", {}).items():+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ raise ValueError(f"Override {key}: only finite numeric existing parameters are supported")+ return protocol+++def solve_protocol(protocol, mesh_points=20, rtol=1e-6, atol=1e-8):+ import pybamm+ import numpy as np+ validate_protocol(protocol)+ if not isinstance(mesh_points, int) or mesh_points < 5:+ raise ValueError("mesh_points must be an integer >=5")+ if not (0 < rtol < 1 and 0 < atol < 1):+ raise ValueError("Solver tolerances must be between zero and one")+ parameters = pybamm.ParameterValues(protocol["parameter_set"])+ overrides = protocol.get("parameter_overrides", {})+ unknown = set(overrides) - set(parameters.keys())+ if unknown:+ raise ValueError(f"Unknown parameter overrides: {sorted(unknown)}")+ if {"Ambient temperature [K]", "Initial temperature [K]"} & set(overrides):+ raise ValueError("Set temperature_K instead of temperature overrides")+ parameters.update(overrides)+ parameters.update({"Ambient temperature [K]": protocol["temperature_K"],+ "Initial temperature [K]": protocol["temperature_K"]})+ capacity = float(parameters["Nominal cell capacity [A.h]"])+ lower, upper = (float(parameters[key]) for key in ("Lower voltage cut-off [V]", "Upper voltage cut-off [V]"))+ if not (capacity > 0 and 0 < lower < upper):+ raise ValueError("Invalid nominal capacity or voltage limits in parameter set")+ steps = []+ for step in protocol["steps"]:+ current = 0 if step["kind"] == "rest" else step["c_rate"] * capacity * (1 if step["kind"] == "discharge" else -1)+ cutoff = step.get("until_voltage_V")+ if cutoff is not None and not lower <= cutoff <= upper:+ raise ValueError("Protocol voltage cutoff exceeds the parameter-set limits")+ steps.append(pybamm.step.current(current, duration=step["duration_s"],+ termination=f"{cutoff} V" if cutoff is not None else None,+ period=protocol["sample_period_s"], skip_ok=False))+ model = {"SPM": pybamm.lithium_ion.SPM, "DFN": pybamm.lithium_ion.DFN}[protocol["model"]](options={"thermal": "isothermal"})+ mesh = {key: mesh_points for key in ("x_n", "x_s", "x_p", "r_n", "r_p")}+ simulation = pybamm.Simulation(model, parameter_values=parameters,+ experiment=pybamm.Experiment([tuple(steps)]), var_pts=mesh,+ solver=pybamm.IDAKLUSolver(rtol=rtol, atol=atol))+ solution = simulation.solve(initial_soc=protocol["initial_soc"])+ segments = [segment for cycle in solution.cycles for segment in cycle.steps]+ if len(segments) != len(steps) or any(isinstance(s, pybamm.EmptySolution) for s in segments):+ raise RuntimeError("Protocol ended early or skipped a step; do not interpret as a complete experiment")+ rows, terminations = [], []+ for index, segment in enumerate(segments):+ t = np.asarray(segment["Time [s]"].entries)+ v = np.asarray(segment["Voltage [V]"].entries)+ current = np.asarray(segment["Current [A]"].entries)+ charge = np.asarray(segment["Discharge capacity [A.h]"].entries)+ requested = protocol["steps"][index]+ if t[-1] - t[0] < requested["duration_s"] - 1e-5:+ cutoff = requested.get("until_voltage_V")+ if cutoff is None or abs(float(v[-1]) - cutoff) > 1e-4:+ raise RuntimeError(f"Step {index} ended before its duration without reaching the requested cutoff")+ if not np.isfinite(np.column_stack([t, v, current, charge])).all():+ raise RuntimeError("Nonfinite simulation output")+ rows.extend(zip([index] * len(t), t, v, current, charge))+ terminations.append({"step": index, "kind": protocol["steps"][index]["kind"],+ "start_s": float(t[0]), "end_s": float(t[-1]), "termination": segment.termination})+ return {"solution": solution, "segments": segments, "rows": rows, "terminations": terminations,+ "parameters": parameters.to_json(), "mesh_points": mesh_points, "rtol": rtol, "atol": atol,+ "nominal_capacity_Ah": capacity, "voltage_limits_V": [lower, upper]}+++def compare_runs(first, second):+ import numpy as np+ differences = []+ for index, (a, b) in enumerate(zip(first["segments"], second["segments"])):+ duration_a, duration_b = a.t[-1] - a.t[0], b.t[-1] - b.t[0]+ local = np.linspace(0, min(duration_a, duration_b), 101)+ va = a["Voltage [V]"](a.t[0] + local)+ vb = b["Voltage [V]"](b.t[0] + local)+ differences.append({"step": index, "max_voltage_difference_V": float(np.max(np.abs(va-vb))),+ "end_time_difference_s": float(abs(duration_a-duration_b))})+ return {"max_voltage_difference_V": max(d["max_voltage_difference_V"] for d in differences),+ "steps": differences}+++def compare_measurement(rows, measurement_path, residual_path):+ import numpy as np+ with Path(measurement_path).open(newline="") as handle:+ reader = csv.DictReader(handle)+ if reader.fieldnames != ["time_s", "voltage_V", "current_A"]:+ raise ValueError("Measured CSV columns must be time_s,voltage_V,current_A")+ measured = np.asarray([[float(r[k]) for k in reader.fieldnames] for r in reader])+ if measured.ndim != 2 or len(measured) < 2 or not np.isfinite(measured).all() or (np.diff(measured[:, 0]) <= 0).any():+ raise ValueError("Need finite measurements and strictly increasing times")+ simulated = np.asarray(rows)+ if measured[0, 0] < simulated[0, 1] or measured[-1, 0] > simulated[-1, 1]:+ raise ValueError("Measurement times exceed simulated interval; no extrapolation")+ predicted = np.interp(measured[:, 0], simulated[:, 1], simulated[:, 2])+ predicted_current = np.interp(measured[:, 0], simulated[:, 1], simulated[:, 3])+ residual = predicted - measured[:, 1]+ with Path(residual_path).open("w", newline="") as handle:+ writer = csv.writer(handle); writer.writerow(["time_s", "predicted_voltage_V", "measured_voltage_V", "residual_V", "current_difference_A"])+ writer.writerows(zip(measured[:, 0], predicted, measured[:, 1], residual, predicted_current-measured[:, 2]))+ return {"samples": len(measured), "rmse_V": float(np.sqrt(np.mean(residual**2))),+ "mae_V": float(np.mean(np.abs(residual))), "bias_V": float(np.mean(residual)),+ "current_rmse_A": float(np.sqrt(np.mean((predicted_current-measured[:, 2])**2))),+ "measurement_sha256": hashlib.sha256(Path(measurement_path).read_bytes()).hexdigest(),+ "comparison_interval_s": [float(measured[0, 0]), float(measured[-1, 0])]}+++def run(protocol_path, output, measured=None, mesh_points=20):+ import pybamm+ protocol_path, output = Path(protocol_path), Path(output)+ protocol = validate_protocol(json.loads(protocol_path.read_text()))+ if output.exists():+ raise FileExistsError(f"Refusing to overwrite {output}")+ baseline = solve_protocol(protocol, mesh_points)+ tight = solve_protocol(protocol, mesh_points, rtol=1e-8, atol=1e-10)+ refined = solve_protocol(protocol, mesh_points * 2, rtol=1e-8, atol=1e-10)+ output.mkdir(parents=True)+ for name, result in (("curve", baseline), ("tight-tolerance", tight), ("refined-mesh", refined)):+ with (output / f"{name}.csv").open("w", newline="") as handle:+ writer = csv.writer(handle)+ writer.writerow(["step", "time_s", "voltage_V", "current_A", "net_discharge_capacity_Ah"])+ writer.writerows(result["rows"])+ (output / "parameters.json").write_text(json.dumps(baseline["parameters"], indent=2) + "\n")+ report = {"pybamm_version": pybamm.__version__, "solver": "IDAKLUSolver", "protocol": protocol,+ "versions": {name: importlib.metadata.version(name) for name in ("pybamm", "pybammsolvers", "numpy", "casadi")},+ "protocol_sha256": hashlib.sha256(protocol_path.read_bytes()).hexdigest(),+ "parameter_set_description": pybamm.parameter_sets.get_docstring(protocol["parameter_set"]),+ "nominal_capacity_Ah": baseline["nominal_capacity_Ah"], "voltage_limits_V": baseline["voltage_limits_V"],+ "mesh_points": mesh_points, "baseline_tolerances": {"rtol": 1e-6, "atol": 1e-8},+ "tight_tolerances": {"rtol": 1e-8, "atol": 1e-10}, "refined_mesh_points": mesh_points * 2,+ "terminations": baseline["terminations"], "solver_sensitivity": compare_runs(baseline, tight),+ "mesh_sensitivity": compare_runs(tight, refined)}+ if measured:+ report["measurement_comparison"] = compare_measurement(baseline["rows"], measured, output / "measurement-residuals.csv")+ (output / "report.json").write_text(json.dumps(report, indent=2) + "\n")+ return report+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("protocol", type=Path)+ parser.add_argument("--output", type=Path, required=True)+ parser.add_argument("--measured", type=Path)+ parser.add_argument("--mesh-points", type=int, default=20)+ args = parser.parse_args()+ print(json.dumps(run(args.protocol, args.output, args.measured, args.mesh_points), indent=2))+++if __name__ == "__main__":+ main()diff --git a/skills/pycalphad/SKILL.md b/skills/pycalphad/SKILL.mdnew file mode 100644index 00000000..c9e4efae--- /dev/null+++ b/skills/pycalphad/SKILL.md@@ -0,0 +1,118 @@+---+name: pycalphad+description: Computes finite-temperature CALPHAD equilibria, phase fractions, and phase compositions from thermodynamic TDB databases using pycalphad. Use for alloy phase stability, equilibrium temperature sweeps, tie lines, lever-rule checks, or reproducible phase-fraction calculations with explicit components and mole-fraction conditions.+license: MIT+compatibility: Requires Python 3.12+, pycalphad 0.11.2, and NumPy. Installation needs network access; calculations run locally without credentials. Real-material predictions require a suitable licensed thermodynamic database.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ tested-package-version: "0.11.2"+---++# pycalphad: TDB equilibrium calculations++## When to use++Use for equilibrium phase fractions and compositions at a fixed bulk elemental mole+composition, specified pressure, and a list of finite temperatures. The bundled helper+executes real pycalphad equilibria, checks mass balance, repeats at greater sampling+density, and exports each stable composition set separately.++Equilibrium is constrained by the selected database, components, phases, and conditions.+It does not predict precipitation rates, retained metastable microstructures, or properties+of phases missing from the database. Successful numerical checks do not establish the+database's experimental accuracy.++## Workflow++1. Identify the TDB's source, license, assessment/publication, valid temperature/pressure+ and composition range, and required elements. Use the user's database for real alloys.+ The bundled [assets/ideal-cu-ni.tdb](assets/ideal-cu-ni.tdb) is an original hypothetical+ teaching model, **not an assessed Cu-Ni database**.+2. Inspect database elements and phases. Select the relevant phases deliberately; record+ exclusions because they can turn the calculation into a metastable constrained result.+ Include `VA` where required by sublattice models. Vacancies are not an independent bulk+ mole fraction. Order-disorder models may require their coupled phase definitions.+3. Copy [assets/equilibrium.json](assets/equilibrium.json). Specify exactly N-1 elemental+ mole fractions and one dependent non-vacancy element. The dependent fraction is+ `1 - sum(independent fractions)`; fractions are not silently normalized. Set K and Pa.+ Convert weight percentages or mass fractions before using this helper.+4. Declare the database temperature interval from its assessment if known, or set+ `database_temperature_range_k` to null if unknown. This is user-supplied evidence,+ not a range automatically inferred from every TDB function. Requests outside a declared+ interval fail. Check pressure and composition validity separately.+5. Run the calculation. Check finite Gibbs energies, phase fractions summing to one,+ reconstructed bulk composition, and stability to doubled `pdens` (phase-constitution+ sampling density). Near transitions, refine temperatures and sampling density further.+6. Deliver phase fractions with their **molar** basis, phase compositions, database hash,+ conditions, excluded phases, and any numerical or assessment limitations.++Read [references/model-and-validation.md](references/model-and-validation.md) for the+analytic example, basis conversion, miscibility-gap handling, and convergence limits.++## Execute the tested example++From the collection root:++```bash+uv run --no-project --python 3.12 --with pycalphad==0.11.2 --with numpy==2.5.3 \+ python skills/pycalphad/scripts/equilibrate.py \+ skills/pycalphad/assets/ideal-cu-ni.tdb \+ skills/pycalphad/assets/equilibrium.json equilibrium-result+```++Tested on Python 3.12, pycalphad 0.11.2, and NumPy 2.5.3. Use a new output directory.+All thermodynamic calculations are local; the script does not upload a TDB.++For the supplied hypothetical model at X(Ni)=0.5 and 101325 Pa:++| Temperature | Equilibrium result |+| --- | --- |+| 900 K | FCC_A1 only |+| 1100 K | 0.5 FCC_A1 + 0.5 LIQUID; X(Ni) approximately 0.527307 and 0.472693 respectively |+| 1300 K | LIQUID only |++The suite verifies analytic common-tangent compositions, a noncentral lever-rule case,+Gibbs energy, mass balance, both single-phase limits, and actual same-phase miscibility+gap vertices. These validate the computational workflow, not real Cu-Ni metallurgy.++## Outputs and acceptance++- `report.json`: settings and versions, TDB/settings SHA-256, excluded database phases,+ reconstructed bulk composition, per-temperature baseline/refined results, and checks.+- `phase-equilibria.csv`: one row per stable vertex per temperature and sampling run,+ including phase name, molar phase fraction, and elemental mole fractions. Its Gibbs+ energy column is the **whole-system molar Gibbs energy**, repeated for each vertex;+ it is not the individual phase energy.++Unused pycalphad vertices have blank names and NaN values; those are omitted. Named+vertices with invalid values cause failure. Multiple vertices with the same phase name+are retained because a miscibility gap can contain two composition sets of one phase.+Vertex indices do not track the same physical phase continuously across temperatures.++`all_checks_passed` requires each run's phase-sum and bulk-composition residuals within+`mass_balance_tolerance`, phase totals stable within `phase_fraction_tolerance`, and+system Gibbs energy stable within `gibbs_energy_tolerance_j_per_mol` when `pdens` doubles.+This comparison does not certify the global minimum or track individual composition-set+movement within a same-phase miscibility gap; inspect their exported compositions too.+Failed checks remain visible in the report rather than being relabeled as convergence.++## Boundaries and upstream contracts++The helper handles elemental mole fractions, one composition, one pressure, and up to+1000 explicit positive temperatures. It validates selected phases through pycalphad's+phase-compatibility rules; incompatible or automatically filtered order/disorder phase+sets produce an explicit error. It does not silently remove requested phases.++Charged-species constraints, externally imposed chemical potentials, custom models,+activity reference-state changes, and database optimization require additional modeling+and are outside this helper's tested scope. Do not extrapolate the pedagogical asset to+real material selection or heat-treatment decisions.++- [Equilibrium dataset semantics](https://pycalphad.org/docs/latest/examples/3_High_Throughput_Analysis/2_UsingCalculationResults.html)+- [Phase fractions and composition basis](https://pycalphad.org/docs/latest/examples/2_Computing_Properties/1_PhaseCompositions.html)+- [Equilibrium and sampling API](https://pycalphad.org/docs/latest/api/pycalphad.core.html)+- [Ordering examples](https://pycalphad.org/docs/latest/examples/EquilibriumWithOrdering.html)++Upstream `latest` documentation includes development APIs; the bundled helper and phase+filtering behavior were exercised against the pinned stable 0.11.2 release.diff --git a/skills/pycalphad/assets/equilibrium.json b/skills/pycalphad/assets/equilibrium.jsonnew file mode 100644index 00000000..1201c907--- /dev/null+++ b/skills/pycalphad/assets/equilibrium.json@@ -0,0 +1,14 @@+{+ "components": ["CU", "NI", "VA"],+ "phases": ["FCC_A1", "LIQUID"],+ "composition_basis": "mole_fraction",+ "dependent_component": "CU",+ "independent_mole_fractions": {"NI": 0.5},+ "temperatures_k": [900.0, 1100.0, 1300.0],+ "pressure_pa": 101325.0,+ "database_temperature_range_k": [298.15, 2000.0],+ "pdens": 500,+ "mass_balance_tolerance": 1e-7,+ "phase_fraction_tolerance": 1e-6,+ "gibbs_energy_tolerance_j_per_mol": 0.01+}diff --git a/skills/pycalphad/assets/ideal-cu-ni.tdb b/skills/pycalphad/assets/ideal-cu-ni.tdbnew file mode 100644index 00000000..a42b6e36--- /dev/null+++ b/skills/pycalphad/assets/ideal-cu-ni.tdb@@ -0,0 +1,16 @@+$ Original pedagogical database by K-Dense Inc.; MIT license.+$ Hypothetical ideal CU-NI model. NOT assessed copper-nickel thermodynamics.+$ G(FCC) = ideal mixing; G(LIQUID) adds (1-x)*(10000-10*T)+x*(12000-10*T).+$ Energies J/mol, T K. Defined range 298.15 to 2000 K. No pressure dependence.+ELEMENT CU FCC_A1 63.546 0 0 !+ELEMENT NI FCC_A1 58.6934 0 0 !+ELEMENT VA VACUUM 0 0 0 !+TYPE_DEFINITION % SEQ * !+PHASE FCC_A1 % 1 1 !+CONSTITUENT FCC_A1 :CU,NI: !+PARAMETER G(FCC_A1,CU;0) 298.15 0; 2000 N !+PARAMETER G(FCC_A1,NI;0) 298.15 0; 2000 N !+PHASE LIQUID % 1 1 !+CONSTITUENT LIQUID :CU,NI: !+PARAMETER G(LIQUID,CU;0) 298.15 10000-10*T; 2000 N !+PARAMETER G(LIQUID,NI;0) 298.15 12000-10*T; 2000 N !diff --git a/skills/pycalphad/references/model-and-validation.md b/skills/pycalphad/references/model-and-validation.mdnew file mode 100644index 00000000..eefa585f--- /dev/null+++ b/skills/pycalphad/references/model-and-validation.md@@ -0,0 +1,63 @@+# Composition basis and equilibrium validation++## Original pedagogical database++`assets/ideal-cu-ni.tdb` was written for this skill and is released under the skill's+MIT license. Cu and Ni are labels for a hypothetical ideal binary; there are no fitted+experimental data. The file defines one substitutional sublattice in FCC_A1 and LIQUID,+with no excess mixing terms or pressure dependence. Its functions span 298.15–2000 K.++With x = X(Ni), energies in J/mol, and R in J/(mol K):++- G(FCC_A1) = R T [x ln x + (1-x) ln(1-x)].+- G(LIQUID) = G(FCC_A1) + (1-x)(10000-10T) + x(12000-10T).++At T=1100 K the liquid endmember offsets are -1000 and +1000 J/mol. Equality of both+component chemical potentials gives x_liquid = 1/(1+exp(1000/(RT))) and+x_solid = 1-x_liquid. The phase fraction of solid at bulk x between those endpoints is+(x_bulk-x_liquid)/(x_solid-x_liquid). This is an independent analytic check of the+numerical common tangent, phase compositions, and lever rule. The tests use pycalphad's+R=8.3145 J/(mol K); the listed decimal values are package/model-specific regression values.++The database intentionally lacks realistic heat capacities, lattice stabilities, excess+mixing, magnetic terms, and pressure effects. Its apparent transitions are synthetic.+Do not fit a real experiment to it or replace an assessed database with this example.++## Basis conversions++For measured elemental mass fractions w_i and molar masses M_i, calculate+x_i = (w_i/M_i) / sum_j(w_j/M_j), including the dependent element. Weight percent is+first divided by 100. Store the original composition, molar masses, and converted values+with the run. The helper accepts only the resulting mole fractions and rejects a+`mass_fraction` basis instead of treating weight percent as atomic fraction.++`NP` is a molar phase fraction at total N=1. A mass phase fraction requires each phase's+composition-weighted molar mass: w_phase = NP_phase*M_phase / sum(NP_j*M_j).+Volume fractions require appropriate phase densities or molar volumes as well. Do not+compare molar fractions directly to microscopy area fractions without explaining the+conversion and sampling assumptions.++## Phase selection and solver checks++`VA` supports vacancy sublattices and is omitted from overall elemental mass balance.+Select actual elements present in the database. A required vacancy or other constituent+missing from every active species in one sublattice can make a phase unavailable.+The helper rejects phase lists that pycalphad filters, including redundant coupled+order/disorder selections, so the agent can review rather than silently alter them.++Excluding a phase can lower the number of stable phases and change apparent solubility.+An excluded phase list is therefore scientific provenance. Preserve each composition+set in miscibility gaps: summing fractions by phase name is useful for totals but loses+the two distinct tie-line endpoints. Never use a vertex index as a persistent phase ID.++Mass balance, phase-sum checks, and finite Gibbs energy are necessary but not sufficient.+Doubled `pdens` only tests one initialization-density change. Repeat with more density,+inspect nearby conditions, compare alternative candidate phase sets, or use a trusted+reference calculation when the result affects a scientific conclusion. Degenerate phase+fractions at invariant points may be nonunique even when Gibbs energies agree. The+helper's flags should be interpreted with that thermodynamic context.++Preserve the actual TDB with the output under its licensing terms. A SHA-256 identifies+bytes but does not document assessment quality, reference-state conventions, or the+validity range. Include the database authors' citation and uncertainty/coverage limits+in the final scientific report.diff --git a/skills/pycalphad/scripts/equilibrate.py b/skills/pycalphad/scripts/equilibrate.pynew file mode 100644index 00000000..9f9b4888--- /dev/null+++ b/skills/pycalphad/scripts/equilibrate.py@@ -0,0 +1,176 @@+#!/usr/bin/env python3+"""Compute TDB-based equilibria at one bulk mole composition over temperatures."""+from __future__ import annotations++import argparse+import csv+import hashlib+import json+from pathlib import Path++import numpy as np+import pycalphad as pc+from pycalphad import variables as v+from pycalphad.core.utils import filter_phases, unpack_species+++def finite(value, name, positive=False):+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not np.isfinite(value):+ raise ValueError(f"{name} must be a finite number")+ if positive and value <= 0:+ raise ValueError(f"{name} must be positive")+ return float(value)+++def validate(db, settings):+ keys = {"components", "phases", "composition_basis", "dependent_component", "independent_mole_fractions",+ "temperatures_k", "pressure_pa", "database_temperature_range_k", "pdens",+ "mass_balance_tolerance", "phase_fraction_tolerance", "gibbs_energy_tolerance_j_per_mol"}+ if set(settings) != keys:+ raise ValueError(f"Missing settings: {sorted(keys-set(settings))}; unknown: {sorted(set(settings)-keys)}")+ for key in ("components", "phases"):+ values = settings[key]+ if not isinstance(values, list) or not values or any(not isinstance(s, str) for s in values) or len(set(values)) != len(values):+ raise ValueError(f"{key} must be a nonempty list of unique names")+ comps = settings["components"]+ phases = settings["phases"]+ if set(comps) - db.elements:+ raise ValueError(f"Components absent from database elements: {sorted(set(comps) - db.elements)}")+ if set(phases) - set(db.phases):+ raise ValueError(f"Unknown phases: {sorted(set(phases) - set(db.phases))}")+ active = filter_phases(db, unpack_species(db, comps), phases)+ if set(active) != set(phases):+ raise ValueError(f"Incompatible or order-disorder-filtered phases: {sorted(set(phases) - set(active))}")+ if settings["composition_basis"] != "mole_fraction":+ raise ValueError("Only elemental mole_fraction conditions are accepted; convert mass fractions explicitly")+ material = set(comps) - {"VA"}+ dependent = settings["dependent_component"]+ if dependent not in material:+ raise ValueError("dependent_component must be a non-vacancy selected element")+ fractions = settings["independent_mole_fractions"]+ if not isinstance(fractions, dict) or set(fractions) != material - {dependent}:+ raise ValueError("Specify exactly one mole fraction for each nondependent, non-vacancy component")+ fractions = {name: finite(value, name) for name, value in fractions.items()}+ if any(value < 0 or value > 1 for value in fractions.values()) or sum(fractions.values()) > 1:+ raise ValueError("Mole fractions must be in [0,1] and sum to at most one")+ bulk = {**fractions, dependent: 1 - sum(fractions.values())}+ temperatures = settings["temperatures_k"]+ if not isinstance(temperatures, list) or not temperatures or len(temperatures) > 1000:+ raise ValueError("temperatures_k must contain between 1 and 1000 explicit temperatures")+ for temperature in temperatures:+ finite(temperature, "temperature_k", True)+ if len(set(temperatures)) != len(temperatures):+ raise ValueError("Duplicate temperatures are not accepted")+ bounds = settings["database_temperature_range_k"]+ if bounds is not None:+ if not isinstance(bounds, list) or len(bounds) != 2:+ raise ValueError("database_temperature_range_k must be [low, high] or null if unknown")+ low, high = [finite(x, "database temperature bound", True) for x in bounds]+ if low >= high or min(temperatures) < low or max(temperatures) > high:+ raise ValueError("Requested temperatures lie outside the declared database range")+ for name in ("pressure_pa", "mass_balance_tolerance", "phase_fraction_tolerance", "gibbs_energy_tolerance_j_per_mol"):+ finite(settings[name], name, True)+ pdens = settings["pdens"]+ if isinstance(pdens, bool) or not isinstance(pdens, int) or not 10 <= pdens <= 10000:+ raise ValueError("pdens must be an integer from 10 through 10000")+ return bulk+++def solve_point(db, settings, bulk, temperature, pdens):+ conditions = {v.T: temperature, v.P: settings["pressure_pa"], v.N: 1}+ conditions.update({v.X(name): value for name, value in settings["independent_mole_fractions"].items()})+ result = pc.equilibrium(db, settings["components"], settings["phases"], conditions, calc_opts={"pdens": pdens})+ energy = float(result.GM.values.item())+ names = result.Phase.values.ravel()+ amounts = result.NP.values.ravel()+ components = [str(c) for c in result.component.values]+ compositions = result.X.values.reshape(-1, len(components))+ if not np.isfinite(energy) or set(components) != set(bulk):+ raise ValueError("Equilibrium failed: nonfinite energy or unexpected output components")+ vertices = []+ reconstructed = {name: 0.0 for name in bulk}+ phase_sums = {name: 0.0 for name in settings["phases"]}+ for index, (name, amount, composition) in enumerate(zip(names, amounts, compositions)):+ if name == "":+ continue # pycalphad pads unused vertices with blank names and NaN amounts.+ if name not in phase_sums or not np.isfinite(amount) or not np.isfinite(composition).all():+ raise ValueError("Equilibrium contains an invalid or fictitious stable vertex")+ if amount < -1e-10 or amount > 1 + 1e-10 or np.min(composition) < -1e-10 or abs(composition.sum() - 1) > 1e-7:+ raise ValueError("Equilibrium has invalid phase fraction or composition")+ fractions = dict(zip(components, map(float, composition)))+ vertices.append({"vertex": index, "phase": str(name), "mole_phase_fraction": float(amount), "mole_fractions": fractions})+ phase_sums[str(name)] += float(amount)+ for component, fraction in fractions.items():+ reconstructed[component] += float(amount) * fraction+ if not vertices:+ raise ValueError("Equilibrium produced no stable phases")+ amount_error = abs(sum(phase_sums.values()) - 1)+ mass_error = max(abs(reconstructed[c] - bulk[c]) for c in bulk)+ return {"temperature_k": temperature, "gibbs_energy_j_per_mol": energy, "vertices": vertices,+ "phase_totals": phase_sums, "reconstructed_bulk_mole_fractions": reconstructed,+ "phase_fraction_sum_error": amount_error, "mass_balance_absolute_error": mass_error,+ "balance_passed": amount_error <= settings["mass_balance_tolerance"] and mass_error <= settings["mass_balance_tolerance"]}+++def calculate(db, settings):+ bulk = validate(db, settings)+ points = []+ for temperature in settings["temperatures_k"]:+ baseline = solve_point(db, settings, bulk, temperature, settings["pdens"])+ refined = solve_point(db, settings, bulk, temperature, 2 * settings["pdens"])+ fraction_change = max(abs(baseline["phase_totals"][p] - refined["phase_totals"][p]) for p in settings["phases"])+ energy_change = abs(baseline["gibbs_energy_j_per_mol"] - refined["gibbs_energy_j_per_mol"])+ points.append({"baseline": baseline, "refined": refined,+ "maximum_phase_fraction_change": fraction_change,+ "gibbs_energy_change_j_per_mol": energy_change,+ "checks_passed": baseline["balance_passed"] and refined["balance_passed"] and+ fraction_change <= settings["phase_fraction_tolerance"] and energy_change <= settings["gibbs_energy_tolerance_j_per_mol"]})+ return {"bulk_mole_fractions": bulk, "points": points,+ "all_checks_passed": all(point["checks_passed"] for point in points),+ "excluded_database_phases": sorted(set(db.phases) - set(settings["phases"]))}+++def run(database_path, settings_path, output_dir):+ database_path, settings_path, output_dir = map(Path, (database_path, settings_path, output_dir))+ if output_dir.exists():+ raise ValueError("Output directory already exists; choose a new directory")+ settings = json.loads(settings_path.read_text())+ db = pc.Database(str(database_path))+ report = calculate(db, settings)+ report.update(versions={"pycalphad": pc.__version__, "numpy": np.__version__}, settings=settings,+ database_sha256=hashlib.sha256(database_path.read_bytes()).hexdigest(),+ settings_sha256=hashlib.sha256(settings_path.read_bytes()).hexdigest(),+ phase_fraction_basis="molar, N=1; vacancies excluded from bulk composition",+ database_experimental_validity="not_assessed",+ refinement="pdens doubled; phase totals and GM compared; not a proof of the global minimum")+ output_dir.mkdir(parents=True)+ (output_dir / "report.json").write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")+ with (output_dir / "phase-equilibria.csv").open("w", newline="") as handle:+ writer = csv.writer(handle)+ components = sorted(report["bulk_mole_fractions"])+ writer.writerow(["run", "temperature_k", "vertex", "phase", "mole_phase_fraction", "gibbs_energy_j_per_mol", *[f"X_{c}" for c in components]])+ for point in report["points"]:+ for variant in ("baseline", "refined"):+ result = point[variant]+ for vertex in result["vertices"]:+ writer.writerow([variant, result["temperature_k"], vertex["vertex"], vertex["phase"],+ vertex["mole_phase_fraction"], result["gibbs_energy_j_per_mol"],+ *[vertex["mole_fractions"][c] for c in components]])+ return report+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("database", type=Path, help="Thermodynamic TDB database")+ parser.add_argument("settings", type=Path, help="Conditions JSON")+ parser.add_argument("output", type=Path, help="New output directory")+ args = parser.parse_args()+ try:+ report = run(args.database, args.settings, args.output)+ except (ValueError, OSError, TypeError, KeyError) as error:+ parser.error(str(error))+ print(json.dumps({"output": str(args.output), "all_checks_passed": report["all_checks_passed"]}))+++if __name__ == "__main__":+ main()diff --git a/skills/qiime2-amplicon/SKILL.md b/skills/qiime2-amplicon/SKILL.mdnew file mode 100644index 00000000..b051128c--- /dev/null+++ b/skills/qiime2-amplicon/SKILL.md@@ -0,0 +1,114 @@+---+name: qiime2-amplicon+description: Processes paired-end 16S amplicon reads into QIIME 2 ASVs and taxonomy with retained artifact provenance. Validates paired FASTQ manifests, primer orientation, post-trimming read overlap, sample metadata, classifier compatibility, and per-sample read retention.+license: MIT+compatibility: Python 3.10+ for the standard-library validation helper; QIIME 2 2026.7 distribution with cutadapt, dada2, feature-table, feature-classifier and taxa plugins for execution. Install through the official conda/container distribution, not PyPI. Requires a matching trained classifier and network for installation/reference downloads.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ upstream-version: "2026.7"+---++# QIIME 2 paired-end 16S amplicons++Use for a demultiplexed, paired-end 16S assay with known primers, quality encoding, expected insert+length, and sample metadata. This bounded workflow imports reads, removes 5′ primers, denoises with+DADA2, classifies ASVs using an explicitly supplied classifier, and retains `.qza`/`.qzv` provenance.+Do not treat read counts as absolute cell counts or taxonomy assignments as strain identification.++## Establish the assay before running++- Confirm Phred+33, read orientation, primer sequences **as sequenced** in forward/reverse reads,+ and whether primers have already been removed. The bundled runner requires primers still+ present at the 5′ ends; it anchors Cutadapt matching and discards untrimmed pairs. Already+ trimmed reads need a direct import → DADA2 workflow with that omission recorded in provenance.+- Choose truncation positions from actual per-base quality and error profiles. `trunc-f/r` are+ positions **after primer removal**. The expected maximum insert length also excludes primers.+ Require `trunc_f + trunc_r - maximum_insert_length >= 12`; use a margin for length variation.+ The check predicts geometrical overlap, not successful biological merging.+- Match classifier reference database, release, primer region, orientation and QIIME/scikit-learn+ compatibility. Record its source URL, database version and checksum. Do not automatically fetch+ an arbitrary “latest” classifier or reuse an incompatible serialized sklearn model. Load sklearn+ classifier artifacts only from trusted sources: QZA format validation does not make an+ untrusted serialized model safe.+- Include extraction blanks, PCR negatives, and a mock community where available. The runner+ rejects empty FASTQs; preserve empty-control IDs separately and report them rather than silently+ deleting control evidence. Assess contamination before ecological interpretation.++## Input files++Manifest is a **tab-separated** `PairedEndFastqManifestPhred33V2` file with exactly these headers:++```text+sample-id forward-absolute-filepath reverse-absolute-filepath+sample1 /data/sample1_R1.fastq.gz /data/sample1_R2.fastq.gz+```++Use actual tab characters, absolute paths visible to the runtime, and one row per sample.+Do not reverse-complement R2 files. Sample metadata is a tab-separated file with first column+`sample-id`, unique IDs matching the manifest, and optional `#q2:types` annotation. Include+covariates and biological replicate IDs needed downstream.++## Execute++The helper lives at [scripts/amplicon_workflow.py](scripts/amplicon_workflow.py). First validate+without QIIME. These example primers and lengths are **illustrative**, not universal assay settings:++```bash+python scripts/amplicon_workflow.py validate \+ --manifest manifest.tsv --metadata sample-metadata.tsv \+ --primer-f GTGYCAGCMGCCGCGGTAA --primer-r GGACTACNVGGGTWTCTAAT \+ --trunc-f 220 --trunc-r 200 --amplicon-max 300+```++Then run in the QIIME 2 2026.7 environment with a compatible classifier:++```bash+python scripts/amplicon_workflow.py run \+ --manifest manifest.tsv --metadata sample-metadata.tsv \+ --primer-f GTGYCAGCMGCCGCGGTAA --primer-r GGACTACNVGGGTWTCTAAT \+ --trunc-f 220 --trunc-r 200 --amplicon-max 300 \+ --classifier region-classifier.qza --threads 4 --output run01+```++`run` executes immediately, writes only to a fresh output directory, and stops on a failing QIIME+command. It streams through every paired FASTQ record to catch mismatched IDs/order/counts,+checks sequence/quality consistency and sample alignment, and profiles the first 1,000 read pairs+for exact IUPAC primer matches. Low exact-match rates are warnings: Cutadapt allows mismatches,+but a low rate can also indicate incorrect orientation, adapters, or already-trimmed data.++The runner uses `--output-dir` for plugin methods with evolving output sets, preserving Cutadapt+statistics and DADA2 base-transition artifacts when supplied by the release. The 2026.7 table+summary also produces `feature-frequencies.qza` and `sample-frequencies.qza` beside `table.qzv`.+It records+`qiime-info.txt`, `commands.json`, `workflow.log`, input QC, classifier checksum and output artifact+checksums. It runs maximum-level QIIME artifact validation before reporting completion.+See [references/runtime-and-interpretation.md](references/runtime-and-interpretation.md) for the+release-pinned runtime, actual validation scope, restart handling and scientific interpretation.++## Inspect results before analysis++Open `trimmed.qzv`, `table.qzv`, and `taxa.qzv` in a local QIIME visualization environment or+[QIIME 2 View](https://view.qiime2.org/) as appropriate for the data. Examine quality/length profiles,+per-sample depth and dominant taxa. Retain original artifacts rather than replacing them with+CSV/BIOM exports: exports do not retain the original provenance graph.++`retention-qc.json` compares raw pairs with DADA2 input and non-chimeric reads, so trimming losses+remain visible. A <50% retained fraction is a review heuristic, not a universal rejection rule.+Inspect the individual stages in `stats/stats.tsv`: filtering loss suggests quality/expected-error+settings; merging loss suggests overlap or orientation; chimera loss warrants reviewing library+quality and parameters. Investigate missing/zero samples and control behavior before rarefaction,+diversity, or differential abundance. Those downstream analyses need a separate design decision;+this skill does not choose a rarefaction depth automatically.++## Primary references++- [Current installation entry point](https://library.qiime2.org/quickstart/qiime2) and+ [amplicon documentation](https://amplicon-docs.qiime2.org/en/latest/).+- [Import formats](https://amplicon-docs.qiime2.org/en/latest/how-to-guides/how-to-import/).+- [Cutadapt actions](https://amplicon-docs.qiime2.org/en/latest/references/plugins/cutadapt/) and+ [DADA2 actions](https://amplicon-docs.qiime2.org/en/latest/references/plugins/dada2/).+- [Classifier data resources](https://library.qiime2.org/data-resources).++The rolling documentation may describe a development release. Inspect `qiime info` and action+`--help` in the exact installed environment before adapting the pinned runner to a later release.diff --git a/skills/qiime2-amplicon/references/runtime-and-interpretation.md b/skills/qiime2-amplicon/references/runtime-and-interpretation.mdnew file mode 100644index 00000000..ffddef8d--- /dev/null+++ b/skills/qiime2-amplicon/references/runtime-and-interpretation.md@@ -0,0 +1,116 @@+# Release-pinned runtime and interpretation++## Installation and environment++This runner targets **QIIME 2 2026.7**. The official distribution image is+`quay.io/qiime2/qiime2:2026.7` (the image naming changed from earlier `amplicon` releases).+Use the official [quickstart](https://library.qiime2.org/quickstart/qiime2) for its conda environment+or container. A PyPI package with a similar name is not a replacement for the distribution's R,+DADA2 and plugin environment. On Apple Silicon, the tested container uses Linux amd64 emulation.++For example, mount a data directory at `/data` and this skill at `/skill`, and run the Python helper+inside the container. Manifest absolute paths must be `/data/...`, not host-only paths. Ensure+enough disk space for both image download/unpacking and working artifacts; artifact creation can+copy/intermediately materialize the reads.++```bash+docker run --rm --platform linux/amd64 \+ -v "$PWD/data:/data" -v "$PWD/qiime2-amplicon:/skill:ro" \+ quay.io/qiime2/qiime2:2026.7 qiime info+```++`qiime info` and `qiime dada2 denoise-paired --help` in the target environment are the authoritative+command contract. Rolling web documentation can already describe `2026.10.0.dev0` and Python+`rachis` imports while an installed release has a different action signature. The runner uses the+CLI and release check rather than relying on rolling Python import paths. Both trimming and+DADA2 use `--output-dir`, preserving release-specific additional outputs. In 2026.7,+`feature-table summarize` takes `--m-metadata-file` and produces `--o-summary`,+`--o-feature-frequencies`, and `--o-sample-frequencies`; older tutorials using+`--m-sample-metadata-file` and `--o-visualization` do not apply to this action.++## Classifiers and provenance++Supply a trusted `TaxonomicClassifier` trained for the reference database/version, assay region,+and compatible QIIME/scikit-learn environment. Record database citation, region extraction primers,+training parameters, confidence threshold, source URL, artifact UUID and SHA-256. Keep the training+artifact lineage when available. QIIME's ZIP/schema validation does not establish the safety of an+untrusted serialized sklearn model.++If no matching classifier exists, train within the target distribution from an appropriate curated+reference sequence/taxonomy pair using its feature-classifier actions. A classifier trained on a+tiny test reference only validates execution and label plumbing; it says nothing about taxonomic+accuracy on biological samples. Do not silently substitute such a test reference for a real database.++The resulting QZA files preserve QIIME action provenance. `commands.json` supplements this with+actual CLI arguments; the runner also records release information and hashes. Copying only exported+FASTA/TSV/BIOM loses the artifact provenance graph. Retain the original FASTQs and classifier.++## Read retention and assay interpretation++The helper's overlap formula assumes fixed positive DADA2 truncation positions after primer+removal, no additional `trim-left`, and an upper bound on primer-free amplicon length. Use the+longest plausible insert rather than its mean. ITS and other highly variable-length amplicons need+a different strategy; applying a 16S fixed-length workflow can preferentially exclude taxa.++Exact primer-prefix matching profiles only the first 1,000 pairs. It is a diagnostic, not a+Cutadapt simulator: Cutadapt allows mismatches/indels according to its defaults. Anchoring assumes+primers begin at base one; staggered primers or remaining sequencing adapters need explicit+adaptation. The helper inspects every record for paired IDs, sequence/quality lengths and raw counts.+Phred+33 character validation cannot establish that the acquisition actually used Phred+33 rather+than Phred+64; obtain that fact from sequencing metadata.++Use `stats/stats.tsv` to localize losses. Raw → DADA2 input includes primer trimming; input →+filtered reflects quality/length/error limits; denoised → merged tests paired overlap; merged →+non-chimeric tests chimera removal. The runner's 50% retention warning is a review heuristic.+Do not automatically relax quality settings until every sample passes. Compare loss patterns by+batch, treatment, read quality, and controls, and report samples excluded from downstream analyses.++ASVs are denoised marker-gene sequences, not guaranteed species or organisms. 16S copy number,+primer bias and contamination affect abundance. Taxonomic confidence does not remove ambiguity+in a short region. Preserve unassigned features and investigate them before choosing exclusions.++## Restart behavior++The runner stops at the first failed command and leaves its log, command list and completed QZA+artifacts intact. It requires a new output directory for an entire rerun. To resume a specific step,+use the recorded QIIME command with validated preceding artifacts and a new output path, keeping+the original parameters unless the failure evidence justifies a change. A changed trimming or+DADA2 parameter produces a different analysis, not an interchangeable continuation.++## Actual integration evidence++The bounded regression used the official `quay.io/qiime2/qiime2:2026.7` image at digest+`sha256:ffde217254fe71bc3ace7f17d4ee5efebbad4f81dab52b6af8aee124ebc713c8`, under Linux+amd64 emulation on Apple Silicon. `qiime info` reported Python 3.12.13, rachis/q2cli 2026.7.0,+and the relevant plugins at 2026.7.0.++Ten nonempty paired samples, each with 100 pairs, derive from the official q2-dada2 regression+fixture at commit `8bbf5158d6c71b37b57a0e1f6e2b1cb69b9e96d7`. Synthetic Q40 primer prefixes were+added so the real Cutadapt stage restores the original upstream reads. The original empty BLANK+control is documented separately. DADA2 recovered exactly the expected **18 ASV sequences and+243 non-chimeric reads**; every sample's input, filtered, denoised, merged and non-chimeric counts+matched the upstream expected table. Two samples have zero retained reads, deliberately exercising+retention reporting rather than silently removing those samples from QC.++The run trained a tiny classifier inside the same environment using the expected sequences and+invented `SyntheticFixture` labels. Real `classify-sklearn` assigned those domain labels to all+18 ASVs, and table/taxonomy visualizations were produced. This verifies artifact and classification+plumbing, not biological taxonomic accuracy or a production database's suitability.++The initial run exposed the changed 2026.7 feature-table summary arguments described above.+After correcting the runner, execution resumed from the already completed DADA2 artifacts;+input import, trimming and denoising were not rerun. The runtime evidence retains both the failed+and corrected commands and the original artifact provenance. In a repository checkout,+`tests/qiime2-amplicon/run_integration.py --output FRESH_DIRECTORY` stages the bundled licensed+fixtures and runs the corrected workflow. Its `--verify-only RESULTS_DIRECTORY` mode independently+checks exact stage counts, ASV sequences, taxonomy feature IDs and synthetic labels, and artifact+action provenance. The portable pytest suite uses only the standard library and does not launch+or download the large QIIME distribution.++All **10 generated QZA artifacts** passed maximum-level QIIME validation. After three sequential+checks had passed, the remaining independent read-only checks used at most three identical+containers concurrently; an interrupted fourth check was recorded and rerun. The final retention+report was generated with the same bundled `retention` and `digest` functions. The standalone+integration verifier passed all count, sequence, taxonomy identity and action-provenance checks.+These results establish regression behavior on the small fixture, not DADA2 error-model+calibration or taxonomic accuracy for a new biological study.diff --git a/skills/qiime2-amplicon/scripts/amplicon_workflow.py b/skills/qiime2-amplicon/scripts/amplicon_workflow.pynew file mode 100644index 00000000..078c0bc1--- /dev/null+++ b/skills/qiime2-amplicon/scripts/amplicon_workflow.py@@ -0,0 +1,232 @@+#!/usr/bin/env python3+"""Validate paired-end amplicons and run a provenance-preserving QIIME 2 workflow."""+from __future__ import annotations++import argparse+import csv+import gzip+import hashlib+import itertools+import json+import math+from pathlib import Path+import re+import subprocess++IUPAC = dict(zip('ACGTRYSWKMBDHVN', ['A', 'C', 'G', 'T', 'AG', 'CT', 'GC', 'AT', 'GT', 'AC', 'CGT', 'AGT', 'ACT', 'ACG', 'ACGT']))+++def fastq(path: Path):+ opener = gzip.open if path.suffix == '.gz' else open+ with opener(path, 'rt', encoding='ascii') as handle:+ while True:+ name = handle.readline()+ if not name:+ break+ sequence, plus, quality = (handle.readline().rstrip('\r\n') for _ in range(3))+ if not name.startswith('@') or not plus.startswith('+') or not sequence or len(sequence) != len(quality):+ raise ValueError(f'Malformed four-line FASTQ record in {path}')+ if set(sequence.upper()) - set('ACGTN') or any(not 33 <= ord(c) <= 126 for c in quality):+ raise ValueError(f'Invalid sequence or Phred+33 characters in {path}')+ identifier = re.sub(r'/[12]$', '', name[1:].split()[0])+ yield identifier, sequence.upper()+++def primer_match(sequence: str, primer: str) -> bool:+ return len(sequence) >= len(primer) and all(base in IUPAC[p] for base, p in zip(sequence, primer))+++def read_metadata(path: Path) -> set[str]:+ with path.open(encoding='utf-8-sig') as handle:+ lines = [line for line in handle if line.strip() and not line.startswith('#q2:')]+ if not lines:+ raise ValueError('Metadata is empty')+ rows = list(csv.reader(lines, delimiter='\t'))+ if rows[0][0] not in ('sample-id', '#SampleID', 'sampleid', 'sample id', 'id'):+ raise ValueError('Use sample-id as the first metadata header')+ samples = [row[0] for row in rows[1:] if not row[0].startswith('#')]+ if any(not s for s in samples) or len(samples) != len(set(samples)):+ raise ValueError('Metadata has empty or duplicate sample IDs')+ return set(samples)+++def validate(manifest: Path, metadata: Path, primer_f: str, primer_r: str,+ trunc_f: int, trunc_r: int, amplicon_max: int, min_overlap: int = 12) -> dict:+ primers = (primer_f.upper(), primer_r.upper())+ if any(not p or set(p) - set(IUPAC) for p in primers):+ raise ValueError('Both primers must be nonempty IUPAC DNA, written 5-prime to 3-prime as sequenced')+ if min(trunc_f, trunc_r, amplicon_max) <= 0 or min_overlap < 12:+ raise ValueError('Positive post-primer truncation/amplicon lengths and overlap >=12 are required')+ overlap = trunc_f + trunc_r - amplicon_max+ if overlap < min_overlap:+ raise ValueError(f'Only {overlap} bp overlap remains; need at least {min_overlap}')+ with manifest.open(newline='', encoding='utf-8-sig') as handle:+ reader = csv.DictReader(handle, delimiter='\t')+ fields = ['sample-id', 'forward-absolute-filepath', 'reverse-absolute-filepath']+ if reader.fieldnames != fields:+ raise ValueError(f'PairedEndFastqManifestPhred33V2 requires tab-separated columns {fields}')+ rows = list(reader)+ seen, paths, results = set(), set(), []+ for row in rows:+ sample = row['sample-id']+ if not sample or sample in seen:+ raise ValueError(f'Empty or duplicate sample ID: {sample}')+ seen.add(sample)+ files = [Path(row[key]) for key in fields[1:]]+ if any(not p.is_absolute() or not p.is_file() for p in files):+ raise ValueError(f'{sample}: FASTQ paths must be absolute existing files')+ if len({p.resolve() for p in files}) != 2 or any(p.resolve() in paths for p in files):+ raise ValueError(f'{sample}: repeated forward/reverse FASTQ file')+ paths.update(p.resolve() for p in files)+ count, matched, lengths, too_short = 0, [0, 0], [0, 0], [0, 0]+ for forward, reverse in itertools.zip_longest(fastq(files[0]), fastq(files[1])):+ if forward is None or reverse is None or forward[0] != reverse[0]:+ raise ValueError(f'{sample}: paired read IDs/order/counts do not match')+ count += 1+ for i, read in enumerate((forward, reverse)):+ sequence = read[1]+ if count <= 1000:+ matched[i] += primer_match(sequence, primers[i])+ lengths[i] = max(lengths[i], len(sequence) - len(primers[i]))+ too_short[i] += len(sequence) - len(primers[i]) < (trunc_f, trunc_r)[i]+ if count == 0 or any(lengths[i] < (trunc_f, trunc_r)[i] for i in range(2)):+ raise ValueError(f'{sample}: no read pairs can survive requested truncation after primer removal')+ results.append({'sample_id': sample, 'raw_pairs': count,+ 'exact_primer_fraction_first_1000': [v/min(count, 1000) for v in matched],+ 'short_fraction_before_quality_filter': [v/count for v in too_short]})+ if not seen or read_metadata(metadata) != seen:+ raise ValueError('Manifest and metadata sample IDs must match exactly')+ warnings = [f"{s['sample_id']}: fewer than 80% exact primer-prefix matches; inspect orientation/adapters"+ for s in results if min(s['exact_primer_fraction_first_1000']) < 0.8]+ return {'samples': results, 'minimum_predicted_overlap': overlap, 'warnings': warnings}+++def retention(path: Path, raw_counts: dict[str, int] | None = None) -> dict:+ with path.open() as handle:+ reader = csv.DictReader((line for line in handle if not line.startswith('#q2:')), delimiter='\t')+ rows = list(reader)+ summaries, warnings = [], []+ for row in rows:+ sample = row.get('sample-id', row.get('sampleid', row.get('#SampleID')))+ if sample is None:+ raise ValueError('DADA2 statistics lack sample IDs')+ counts = [float(row[key]) for key in ['input', 'filtered', 'denoised', 'merged', 'non-chimeric']]+ if any(not math.isfinite(x) or x < 0 or not x.is_integer() for x in counts):+ raise ValueError('Invalid DADA2 read counts')+ if any(b > a for a, b in zip(counts, counts[1:])):+ raise ValueError('DADA2 retained counts increase between stages')+ raw = raw_counts[sample] if raw_counts is not None else int(counts[0])+ if counts[0] > raw:+ raise ValueError('DADA2 input exceeds raw read pairs')+ fraction = counts[-1]/raw if raw else 0.0+ if fraction < 0.5:+ warnings.append(f'{sample}: retained {fraction:.1%} of raw pairs; inspect trimming, quality, merging, chimeras')+ summaries.append({'sample_id': sample, 'raw_pairs': raw, 'dada2_input': int(counts[0]),+ 'non_chimeric': int(counts[-1]), 'retained_fraction': fraction})+ ids = [r['sample_id'] for r in summaries]+ if not ids or len(ids) != len(set(ids)) or (raw_counts is not None and set(ids) != set(raw_counts)):+ raise ValueError('Missing/duplicate samples in DADA2 statistics')+ return {'samples': summaries, 'warnings': warnings}+++def run(args) -> dict:+ qc = validate(args.manifest, args.metadata, args.primer_f, args.primer_r,+ args.trunc_f, args.trunc_r, args.amplicon_max, args.min_overlap)+ output = args.output.resolve()+ if output.exists() and any(output.iterdir()):+ raise ValueError('Use a fresh output directory; retain prior QIIME artifacts and provenance')+ if not args.classifier.is_file():+ raise ValueError('Provide a release-compatible TaxonomicClassifier .qza')+ info = subprocess.run([args.qiime, 'info'], check=True, text=True, capture_output=True).stdout+ if not re.search(r'2026\.7(?:\.|\b)', info):+ raise ValueError('This runner targets QIIME 2 2026.7; check qiime info and use the matching environment')+ output.mkdir(parents=True, exist_ok=True)+ (output/'qiime-info.txt').write_text(info)+ (output/'input-qc.json').write_text(json.dumps(qc, indent=2)+'\n')+ commands = []+ def invoke(*parts):+ command = [args.qiime, *map(str, parts)]+ commands.append(command)+ (output/'commands.json').write_text(json.dumps(commands, indent=2)+'\n')+ with (output/'workflow.log').open('a') as log:+ subprocess.run(command, stdout=log, stderr=subprocess.STDOUT, check=True)+ invoke('tools', 'validate', args.classifier.resolve(), '--level', 'max')+ invoke('tools', 'import', '--type', 'SampleData[PairedEndSequencesWithQuality]',+ '--input-format', 'PairedEndFastqManifestPhred33V2', '--input-path', args.manifest.resolve(),+ '--output-path', output/'demux.qza')+ invoke('cutadapt', 'trim-paired', '--i-demultiplexed-sequences', output/'demux.qza',+ '--p-front-f', '^'+args.primer_f.upper(), '--p-front-r', '^'+args.primer_r.upper(),+ '--p-discard-untrimmed', '--p-cores', args.threads, '--output-dir', output/'cutadapt')+ invoke('demux', 'summarize', '--i-data', output/'cutadapt/trimmed_sequences.qza', '--o-visualization', output/'trimmed.qzv')+ invoke('dada2', 'denoise-paired', '--i-demultiplexed-seqs', output/'cutadapt/trimmed_sequences.qza',+ '--p-trunc-len-f', args.trunc_f, '--p-trunc-len-r', args.trunc_r,+ '--p-trim-left-f', 0, '--p-trim-left-r', 0, '--p-min-overlap', args.min_overlap,+ '--p-n-threads', args.threads, '--output-dir', output/'denoise')+ invoke('feature-table', 'summarize', '--i-table', output/'denoise/table.qza',+ '--m-metadata-file', args.metadata.resolve(), '--o-summary', output/'table.qzv',+ '--o-feature-frequencies', output/'feature-frequencies.qza',+ '--o-sample-frequencies', output/'sample-frequencies.qza')+ invoke('feature-classifier', 'classify-sklearn', '--i-classifier', args.classifier.resolve(),+ '--i-reads', output/'denoise/representative_sequences.qza', '--p-n-jobs', args.threads,+ '--o-classification', output/'taxonomy.qza')+ invoke('taxa', 'barplot', '--i-table', output/'denoise/table.qza', '--i-taxonomy', output/'taxonomy.qza',+ '--m-metadata-file', args.metadata.resolve(), '--o-visualization', output/'taxa.qzv')+ invoke('tools', 'export', '--input-path', output/'denoise/denoising_stats.qza',+ '--output-path', output/'stats')+ artifacts = sorted(output.rglob('*.qza'))+ for artifact in artifacts:+ invoke('tools', 'validate', artifact, '--level', 'max')+ result = retention(output/'stats/stats.tsv', {s['sample_id']: s['raw_pairs'] for s in qc['samples']})+ result.update({'classifier_sha256': digest(args.classifier),+ 'manifest_sha256': digest(args.manifest), 'metadata_sha256': digest(args.metadata),+ 'artifacts': {str(p.relative_to(output)): digest(p) for p in artifacts}})+ (output/'retention-qc.json').write_text(json.dumps(result, indent=2)+'\n')+ return result+++def digest(path: Path) -> str:+ value = hashlib.sha256()+ with path.open('rb') as handle:+ for block in iter(lambda: handle.read(1024*1024), b''):+ value.update(block)+ return value.hexdigest()+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest='action', required=True)+ for action in ['validate', 'run']:+ command = sub.add_parser(action)+ command.add_argument('--manifest', type=Path, required=True)+ command.add_argument('--metadata', type=Path, required=True)+ command.add_argument('--primer-f', required=True)+ command.add_argument('--primer-r', required=True)+ command.add_argument('--trunc-f', type=int, required=True)+ command.add_argument('--trunc-r', type=int, required=True)+ command.add_argument('--amplicon-max', type=int, required=True, help='Maximum expected biological insert length AFTER removing primers')+ command.add_argument('--min-overlap', type=int, default=12)+ if action == 'run':+ command.add_argument('--classifier', type=Path, required=True)+ command.add_argument('--output', type=Path, required=True)+ command.add_argument('--qiime', default='qiime')+ command.add_argument('--threads', type=int, default=1)+ stats = sub.add_parser('retention')+ stats.add_argument('stats_tsv', type=Path)+ args = parser.parse_args()+ try:+ if args.action == 'run':+ if args.threads < 1:+ raise ValueError('threads must be positive')+ result = run(args)+ elif args.action == 'validate':+ result = validate(args.manifest, args.metadata, args.primer_f, args.primer_r,+ args.trunc_f, args.trunc_r, args.amplicon_max, args.min_overlap)+ else:+ result = retention(args.stats_tsv)+ except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as exc:+ parser.exit(1, f'Error: {exc}\n')+ print(json.dumps(result, indent=2))+++if __name__ == '__main__':+ main()diff --git a/skills/relion/SKILL.md b/skills/relion/SKILL.mdnew file mode 100644index 00000000..c3438d8e--- /dev/null+++ b/skills/relion/SKILL.md@@ -0,0 +1,120 @@+---+name: relion+description: Validates and executes RELION single-particle cryo-EM refinement and half-map postprocessing. Supports STAR optics/acquisition checks, particle-stack consistency, gold-standard half sets, soft-mask validation, diagnostic Fourier shell correlation, and restart guidance.+license: MIT+compatibility: Python 3.10+ with numpy, mrcfile and starfile for bundled validation; RELION 5.0.1 CPU/MPI executables for refinement and postprocessing. GPU builds require their supported accelerator stack. FFTW, OpenMP and MPI are build/runtime dependencies. Network is needed for installation only.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ upstream-version: "5.0.1"+---++# RELION single-particle refinement++Use for a RELION single-particle project, especially extracted particles → homogeneous selected+particle subset → gold-standard refinement → half-map validation and postprocessing. The bundled+runner starts from **CTF-annotated extracted particles and an initial 3D reference**. It does not+replace motion correction, picking, 2D/3D selection, or a biological interpretation of map quality.+For tomography, helical reconstruction, Blush, or heterogeneous-state modeling, use the appropriate+upstream workflow rather than forcing those data into this bounded SPA runner.++## Preserve acquisition and coordinate conventions++Read [references/acquisition-and-restarts.md](references/acquisition-and-restarts.md) when starting+from movies or resuming jobs. Confirm pixel size in **Å/pixel**, voltage in **kV**, spherical+aberration in **mm**, defocus in **Å**, amplitude contrast as a fraction, and the symmetry justified+by the specimen. Do not “correct” a suspicious value by guessing its units.++`data_optics` describes acquisition/image groups; `data_particles` references them through+`_rlnOpticsGroup`. Particle filenames use **one-based** `[email protected]`. Relative paths resolve+from the RELION project directory, not the STAR file's directory. Keep optics groups when merging+or subsetting STAR files. `_rlnOriginXAngst`/`_rlnOriginYAngst` are Å translations, not pixels.++Run from this skill directory with paths to the real project:++```bash+python scripts/spa_workflow.py validate-star project/particles.star --project project+```++This opens referenced stacks and checks optics membership, finite acquisition/CTF values, indices,+box sizes, duplicate particle references and existing half-set assignments. Use `--metadata-only`+only when stacks are genuinely unavailable, and report that the stack checks were omitted.+Physical-range warnings are review prompts, not proof that unusual microscope settings are wrong.++## Refine a selected particle population++Before running, inspect representative particles and class averages, defocus distributions, CTF+fits, particle orientation distribution, and the initial reference. Ensure the map and particle+boxes/pixel sizes agree after any downsampling. The runner deliberately supports one effective+box/pixel size across optics groups; handle heterogeneous sampling with an explicit upstream+resampling workflow.++```bash+python scripts/spa_workflow.py refine \+ --star project/particles.star --reference project/initial.mrc \+ --project project --diameter 180 --symmetry C1 \+ --initial-lowpass 40 --mpi-ranks 3 --threads 2 --output project/RefinePilot+```++The diameter and low-pass filter above are illustrative **Å** values. Use specimen-appropriate+values. Refinement executes `mpirun -np 3 relion_refine_mpi` with `--auto_refine`,+`--split_random_halves`, `--ctf`, and a low-pass starting reference. Gold-standard splitting+requires MPI; the plain sequential `relion_refine` executable cannot perform this split.+Use odd ranks ≥3 (master plus balanced half-set workers), with a matching MPI installation.+The CPU command is useful for a bounded pilot; choose a documented GPU/MPI launch for full data.++The runner keeps the command, native version and log in a new output directory, records an+explicit random seed (default 1), surfaces runtime warnings, stops on process failure, and+requires converged unfiltered half maps before reporting success. It does not automatically retry+expensive jobs or silently discard failed-job artifacts. Keep `_optimiser.star`, model/sampling+STAR files, and referenced particle paths for restart. Use the original job's optimiser rather+than starting a new random split from a partially processed table.++## Inspect independent half maps++Use the two independently refined **unfiltered** half maps, never two copies of the combined,+sharpened map. Matching headers cannot establish statistical independence; the independent+particle assignments and refinement history provide that evidence. Inspect directional+anisotropy, preferred orientation and local resolution as well as a global FSC curve.++```bash+python scripts/spa_workflow.py fsc \+ project/RefinePilot/run_half1_class001_unfil.mrc \+ project/RefinePilot/run_half2_class001_unfil.mrc --output diagnostic-fsc.tsv+```++This checks map dimensions, finite values, pixel size, origin, axis order and duplicate maps, then+writes an **unmasked diagnostic FSC**. The reported 0.143 crossing uses linear interpolation;+`null` means no downward crossing was detected, not infinite resolution. Nyquist resolution is+2 × pixel size. This diagnostic is limited to even cubic maps ≤256³; use RELION's native+`relion_image_handler --fsc` for larger maps. It does not substitute for mask-corrected FSC.++## Postprocess with a soft mask++Construct the solvent mask from an appropriately low-pass-filtered density, with an expanded+boundary and a smooth edge. Inspect all slices; a tight mask can inflate correlation. Avoid a+mask derived from high-frequency noise shared between half maps.++```bash+python scripts/spa_workflow.py postprocess \+ --half1 project/RefinePilot/run_half1_class001_unfil.mrc \+ --half2 project/RefinePilot/run_half2_class001_unfil.mrc \+ --mask project/soft_mask.mrc --output project/PostProcessPilot+```++The helper checks a nonconstant mask in [0,1], soft-edge voxels and matching map grids, then runs+`relion_postprocess` with explicit half maps, mask and pixel size. RELION performs its own+mask/randomization correction and writes `postprocess.star`. The bounded command leaves the+B-factor at its default; add automatic/manual sharpening only after choosing a defensible fit+range and inspecting map quality. A valid range and some fractional mask voxels do not prove the+mask is scientifically appropriate.++See [references/runtime-and-validation.md](references/runtime-and-validation.md) for the tested+native utilities and the distinction between pipeline execution and reconstruction validation.++## Primary references++- [RELION 5.0 installation](https://relion.readthedocs.io/en/release-5.0/Installation.html).+- [STAR and map conventions](https://relion.readthedocs.io/en/release-5.0/Reference/Conventions.html).+- [Single-particle tutorial](https://relion.readthedocs.io/en/release-5.0/SPA_tutorial/index.html).+- [Gold-standard refinement](https://relion.readthedocs.io/en/release-5.0/SPA_tutorial/Refine3D.html).diff --git a/skills/relion/references/acquisition-and-restarts.md b/skills/relion/references/acquisition-and-restarts.mdnew file mode 100644index 00000000..a09c14e3--- /dev/null+++ b/skills/relion/references/acquisition-and-restarts.md@@ -0,0 +1,63 @@+# Acquisition, job selection, and restart decisions++## Before extracted particles++Keep the project's movie/micrograph paths, optics groups, dose information, and gain/detector+metadata. For movies, confirm physical and super-resolution pixel sizes separately; a factor-of-two+pixel-size error propagates into defocus, extraction diameter, map scale and reported resolution.+For dose weighting, confirm dose per frame and pre-exposure rather than copying another dataset's+settings. Inspect drift trajectories, damaged frames and residual motion after correction.++RELION has an internal CPU motion-correction implementation and wrappers for external tools.+For CTF estimation, RELION 5.0 documentation specifies CTFFIND 4.1.x, not CTFFIND 5.x. A successful+wrapper launch does not validate a CTF fit: inspect Thon rings, astigmatism, fit resolution, and+defocus against acquisition expectations. Rejecting all high-defocus particles can introduce a+selection bias; use documented criteria appropriate to the specimen and target resolution.++Before 3D auto-refine, select a reasonably homogeneous particle population using actual 2D/3D+classification results. Do not interpret class occupancy as quantitative state populations without+considering selection and alignment bias. Avoid imposing high symmetry solely because it improves+nominal resolution. Use C1 when symmetry is unknown and test a justified alternative separately.++## Path and sampling invariants++A STAR file in `Extract/job010/` often points to paths relative to the project root. Moving only the+STAR file does not move its dependencies. The bundled validator takes `--project` to make this+explicit. It checks stack indices/box dimensions; optics pixel size is the sampling authority for+particle processing and still needs acquisition/re-extraction verification.++After resizing a particle box, adjust image pixel size to preserve physical field of view and+resample the initial reference consistently. Do not merely edit an MRC header to make a mismatch+disappear. Keep translations in their declared units (`Origin*Angst` versus legacy pixel fields).+For RELION's centered coordinate conventions, follow the official conventions page rather than+interpreting map array indices as laboratory coordinates.++## Restart a stopped refinement++A completed iteration's `_optimiser.star` points to the sampling/model/data state required for+continuation. Keep those referenced files and their relative paths together. Preserve the original+half-set split. An example continuation, from the same project root with the original MPI runtime:++```bash+mpirun -np 3 relion_refine_mpi \+ --continue RefinePilot/run_it005_optimiser.star \+ --o RefineContinue/run --j 2+```++The iteration filename is illustrative: use the last intact checkpoint actually present and a new+output prefix. Inspect the failing job log before deciding whether the cause was transient I/O,+insufficient memory, invalid CTF metadata, an absent external tool, or scientific nonconvergence.+Change one relevant condition, preserve the old job, and resume that checkpoint. Do not repeatedly+restart a deterministic invalid-input failure.++The GUI's Continue operation records the new job relationship in the RELION pipeline. A direct+command does not automatically supply every GUI bookkeeping relationship, so retain the command,+version/build, output prefix and source checkpoint alongside the results.++## Reporting resolution++Report the FSC threshold and mask correction, pixel size, particle count, imposed symmetry and+processing version. Keep both original half maps, the postprocessing STAR/PDF and mask. A scalar+FSC estimate can hide preferred orientation and regional flexibility; inspect local and directional+resolution and map-model validation before making structural claims. A high unmasked correlation+from duplicated or coupled half maps is a failure of independence, not a high-resolution result.diff --git a/skills/relion/references/runtime-and-validation.md b/skills/relion/references/runtime-and-validation.mdnew file mode 100644index 00000000..5305abb9--- /dev/null+++ b/skills/relion/references/runtime-and-validation.md@@ -0,0 +1,64 @@+# Runtime and verification scope++## Targeted build++The workflow targets **RELION 5.0.1**, source tag `5.0.1`, commit+`d476e6f6a4f1f37627c06ace5227fc374c0c2b05` from the+[official repository](https://github.com/3dem/relion/tree/5.0.1).+The Python helper was tested with Python 3.12, numpy 2.5.3, mrcfile 1.5.4 and starfile 0.5.13.++Native integration used a CPU-only, GUI-disabled build on Apple Silicon: AppleClang, OpenMPI+5.0.11, FFTW, OpenMP, and CMake 3.26. The build disabled optional model-weight downloads;+Blush, DynaMight, ModelAngelo and GPU paths were not installed or exercised. AppleClang required+explicit OpenMP include/library flags for the installed libomp. Use the official installation+instructions for the platform, and ensure the MPI runtime matches the binary's build.++The build targets are `image_handler`, `postprocess`, and `refine_mpi`; resulting executable names+are `relion_image_handler`, `relion_postprocess`, and `relion_refine_mpi`. MPI remains a dependency+of the RELION 5.0.1 source configuration even when acceleration and GUI support are disabled.+Keep native build artifacts outside the skill directory.++## What has been checked++- Real STAR parsing, optics-group/CTF checks and opening tiny particle stacks.+- Failure cases for undefined optics, invalid particle indices, duplicate references after path+ normalization, nonfinite metadata, reversed defocus signs, and invalid half-set assignments.+- Diagnostic FSC on two independently generated noisy 32³ maps sharing a smooth signal: high+ low-frequency correlation and a noise floor at high frequencies.+- The native `relion_image_handler --i half1.mrc --fsc half2.mrc --angpix 1.5` utility on those maps,+ with its shell curve compared to the Python diagnostic.+- Real `relion_postprocess` execution through the helper, using a smooth solvent mask, and a+ finite reported resolution in `postprocess.star`.+- A tiny native MPI auto-refine run with 32 noisy 16×16 synthetic projections, verifying the+ executable launch, final half maps and preservation of both particle half sets. The rotationally+ symmetric toy signal is not a physical CTF simulation; native alignment warnings are expected+ and its nominal resolution is not meaningful.+- Rejection of duplicated half maps, inconsistent sampling, and hard-edged masks.++These small synthetic maps establish executable/format/FSC behavior, not a validated biological+reconstruction or mask-selection strategy. Full production-data refinement, external motion+correction/CTF programs and GPU acceleration require verification on the actual installation and+representative experimental data. Example particle diameters, resolutions and checkpoint names+in the entry point are illustrative.++## Reproduce native utility regression tests++In a repository checkout, use an isolated Python environment containing the three Python packages+above and pytest. Set `RELION_IMAGE_HANDLER_TEST_EXECUTABLE` and+`RELION_POSTPROCESS_TEST_EXECUTABLE` to the corresponding native binaries. Set+`RELION_REFINE_TEST_EXECUTABLE` to `relion_refine_mpi` for the additional MPI smoke test with+`mpirun` on PATH, then run+`python -m pytest tests/relion -q`. The suite constructs the synthetic STAR/MRC data in a temporary+folder. Without those variables, only the explicit native integration cases are skipped; local+scientific validation and CLI tests run normally.++A native diagnostic command writes its FSC STAR table to standard output:++```bash+relion_image_handler --i half1.mrc --fsc half2.mrc --angpix 1.5 > unmasked-fsc.star+```++Use the actual image sampling. Compare the resulting curve with corrected FSC from postprocessing;+they answer different questions. The Python diagnostic uses shell-rounded radii and conjugate+weights for an rFFT. The native utility's Fourier-grid conventions can produce small shell-wise+differences on tiny maps; the regression checks agreement within 0.06 rather than bitwise identity.diff --git a/skills/relion/scripts/spa_workflow.py b/skills/relion/scripts/spa_workflow.pynew file mode 100644index 00000000..78b9fce6--- /dev/null+++ b/skills/relion/scripts/spa_workflow.py@@ -0,0 +1,241 @@+#!/usr/bin/env python3+"""Validate RELION SPA inputs, run refinement/postprocessing, and inspect half-map FSC."""+from __future__ import annotations++import argparse+import csv+import json+import math+from pathlib import Path+import re+import subprocess+++def read_map(path: Path, max_voxels: int | None = None):+ import mrcfile+ import numpy as np+ with mrcfile.mmap(path, permissive=False) as handle:+ if max_voxels is not None and handle.data.size > max_voxels:+ raise ValueError("Python diagnostic limited to 256-cubed maps; use relion_image_handler --fsc for larger maps")+ data = handle.data.copy()+ voxel = tuple(float(handle.voxel_size[axis]) for axis in ('x', 'y', 'z'))+ origin = tuple(float(handle.header.origin[axis]) for axis in ('x', 'y', 'z'))+ axes = tuple(int(handle.header[axis]) for axis in ('mapc', 'mapr', 'maps'))+ if data.ndim != 3 or len(set(data.shape)) != 1 or min(data.shape) < 4 or data.shape[0] % 2:+ raise ValueError(f'{path}: expected an even-sized cubic 3D map')+ if not np.isfinite(data).all() or not all(math.isfinite(x) for x in voxel + origin):+ raise ValueError(f'{path}: nonfinite map or header')+ if min(voxel) <= 0 or not np.allclose(voxel, voxel[0], rtol=1e-5):+ raise ValueError(f'{path}: positive isotropic voxel size required')+ if axes != (1, 2, 3):+ raise ValueError(f'{path}: noncanonical map axes; explicitly reorder before analysis')+ return data, voxel[0], origin+++def validate_star(path: Path, project: Path, check_stacks: bool = True) -> dict:+ import mrcfile+ import numpy as np+ import starfile+ blocks = starfile.read(path, always_dict=True)+ if not {'optics', 'particles'}.issubset(blocks):+ raise ValueError('Requires RELION 3.1+ data_optics and data_particles blocks')+ optics, particles = blocks['optics'], blocks['particles']+ needed_optics = {'rlnOpticsGroup', 'rlnVoltage', 'rlnSphericalAberration', 'rlnAmplitudeContrast',+ 'rlnImagePixelSize', 'rlnImageSize', 'rlnImageDimensionality'}+ needed_particles = {'rlnOpticsGroup', 'rlnImageName', 'rlnDefocusU', 'rlnDefocusV', 'rlnDefocusAngle'}+ if not needed_optics.issubset(optics.columns) or not needed_particles.issubset(particles.columns):+ raise ValueError('Missing optics/acquisition/CTF columns for a 2D-particle SPA refinement')+ if len(optics) == 0 or len(particles) == 0 or optics.rlnOpticsGroup.duplicated().any():+ raise ValueError('Empty tables or duplicate optics group IDs')+ for frame, columns in [(optics, needed_optics), (particles, needed_particles - {'rlnImageName'})]:+ for column in columns:+ values = np.asarray(frame[column], dtype=float)+ if not np.isfinite(values).all():+ raise ValueError(f'Nonfinite values in {column}')+ if any(optics.rlnOpticsGroup <= 0) or any(optics.rlnOpticsGroup % 1):+ raise ValueError('Optics group IDs must be positive integers')+ if not set(particles.rlnOpticsGroup).issubset(set(optics.rlnOpticsGroup)):+ raise ValueError('Particle references an undefined optics group')+ if any(optics.rlnImagePixelSize <= 0) or any(optics.rlnVoltage <= 0) or any(optics.rlnSphericalAberration < 0):+ raise ValueError('Pixel size/voltage must be positive and spherical aberration nonnegative')+ if any((optics.rlnAmplitudeContrast < 0) | (optics.rlnAmplitudeContrast >= 1)):+ raise ValueError('Amplitude contrast must be in [0,1)')+ if any(optics.rlnImageDimensionality != 2) or any(optics.rlnImageSize < 4) or any(optics.rlnImageSize % 2):+ raise ValueError('This runner requires 2D particles with an even box size >=4')+ if any(particles.rlnDefocusU <= 0) or any(particles.rlnDefocusV <= 0):+ raise ValueError('Underfocus values must be positive Angstroms; verify CTF import units/sign')+ if particles.rlnImageName.duplicated().any():+ raise ValueError('Duplicate particle image references can leak between half sets')+ subsets = None+ if 'rlnRandomSubset' in particles:+ values = set(particles.rlnRandomSubset)+ if values != {1, 2}:+ raise ValueError('Existing rlnRandomSubset must contain both half sets, encoded 1 and 2')+ subsets = {str(k): int(v) for k, v in particles.rlnRandomSubset.value_counts().items()}+ groups = optics.set_index('rlnOpticsGroup')+ stack_cache, canonical_images = {}, set()+ for row in particles.itertuples(index=False):+ match = re.fullmatch(r'([1-9][0-9]*)@(.+)', str(row.rlnImageName))+ if not match:+ raise ValueError(f'Expected 1-based [email protected]: {row.rlnImageName}')+ index, stack_name = int(match[1]), match[2]+ stack = Path(stack_name)+ stack = stack if stack.is_absolute() else project / stack+ identity = (index, stack.resolve())+ if identity in canonical_images:+ raise ValueError('Duplicate particle image after path normalization')+ canonical_images.add(identity)+ if check_stacks:+ if stack not in stack_cache:+ with mrcfile.mmap(stack, permissive=False) as handle:+ shape = handle.data.shape+ # MRC may expose a single image as 2D rather than a stack of length one.+ stack_cache[stack] = ((1, *shape) if len(shape) == 2 else shape)+ shape = stack_cache[stack]+ box = int(groups.loc[row.rlnOpticsGroup, 'rlnImageSize'])+ if len(shape) != 3 or index > shape[0] or shape[1:] != (box, box):+ raise ValueError(f'Particle stack index/box does not agree with optics: {row.rlnImageName}')+ warnings = []+ if any((optics.rlnVoltage < 60) | (optics.rlnVoltage > 400)):+ warnings.append('Unusual voltage; confirm kV rather than V')+ if any(particles.rlnDefocusU > 100000) or any(particles.rlnDefocusV > 100000):+ warnings.append('Defocus exceeds 10 micrometers; inspect CTF fits and units')+ return {'particles': len(particles), 'optics_groups': len(optics), 'half_sets': subsets,+ 'pixel_sizes_angstrom': sorted(set(float(x) for x in optics.rlnImagePixelSize)),+ 'box_sizes': sorted(set(int(x) for x in optics.rlnImageSize)), 'warnings': warnings}+++def check_halves(first: Path, second: Path, mask: Path | None = None, max_voxels: int | None = None):+ import numpy as np+ a, pixel, origin = read_map(first, max_voxels)+ b, other_pixel, other_origin = read_map(second, max_voxels)+ if a.shape != b.shape or not np.isclose(pixel, other_pixel) or not np.allclose(origin, other_origin):+ raise ValueError('Half maps disagree in grid, pixel size, or origin')+ if np.array_equal(a, b):+ raise ValueError('Half maps are identical; provide independent unfiltered half reconstructions')+ if np.std(a) == 0 or np.std(b) == 0:+ raise ValueError('Constant half map has no measurable signal')+ if mask:+ m, mp, mo = read_map(mask)+ if m.shape != a.shape or not np.isclose(pixel, mp) or not np.allclose(origin, mo):+ raise ValueError('Mask grid differs from half maps')+ if m.min() < 0 or m.max() > 1 or m.max() == m.min():+ raise ValueError('Mask must be nonconstant and lie in [0,1]')+ if not np.any((m > 0) & (m < 1)):+ raise ValueError('Mask has no soft edge; generate a soft solvent mask')+ return a, b, pixel+++def fsc(first: Path, second: Path, output: Path) -> dict:+ import numpy as np+ a, b, pixel = check_halves(first, second, max_voxels=256**3)+ n = a.shape[0]+ fa, fb = np.fft.rfftn(a), np.fft.rfftn(b)+ z, y, x = np.ogrid[-n//2:n-n//2, -n//2:n-n//2, 0:n//2+1]+ shells = np.floor(np.sqrt(z*z+y*y+x*x)+0.5).astype(int)+ # Shift only the fully represented axes; weight interior rFFT x planes twice.+ fa, fb = np.fft.fftshift(fa, axes=(0,1)), np.fft.fftshift(fb, axes=(0,1))+ weights = np.ones(fa.shape); weights[:,:,1:-1] = 2+ cross = np.bincount(shells.ravel(), weights=(weights*(fa*np.conj(fb)).real).ravel())+ power_a = np.bincount(shells.ravel(), weights=(weights*abs(fa)**2).ravel())+ power_b = np.bincount(shells.ravel(), weights=(weights*abs(fb)**2).ravel())+ counts = np.bincount(shells.ravel(), weights=weights.ravel())+ denominator = np.sqrt(power_a*power_b)+ values = np.divide(cross, denominator, out=np.full_like(cross, np.nan), where=denominator>0)+ rows = [{'shell': k, 'frequency_inv_angstrom': k/(n*pixel),+ 'fsc': float(values[k]) if np.isfinite(values[k]) else None,+ 'fourier_samples': int(counts[k])} for k in range(n//2+1)]+ crossing = None+ for previous, current in zip(rows[1:], rows[2:]):+ a_fsc, b_fsc = previous['fsc'], current['fsc']+ if a_fsc is not None and b_fsc is not None and a_fsc >= 0.143 > b_fsc:+ frequency = previous['frequency_inv_angstrom'] + (0.143-a_fsc)/(b_fsc-a_fsc)/(n*pixel)+ crossing = 1/frequency+ break+ output.parent.mkdir(parents=True, exist_ok=True)+ with output.open('w', newline='') as handle:+ writer = csv.DictWriter(handle, fieldnames=list(rows[0]), delimiter='\t')+ writer.writeheader(); writer.writerows(rows)+ return {'unmasked_diagnostic_fsc_0143_angstrom': crossing, 'nyquist_angstrom': 2*pixel,+ 'warning': 'Diagnostic unmasked FSC; use corrected RELION postprocessing FSC for reported global resolution',+ 'shells': len(rows)}+++def run_native_command(command: list[str], output: Path, project: Path, executable: str) -> None:+ if output.exists() and any(output.iterdir()):+ raise ValueError('Use an empty output directory; preserve prior jobs for restart/provenance')+ version = subprocess.run([executable, '--version'], capture_output=True, text=True, check=True)+ version_text = version.stdout + version.stderr+ if '5.0.1' not in version_text:+ raise ValueError('This runner targets RELION5.0.1; verify the installed executable before adapting it')+ output.mkdir(parents=True, exist_ok=True)+ (output/'version.txt').write_text(version_text)+ (output/'command.json').write_text(json.dumps(command, indent=2)+'\n')+ with (output/'run.log').open('w') as log:+ subprocess.run(command, cwd=project, stdout=log, stderr=subprocess.STDOUT, check=True)+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ sub = parser.add_subparsers(dest='action', required=True)+ star = sub.add_parser('validate-star')+ star.add_argument('star', type=Path); star.add_argument('--project', type=Path, default=Path.cwd())+ star.add_argument('--metadata-only', action='store_true', help='Explicitly omit opening particle stacks')+ comparison = sub.add_parser('fsc')+ comparison.add_argument('half1', type=Path); comparison.add_argument('half2', type=Path)+ comparison.add_argument('--output', type=Path, required=True)+ refine = sub.add_parser('refine')+ refine.add_argument('--star', type=Path, required=True); refine.add_argument('--reference', type=Path, required=True)+ refine.add_argument('--diameter', type=float, required=True, help='Particle diameter in Angstroms')+ refine.add_argument('--symmetry', default='C1'); refine.add_argument('--initial-lowpass', type=float, default=40.0)+ refine.add_argument('--threads', type=int, default=1); refine.add_argument('--executable', default='relion_refine_mpi')+ refine.add_argument('--mpirun', default='mpirun'); refine.add_argument('--mpi-ranks', type=int, default=3)+ refine.add_argument('--seed', type=int, default=1)+ refine.add_argument('--project', type=Path, default=Path.cwd()); refine.add_argument('--output', type=Path, required=True)+ post = sub.add_parser('postprocess')+ post.add_argument('--half1', type=Path, required=True); post.add_argument('--half2', type=Path, required=True)+ post.add_argument('--mask', type=Path, required=True); post.add_argument('--output', type=Path, required=True)+ post.add_argument('--executable', default='relion_postprocess')+ args = parser.parse_args()+ try:+ if args.action == 'validate-star':+ result = validate_star(args.star, args.project, not args.metadata_only)+ elif args.action == 'fsc':+ result = fsc(args.half1, args.half2, args.output)+ elif args.action == 'refine':+ result = validate_star(args.star, args.project)+ reference, pixel, _ = read_map(args.reference)+ if result['box_sizes'] != [reference.shape[0]] or any(abs(p-pixel)>1e-5*pixel for p in result['pixel_sizes_angstrom']):+ raise ValueError('Reference box/pixel size must match all particle optics groups for this bounded runner')+ if not 0 < args.diameter < reference.shape[0]*pixel or args.initial_lowpass < 2*pixel or args.threads<1 or args.mpi_ranks<3 or args.mpi_ranks%2 == 0:+ raise ValueError('Invalid diameter, lowpass, threads or MPI ranks (use odd ranks >=3)')+ if not re.fullmatch(r'(?:[CD][1-9][0-9]*|[TO]|I[1-4]?)', args.symmetry):+ raise ValueError('Use an explicit supported RELION point-group symmetry such as C1, D2, O, I1')+ command = [args.mpirun, '-np', str(args.mpi_ranks), args.executable, '--o', str(args.output.resolve()/'run'), '--i', str(args.star.resolve()),+ '--ref', str(args.reference.resolve()), '--auto_refine', '--split_random_halves', '--ctf',+ '--firstiter_cc', '--ini_high', str(args.initial_lowpass), '--sym', args.symmetry,+ '--particle_diameter', str(args.diameter), '--flatten_solvent', '--zero_mask',+ '--oversampling', '1', '--healpix_order', '2', '--auto_local_healpix_order', '4',+ '--offset_range', '5', '--offset_step', '2', '--j', str(args.threads), '--random_seed', str(args.seed)]+ run_native_command(command, args.output.resolve(), args.project.resolve(), args.executable)+ if not all((args.output/f'run_half{k}_class001_unfil.mrc').is_file() for k in (1,2)):+ raise ValueError('Refinement exited without converged unfiltered half maps; inspect run.log/optimiser')+ result['refined_particles'] = validate_star(args.output/'run_data.star', args.project)+ result['runtime_warnings'] = list(dict.fromkeys(line.split('WARNING:', 1)[1].strip()+ for line in (args.output/'run.log').read_text().splitlines() if 'WARNING:' in line))+ result['command'] = command+ else:+ _, _, pixel = check_halves(args.half1, args.half2, args.mask)+ command = [args.executable, '--i', str(args.half1.resolve()), '--i2', str(args.half2.resolve()),+ '--mask', str(args.mask.resolve()), '--angpix', str(pixel), '--o', str(args.output.resolve()/'postprocess')]+ run_native_command(command, args.output.resolve(), Path.cwd(), args.executable)+ if not (args.output/'postprocess.star').is_file():+ raise ValueError('Postprocess did not produce postprocess.star')+ result = {'command': command, 'pixel_size_angstrom': pixel}+ except (ValueError, OSError, KeyError, subprocess.CalledProcessError) as exc:+ parser.exit(1, f'Error: {exc}\n')+ print(json.dumps(result, indent=2))+++if __name__ == '__main__':+ main()diff --git a/skills/tellurium/SKILL.md b/skills/tellurium/SKILL.mdnew file mode 100644index 00000000..25d7f7da--- /dev/null+++ b/skills/tellurium/SKILL.md@@ -0,0 +1,106 @@+---+name: tellurium+description: Simulates biochemical kinetic models from SBML or Antimony with Tellurium and libRoadRunner, checks model units, compares deterministic parameter perturbations, and exports and replays SBML plus SED-ML COMBINE archives. Use for reaction-network time courses, kinetic parameters, concentration dynamics and reproducible simulation experiments; steady-state constraint-based metabolic flux analysis belongs to cobrapy.+license: MIT+compatibility: Requires Python 3.11 with Tellurium 2.2.13.1, libRoadRunner 2.10.0, Antimony 3.2.0, python-libsbml 5.21.2, python-libsedml 2.0.34 and python-libcombine 0.2.20. Network is needed for installation only. Native wheels were tested on macOS ARM64. No credentials or external services.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ upstream-version: "2.2.13.1"+---++# Tellurium kinetic experiments++## When to use++Use this skill for deterministic reaction-network trajectories and independent parameter conditions+from a local model. The helper performs SBML consistency checks, CVODE integration and an actual+COMBINE archive replay. It exports each condition's exact SBML and the SED-ML experiment rather+than handing off an unrecorded notebook state.++## Runtime++```bash+uv venv --python 3.11 kinetic-env+uv pip install --python kinetic-env/bin/python tellurium==2.2.13.1 libroadrunner==2.10.0 \+ antimony==3.2.0 python-libsbml==5.21.2 python-libsedml==2.0.34 python-libcombine==0.2.20+```++The full workflow ran with these packages on macOS ARM64. It constructs SED-ML with libSEDML and+archives with Tellurium/libCombine; PhraSEDML is not required by this helper. Headless runs can set+`MPLBACKEND=Agg`. No plotting window is opened by the helper.++## Workflow++1. Inspect the supplied model's compartments, species, initial conditions, boundary species,+ reactions, parameter definitions and rules/events. Identify the scientific question and+ distinguish a mechanistic kinetic model from a flux-balance reconstruction. Record the+ source model, version and any literature parameters; do not treat an example model as+ experimentally calibrated.+2. Check units before interpreting a trajectory. SBML reaction rates have amount/time units;+ species may have concentration or amount semantics. In a fixed-volume first-order model,+ `k*A*cell` converts concentration dependence into amount/time. The helper checks SBML+ consistency and retains every warning, including undefined units. Undefined units are+ reported as empty/indeterminable, not silently assumed to mean SI.+3. Select concentration outputs and an experiment in the JSON format described in+ [references/experiments.md](references/experiments.md). Time values use the model's own time+ units. The tested helper outputs concentration for species with `hasOnlySubstanceUnits=false`;+ it rejects amount-only selections to avoid changing their meaning during SED-ML replay.+4. Run baseline and desired constant-global-parameter changes. Every scenario starts from a+ fresh SBML model, so previous final concentrations cannot leak into the next condition.+ Changes to species initial values, compartment volume, assignment rules or time-varying+ inputs require explicit model changes and corresponding tests; they are not parameter+ mutations hidden in this helper.+5. Examine finite outputs, signs, relevant conservation relations and timescales. Check solver+ sensitivity by repeating at stricter tolerances when the scientific interpretation depends+ on small differences. A smooth curve or zero archive-replay error does not establish model+ validity or parameter identifiability. Never clip negative concentrations to hide solver+ or model problems.+6. Review the COMBINE replay comparison, model warnings and units in `report.json`. The helper+ replays the archive it generated and compares every selected value against the direct+ trajectories. Deliver the archive, report, source model, experiment config and CSV curves.++## Run the executable reference++[assets/first-order.ant](assets/first-order.ant) defines the closed reaction A → B in a constant+1-L compartment, initially A=1 and B=0 mol/L, with k=0.2 per second.+[assets/experiment.json](assets/experiment.json) runs baseline and k=0.4 per second from 0 to 10 s.+From the skill directory, point the interpreter to the environment created above:++```bash+MPLBACKEND=Agg kinetic-env/bin/python scripts/kinetic_experiment.py \+ --model assets/first-order.ant --format antimony --experiment assets/experiment.json \+ --output kinetic-reference++# The SBML branch was also exercised; replace these filenames with actual user inputs.+MPLBACKEND=Agg kinetic-env/bin/python scripts/kinetic_experiment.py \+ --model model.xml --format sbml --experiment experiment.json --output kinetic-analysis+```++Output directories must be new. The reference was executed, including Antimony-to-SBML conversion,+libSBML checks, both direct integrations, SED-ML creation and COMBINE replay. Both conditions matched+the analytical `A(t)=exp(-k*t)`, `B(t)=1-A(t)` within 2e-8 absolute/relative tolerance; A+B was+conserved within 1e-10, and archive replay matched direct output exactly on the tested stack.+That verifies this controlled example; arbitrary SBML packages, events, delays or stochastic models+are not covered by those tests.++## Artifacts++| File | Contents |+| --- | --- |+| `baseline.csv`, other scenario CSVs | Time and selected concentrations, with bracketed species headers |+| `model_<scenario>.xml` | Exact independent SBML condition used by both execution routes |+| `experiment.sedml` | Uniform time course, CVODE/tolerances, models, tasks and output selections |+| `experiment.omex` | Those SBML files plus the master SED-ML and archive manifest |+| `report.json` | Versions, input/archive checksums, parameters, units, validation findings, minimum concentrations and replay differences |++The libSEDML findings in the report are **parse diagnostics**. Successful execution and equality+provide additional evidence that this generated uniform-course experiment works in Tellurium;+they do not certify every SED-ML feature or every simulator's compatibility.++## Primary references++- [Tellurium model loading and export methods](https://tellurium.readthedocs.io/en/latest/tellurium_methods.html)+- [Antimony unit and reaction semantics](https://tellurium.readthedocs.io/en/latest/antimony.html)+- [COMBINE and SED-ML examples](https://tellurium.readthedocs.io/en/latest/notebooks.html)+- [libRoadRunner documentation](https://libroadrunner.readthedocs.io/)diff --git a/skills/tellurium/assets/experiment.json b/skills/tellurium/assets/experiment.jsonnew file mode 100644index 00000000..7100bbea--- /dev/null+++ b/skills/tellurium/assets/experiment.json@@ -0,0 +1,11 @@+{+ "end_time": 10.0,+ "points": 101,+ "relative_tolerance": 1e-9,+ "absolute_tolerance": 1e-12,+ "species": ["A", "B"],+ "scenarios": {+ "baseline": {},+ "double_k": {"k": 0.4}+ }+}diff --git a/skills/tellurium/assets/first-order.ant b/skills/tellurium/assets/first-order.antnew file mode 100644index 00000000..42023b3c--- /dev/null+++ b/skills/tellurium/assets/first-order.ant@@ -0,0 +1,17 @@+// Synthetic closed, constant-volume first-order conversion; concentrations in mol/L.+model first_order()+ compartment cell = 1;+ cell has litre;+ species A in cell, B in cell;+ A = 1; A has molar;+ B = 0; B has molar;+ k = 0.2; k has per_second;+ conversion: A -> B; k*A*cell;+ const cell, k;+ unit molar = mole / litre;+ unit per_second = 1 / second;+ unit substance = mole;+ unit extent = mole;+ unit volume = litre;+ unit time_unit = second;+enddiff --git a/skills/tellurium/references/experiments.md b/skills/tellurium/references/experiments.mdnew file mode 100644index 00000000..101d4d7c--- /dev/null+++ b/skills/tellurium/references/experiments.md@@ -0,0 +1,68 @@+# Experiment semantics and reproducibility++The JSON accepts exactly these keys:++| Key | Meaning |+| --- | --- |+| `end_time` | Positive end of integration, in the model's time unit; initial and output start are zero |+| `points` | Number of saved samples including both endpoints, integer >=2 |+| `relative_tolerance`, `absolute_tolerance` | Positive CVODE error-control settings |+| `species` | Unique SBML IDs to report as concentrations |+| `scenarios` | Named mappings of constant global parameter IDs to finite numeric values; includes `baseline: {}` |++Scenario names must be SBML-style identifiers. Parameter changes are applied to independent cloned+SBML documents before RoadRunner loads them, and the modified files become the archive models.+The helper rejects nonexistent/nonconstant parameters and parameters with initial assignments,+because setting a numeric field there would not necessarily implement the requested perturbation.+A fresh model per condition avoids ambiguity between RoadRunner reset variants and persistent+parameter changes.++The supplied two-condition first-order model is synthetic. Its units are explicit: time in seconds,+volume in liters, species concentrations in mol/L and k in inverse seconds. Reaction flux is+`k*A*cell` mol/s. Unit annotations describe dimensions; merely changing a unit label does not rescale+a numeric initial value or kinetic constant. Check dimensional consistency and magnitudes together.++For a closed constant-volume A→B model, the conserved amount is compartment volume times A+B.+The example's volume is exactly 1 L, so its concentration sum also stays numerically one. In a+variable-volume model, open system, synthesis/degradation model or chemostatted network, the same+concentration-sum check would be invalid. Choose invariants from the actual stoichiometry and+boundary conditions rather than treating total species sum as universally conserved.++## SBML and solver checks++libSBML parses the source and runs consistency checks before simulation. Errors/fatal diagnostics+stop execution; warnings remain in the report for review. Missing units do not prevent numerical+execution but prevent a claim of dimensional validation. Confirm the units of every reported+concentration and parameter. The helper reports the minimum concentration per scenario rather than+clipping negatives. Small negatives near zero may reflect tolerance; significant negatives require+investigating the equations, initial state and solver behavior.++CVODE uses stiff integration with explicit relative and absolute tolerances. Output samples are not+internal integration steps. Repeat selected scientifically relevant cases at tighter tolerances and+compare outputs, conservation residuals and event timing. For concentrations near zero, absolute+rather than relative tolerance dominates. Very different species scales may require a model-specific+per-species tolerance workflow beyond this scalar-tolerance helper.++The script is scoped to deterministic concentration trajectories. Stochastic counts, amount-only+species, event-rich models, delay equations, external SBML comp references and arbitrary package+extensions require separate verification before extending these guarantees. No model or data is+uploaded to an external solver.++## Archive experiment++The helper writes SED-ML Level 1 Version 3 with one uniform simulation, one model/task per scenario,+and a report with data generators for time and each selected species. It encodes CVODE as+`KISAO:0000019`, relative tolerance as `KISAO:0000209`, and absolute tolerance as `KISAO:0000211`.+SED-ML `numberOfPoints` is **intervals**, so the script writes `points - 1` to retain exactly the+number of samples requested by RoadRunner.++COMBINE entries use local filenames and one master SED-ML. `executeCombineArchive` replays only+this newly generated archive; the helper is not an arbitrary archive extraction interface. Every+replayed data generator is compared to the corresponding direct trajectory before the run reports+success. A baseline-only archive does not represent perturbations, so all condition-specific SBML+files are included. Export/replay was verified without optional PhraSEDML.++Replay tests reproducibility of the represented experiment on this runtime. It does not test+biological plausibility, independent model calibration, cross-simulator numerical agreement or+interoperability of unexercised SED-ML features. Preserve the source model, full config and report+alongside the archive, including warnings and exact runtime versions.diff --git a/skills/tellurium/scripts/kinetic_experiment.py b/skills/tellurium/scripts/kinetic_experiment.pynew file mode 100644index 00000000..9fba78d3--- /dev/null+++ b/skills/tellurium/scripts/kinetic_experiment.py@@ -0,0 +1,170 @@+"""Simulate local SBML/Antimony models and verify replay of a generated COMBINE archive."""+from __future__ import annotations++import argparse+import csv+import hashlib+import importlib.metadata+import json+import math+from pathlib import Path+import re+++def model_document(path, model_format):+ import libsbml+ import tellurium as te+ source = Path(path).read_text()+ sbml = te.antimonyToSBML(source) if model_format == "antimony" else source+ document = libsbml.readSBMLFromString(sbml)+ if document.getModel() is None:+ raise ValueError("Input has no SBML model")+ document.checkConsistency()+ issues = [{"id": document.getError(i).getErrorId(), "severity": document.getError(i).getSeverityAsString(),+ "message": document.getError(i).getMessage().strip()} for i in range(document.getNumErrors())]+ if any(issue["severity"] in {"Error", "Fatal"} for issue in issues):+ raise ValueError("SBML validation errors: " + json.dumps(issues))+ return document, issues+++def validate_experiment(config, model):+ allowed = {"end_time", "points", "relative_tolerance", "absolute_tolerance", "species", "scenarios"}+ if set(config) != allowed:+ raise ValueError(f"Experiment requires exactly {sorted(allowed)}")+ for name in ("end_time", "relative_tolerance", "absolute_tolerance"):+ value = config[name]+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or value <= 0:+ raise ValueError(f"{name} must be positive and finite")+ if isinstance(config["points"], bool) or not isinstance(config["points"], int) or config["points"] < 2:+ raise ValueError("points must be an integer >=2 (including both endpoints)")+ species = config["species"]+ if not species or len(set(species)) != len(species) or any(model.getSpecies(s) is None for s in species):+ raise ValueError("species must contain unique SBML species IDs")+ # SED-ML species targets below use SBML concentration semantics.+ if any(model.getSpecies(s).getHasOnlySubstanceUnits() for s in species):+ raise ValueError("This archive workflow selects concentrations; amount-only species need an explicit amount workflow")+ scenarios = config["scenarios"]+ if not isinstance(scenarios, dict) or scenarios.get("baseline") != {}:+ raise ValueError("scenarios must include an unchanged baseline mapping")+ for name, changes in scenarios.items():+ if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", name) or not isinstance(changes, dict):+ raise ValueError("Scenario names must be SBML-style identifiers and changes must be a mapping")+ for symbol, value in changes.items():+ parameter = model.getParameter(symbol)+ if parameter is None or not parameter.getConstant() or model.getInitialAssignmentBySymbol(symbol) is not None:+ raise ValueError(f"{symbol}: perturbations require a constant global parameter without an initial assignment")+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):+ raise ValueError(f"{symbol}: perturbation must be a finite number")+ return config+++def make_sedml(config, names):+ import libsedml+ sed = libsedml.SedDocument(1, 3)+ simulation = sed.createUniformTimeCourse(); simulation.setId("simulation")+ simulation.setInitialTime(0.); simulation.setOutputStartTime(0.)+ simulation.setOutputEndTime(config["end_time"]); simulation.setNumberOfPoints(config["points"] - 1)+ algorithm = simulation.createAlgorithm(); algorithm.setKisaoID("KISAO:0000019")+ for kisao, value in (("KISAO:0000209", config["relative_tolerance"]), ("KISAO:0000211", config["absolute_tolerance"])):+ parameter = algorithm.createAlgorithmParameter(); parameter.setKisaoID(kisao); parameter.setValue(str(value))+ for scenario in names:+ model = sed.createModel(); model.setId(f"model_{scenario}")+ model.setSource(f"model_{scenario}.xml"); model.setLanguage("urn:sedml:language:sbml")+ task = sed.createTask(); task.setId(f"task_{scenario}")+ task.setModelReference(f"model_{scenario}"); task.setSimulationReference("simulation")+ report = sed.createReport(); report.setId(f"report_{scenario}")+ for index, symbol in enumerate(["time"] + config["species"]):+ generator = sed.createDataGenerator(); generator.setId(f"dg_{scenario}_{index}")+ variable = generator.createVariable(); variable.setId(f"v_{scenario}_{index}")+ variable.setTaskReference(f"task_{scenario}")+ if symbol == "time":+ variable.setSymbol("urn:sedml:symbol:time")+ else:+ variable.setTarget(f"/sbml:sbml/sbml:model/sbml:listOfSpecies/sbml:species[@id='{symbol}']")+ generator.setMath(libsedml.parseFormula(variable.getId()))+ dataset = report.createDataSet(); dataset.setId(f"ds_{scenario}_{index}")+ dataset.setLabel(symbol); dataset.setDataReference(generator.getId())+ return sed+++def run(model_path, model_format, experiment_path, output):+ import libsbml+ import libsedml+ import numpy as np+ import tellurium as te+ model_path, experiment_path, output = Path(model_path), Path(experiment_path), Path(output)+ if output.exists():+ raise FileExistsError(f"Refusing to overwrite {output}")+ document, issues = model_document(model_path, model_format)+ config = validate_experiment(json.loads(experiment_path.read_text()), document.getModel())+ output.mkdir(parents=True)+ selections = ["time"] + [f"[{s}]" for s in config["species"]]+ results, model_files = {}, []+ for scenario, changes in config["scenarios"].items():+ # Fresh SBML per condition avoids reset/state carryover ambiguity.+ condition = document.clone()+ for symbol, value in changes.items():+ condition.getModel().getParameter(symbol).setValue(value)+ sbml = libsbml.writeSBMLToString(condition)+ model_file = output / f"model_{scenario}.xml"; model_file.write_text(sbml); model_files.append(model_file)+ runner = te.loadSBMLModel(sbml)+ runner.setIntegrator("cvode")+ runner.integrator.relative_tolerance = config["relative_tolerance"]+ runner.integrator.absolute_tolerance = config["absolute_tolerance"]+ runner.integrator.stiff = True+ values = np.asarray(runner.simulate(0., config["end_time"], config["points"], selections))+ if values.shape != (config["points"], len(selections)) or not np.isfinite(values).all():+ raise RuntimeError(f"{scenario}: invalid simulation output")+ results[scenario] = values+ with (output / f"{scenario}.csv").open("w", newline="") as handle:+ writer = csv.writer(handle); writer.writerow(selections); writer.writerows(values)+ sed = make_sedml(config, config["scenarios"])+ sed_path = output / "experiment.sedml"+ libsedml.writeSedMLToFile(sed, str(sed_path))+ parsed_sed = libsedml.readSedMLFromFile(str(sed_path))+ sed_issues = [{"severity": parsed_sed.getError(i).getSeverityAsString(), "message": parsed_sed.getError(i).getMessage()}+ for i in range(parsed_sed.getNumErrors())]+ if any(issue["severity"] in {"Error", "Fatal"} for issue in sed_issues):+ raise ValueError("Generated SED-ML failed validation")+ archive = output / "experiment.omex"+ te.createCombineArchive(str(archive), [str(p) for p in model_files] + [str(sed_path)],+ [p.name for p in model_files] + [sed_path.name],+ ["http://identifiers.org/combine.specifications/sbml"] * len(model_files) + ["http://identifiers.org/combine.specifications/sed-ml"],+ [False] * len(model_files) + [True])+ # Replay only this generated archive; no arbitrary archive extraction entry point.+ replay = te.executeCombineArchive(str(archive), createOutputs=False)+ if len(replay) != 1:+ raise RuntimeError("Expected one SED-ML document in generated archive")+ generators = next(iter(replay.values()))["dataGenerators"]+ replay_errors = {}+ for scenario, values in results.items():+ replayed = np.column_stack([generators[f"dg_{scenario}_{i}"].reshape(-1) for i in range(len(selections))])+ np.testing.assert_allclose(replayed, values, rtol=config["relative_tolerance"] * 10,+ atol=config["absolute_tolerance"] * 10)+ replay_errors[scenario] = float(np.max(np.abs(replayed - values)))+ model = document.getModel()+ units = {"time": model.getTimeUnits(), "substance": model.getSubstanceUnits(), "volume": model.getVolumeUnits(),+ "species": {s: libsbml.UnitDefinition.printUnits(model.getSpecies(s).getDerivedUnitDefinition()) for s in config["species"]}}+ report = {"versions": {**dict(te.getVersionInfo()), "libcombine": importlib.metadata.version("python-libcombine")}, "integrator": "cvode", "stiff": True, "experiment": config,+ "source_model_sha256": hashlib.sha256(model_path.read_bytes()).hexdigest(),+ "experiment_sha256": hashlib.sha256(experiment_path.read_bytes()).hexdigest(),+ "sbml_validation_findings": issues, "sedml_parse_findings": sed_issues, "units": units,+ "archive_sha256": hashlib.sha256(archive.read_bytes()).hexdigest(),+ "archive_replay_max_absolute_difference": replay_errors,+ "minimum_concentration": {s: float(v[:, 1:].min()) for s, v in results.items()}}+ (output / "report.json").write_text(json.dumps(report, indent=2) + "\n")+ return report+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--model", type=Path, required=True)+ parser.add_argument("--format", choices=["sbml", "antimony"], required=True)+ parser.add_argument("--experiment", type=Path, required=True)+ parser.add_argument("--output", type=Path, required=True)+ args = parser.parse_args()+ print(json.dumps(run(args.model, args.format, args.experiment, args.output), indent=2))+++if __name__ == "__main__":+ main()diff --git a/tests/cantera/test_scripts.py b/tests/cantera/test_scripts.pynew file mode 100644index 00000000..488fccd5--- /dev/null+++ b/tests/cantera/test_scripts.py@@ -0,0 +1,82 @@+import hashlib+import importlib.util+import json+from pathlib import Path+import subprocess+import sys++import pytest+import skill_contract++np = pytest.importorskip("numpy")+ct = pytest.importorskip("cantera")+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "cantera"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+spec = importlib.util.spec_from_file_location("cantera_ignition", SKILL_ROOT / "scripts" / "ignition_delay.py")+module = importlib.util.module_from_spec(spec)+spec.loader.exec_module(module)+++def config():+ return json.loads((SKILL_ROOT / "assets" / "hydrogen-ignition.json").read_text())++[email protected]("reactor,equilibrium_constraint", [("constant-volume", "UV"), ("constant-pressure", "HP")])+def test_hydrogen_ignition_conservation_and_independent_equilibrium(reactor, equilibrium_constraint):+ conditions = config()+ conditions["reactor"] = reactor+ history, report = module.simulate(conditions)+ assert report["status"] == "resolved"+ assert report["conservation"]["passed"]+ assert report["conservation"]["element_mass_fraction_absolute_drift"] < 1e-10+ equilibrium = module.load_gas(conditions)+ equilibrium.equilibrate(equilibrium_constraint)+ assert history[-1, 1] == pytest.approx(equilibrium.T, abs=0.02)+ if reactor == "constant-volume":+ assert report["delay_s"] == pytest.approx(0.000313, abs=2e-6)+ assert history[:, 3] == pytest.approx(np.ones(len(history)))+ else:+ assert history[:, 2] == pytest.approx(np.full(len(history), conditions["pressure_pa"]), rel=1e-8)+++def test_unreached_ignition_is_not_a_reported_delay():+ conditions = config()+ conditions.update(temperature_k=500, end_time_s=0.001, samples=101)+ _, report = module.simulate(conditions)+ assert report["delay_s"] is None+ assert report["status"] == "temperature-rise-not-reached"+++def test_boundary_maximum_is_unresolved():+ times = np.linspace(0, 1, 21)+ report = module.delay_from_history(times, 1000 + 500 * times**3, 200)+ assert report["delay_s"] is None+ assert report["status"] == "derivative-maximum-at-boundary"++[email protected]("change", [{"pressure_pa": -1}, {"samples": 3},+ {"mole_amounts": {"H2": -1}}, {"mole_amounts": {"H2": 0}},+ {"mole_amounts": {"NOT_A_SPECIES": 1}}, {"rtol": float("nan")}])+def test_invalid_conditions_rejected(change):+ conditions = config()+ conditions.update(change)+ with pytest.raises(ValueError):+ module.simulate(conditions)+++def test_cli_refinement_provenance_and_replay(tmp_path):+ path = SKILL_ROOT / "assets" / "hydrogen-ignition.json"+ command = [sys.executable, str(SKILL_ROOT / "scripts" / "ignition_delay.py"), str(path), str(tmp_path / "run")]+ result = subprocess.run(command, capture_output=True, text=True, timeout=60)+ assert result.returncode == 0, result.stderr+ out = tmp_path / "run"+ report = json.loads((out / "report.json").read_text())+ assert report["numerically_resolved"]+ assert set(report["delay_relative_changes"]) == {"finer_output", "tighter_solver", "longer_horizon"}+ assert all(delta <= 0.01 for delta in report["delay_relative_changes"].values())+ assert report["mechanism"]["snapshot_sha256"] == hashlib.sha256((out / "mechanism.yaml").read_bytes()).hexdigest()+ original = module.load_gas(config())+ replay = ct.Solution(str(out / "mechanism.yaml"), "ohmech")+ np.testing.assert_allclose(replay.forward_rate_constants, original.forward_rate_constants, rtol=1e-12)+ assert len((out / "baseline.csv").read_text().splitlines()) == 3002+ assert subprocess.run(command, capture_output=True, text=True, timeout=60).returncode != 0diff --git a/tests/cellprofiler/test_scripts.py b/tests/cellprofiler/test_scripts.pynew file mode 100644index 00000000..baac30d9--- /dev/null+++ b/tests/cellprofiler/test_scripts.py@@ -0,0 +1,76 @@+from pathlib import Path+import csv+import importlib.util+import json+import os+import subprocess+import sys+import numpy as np+import pytest+import tifffile+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / 'skills' / 'cellprofiler'+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+spec = importlib.util.spec_from_file_location('nuclei_assay', SKILL_ROOT / 'scripts' / 'nuclei_assay.py')+assay = importlib.util.module_from_spec(spec)+spec.loader.exec_module(assay)+++def fixture_manifest(tmp_path):+ yy, xx = np.indices((128, 128))+ data = np.zeros((128, 128), dtype=np.uint16)+ for cy, cx, intensity in [(30, 30, 20000), (30, 90, 30000), (90, 60, 40000)]:+ data[(yy-cy)**2+(xx-cx)**2 <= 10**2] = intensity+ tifffile.imwrite(tmp_path / 'nuclei.tif', data)+ manifest = tmp_path / 'manifest.csv'+ manifest.write_text('sample_id,image_path,plate,well,site\ncontrol,nuclei.tif,P1,A01,1\n')+ return manifest+++def test_prepare_preserves_scaling_and_sample_identity(tmp_path):+ manifest = fixture_manifest(tmp_path)+ result = assay.prepare(manifest, tmp_path / 'load.csv')+ assert result['images'][0]['dtype'] == 'uint16'+ assert result['images'][0]['saturated_fraction'] == 0+ with (tmp_path / 'load.csv').open() as f:+ rows = list(csv.DictReader(f))+ assert rows[0]['Metadata_Well'] == 'A01'+ assert rows[0]['URL_DNA'] == (tmp_path / 'nuclei.tif').as_uri()++[email protected]('kind', ['rgb', 'float', 'constant', 'duplicate'])+def test_invalid_images_and_duplicate_acquisition_rejected(tmp_path, kind):+ manifest = fixture_manifest(tmp_path)+ if kind == 'duplicate':+ with manifest.open('a') as f:+ f.write('duplicate,nuclei.tif,P1,A01,1\n')+ else:+ data = {'rgb': np.zeros((32, 32, 3), dtype=np.uint8),+ 'float': np.ones((32, 32), dtype=np.float32),+ 'constant': np.zeros((32, 32), dtype=np.uint16)}[kind]+ tifffile.imwrite(tmp_path / 'nuclei.tif', data)+ with pytest.raises(ValueError):+ assay.prepare(manifest, tmp_path / 'load.csv')+++def test_measurement_consistency(tmp_path):+ (tmp_path / 'Image.csv').write_text('ImageNumber,Metadata_Sample,Count_Nuclei\n1,control,2\n')+ (tmp_path / 'Nuclei.csv').write_text('ImageNumber,Intensity_MeanIntensity_DNA\n1,0.25\n1,0.75\n')+ assert assay.summarize(tmp_path, ['control'])['measurements'][0]['mean_nuclear_intensity'] == 0.5+ with pytest.raises(ValueError, match='identities'):+ assay.summarize(tmp_path, ['other'])+ (tmp_path / 'Nuclei.csv').write_text('ImageNumber,Intensity_MeanIntensity_DNA\n1,nan\n1,0.75\n')+ with pytest.raises(ValueError, match='Nonfinite'):+ assay.summarize(tmp_path)+++def test_real_cellprofiler_synthetic_counts_and_intensity(tmp_path):+ executable = os.environ.get('CELLPROFILER_TEST_EXECUTABLE')+ if not executable:+ pytest.skip('Set CELLPROFILER_TEST_EXECUTABLE for installed CellProfiler 4.2.8 integration')+ result = assay.run(fixture_manifest(tmp_path), tmp_path / 'output', executable,+ SKILL_ROOT / 'assets' / 'nuclei.cppipe')+ assert result['measurements'][0]['nuclei'] == 3+ assert result['measurements'][0]['mean_nuclear_intensity'] == pytest.approx(30000/65535, abs=0.03)+ assert (tmp_path / 'output' / 'control_nuclei.png').is_file()diff --git a/tests/mageck/test_scripts.py b/tests/mageck/test_scripts.pynew file mode 100644index 00000000..54fda711--- /dev/null+++ b/tests/mageck/test_scripts.py@@ -0,0 +1,95 @@+from pathlib import Path+import csv+import importlib.util+import random+import shutil+import subprocess++import pytest+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "mageck"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+spec = importlib.util.spec_from_file_location("screen_analysis", SKILL_ROOT / "scripts" / "screen_analysis.py")+screen = importlib.util.module_from_spec(spec)+spec.loader.exec_module(screen)+++def counts(tmp_path):+ rng = random.Random(17)+ path = tmp_path / "counts.tsv"+ with path.open("w") as handle:+ handle.write("sgRNA\tGene\tc1\tc2\tt1\tt2\n")+ for gene in range(100):+ for guide in range(5):+ baseline = rng.randint(600, 1800)+ fold = .015 if gene == 0 else 30 if gene == 1 else 1+ values = [round(baseline * rng.uniform(.85, 1.15)) for _ in range(2)]+ values += [round(baseline * fold * rng.uniform(.85, 1.15)) for _ in range(2)]+ handle.write(f"g{gene}_{guide}\tGENE{gene}\t" + "\t".join(map(str, values)) + "\n")+ return path+++def test_qc_replicates_and_missing_sample(counts):+ qc = screen.inspect_screen(counts, ["c1", "c2"], ["t1", "t2"])+ assert qc["guides"] == 500+ assert all(c > .9 for c in qc["within_condition_log2_count_correlations"].values())+ assert qc["samples"]["c1"]["zero_fraction"] == 0+ with pytest.raises(ValueError, match="Unknown sample"):+ screen.inspect_screen(counts, ["wrong"], ["t1"])+ with pytest.raises(ValueError, match="equal counts"):+ screen.inspect_screen(counts, ["c1", "c2"], ["t1"], paired=True)+++def test_invalid_counts_library_and_controls(counts, tmp_path):+ bad = tmp_path / "bad.tsv"+ bad.write_text("sgRNA\tGene\ta\tb\nx\tX\t-1\t3\n")+ with pytest.raises(ValueError, match="negative"):+ screen.read_counts(bad)+ library = tmp_path / "library.tsv"+ library.write_text("x\tAAAA\tX\ny\tAAAA\tY\n")+ with pytest.raises(ValueError, match="ambiguous"):+ screen.read_library(library)+ controls = tmp_path / "controls.txt"+ controls.write_text("missing\n")+ with pytest.raises(ValueError, match="known IDs"):+ screen.inspect_screen(counts, ["c1"], ["t1"], controls_path=controls)+ with pytest.raises(ValueError, match="requires control"):+ screen.run_test(counts, tmp_path / "out", ["c1"], ["t1"], normalization="control")++[email protected](shutil.which("mageck") is None, reason="MAGeCK 0.5.9.5 and RRA are external source/conda executables")+def test_real_mageck_ranks_known_signals(counts, tmp_path):+ report = screen.run_test(counts, tmp_path / "results", ["c1", "c2"], ["t1", "t2"])+ negative = sorted(report["hits"]["neg"], key=lambda r: r["rank"])+ positive = sorted(report["hits"]["pos"], key=lambda r: r["rank"])+ assert negative[0]["gene"] == "GENE0" and negative[0]["lfc"] < -4+ assert positive[0]["gene"] == "GENE1" and positive[0]["lfc"] > 4+ assert (tmp_path / "results" / "screen.sgrna_summary.txt").is_file()++[email protected](shutil.which("mageck") is None, reason="MAGeCK is an external source/conda executable")+def test_real_fastq_counting(tmp_path):+ sequences = {"g1": "ACGTACGTACGTACGTACGT", "g2": "TTTTCCCCAAAAGGGGTTTT"}+ library = tmp_path / "library.tsv"+ library.write_text("\n".join(f"{g}\t{s}\tGENE{i}" for i, (g, s) in enumerate(sequences.items())) + "\n")+ fastq = tmp_path / "reads.fastq"+ reads = [sequences["g1"]] * 30 + [sequences["g2"]] * 12+ fastq.write_text("".join(f"@r{i}\n{seq}\n+\n{'I' * 20}\n" for i, seq in enumerate(reads)))+ subprocess.run(["mageck", "count", "-l", "library.tsv", "--fastq", "reads.fastq", "--sample-label", "sample", "--trim-5", "0", "--norm-method", "none", "-n", "counted"], cwd=tmp_path, check=True, capture_output=True, text=True)+ with (tmp_path / "counted.count.txt").open() as handle:+ output = list(csv.DictReader(handle, delimiter="\t"))+ assert {row["sgRNA"]: int(row["sample"]) for row in output} == {"g1": 30, "g2": 12}++[email protected](shutil.which("mageck") is None, reason="MAGeCK is an external source/conda executable")+def test_control_normalization_retains_control_provenance(counts, tmp_path):+ import hashlib+ controls = tmp_path / "negative-guides.txt"+ controls.write_text("".join(f"g{gene}_{guide}\n" for gene in range(2, 22) for guide in range(5)))+ report = screen.run_test(counts, tmp_path / "control-normalized", ["c1", "c2"], ["t1", "t2"],+ controls_path=controls, normalization="control")+ assert report["control_guide_ids"] == controls.read_text().splitlines()+ assert report["control_guides_sha256"] == hashlib.sha256(controls.read_bytes()).hexdigest()+ assert min(report["hits"]["neg"], key=lambda row: row["rank"])["gene"] == "GENE0"diff --git a/tests/nmrglue/test_scripts.py b/tests/nmrglue/test_scripts.pynew file mode 100644index 00000000..9f750e62--- /dev/null+++ b/tests/nmrglue/test_scripts.py@@ -0,0 +1,142 @@+import importlib.util+import json+from pathlib import Path+import subprocess+import sys++import pytest+import skill_contract++np = pytest.importorskip("numpy")+pytest.importorskip("nmrglue")+pytest.importorskip("scipy")+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "nmrglue"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+spec = importlib.util.spec_from_file_location("nmr_process_1d", SKILL_ROOT / "scripts" / "process_1d.py")+module = importlib.util.module_from_spec(spec)+spec.loader.exec_module(module)+++def example():+ config = json.loads((SKILL_ROOT / "assets" / "processing.json").read_text())+ t = np.arange(8192) / config["spectral_width_hz"]+ fid = sum(a * np.exp(-np.pi * 2 * t) * np.exp(-2j * np.pi * (ppm - 5) * 400 * t)+ for ppm, a in [(3, 1), (7, 2)])+ return fid, config+++def test_known_two_line_spectrum_orientation_and_area_ratio():+ fid, config = example()+ result = module.process(fid, config)+ assert np.all(np.diff(result["ppm"]) < 0)+ assert sorted(p["ppm"] for p in result["peaks"]) == pytest.approx([3, 7], abs=0.001)+ a, b = [r["area_signal_ppm"] for r in result["integrals"]]+ assert a > 0+ assert b / a == pytest.approx(2, rel=0.001)+ assert result["acquisition_time_s"] == 2.048+ # Infinite-time causal Lorentzian, first point halved: integral is SW/(2*obs)*amplitude.+ assert a == pytest.approx(5, rel=0.01)+++def test_positive_complex_convention_and_phase_recovery():+ fid, config = example()+ expected = module.process(fid, config)+ config["fid_sign"] = "+i"+ config["phase0_deg"] = -30+ actual = module.process((fid * np.exp(1j * np.pi / 6)).conj(), config)+ np.testing.assert_allclose(actual["real"], expected["real"], atol=1e-11)+++def test_linear_baseline_removes_added_constant():+ fid, config = example()+ # A real offset at t=0 transforms to a constant baseline.+ noisy = fid.copy()+ noisy[0] += 20+ config.update(baseline="linear", baseline_regions_ppm=[[0.2, 0.8], [9.2, 9.8]])+ result = module.process(noisy, config)+ assert np.median(result["baseline"]) == pytest.approx(10, abs=0.02)+ assert result["integrals"][1]["area_signal_ppm"] / result["integrals"][0]["area_signal_ppm"] == pytest.approx(2, rel=0.002)++[email protected]("change", [{"spectral_width_hz": 0}, {"fid_sign": "unknown"},+ {"integration_regions_ppm": [[-1, 2]]},+ {"zero_fill_points": 15}, {"line_broadening_hz": -1},+ {"baseline": "linear", "baseline_regions_ppm": []}])+def test_invalid_scientific_settings_rejected(change):+ fid, config = example()+ config.update(change)+ with pytest.raises(ValueError):+ module.process(fid, config)+++def test_nonfinite_and_real_fids_rejected():+ fid, config = example()+ with pytest.raises(ValueError):+ module.process(fid.real, config)+ fid[10] = np.nan+ with pytest.raises(ValueError):+ module.process(fid, config)+++def test_cli_writes_spectrum_and_provenance(tmp_path):+ fid, config = example()+ np.savez(tmp_path / "fid.npz", fid=fid)+ (tmp_path / "settings.json").write_text(json.dumps(config))+ command = [sys.executable, str(SKILL_ROOT / "scripts" / "process_1d.py"), str(tmp_path / "fid.npz"),+ str(tmp_path / "settings.json"), str(tmp_path / "result")]+ outcome = subprocess.run(command, capture_output=True, text=True, timeout=60)+ assert outcome.returncode == 0, outcome.stderr+ report = json.loads((tmp_path / "result" / "report.json").read_text())+ assert len(report["input_sha256"]) == 64+ assert len(report["peaks"]) == 2+ assert len((tmp_path / "result" / "spectrum.csv").read_text().splitlines()) == 32769+ assert subprocess.run(command, capture_output=True, text=True, timeout=60).returncode != 0+++def write_synthetic_nmrpipe(path, fid, config, frequency_domain=False):+ import nmrglue as ng+ universal = ng.fileiobase.create_blank_udic(1)+ universal[0].update(size=len(fid), complex=True, time=not frequency_domain,+ freq=frequency_domain, sw=config["spectral_width_hz"],+ obs=config["observation_mhz"], car=config["carrier_ppm"] * config["observation_mhz"],+ label=config["nucleus"], encoding="direct")+ header = ng.pipe.create_dic(universal)+ ng.pipe.write(str(path), header, fid.astype(np.complex64))+++def test_nmrpipe_roundtrip_and_cli_calibrated_spectrum(tmp_path):+ fid, config = example()+ pipe_path = tmp_path / "synthetic.fid"+ write_synthetic_nmrpipe(pipe_path, fid, config)+ decoded, metadata = module.load_fid(pipe_path, config, "nmrpipe")+ np.testing.assert_array_equal(decoded, fid.astype(np.complex64))+ assert metadata["header"]["FDF2FTFLAG"] == 0+ config_path = tmp_path / "settings.json"+ config_path.write_text(json.dumps(config))+ result = subprocess.run([sys.executable, str(SKILL_ROOT / "scripts" / "process_1d.py"), str(pipe_path),+ str(config_path), str(tmp_path / "result"), "--input-format", "nmrpipe"],+ capture_output=True, text=True, timeout=60)+ assert result.returncode == 0, result.stderr+ report = json.loads((tmp_path / "result" / "report.json").read_text())+ assert report["input"]["format"] == "nmrpipe"+ assert sorted(p["ppm"] for p in report["peaks"]) == pytest.approx([3, 7], abs=0.001)+ areas = [r["area_signal_ppm"] for r in report["integrals"]]+ assert areas[1] / areas[0] == pytest.approx(2, rel=0.001)+++def test_nmrpipe_frequency_domain_rejected(tmp_path):+ fid, config = example()+ pipe_path = tmp_path / "spectrum.ft1"+ write_synthetic_nmrpipe(pipe_path, fid, config, frequency_domain=True)+ with pytest.raises(ValueError, match="time-domain"):+ module.load_fid(pipe_path, config, "nmrpipe")++[email protected]("key", ["spectral_width_hz", "observation_mhz", "carrier_ppm"])+def test_nmrpipe_header_mismatch_rejected(tmp_path, key):+ fid, config = example()+ pipe_path = tmp_path / "fid.pipe"+ write_synthetic_nmrpipe(pipe_path, fid, config)+ config[key] *= 1.1+ with pytest.raises(ValueError, match="disagrees"):+ module.load_fid(pipe_path, config, "nmrpipe")diff --git a/tests/nwb-conversion/test_scripts.py b/tests/nwb-conversion/test_scripts.pynew file mode 100644index 00000000..15dc0398--- /dev/null+++ b/tests/nwb-conversion/test_scripts.py@@ -0,0 +1,98 @@+from pathlib import Path+import importlib.util+import json++import pytest+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "nwb-conversion"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+np = pytest.importorskip("numpy")+tifffile = pytest.importorskip("tifffile")+pytest.importorskip("neuroconv")+pytest.importorskip("nwbinspector")+spec = importlib.util.spec_from_file_location("convert_session", SKILL_ROOT / "scripts" / "convert_session.py")+converter = importlib.util.module_from_spec(spec)+spec.loader.exec_module(converter)+++def session(tmp_path):+ images = np.arange(8 * 7 * 9, dtype="uint16").reshape(8, 7, 9)+ tifffile.imwrite(tmp_path / "imaging.tif", images, photometric="minisblack")+ times = [0, .1, .2, .31, .4, .5, .6, .7]+ (tmp_path / "frames.csv").write_text("time_s\n" + "\n".join(map(str, times)) + "\n")+ (tmp_path / "position.csv").write_text("time_s,x,y\n0,10,20\n0.2,11,21\n0.4,12,22\n0.6,13,23\n")+ config = json.loads((SKILL_ROOT / "assets" / "session-template.json").read_text())+ path = tmp_path / "session.json"+ path.write_text(json.dumps(config))+ return path+++def test_real_tiff_csv_roundtrip_and_schema(session, tmp_path):+ report = converter.convert(session, tmp_path / "session.nwb")+ assert report["schema_errors"] == []+ assert report["roundtrip"]["frame_count"] == 8+ assert report["roundtrip"]["all_frames_equal"]+ assert isinstance(report["inspector_findings"], list)+ from pynwb import NWBHDF5IO+ with NWBHDF5IO(str(tmp_path / "session.nwb"), "r") as io:+ nwb = io.read()+ assert nwb.acquisition["Imaging"].data.shape == (8, 9, 7)+ assert nwb.acquisition["Imaging"].imaging_plane.location == "synthetic test plane"+ np.testing.assert_allclose(nwb.processing["behavior"]["Position"]["Position"].data[0], [.1, .2])+ with pytest.raises(FileExistsError):+ converter.convert(session, tmp_path / "session.nwb")+++def test_clock_drift_is_fit_from_pulse_evidence(session, tmp_path):+ (tmp_path / "pulses.csv").write_text("device_time_s,reference_time_s\n0,0.05\n0.3,0.3503\n0.6,0.6506\n")+ config = json.loads(session.read_text())+ config["synchronization"] = {"pulse_pairs_csv": "pulses.csv", "max_residual_s": .0001}+ session.write_text(json.dumps(config))+ result = converter.convert(session, tmp_path / "aligned.nwb")+ assert result["alignment"]["slope"] == pytest.approx(1.001)+ assert result["alignment"]["offset_s"] == pytest.approx(.05)+ assert result["alignment"]["max_residual_s"] < 1e-12+++def test_reject_false_clock_mapping_and_unsorted_samples(tmp_path):+ (tmp_path / "pulses.csv").write_text("device_time_s,reference_time_s\n0,0\n1,1.2\n2,2\n")+ with pytest.raises(ValueError, match="Clock fit failed"):+ converter.align_behavior(np.array([0., 1.]), {"pulse_pairs_csv": "pulses.csv", "max_residual_s": .001}, tmp_path)+ with pytest.raises(ValueError, match="either"):+ converter.align_behavior(np.array([0., 1.]), {}, tmp_path)+ (tmp_path / "bad.csv").write_text("time_s\n0\n0\n")+ with pytest.raises(ValueError, match="strictly increasing"):+ converter.read_numeric_csv(tmp_path / "bad.csv", ["time_s"])+++def test_reject_missing_frames_and_timezone(session, tmp_path):+ config = json.loads(session.read_text())+ config["session_start_time"] = "2020-01-01T12:00:00"+ session.write_text(json.dumps(config))+ with pytest.raises(ValueError, match="timezone"):+ converter.convert(session, tmp_path / "bad.nwb")+ config["session_start_time"] += "+00:00"+ session.write_text(json.dumps(config))+ (tmp_path / "frames.csv").write_text("time_s\n0\n1\n")+ with pytest.raises(ValueError, match="one grayscale"):+ converter.convert(session, tmp_path / "bad.nwb")+++def test_normal_length_stack_has_no_critical_inspector_findings(session, tmp_path):+ images = np.arange(16 * 7 * 9, dtype="uint16").reshape(16, 7, 9)+ tifffile.imwrite(tmp_path / "imaging.tif", images, photometric="minisblack")+ (tmp_path / "frames.csv").write_text("time_s\n" + "\n".join(str(i * .1) for i in range(16)) + "\n")+ report = converter.convert(session, tmp_path / "normal.nwb")+ assert report["schema_errors"] == []+ assert report["roundtrip"]["all_frames_equal"]+ assert report["inspector_requires_review"] is False+++def test_reject_other_acquisition_modality(session, tmp_path):+ config = json.loads(session.read_text())+ config["imaging"]["modality"] = "widefield"+ session.write_text(json.dumps(config))+ with pytest.raises(ValueError, match="two-photon"):+ converter.convert(session, tmp_path / "wrong-modality.nwb")diff --git a/tests/pybamm/fixtures/chen2020-reference.csv b/tests/pybamm/fixtures/chen2020-reference.csvnew file mode 100644index 00000000..1cce3ecd--- /dev/null+++ b/tests/pybamm/fixtures/chen2020-reference.csv@@ -0,0 +1,5 @@+time_s,voltage_V,current_A+0.0,3.9820649736442477,2.5+120.0,3.9341449882071995,2.5+300.0,3.9031419872015602,2.5+600.0,3.8653473827836455,2.5diff --git a/tests/pybamm/fixtures/reference-provenance.json b/tests/pybamm/fixtures/reference-provenance.jsonnew file mode 100644index 00000000..d063de99--- /dev/null+++ b/tests/pybamm/fixtures/reference-provenance.json@@ -0,0 +1,8 @@+{+ "type": "synthetic numerical regression reference, not experimental data",+ "source": "PyBaMM 26.9.0.0 Chen2020 SPM, isothermal 298.15 K, initial SOC 0.8, 0.5C discharge",+ "solver": "IDAKLUSolver rtol=1e-8 atol=1e-10",+ "mesh": "40 points for x_n, x_s, x_p, r_n, r_p",+ "nominal_capacity_Ah": 5.0,+ "reference_file": "chen2020-reference.csv"+}diff --git a/tests/pybamm/test_scripts.py b/tests/pybamm/test_scripts.pynew file mode 100644index 00000000..f9c9de02--- /dev/null+++ b/tests/pybamm/test_scripts.py@@ -0,0 +1,80 @@+from pathlib import Path+import copy+import csv+import importlib.util+import json+import os++import pytest+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pybamm"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+os.environ["PYBAMM_DISABLE_TELEMETRY"] = "true"+np = pytest.importorskip("numpy")+pytest.importorskip("pybamm")+spec = importlib.util.spec_from_file_location("simulate_battery", SKILL_ROOT / "scripts" / "simulate_battery.py")+battery = importlib.util.module_from_spec(spec)+spec.loader.exec_module(battery)+++def protocol():+ return json.loads((SKILL_ROOT / "assets" / "chen2020-protocol.json").read_text())+++def test_real_charge_discharge_and_numerical_studies(protocol, tmp_path):+ source = tmp_path / "protocol.json"+ source.write_text(json.dumps(protocol))+ reference = Path(__file__).resolve().parent / "fixtures" / "chen2020-reference.csv"+ report = battery.run(source, tmp_path / "result", measured=reference)+ assert report["nominal_capacity_Ah"] == 5.0+ assert report["solver_sensitivity"]["max_voltage_difference_V"] < 1e-4+ assert report["mesh_sensitivity"]["max_voltage_difference_V"] < .003+ assert report["measurement_comparison"]["rmse_V"] < .003+ assert report["measurement_comparison"]["current_rmse_A"] < 1e-9+ with (tmp_path / "result" / "curve.csv").open() as handle:+ rows = list(csv.DictReader(handle))+ discharge_end = next(r for r in reversed(rows) if r["step"] == "0")+ assert float(discharge_end["net_discharge_capacity_Ah"]) == pytest.approx(2.5 * 600 / 3600, abs=1e-8)+ assert float(rows[-1]["net_discharge_capacity_Ah"]) == pytest.approx(0, abs=1e-8)+ assert {float(r["current_A"]) for r in rows} == {-2.5, 0., 2.5}+ assert all(2.5 < float(r["voltage_V"]) < 4.2 for r in rows)+ assert report["terminations"][-1]["end_s"] == pytest.approx(1320)+++def test_real_dfn_and_voltage_termination(protocol):+ protocol["model"] = "DFN"+ protocol["steps"] = [{"kind": "discharge", "c_rate": .5, "duration_s": 600, "until_voltage_V": 3.9}]+ result = battery.solve_protocol(protocol)+ assert 0 < result["terminations"][0]["end_s"] < 600+ assert result["rows"][-1][2] == pytest.approx(3.9, abs=1e-5)+ assert "Voltage" in result["terminations"][0]["termination"] or "voltage" in result["terminations"][0]["termination"]+ duration = result["terminations"][0]["end_s"]+ assert result["rows"][-1][4] == pytest.approx(2.5 * duration / 3600, abs=1e-7)++[email protected]("change", [+ {"initial_soc": 1.1}, {"temperature_K": 0}, {"sample_period_s": float("nan")},+ {"cycles": 5}, {"model": "unknown"}, {"steps": [{"kind": "rest", "duration_s": 2, "c_rate": 1}]},+])+def test_reject_bad_protocol(protocol, change):+ protocol.update(change)+ with pytest.raises(ValueError):+ battery.validate_protocol(protocol)+++def test_unknown_parameter_and_out_of_range_reference(protocol, tmp_path):+ protocol["parameter_overrides"] = {"misspelled conductivity": 1.}+ with pytest.raises(ValueError, match="Unknown parameter"):+ battery.solve_protocol(protocol)+ bad = tmp_path / "outside.csv"+ bad.write_text("time_s,voltage_V,current_A\n0,4,1\n11,4,1\n")+ with pytest.raises(ValueError, match="no extrapolation"):+ battery.compare_measurement([(0, 0., 4., 1., 0.), (0, 10., 3.9, 1., .01)], bad, tmp_path / "residuals.csv")+++def test_detect_global_limit_before_requested_duration(protocol):+ protocol["steps"] = [{"kind": "discharge", "c_rate": 1., "duration_s": 14400.}]+ with pytest.raises(RuntimeError, match="ended before"):+ battery.solve_protocol(protocol)diff --git a/tests/pycalphad/test_scripts.py b/tests/pycalphad/test_scripts.pynew file mode 100644index 00000000..3d04d488--- /dev/null+++ b/tests/pycalphad/test_scripts.py@@ -0,0 +1,99 @@+import hashlib+import importlib.util+import json+from pathlib import Path+import subprocess+import sys++import pytest+import skill_contract++np = pytest.importorskip("numpy")+pc = pytest.importorskip("pycalphad")+SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "pycalphad"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+spec = importlib.util.spec_from_file_location("pycalphad_equilibrate", SKILL_ROOT / "scripts" / "equilibrate.py")+module = importlib.util.module_from_spec(spec)+spec.loader.exec_module(module)+DATABASE = SKILL_ROOT / "assets" / "ideal-cu-ni.tdb"+++def settings():+ return json.loads((SKILL_ROOT / "assets" / "equilibrium.json").read_text())+++def test_analytic_tie_line_lever_rule_and_gibbs_energy():+ config = settings()+ config["temperatures_k"] = [1100.0]+ config["independent_mole_fractions"] = {"NI": 0.49}+ report = module.calculate(pc.Database(str(DATABASE)), config)+ assert report["all_checks_passed"]+ result = report["points"][0]["baseline"]+ phases = {vertex["phase"]: vertex for vertex in result["vertices"]}+ # Independent common-tangent solution for the original ideal model.+ rt = 8.3145 * 1100 # Gas constant used by pycalphad's thermodynamic models.+ x_liquid = 1 / (1 + np.exp(1000 / rt))+ x_solid = 1 - x_liquid+ solid_fraction = (0.49 - x_liquid) / (x_solid - x_liquid)+ assert phases["LIQUID"]["mole_fractions"]["NI"] == pytest.approx(x_liquid, abs=1e-7)+ assert phases["FCC_A1"]["mole_fractions"]["NI"] == pytest.approx(x_solid, abs=1e-7)+ assert phases["FCC_A1"]["mole_phase_fraction"] == pytest.approx(solid_fraction, abs=1e-6)+ mixing = lambda x: rt * (x * np.log(x) + (1 - x) * np.log(1 - x))+ expected_gm = solid_fraction * mixing(x_solid) + (1 - solid_fraction) * (mixing(x_liquid) - 1000 + 2000 * x_liquid)+ assert result["gibbs_energy_j_per_mol"] == pytest.approx(expected_gm, abs=1e-4)+ assert result["mass_balance_absolute_error"] < 1e-8+++def test_single_phase_limits_and_refinement():+ config = settings()+ report = module.calculate(pc.Database(str(DATABASE)), config)+ assert report["all_checks_passed"]+ low, middle, high = [r["baseline"] for r in report["points"]]+ assert low["phase_totals"]["FCC_A1"] == pytest.approx(1)+ assert high["phase_totals"]["LIQUID"] == pytest.approx(1)+ assert middle["phase_totals"]["LIQUID"] == pytest.approx(0.5, abs=1e-6)+++def test_miscibility_gap_preserves_distinct_same_phase_vertices():+ # Original regular-solution perturbation produces FCC/FCC separation.+ db = pc.Database(DATABASE.read_text() + "\nPARAMETER L(FCC_A1,CU,NI;0) 298.15 30000; 2000 N !\n")+ config = settings()+ config.update(phases=["FCC_A1"], temperatures_k=[900.0])+ report = module.calculate(db, config)+ result = report["points"][0]["baseline"]+ assert report["all_checks_passed"]+ vertices = result["vertices"]+ assert len(vertices) == 2+ assert {p["phase"] for p in vertices} == {"FCC_A1"}+ assert vertices[0]["mole_fractions"]["NI"] != pytest.approx(vertices[1]["mole_fractions"]["NI"])+ for vertex in vertices:+ x = vertex["mole_fractions"]["NI"]+ assert abs(8.3145 * 900 * np.log(x / (1 - x)) + 30000 * (1 - 2 * x)) < 0.1+ assert vertex["mole_phase_fraction"] == pytest.approx(0.5, abs=1e-6)++[email protected]("change", [{"composition_basis": "mass_fraction"},+ {"independent_mole_fractions": {"NI": 1.1}},+ {"independent_mole_fractions": {"NI": 0.5, "CU": 0.5}},+ {"phases": ["UNKNOWN"]}, {"components": ["CU", "NI", "FE"]},+ {"temperatures_k": [2500]}, {"pressure_pa": -1},+ {"dependent_component": "VA"}, {"temperatures_k": [float("nan")]}])+def test_invalid_scientific_conditions_rejected(change):+ config = settings()+ config.update(change)+ with pytest.raises(ValueError):+ module.calculate(pc.Database(str(DATABASE)), config)+++def test_cli_exports_both_density_runs_and_hashes(tmp_path):+ command = [sys.executable, str(SKILL_ROOT / "scripts" / "equilibrate.py"), str(DATABASE),+ str(SKILL_ROOT / "assets" / "equilibrium.json"), str(tmp_path / "result")]+ result = subprocess.run(command, capture_output=True, text=True, timeout=120)+ assert result.returncode == 0, result.stderr+ report = json.loads((tmp_path / "result" / "report.json").read_text())+ assert report["all_checks_passed"]+ assert report["database_sha256"] == hashlib.sha256(DATABASE.read_bytes()).hexdigest()+ csv = (tmp_path / "result" / "phase-equilibria.csv").read_text()+ assert "baseline" in csv and "refined" in csv+ assert report["phase_fraction_basis"].startswith("molar")+ assert subprocess.run(command, capture_output=True, text=True, timeout=120).returncode != 0diff --git a/tests/qiime2-amplicon/fixtures/BAQ2420.2_10_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ2420.2_10_L001_R1_001.fastq.gznew file mode 100644index 00000000..4c156881Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ2420.2_10_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ2420.2_11_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ2420.2_11_L001_R2_001.fastq.gznew file mode 100644index 00000000..ebaa2e57Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ2420.2_11_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ3473.2_0_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ3473.2_0_L001_R1_001.fastq.gznew file mode 100644index 00000000..f8542a5bBinary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ3473.2_0_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ3473.2_1_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ3473.2_1_L001_R2_001.fastq.gznew file mode 100644index 00000000..8cda0362Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ3473.2_1_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ3473.3_2_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ3473.3_2_L001_R1_001.fastq.gznew file mode 100644index 00000000..b9c2a423Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ3473.3_2_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ3473.3_3_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ3473.3_3_L001_R2_001.fastq.gznew file mode 100644index 00000000..9ca2b907Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ3473.3_3_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ4166.2_4_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ4166.2_4_L001_R1_001.fastq.gznew file mode 100644index 00000000..1e71c44cBinary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ4166.2_4_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ4166.2_5_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ4166.2_5_L001_R2_001.fastq.gznew file mode 100644index 00000000..ff7f9e38Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ4166.2_5_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ4166.3_14_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ4166.3_14_L001_R1_001.fastq.gznew file mode 100644index 00000000..7f81f850Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ4166.3_14_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/BAQ4166.3_15_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/BAQ4166.3_15_L001_R2_001.fastq.gznew file mode 100644index 00000000..19f2f841Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/BAQ4166.3_15_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/LICENSE b/tests/qiime2-amplicon/fixtures/LICENSEnew file mode 100644index 00000000..114f26f0--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/LICENSE@@ -0,0 +1,29 @@+BSD 3-Clause License++Copyright (c) 2016-2026, QIIME 2 development team.+All rights reserved.++Redistribution and use in source and binary forms, with or without+modification, are permitted provided that the following conditions are met:++* Redistributions of source code must retain the above copyright notice, this+ list of conditions and the following disclaimer.++* Redistributions in binary form must reproduce the above copyright notice,+ this list of conditions and the following disclaimer in the documentation+ and/or other materials provided with the distribution.++* Neither the name of the copyright holder nor the names of its+ contributors may be used to endorse or promote products derived from+ this software without specific prior written permission.++THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL+DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR+SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER+CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.diff --git a/tests/qiime2-amplicon/fixtures/PAP130.2_6_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/PAP130.2_6_L001_R1_001.fastq.gznew file mode 100644index 00000000..7bf43672Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/PAP130.2_6_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/PAP130.2_7_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/PAP130.2_7_L001_R2_001.fastq.gznew file mode 100644index 00000000..a2c8d602Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/PAP130.2_7_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/README.md b/tests/qiime2-amplicon/fixtures/README.mdnew file mode 100644index 00000000..a44f6ce9--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/README.md@@ -0,0 +1,25 @@+# Bounded QIIME 2 runtime fixture++The paired reads and expected DADA2 outputs derive from the BSD-3-Clause+[q2-dada2 test data](https://github.com/qiime2/q2-dada2/tree/8bbf5158d6c71b37b57a0e1f6e2b1cb69b9e96d7/q2_dada2/tests/data),+commit `8bbf5158d6c71b37b57a0e1f6e2b1cb69b9e96d7`. The upstream license is retained+in `LICENSE`. `provenance.json` records hashes of the distributed fixture files.++Ten nonempty samples retain their original 100 read pairs. The empty `BLANK` control is+excluded from the executable manifest because this bounded runner rejects empty FASTQs;+its original zero row remains in the upstream expected statistics. Each R1 read has the+synthetic primer `ACGTTGCAACGTTGCAAC` prepended, and each R2 has+`TGCAACGTTGCAACGTTG`, with Q40 primer bases. Removing those prefixes restores the+upstream read sequences and qualities. Truncate both reads to 150 bases after trimming;+the maximum expected merged insert length is 254 bases.++`smoke-taxonomy.tsv` deliberately assigns invented `SyntheticFixture` taxonomy labels to+the upstream expected sequences. A classifier trained from these sequences tests artifact+serialization and classification execution only. It does not measure taxonomy accuracy.+The upstream reference has 18 ASVs and 243 non-chimeric reads. Exact agreement is a+regression check for this fixture, not a universal expected yield.++Run `../run_integration.py` in the documented QIIME 2 environment, providing a fresh+output directory. It stages absolute-path manifests, trains the tiny classifier, runs the+actual skill, and checks statistics and sequence recovery. The default portable pytest+suite does not download or launch the large QIIME distribution.diff --git a/tests/qiime2-amplicon/fixtures/YUN1005.3_16_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN1005.3_16_L001_R1_001.fastq.gznew file mode 100644index 00000000..86dd4e82Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN1005.3_16_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/YUN1005.3_17_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN1005.3_17_L001_R2_001.fastq.gznew file mode 100644index 00000000..e95e169bBinary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN1005.3_17_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/YUN1242.1_8_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN1242.1_8_L001_R1_001.fastq.gznew file mode 100644index 00000000..4b158295Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN1242.1_8_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/YUN1242.1_9_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN1242.1_9_L001_R2_001.fastq.gznew file mode 100644index 00000000..8a174057Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN1242.1_9_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/YUN1242.3_12_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN1242.3_12_L001_R1_001.fastq.gznew file mode 100644index 00000000..61658dedBinary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN1242.3_12_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/YUN1242.3_13_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN1242.3_13_L001_R2_001.fastq.gznew file mode 100644index 00000000..118f22d5Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN1242.3_13_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/YUN3153.3_18_L001_R1_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN3153.3_18_L001_R1_001.fastq.gznew file mode 100644index 00000000..e02f57f7Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN3153.3_18_L001_R1_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/YUN3153.3_19_L001_R2_001.fastq.gz b/tests/qiime2-amplicon/fixtures/YUN3153.3_19_L001_R2_001.fastq.gznew file mode 100644index 00000000..c6753719Binary files /dev/null and b/tests/qiime2-amplicon/fixtures/YUN3153.3_19_L001_R2_001.fastq.gz differdiff --git a/tests/qiime2-amplicon/fixtures/paired-default-stats.tsv b/tests/qiime2-amplicon/fixtures/paired-default-stats.tsvnew file mode 100644index 00000000..aeae692d--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/paired-default-stats.tsv@@ -0,0 +1,13 @@+sample-id input filtered percentage of input passed filter denoised merged percentage of input merged non-chimeric percentage of input non-chimeric+#q2:types numeric numeric numeric numeric numeric numeric numeric numeric+BAQ2420.2 100 92 92 34 15 15 15 15+BAQ3473.2 100 95 95 14 0 0 0 0+BAQ3473.3 100 92 92 30 16 16 16 16+BAQ4166.2 100 92 92 20 0 0 0 0+BAQ4166.3 100 89 89 26 9 9 9 9+BLANK 0 0 0 0 0 0 0 0+PAP130.2 100 89 89 43 5 5 5 5+YUN1005.3 100 95 95 76 68 68 68 68+YUN1242.1 100 86 86 81 49 49 49 49+YUN1242.3 100 93 93 76 50 50 50 50+YUN3153.3 100 89 89 64 31 31 31 31diff --git a/tests/qiime2-amplicon/fixtures/paired-default.fasta b/tests/qiime2-amplicon/fixtures/paired-default.fastanew file mode 100644index 00000000..aec81fae--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/paired-default.fasta@@ -0,0 +1,36 @@+>cbd46c06c1ddceeb8d856468c1b549c8+TACGTAGGGTGCAAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCTCGTAGGCGGTCTGTCGCGTCGGCTGTGAAAACTCGGGGCTCAACTCCGAGCTTGCAGCCGATACGGGCAGACTAGAGTTCGGCAGGGGAGACTGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCGGTGGCGAAGGCGGGTCTCTGGGCCGATACTGACGCTGAGGAGCGAAAGCGTGGGGAGCAAACAGG+>c15fd6a65f4f8d575c2cb4cfe2a659a5+TACGTAGGGGGCGAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCGTGTAGGCGGTCTGGTAAGTCTGCCGTGAAAACCCGGGGCTCAACCCCGGGCGTGCGGTGGATACTGCCAGGCTAGAGGGTGGTAGAGGCGAGTGGAATTCCCGGTGTAGCGGTGAAATGCGCAGATATCGGGAGGAACACCAGTAGCGAAGGCGGCTCGCTGGGCCATTCCTGACGCTGAGACGCGAAAGCTAGGGGAGCGAACAGG+>854614d933d994aecc1d1b7bbc24e675+TACGTAGGGTGCAAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCTCGTAGGCGGTCTGTTACGTCGGCTGTGAAAACTCGGGGCTCAACCCTGAGCCTGCAGTCGATACGGGCAGACTAGAGTTCGGCAGGGGAGACTGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCGGTGGCGAAGGCGGGTCTCTGGGCCGATACTGACGCTGAGGAGCGAAAGCGTGGGGAGCGAACAGG+>7925aae7da7d248eccdcd0ed0935ad61+TACGTAGGGGGCAAGCGTTGTCCGGAATCATTGGGCGTAAAGAGCGCGTAGGCGGTCCGGTAAGTCCATCGTGAAAGCCAAGGGCTCAACCCTTGGATGCCGGTGGATACTGTCGGGCTAGAGTCCGGAAGAGGCGAGTGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAAGAACACCTATGGCGAAGGCAGCTCGCTGGGACGGAACTGACGCTGAGGCGCGAAAGCGTGGGGAGCAAACAGG+>5de23fc8df270235a8958de416e2f944+TACGTAGGGGGCAAGCGTTGTCCGGATTCATTGGGCGTAAAGAGCTCGTAGGCGGCTTGGCAAGTCGGGTGTGAAAACTTCAGGCTCAACCTGGAGATGCCACCCGAGACTGCTATGGCTAGAGTCCGGTAGGGGACCACGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCGGTAGCGAAGGCGGTGGTCTGGGCCGGCACTGACGCTGAGGAGCGAAAGCGTGGGTAGCAAACAGG+>27ae47cc0e39b6df154b6938d9848c1b+TACGTAGGGTGCAAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCTCGTAGGCGGTTTGTCGCGTCGGCTGTGAAAACTCGGGGCTCAACTCTGAGCTTGCAGTCGATACGGGCAGACTAGAGTTCGGCAGGGGAGACTGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCGGTGGCGAAGGCGGGTCTCTGGGCCGATACTGACGCTGAGGAGCGAAAGCGTGGGGAGCGAACAGG+>acca130825261f8ae2e602bfe1865525+CACGTAGGGACCGAGCGTTGTCCGGAATCATTGGGCGTAAAGAGCGCGTAGGCGGCTATCCACGTCGGGTGTGAAAGCTCAGAGCTCAACTCTGAGAGGCCATTCGATACGGGATAGCTAGAGGCAGCTAGGGGAGAGTGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCGGTGGCGAAGGCGGCTCTCTGGGGCTGATCTGACGCTGAGGCGCGAAAGCTGGGGGAGCAAACAGG+>0018939bf02c32c9a63c42ade52cefad+TACGGAGGGTGCGAGCGTTAATCGGAATTACTGGGCGTAAAGGGCGCGTAGGTGGTTGGGTAAGTCGGGTGTGAAAGCCCTGGGCTTAACCTGGGAATGGCATTCGAGACTACCTATCTAGAGTCTGGTAGAGGGAAGTGGAATTTCCGGTGTAGCGGTGAAATGTGTAGATATCGGAAGGAACACCAGTGGCGAAGGCGACTTCCTGGACCAAGACTGACGCTGAGGCGCGAAAGCGTGGGGATCAAACAGG+>31ca42f58709548b0c88ae9153bece35+TACGGAGGATGCAAGCGTTATCCGGATTTATTGGGTTTAAAGGGTGCGTAGGCGGCCTGTTAAGTCAGGGGTGAAAGGTTGCGGCTTAACCGCAGAATTGCCTTTGATACTGGCGGGCTTGAATAAAGTTGAGGTAGGCGGAATGTGGCAAGTAGCGGTGAAATGCATAGAGATGCCACAGAACACCGATTGCGAAGGCAGCTTACTAAGCTTTGATTGACGCTGAGGCACGAAAGCGTGGGGATCAAACAGG+>4ec5e8b7a8c0d46bebe446577daa0352+CACGTAGGGGGCGAGCGTTGTCCGGATTTATTGGGCGTAAAGAGCTCGTAGGCGGCCGTTCGCGTCGGATGTGAAAGCTCAAGGCTCAACCTTGAGAGGCCATTCGATACGGGACGGCTGGAGGCAGGCAGGGGAGAGTGGAATTCCTGGTGTAGCGGTGGAATGCGCAGATATCAGGAGGAACACCGGTGGCGAAGGCGGCTCTCTGGGCCTGTTCTGACGCTGAGGAGCGAAAGCTGGGGTAGCAAACAGG+>90179b7710e4f00cc4de907ada3d13a5+TACGTAGGGTCCAAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCTCGTAGGCGGTCCGTTAAGTCGGAAGTGAAATCTCAAGGCTCAACCTTGAAATTGCTTTCGATACTGGCGGACTTGAGGCAGGTAGGGGAAGGTGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCAGTGGCGAAGGCGGCCTTCTGGGCCTGTACTGACGCTGAGGAGCGAAAGCGTGGGGAGCAAACAGG+>bb0a57a999432eb92864d72d6284edae+TACGTAGGGACCAAGCGTTGTCCGGATTTATTGGGCGTAAAGAGCTCGTAGGCGGCTGTTCGCGTCGGATGTGAAAGCTCAGAGCTCAACTCTGAGAGGCCATTCGATACGGGATAGCTAGAGGTAGGTAGGGGAGATCGGAATTCCTGGTGTAGCGGTGAAATGCGCAGATATCAGGAGGAACACCGGTGGCGAAGGCGGATCTCTGGGCCTTACCTGACGCTGAGGAGCGAAAGCTGGGGGAGCAAACAGG+>d324c95a5966d689591653062ca99d03+TACGTAGGGGGCGAGCGTTGTCCGGAATTATTGGGCGTAAAGAGCGTGTAGGCGGCCTGGTAAGTCTGCTGTGAAACCTTGGGGCTCAACCCCAAGCGTGCAGTGGATACTGCTAGGCTAGAGGATGGTAGAGGCGAGTGGAATTCCCGGTGTAGCGGTGAAATGCGCAGATATCGGGAGGAACACCAGTAGCGAAGGCGGCTCGCTGGGCCATTCCTGACGCTGAGACGCGAAAGCTAGGGGAGCGAACAGG+>3587ee8f8d9cefe13b27e5559b8e1b58+TACGTAGGGGGCAAGCGTTGTCCGGATTTATTGGGCGTAAAGAGCTCGTAGGCGGCCTGGTGAGTCGGGTGTGAAAGCCCGAGGCTCAACCTCGGAATTGCATTCGATACTGCTGGGCTTGAGGCAGGTAGGGGAGGATGGAATTCCCGGTGTAGCGGTGGAATGCGCAGATATCGGGAGGAACACCTGCGGCGAAGGCGGTCCTCTGGGCCTGTCCTGACGCTGAGGAGCGAAAGCGTGGGGAGCGAACAGG+>868e0aaa76b7fda3a2d8845889ca8f2b+TACGGAGGGTGCGAGCGTTAATCGGAATTACTGGGCGTAAAGGGCGCGTAGGCGGTTGGGTAAGTCGGATGTGAAAGCCCTGGGCTTAACCTGGGAATGGCATTCGAGACTACCTATCTAGAGTCTGGTAGAGGGAAGTGGAATTTCCGGTGTAGCGGTGAAATGTGTAGATATCGGAAGGAACACCAGTGGCGAAGGCGACTTCCTGGACCAAGACTGACGCTGAGGCGCGAAAGCGTGGGGATCAAACAGG+>f2fd9d7b74d80ad0cc6f3439e6325d27+TACGGAGGGTGCGAGCGTTGTCCGGAATCACTGGGCGTAAAGGGCGCGTAGGCGGCCTGATAAGTAGGGGGTGAAATCCTGCGGCTTAACCGCAGGGCTGCCTTCTAAACTGTCAGGCTCGAGCACAGTAGAGGCAGGTGGAATTCCCGGTGTAGCGGTGGAATGCGTAGAGATCGGGAAGAACATCAGTGGCGAAGGCGGCCTGCTGGGCTGTTGCTGACGCTGAGGCGCGACAGCGTGGGGAGCAAACAGG+>f01fcb3165881248269b22cf5ff01ebe+GACGTAGGGCGCGAGCGTTGTCCGGATTTATTGGGCGTAAAGGGCTCGTAGGCGGCTCGTCGCGTCTGTCGTGAAAGGCTCCGGCTTAACCGGGGTTTTGCGGTGGATACGGGCGGGCTTGAGGCTAGTAGGGGAGATCGGAATTCTACGTGTAGCGGTGAAATGCGCAGATATGTGGAGGAACACCGGTGGCGAAGGCGGATCTCTGGGCTGGTTCTGACGCTGAGGAGCGAAAGCATGGGGAGCGAACAGG+>e16d86b7fe770de88e7e8fd0fb6c8b5a+TACAGAGGGTGCGAGCGTTAATCGGAATTACTGGGCGTAAAGCGCGCGTAGGCGGCTTTGCAAGTCGGGTGTGAAATCCCCAGGCTTAACCTGGGAACTGCATTCGAGACTGCATTGCTAGAGTATGGGAGAGGGAAGTGGAATTTCCGGTGTAGCGGTGAAATGCGTAGATATCGGAAGGAACATCAGTGGCGAAAGCGACTTCCTGGACCAATACTGACGCTCATGTGCGAAAGCGTGGGGAGCAAACAGGdiff --git a/tests/qiime2-amplicon/fixtures/paired-default.tsv b/tests/qiime2-amplicon/fixtures/paired-default.tsvnew file mode 100644index 00000000..1e15f881--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/paired-default.tsv@@ -0,0 +1,20 @@+# Constructed from biom file+#OTU ID BAQ2420.2 BAQ3473.2 BAQ3473.3 BAQ4166.2 BAQ4166.3 PAP130.2 YUN1005.3 YUN1242.1 YUN1242.3 YUN3153.3 BLANK+cbd46c06c1ddceeb8d856468c1b549c8 0.0 0.0 0.0 0.0 0.0 0.0 0.0 30.0 0.0 0.0 0.0+c15fd6a65f4f8d575c2cb4cfe2a659a5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 28.0 0.0 0.0+854614d933d994aecc1d1b7bbc24e675 0.0 0.0 0.0 0.0 0.0 0.0 22.0 0.0 0.0 0.0 0.0+7925aae7da7d248eccdcd0ed0935ad61 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 20.0 0.0+5de23fc8df270235a8958de416e2f944 0.0 0.0 0.0 0.0 0.0 0.0 18.0 0.0 0.0 0.0 0.0+27ae47cc0e39b6df154b6938d9848c1b 0.0 0.0 0.0 0.0 0.0 0.0 17.0 0.0 0.0 0.0 0.0+acca130825261f8ae2e602bfe1865525 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 16.0 0.0 0.0+0018939bf02c32c9a63c42ade52cefad 15.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0+31ca42f58709548b0c88ae9153bece35 0.0 0.0 11.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0+4ec5e8b7a8c0d46bebe446577daa0352 0.0 0.0 0.0 0.0 0.0 0.0 11.0 0.0 0.0 0.0 0.0+90179b7710e4f00cc4de907ada3d13a5 0.0 0.0 0.0 0.0 0.0 0.0 0.0 11.0 0.0 0.0 0.0+bb0a57a999432eb92864d72d6284edae 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 11.0 0.0+d324c95a5966d689591653062ca99d03 0.0 0.0 0.0 0.0 0.0 0.0 0.0 8.0 0.0 0.0 0.0+3587ee8f8d9cefe13b27e5559b8e1b58 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 6.0 0.0 0.0+868e0aaa76b7fda3a2d8845889ca8f2b 0.0 0.0 5.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0+f2fd9d7b74d80ad0cc6f3439e6325d27 0.0 0.0 0.0 0.0 5.0 0.0 0.0 0.0 0.0 0.0 0.0+f01fcb3165881248269b22cf5ff01ebe 0.0 0.0 0.0 0.0 0.0 5.0 0.0 0.0 0.0 0.0 0.0+e16d86b7fe770de88e7e8fd0fb6c8b5a 0.0 0.0 0.0 0.0 4.0 0.0 0.0 0.0 0.0 0.0 0.0diff --git a/tests/qiime2-amplicon/fixtures/provenance.json b/tests/qiime2-amplicon/fixtures/provenance.jsonnew file mode 100644index 00000000..216fc91f--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/provenance.json@@ -0,0 +1,35 @@+{+ "upstream_commit": "8bbf5158d6c71b37b57a0e1f6e2b1cb69b9e96d7",+ "upstream_url": "https://github.com/qiime2/q2-dada2/tree/8bbf5158d6c71b37b57a0e1f6e2b1cb69b9e96d7/q2_dada2/tests/data",+ "primer_forward": "ACGTTGCAACGTTGCAAC",+ "primer_reverse": "TGCAACGTTGCAACGTTG",+ "maximum_insert_length": 254,+ "files_sha256": {+ "BAQ2420.2_10_L001_R1_001.fastq.gz": "9cc0f30c29e16143f122779b574f9177d1ef83874b83622df7f7549a8118b3e6",+ "BAQ2420.2_11_L001_R2_001.fastq.gz": "493b37da2dbf5a233a2655d20a0abc741def552032f592258fdfbf1967bc930e",+ "BAQ3473.2_0_L001_R1_001.fastq.gz": "37dcc4cb894c39b68e2c64827dae131f672e1e258bcacb68c9d1afe94442a2e5",+ "BAQ3473.2_1_L001_R2_001.fastq.gz": "f0fce673132fd30e208e69fe3c4f1b131dbacd7f9b67c2d10599ddc287f91f21",+ "BAQ3473.3_2_L001_R1_001.fastq.gz": "f0579f91f3b8286aabacea4b1117755d0e7333466d626b3e75c1d36154259ab1",+ "BAQ3473.3_3_L001_R2_001.fastq.gz": "a0c99964282dff1cb8b6974a39ea82ffc8ee124041d9c7fc9d1ef91c82eee34d",+ "BAQ4166.2_4_L001_R1_001.fastq.gz": "2839bf6031f5f294b4c0bb82b53db11575cdbe599cd600c7c193768664fc13c5",+ "BAQ4166.2_5_L001_R2_001.fastq.gz": "72f1ddbefd627a38b26a0b3c11eaddfab8352d43072dbda89d9a05c88f8a6f7b",+ "BAQ4166.3_14_L001_R1_001.fastq.gz": "86be0b44f6bba718a51bd2db6ff54a57cc299328e5bbc310222340849e99deb7",+ "BAQ4166.3_15_L001_R2_001.fastq.gz": "da9eb8aeb7094e9191299bbbb208d3e74bd70cb54eb3af9fe89450e30cd5132c",+ "LICENSE": "2a8ee71d2101f596a3749b7dc0541023dba34fe456b8b6e1230f690dc81be321",+ "PAP130.2_6_L001_R1_001.fastq.gz": "c50981ae89ae45de1c5c8c54011dc876dcd40f2442f04de7d25ce013b7f1f4e6",+ "PAP130.2_7_L001_R2_001.fastq.gz": "f4aa82e639d2a861fa0376e91b7045b0097153253adf5db4c9b90b4085de8b5b",+ "YUN1005.3_16_L001_R1_001.fastq.gz": "c21c6cd25035fe96bc899cbd7f36b30599ffcb6fdf0175bf5b12d381da725f2e",+ "YUN1005.3_17_L001_R2_001.fastq.gz": "951695ad3eca58b9e13513ea21965773842a6bba4da5e5c9d82df2e1650057c8",+ "YUN1242.1_8_L001_R1_001.fastq.gz": "efef76a896c86b5e6d46ad61bf0936af3f67c01c8011f30c26359cd73bdc3353",+ "YUN1242.1_9_L001_R2_001.fastq.gz": "efbe2d9dfd7e36a8b8ec67edbf77ff73be942cd0364af5d191cac2da3fa90768",+ "YUN1242.3_12_L001_R1_001.fastq.gz": "c8a7ed213c9e92efc5645458e330ccaec757461f178e5913e1130a8bb3e708b5",+ "YUN1242.3_13_L001_R2_001.fastq.gz": "fab9f26442aa0fcd735e1522bf817621a82aaea74bfa50f465e4f11d4858fd10",+ "YUN3153.3_18_L001_R1_001.fastq.gz": "9c5912158dd998c8f8f1db9cc7b13688348c4f27fc141a5242b98f855de0a83b",+ "YUN3153.3_19_L001_R2_001.fastq.gz": "5c8b16cf74b0d5784cb3b2b2c0a816088f38bf78c36500cda64a858ee1dca841",+ "paired-default-stats.tsv": "c0d3a36eedd50b4b2ce24f8d121b17c6d6b3f2437d15b3f042c59d3d4910caa4",+ "paired-default.fasta": "48a096b1263df7d2ed7c3c08784f3303818c8ebd72fa7504d7b82ab349dcc3aa",+ "paired-default.tsv": "b2c652be32268dc296e0bca52fb6bf5d905d3679e88aa57831a4f0fc14401a43",+ "sample-metadata.tsv": "a7d780f536669a16018b3dbc8635c6bf4b5882bf3e2c583f6028a660634498fe",+ "smoke-taxonomy.tsv": "0093282e83166c057214b04bd5e6dec03fef7778f858c1eebe63738cdcd9751e"+ }+}diff --git a/tests/qiime2-amplicon/fixtures/sample-metadata.tsv b/tests/qiime2-amplicon/fixtures/sample-metadata.tsvnew file mode 100644index 00000000..aa5140ec--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/sample-metadata.tsv@@ -0,0 +1,11 @@+sample-id fixture+BAQ2420.2 upstream-paired+BAQ3473.2 upstream-paired+BAQ3473.3 upstream-paired+BAQ4166.2 upstream-paired+BAQ4166.3 upstream-paired+PAP130.2 upstream-paired+YUN1005.3 upstream-paired+YUN1242.1 upstream-paired+YUN1242.3 upstream-paired+YUN3153.3 upstream-paireddiff --git a/tests/qiime2-amplicon/fixtures/smoke-taxonomy.tsv b/tests/qiime2-amplicon/fixtures/smoke-taxonomy.tsvnew file mode 100644index 00000000..63029db8--- /dev/null+++ b/tests/qiime2-amplicon/fixtures/smoke-taxonomy.tsv@@ -0,0 +1,18 @@+cbd46c06c1ddceeb8d856468c1b549c8 d__SyntheticFixture; p__Fixture1+c15fd6a65f4f8d575c2cb4cfe2a659a5 d__SyntheticFixture; p__Fixture2+854614d933d994aecc1d1b7bbc24e675 d__SyntheticFixture; p__Fixture3+7925aae7da7d248eccdcd0ed0935ad61 d__SyntheticFixture; p__Fixture4+5de23fc8df270235a8958de416e2f944 d__SyntheticFixture; p__Fixture5+27ae47cc0e39b6df154b6938d9848c1b d__SyntheticFixture; p__Fixture6+acca130825261f8ae2e602bfe1865525 d__SyntheticFixture; p__Fixture7+0018939bf02c32c9a63c42ade52cefad d__SyntheticFixture; p__Fixture8+31ca42f58709548b0c88ae9153bece35 d__SyntheticFixture; p__Fixture9+4ec5e8b7a8c0d46bebe446577daa0352 d__SyntheticFixture; p__Fixture10+90179b7710e4f00cc4de907ada3d13a5 d__SyntheticFixture; p__Fixture11+bb0a57a999432eb92864d72d6284edae d__SyntheticFixture; p__Fixture12+d324c95a5966d689591653062ca99d03 d__SyntheticFixture; p__Fixture13+3587ee8f8d9cefe13b27e5559b8e1b58 d__SyntheticFixture; p__Fixture14+868e0aaa76b7fda3a2d8845889ca8f2b d__SyntheticFixture; p__Fixture15+f2fd9d7b74d80ad0cc6f3439e6325d27 d__SyntheticFixture; p__Fixture16+f01fcb3165881248269b22cf5ff01ebe d__SyntheticFixture; p__Fixture17+e16d86b7fe770de88e7e8fd0fb6c8b5a d__SyntheticFixture; p__Fixture18diff --git a/tests/qiime2-amplicon/run_integration.py b/tests/qiime2-amplicon/run_integration.pynew file mode 100644index 00000000..461fb602--- /dev/null+++ b/tests/qiime2-amplicon/run_integration.py@@ -0,0 +1,113 @@+"""Execute or independently verify the bounded real QIIME 2 regression workflow."""+from __future__ import annotations++import argparse+import csv+import gzip+import hashlib+import io+import json+from pathlib import Path+import shutil+import subprocess+import sys+import zipfile++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "qiime2-amplicon"+FIXTURES = Path(__file__).resolve().parent / "fixtures"+++def fasta_sequences(text):+ sequences, current = [], []+ for line in text.splitlines():+ if line.startswith(">"):+ if current:+ sequences.append("".join(current))+ current = []+ else:+ current.append(line.strip())+ if current:+ sequences.append("".join(current))+ return set(sequences)+++def stats_rows(path):+ with path.open(newline="") as handle:+ return {row["sample-id"]: row for row in csv.DictReader(handle, delimiter="\t")+ if not row["sample-id"].startswith("#")}+++def verify(results):+ expected = stats_rows(FIXTURES / "paired-default-stats.tsv")+ expected.pop("BLANK")+ observed = stats_rows(results / "stats" / "stats.tsv")+ assert set(observed) == set(expected), "DADA2 sample IDs changed"+ for sample, row in expected.items():+ for stage in ("input", "filtered", "denoised", "merged", "non-chimeric"):+ assert int(observed[sample][stage]) == int(row[stage]), (sample, stage, observed[sample][stage], row[stage])+ artifact = results / "denoise" / "representative_sequences.qza"+ with zipfile.ZipFile(artifact) as archive:+ names = [name for name in archive.namelist() if "/data/" in name and name.endswith((".fasta", ".fa"))]+ assert len(names) == 1, names+ actual_sequences = fasta_sequences(archive.read(names[0]).decode())+ expected_sequences = fasta_sequences((FIXTURES / "paired-default.fasta").read_text())+ assert actual_sequences == expected_sequences, "Recovered ASV sequences differ from upstream regression fixture"+ for name in ("taxonomy.qza", "table.qzv", "taxa.qzv", "feature-frequencies.qza", "sample-frequencies.qza", "retention-qc.json", "commands.json", "qiime-info.txt"):+ assert (results / name).is_file(), name+ expected_feature_ids = {hashlib.md5(sequence.encode()).hexdigest() for sequence in expected_sequences}+ with zipfile.ZipFile(results / "taxonomy.qza") as archive:+ names = [name for name in archive.namelist() if name.endswith("/data/taxonomy.tsv")]+ assert len(names) == 1, names+ taxonomy = list(csv.DictReader(io.StringIO(archive.read(names[0]).decode()), delimiter="\t"))+ assert {row["Feature ID"] for row in taxonomy} == expected_feature_ids, "Taxonomy feature IDs do not match ASVs"+ assert all(row["Taxon"].startswith("d__SyntheticFixture") for row in taxonomy), "Smoke classifier lost its known domain labels"+ artifacts = list(results.rglob("*.qza"))+ for artifact in artifacts:+ with zipfile.ZipFile(artifact) as archive:+ assert any(name.endswith("/provenance/action/action.yaml") for name in archive.namelist()), artifact+ return {"samples": len(observed), "asvs": len(actual_sequences),+ "non_chimeric_reads": sum(int(row["non-chimeric"]) for row in observed.values()),+ "upstream_sequence_and_stage_counts_match": True,+ "taxonomy_feature_ids_and_synthetic_domain_labels_match": True,+ "artifacts_with_action_provenance": len(artifacts),+ "taxonomy_accuracy_evaluated": False}+++def run(output):+ output.mkdir(parents=True, exist_ok=False)+ reads = output / "reads"+ reads.mkdir()+ pairs = {}+ for source in sorted(FIXTURES.glob("*.fastq.gz")):+ target = reads / source.name+ shutil.copy2(source, target)+ sample = source.name.split("_")[0]+ direction = "forward" if "_R1_" in source.name else "reverse"+ with gzip.open(target, "rt") as handle:+ assert sum(1 for _ in handle) == 400+ pairs.setdefault(sample, {})[direction] = str(target.resolve())+ manifest = output / "manifest.tsv"+ with manifest.open("w", newline="") as handle:+ writer = csv.writer(handle, delimiter="\t")+ writer.writerow(["sample-id", "forward-absolute-filepath", "reverse-absolute-filepath"])+ writer.writerows([sample, pair["forward"], pair["reverse"]] for sample, pair in sorted(pairs.items()))+ commands = [+ ["qiime", "tools", "import", "--type", "FeatureData[Sequence]", "--input-path", str(FIXTURES / "paired-default.fasta"), "--output-path", str(output / "reference-seqs.qza")],+ ["qiime", "tools", "import", "--type", "FeatureData[Taxonomy]", "--input-format", "HeaderlessTSVTaxonomyFormat", "--input-path", str(FIXTURES / "smoke-taxonomy.tsv"), "--output-path", str(output / "reference-taxonomy.qza")],+ ["qiime", "feature-classifier", "fit-classifier-naive-bayes", "--i-reference-reads", str(output / "reference-seqs.qza"), "--i-reference-taxonomy", str(output / "reference-taxonomy.qza"), "--o-classifier", str(output / "smoke-classifier.qza")],+ [sys.executable, str(SKILL_ROOT / "scripts" / "amplicon_workflow.py"), "run", "--manifest", str(manifest), "--metadata", str(FIXTURES / "sample-metadata.tsv"), "--primer-f", "ACGTTGCAACGTTGCAAC", "--primer-r", "TGCAACGTTGCAACGTTG", "--trunc-f", "150", "--trunc-r", "150", "--amplicon-max", "254", "--classifier", str(output / "smoke-classifier.qza"), "--output", str(output / "results")],+ ]+ (output / "fixture-commands.json").write_text(json.dumps(commands, indent=2) + "\n")+ for command in commands:+ subprocess.run(command, check=True)+ return verify(output / "results")+++if __name__ == "__main__":+ parser = argparse.ArgumentParser(description=__doc__)+ mode = parser.add_mutually_exclusive_group(required=True)+ mode.add_argument("--output", type=Path, help="Fresh directory for an actual QIIME run")+ mode.add_argument("--verify-only", type=Path, help="Existing skill results directory")+ args = parser.parse_args()+ evidence = verify(args.verify_only) if args.verify_only else run(args.output.resolve())+ print(json.dumps(evidence, indent=2))diff --git a/tests/qiime2-amplicon/test_scripts.py b/tests/qiime2-amplicon/test_scripts.pynew file mode 100644index 00000000..8bcc54cc--- /dev/null+++ b/tests/qiime2-amplicon/test_scripts.py@@ -0,0 +1,67 @@+from pathlib import Path+import gzip+import importlib.util+import pytest+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / 'skills' / 'qiime2-amplicon'+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+spec = importlib.util.spec_from_file_location('amplicon_workflow', SKILL_ROOT / 'scripts' / 'amplicon_workflow.py')+workflow = importlib.util.module_from_spec(spec)+spec.loader.exec_module(workflow)+++def example(tmp_path, reverse_id='read1', reverse_sequence='TGCATGCA'+'C'*100):+ for name, identifier, sequence in [('f', 'read1', 'ACGTACGT'+'A'*100), ('r', reverse_id, reverse_sequence)]:+ with gzip.open(tmp_path/f'{name}.fastq.gz', 'wt') as f:+ f.write(f'@{identifier}\n{sequence}\n+\n'+len(sequence)*'I'+'\n')+ manifest = tmp_path/'manifest.tsv'+ manifest.write_text('sample-id\tforward-absolute-filepath\treverse-absolute-filepath\nsample1\t'+str(tmp_path/'f.fastq.gz')+'\t'+str(tmp_path/'r.fastq.gz')+'\n')+ metadata = tmp_path/'metadata.tsv'+ metadata.write_text('sample-id\tcondition\n#q2:types\tcategorical\nsample1\tcontrol\n')+ return manifest, metadata+++def test_iupac_primer_detection_and_real_overlap(tmp_path):+ manifest, metadata = example(tmp_path)+ result = workflow.validate(manifest, metadata, 'ACGTNCGT', 'TGCATGCA', 100, 100, 180)+ assert result['minimum_predicted_overlap'] == 20+ assert result['samples'][0]['exact_primer_fraction_first_1000'] == [1.0, 1.0]+ assert result['samples'][0]['raw_pairs'] == 1+++def test_insufficient_overlap_is_rejected(tmp_path):+ manifest, metadata = example(tmp_path)+ with pytest.raises(ValueError, match='overlap'):+ workflow.validate(manifest, metadata, 'ACGTACGT', 'TGCATGCA', 100, 100, 195)++[email protected]('problem', ['pair_id', 'metadata', 'truncation', 'same_file'])+def test_read_and_sample_failures(tmp_path, problem):+ manifest, metadata = example(tmp_path, reverse_id='different' if problem == 'pair_id' else 'read1')+ if problem == 'metadata':+ metadata.write_text('sample-id\nother\n')+ if problem == 'same_file':+ manifest.write_text(manifest.read_text().replace('r.fastq.gz', 'f.fastq.gz'))+ with pytest.raises(ValueError):+ workflow.validate(manifest, metadata, 'ACGTACGT', 'TGCATGCA', 120 if problem == 'truncation' else 100, 100, 180)+++def test_malformed_fastq_is_rejected(tmp_path):+ path = tmp_path/'bad.fastq'+ path.write_text('@r\nACGT\n+\nIII\n')+ with pytest.raises(ValueError, match='Malformed'):+ list(workflow.fastq(path))+++def test_retention_separates_raw_and_trimmed_losses(tmp_path):+ stats = tmp_path/'stats.tsv'+ stats.write_text('sample-id\tinput\tfiltered\tdenoised\tmerged\tnon-chimeric\n#q2:types\tnumeric\tnumeric\tnumeric\tnumeric\tnumeric\nsample1\t80\t60\t55\t40\t30\n')+ result = workflow.retention(stats, {'sample1': 100})+ assert result['samples'][0]['retained_fraction'] == 0.3+ assert result['warnings']+ with pytest.raises(ValueError, match='exceeds'):+ workflow.retention(stats, {'sample1': 50})+ stats.write_text(stats.read_text().replace('\t40\t30', '\t40\t45'))+ with pytest.raises(ValueError, match='increase'):+ workflow.retention(stats)diff --git a/tests/relion/test_scripts.py b/tests/relion/test_scripts.pynew file mode 100644index 00000000..1b9921ae--- /dev/null+++ b/tests/relion/test_scripts.py@@ -0,0 +1,158 @@+from pathlib import Path+import importlib.util+import os+import subprocess+import numpy as np+import mrcfile+import pandas as pd+import pytest+import starfile+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / 'skills' / 'relion'+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+spec = importlib.util.spec_from_file_location('spa_workflow', SKILL_ROOT/'scripts'/'spa_workflow.py')+spa = importlib.util.module_from_spec(spec)+spec.loader.exec_module(spa)+++def write_map(path, data, pixel=1.5):+ with mrcfile.new(path, overwrite=True) as handle:+ handle.set_data(np.asarray(data, dtype=np.float32))+ handle.voxel_size = pixel+++def star_fixture(tmp_path):+ write_map(tmp_path/'particles.mrcs', np.ones((4, 8, 8)))+ optics = pd.DataFrame({'rlnOpticsGroup': [1], 'rlnVoltage': [300.], 'rlnSphericalAberration': [2.7],+ 'rlnAmplitudeContrast': [.1], 'rlnImagePixelSize': [1.5],+ 'rlnImageSize': [8], 'rlnImageDimensionality': [2]})+ particles = pd.DataFrame({'rlnOpticsGroup': [1]*4, 'rlnImageName': [f'{k}@particles.mrcs' for k in range(1,5)],+ 'rlnDefocusU': [10000.]*4, 'rlnDefocusV': [11000.]*4,+ 'rlnDefocusAngle': [0.]*4, 'rlnRandomSubset': [1,2,1,2]})+ path = tmp_path/'particles.star'+ starfile.write({'optics': optics, 'particles': particles}, path)+ return path, optics, particles+++def half_maps(tmp_path):+ rng = np.random.default_rng(13)+ z,y,x = np.indices((32,32,32)); signal=np.exp(-((z-16)**2+(y-16)**2+(x-16)**2)/32)+ a, b = signal+rng.normal(0,.05,signal.shape), signal+rng.normal(0,.05,signal.shape)+ first, second = tmp_path/'half1.mrc', tmp_path/'half2.mrc'+ write_map(first, a); write_map(second, b)+ return first, second+++def test_optics_particle_stack_and_half_set_mapping(tmp_path):+ path, _, _ = star_fixture(tmp_path)+ result = spa.validate_star(path, tmp_path)+ assert result['particles'] == 4+ assert result['half_sets'] == {'1': 2, '2': 2}+ assert result['pixel_sizes_angstrom'] == [1.5]++[email protected]('kind', ['undefined_optics', 'duplicate', 'bad_index', 'defocus_sign', 'nan', 'single_half'])+def test_invalid_star_scientific_contracts(tmp_path, kind):+ path, optics, particles = star_fixture(tmp_path)+ if kind == 'undefined_optics': particles.loc[0, 'rlnOpticsGroup'] = 2+ if kind == 'duplicate': particles.loc[0, 'rlnImageName'] = '2@./particles.mrcs'+ if kind == 'bad_index': particles.loc[0, 'rlnImageName'] = '[email protected]'+ if kind == 'defocus_sign': particles.loc[0, 'rlnDefocusU'] = -1+ if kind == 'nan': optics.loc[0, 'rlnImagePixelSize'] = float('nan')+ if kind == 'single_half': particles['rlnRandomSubset'] = 1+ starfile.write({'optics': optics, 'particles': particles}, path, overwrite=True)+ with pytest.raises(ValueError):+ spa.validate_star(path, tmp_path)+++def test_fsc_detects_shared_signal_and_noise_floor(tmp_path):+ first, second = half_maps(tmp_path)+ result = spa.fsc(first, second, tmp_path/'fsc.tsv')+ frame = pd.read_csv(tmp_path/'fsc.tsv', sep='\t')+ assert frame.fsc.iloc[1] > .99+ assert abs(frame.fsc.iloc[-5:].mean()) < .05+ assert result['unmasked_diagnostic_fsc_0143_angstrom'] > result['nyquist_angstrom']+ assert result['shells'] == 17+++def test_independence_and_grid_failures(tmp_path):+ first, second = half_maps(tmp_path)+ with pytest.raises(ValueError, match='identical'):+ spa.check_halves(first, first)+ with mrcfile.open(second, mode='r+') as handle:+ handle.voxel_size = 2.+ with pytest.raises(ValueError, match='disagree'):+ spa.check_halves(first, second)+++def test_hard_mask_is_not_accepted_for_postprocessing(tmp_path):+ first, second = half_maps(tmp_path)+ mask = np.zeros((32,32,32)); mask[8:24,8:24,8:24] = 1+ path = tmp_path/'mask.mrc'; write_map(path, mask)+ with pytest.raises(ValueError, match='soft edge'):+ spa.check_halves(first, second, path)+++def test_native_relion_fsc_agrees_with_local_diagnostic(tmp_path):+ executable = os.environ.get('RELION_IMAGE_HANDLER_TEST_EXECUTABLE')+ if not executable:+ pytest.skip('Set RELION_IMAGE_HANDLER_TEST_EXECUTABLE for RELION5.0.1 CPU integration')+ first, second = half_maps(tmp_path)+ result = subprocess.run([executable, '--i', str(first), '--fsc', str(second), '--angpix', '1.5'],+ text=True, capture_output=True, check=True, cwd=tmp_path)+ native = tmp_path/'native.star'; native.write_text(result.stdout)+ frame = starfile.read(native)+ spa.fsc(first, second, tmp_path/'local.tsv')+ local = pd.read_csv(tmp_path/'local.tsv', sep='\t')+ # RELION stores one rFFT half-plane; small differences may arise from shell weighting.+ assert np.max(abs(frame['rlnFourierShellCorrelation'].to_numpy()[1:] - local.fsc.to_numpy()[1:])) < .06+++def test_native_relion_postprocess_runs_with_soft_mask(tmp_path):+ executable = os.environ.get('RELION_POSTPROCESS_TEST_EXECUTABLE')+ if not executable:+ pytest.skip('Set RELION_POSTPROCESS_TEST_EXECUTABLE for RELION5.0.1 postprocessing integration')+ first, second = half_maps(tmp_path)+ z,y,x = np.indices((32,32,32)); radius=np.sqrt((z-16)**2+(y-16)**2+(x-16)**2)+ mask = np.where(radius<=8, 1, np.where(radius>=12, 0, .5+.5*np.cos(np.pi*(radius-8)/4)))+ mask_path = tmp_path/'soft_mask.mrc'; write_map(mask_path, mask)+ import sys+ subprocess.run([sys.executable, str(SKILL_ROOT/'scripts'/'spa_workflow.py'), 'postprocess',+ '--half1', str(first), '--half2', str(second), '--mask', str(mask_path),+ '--output', str(tmp_path/'postprocess'), '--executable', executable],+ capture_output=True, text=True, check=True, cwd=tmp_path)+ result = starfile.read(tmp_path/'postprocess'/'postprocess.star', always_dict=True)+ assert np.isfinite(result['general']['rlnFinalResolution'])+ assert result['general']['rlnFinalResolution'] > 3+++def test_native_mpi_refinement_smoke_preserves_halves(tmp_path):+ executable = os.environ.get('RELION_REFINE_TEST_EXECUTABLE')+ if not executable:+ pytest.skip('Set RELION_REFINE_TEST_EXECUTABLE for tiny RELION5.0.1 MPI runtime smoke')+ # Symmetric smooth signal with noise is a launcher fixture, not a physical CTF simulation.+ rng = np.random.default_rng(17)+ z,y,x = np.indices((16,16,16))+ reference = np.exp(-((z-8)**2+(y-8)**2+(x-8)**2)/8)+ projection = reference.sum(axis=0); projection /= projection.std()+ images = np.stack([projection+rng.normal(0,1,(16,16)) for _ in range(32)])+ write_map(tmp_path/'initial.mrc', reference); write_map(tmp_path/'particles.mrcs', images)+ optics = pd.DataFrame({'rlnOpticsGroupName': ['optics1'], 'rlnOpticsGroup': [1],+ 'rlnVoltage': [300.], 'rlnSphericalAberration': [2.7], 'rlnAmplitudeContrast': [.1],+ 'rlnImagePixelSize': [1.5], 'rlnImageSize': [16], 'rlnImageDimensionality': [2]})+ particles = pd.DataFrame({'rlnOpticsGroup': [1]*32, 'rlnImageName': [f'{k}@particles.mrcs' for k in range(1,33)],+ 'rlnDefocusU': [10000.]*32, 'rlnDefocusV': [10000.]*32, 'rlnDefocusAngle': [0.]*32})+ starfile.write({'optics': optics, 'particles': particles}, tmp_path/'particles.star')+ import sys, json+ result = subprocess.run([sys.executable, str(SKILL_ROOT/'scripts'/'spa_workflow.py'), 'refine',+ '--star', str(tmp_path/'particles.star'), '--reference', str(tmp_path/'initial.mrc'),+ '--project', str(tmp_path), '--diameter', '18', '--initial-lowpass', '12',+ '--threads', '1', '--output', str(tmp_path/'result'), '--executable', executable],+ capture_output=True, text=True, check=True, timeout=180, cwd=tmp_path)+ report = json.loads(result.stdout)+ assert report['refined_particles']['particles'] == 32+ assert set(report['refined_particles']['half_sets']) == {'1', '2'}+ for k in (1,2):+ data, pixel, _ = spa.read_map(tmp_path/'result'/f'run_half{k}_class001_unfil.mrc')+ assert data.shape == (16,16,16) and pixel == 1.5diff --git a/tests/skill-requirements.toml b/tests/skill-requirements.tomlindex 59d2603d..b217599f 100644--- a/tests/skill-requirements.toml+++ b/tests/skill-requirements.toml@@ -831,12 +831,69 @@ packages = []python = "3.10"packages = ["torch"]+# --- additional executable scientific workflows --------------------------++[skills.nmrglue]+python = "3.12"+packages = ["nmrglue==0.12", "numpy==2.5.3", "scipy==1.18.1"]++[skills.mageck]+python = "3.11"+packages = []++[skills.cantera]+python = "3.12"+packages = ["cantera==3.2.0", "numpy==2.5.3"]++[skills.cellprofiler]+python = "3.12"+packages = ["numpy==2.5.3", "tifffile==2026.9.20"]++[skills.nwb-conversion]+python = "3.12"+packages = [+ "neuroconv[tiff]==0.10.2",+ "pynwb==4.2.0",+ "nwbinspector==0.7.2",+ "roiextractors==0.10.0",+ "tifffile==2026.9.20",+ "zarr==2.18.7",+ "hdmf-zarr==0.11.3",+]++[skills.pycalphad]+python = "3.12"+packages = ["pycalphad==0.11.2", "numpy==2.5.3"]++[skills.pybamm]+python = "3.12"+packages = ["pybamm==26.9.0.0", "pybammsolvers==0.10.0"]++[skills.qiime2-amplicon]+python = "3.12"+packages = []++[skills.relion]+python = "3.12"+packages = ["numpy==2.5.3", "mrcfile==1.5.4", "starfile==0.5.13"]++[skills.tellurium]+python = "3.11"+packages = [+ "tellurium==2.2.13.1", "libroadrunner==2.10.0", "antimony==3.2.0",+ "python-libsbml==5.21.2", "python-libsedml==2.0.34", "python-libcombine==0.2.20",+]+# --- packages a skill documents that cannot be installed here -------------## The runner prints these when it sets up the skill, so the gap is visible in# the test output rather than rediscovered each time.[unavailable]+qiime2-amplicon = "qiime2-amplicon skill: QIIME 2 2026.7 requires the full conda/container distribution including R and DADA2, rather than a pip installation. The portable helper suite is standard-library only."+relion = "relion skill: RELION 5.0.1 C++/MPI executables require a native build with FFTW, OpenMP, and MPI; the Python validators are tested separately."+cellprofiler = "cellprofiler skill: CellProfiler 4.2.8 needs Java and native system dependencies. Real integration was tested in the official linux/amd64 Docker image; the portable helper suite needs NumPy and tifffile only."+mageck = "mageck skill: MAGeCK 0.5.9.5 requires a source or Bioconda installation with its compiled RRA binary. Put the executable on PATH to run real integration tests; the bundled validation helpers use only the standard library."adaptyv-sdk = "adaptyv skill: distributed from GitHub only, not on PyPI"tiledbvcf = "tiledbvcf skill: not published to PyPI; conda-forge or a source build only"matlabengine = "matlab skill: requires a local MATLAB installation to build against"diff --git a/tests/tellurium/test_scripts.py b/tests/tellurium/test_scripts.pynew file mode 100644index 00000000..1145f99d--- /dev/null+++ b/tests/tellurium/test_scripts.py@@ -0,0 +1,79 @@+from pathlib import Path+import csv+import importlib.util+import json+import os+import zipfile++import pytest+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "tellurium"+CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)+os.environ.setdefault("MPLBACKEND", "Agg")+np = pytest.importorskip("numpy")+te = pytest.importorskip("tellurium")+libsbml = pytest.importorskip("libsbml")+pytest.importorskip("libsedml")+pytest.importorskip("libcombine")+spec = importlib.util.spec_from_file_location("kinetic_experiment", SKILL_ROOT / "scripts" / "kinetic_experiment.py")+kinetics = importlib.util.module_from_spec(spec)+spec.loader.exec_module(kinetics)+++def read_curve(path):+ with path.open() as handle:+ return np.asarray([[float(v) for v in row] for row in list(csv.reader(handle))[1:]])+++def test_real_antimony_analytic_conservation_perturbation_and_archive(tmp_path):+ report = kinetics.run(SKILL_ROOT / "assets" / "first-order.ant", "antimony",+ SKILL_ROOT / "assets" / "experiment.json", tmp_path / "result")+ assert report["sbml_validation_findings"] == []+ assert report["sedml_parse_findings"] == []+ for scenario, k in (("baseline", .2), ("double_k", .4)):+ values = read_curve(tmp_path / "result" / f"{scenario}.csv")+ np.testing.assert_allclose(values[:, 1], np.exp(-k * values[:, 0]), atol=2e-8, rtol=2e-8)+ np.testing.assert_allclose(values[:, 1] + values[:, 2], 1., atol=1e-10)+ assert report["archive_replay_max_absolute_difference"][scenario] < 1e-10+ with zipfile.ZipFile(tmp_path / "result" / "experiment.omex") as archive:+ assert {"model_baseline.xml", "model_double_k.xml", "experiment.sedml", "manifest.xml"} <= set(archive.namelist())+ assert report["units"]["time"] == "second"+ assert "litre (exponent = -1" in report["units"]["species"]["A"]+++def test_sbml_input_and_independent_conditions(tmp_path):+ source = tmp_path / "model.xml"+ source.write_text(te.antimonyToSBML((SKILL_ROOT / "assets" / "first-order.ant").read_text()))+ config = json.loads((SKILL_ROOT / "assets" / "experiment.json").read_text())+ config["scenarios"] = {"double_k": {"k": .4}, "baseline": {}}+ experiment = tmp_path / "experiment.json"; experiment.write_text(json.dumps(config))+ kinetics.run(source, "sbml", experiment, tmp_path / "result")+ baseline = read_curve(tmp_path / "result" / "baseline.csv")+ assert baseline[-1, 1] == pytest.approx(np.exp(-2), rel=1e-7)+++def test_preserve_unit_warnings_and_reject_invalid_model(tmp_path):+ source = tmp_path / "unitless.ant"+ source.write_text("model unitless()\nA -> B; k*A; A=1; B=0; k=0.2; end")+ _, issues = kinetics.model_document(source, "antimony")+ assert issues and any("unit" in issue["message"].lower() for issue in issues)+ source.write_text("<not_sbml />")+ with pytest.raises(ValueError, match="no SBML"):+ kinetics.model_document(source, "sbml")+++def test_reject_unknown_or_amount_species_and_bad_parameter():+ document, _ = kinetics.model_document(SKILL_ROOT / "assets" / "first-order.ant", "antimony")+ config = json.loads((SKILL_ROOT / "assets" / "experiment.json").read_text())+ config["scenarios"]["bad"] = {"A": .2}+ with pytest.raises(ValueError, match="constant global"):+ kinetics.validate_experiment(config, document.getModel())+ config["scenarios"].pop("bad")+ document.getModel().getSpecies("A").setHasOnlySubstanceUnits(True)+ with pytest.raises(ValueError, match="amount-only"):+ kinetics.validate_experiment(config, document.getModel())+ document.getModel().getSpecies("A").setHasOnlySubstanceUnits(False)+ config["points"] = 1+ with pytest.raises(ValueError, match="points"):+ kinetics.validate_experiment(config, document.getModel())