FlowKit

repository·master·Indexed 42 days ago

https://github.com/whitews/flowkit

A Python toolkit for integrated manual and automated flow cytometry analysis workflows. It features full GatingML 2.0 support, FCS file handling (versions 2.0, 3.0, and 3.1), and comprehensive visualization capabilities including histograms and interactive scatter plots. FlowKit supports various transformations (Logicle, ArcSinh, Hyperlog, etc.), compensation using spillover matrices, and programmatic gating. It allows for the import/export of GatingML XML and provides limited FlowJo 10 workspace support.

Tokens
15.5K
Snippets
56
Records
87
Agent score
53%

What's inside FlowKit

  1. Overview of FlowKit features

    master

    FlowKit is a Python toolkit designed for flow cytometry analysis and visualization. Key capabilities include:

    • FCS File Handling: Read FCS versions 2.0, 3.0, and 3.1. Export data as new FCS 3.1 files, NumPy arrays, Pandas DataFrames, or CSV text files.
    • Compensation: Compensate events using spillover matrices from $SPILL or $SPILLOVER keywords, FlowJo tab-delimited text, NumPy arrays, or GatingML 2.0 spectrumMatrix XML elements.
    • Transformations: Supports Logicle, ArcSinh (Inverse hyperbolic sine), FlowJo Bi-exponential, Hyperlog, Logarithmic, Channel ratios, and Linear transforms.
    • Gating:
      • Full GatingML 2.0 support (Import/Export XML).
      • Limited FlowJo 10 workspace support (Linear, logarithmic, bi-exponential, and logicle transforms; Polygon, rectangle, ellipse, quadrant, and Boolean gates).
      • Programmatic creation of various gate types.
      • Retrieve gating results as a Pandas DataFrame.
    • Visualization: Provides histograms, contour density plots, interactive scatter plots, and interactive scatter plot matrices.
  2. Follow the Basic FlowKit Tutorial Series

    master

    FlowKit provides a structured learning path through a series of notebooks that cover the core object model and functional modules. The series progresses from basic class definitions to complex session and workspace management:

    1. Sample Class: Introduction to the fundamental data structures.
    2. Transforms Module & Matrix Class: Working with mathematical transformations and matrix operations.
    3. Gating Strategy & Gating Results: Understanding how to define and store gating logic and its outcomes.
    4. Gates Module: Using the gates module for population analysis.
    5. Session Class: Managing data sessions.
    6. Workspace Class: Organizing multiple sessions and data within a workspace.
  3. Install FlowKit from source

    master

    To install FlowKit from the source repository, clone the repository and ensure your pip is up-to-date before installing the local package.

    Note for macOS Apple Silicon users: You may need to upgrade pip prior to installation to ensure required dependencies install correctly.

    git clone https://github.com/whitews/flowkit
    cd flowkit
    pip install --upgrade pip
    pip install .
  4. Access FlowKit tutorials and advanced examples

    master

    FlowKit provides extensive learning resources through Jupyter notebooks:

    Tutorials

    Located in the docs/notebooks directory, these cover:

    • Part 1: Sample Class
    • Part 2: transforms Module & Matrix Class
    • Part 3: GatingStrategy & GatingResults Classes
    • Part 4: gates Module
    • Part 5: Session Class
    • Part 6: Workspace Class

    Advanced Examples

    Located in docs/notebooks/advanced, these include practical workflows such as:

    • Comparing Mean Fluorescence Intensity (MFI) in gated populations.
    • Replicating FlowJo 10 WSP analysis in FlowKit.
    • Boolean combinations of gates.
    • Dimension reduction on gated populations.
    • Clustering comparisons (Leiden vs Louvain).
    • Saving data as AnnData objects for ScanPy.
  5. Analyze samples and extract gated events as DataFrames

    master

    Before performing downstream analysis like clustering, you should analyze the samples within the workspace and then extract specific gated populations into pandas DataFrames. This allows you to filter for relevant cell populations (e.g., live single cells) and remove unwanted data like doublets or dead cells.

    1. Call workspace.analyze_samples(sample_group) to process the data.
    2. Use workspace.get_gate_events(sample_id, gate_name="...") to retrieve the events for a specific gate as a DataFrame.
    # 1. Analyze the samples in a specific group
    workspace.analyze_samples(sample_group)
    
    # 2. Extract events for a specific gate across multiple samples
    dfs = []
    for sample_id in sample_ids:
        df = workspace.get_gate_events(sample_id, gate_name="aAmine-")
        dfs.append(df)
  6. Initialize a FlowKit Workspace

    master

    To begin analyzing flow cytometry data, create a flowkit.Workspace object by providing the path to a FlowJo .wsp workspace file and the directory containing the .fcs sample files. This object serves as the central entry point for accessing sample groups, sample IDs, and gate hierarchies.

    import flowkit as fk
    import os
    
    base_dir = "../../../data/8_color_data_set/"
    sample_path = os.path.join(base_dir, "fcs_files")
    wsp_path = os.path.join(base_dir, "8_color_ICS.wsp")
    
    workspace = fk.Workspace(wsp_path, fcs_samples=sample_path)
  7. Explore Advanced FlowKit Examples

    master

    For complex workflows, FlowKit provides advanced notebooks covering specialized analysis tasks:

    • Clustering Comparison: Comparing Leiden vs. Louvain clustering algorithms.
    • Dimension Reduction: Performing dimensionality reduction specifically on gated populations.
    • MFI Comparison: Comparing Median Fluorescence Intensity (MFI) of gated events.
    • FlowJo Replication: Replicating .wsp (FlowJo Workspace) files.
    • Boolean Logic: Implementing boolean combinations of gates.
    • Scanpy Integration: Creating and using AnnData objects within the Scanpy ecosystem.
  8. Preprocess data for clustering and dimension reduction

    master

    To improve the performance of clustering algorithms (like Louvain or Leiden) and dimension reduction (like PaCMAP), follow these preprocessing steps:

    1. Column Selection: Filter the DataFrame to include only relevant marker channels (e.g., CD3, CD4, CD8) and exclude scatter or time channels.
    2. Subsampling: Use .sample(k) to reduce the dataset size and balance contributions from different samples. Ensure the subsample count is higher than the expected frequency of your target populations.
    3. Scaling: Use sklearn.preprocessing.StandardScaler to normalize the feature values before clustering.
    import pandas as pd
    from sklearn.preprocessing import StandardScaler
    
    # Define columns of interest
    cols_of_interest = ['CD3 APC-H7 FLR-A', 'CD4 PE-Cy7 FLR-A', 'CD8 PerCP-Cy55 FLR-A']
    
    # Subsample and filter
    k = 10_000
    X = pd.concat([df[cols_of_interest].sample(k) for df in dfs])
    
    # Scale the data
    scaler = StandardScaler()
    X_scaled = scaler.fit_transform(X)
  9. Understand GatingResults output structure

    master

    The GatingResults object returned by gate_sample contains a dictionary of results. For each gate, the result includes:

    • sample: The ID of the sample.
    • events: A boolean array (or DataFrame for BooleanGate) representing the events that passed the gate.
    • count: The number of events that passed the gate.
    • absolute_percent: The percentage of events passing the gate relative to the total sample event count.
    • relative_percent: The percentage of events passing the gate relative to the parent gate's event count.
    • gate_type: The type of gate applied.
    • parent: The ID of the parent gate (if applicable).
    • gate_path: The hierarchical path to the gate.

    Note on QuadrantGates: If a QuadrantGate is used, the results dictionary will contain sub-entries for each quadrant (q_id), each including its own sample, events, count, absolute_percent, relative_percent, and gate_type.

  10. How GML gates work and their relationship to parent classes

    master

    GML (GatingML) gate classes are specialized internal implementations used to convert XML-based GatingML elements into an intermediate gate representation.

    Key characteristics of GML gates:

    • Tree Assembly: Unlike standard gate classes, GML gates retain a parent reference, which is used to assemble the gate tree from XML data.
    • Conversion: GML gates provide a convert_to_parent_class() method. This method should be called to transform the GML-specific instance into its corresponding public-facing parent class (e.g., converting a GMLRectangleGate into a RectangleGate) for use in a GatingStrategy.
  11. How BooleanGates and QuadrantGates are handled

    master

    The GatingStrategy handles different gate types with specific logic during the gate_sample process:

    • BooleanGate: These gates require a DataFrame of results from their referenced gates (gate_refs). The strategy retrieves the events from each reference and passes them as a pd.DataFrame to the gate's apply method.
    • QuadrantGate: These gates split the results into multiple quadrants. When a gate's parent is a QuadrantGate, the strategy correctly resolves the quadrant-specific results to ensure hierarchical gating (logical AND between parent quadrant and child gate) is maintained.
    • Standard Gates: For other gate types, the strategy performs event pre-processing (compensation and transformation) before calling the gate's apply method.