Pycytominer

repository·main·Indexed 40 days ago

https://github.com/cytomining/pycytominer

A Python toolkit for processing high-dimensional readouts from high-throughput image-based profiling experiments. It transforms single-cell morphology features into analysis-ready profiles through a five-step pipeline: Aggregate, Annotate, Normalize, Feature select, and Consensus. Built on pandas, it supports Apache Parquet, AnnData, and CellProfiler data structures.

Tokens
16.7K
Snippets
39
Records
64
Agent score
49%

What's inside Pycytominer

  1. Explore the pycytominer API modules

    main

    The pycytominer API is organized into several functional modules that handle different stages of the image-based profiling data processing pipeline. The core modules are:

    • pycytominer.aggregate: For aggregating data.
    • pycytominer.annotate: For annotating data.
    • pycytominer.normalize: For normalizing data.
    • pycytominer.feature_select: For feature selection.
    • pycytominer.consensus: For consensus-based analysis.
    • pycytominer.cyto_utils: Utility functions for cytomining operations.

    Most functions within these modules accept either a pandas.DataFrame or a file path as input.

  2. What is ProfileSchema?

    main
    A ProfileSchema is a lightweight dataclass designed to store resolved metadata and feature column names without wrapping the actual profile data itself. It is used internally to avoid repeatedly inferring metadata and feature columns across core function calls. It is designed to be independent of data containers like pandas, Polars, CytoDataFrame, or AnnData, allowing different containers to adopt the same schema.
  3. What is CytoDataFrame and how does it integrate with Pycytominer?

    main

    CytoDataFrame is a cytomining library that provides an in-memory data format for single-cell profiles alongside their corresponding images and segmentation masks.

    In Pycytominer v1.8+, core functions accept CytoDataFrame as input in addition to str or pd.DataFrame. CytoDataFrame stores or exposes a ProfileSchema so that schema inference is shared between the CytoDataFrame object and Pycytominer's standalone function API.

  4. How the Pycytominer pipeline works

    main

    Pycytominer is a toolkit for processing high-dimensional readouts from high-throughput image-based profiling experiments. It sits between feature extraction and downstream analysis.

    The Workflow:

    1. Feature Extraction: Image data flows from a microscope to segmentation and feature extraction tools like CellProfiler or DeepProfiler.
    2. Harmonization: Single-cell readouts are curated into a manageable form. For CellProfiler, it is recommended to use CytoTable to harmonize outputs before Pycytominer processing. For DeepProfiler, Pycytominer provides utilities in pycytominer.cyto_utils.
    3. Pycytominer Processing: Pycytominer performs five fundamental functions (Aggregate, Annotate, Normalize, Feature select, and Consensus) to process morphology features.
    4. Downstream Analysis: The outputs are used for machine learning models and statistical testing to derive biological insights.
  5. Collate CellProfiler CSVs using `cyto_utils.collate`

    main

    When running images on a cluster, you may have many individual folders containing Image.csv, Nuclei.csv, etc. To process full plates, you must collate these into a single file (currently SQLite) per plate.

    This is performed using the pycytominer.cyto_utils.collate function.

    Note: This functionality depends on the deprecated cytominer-database package. To use it, ensure you install Pycytominer with the [collate] extra to pin cytominer-database==0.3.4.

  6. Use the high-level Pycytominer API instead of operations modules

    main
    The pycytominer.operations modules (such as correlation_threshold, frequency_threshold, get_na_columns, transform, and variance_threshold) contain the low-level logic used by the library. It is not recommended to interact with these functions directly. Instead, you should use the core Pycytominer API, which orchestrates these operations internally to perform data processing workflows.
  7. Supported data formats and frameworks

    main

    Pycytominer is built on top of pandas and supports several data formats:

    • Core Formats: Apache Parquet, Parquet dataset directories, and compressed text (e.g., .csv.gz).
    • AnnData Support: You can use anndata (specifically h5ad or zarr) by installing the extra dependency: pip install pycytominer[anndata].
    • CellProfiler Integration: Pycytominer supports CellProfiler data structures directly, recognizing Metadata_ prefixes for experimental details and compartment prefixes (e.g., Cells_, Cytoplasm_, Nuclei_, or custom ones like Mito_) for morphology features.

    Note on Image Payloads: If using Parquet-backed CytoTable or anndata with OME-Arrow image payload columns, Pycytominer supports numeric Image_* measurements. However, normalize() only accepts numeric feature columns, and non-normalized image payload columns are preserved in outputs rather than transformed.

  8. Getting started with pycytominer tutorials

    main

    If you are new to pycytominer, use the learning-oriented tutorials to understand the pipeline concepts step by step. These tutorials use small synthetic datasets to help you focus on the underlying logic and the why behind each processing decision without the overhead of managing large real-world datasets.

    Available tutorials include:

    • Introduction to pycytominer: A foundational guide to the library.
    • Single cell QC profiling: A tutorial focused on quality control workflows for single-cell data.

    Once you have mastered these concepts, you can transition to the task-focused walkthrough guides for more advanced goals.

  9. Install Pycytominer with extra dependencies

    main

    Depending on your required functionality, you may need to install specific extras:

    • For CellProfiler CSV collation (collate function): Requires cytominer-database==0.3.4.
      • pip install "pycytominer[collate]"
      • Or for a specific commit: pip install "pycytominer[collate] @ git+https://github.com/cytomining/pycytominer@<commit_hash>"
    • For Cell Location lookup tables (cell_locations functionality):
      • pip install "pycytominer[cell_locations]"
    # Install with collation support
    pip install "pycytominer[collate]"
    
    # Install with cell location support
    pip install "pycytominer[cell_locations]"
  10. Install Pycytominer via pip, conda, or Docker

    main

    Pycytominer can be installed using several different package managers depending on your environment:

    pip

    Install directly from PyPI:

    pip install pycytominer

    conda

    Install from the conda-forge channel:

    conda install -c conda-forge pycytominer

    Docker

    Container images are available on Docker Hub. You can run modules directly, start interactive sessions, or map local directories to run scripts inside the container.

    Run a module:

    docker run --platform=linux/amd64 cytomining/pycytominer:latest python -m pycytominer.<module_name>

    Interactive bash session (specific commit):

    docker run -it --platform=linux/amd64 cytomining/pycytominer:pycytominer-1.1.0.post16.dev0_b1bb292 bash

    Run a local script (mapping current directory to /opt):

    docker run -v $PWD:/opt --platform=linux/amd64 cytomining/pycytominer:pycytominer-1.1.0.post16.dev0_b1bb292_240417 python /opt/script.py
    pip install pycytominer
  11. Use the CytoDataFrame fluent pipeline (v2.0+)

    main

    In version 2.0 and later, Pycytominer introduces a fluent API via the CytoDataFrame object. This allows you to chain pipeline methods together. Because it leverages Polars LazyFrame, the entire chained pipeline can execute as a single optimized query plan rather than materializing intermediate DataFrames at each step. Use .collect() at the end of the chain to execute the pipeline and return the result.

    import pycytominer as pm
    
    result = (
        pm.CytoDataFrame(profiles)
        .aggregate(strata=["Metadata_Well"])
        .normalize(method="standardize", samples="Metadata_treatment == 'DMSO'")
        .feature_select(operations=["variance_threshold", "correlation_threshold"])
        .collect()
    )
  12. Use Pycytominer in Python scripts

    main

    The primary way to use Pycytominer is via its Python API. Most functions accept either a pandas.DataFrame or a file path as input.

    Common tasks include:

    • Normalization: Use pycytominer.normalize() to standardize profiles. You can specify a method (e.g., 'standardize') and a samples string to define the control group (e.g., "Metadata_treatment == 'control'").
    • Loading CytoTable profiles: Use pycytominer.cyto_utils.load_profiles() to load a profile table directory, or load_cytotable_profiles() as a convenience helper for specific table names within a warehouse root.
    import pandas as pd
    import pycytominer
    
    # Example: Normalizing a dataset
    df = pd.read_csv("path/to/profiles.csv.gz")
    normalized_df = pycytominer.normalize(
        profiles=df,
        method="standardize",
        samples="Metadata_broad_sample == 'DMSO'"
    )
    
    # Example: Loading CytoTable profiles
    from pycytominer import normalize
    from pycytominer.cyto_utils import load_cytotable_profiles, load_profiles
    
    profiles_from_helper_df = load_cytotable_profiles(
        "path/to/warehouse_root",
        table_name="joined_profiles",
    )
    
    normalized_df = normalize(
        profiles=profiles_from_helper_df.assign(
            Metadata_treatment=["control" if i % 2 == 0 else "drug" for i in profiles_from_helper_df["Metadata_ImageNumber"]]
        ),
        samples="Metadata_treatment == 'control'",
        method="standardize",
    )