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
Add tested FlowKit cytometry analysis skill
Timothy Kassis0cfee454a072
diff --git a/README.md b/README.mdindex 6ff87f31..7425df03 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 168 skills in this repo. Your data stays on your computer, and you can optionally scale to cloud compute via [Modal](https://modal.com/) for heavy workloads. [Get started here.](https://github.com/K-Dense-AI/k-dense-byok)+> **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 169 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 **168 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, genome-wide precomputed variant effects from the AlphaGenome Atlas, hosted regulatory-sequence prediction, live pathogen-variant surveillance, analytical method validation, PK/PD modelling and dose selection, full-text biomedical and regulatory literature retrieval, drug-target binding, bounded biomedical knowledge graph search, custom lab-part fabrication quotes and orders through Fictiv, molecular dynamics, RNA velocity, microbiome foundation models, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). The repository is also a portable [Agent Plugins](https://agent-plugins.org/) package (`plugin.json` + `skills/`), so plugin-capable clients can load the whole collection as one plugin. Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.+A comprehensive collection of **169 ready-to-use scientific and research skills** (covering cancer genomics, individual-level 1000 Genomes queries, genome-wide precomputed variant effects from the AlphaGenome Atlas, hosted regulatory-sequence prediction, live pathogen-variant surveillance, analytical method validation, PK/PD modelling and dose selection, full-text biomedical and regulatory literature retrieval, drug-target binding, bounded biomedical knowledge graph search, custom lab-part fabrication quotes and orders through Fictiv, molecular dynamics, RNA velocity, microbiome foundation models, geospatial science, time series forecasting, scientific ML resource discovery via Hugging Science, 78+ scientific databases, and more) for any AI agent that supports the open [Agent Skills](https://agentskills.io/) standard, created by [K-Dense](https://k-dense.ai). The repository is also a portable [Agent Plugins](https://agent-plugins.org/) package (`plugin.json` + `skills/`), so plugin-capable clients can load the whole collection as one plugin. Works with **Cursor, Claude Code, Codex, Google Antigravity, and more**. Transform your AI agent into a research assistant capable of executing complex multi-step scientific workflows across biology, chemistry, medicine, and beyond.> ⭐ **Help make AI for science easier to discover:** If Scientific Agent Skills saves you time, teaches your agent a workflow, or helps your lab move faster, please [star this repository](https://github.com/K-Dense-AI/scientific-agent-skills). A star is a public signal that these open, reusable research skills are worth maintaining: it helps scientists, engineers, and open-source contributors find the project, shows which agent-skill standards are gaining real adoption, and gives us a clear reason to keep expanding the collection for the community.@@ -74,7 +74,7 @@ Recorded walkthroughs of these skills on real research tasks, from the [K-Dense## 📦 What's Included-This repository provides **168 scientific and research skills** organized into the following categories:+This repository provides **169 scientific and research skills** organized into the following categories:- **100+ Scientific & Financial Databases** - A unified database-lookup skill provides deterministic, provenance-rich access to 78 public databases (PubChem, ChEMBL, UniProt, COSMIC, ClinicalTrials.gov, FRED, USPTO, and more), plus dedicated skills for DepMap, Imaging Data Commons, PrimeKG, NCATS ARAX, U.S. Treasury Fiscal Data, Hugging Science, OneKGPd, Genomic Intelligence, and AlphaGenome (Atlas lookups and model scoring). Multi-database packages like BioServices (~40 bioinformatics services), BioPython (39 NCBI sub-databases via Entrez), and gget (20+ genomics databases) add further coverage- **70+ Optimized Python Package Skills** - Explicitly defined, version-aware workflows for RDKit, Scanpy, PyTorch Lightning, scikit-learn, PyTDC, PathML, pydicom, NeuroKit2, PufferLib, QuTiP, GeoPandas, pymatgen, BioPython, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), and others. The agent can still use *any* Python package; these skills provide stronger, safer guidance for the packages listed@@ -121,7 +121,7 @@ Each skill includes:- **Multi-Step Workflows** - Execute complex pipelines with a single prompt### 🎯 **Comprehensive Coverage**-- **168 Skills** - Extensive coverage across all major scientific domains+- **169 Skills** - Extensive coverage across all major scientific domains- **100+ Databases** - Unified access to 78+ databases via database-lookup, plus dedicated data access skills and multi-database packages like BioServices, BioPython, and gget- **70+ Optimized Python Package Skills** - Current, version-scoped guidance for packages including RDKit, Scanpy, PyTorch Lightning, scikit-learn, PyTDC, pydicom, PufferLib, QuTiP, GeoPandas, pymatgen, Qiskit, Molecular Dynamics (OpenMM/MDAnalysis), scVelo, and TimesFM (the agent can use any Python package; these are the pre-documented paths)@@ -228,7 +228,7 @@ For Hermes versions that support skill taps, add the repository as a tap:hermes skills tap add K-Dense-AI/scientific-agent-skills```-Every `SKILL.md` has YAML frontmatter, but legacy and community skills vary in `metadata` formatting (block or flow style) and optional extension fields. Repository updates must keep `metadata.version` as a quoted numeric string and pass canonical `skills-ref validate ./skills/<skill-name>` checks. Hosts may interpret optional metadata and credential prompts differently, so verify behavior on the target host. Because 168 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 169 skills add up to a lot of standing context, consider installing a topical subset rather than the whole collection.> **NemoClaw note:** NemoClaw runs agents inside NVIDIA OpenShell with default-deny outbound networking. Skills are discovered and loaded normally, but any skill that needs the network — package installs via `uv`, or API calls (Exa, Parallel, Benchling, NCBI, Materials Project, …) — only works once the operator pre-approves the relevant domains in the OpenShell TUI.@@ -469,17 +469,18 @@ networks, and search GEO for similar patterns.## 📚 Available Skills-This repository contains **168 scientific and research skills** organized across multiple domains. Each skill provides comprehensive documentation, code examples, and best practices for working with scientific libraries, databases, and tools.+This repository contains **169 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** (28 skills)+#### 🧬 **Bioinformatics & Genomics** (29 skills)- RNA-seq pipelines: Bulk RNA-seq (end-to-end FASTQ -> counts -> DE -> enrichment orchestrator)- Sequence analysis: BioPython, pysam, scikit-bio, BioServices- Single-cell analysis: Scanpy, AnnData, scvi-tools, scVelo (RNA velocity), Arboreto, Cellxgene Census-- Genomic tools: gget, current geniml/Gtars interval workflows, deepTools, FlowIO, Polars-Bio, Zarr, TileDB-VCF+- Genomic tools: gget, current geniml/Gtars interval workflows, deepTools, Polars-Bio, Zarr, TileDB-VCF+- Flow cytometry: FlowIO (FCS input/output), [FlowKit](skills/flowkit/SKILL.md) (compensation, transforms, hierarchical gating, and FlowJo workspace analysis)- Coordinate hygiene: Genomic Coordinates (convert intervals across BED/GFF/GTF/VCF/SAM/WIG conventions, normalise variant representations, and catch 0-based vs 1-based and assembly/contig-naming mismatches before they corrupt an analysis)- 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)@@ -925,7 +926,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 = {168 skills covering databases, packages, integrations, and analysis tools}+ note = {169 skills covering databases, packages, integrations, and analysis tools}}```diff --git a/docs/skills.md b/docs/skills.mdindex 50ce7a0e..434a6b67 100644--- a/docs/skills.md+++ b/docs/skills.md@@ -1,6 +1,6 @@# Scientific Skills-All **167 skills** in this checkout, grouped by domain. Summaries mirror each skill's+This checkout contains **169 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.@@ -58,6 +58,7 @@ and limitations. See [workflow examples](examples.md) for ways to combine them.- **[Cellxgene Census](../skills/cellxgene-census/SKILL.md)** - Query the CZ CELLxGENE Census programmatically for versioned public single-cell and spatial transcriptomics data. Use when you need population-scale cell metadata, gene expression slices, Census summary counts, source H5AD URIs/downloads, embeddings, spatial Census data, or reference atlas comparisons across organisms, tissues, diseases, assays, and cell types. For analyzing your own local single-cell data use scanpy, anndata, or scvi-tools.- **[deepTools](../skills/deeptools/SKILL.md)** - NGS analysis toolkit. BAM to bigWig conversion, QC (correlation, PCA, fingerprints), heatmaps/profiles (TSS, peaks), for ChIP-seq, RNA-seq, ATAC-seq visualization.- **[FlowIO](../skills/flowio/SKILL.md)** - Read, inspect, and write Flow Cytometry Standard (FCS) 2.0, 3.0, and 3.1 files with FlowIO. Use for low-level FCS metadata and channel inspection, NumPy event extraction, multi-dataset files, table export, and FCS 3.1 creation; use FlowKit for compensation, cytometry transforms, gating, or FlowJo workspaces.+- **[FlowKit](../skills/flowkit/SKILL.md)** - Analyzes flow cytometry data with FlowKit, including spillover compensation, logicle and biexponential transforms, hierarchical gating, GatingML strategies, and supported FlowJo 10 workspaces. Use for reproducible gate counts, population percentages, gated fluorescence summaries, or reproducing a FlowJo analysis in Python. For FCS metadata inspection or file-format repair alone, use FlowIO.- **[gget](../skills/gget/SKILL.md)** - Fast CLI/Python queries to 20+ bioinformatics databases. Use for quick lookups: gene info, BLAST/BLAT, viral sequence downloads, AlphaFold structures, enrichment analysis, OpenTargets, COSMIC, CELLxGENE, and 8cube mouse specificity/expression data. Best for interactive exploration and simple queries. For batch processing or advanced BLAST use biopython; for multi-database Python workflows use bioservices.- **[Genomic Coordinates](../skills/genomic-coordinates/SKILL.md)** - Convert genomic intervals between coordinate conventions, normalise and compare variant representations, and detect assembly or contig-naming mismatches before they corrupt an analysis. Use whenever coordinates cross a format, tool, or assembly boundary - converting between BED, GFF/GTF, VCF, SAM/BAM, WIG, PSL, genePred, Picard interval_list, or region strings; reconciling 0-based half-open with 1-based inclusive; left-aligning or trimming indels; checking whether two variant records describe the same change; mapping genomic to transcript, CDS, or protein positions; auditing a BED/GTF/VCF for convention violations; or diagnosing GRCh37 vs hg19 vs GRCh38 vs T2T, chr-prefix, and liftover problems. Triggers include "off by one", "0-based", "1-based", "half-open", "coordinate system", "left-align", "normalize variant", "bcftools norm", "chr prefix", "wrong genome build", "liftover", "REF mismatch", and "HGVS".- **[Genomic Intelligence](../skills/genomic-intelligence/SKILL.md)** - Predict regulatory features, gene structure, and expression directly from DNA sequence using Genomic Intelligence's hosted transformer DNA language models — no local GPU or model weights. Six tasks over a REST API and a hosted MCP server (keyless public demo): promoter regions, splice donor/acceptor sites, enhancer activity, chromatin state, sequence-to-expression (log TPM), and de-novo gene annotation, plus a composite find-genes-then-predict-expression workflow. Use when the user has a gene symbol, a genomic region, or a DNA/FASTA sequence and wants any of these predictions, mentions Genomic Intelligence, genomicintelligence.ai, api.genomicintelligence.ai, or mcp.genomicintelligence.ai.diff --git a/skills/flowkit/SKILL.md b/skills/flowkit/SKILL.mdnew file mode 100644index 00000000..9cd842b4--- /dev/null+++ b/skills/flowkit/SKILL.md@@ -0,0 +1,175 @@+---+name: flowkit+description: Analyzes flow cytometry data with FlowKit, including spillover compensation, logicle and biexponential transforms, hierarchical gating, GatingML strategies, and supported FlowJo 10 workspaces. Use for reproducible gate counts, population percentages, gated fluorescence summaries, or reproducing a FlowJo analysis in Python. For FCS metadata inspection or file-format repair alone, use FlowIO.+license: MIT+compatibility: Requires Python 3.13 with flowkit==1.3.2 for the tested environment. Dependencies include FlowIO, FlowUtils, NumPy, pandas, SciPy, lxml, and Bokeh. Installation needs network access; analysis uses local FCS/XML/WSP files without credentials. FlowUtils needs a C compiler if a compatible wheel is unavailable.+metadata:+ version: "1.0"+ skill-author: K-Dense Inc.+ last-reviewed: "2026-09-30"+---++# FlowKit++## When to use++Use FlowKit to apply or build cytometry gating strategies, analyze batches of+FCS samples, or reproduce supported FlowJo workspace analyses. It supports+GatingML 2.0 and a **subset of FlowJo 10 features**. Import success alone does+not establish agreement with FlowJo.++The examples and bundled helper target **FlowKit 1.3.2 on Python 3.13**.+Upstream supports additional Python versions; those were not exercised here.+The helper and examples were tested on synthetic FCS data, including a public+FlowJo 10.6.1 synthetic workspace fixture. They are not biological validation.++## Install++Use a separate environment; FlowKit 1.3.2 requires NumPy >2 and pandas <3:++```bash+uv venv --python 3.13 .venv-flowkit+uv pip install --python .venv-flowkit/bin/python "flowkit==1.3.2"+.venv-flowkit/bin/python -c "import flowkit; print(flowkit.__version__)"+```++The scientific package is BSD-3-Clause licensed; this skill is MIT licensed.++## Workflow++1. **Identify the analysis definition.** Use `Session` for a programmatic or+ GatingML strategy; use `Workspace` for FlowJo sample-specific gates,+ compensation, and transforms. Request the actual strategy or controls when+ biological thresholds have not been supplied.+2. **Inspect samples and channel identities.** Match detector/PnN labels to+ compensation matrices and gate dimensions; PnS marker names may be empty or+ repeated. Verify sample IDs: the default is FCS `$FIL`, which can differ+ from the current filename. Reject ID collisions before loading a batch.+3. **Establish the coordinate system.** Determine whether the supplied events+ are already compensated. Apply compensation before nonlinear transforms;+ match gate thresholds to the same transformed or untransformed coordinates.+ See [compensation and gating](references/compensation-and-gating.md).+4. **Check the hierarchy.** Preserve parent gates and full gate paths, including+ `root`. For a study, review acquisition/time stability, debris exclusion,+ singlets, viability, and phenotype gates as appropriate to its panel. Use+ single-stain controls for compensation and suitable negative/FMO controls+ for positivity; demonstration thresholds are not transferable biology.+5. **Analyze and inspect.** Run on all events, then check gate overlays and+ sample-level QC. A plot's subsample is not the population denominator.+ Review warnings and compare representative imported results to FlowJo.+6. **Export counts with denominators and provenance.** Keep gate paths,+ sample IDs, total event counts, input hashes, package versions, and the+ analysis definition. Keep biological replicates identifiable; events from+ one specimen are not independent experimental replicates.++## Apply an existing strategy++Set `FLOWKIT_SKILL_DIR` to this skill's installed directory. From the repository+root it is `skills/flowkit`. Paths below represent the user's local inputs.++```bash+FLOWKIT_SKILL_DIR="skills/flowkit"+uv run --no-project --python 3.13 --with "flowkit==1.3.2" \+ python "$FLOWKIT_SKILL_DIR/scripts/analyze_gates.py" \+ --gatingml gates.xml --fcs sample.fcs --output-dir results-gatingml+```++For a FlowJo workspace, supply **every FCS file in the selected group**:++```bash+uv run --no-project --python 3.13 --with "flowkit==1.3.2" \+ python "$FLOWKIT_SKILL_DIR/scripts/analyze_gates.py" \+ --workspace study.wsp --group "Study" \+ --fcs sample-a.fcs sample-b.fcs --output-dir results-workspace+```++The helper writes `gate_report.csv` and `provenance.json` to a new directory.+It rejects duplicate sample IDs, missing/extra workspace-group samples,+zero-event samples, and strategies without gates. It uses explicit input files,+does not follow paths embedded in the workspace, and runs without+multiprocessing or transformed-event caching. It still loads each sample into+memory; use manageable batches via the Python API for large studies.++`--filename-as-id` deliberately switches from `$FIL` to file basenames. Use it+only when those names match the analysis definition. See+[workspace analysis](references/workspaces-and-results.md) for partial-group+analysis, result interpretation, and fluorescence summaries.++## Build a strategy in Python++This runnable example uses `sample.fcs` with `FSC-A`, `FL1-A`, and `FL2-A`.+The matrix, thresholds, and transform parameters are **synthetic teaching+values**. Replace them with the study's validated settings.++```python+import flowkit as fk+import numpy as np++sample = fk.Sample("sample.fcs")+strategy = fk.GatingStrategy()+strategy.add_comp_matrix(+ "spill", fk.Matrix(+ np.array([[1.0, 0.1], [0.2, 1.0]]), ["FL1-A", "FL2-A"],+ fluorochromes=["FITC", "PE"],+ )+)+logicle = fk.transforms.LogicleTransform(+ param_t=262144, param_w=0.5, param_m=4.5, param_a=0+)+strategy.add_transform("logicle", logicle)+strategy.add_gate(+ fk.gates.RectangleGate("Cells", [+ fk.Dimension("FSC-A", range_min=50, range_max=300)+ ]),+ gate_path=("root",),+)+thresholds = logicle.apply(np.array([50.0, 600.0]))+strategy.add_gate(+ fk.gates.RectangleGate("Positive", [+ fk.Dimension(+ "FL1-A", compensation_ref="spill", transformation_ref="logicle",+ range_min=float(thresholds[0]), range_max=float(thresholds[1]),+ )+ ]),+ gate_path=("root", "Cells"),+)+session = fk.Session(gating_strategy=strategy, fcs_samples=[sample])+session.analyze_samples(use_mp=False)+report = session.get_analysis_report()+print(report[["sample_id", "gate_path", "gate_name", "count",+ "absolute_percent", "relative_percent"]])+with open("gates.xml", "xb") as handle:+ session.export_gml(handle)+```++GatingML exports a template by default. When custom per-sample gates exist,+use `session.export_gml(handle, sample_id=sample.id)` for that sample's strategy.+A single template export does not preserve every sample-specific override.++## Interpretation checks++- `count` is the number of events passing the gate and its ancestors.+- `absolute_percent` is percent of all sample events; `relative_percent` is+ percent of the immediate parent. These are percentages, not fractions.+- Gate names can repeat under different parents. Use `(gate_name, gate_path)`+ as the identifier, not the name alone. The helper serializes paths as JSON+ arrays inside CSV cells to preserve names containing separators.+- A zero-event parent makes a child percentage biologically undefined;+ FlowKit may report zero. Report the denominator and mark that comparison+ unavailable rather than interpreting it as absence of a phenotype.+- Compensated negative fluorescence is legitimate. Do not clip it to zero or+ discard those events merely to permit a logarithmic transform.+- Define whether “MFI” means mean or median and name the event source.+ A transformed display value is not an intensity on the original scale.++## References++- [Compensation and gating](references/compensation-and-gating.md): event+ sources, detector order, transform semantics, gate paths, and plotting.+- [Workspaces and results](references/workspaces-and-results.md): sample+ matching, missing FCS files, FlowJo limits, and gated fluorescence summaries.+- [FlowKit API](https://flowkit.readthedocs.io/en/latest/api.html) and+ [versioned source](https://github.com/whitews/FlowKit/tree/1.3.2): consult+ signatures when moving beyond the tested release.+- [FlowKit publication](https://doi.org/10.3389/fimmu.2021.768541): cite the+ software and version in scientific methods when used for analysis.diff --git a/skills/flowkit/references/compensation-and-gating.md b/skills/flowkit/references/compensation-and-gating.mdnew file mode 100644index 00000000..815ee6b3--- /dev/null+++ b/skills/flowkit/references/compensation-and-gating.md@@ -0,0 +1,89 @@+# Compensation, transforms, and gates++## Event sources are different representations++FlowKit `Sample` uses FlowIO preprocessing by default: gain, logarithmic FCS+encoding, and time scaling are applied when loading. Consequently,+`sample.get_events(source="raw")` is **before compensation/transforms**, not+necessarily the values encoded in the FCS DATA segment. Reserve+`preprocess=False` for explicitly investigating encoding; it changes the+coordinate system and may make an existing strategy inappropriate.++`source="comp"` requires compensation to have been applied to the Sample;+`source="xform"` requires transformation. The default event source is `xform`,+so specify the source instead of relying on it. Gating a Sample through a+`GatingStrategy` processes its own event arrays; do not assume that it also+populates the Sample's `comp` or `xform` arrays.++## Compensation++Construct `fk.Matrix(spill_data_or_file, detectors, fluorochromes=None)` using+detector/PnN names in the matrix's order. Inputs can be a NumPy matrix, an FCS+spillover keyword string, or supported spillover text. Marker/PnS labels are+annotations and do not replace detector identity. Confirm that all detectors+are present, the matrix is finite and nonsingular, and the fluorescence panel+matches the controls. An identity matrix means no cross-channel spillover; it+is not a fallback for a missing matrix.++For GatingML export in 1.3.2, supply nonempty `fluorochromes` labels as well.+Omitting them leaves empty labels in the exported XML, which fails GatingML+schema validation on re-import even though in-memory gating works. Use the+panel's actual fluorochrome names in matrix order and verify the round-trip.++For a programmatic strategy, register it with+`strategy.add_comp_matrix("spill", matrix)` and set+`compensation_ref="spill"` on the relevant `Dimension`s. The special reference+`"FCS"` uses spillover metadata from each sample; check that every sample has+the intended metadata before using it. The default dimension reference is+`"uncompensated"`. Merely registering a matrix does not apply it to all gates.++For direct fluorescence summaries, use `sample.apply_compensation(matrix)`+and explicitly read `source="comp"`. This starts from that Sample's raw event+array. It cannot detect that the FCS itself was exported already compensated;+verify export provenance to avoid compensating such data a second time.++Classical spillover compensation is not a general replacement for spectral+unmixing. Confirm how spectral-instrument data were unmixed and exported.++## Transform and threshold coordinates++`LogicleTransform(param_t, param_w, param_m, param_a)` handles signed+fluorescence. Match parameters to the acquisition and analysis definition;+the values in the quick start are illustrative. FlowJo's+`WSPBiexTransform` is a distinct transform; substituting logicle or an+arbitrary arcsinh cofactor can change imported gate membership.++Register transforms with `strategy.add_transform(id, transform)` and reference+that ID on each dimension needing it. Gate vertices/bounds must be in the+coordinates of that dimension. If a scientifically justified threshold is on+the untransformed compensated scale, transform that threshold with the same+object used for the data, as the quick start does. Do not transform imported+workspace gates again; the workspace parser handles their coordinates.++## Hierarchy and visual checks++Top-level gates have path `("root",)`. A child of `Cells` has path+`("root", "Cells")`; the gate's own name is excluded from its path. Rectangle+lower bounds are inclusive and upper bounds exclusive. Missing bounds are+unbounded. Polygon boundaries and events near thresholds require particular+care when comparing software implementations.++Get Boolean event masks using+`session.get_gate_membership(sample_id, gate_name, gate_path=path)`. Masks+retain the original sample's event order and cover the entire sample. Their+sum should match the reported count, and child masks should be subsets of+their parents. Boolean/overlapping gates need not sum to the parent count;+mutually exclusive quadrants should be checked as a partition when applicable.++`session.plot_gate(sample_id, gate_name, gate_path=path)` returns a Bokeh plot.+Save it with `bokeh.plotting.save`, using `bokeh.resources.INLINE` when the+HTML must work offline. Inspect events and gate boundaries in matching+coordinates; plotting uses subsampling for large samples, while analysis+uses full event arrays. Plotting is not evidence that controls support a gate.++## Primary sources++- [Sample API](https://flowkit.readthedocs.io/en/latest/sample.html)+- [Matrix API](https://flowkit.readthedocs.io/en/latest/matrix.html)+- [Dimension API](https://flowkit.readthedocs.io/en/latest/dimension.html)+- [GatingStrategy API](https://flowkit.readthedocs.io/en/latest/gating_strategy.html)diff --git a/skills/flowkit/references/workspaces-and-results.md b/skills/flowkit/references/workspaces-and-results.mdnew file mode 100644index 00000000..5262c44f--- /dev/null+++ b/skills/flowkit/references/workspaces-and-results.md@@ -0,0 +1,90 @@+# Workspaces and result interpretation++## Match samples before interpreting results++Use explicit FCS files and inspect the workspace's sample groups. Retaining+missing-file metadata is essential: otherwise missing samples may be removed+from group membership during construction and a partial analysis can look+complete. `load_missing_file_data=True` retains workspace metadata for missing+FCS files; it does not supply those files' events.++The following example is exercised with the repository's synthetic FlowJo+fixture. Replace paths, group name, and sample identity for real work:++```python+import flowkit as fk++workspace = fk.Workspace(+ "study.wsp",+ fcs_samples=["data_set_simple_line_100.fcs"],+ load_missing_file_data=True,+ find_fcs_files_from_wsp=False,+)+print(workspace.get_sample_groups())+group = "my_group"+expected = set(workspace.get_sample_ids(group_name=group, loaded_only=False))+loaded = set(workspace.get_sample_ids(group_name=group, loaded_only=True))+if not expected or expected != loaded:+ raise ValueError(f"Empty group or missing FCS samples: {sorted(expected - loaded)}")+workspace.analyze_samples(group_name=group, use_mp=False)+print(workspace.get_analysis_report(group_name=group))+```++FCS `$FIL`, filesystem basename, and workspace sample name can disagree after+renaming/export. Inspect these identities rather than matching by position.+`filename_as_id=True` is useful only when current basenames match the workspace.+When an explicit, reviewed mapping is necessary, construct+`fk.Sample(path, sample_id=workspace_id, use_flowjo_labels=True)` objects and+pass those to `Workspace`. Check uniqueness before building the list.++For an intentionally partial group, use `analyze_samples(sample_id=...)` for+the explicitly selected IDs and report included and missing IDs. The bundled+CLI deliberately requires the complete named group.++## FlowJo compatibility++FlowKit supports a subset of FlowJo 10: documented transformations and+polygon, rectangle, ellipse, quadrant, and Boolean gates. Plugins, derived+parameters, specialized models, or other unsupported workspace features may+not reproduce. Review parser warnings and imported gate inventories. Compare+counts, percentages, and overlays against the original FlowJo export on+representative samples, including sample-specific overrides and rare gates.+Record both software versions and any mismatch; importing without an+exception is insufficient.++Prefer the original workspace for reproduction. A single GatingML template+does not encode all custom sample gates. FlowKit's WSP exporter is not a+guaranteed round-trip: in the tested 1.3.2 environment, re-importing a synthetic+compensated `Session.export_wsp` result failed to resolve a `Comp-FL1-A`+channel. Native FlowJo fixture import was tested separately. Validate any+conversion independently before relying on it.++## Fluorescence summaries++Choose mean or median explicitly, retain sample and gate path, and report the+number of events. For a programmatic `Session`, obtain the gate mask, then+apply the intended matrix to the Sample and summarize the desired detector+from `source="comp"`. This keeps compensation separate from display transforms.++For a `Workspace`, `get_gate_events(sample_id, gate_name, gate_path=path,+source="comp")` returns gated, compensated events. Its default `source=None`+uses the workspace's compensation **and transforms**, so it is unsuitable for+an untransformed intensity summary without an explicit source choice.++There is an API asymmetry: `Session.get_gate_events(...)` defaults to raw+events unless `matrix` and/or `transform` are supplied. It does not+automatically choose the preprocessing of the gate's dimensions. Therefore,+identical-looking calls on Session and Workspace can summarize different+numbers. Do not compare them until their coordinate systems agree.++Empty gates have no defined mean/median; return missing values with count zero.+Negative compensated values make geometric means inappropriate without a+separately justified method. Across samples, account for panel, instrument,+batch, controls, and calibration before interpreting intensity differences.++## Primary sources++- [Workspace API](https://flowkit.readthedocs.io/en/latest/workspace.html)+- [Session API](https://flowkit.readthedocs.io/en/latest/session.html)+- [GatingResults API](https://flowkit.readthedocs.io/en/latest/gating_results.html)+- [Upstream feature scope](https://github.com/whitews/FlowKit)diff --git a/skills/flowkit/scripts/analyze_gates.py b/skills/flowkit/scripts/analyze_gates.pynew file mode 100644index 00000000..84ee8f7d--- /dev/null+++ b/skills/flowkit/scripts/analyze_gates.py@@ -0,0 +1,156 @@+#!/usr/bin/env python3+"""Apply a supplied GatingML strategy or FlowJo workspace to explicit FCS files."""++from __future__ import annotations++import argparse+import hashlib+import json+from importlib.metadata import version+from pathlib import Path+++def file_record(path: Path) -> dict:+ with path.open("rb") as handle:+ digest = hashlib.file_digest(handle, "sha256").hexdigest()+ return {"path": str(path.resolve()), "sha256": digest}+++def analyze(+ *,+ fcs_paths: list[Path],+ definition: Path,+ mode: str,+ output_dir: Path,+ group: str | None = None,+ filename_as_id: bool = False,+) -> dict:+ """Analyze all supplied samples; reject incomplete workspace groups and ID collisions."""+ import flowkit as fk++ if mode not in {"gatingml", "workspace"}:+ raise ValueError("mode must be gatingml or workspace")+ if (mode == "workspace") != (group is not None):+ raise ValueError("A group is required for workspace mode and only valid there")+ if output_dir.exists():+ raise FileExistsError(f"Output directory already exists: {output_dir}")+ if not fcs_paths:+ raise ValueError("Supply at least one FCS file")+ for path in [definition, *fcs_paths]:+ if not path.is_file():+ raise ValueError(f"Expected a local file: {path}")++ # Hash the actual inputs, not paths or metadata supplied by a workspace.+ definition_record = file_record(definition)+ samples = []+ records = []+ seen_ids = set()+ for path in fcs_paths:+ record = file_record(path)+ sample = fk.Sample(+ path,+ filename_as_id=filename_as_id,+ use_flowjo_labels=(mode == "workspace"),+ )+ if sample.id in seen_ids:+ raise ValueError(f"Duplicate sample ID: {sample.id!r}; check FCS $FIL values")+ if sample.event_count == 0:+ raise ValueError(f"Sample has no events: {sample.id!r}")+ seen_ids.add(sample.id)+ samples.append(sample)+ record.update(sample_id=sample.id, event_count=sample.event_count)+ records.append(record)++ if mode == "gatingml":+ strategy = fk.parse_gating_xml(str(definition))+ if not strategy.get_gate_ids():+ raise ValueError("GatingML strategy has no gates")+ analysis = fk.Session(strategy, fcs_samples=samples)+ analysis.analyze_samples(use_mp=False, cache_events=False)+ report = analysis.get_analysis_report()+ else:+ analysis = fk.Workspace(+ str(definition),+ fcs_samples=samples,+ # Retain missing-sample gate metadata so completeness can be checked.+ load_missing_file_data=True,+ find_fcs_files_from_wsp=False,+ )+ expected = set(analysis.get_sample_ids(group_name=group, loaded_only=False))+ if not expected:+ raise ValueError(f"Workspace group is empty: {group!r}")+ if expected != seen_ids:+ raise ValueError(+ "FCS inputs must exactly match the selected workspace group; "+ f"missing IDs={sorted(expected - seen_ids)}, "+ f"unexpected IDs={sorted(seen_ids - expected)}"+ )+ for sample_id in sorted(expected):+ if not analysis.get_gate_ids(sample_id):+ raise ValueError(f"Workspace sample has no gates: {sample_id!r}")+ analysis.analyze_samples(group_name=group, use_mp=False, cache_events=False)+ report = analysis.get_analysis_report(group_name=group)++ if report.empty or set(report["sample_id"]) != seen_ids:+ raise ValueError("Analysis did not produce gate results for every input sample")+ # A JSON array preserves a gate path even when gate names contain slashes.+ report = report.copy()+ report["gate_path"] = report["gate_path"].map(lambda path: json.dumps(list(path)))+ manifest = {+ "mode": mode,+ "group": group,+ "filename_as_id": filename_as_id,+ "definition": definition_record,+ "samples": records,+ "versions": {+ package: version(package)+ for package in ("flowkit", "flowio", "flowutils", "numpy", "pandas")+ },+ "report": "gate_report.csv",+ "percentages": {+ "absolute_percent": "100 * gate count / total sample events",+ "relative_percent": "100 * gate count / parent population count",+ },+ "event_processing": "FlowKit FCS preprocessing; compensation and transforms from gate definitions",+ "use_mp": False,+ }+ output_dir.mkdir(parents=True, exist_ok=False)+ report.to_csv(output_dir / "gate_report.csv", index=False)+ (output_dir / "provenance.json").write_text(+ json.dumps(manifest, indent=2, allow_nan=False) + "\n", encoding="utf-8"+ )+ return manifest+++def main(argv: list[str] | None = None) -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ definitions = parser.add_mutually_exclusive_group(required=True)+ definitions.add_argument("--gatingml", type=Path, help="GatingML 2.0 XML strategy")+ definitions.add_argument("--workspace", type=Path, help="FlowJo 10 .wsp file")+ parser.add_argument("--fcs", nargs="+", type=Path, required=True, help="Explicit local FCS files")+ parser.add_argument("--group", help="Workspace group; all its FCS files must be supplied")+ parser.add_argument("--output-dir", type=Path, required=True, help="New results directory")+ parser.add_argument(+ "--filename-as-id", action="store_true",+ help="Use current file basenames instead of FCS $FIL metadata for sample IDs",+ )+ args = parser.parse_args(argv)+ if bool(args.workspace) != (args.group is not None):+ parser.error("--workspace requires --group; --group is not valid with --gatingml")+ try:+ manifest = analyze(+ fcs_paths=args.fcs,+ definition=args.workspace or args.gatingml,+ mode="workspace" if args.workspace else "gatingml",+ output_dir=args.output_dir,+ group=args.group,+ filename_as_id=args.filename_as_id,+ )+ except (ValueError, KeyError, OSError) as exc:+ parser.exit(2, f"Analysis failed: {exc}\n")+ print(f"Analyzed {len(manifest['samples'])} samples: {args.output_dir / 'gate_report.csv'}")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/tests/flowkit/fixtures/LICENSE b/tests/flowkit/fixtures/LICENSEnew file mode 100644index 00000000..59f54074--- /dev/null+++ b/tests/flowkit/fixtures/LICENSE@@ -0,0 +1,29 @@+BSD 3-Clause License++Copyright (c) 2018, Scott White+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/flowkit/fixtures/README.md b/tests/flowkit/fixtures/README.mdnew file mode 100644index 00000000..7929a986--- /dev/null+++ b/tests/flowkit/fixtures/README.md@@ -0,0 +1,14 @@+# Synthetic FlowJo import fixture++`data_set_simple_line_100.fcs` and `simple_poly_and_rect_v2_poly50.wsp`+come from [FlowKit's synthetic line example](https://github.com/whitews/FlowKit/tree/f2159043b6a56e527d4baacf97490caf8354618e/data/simple_line_example).+The upstream commit is `f2159043b6a56e527d4baacf97490caf8354618e`.+Its BSD-3-Clause license is preserved in `LICENSE`.++The FCS contains 100 generated points, not biological samples. The workspace+was saved by FlowJo 10.6.1 and defines a polygon containing 50 points and a+rectangle containing none. The only change to the upstream WSP is replacement+of its original absolute `file:/V:/flowkit/flowjo_workspace_parsing/simple_line_example/`+URI prefix with `file:`. Tests supply FCS paths explicitly and do not follow+workspace URIs. These files validate import and transform semantics, not+compatibility with all FlowJo features or biological gating accuracy.diff --git a/tests/flowkit/fixtures/data_set_simple_line_100.fcs b/tests/flowkit/fixtures/data_set_simple_line_100.fcsnew file mode 100644index 00000000..aaacf3aaBinary files /dev/null and b/tests/flowkit/fixtures/data_set_simple_line_100.fcs differdiff --git a/tests/flowkit/fixtures/simple_poly_and_rect_v2_poly50.wsp b/tests/flowkit/fixtures/simple_poly_and_rect_v2_poly50.wspnew file mode 100644index 00000000..a12c065b--- /dev/null+++ b/tests/flowkit/fixtures/simple_poly_and_rect_v2_poly50.wsp@@ -0,0 +1,321 @@+<?xml version="1.0" encoding="UTF-8"?>+ <Workspace version="20.0" modDate="Wed Feb 17 00:35:55 EST 2021" clientTimestamp="1613540155792" flowJoVersion="10.7.1" drawRowBorders="1" drawColumnBorders="1" hideCompNodes="1" curGroup="All Samples" groupPaneHeight="80" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:gating="http://www.isac-net.org/std/Gating-ML/v2.0/gating" xmlns:transforms="http://www.isac-net.org/std/Gating-ML/v2.0/transformations" xmlns:data-type="http://www.isac-net.org/std/Gating-ML/v2.0/datatypes" xsi:schemaLocation="http://www.isac-net.org/std/Gating-ML/v2.0/gating http://www.isac-net.org/std/Gating-ML/v2.0/gating/Gating-ML.v2.0.xsd http://www.isac-net.org/std/Gating-ML/v2.0/transformations http://www.isac-net.org/std/Gating-ML/v2.0/gating/Transformations.v2.0.xsd http://www.isac-net.org/std/Gating-ML/v2.0/datatypes http://www.isac-net.org/std/Gating-ML/v2.0/gating/DataTypes.v2.0.xsd " nonAutoSaveFileName="file:/V:/flowkit/flowjo_export_testing/wsp_export_from_flowkit/simple_poly_and_rect_v2_poly50.wsp" >+ <WindowPosition x="200" y="45" width="792" height="720" displayed="1" panelState="" />+ <TextTraits font="SansSerif" size="14" name="" style="plain" color="#000000" background="#00ffffff" just="left" />+ <Columns>+ <TColumn width="364" >+ <Property key="fj.appnode.prop.name" />+ </TColumn>+ <TColumn width="204" >+ <Property key="fj.appnode.prop.statistic" />+ </TColumn>+ <TColumn width="204" >+ <Property key="fj.appnode.prop.ncells" />+ </TColumn>+ </Columns>+ <Matrices/>+ <Cytometers>+ <Cytometer name="GENERIC" cyt="" useFCS3="1" extraNegs="0" widthBasis="-10" linMin="0" logMin="1" linMax="10000" logMax="10000" linearRescale="1" logRescale="1" linFromKW="1" logFromKW="1" useGain="0" useTransform="0" transformType="LOG" manufacturer="" serialnumber="" homepage="workspaces-and-samples/flowjo-and-your-cytometer/ws-instrumentation/" icon="generic.png" >+ <LinParams>+ <Param>time</Param>+ </LinParams>+ <LogParams/>+ <FilterParams/>+ <TransformStore/>+ </Cytometer>+ </Cytometers>+ <Groups>+ <GroupNode name="All Samples" annotation="" owningGroup="All Samples" expanded="1" sortPriority="10" count="-1" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="" label="" auto="auto" />+ <Axis dimension="y" name="" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ </GraphEnvironment>+ </Graph>+ <Group name="All Samples" live="1" role="ws.group.dlog.test" key="" synchronized="0" foreground="#000000" fontStyle="bold" >+ <Criteria/>+ <SampleRefs>+ <SampleRef sampleID="1" />+ </SampleRefs>+ <Keywords/>+ </Group>+ </GroupNode>+ <GroupNode name="Compensation" annotation="" owningGroup="Compensation" expanded="1" sortPriority="10" count="-1" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="" label="" auto="auto" />+ <Axis dimension="y" name="" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ </GraphEnvironment>+ </Graph>+ <Group name="Compensation" live="1" role="ws.group.dlog.compensation" key="" synchronized="0" foreground="#bc1900" fontStyle="bold" >+ <Criteria>+ <Criterion connector="And" keyword="$FIL" function="Contains" value="unstained" />+ <Criterion connector="Or" keyword="$FIL" function="Contains" value="comp" />+ </Criteria>+ <Keywords/>+ </Group>+ </GroupNode>+ <GroupNode name="my_group" annotation="" owningGroup="my_group" expanded="1" sortPriority="10" count="-1" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="" label="" auto="auto" />+ <Axis dimension="y" name="" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ <WindowPosition x="0" y="0" width="0" height="0" displayed="0" panelState="" />+ </GraphEnvironment>+ </Graph>+ <Subpopulations>+ <Population name="poly1" annotation="" owningGroup="my_group" expanded="1" sortPriority="10" count="0" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" heatMapStatParameter="channel_A" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="channel_A" label="" auto="auto" />+ <Axis dimension="y" name="channel_B" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ <WindowPosition x="620" y="0" width="880" height="939" displayed="1" panelState="---" />+ </GraphEnvironment>+ </Graph>+ <Gate gating:id="ID54754627" >+ <gating:PolygonGate eventsInside="1" annoOffsetX="190" annoOffsetY="-26" tint="#000000" isTinted="0" lineWeight="Normal" userDefined="1" quadId="-1" gateResolution="256" >+ <gating:dimension>+ <data-type:fcs-dimension data-type:name="channel_A" />+ </gating:dimension>+ <gating:dimension>+ <data-type:fcs-dimension data-type:name="channel_B" />+ </gating:dimension>+ <gating:vertex>+ <gating:coordinate data-type:value="59483.5164835165" />+ <gating:coordinate data-type:value="106300.1745200698" />+ </gating:vertex>+ <gating:vertex>+ <gating:coordinate data-type:value="59500" />+ <gating:coordinate data-type:value="130638.7434554974" />+ </gating:vertex>+ <gating:vertex>+ <gating:coordinate data-type:value="136675.8241758242" />+ <gating:coordinate data-type:value="130638.7434554974" />+ </gating:vertex>+ <gating:vertex>+ <gating:coordinate data-type:value="136659.3406593407" />+ <gating:coordinate data-type:value="106366.4921465969" />+ </gating:vertex>+ </gating:PolygonGate>+ </Gate>+ </Population>+ <Population name="rect1" annotation="" owningGroup="my_group" expanded="1" sortPriority="10" count="0" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" heatMapStatParameter="channel_A" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="channel_A" label="" auto="auto" />+ <Axis dimension="y" name="channel_B" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ <WindowPosition x="620" y="0" width="880" height="939" displayed="1" panelState="---" />+ </GraphEnvironment>+ </Graph>+ <Gate gating:id="ID1134572704" >+ <gating:RectangleGate eventsInside="1" annoOffsetX="6" annoOffsetY="1" tint="#000000" isTinted="0" lineWeight="Normal" userDefined="1" percentX="0" percentY="0" >+ <gating:dimension gating:min="59478.02197802198" gating:max="136675.82417582418" >+ <data-type:fcs-dimension data-type:name="channel_A" />+ </gating:dimension>+ <gating:dimension gating:min="106300.1745200698" gating:max="130638.74345549737" >+ <data-type:fcs-dimension data-type:name="channel_B" />+ </gating:dimension>+ </gating:RectangleGate>+ </Gate>+ </Population>+ </Subpopulations>+ <Group name="my_group" live="1" role="ws.group.dlog.undefined" key="" synchronized="0" foreground="#0000d0" fontStyle="plain" >+ <Criteria refGroupFunction="only" refGroupName="my_group" />+ <ManuallyIncludedSamples>+ <SampleRef sampleID="1" />+ </ManuallyIncludedSamples>+ <SampleRefs>+ <SampleRef sampleID="1" />+ </SampleRefs>+ <Keywords/>+ </Group>+ </GroupNode>+ </Groups>+ <SampleList>+ <Sample>+ <DataSet uri="file:data_set_simple_line_100.fcs" sampleID="1" />+ <Transformations>+ <transforms:linear transforms:minRange="50000" transforms:maxRange="150000" gain="1" >+ <data-type:parameter data-type:name="channel_A" />+ </transforms:linear>+ <transforms:linear transforms:minRange="0" transforms:maxRange="255000" gain="1" >+ <data-type:parameter data-type:name="channel_B" />+ </transforms:linear>+ </Transformations>+ <Keywords>+ <Keyword name="FJ_FCS_VERSION" value="3.1" />+ <Keyword name="$BEGINANALYSIS" value="0" />+ <Keyword name="$BEGINDATA" value="497" />+ <Keyword name="$BEGINSTEXT" value="0" />+ <Keyword name="$BYTEORD" value="1,2,3,4" />+ <Keyword name="$DATATYPE" value="F" />+ <Keyword name="$ENDANALYSIS" value="0" />+ <Keyword name="$ENDDATA" value="1296" />+ <Keyword name="$ENDSTEXT" value="0" />+ <Keyword name="$MODE" value="L" />+ <Keyword name="$NEXTDATA" value="0" />+ <Keyword name="$PAR" value="2" />+ <Keyword name="$TOT" value="100" />+ <Keyword name="$P1B" value="32" />+ <Keyword name="$P1E" value="0,0" />+ <Keyword name="$P1R" value="262144" />+ <Keyword name="$P1N" value="channel_A" />+ <Keyword name="$P2B" value="32" />+ <Keyword name="$P2E" value="0,0" />+ <Keyword name="$P2R" value="262144" />+ <Keyword name="$P2N" value="channel_B" />+ <Keyword name="$P1S" value="" />+ <Keyword name="$P2S" value="" />+ </Keywords>+ <SampleNode name="data_set_simple_line_100.fcs" annotation="" owningGroup="" expanded="1" sortPriority="10" count="100" sampleID="1" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" heatMapStatParameter="channel_A" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="channel_A" label="" auto="auto" />+ <Axis dimension="y" name="channel_B" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ <WindowPosition x="830" y="12" width="880" height="925" displayed="1" panelState="-+-" />+ </GraphEnvironment>+ </Graph>+ <Subpopulations>+ <Population name="poly1" annotation="" owningGroup="" expanded="1" sortPriority="10" count="0" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" heatMapStatParameter="channel_A" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="channel_A" label="" auto="auto" />+ <Axis dimension="y" name="channel_B" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ <WindowPosition x="620" y="0" width="880" height="939" displayed="0" panelState="---" />+ </GraphEnvironment>+ </Graph>+ <Gate gating:id="ID1571031032" >+ <gating:PolygonGate eventsInside="1" annoOffsetX="190" annoOffsetY="-26" tint="#000000" isTinted="0" lineWeight="Normal" userDefined="1" quadId="-1" gateResolution="256" gating:id="ID1571031032" >+ <gating:dimension>+ <data-type:fcs-dimension data-type:name="channel_A" />+ </gating:dimension>+ <gating:dimension>+ <data-type:fcs-dimension data-type:name="channel_B" />+ </gating:dimension>+ <gating:vertex>+ <gating:coordinate data-type:value="59478.021978022" />+ <gating:coordinate data-type:value="106171.5399610137" />+ </gating:vertex>+ <gating:vertex>+ <gating:coordinate data-type:value="58928.5714285714" />+ <gating:coordinate data-type:value="131668.6159844054" />+ </gating:vertex>+ <gating:vertex>+ <gating:coordinate data-type:value="136675.8241758242" />+ <gating:coordinate data-type:value="130495.126705653" />+ </gating:vertex>+ <gating:vertex>+ <gating:coordinate data-type:value="136675.8241758242" />+ <gating:coordinate data-type:value="106230.0194931774" />+ </gating:vertex>+ </gating:PolygonGate>+ </Gate>+ </Population>+ <Population name="rect1" annotation="" owningGroup="" expanded="1" sortPriority="10" count="0" >+ <Graph smoothing="0" backColor="#ffffff" foreColor="#000000" heatMapStatParameter="channel_A" type="Pseudocolor" fast="1" >+ <Axis dimension="x" name="channel_A" label="" auto="auto" />+ <Axis dimension="y" name="channel_B" label="" auto="auto" />+ <GraphSettings level="5%" smoothingHighResolution="1" contourHighResolution="1" histogramSmoothingCount="0" graphResolution="256" showOutliers="0" drawLargeDots="0" dotsToDraw="0" tint="le.chartfill.tinted.40" lineWeight="le.lineweight.normal" lineStyle="le.linestyle.solid" />+ <GraphEnvironment showGrid="0" showAxes="tnlTNL" showGates="1" showFreqOnPlots="1" showGateNameOnPlots="1" showMedians="0" showUncomped="0" addEventParam="0" lastYAxisName="" >+ <TextTraits font="SansSerif" size="11" name="Labels" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="11" name="LayoutGates" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Numbers" style="plain" color="#000000" background="#00ffffff" just="left" />+ <TextTraits font="SansSerif" size="9" name="Legend" style="plain" color="#000000" background="#00ffffff" just="left" />+ <WindowPosition x="620" y="0" width="880" height="939" displayed="0" panelState="---" />+ </GraphEnvironment>+ </Graph>+ <Gate gating:id="ID613872335" >+ <gating:RectangleGate eventsInside="1" annoOffsetX="6" annoOffsetY="1" tint="#000000" isTinted="0" lineWeight="Normal" userDefined="1" percentX="0" percentY="0" gating:id="ID613872335" >+ <gating:dimension gating:min="63049.45054945055" gating:max="133104.3956043956" >+ <data-type:fcs-dimension data-type:name="channel_A" />+ </gating:dimension>+ <gating:dimension gating:min="107397.66081871346" gating:max="129561.40350877192" >+ <data-type:fcs-dimension data-type:name="channel_B" />+ </gating:dimension>+ </gating:RectangleGate>+ </Gate>+ </Population>+ </Subpopulations>+ </SampleNode>+ </Sample>+ </SampleList>+ <TableEditor title="FlowJo Tables: simple_poly_and_rect_v2_poly50.wsp" current="Table" >+ <Table name="Table" outputFile="file:/C:/Users/swhite/Documents/Table" color="#00ffffff" isBatch="0" quickclose="0" destination="toDisplay" outputFormat="fj.document.type.table" autoColumnName="" >+ <PrintLayout flipPattern0="0" rows="1" columns="1" padding="36" header="" footer="" headerActive="0" footerActive="0" scalingMode="fj.print.scale.none" scaling="1" orientation="1" width="612" height="792" imageableX="72" imageableY="72" imageableWidth="468" imageableHeight="648" />+ <PageSection sectionName="header" ><table width="100%"><tr><td align="left" valign="top">&NBSP&NBSP&NBSP&NBSP<IMG SRC="file:/C:/Program%20Files/FlowJo%2010.6.1/images/fj_icon.png"></IMG><br/>FlowJo, LLC</td><td align="right" valign="top">Page <PageNumber/></td></tr></table></PageSection>+ <PageSection sectionName="footer" ><table width="100%"><tr><td align="left" valign="bottom"><LongDate/></td><td align="right" valign="bottom"><Version/></td></tr></table></PageSection>+ <Iteration iterationType="SAMPLE" iterationValue="1" iterationKeyword="" discriminator="" panelSize="1" groupName="workspaceSelection" />+ </Table>+ </TableEditor>+ <LayoutEditor title="FlowJo Layouts: simple_poly_and_rect_v2_poly50.wsp" current="Layout" showGrid="0" showPageBreaks="0" showGuides="0" showDebugOutput="0" >+ <Layout name="Layout" outputFile="file:/C:/Users/swhite/Documents/Layout" color="#00ffffff" isBatch="0" showGrid="0" showRulers="1" showDebugOutput="0" showGuides="0" showPageBreaks="1" scale="1" >+ <PrintLayout flipPattern0="0" rows="1" columns="1" padding="36" header="" footer="" headerActive="0" footerActive="0" scalingMode="fj.print.scale.none" scaling="1" orientation="1" width="612" height="792" imageableX="72" imageableY="72" imageableWidth="468" imageableHeight="648" />+ <PageSection sectionName="header" ><table width="100%"><tr><td align="left" valign="top">&NBSP&NBSP&NBSP&NBSP<IMG SRC="file:/C:/Program%20Files/FlowJo%2010.6.1/images/fj_icon.png"></IMG><br/>FlowJo, LLC</td><td align="right" valign="top">Page <PageNumber/></td></tr></table></PageSection>+ <PageSection sectionName="footer" ><table width="100%"><tr><td align="left" valign="bottom"><LongDate/></td><td align="right" valign="bottom"><Version/></td></tr></table></PageSection>+ <Iteration iterationType="OFF" iterationValue="1" iterationKeyword="" discriminator="" panelSize="1" groupName="workspaceSelection" />+ <BatchSettings useCurrentGroup="1" length="3" name="" order="ACROSS" direction="COLUMNS" append="0" destination="toLayout" separatePages="0" launchApp="1" header="0" footer="0" commandLineBatch="0" />+ <FigList/>+ </Layout>+ <WindowPosition x="0" y="0" width="900" height="600" />+ </LayoutEditor>+ <Scripts>+ <Script lang="text/javascript" name="New Script " />+ </Scripts>+ <Experiment>+ <PlateModel name="Plate" color="#00ffffff" rows="8" columns="12" plateID="00000" expID="000-00000" format="Plate" showNEntries="1" peHeatmap="1" peShowEnums="1" peThickBorders="1" >+ <PrintLayout flipPattern0="0" rows="1" columns="1" padding="36" header="" footer="" headerActive="0" footerActive="0" scalingMode="fj.print.scale.none" scaling="1" orientation="1" width="612" height="792" imageableX="72" imageableY="72" imageableWidth="468" imageableHeight="648" />+ </PlateModel>+ <PlateEditorState>+ <KeywordList>+ <Keyword attribute="Treatment "Drug A"" value="10ug/L" />+ <Keyword attribute="Time point" value="24hr" />+ <Keyword attribute="Assay" value="GFP Reporter" />+ </KeywordList>+ <StagingArea>+ <StagingWell/>+ <StagingWell/>+ <StagingWell/>+ <StagingWell/>+ </StagingArea>+ </PlateEditorState>+ </Experiment>+ <Exports/>+ <SOPS/>+ <experiment/>+ <weights/>+ </Workspace>diff --git a/tests/flowkit/test_scripts.py b/tests/flowkit/test_scripts.pynew file mode 100644index 00000000..a27e48cf--- /dev/null+++ b/tests/flowkit/test_scripts.py@@ -0,0 +1,217 @@+"""Known-population cytometry tests, including an actual synthetic FlowJo export."""++from __future__ import annotations++import hashlib+import json+import os+from pathlib import Path+import re+import shutil+import subprocess+import sys++import pytest+import skill_contract++SKILL_ROOT = Path(__file__).resolve().parents[2] / "skills" / "flowkit"+FIXTURES = Path(__file__).resolve().parent / "fixtures"+sys.path.insert(0, str(SKILL_ROOT / "scripts"))++import analyze_gates++CliHelpTests = skill_contract.cli.help_test_case(SKILL_ROOT)++fk = pytest.importorskip("flowkit")+flowio = pytest.importorskip("flowio")+np = pytest.importorskip("numpy")+pd = pytest.importorskip("pandas")+++def write_sample(path, sample_id=None):+ # Exactly four events in Cells; three of those in Positive after compensation.+ truth = np.array([[-10, 0], [10, 20], [100, 10], [200, 50], [500, 100], [800, 200]])+ spill = np.array([[1.0, 0.1], [0.2, 1.0]])+ events = np.column_stack(([10, 100, 150, 200, 250, 500], truth @ spill))+ with path.open("wb") as handle:+ flowio.create_fcs(+ handle, events.ravel(), ["FSC-A", "FL1-A", "FL2-A"],+ metadata_dict={"fil": sample_id or path.name},+ )+ return path+++def strategy():+ result = fk.GatingStrategy()+ result.add_comp_matrix("spill", fk.Matrix(+ np.array([[1, .1], [.2, 1]]), ["FL1-A", "FL2-A"], fluorochromes=["FITC", "PE"]+ ))+ transform = fk.transforms.LogicleTransform(262144, .5, 4.5, 0)+ result.add_transform("logicle", transform)+ result.add_gate(fk.gates.RectangleGate("Cells", [+ fk.Dimension("FSC-A", range_min=50, range_max=300)+ ]), ("root",))+ lo, hi = transform.apply(np.array([50.0, 600.0]))+ result.add_gate(fk.gates.RectangleGate("Positive", [+ fk.Dimension("FL1-A", compensation_ref="spill", transformation_ref="logicle",+ range_min=float(lo), range_max=float(hi))+ ]), ("root", "Cells"))+ return result+++def inputs(tmp_path):+ sample = write_sample(tmp_path / "sample.fcs")+ xml = tmp_path / "gates.xml"+ with xml.open("wb") as handle:+ fk.export_gatingml(strategy(), handle)+ return sample, xml+++def run_analysis(tmp_path, inputs, **overrides):+ sample, xml = inputs+ options = dict(fcs_paths=[sample], definition=xml, mode="gatingml", output_dir=tmp_path / "out")+ options.update(overrides)+ manifest = analyze_gates.analyze(**options)+ return manifest, pd.read_csv(options["output_dir"] / "gate_report.csv")+++def test_compensation_transform_hierarchy_and_denominators(tmp_path, inputs):+ manifest, report = run_analysis(tmp_path, inputs)+ rows = report.set_index("gate_name")+ assert rows.loc["Cells", "count"] == 4+ assert rows.loc["Positive", "count"] == 3+ assert rows.loc["Positive", "absolute_percent"] == pytest.approx(50)+ assert rows.loc["Positive", "relative_percent"] == pytest.approx(75)+ assert json.loads(rows.loc["Positive", "gate_path"]) == ["root", "Cells"]+ assert manifest["samples"][0]["event_count"] == 6+ assert manifest["samples"][0]["sha256"] == hashlib.sha256(inputs[0].read_bytes()).hexdigest()+ assert manifest["definition"]["sha256"] == hashlib.sha256(inputs[1].read_bytes()).hexdigest()+ assert json.loads((tmp_path / "out" / "provenance.json").read_text()) == manifest+++def test_membership_keeps_event_order_and_matches_report(inputs):+ sample = fk.Sample(inputs[0])+ session = fk.Session(strategy(), [sample])+ session.analyze_samples(use_mp=False)+ mask = session.get_gate_membership(sample.id, "Positive", ("root", "Cells"))+ np.testing.assert_array_equal(mask, [False, False, True, True, True, False])+ parent = session.get_gate_membership(sample.id, "Cells", ("root",))+ assert np.all(~mask | parent)+ sample.apply_compensation(session.get_comp_matrix("spill"))+ intensity = sample.get_channel_events("FL1-A", source="comp")[mask]+ assert np.median(intensity) == pytest.approx(200)+ assert sample.get_channel_events("FL1-A", source="comp")[0] == pytest.approx(-10)+++def test_batch_reports_each_sample(tmp_path, inputs):+ second = write_sample(tmp_path / "second.fcs")+ manifest, report = run_analysis(tmp_path, inputs, fcs_paths=[inputs[0], second])+ assert set(report.sample_id) == {"sample.fcs", "second.fcs"}+ assert len(manifest["samples"]) == 2+ assert len(report) == 4+++def test_duplicate_fil_rejected_instead_of_silent_sample_loss(tmp_path, inputs):+ duplicate = write_sample(tmp_path / "renamed.fcs", sample_id="sample.fcs")+ with pytest.raises(ValueError, match="Duplicate sample ID"):+ run_analysis(tmp_path, inputs, fcs_paths=[inputs[0], duplicate])+ assert not (tmp_path / "out").exists()+ _, report = run_analysis(tmp_path, inputs, fcs_paths=[inputs[0], duplicate], filename_as_id=True)+ assert set(report.sample_id) == {"sample.fcs", "renamed.fcs"}+++def test_existing_output_is_preserved(tmp_path, inputs):+ destination = tmp_path / "out"+ destination.mkdir()+ sentinel = destination / "gate_report.csv"+ sentinel.write_text("previous results")+ with pytest.raises(FileExistsError):+ run_analysis(tmp_path, inputs)+ assert sentinel.read_text() == "previous results"+++def test_empty_strategy_rejected(tmp_path, inputs):+ from lxml import etree+ tree = etree.parse(str(inputs[1]))+ root = tree.getroot()+ for element in list(root):+ if etree.QName(element).localname.endswith("Gate"):+ root.remove(element)+ tree.write(str(inputs[1]))+ with pytest.raises(ValueError, match="no gates"):+ run_analysis(tmp_path, inputs)+++def test_imported_flowjo_polygon_has_known_50_events(tmp_path):+ sample = FIXTURES / "data_set_simple_line_100.fcs"+ wsp = FIXTURES / "simple_poly_and_rect_v2_poly50.wsp"+ _, report = run_analysis(tmp_path, (sample, wsp), mode="workspace", group="my_group")+ rows = report.set_index("gate_name")+ assert rows.loc["poly1", "count"] == 50+ assert rows.loc["poly1", "absolute_percent"] == pytest.approx(50)+ assert rows.loc["rect1", "count"] == 0+++def test_missing_workspace_member_is_not_silently_dropped(tmp_path):+ sample = FIXTURES / "data_set_simple_line_100.fcs"+ text = (FIXTURES / "simple_poly_and_rect_v2_poly50.wsp").read_text()+ # A second expected sample has gating metadata but no supplied FCS.+ from lxml import etree+ root = etree.fromstring(text.encode())+ original = root.find("SampleList/Sample")+ import copy+ missing = copy.deepcopy(original)+ missing.find("DataSet").set("sampleID", "2")+ missing.find("SampleNode").set("sampleID", "2")+ missing.find("SampleNode").set("name", "missing.fcs")+ for keyword in missing.findall("Keywords/Keyword"):+ if keyword.get("name", "").lower() == "$fil":+ keyword.set("value", "missing.fcs")+ root.find("SampleList").append(missing)+ group = root.find("Groups/GroupNode[@name='my_group']/Group/SampleRefs")+ etree.SubElement(group, "SampleRef", sampleID="2")+ wsp = tmp_path / "incomplete.wsp"+ wsp.write_bytes(etree.tostring(root))+ with pytest.raises(ValueError, match="missing IDs=.*missing.fcs"):+ run_analysis(tmp_path, (sample, wsp), mode="workspace", group="my_group")+ assert not (tmp_path / "out").exists()+++def test_unmatched_workspace_input_rejected(tmp_path, inputs):+ wsp = FIXTURES / "simple_poly_and_rect_v2_poly50.wsp"+ with pytest.raises(ValueError, match="unexpected IDs"):+ run_analysis(tmp_path, (inputs[0], wsp), mode="workspace", group="my_group")+++def test_cli_writes_report(tmp_path, inputs):+ result = subprocess.run(+ [sys.executable, str(SKILL_ROOT / "scripts" / "analyze_gates.py"),+ "--gatingml", str(inputs[1]), "--fcs", str(inputs[0]),+ "--output-dir", str(tmp_path / "cli")],+ capture_output=True, text=True, timeout=60,+ )+ assert result.returncode == 0, result.stderr+ assert "Analyzed 1 samples" in result.stdout+ assert len(pd.read_csv(tmp_path / "cli" / "gate_report.csv")) == 2++[email protected]("filename", ["SKILL.md", "references/workspaces-and-results.md"])+def test_documented_python_workflows_run(tmp_path, filename):+ if filename == "SKILL.md":+ write_sample(tmp_path / "sample.fcs")+ else:+ shutil.copyfile(FIXTURES / "data_set_simple_line_100.fcs", tmp_path / "data_set_simple_line_100.fcs")+ shutil.copyfile(FIXTURES / "simple_poly_and_rect_v2_poly50.wsp", tmp_path / "study.wsp")+ code = re.findall(r"```python\n(.*?)```", (SKILL_ROOT / filename).read_text(), re.S)+ assert len(code) == 1+ script = tmp_path / "example.py"+ script.write_text(code[0])+ result = subprocess.run(+ [sys.executable, str(script)], cwd=tmp_path, capture_output=True, text=True,+ env={**os.environ, "PYTHONDONTWRITEBYTECODE": "1"}, timeout=60,+ )+ assert result.returncode == 0, result.stderr+ if filename == "SKILL.md":+ _, report = run_analysis(tmp_path, (tmp_path / "sample.fcs", tmp_path / "gates.xml"))+ assert report.set_index("gate_name").loc["Positive", "count"] == 3diff --git a/tests/skill-requirements.toml b/tests/skill-requirements.tomlindex 8afc6f73..65067eb6 100644--- a/tests/skill-requirements.toml+++ b/tests/skill-requirements.toml@@ -501,6 +501,10 @@ packages = ["deeptools"][skills.flowio]packages = ["flowio", "numpy", "pandas"]+[skills.flowkit]+python = "3.13"+packages = ["flowkit==1.3.2"]+[skills.etetoolkit]packages = ["ete4"]