Sovereign 8s.is mirror of standardgalactic/RNAkinetoScope
- Python 100%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
| src | ||
| pyproject.toml | ||
| README.md | ||
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 (
simulationmodule). - AnnData Base Functions: Modify AnnData structure, add new/old/total layers, and calculate cell-level statistics (
base_adatamodule). - Group-level Kinetics: Calculate CPM, transcription rates (alpha), degradation rates (gamma), and half-lives for cell groups. Includes options for imputation (
group_kineticsmodule). - Metacell Analysis: Generate metacells, calculate kinetics on metacell profiles, and add results back to AnnData objects (
metacellmodule). - Utilities: Helper functions for KNN-based imputation and dataset downsampling (
utilsmodule).
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: Containssimulate_kinetic_datafor generating test datasets.RNAkinetoScope.base_adata: Includesadd_new_old_layersfor setting up essential RNA count layers (new, old, total) andadd_ntr_statsfor calculating cell-level statistics like New-to-Total Ratio (NTR) and size factors, adding them toadata.obs.RNAkinetoScope.group_kinetics: Providesgroup_cpmfor calculating grouped Counts Per Million,calculate_group_kineticsfor estimating kinetic parameters (alpha, gamma, half-life) at the group level,calculate_imputed_group_kineticswhich adds an imputation step for half-life values, andcompute_and_save_kineticsas a wrapper to run calculations and save results.RNAkinetoScope.metacell: Contains functions for metacell analysis:get_metacells_for_clusterandmerge_metacells_all_clustersfor generating metacell expression profiles.calculate_metacell_kineticsthen uses these profiles to estimate kinetic parameters at the metacell resolution, including an imputation step.add_layer_from_dataframeis a utility to add DataFrame data as a new layer in AnnData, andadd_metacell_kinetics_to_layersspecifically adds the computed metacell kinetics back into the AnnData object.RNAkinetoScope.utils: Houses utility functions:impute_dataframefor KNN-based imputation of missing values in DataFrames,remove_unimputed_columnsto clean up DataFrames post-imputation, anddownsample_adata_by_groupfor reducing dataset size by sampling cells from specified groups.
License
This project is licensed under the MIT License.