Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

bio-expression-matrix-sparse-handling

БесплатноЗапускает вложенные скриптыНе проверен

Stores and operates on sparse expression matrices for single-cell and large bulk RNA-seq, covering dgCMatrix/dgRMatrix/dgTMatrix when-each-is-fast, the…

lilinjiот lilinji★ 18 звёзд на GitHub

Об этом скилле

Version Compatibility

Reference examples tested with: numpy 1.26+, scipy 1.12+, pandas 2.2+, anndata 0.10+, scanpy 1.10+, Matrix R package 1.6+, HDF5Array 1.30+ (Bioconductor), DelayedArray 0.28+, zellkonverter 1.12+, zarr-python 2.18+, dask 2024.1+

Before using code patterns, verify installed versions match. If versions differ:

  • Python: pip show <package> then help(module.function) to check signatures
  • R: packageVersion('<pkg>') then ?function_name to verify parameters

If code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.

Sparse Matrix Handling

"Store / compute on a single-cell matrix without blowing up memory" -> Pick the sparse format that matches the access pattern (CSC for column ops, CSR for row ops), respect the R/Python convention difference (Bioconductor stores cells in columns; AnnData stores cells in rows), and use HDF5/Zarr backed mode for matrices too large for RAM.

The Single Most Important Modern Insight -- The R/Python interop transpose is silent and catastrophic

R Bioconductor (Seurat, SingleCellExperiment) stores cells in COLUMNS and uses dgCMatrix (Column-Compressed Sparse). Python scverse (AnnData, scanpy) stores cells in ROWS and defaults to CSR (Compressed Sparse Row). Round-tripping with anndata2ri, zellkonverter, or rpy2 triggers a TRANSPOSE under the hood -- once per direction. Two flips silently cancel. A debugging session that converts back and forth multiple times can end up with mysteriously transposed data and no error.

Conversion Implicit transpose
Python CSR -> R dgCMatrix YES (rows <-> cols)
AnnData .X (cells x genes) -> SingleCellExperiment counts (genes x cells) YES
Seurat @assays$RNA@counts (genes x cells) -> AnnData .X (cells x genes) YES
scipy.sparse.csr_matrix(dense) None (just format conversion)
csr.tocsc() / csc.tocsr() None (semantically same matrix, different layout)

The safe pattern for one-shot conversions: file-based intermediate. adata.write('file.h5ad') then zellkonverter::readH5AD('file.h5ad') -- avoids the in-memory rpy2/reticulate gymnastics, and the file roundtrip makes orientation explicit.

For a 1M-cell single-cell matrix, the implicit transpose is non-trivial -- minutes of wall time and a temporary memory peak roughly equal to nnz x 12 bytes (CSC) or x 16 bytes (CSR with int64). Avoid unnecessary transposes by aligning the format to the consumer.

Two adjacent insights:

  1. Sparse becomes inefficient above ~10-15% density. Sparse iteration has cache-unfriendly indirection; dense iteration is sequential. Above ~10-15% nonzero, dense is often faster for most operations even though it uses more memory.
  2. AnnData backed mode quietly differs from in-memory in important ways. sc.read_h5ad('file.h5ad', backed='r') returns an AnnData where .X is a wrapped HDF5 dataset, read-only. Many scanpy functions silently load to memory; some functions error or hang on backed mode.

Algorithmic Taxonomy

Format Layout Fast for Slow for
dgCMatrix (CSC, R) i (row indices), p (col pointers), x (values) Column slicing; per-cell ops in single-cell (cells in cols); matrix-vector with col vector Row slicing
dgRMatrix (CSR, R) j (col indices), p (row pointers), x (values) Row slicing; per-gene ops when genes in rows Column slicing
dgTMatrix (COO, R triplet) i, j, x Random insertion when building; reading MTX Most operations -- convert to dgCMatrix after build
scipy csc_matrix Same as dgCMatrix Column ops in Python Row ops
scipy csr_matrix Same as dgRMatrix Row ops (NumPy convention); matmul; sklearn defaults Column ops
scipy coo_matrix Triplet (i, j, data) Construction; MTX I/O Most ops -- convert after build
HDF5 (h5ad, h5) Single-file binary chunked Random access via chunks; compression; widely supported Cloud / parallel writes
Zarr Chunked array, per-chunk file (or S3 object) Cloud-native; parallel writes; Dask integration Single-file simplicity
DelayedArray + HDF5Array Bioc lazy evaluation over HDF5 Out-of-memory bulk ops in R Speed of in-memory

Decision Tree by Scenario

Scenario Recommended approach
Single-cell (>10k cells), per-cell ops dgCMatrix in R (Bioconductor); CSR adata.X in Python (scanpy)
Bulk RNA-seq (60-80% density) Dense -- sparse overhead exceeds benefit
Single-cell pseudobulk (after donor aggregation) Dense -- now 60-80% density typically
1M+ cells, can't fit in RAM scanpy backed mode OR HDF5SummarizedExperiment + DelayedArray
TCGA + GTEx + recount3 scale (100k+ samples) HDF5Array / Zarr + Dask
10X CellRanger 3.0+ output sc.read_10x_h5() or Read10X_h5() -- the .h5 is faster than the .mtx tr
Полный SKILL.md на GitHub

Установить bio-expression-matrix-sparse-handling в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

examples/sparse_operations.pyusage-guide.md

FAQ

Что делает скилл bio-expression-matrix-sparse-handling?

Stores and operates on sparse expression matrices for single-cell and large bulk RNA-seq, covering dgCMatrix/dgRMatrix/dgTMatrix when-each-is-fast, the dgCMatrix (CSC, R) <-> CSR (Python) implicit transpose, AnnData (cells-rows) <-> SingleCellExperiment (cells-cols) orientation flip, HDF5/h5ad vs Zarr cloud-native shift, HDF5SummarizedExperiment + DelayedArray for out-of-memory bulk, scanpy backed mode for large h5ad, the ~10-15% density crossover where dense beats sparse, 10X format proliferation (MTX vs CellRanger H5 vs h5ad), the dense-conversion memory blow-up, and Dask + Zarr for consortium-scale matrices. Use when choosing sparse format, working with single-cell-sized matrices, importing/exporting 10X, debugging R/Python interop transposes, processing matrices too large for RAM, or building cloud-native pipelines.

Как установить скилл bio-expression-matrix-sparse-handling?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл bio-expression-matrix-sparse-handling запускает скрипты?

Да, скилл несёт исполняемые скрипты. Проверь исходник перед установкой.

Похожие скиллы

Сравнить bio-expression-matrix-sparse-handling с