{"data":{"slug":"github-aipoch-medical-research-skills-scientific-skills-data-analysis-flowio-671036da8544","title":"Parse and Extract FCS Files for Cytometry Data","summary":"Parse FCS v2.0\u20133.1 files and extract event matrices, metadata, and channel definitions for preprocessing workflows. Deliverables include NumPy arrays, Pandas DataFrames, and CSV exports, with support for handling problematic files and multi-dataset content.","url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-flowio-671036da8544","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-flowio-671036da8544","markdown_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-flowio-671036da8544.md","download_url":"https:\/\/skillshunter.net\/skills\/github-aipoch-medical-research-skills-scientific-skills-data-analysis-flowio-671036da8544\/download","category":{"slug":"data-research","name":"Data & Research"},"editor_note":"Ensure Python 3.9 or higher is installed, and install the `flowio` package via pip or uv. Example usage requires `numpy` and `pandas` for data conversion and export.","instructions":"---\nname: flowio\ndescription: Parse Flow Cytometry Standard (FCS) files v2.0\u20133.1 and extract events\/metadata for preprocessing workflows (e.g., when you need NumPy arrays, channel info, or CSV\/DataFrame export from cytometry files).\nlicense: MIT\nauthor: AIPOCH\n---\n> **Source**: [https:\/\/github.com\/aipoch\/medical-research-skills](https:\/\/github.com\/aipoch\/medical-research-skills)\n\n## When to Use\n\n- You need to read FCS v2.0\/3.0\/3.1 files and extract event matrices for downstream preprocessing.\n- You want to inspect or validate FCS metadata (TEXT segment) without loading event data (memory-efficient parsing).\n- You need channel definitions (PnN\/PnS), ranges (PnR), and automatic identification of scatter\/fluorescence\/time channels.\n- You need to handle problematic FCS files with offset inconsistencies or multi-dataset content.\n- You want to export cytometry events to CSV\/Pandas DataFrame or write new\/modified FCS files.\n\n## Key Features\n\n- **FCS parsing (v2.0\u20133.1):** Reads HEADER\/TEXT\/DATA and optional ANALYSIS segments.\n- **Event extraction to NumPy:** Returns event data as `ndarray` with shape `(events, channels)`.\n- **Optional preprocessing:** Applies standard FCS transformations (gain\/log\/time scaling) when enabled.\n- **Metadata access:** Exposes TEXT keywords and common instrument\/acquisition fields.\n- **Channel utilities:** Provides PnN\/PnS labels, ranges, and indices for scatter\/fluorescence\/time channels.\n- **Robust parsing options:** Flags for offset discrepancy handling and null-channel exclusion.\n- **Multi-dataset support:** Detects and reads files containing multiple datasets.\n- **FCS writing:** Create new FCS files from arrays and optionally preserve\/override metadata.\n\n## Dependencies\n\n- `python >= 3.9`\n- `flowio` (install via pip\/uv; version depends on your environment)\n- Example-only:\n  - `numpy >= 1.20`\n  - `pandas >= 1.5`\n\n## Example Usage\n\n```python\n\"\"\"\nEnd-to-end example:\n1) Read an FCS file (metadata + events)\n2) Convert to a Pandas DataFrame and export CSV\n3) Filter events and write a new FCS file\n4) Handle multi-dataset files\n\"\"\"\n\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\n\nfrom flowio import (\n    FlowData,\n    create_fcs,\n    read_multiple_data_sets,\n    MultipleDataSetsError,\n    FCSParsingError,\n    DataOffsetDiscrepancyError,\n)\n\nFCS_PATH = \"sample.fcs\"\n\ndef read_fcs_safely(path: str) -> FlowData:\n    try:\n        return FlowData(path)\n    except DataOffsetDiscrepancyError:\n        # Common workaround for files with inconsistent offsets\n        return FlowData(path, ignore_offset_discrepancy=True)\n    except FCSParsingError:\n        # Looser mode if the file is malformed\n        return FlowData(path, ignore_offset_error=True)\n\ndef main() -> None:\n    # --- 1) Read file (single dataset) ---\n    try:\n        flow = read_fcs_safely(FCS_PATH)\n    except MultipleDataSetsError:\n        # --- 4) Multi-dataset handling ---\n        datasets = read_multiple_data_sets(FCS_PATH)\n        flow = datasets[0]  # pick the first dataset for this demo\n\n    print(\"File:\", getattr(flow, \"name\", Path(FCS_PATH).name))\n    print(\"FCS version:\", flow.version)\n    print(\"Events:\", flow.event_count)\n    print(\"Channels:\", flow.channel_count)\n    print(\"PnN labels:\", flow.pnn_labels)\n\n    # Metadata (TEXT segment)\n    print(\"Instrument ($CYT):\", flow.text.get(\"$CYT\", \"N\/A\"))\n    print(\"Acquisition date ($DATE):\", flow.text.get(\"$DATE\", \"N\/A\"))\n\n    # --- 2) Events -> NumPy -> DataFrame -> CSV ---\n    events = flow.as_array(preprocess=True)  # default preprocessing behavior\n    df = pd.DataFrame(events, columns=flow.pnn_labels)\n    df.to_csv(\"events.csv\", index=False)\n    print(\"Wrote CSV:\", \"events.csv\")\n\n    # --- 3) Filter and write a new FCS ---\n    # Example: threshold on first scatter channel if available, else channel 0\n    fsc_idx = flow.scatter_indices[0] if getattr(flow, \"scatter_indices\", []) else 0\n    threshold = np.percentile(events[:, fsc_idx], 50)  # median threshold\n    mask = events[:, fsc_idx] > threshold\n    filtered = events[mask]\n\n    create_fcs(\n        \"filtered.fcs\",\n        filtered,\n        flow.pnn_labels,\n        opt_channel_names=flow.pns_labels,\n        metadata={**flow.text, \"$SRC\": \"Filtered via FlowIO example\"},\n    )\n    print(\"Wrote FCS:\", \"filtered.fcs\")\n\n    # --- Metadata-only read (memory efficient) ---\n    meta_only = FlowData(FCS_PATH, only_text=True)\n    print(\"Metadata-only read: $DATE =\", meta_only.text.get(\"$DATE\", \"N\/A\"))\n\nif __name__ == \"__main__\":\n    main()\n```\n\n## Implementation Details\n\n### Data Model and Segments\n\nAn FCS file is organized into segments:\n\n- **HEADER:** FCS version and byte offsets for other segments.\n- **TEXT:** Keyword\/value metadata (e.g., `$DATE`, `$CYT`, `$PnN`, `$PnS`, `$PnR`, `$PnG`, `$PnE`).\n- **DATA:** Event matrix encoded as integer\/float\/double\/ASCII depending on file keywords.\n- **ANALYSIS (optional):** Post-processing results if present.\n\nIn FlowIO, these are exposed via `FlowData` attributes such as:\n- `flow.header` (HEADER info)\n- `flow.text` (TEXT keyword dictionary)\n- `flow.analysis` (ANALYSIS keyword dictionary, if present)\n- `flow.as_array(...)` (decoded event matrix)\n\n### Preprocessing (`as_array(preprocess=True)`)\n\nWhen preprocessing is enabled, FlowIO applies common FCS transformations:\n\n1. **Gain scaling (PnG):** Values are multiplied by the per-parameter gain.\n2. **Log\/exponential transform (PnE):** If present, applies:\n   - `value = a * 10^(b * raw_value)` where `PnE = \"a,b\"`.\n3. **Time scaling:** If a time channel is detected, values may be scaled into appropriate units.\n\nTo disable all transformations and obtain raw decoded values:\n- `flow.as_array(preprocess=False)`\n\n### Channel Identification\n\nFlowIO provides convenience indices for common channel types:\n\n- `flow.scatter_indices` (e.g., FSC\/SSC)\n- `flow.fluoro_indices` (fluorescence channels)\n- `flow.time_index` (time channel index or `None`)\n\nThese indices can be used to slice the event matrix:\n- `events[:, flow.scatter_indices]`\n- `events[:, flow.fluoro_indices]`\n\n### Handling Problematic Files (Offsets and Null Channels)\n\nSome files contain inconsistent offsets between HEADER and TEXT:\n\n- `ignore_offset_discrepancy=True` to tolerate HEADER\/TEXT offset mismatch.\n- `use_header_offsets=True` to prefer HEADER offsets.\n- `ignore_offset_error=True` to bypass offset-related failures more aggressively.\n\nTo exclude known null\/empty channels during parsing:\n- `FlowData(path, null_channel_list=[...])`\n\n### Multi-Dataset Files\n\nIf a file contains multiple datasets, constructing `FlowData(path)` may raise `MultipleDataSetsError`. Use:\n\n- `read_multiple_data_sets(path)` to load all datasets, or\n- `FlowData(path, nextdata_offset=...)` to load a specific dataset using `$NEXTDATA` offsets.\n\n### Writing FCS\n\nTwo common patterns:\n\n- **Write metadata-only changes:** `flow.write_fcs(\"out.fcs\", metadata={...})`\n- **Modify event data:** extract array \u2192 modify \u2192 `create_fcs(...)` to generate a new file (FlowIO does not modify event data in-place).","use_cases":["Read FCS files and extract event matrices for downstream preprocessing.","Inspect FCS metadata without loading event data for memory-efficient parsing.","Identify scatter\/fluorescence\/time channels and extract channel definitions.","Handle problematic FCS files with offset inconsistencies or multi-dataset content."],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/aipoch\/medical-research-skills\/blob\/686e09dfdb45d9fa1a08664f06bb93769b3c9d91\/scientific-skills\/Data%20Analysis\/flowio\/SKILL.md","source_commit":"686e09dfdb45d9fa1a08664f06bb93769b3c9d91","license":"MIT","version":null,"listing_approved_at":"2026-11-24","created_at":"2026-11-23T11:32:48.000000Z","updated_at":"2026-11-24T07:14:56.000000Z","seo_title":"Parse FCS Files for Cytometry Data","seo_description":"Parse FCS v2.0\u20133.1 files to extract event matrices, metadata, and channel definitions for preprocessing workflows. Supports memory-efficient parsing and multi-dataset FCS","seo_keywords":["parse FCS files","extract cytometry data","FCS file preprocessing","cytometry metadata extraction","FCS event matrix extraction"]}}