Sovereign 8s.is mirror of standardgalactic/RNAkinetoScope
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
2026-03-18 15:27:09 +08:00
src Update group_kinetics.py 2026-03-18 15:27:09 +08:00
pyproject.toml Initial commit of RNAkinetoScope 2025-05-06 10:53:56 -04:00
README.md Update README.md 2026-03-16 17:28:33 +08:00

RNAkinetoScope

RNAkinetoScope is a Python package designed for the analysis of single-cell metabolic labeling data. It provides a modular suite of tools for estimating RNA kinetics both at group and metacell levels.

Features

  • Data Simulation: Generate synthetic datasets with defined kinetic parameters (simulation module).
  • AnnData Base Functions: Modify AnnData structure, add new/old/total layers, and calculate cell-level statistics (base_adata module).
  • Group-level Kinetics: Calculate CPM, transcription rates (alpha), degradation rates (gamma), and half-lives for cell groups. Includes options for imputation (group_kinetics module).
  • Metacell Analysis: Generate metacells, calculate kinetics on metacell profiles, and add results back to AnnData objects (metacell module).
  • Utilities: Helper functions for KNN-based imputation and dataset downsampling (utils module).

Installation

To install the package locally, navigate to the RNAkinetoScope directory (the one containing pyproject.toml) and run:

git clone git@github.com:hongjie7/RNAkinetoScope.git
cd RNAkinetoScope
pip install .

For editable (development) mode:

pip install -e .

This package requires Python >= 3.10.

Dependencies

The core dependencies are:

  • numpy
  • pandas
  • scanpy
  • anndata
  • scipy
  • scikit-learn

These will be installed automatically when you install RNAkinetoScope.

Usage Example

import RNAkinetoScope as rks
import scanpy as sc # For AnnData related operations

# --- 1. Simulate Data ---
# (from RNAkinetoScope.simulation)
sim_adata = rks.simulate_kinetic_data(
    n_cells=500,
    n_genes=1000,
    n_cell_types=2,
    label_time=240, # minutes
    random_state=42
)
print("Simulated AnnData:")
print(sim_adata)
print(f"Default label time constant: {rks.DEFAULT_LABEL_TIME}")


# --- 2. Add NTR stats to AnnData ---
# (from RNAkinetoScope.base_adata)
# Ensure 'new' and 'total' layers exist from simulation or prior processing
sim_adata = rks.add_ntr_stats(
    adata=sim_adata,
    new_layer='new',
    total_layer='total'
)
print("\nAnnData with NTR stats in .obs:")
print(sim_adata.obs.head())

# --- 3. Calculate Group Kinetics ---
# (from RNAkinetoScope.group_kinetics)
try:
    # This function returns a tuple, here we expect 5 DataFrames as per default return_values
    kinetics_results = rks.calculate_group_kinetics(
        t=240, # labeling time in minutes
        adata=sim_adata,
        groupby='cell_type', # from sim_adata.obs
        new_layer='new',     # from sim_adata.layers
        total_layer='total'  # from sim_adata.layers
    )
    # Unpack based on the default return_values: ["alpha", "gamma", "halflife", "R", "total_CPM"]
    alpha_df, gamma_df, halflife_df, r_df, total_cpm_df = kinetics_results

    print("\nGroup Alpha values (head):")
    print(alpha_df.head())
except Exception as e:
    print(f"Error in group kinetics: {e}")
    import traceback
    traceback.print_exc()

# --- 4. Calculate Metacell Kinetics ---
# (from RNAkinetoScope.metacell)
# This function performs metacell generation and then calculates kinetics.
# It requires 'X_pca' in adata.obsm for neighbor finding (created by simulate_kinetic_data).
try:
    meta_alpha, meta_gamma, meta_halflife = rks.calculate_metacell_kinetics(
        adata=sim_adata,
        groupby='cell_type',
        t=240,
        n_neighbors=10,      # For metacell construction
        use_rep="X_pca",
        new_layer='new',
        total_layer='total',
        impute_k=5,         # For half-life imputation within clusters
        impute_nan_cutoff=0.5
    )
    print("\nMetacell Alpha values (head):")
    print(meta_alpha.head())

    # Add these metacell kinetics as layers
    # (from RNAkinetoScope.metacell - specifically add_metacell_kinetics_to_layers)
    sim_adata_with_meta_kinetics = rks.add_metacell_kinetics_to_layers(
        sim_adata.copy(), # Work on a copy
        meta_alpha,
        meta_gamma,
        meta_halflife,
        layer_prefix="meta_" # e.g., creates 'meta_alpha' layer
    )
    print("\nAnnData with metacell kinetic layers:")
    print(sim_adata_with_meta_kinetics)
    print(f"Available layers: {list(sim_adata_with_meta_kinetics.layers.keys())}")

except Exception as e:
    print(f"Error in metacell kinetics: {e}")
    import traceback
    traceback.print_exc()

# --- 5. Downsample data ---
# (from RNAkinetoScope.utils)
try:
    adata_downsampled = rks.downsample_adata_by_group(
        adata=sim_adata,
        groupby='cell_type',
        n_cells_per_group=50,
        random_state=42
    )
    print("\nDownsampled AnnData:")
    print(adata_downsampled)
except Exception as e:
    print(f"Error in downsampling: {e}")


Module Overview

  • RNAkinetoScope.__init__: Exposes the main functions from submodules for easy access.
  • RNAkinetoScope._constants: Defines shared constants like default labeling times and CPM factors.
  • RNAkinetoScope.simulation: Contains simulate_kinetic_data for generating test datasets.
  • RNAkinetoScope.base_adata: Includes add_new_old_layers for setting up essential RNA count layers (new, old, total) and add_ntr_stats for calculating cell-level statistics like New-to-Total Ratio (NTR) and size factors, adding them to adata.obs.
  • RNAkinetoScope.group_kinetics: Provides group_cpm for calculating grouped Counts Per Million, calculate_group_kinetics for estimating kinetic parameters (alpha, gamma, half-life) at the group level, calculate_imputed_group_kinetics which adds an imputation step for half-life values, and compute_and_save_kinetics as a wrapper to run calculations and save results.
  • RNAkinetoScope.metacell: Contains functions for metacell analysis: get_metacells_for_cluster and merge_metacells_all_clusters for generating metacell expression profiles. calculate_metacell_kinetics then uses these profiles to estimate kinetic parameters at the metacell resolution, including an imputation step. add_layer_from_dataframe is a utility to add DataFrame data as a new layer in AnnData, and add_metacell_kinetics_to_layers specifically adds the computed metacell kinetics back into the AnnData object.
  • RNAkinetoScope.utils: Houses utility functions: impute_dataframe for KNN-based imputation of missing values in DataFrames, remove_unimputed_columns to clean up DataFrames post-imputation, and downsample_adata_by_group for reducing dataset size by sampling cells from specified groups.

License

This project is licensed under the MIT License.