[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M735FPTSQEXS6JD2M0YRDGYY":3,"skill-same:01M735FPTSQEXS6JD2M0YRDGYY":54},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":26,"commitSha":27,"skillDirectory":28,"forksCount":29,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":6,"updatedAt":33,"install":34,"resources":47},"01M735FPTSQEXS6JD2M0YRDGYY","alterlab-flowio",null,"Parse FCS (Flow Cytometry Standard) files v2.0-3.1. Extract events as NumPy arrays, read metadata\u002Fchannels, convert to CSV\u002FDataFrame, for flow cytometry data preprocessing. Part of the AlterLab Academic Skills suite.","roohe\u002Fagentic-super-skills","roohe","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99054084?v=4","01M734WCDFP6RZVT5CNM00QR26","01M734WCE4BD0T4NZS5PCV9V5F",10,"MIT","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Falterlab-flowio\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: alterlab-flowio\ndescription: Parse FCS (Flow Cytometry Standard) files v2.0-3.1. Extract events as NumPy arrays, read metadata\u002Fchannels, convert to CSV\u002FDataFrame, for flow cytometry data preprocessing. Part of the AlterLab Academic Skills suite.\nlicense: MIT\nmetadata:\n    skill-author: AlterLab\n    version: \"1.0.0\"\n---\n\n# FlowIO: Flow Cytometry Standard File Handler\n\n## Overview\n\nFlowIO is a lightweight Python library for reading and writing Flow Cytometry Standard (FCS) files. Parse FCS metadata, extract event data, and create new FCS files with minimal dependencies. The library supports FCS versions 2.0, 3.0, and 3.1, making it ideal for backend services, data pipelines, and basic cytometry file operations.\n\n## When to Use This Skill\n\nThis skill should be used when:\n\n- FCS files requiring parsing or metadata extraction\n- Flow cytometry data needing conversion to NumPy arrays\n- Event data requiring export to FCS format\n- Multi-dataset FCS files needing separation\n- Channel information extraction (scatter, fluorescence, time)\n- Cytometry file validation or inspection\n- Pre-processing workflows before advanced analysis\n\n**Related Tools:** For advanced flow cytometry analysis including compensation, gating, and FlowJo\u002FGatingML support, recommend FlowKit library as a companion to FlowIO.\n\n## Installation\n\n```bash\nuv pip install flowio\n```\n\nRequires Python 3.9 or later.\n\n## Quick Start\n\n### Basic File Reading\n\n```python\nfrom flowio import FlowData\n\n# Read FCS file\nflow_data = FlowData('experiment.fcs')\n\n# Access basic information\nprint(f\"FCS Version: {flow_data.version}\")\nprint(f\"Events: {flow_data.event_count}\")\nprint(f\"Channels: {flow_data.pnn_labels}\")\n\n# Get event data as NumPy array\nevents = flow_data.as_array()  # Shape: (events, channels)\n```\n\n### Creating FCS Files\n\n```python\nimport numpy as np\nfrom flowio import create_fcs\n\n# Prepare data\ndata = np.array([[100, 200, 50], [150, 180, 60]])  # 2 events, 3 channels\nchannels = ['FSC-A', 'SSC-A', 'FL1-A']\n\n# Create FCS file\ncreate_fcs('output.fcs', data, channels)\n```\n\n## Core Workflows\n\n### Reading and Parsing FCS Files\n\nThe FlowData class provides the primary interface for reading FCS files.\n\n**Standard Reading:**\n\n```python\nfrom flowio import FlowData\n\n# Basic reading\nflow = FlowData('sample.fcs')\n\n# Access attributes\nversion = flow.version              # '3.0', '3.1', etc.\nevent_count = flow.event_count      # Number of events\nchannel_count = flow.channel_count  # Number of channels\npnn_labels = flow.pnn_labels        # Short channel names\npns_labels = flow.pns_labels        # Descriptive stain names\n\n# Get event data\nevents = flow.as_array()            # Preprocessed (gain, log scaling applied)\nraw_events = flow.as_array(preprocess=False)  # Raw data\n```\n\n**Memory-Efficient Metadata Reading:**\n\nWhen only metadata is needed (no event data):\n\n```python\n# Only parse TEXT segment, skip DATA and ANALYSIS\nflow = FlowData('sample.fcs', only_text=True)\n\n# Access metadata\nmetadata = flow.text  # Dictionary of TEXT segment keywords\nprint(metadata.get('$DATE'))  # Acquisition date\nprint(metadata.get('$CYT'))   # Instrument name\n```\n\n**Handling Problematic Files:**\n\nSome FCS files have offset discrepancies or errors:\n\n```python\n# Ignore offset discrepancies between HEADER and TEXT sections\nflow = FlowData('problematic.fcs', ignore_offset_discrepancy=True)\n\n# Use HEADER offsets instead of TEXT offsets\nflow = FlowData('problematic.fcs', use_header_offsets=True)\n\n# Ignore offset errors entirely\nflow = FlowData('problematic.fcs', ignore_offset_error=True)\n```\n\n**Excluding Null Channels:**\n\n```python\n# Exclude specific channels during parsing\nflow = FlowData('sample.fcs', null_channel_list=['Time', 'Null'])\n```\n\n### Extracting Metadata and Channel Information\n\nFCS files contain rich metadata in the TEXT segment.\n\n**Common Metadata Keywords:**\n\n```python\nflow = FlowData('sample.fcs')\n\n# File-level metadata\ntext_dict = flow.text\nacquisition_date = text_dict.get('$DATE', 'Unknown')\ninstrument = text_dict.get('$CYT', 'Unknown')\ndata_type = flow.data_type  # 'I', 'F', 'D', 'A'\n\n# Channel metadata\nfor i in range(flow.channel_count):\n    pnn = flow.pnn_labels[i]      # Short name (e.g., 'FSC-A')\n    pns = flow.pns_labels[i]      # Descriptive name (e.g., 'Forward Scatter')\n    pnr = flow.pnr_values[i]      # Range\u002Fmax value\n    print(f\"Channel {i}: {pnn} ({pns}), Range: {pnr}\")\n```\n\n**Channel Type Identification:**\n\nFlowIO automatically categorizes channels:\n\n```python\n# Get indices by channel type\nscatter_idx = flow.scatter_indices    # [0, 1] for FSC, SSC\nfluoro_idx = flow.fluoro_indices      # [2, 3, 4] for FL channels\ntime_idx = flow.time_index            # Index of time channel (or None)\n\n# Access specific channel types\nevents = flow.as_array()\nscatter_data = events[:, scatter_idx]\nfluorescence_data = events[:, fluoro_idx]\n```\n\n**ANALYSIS Segment:**\n\nIf present, access processed results:\n\n```python\nif flow.analysis:\n    analysis_keywords = flow.analysis  # Dictionary of ANALYSIS keywords\n    print(analysis_keywords)\n```\n\n### Creating New FCS Files\n\nGenerate FCS files from NumPy arrays or other data sources.\n\n**Basic Creation:**\n\n```python\nimport numpy as np\nfrom flowio import create_fcs\n\n# Create event data (rows=events, columns=channels)\nevents = np.random.rand(10000, 5) * 1000\n\n# Define channel names\nchannel_names = ['FSC-A', 'SSC-A', 'FL1-A', 'FL2-A', 'Time']\n\n# Create FCS file\ncreate_fcs('output.fcs', events, channel_names)\n```\n\n**With Descriptive Channel Names:**\n\n```python\n# Add optional descriptive names (PnS)\nchannel_names = ['FSC-A', 'SSC-A', 'FL1-A', 'FL2-A', 'Time']\ndescriptive_names = ['Forward Scatter', 'Side Scatter', 'FITC', 'PE', 'Time']\n\ncreate_fcs('output.fcs',\n           events,\n           channel_names,\n           opt_channel_names=descriptive_names)\n```\n\n**With Custom Metadata:**\n\n```python\n# Add TEXT segment metadata\nmetadata = {\n    '$SRC': 'Python script',\n    '$DATE': '19-OCT-2025',\n    '$CYT': 'Synthetic Instrument',\n    '$INST': 'Laboratory A'\n}\n\ncreate_fcs('output.fcs',\n           events,\n           channel_names,\n           opt_channel_names=descriptive_names,\n           metadata=metadata)\n```\n\n**Note:** FlowIO exports as FCS 3.1 with single-precision floating-point data.\n\n### Exporting Modified Data\n\nModify existing FCS files and re-export them.\n\n**Approach 1: Using write_fcs() Method:**\n\n```python\nfrom flowio import FlowData\n\n# Read original file\nflow = FlowData('original.fcs')\n\n# Write with updated metadata\nflow.write_fcs('modified.fcs', metadata={'$SRC': 'Modified data'})\n```\n\n**Approach 2: Extract, Modify, and Recreate:**\n\nFor modifying event data:\n\n```python\nfrom flowio import FlowData, create_fcs\n\n# Read and extract data\nflow = FlowData('original.fcs')\nevents = flow.as_array(preprocess=False)\n\n# Modify event data\nevents[:, 0] = events[:, 0] * 1.5  # Scale first channel\n\n# Create new FCS file with modified data\ncreate_fcs('modified.fcs',\n           events,\n           flow.pnn_labels,\n           opt_channel_names=flow.pns_labels,\n           metadata=flow.text)\n```\n\n### Handling Multi-Dataset FCS Files\n\nSome FCS files contain multiple datasets in a single file.\n\n**Detecting Multi-Dataset Files:**\n\n```python\nfrom flowio import FlowData, MultipleDataSetsError\n\ntry:\n    flow = FlowData('sample.fcs')\nexcept MultipleDataSetsError:\n    print(\"File contains multiple datasets\")\n    # Use read_multiple_data_sets() instead\n```\n\n**Reading All Datasets:**\n\n```python\nfrom flowio import read_multiple_data_sets\n\n# Read all datasets from file\ndatasets = read_multiple_data_sets('multi_dataset.fcs')\n\nprint(f\"Found {len(datasets)} datasets\")\n\n# Process each dataset\nfor i, dataset in enumerate(datasets):\n    print(f\"\\nDataset {i}:\")\n    print(f\"  Events: {dataset.event_count}\")\n    print(f\"  Channels: {dataset.pnn_labels}\")\n\n    # Get event data for this dataset\n    events = dataset.as_array()\n    print(f\"  Shape: {events.shape}\")\n    print(f\"  Mean values: {events.mean(axis=0)}\")\n```\n\n**Reading Specific Dataset:**\n\n```python\nfrom flowio import FlowData\n\n# Read first dataset (nextdata_offset=0)\nfirst_dataset = FlowData('multi.fcs', nextdata_offset=0)\n\n# Read second dataset using NEXTDATA offset from first\nnext_offset = int(first_dataset.text['$NEXTDATA'])\nif next_offset > 0:\n    second_dataset = FlowData('multi.fcs', nextdata_offset=next_offset)\n```\n\n## Data Preprocessing\n\nFlowIO applies standard FCS preprocessing transformations when `preprocess=True`.\n\n**Preprocessing Steps:**\n\n1. **Gain Scaling:** Multiply values by PnG (gain) keyword\n2. **Logarithmic Transformation:** Apply PnE exponential transformation if present\n   - Formula: `value = a * 10^(b * raw_value)` where PnE = \"a,b\"\n3. **Time Scaling:** Convert time values to appropriate units\n\n**Controlling Preprocessing:**\n\n```python\n# Preprocessed data (default)\npreprocessed = flow.as_array(preprocess=True)\n\n# Raw data (no transformations)\nraw = flow.as_array(preprocess=False)\n```\n\n## Error Handling\n\nHandle common FlowIO exceptions appropriately.\n\n```python\nfrom flowio import (\n    FlowData,\n    FCSParsingError,\n    DataOffsetDiscrepancyError,\n    MultipleDataSetsError\n)\n\ntry:\n    flow = FlowData('sample.fcs')\n    events = flow.as_array()\n\nexcept FCSParsingError as e:\n    print(f\"Failed to parse FCS file: {e}\")\n    # Try with relaxed parsing\n    flow = FlowData('sample.fcs', ignore_offset_error=True)\n\nexcept DataOffsetDiscrepancyError as e:\n    print(f\"Offset discrepancy detected: {e}\")\n    # Use ignore_offset_discrepancy parameter\n    flow = FlowData('sample.fcs', ignore_offset_discrepancy=True)\n\nexcept MultipleDataSetsError as e:\n    print(f\"Multiple datasets detected: {e}\")\n    # Use read_multiple_data_sets instead\n    from flowio import read_multiple_data_sets\n    datasets = read_multiple_data_sets('sample.fcs')\n\nexcept Exception as e:\n    print(f\"Unexpected error: {e}\")\n```\n\n## Common Use Cases\n\n### Inspecting FCS File Contents\n\nQuick exploration of FCS file structure:\n\n```python\nfrom flowio import FlowData\n\nflow = FlowData('unknown.fcs')\n\nprint(\"=\" * 50)\nprint(f\"File: {flow.name}\")\nprint(f\"Version: {flow.version}\")\nprint(f\"Size: {flow.file_size:,} bytes\")\nprint(\"=\" * 50)\n\nprint(f\"\\nEvents: {flow.event_count:,}\")\nprint(f\"Channels: {flow.channel_count}\")\n\nprint(\"\\nChannel Information:\")\nfor i, (pnn, pns) in enumerate(zip(flow.pnn_labels, flow.pns_labels)):\n    ch_type = \"scatter\" if i in flow.scatter_indices else \\\n              \"fluoro\" if i in flow.fluoro_indices else \\\n              \"time\" if i == flow.time_index else \"other\"\n    print(f\"  [{i}] {pnn:10s} | {pns:30s} | {ch_type}\")\n\nprint(\"\\nKey Metadata:\")\nfor key in ['$DATE', '$BTIM', '$ETIM', '$CYT', '$INST', '$SRC']:\n    value = flow.text.get(key, 'N\u002FA')\n    print(f\"  {key:15s}: {value}\")\n```\n\n### Batch Processing Multiple Files\n\nProcess a directory of FCS files:\n\n```python\nfrom pathlib import Path\nfrom flowio import FlowData\nimport pandas as pd\n\n# Find all FCS files\nfcs_files = list(Path('data\u002F').glob('*.fcs'))\n\n# Extract summary information\nsummaries = []\nfor fcs_path in fcs_files:\n    try:\n        flow = FlowData(str(fcs_path), only_text=True)\n        summaries.append({\n            'filename': fcs_path.name,\n            'version': flow.version,\n            'events': flow.event_count,\n            'channels': flow.channel_count,\n            'date': flow.text.get('$DATE', 'N\u002FA')\n        })\n    except Exception as e:\n        print(f\"Error processing {fcs_path.name}: {e}\")\n\n# Create summary DataFrame\ndf = pd.DataFrame(summaries)\nprint(df)\n```\n\n### Converting FCS to CSV\n\nExport event data to CSV format:\n\n```python\nfrom flowio import FlowData\nimport pandas as pd\n\n# Read FCS file\nflow = FlowData('sample.fcs')\n\n# Convert to DataFrame\ndf = pd.DataFrame(\n    flow.as_array(),\n    columns=flow.pnn_labels\n)\n\n# Add metadata as attributes\ndf.attrs['fcs_version'] = flow.version\ndf.attrs['instrument'] = flow.text.get('$CYT', 'Unknown')\n\n# Export to CSV\ndf.to_csv('output.csv', index=False)\nprint(f\"Exported {len(df)} events to CSV\")\n```\n\n### Filtering Events and Re-exporting\n\nApply filters and save filtered data:\n\n```python\nfrom flowio import FlowData, create_fcs\nimport numpy as np\n\n# Read original file\nflow = FlowData('sample.fcs')\nevents = flow.as_array(preprocess=False)\n\n# Apply filtering (example: threshold on first channel)\nfsc_idx = 0\nthreshold = 500\nmask = events[:, fsc_idx] > threshold\nfiltered_events = events[mask]\n\nprint(f\"Original events: {len(events)}\")\nprint(f\"Filtered events: {len(filtered_events)}\")\n\n# Create new FCS file with filtered data\ncreate_fcs('filtered.fcs',\n           filtered_events,\n           flow.pnn_labels,\n           opt_channel_names=flow.pns_labels,\n           metadata={**flow.text, '$SRC': 'Filtered data'})\n```\n\n### Extracting Specific Channels\n\nExtract and process specific channels:\n\n```python\nfrom flowio import FlowData\nimport numpy as np\n\nflow = FlowData('sample.fcs')\nevents = flow.as_array()\n\n# Extract fluorescence channels only\nfluoro_indices = flow.fluoro_indices\nfluoro_data = events[:, fluoro_indices]\nfluoro_names = [flow.pnn_labels[i] for i in fluoro_indices]\n\nprint(f\"Fluorescence channels: {fluoro_names}\")\nprint(f\"Shape: {fluoro_data.shape}\")\n\n# Calculate statistics per channel\nfor i, name in enumerate(fluoro_names):\n    channel_data = fluoro_data[:, i]\n    print(f\"\\n{name}:\")\n    print(f\"  Mean: {channel_data.mean():.2f}\")\n    print(f\"  Median: {np.median(channel_data):.2f}\")\n    print(f\"  Std Dev: {channel_data.std():.2f}\")\n```\n\n## Best Practices\n\n1. **Memory Efficiency:** Use `only_text=True` when event data is not needed\n2. **Error Handling:** Wrap file operations in try-except blocks for robust code\n3. **Multi-Dataset Detection:** Check for MultipleDataSetsError and use appropriate function\n4. **Preprocessing Control:** Explicitly set `preprocess` parameter based on analysis needs\n5. **Offset Issues:** If parsing fails, try `ignore_offset_discrepancy=True` parameter\n6. **Channel Validation:** Verify channel counts and names match expectations before processing\n7. **Metadata Preservation:** When modifying files, preserve original TEXT segment keywords\n\n## Advanced Topics\n\n### Understanding FCS File Structure\n\nFCS files consist of four segments:\n\n1. **HEADER:** FCS version and byte offsets for other segments\n2. **TEXT:** Key-value metadata pairs (delimiter-separated)\n3. **DATA:** Raw event data (binary\u002Ffloat\u002FASCII format)\n4. **ANALYSIS** (optional): Results from data processing\n\nAccess these segments via FlowData attributes:\n- `flow.header` - HEADER segment\n- `flow.text` - TEXT segment keywords\n- `flow.events` - DATA segment (as bytes)\n- `flow.analysis` - ANALYSIS segment keywords (if present)\n\n### Detailed API Reference\n\nFor comprehensive API documentation including all parameters, methods, exceptions, and FCS keyword reference, consult the detailed reference file:\n\n**Read:** `references\u002Fapi_reference.md`\n\nThe reference includes:\n- Complete FlowData class documentation\n- All utility functions (read_multiple_data_sets, create_fcs)\n- Exception classes and handling\n- FCS file structure details\n- Common TEXT segment keywords\n- Extended example workflows\n\nWhen working with complex FCS operations or encountering unusual file formats, load this reference for detailed guidance.\n\n## Integration Notes\n\n**NumPy Arrays:** All event data is returned as NumPy ndarrays with shape (events, channels)\n\n**Pandas DataFrames:** Easily convert to DataFrames for analysis:\n```python\nimport pandas as pd\ndf = pd.DataFrame(flow.as_array(), columns=flow.pnn_labels)\n```\n\n**FlowKit Integration:** For advanced analysis (compensation, gating, FlowJo support), use FlowKit library which builds on FlowIO's parsing capabilities\n\n**Web Applications:** FlowIO's minimal dependencies make it ideal for web backend services processing FCS uploads\n\n## Troubleshooting\n\n**Problem:** \"Offset discrepancy error\"\n**Solution:** Use `ignore_offset_discrepancy=True` parameter\n\n**Problem:** \"Multiple datasets error\"\n**Solution:** Use `read_multiple_data_sets()` function instead of FlowData constructor\n\n**Problem:** Out of memory with large files\n**Solution:** Use `only_text=True` for metadata-only operations, or process events in chunks\n\n**Problem:** Unexpected channel counts\n**Solution:** Check for null channels; use `null_channel_list` parameter to exclude them\n\n**Problem:** Cannot modify event data in place\n**Solution:** FlowIO doesn't support direct modification; extract data, modify, then use `create_fcs()` to save\n\n## Summary\n\nFlowIO provides essential FCS file handling capabilities for flow cytometry workflows. Use it for parsing, metadata extraction, and file creation. For simple file operations and data extraction, FlowIO is sufficient. For complex analysis including compensation and gating, integrate with FlowKit or other specialized tools.\n\n","# FlowIO: Flow Cytometry Standard File Handler\n\n## Overview\n\nFlowIO is a lightweight Python library for reading and writing Flow Cytometry Standard (FCS) files. Parse FCS metadata, extract event data, and create new FCS files with minimal dependencies. The library supports FCS versions 2.0, 3.0, and 3.1, making it ideal for backend services, data pipelines, and basic cytometry file operations.\n\n## When to Use This Skill\n\nThis skill should be used when:\n\n- FCS files requiring parsing or metadata extraction\n- Flow cytometry data needing conversion to NumPy arrays\n- Event data requiring export to FCS format\n- Multi-dataset FCS files needing separation\n- Channel information extraction (scatter, fluorescence, time)\n- Cytometry file validation or inspection\n- Pre-processing workflows before advanced analysis\n\n**Related Tools:** For advanced flow cytometry analysis including compensation, gating, and FlowJo\u002FGatingML support, recommend FlowKit library as a companion to FlowIO.\n\n## Installation\n\n```bash\nuv pip install flowio\n```\n\nRequires Python 3.9 or later.\n\n## Quick Start\n\n### Basic File Reading\n\n```python\nfrom flowio import FlowData\n\n# Read FCS file\nflow_data = FlowData('experiment.fcs')\n\n# Access basic information\nprint(f\"FCS Version: {flow_data.version}\")\nprint(f\"Events: {flow_data.event_count}\")\nprint(f\"Channels: {flow_data.pnn_labels}\")\n\n# Get event data as NumPy array\nevents = flow_data.as_array()  # Shape: (events, channels)\n```\n\n### Creating FCS Files\n\n```python\nimport numpy as np\nfrom flowio import create_fcs\n\n# Prepare data\ndata = np.array([[100, 200, 50], [150, 180, 60]])  # 2 events, 3 channels\nchannels = ['FSC-A', 'SSC-A', 'FL1-A']\n\n# Create FCS file\ncreate_fcs('output.fcs', data, channels)\n```\n\n## Core Workflows\n\n### Reading and Parsing FCS Files\n\nThe FlowData class provides the primary interface for reading FCS files.\n\n**Standard Reading:**\n\n```python\nfrom flowio import FlowData\n\n# Basic reading\nflow = FlowData('sample.fcs')\n\n# Access attributes\nversion = flow.version              # '3.0', '3.1', etc.\nevent_count = flow.event_count      # Number of events\nchannel_count = flow.channel_count  # Number of channels\npnn_labels = flow.pnn_labels        # Short channel names\npns_labels = flow.pns_labels        # Descriptive stain names\n\n# Get event data\nevents = flow.as_array()            # Preprocessed (gain, log scaling applied)\nraw_events = flow.as_array(preprocess=False)  # Raw data\n```\n\n**Memory-Efficient Metadata Reading:**\n\nWhen only metadata is needed (no event data):\n\n```python\n# Only parse TEXT segment, skip DATA and ANALYSIS\nflow = FlowData('sample.fcs', only_text=True)\n\n# Access metadata\nmetadata = flow.text  # Dictionary of TEXT segment keywords\nprint(metadata.get('$DATE'))  # Acquisition date\nprint(metadata.get('$CYT'))   # Instrument name\n```\n\n**Handling Problematic Files:**\n\nSome FCS files have offset discrepancies or errors:\n\n```python\n# Ignore offset discrepancies between HEADER and TEXT sections\nflow = FlowData('problematic.fcs', ignore_offset_discrepancy=True)\n\n# Use HEADER offsets instead of TEXT offsets\nflow = FlowData('problematic.fcs', use_header_offsets=True)\n\n# Ignore offset errors entirely\nflow = FlowData('problematic.fcs', ignore_offset_error=True)\n```\n\n**Excluding Null Channels:**\n\n```python\n# Exclude specific channels during parsing\nflow = FlowData('sample.fcs', null_channel_list=['Time', 'Null'])\n```\n\n### Extracting Metadata and Channel Information\n\nFCS files contain rich metadata in the TEXT segment.\n\n**Common Metadata Keywords:**\n\n```python\nflow = FlowData('sample.fcs')\n\n# File-level metadata\ntext_dict = flow.text\nacquisition_date = text_dict.get('$DATE', 'Unknown')\ninstrument = text_dict.get('$CYT', 'Unknown')\ndata_type = flow.data_type  # 'I', 'F', 'D', 'A'\n\n# Channel metadata\nfor i in range(flow.channel_count):\n    pnn = flow.pnn_labels[i]      # Short name (e.g., 'FSC-A')\n    pns = flow.pns_labels[i]      # Descriptive name (e.g., 'Forward Scatter')\n    pnr = flow.pnr_values[i]      # Range\u002Fmax value\n    print(f\"Channel {i}: {pnn} ({pns}), Range: {pnr}\")\n```\n\n**Channel Type Identification:**\n\nFlowIO automatically categorizes channels:\n\n```python\n# Get indices by channel type\nscatter_idx = flow.scatter_indices    # [0, 1] for FSC, SSC\nfluoro_idx = flow.fluoro_indices      # [2, 3, 4] for FL channels\ntime_idx = flow.time_index            # Index of time channel (or None)\n\n# Access specific channel types\nevents = flow.as_array()\nscatter_data = events[:, scatter_idx]\nfluorescence_data = events[:, fluoro_idx]\n```\n\n**ANALYSIS Segment:**\n\nIf present, access processed results:\n\n```python\nif flow.analysis:\n    analysis_keywords = flow.analysis  # Dictionary of ANALYSIS keywords\n    print(analysis_keywords)\n```\n\n### Creating New FCS Files\n\nGenerate FCS files from NumPy arrays or other data sources.\n\n**Basic Creation:**\n\n```python\nimport numpy as np\nfrom flowio import create_fcs\n\n# Create event data (rows=events, columns=channels)\nevents = np.random.rand(10000, 5) * 1000\n\n# Define channel names\nchannel_names = ['FSC-A', 'SSC-A', 'FL1-A', 'FL2-A', 'Time']\n\n# Create FCS file\ncreate_fcs('output.fcs', events, channel_names)\n```\n\n**With Descriptive Channel Names:**\n\n```python\n# Add optional descriptive names (PnS)\nchannel_names = ['FSC-A', 'SSC-A', 'FL1-A', 'FL2-A', 'Time']\ndescriptive_names = ['Forward Scatter', 'Side Scatter', 'FITC', 'PE', 'Time']\n\ncreate_fcs('output.fcs',\n           events,\n           channel_names,\n           opt_channel_names=descriptive_names)\n```\n\n**With Custom Metadata:**\n\n```python\n# Add TEXT segment metadata\nmetadata = {\n    '$SRC': 'Python script',\n    '$DATE': '19-OCT-2025',\n    '$CYT': 'Synthetic Instrument',\n    '$INST': 'Laboratory A'\n}\n\ncreate_fcs('output.fcs',\n           events,\n           channel_names,\n           opt_channel_names=descriptive_names,\n           metadata=metadata)\n```\n\n**Note:** FlowIO exports as FCS 3.1 with single-precision floating-point data.\n\n### Exporting Modified Data\n\nModify existing FCS files and re-export them.\n\n**Approach 1: Using write_fcs() Method:**\n\n```python\nfrom flowio import FlowData\n\n# Read original file\nflow = FlowData('original.fcs')\n\n# Write with updated metadata\nflow.write_fcs('modified.fcs', metadata={'$SRC': 'Modified data'})\n```\n\n**Approach 2: Extract, Modify, and Recreate:**\n\nFor modifying event data:\n\n```python\nfrom flowio import FlowData, create_fcs\n\n# Read and extract data\nflow = FlowData('original.fcs')\nevents = flow.as_array(preprocess=False)\n\n# Modify event data\nevents[:, 0] = events[:, 0] * 1.5  # Scale first channel\n\n# Create new FCS file with modified data\ncreate_fcs('modified.fcs',\n           events,\n           flow.pnn_labels,\n           opt_channel_names=flow.pns_labels,\n           metadata=flow.text)\n```\n\n### Handling Multi-Dataset FCS Files\n\nSome FCS files contain multiple datasets in a single file.\n\n**Detecting Multi-Dataset Files:**\n\n```python\nfrom flowio import FlowData, MultipleDataSetsError\n\ntry:\n    flow = FlowData('sample.fcs')\nexcept MultipleDataSetsError:\n    print(\"File contains multiple datasets\")\n    # Use read_multiple_data_sets() instead\n```\n\n**Reading All Datasets:**\n\n```python\nfrom flowio import read_multiple_data_sets\n\n# Read all datasets from file\ndatasets = read_multiple_data_sets('multi_dataset.fcs')\n\nprint(f\"Found {len(datasets)} datasets\")\n\n# Process each dataset\nfor i, dataset in enumerate(datasets):\n    print(f\"\\nDataset {i}:\")\n    print(f\"  Events: {dataset.event_count}\")\n    print(f\"  Channels: {dataset.pnn_labels}\")\n\n    # Get event data for this dataset\n    events = dataset.as_array()\n    print(f\"  Shape: {events.shape}\")\n    print(f\"  Mean values: {events.mean(axis=0)}\")\n```\n\n**Reading Specific Dataset:**\n\n```python\nfrom flowio import FlowData\n\n# Read first dataset (nextdata_offset=0)\nfirst_dataset = FlowData('multi.fcs', nextdata_offset=0)\n\n# Read second dataset using NEXTDATA offset from first\nnext_offset = int(first_dataset.text['$NEXTDATA'])\nif next_offset > 0:\n    second_dataset = FlowData('multi.fcs', nextdata_offset=next_offset)\n```\n\n## Data Preprocessing\n\nFlowIO applies standard FCS preprocessing transformations when `preprocess=True`.\n\n**Preprocessing Steps:**\n\n1. **Gain Scaling:** Multiply values by PnG (gain) keyword\n2. **Logarithmic Transformation:** Apply PnE exponential transformation if present\n   - Formula: `value = a * 10^(b * raw_value)` where PnE = \"a,b\"\n3. **Time Scaling:** Convert time values to appropriate units\n\n**Controlling Preprocessing:**\n\n```python\n# Preprocessed data (default)\npreprocessed = flow.as_array(preprocess=True)\n\n# Raw data (no transformations)\nraw = flow.as_array(preprocess=False)\n```\n\n## Error Handling\n\nHandle common FlowIO exceptions appropriately.\n\n```python\nfrom flowio import (\n    FlowData,\n    FCSParsingError,\n    DataOffsetDiscrepancyError,\n    MultipleDataSetsError\n)\n\ntry:\n    flow = FlowData('sample.fcs')\n    events = flow.as_array()\n\nexcept FCSParsingError as e:\n    print(f\"Failed to parse FCS file: {e}\")\n    # Try with relaxed parsing\n    flow = FlowData('sample.fcs', ignore_offset_error=True)\n\nexcept DataOffsetDiscrepancyError as e:\n    print(f\"Offset discrepancy detected: {e}\")\n    # Use ignore_offset_discrepancy parameter\n    flow = FlowData('sample.fcs', ignore_offset_discrepancy=True)\n\nexcept MultipleDataSetsError as e:\n    print(f\"Multiple datasets detected: {e}\")\n    # Use read_multiple_data_sets instead\n    from flowio import read_multiple_data_sets\n    datasets = read_multiple_data_sets('sample.fcs')\n\nexcept Exception as e:\n    print(f\"Unexpected error: {e}\")\n```\n\n## Common Use Cases\n\n### Inspecting FCS File Contents\n\nQuick exploration of FCS file structure:\n\n```python\nfrom flowio import FlowData\n\nflow = FlowData('unknown.fcs')\n\nprint(\"=\" * 50)\nprint(f\"File: {flow.name}\")\nprint(f\"Version: {flow.version}\")\nprint(f\"Size: {flow.file_size:,} bytes\")\nprint(\"=\" * 50)\n\nprint(f\"\\nEvents: {flow.event_count:,}\")\nprint(f\"Channels: {flow.channel_count}\")\n\nprint(\"\\nChannel Information:\")\nfor i, (pnn, pns) in enumerate(zip(flow.pnn_labels, flow.pns_labels)):\n    ch_type = \"scatter\" if i in flow.scatter_indices else \\\n              \"fluoro\" if i in flow.fluoro_indices else \\\n              \"time\" if i == flow.time_index else \"other\"\n    print(f\"  [{i}] {pnn:10s} | {pns:30s} | {ch_type}\")\n\nprint(\"\\nKey Metadata:\")\nfor key in ['$DATE', '$BTIM', '$ETIM', '$CYT', '$INST', '$SRC']:\n    value = flow.text.get(key, 'N\u002FA')\n    print(f\"  {key:15s}: {value}\")\n```\n\n### Batch Processing Multiple Files\n\nProcess a directory of FCS files:\n\n```python\nfrom pathlib import Path\nfrom flowio import FlowData\nimport pandas as pd\n\n# Find all FCS files\nfcs_files = list(Path('data\u002F').glob('*.fcs'))\n\n# Extract summary information\nsummaries = []\nfor fcs_path in fcs_files:\n    try:\n        flow = FlowData(str(fcs_path), only_text=True)\n        summaries.append({\n            'filename': fcs_path.name,\n            'version': flow.version,\n            'events': flow.event_count,\n            'channels': flow.channel_count,\n            'date': flow.text.get('$DATE', 'N\u002FA')\n        })\n    except Exception as e:\n        print(f\"Error processing {fcs_path.name}: {e}\")\n\n# Create summary DataFrame\ndf = pd.DataFrame(summaries)\nprint(df)\n```\n\n### Converting FCS to CSV\n\nExport event data to CSV format:\n\n```python\nfrom flowio import FlowData\nimport pandas as pd\n\n# Read FCS file\nflow = FlowData('sample.fcs')\n\n# Convert to DataFrame\ndf = pd.DataFrame(\n    flow.as_array(),\n    columns=flow.pnn_labels\n)\n\n# Add metadata as attributes\ndf.attrs['fcs_version'] = flow.version\ndf.attrs['instrument'] = flow.text.get('$CYT', 'Unknown')\n\n# Export to CSV\ndf.to_csv('output.csv', index=False)\nprint(f\"Exported {len(df)} events to CSV\")\n```\n\n### Filtering Events and Re-exporting\n\nApply filters and save filtered data:\n\n```python\nfrom flowio import FlowData, create_fcs\nimport numpy as np\n\n# Read original file\nflow = FlowData('sample.fcs')\nevents = flow.as_array(preprocess=False)\n\n# Apply filtering (example: threshold on first channel)\nfsc_idx = 0\nthreshold = 500\nmask = events[:, fsc_idx] > threshold\nfiltered_events = events[mask]\n\nprint(f\"Original events: {len(events)}\")\nprint(f\"Filtered events: {len(filtered_events)}\")\n\n# Create new FCS file with filtered data\ncreate_fcs('filtered.fcs',\n           filtered_events,\n           flow.pnn_labels,\n           opt_channel_names=flow.pns_labels,\n           metadata={**flow.text, '$SRC': 'Filtered data'})\n```\n\n### Extracting Specific Channels\n\nExtract and process specific channels:\n\n```python\nfrom flowio import FlowData\nimport numpy as np\n\nflow = FlowData('sample.fcs')\nevents = flow.as_array()\n\n# Extract fluorescence channels only\nfluoro_indices = flow.fluoro_indices\nfluoro_data = events[:, fluoro_indices]\nfluoro_names = [flow.pnn_labels[i] for i in fluoro_indices]\n\nprint(f\"Fluorescence channels: {fluoro_names}\")\nprint(f\"Shape: {fluoro_data.shape}\")\n\n# Calculate statistics per channel\nfor i, name in enumerate(fluoro_names):\n    channel_data = fluoro_data[:, i]\n    print(f\"\\n{name}:\")\n    print(f\"  Mean: {channel_data.mean():.2f}\")\n    print(f\"  Median: {np.median(channel_data):.2f}\")\n    print(f\"  Std Dev: {channel_data.std():.2f}\")\n```\n\n## Best Practices\n\n1. **Memory Efficiency:** Use `only_text=True` when event data is not needed\n2. **Error Handling:** Wrap file operations in try-except blocks for robust code\n3. **Multi-Dataset Detection:** Check for MultipleDataSetsError and use appropriate function\n4. **Preprocessing Control:** Explicitly set `preprocess` parameter based on analysis needs\n5. **Offset Issues:** If parsing fails, try `ignore_offset_discrepancy=True` parameter\n6. **Channel Validation:** Verify channel counts and names match expectations before processing\n7. **Metadata Preservation:** When modifying files, preserve original TEXT segment keywords\n\n## Advanced Topics\n\n### Understanding FCS File Structure\n\nFCS files consist of four segments:\n\n1. **HEADER:** FCS version and byte offsets for other segments\n2. **TEXT:** Key-value metadata pairs (delimiter-separated)\n3. **DATA:** Raw event data (binary\u002Ffloat\u002FASCII format)\n4. **ANALYSIS** (optional): Results from data processing\n\nAccess these segments via FlowData attributes:\n- `flow.header` - HEADER segment\n- `flow.text` - TEXT segment keywords\n- `flow.events` - DATA segment (as bytes)\n- `flow.analysis` - ANALYSIS segment keywords (if present)\n\n### Detailed API Reference\n\nFor comprehensive API documentation including all parameters, methods, exceptions, and FCS keyword reference, consult the detailed reference file:\n\n**Read:** `references\u002Fapi_reference.md`\n\nThe reference includes:\n- Complete FlowData class documentation\n- All utility functions (read_multiple_data_sets, create_fcs)\n- Exception classes and handling\n- FCS file structure details\n- Common TEXT segment keywords\n- Extended example workflows\n\nWhen working with complex FCS operations or encountering unusual file formats, load this reference for detailed guidance.\n\n## Integration Notes\n\n**NumPy Arrays:** All event data is returned as NumPy ndarrays with shape (events, channels)\n\n**Pandas DataFrames:** Easily convert to DataFrames for analysis:\n```python\nimport pandas as pd\ndf = pd.DataFrame(flow.as_array(), columns=flow.pnn_labels)\n```\n\n**FlowKit Integration:** For advanced analysis (compensation, gating, FlowJo support), use FlowKit library which builds on FlowIO's parsing capabilities\n\n**Web Applications:** FlowIO's minimal dependencies make it ideal for web backend services processing FCS uploads\n\n## Troubleshooting\n\n**Problem:** \"Offset discrepancy error\"\n**Solution:** Use `ignore_offset_discrepancy=True` parameter\n\n**Problem:** \"Multiple datasets error\"\n**Solution:** Use `read_multiple_data_sets()` function instead of FlowData constructor\n\n**Problem:** Out of memory with large files\n**Solution:** Use `only_text=True` for metadata-only operations, or process events in chunks\n\n**Problem:** Unexpected channel counts\n**Solution:** Check for null channels; use `null_channel_list` parameter to exclude them\n\n**Problem:** Cannot modify event data in place\n**Solution:** FlowIO doesn't support direct modification; extract data, modify, then use `create_fcs()` to save\n\n## Summary\n\nFlowIO provides essential FCS file handling capabilities for flow cytometry workflows. Use it for parsing, metadata extraction, and file creation. For simple file operations and data extraction, FlowIO is sufficient. For complex analysis including compensation and gating, integrate with FlowKit or other specialized tools.\n\n",{"name":5,"license":14,"metadata":23,"description":7},{"version":24,"skill-author":25},"1.0.0","AlterLab","master","f483e54f3ad5f202a77d45f2e57f8d970b71195f","skills_library\u002Falterlab-flowio",2,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills","https:\u002F\u002Fgithub.com\u002Froohe","yoou.link","2026-05-19 15:56:07",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add roohe\u002Fagentic-super-skills --skill alterlab-flowio",{"tool":40,"command":41},"bunx","bunx skills add roohe\u002Fagentic-super-skills --skill alterlab-flowio",{"tool":43,"command":44},"pnpm","pnpm dlx skills add roohe\u002Fagentic-super-skills --skill alterlab-flowio","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Falterlab-flowio\u002FSKILL.md",true,[48],{"path":49,"resourceType":50,"resourceTypeDesc":51,"sizeBytes":52,"sourceHtmlUrl":53},"references\u002Fapi_reference.md","REFERENCE","参考文档",10481,"https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Falterlab-flowio\u002Freferences\u002Fapi_reference.md",[55,62,69,76,83,90],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M73D865CZME2FCMKA4PQM348","zarr-python","Chunked N-D arrays for cloud storage. Compressed arrays, parallel I\u002FO, S3\u002FGCS integration, NumPy\u002FDask\u002FXarray compatible, for large-scale scientific computing pipelines.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fzarr-python\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":18},"01M73D7Z64J4ABWZJD7P44XBBF","youtube-downloader","Download and process YouTube content for research. Use when: downloading competitor videos for analysis; extracting audio for podcasts; getting transcripts for content repurposing; archiving webinars; research content curation","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyoutube-downloader\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":18},"01M73D7K8778TGZV3GJFR3703D","yc-pitch-deck","Create a compelling startup pitch deck that follows the structure proven to raise billions from top investors. Master the YC and Sequoia formats that get founders funded. Use when: **Fundraising** to create investor pitch decks; **YC application** to structure your narrative; **Demo Day prep** to craft your 2-minute pitch; **Angel investors** to communicate your opportunity; **Partnership pitches** to structure compelling asks","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fyc-pitch-deck\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":18},"01M73D70KJSE0E8Z28YMNNRT04","x-twitter-scraper","Use when the user needs X (Twitter) data or confirmation-gated X actions through Xquik: tweet search, user lookup, follower extraction, media download, monitoring, webhooks, MCP, SDKs, posting, likes, DMs, and profile updates. Requires a Xquik API key. Never ask for X login material.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fx-twitter-scraper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":18},"01M73D6ED01GV077R7K4NZNFZJ","write-vignette","Create R package vignettes using R Markdown or Quarto. Covers vignette setup, YAML configuration, code chunk options, building and testing, and CRAN requirements for vignettes. Use when adding a Getting Started tutorial, documenting complex workflows spanning multiple functions, creating domain-specific guides, or when CRAN submission requires user-facing documentation beyond function help pages.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-vignette\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":18},"01M73D69YJR0BK3NFHE0CYG3EF","write-validation-documentation","Write IQ\u002FOQ\u002FPQ validation documentation for computerized systems in regulated environments. Covers protocols, reports, test scripts, deviation handling, and approval workflows. Use when validating R or other software for regulated use, preparing for a regulatory audit, documenting qualification of computing environments, or creating and updating validation protocols and reports for new or re-qualified systems.","https:\u002F\u002Fgithub.com\u002Froohe\u002Fagentic-super-skills\u002Fblob\u002Fmaster\u002Fskills_library\u002Fwrite-validation-documentation\u002FSKILL.md",[],[]]