Bulk Rnaseq
K-DenseCommunityCreated by K-Dense Inc.
- Skill
- Workflow
- Science and research
- MIT
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The bulk-rnaseq skill provides a structured, defensible pipeline for bulk RNA-seq analysis. It manages the transition from raw sequencing reads to a gene-level counts matrix, ensuring reproducibility through version pinning and quality-gated steps. The skill supports two primary paths: an automated nf-core/rnaseq pipeline for scalable, standardized analysis, and a manual standalone path using STAR, Salmon, or featureCounts for transparency in constrained environments. It concludes with a bridge script that generates a counts matrix and metadata template specifically formatted for PyDESeq2, while emphasizing the importance of experimental design, biological replication, and rigorous QC.
What it does
- Validates samplesheets and experimental design to prevent common analysis failures.
- Automates raw-read QC, trimming, and alignment using industry-standard tools.
- Provides a bridge to convert Salmon, STAR, or featureCounts output into integer counts.
- Generates provenance records for all quantification steps to ensure reproducibility.
- Supports integration with downstream skills for differential expression and pathway enrichment.
- Enforces strict quality-gating and strandedness verification throughout the pipeline.
When to use it
- When you need to process bulk RNA-seq data from FASTQ files to a gene-level counts matrix.
- When you want to run or configure the nf-core/rnaseq pipeline.
- When you need to prepare a counts matrix for PyDESeq2 differential expression analysis.
- When you are designing a bulk RNA-seq experiment and need to ensure statistical soundness.
- When you require a reproducible, audited workflow for academic or clinical research.
Advantages
- Promotes reproducibility through pinned tool versions and containerized environments.
- Reduces errors by validating samplesheets and quantification outputs before downstream analysis.
- Offers flexibility between automated pipeline execution and manual, step-by-step control.
- Provides a clear, standardized handoff to PyDESeq2 and pathway enrichment tools.
- Includes comprehensive guidance on experimental design to avoid common pitfalls like batch confounding.
Usage examples
- “I have a set of FASTQ files and need to run a standard RNA-seq pipeline. How do I start?”
- The agent will guide you through validating your samplesheet and using the nf-core/rnaseq pipeline (Path A) for a standardized, audited analysis.
- “How do I convert my Salmon quantification output into a counts matrix for PyDESeq2?”
- The agent will instruct you to use the build_counts_matrix.py script to aggregate your quant.sf files into a gene-level counts.csv and metadata_template.csv.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/k-dense-ai/bulk-rnaseq/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip bulk-rnaseq.zip -d .agents/skills
Documentation by K-Dense Inc.
Bulk RNA-seq
Overview
This skill prepares bulk RNA-seq reads and quantification output for a reproducible gene-level comparison. It owns sample validation, reads-to-counts recipes, and the count/metadata handoff; downstream statistical fitting and enrichment remain in their specialist skills.
"Defensible" means three things, applied throughout:
Reproducible — pinned pipeline/tool versions, containers where possible, recorded parameters, fixed random seeds.
Quality-gated — QC is inspected and acted on before, during, and after quantification, not skipped.
Statistically sound — adequate replication, a design that matches the biology, counts handled correctly, and FDR-controlled testing.
The pipeline is: FastQC/trim → align/quant (STAR/Salmon) → counts → DE (pydeseq2) → enrichment (pathway-enrichment) → figures.
When to Use This Skill
Use this skill when the user wants to:
Go from FASTQ files (or a sequencing run) to differentially expressed genes and pathways.
Run or configure
nf-core/rnaseq, or align/quantify with STAR, Salmon, or featureCounts.Turn Salmon/STAR/featureCounts output into a counts matrix ready for DESeq2/PyDESeq2.
Design or sanity-check a bulk RNA-seq experiment (replicates, batch, strandedness) before committing compute.
Scope an end-to-end RNA-seq analysis and decide which tools and skills to chain.
This is bulk RNA-seq (samples = biological specimens). For single-cell/nuclei data use scanpy; for the DE statistics alone use pydeseq2; for enrichment alone use pathway-enrichment.
The Pipeline at a Glance
flowchart TD
fastq["Raw FASTQ + samplesheet"] --> qc["FastQC + MultiQC"]
qc --> trim["Trim: fastp / Trim Galore"]
trim --> align["Align + quant: STAR and/or Salmon"]
align --> counts["Gene-level counts matrix"]
counts --> de["Differential expression"]
de --> enrich["Pathway / GSEA enrichment"]
de --> fig["Figures"]
enrich --> fig
nfcore["nf-core/rnaseq via nextflow skill"] -.->|"path A"| align
manual["Standalone recipes (this skill)"] -.->|"path B"| align
bridge["build_counts_matrix.py (this skill)"] -.-> counts
pydeseq2skill["pydeseq2 skill"] -.-> de
pwskill["pathway-enrichment skill"] -.-> enrich
vizskill["scientific-visualization skill"] -.-> figTwo Upstream Paths — Pick One
The reads → counts stage can be run two ways. Both produce gene-level counts, but STAR/featureCounts and Salmon/tximport do not generally give identical or interchangeable values: assignment rules, multimapping, and effective-length corrections differ. Choose one quantification route for the entire comparison.
Use Path A — nf-core/rnaseq when… | Use Path B — standalone tools when… |
|---|---|
| You want the field-standard, audited, citable pipeline with one command | You have a few samples and want to learn/inspect each step |
| Many samples, or you'll scale to HPC/cloud | No Nextflow/containers available, or a constrained environment |
| Reproducibility and a full MultiQC report matter most | You need a non-standard step the pipeline doesn't expose |
→ Drive it through the nextflow skill | → Follow references/upstream-manual.md |
When unsure, prefer Path A: nf-core/rnaseq already wires together FastQC → trimming → STAR/Salmon → quantification → tximport → MultiQC with sensible, reviewed defaults, which is the most defensible option. Path B exists for transparency and constrained setups.
Both paths converge on a gene-level counts matrix. Preserve whether counts are raw or length-scaled, the transcript-to-gene mapping release, and any offsets. Length-scaled counts must not receive a second transcript-length correction.
Setup
# This skill's glue (bridge + handoffs) — Python
uv pip install "pytximport==0.13.0" pandas numpy
# Downstream skills install their own deps:
# pydeseq2 skill -> uv pip install pydeseq2
# pathway-enrichment skill -> uv pip install gseapy gprofiler-official
# Path A (nf-core): only Nextflow + a container engine are needed — see the `nextflow` skill.
# Path B (standalone tools): install via bioconda. Pin versions for reproducibility.
conda create -n rnaseq -c conda-forge -c bioconda --strict-channel-priority \
fastqc fastp trim-galore "star=2.7.11b" "salmon=2.8.0" subread multiqcReviewed against nf-core/rnaseq 3.27.0, STAR 2.7.11b documentation, Salmon 2.8.0, pytximport 0.13.0 and PyDESeq2 0.5.4. The bundled Python bridge and a tiny Salmon index/quant run were executed; the full Nextflow/STAR/trimming recipes are illustrative, not an end-to-end validation. Salmon 2.x cannot read older C++ indexes: rebuild them. The bridge's length-scaled Salmon route is for full-length bulk RNA-seq; 3′ counting assays need original counts without transcript-length correction.
Record the exact versions you use (pipeline revision, tool versions, reference genome + annotation release) — they belong in the methods section and make the analysis reproducible.
Version 2.0 makes STAR strandedness explicit and rejects ambiguous samples, gene sets, transcript mappings and fractional featureCounts data that older bridge versions accepted.
Quick Start
Path A — nf-core/rnaseq (recommended)
# 0. Validate the samplesheet first (catches the most common failures early)
python scripts/validate_samplesheet.py --samplesheet samplesheet.csv --nfcore
# 1. Smoke-test the environment with tiny bundled data
nextflow run nf-core/rnaseq -r 3.27.0 -profile test,docker --outdir test_results
# 2. Real run: pin the revision, pick an aligner, pass a samplesheet + reference
nextflow run nf-core/rnaseq -r 3.27.0 \
-profile docker \
--input samplesheet.csv \
--genome GRCh38 \
--aligner star_salmon \
--outdir results \
-resumenf-core/rnaseq runs tximport internally, so gene counts come out already merged — no bridge script needed. Use results/star_salmon/salmon.merged.gene_counts_length_scaled.tsv for DE. Samplesheet format, aligner choice, and outputs: references/upstream-nfcore.md. For engine/HPC/cloud/container detail, use the nextflow skill.
Path B — standalone STAR/Salmon (abbreviated)
mkdir -p qc/
fastqc -o qc/ reads/*.fastq.gz # 1. QC raw reads
fastp -i s1_R1.fq.gz -I s1_R2.fq.gz \
-o s1_R1.trim.fq.gz -O s1_R2.trim.fq.gz \
--thread 4 -j s1.fastp.json # 2. Trim adapters/low-quality
salmon quant -i salmon_index -l A \
-1 s1_R1.trim.fq.gz -2 s1_R2.trim.fq.gz \
--gcBias --seqBias -p 8 -o quant/s1 # 3. Quantify (per sample)Full recipes (FastQC, fastp/Trim Galore, STAR index+align+--quantMode GeneCounts, Salmon decoy-aware index, featureCounts, strandedness): references/upstream-manual.md.
Counts → DE → enrichment (both paths)
# Path B only: assemble a gene x sample counts matrix + metadata template for PyDESeq2
python scripts/build_counts_matrix.py --from salmon \
--quant-dir quant/ --tx2gene tx2gene.tsv --output-dir counts/
# Then hand off (see the dedicated skills):
# pydeseq2: counts.csv + metadata.csv -> DE table (log2FC, padj, stat)
# pathway-enrichment: rank by `stat` (GSEA) or padj+|LFC| hit list (ORA)
# scientific-visualization / matplotlib: volcano, MA, heatmap, PCA, enrichment dotplotStage-by-Stage Workflow
Work top to bottom. Each stage names the skill or file that owns the detail. Don't skip the design/QC stages — they are where bulk RNA-seq studies most often go wrong.
Design & sample sheet. Confirm ≥3 biological replicates per group, identify batch/confounders, and choose the comparison(s). Build the samplesheet and validate it with
scripts/validate_samplesheet.py. Rationale and rules:references/design-and-qc.md.Raw-read QC. FastQC per file; aggregate with MultiQC. Check per-base quality, adapter content, duplication, and over-representation. Thresholds:
references/design-and-qc.md.Trimming. Remove adapters and low-quality tails (via
fastporTrim Galore). Re-run FastQC to confirm. Recipes:references/upstream-manual.md(Path A does this for you).Align / quantify. STAR (genome alignment +
--quantMode GeneCounts) and/or Salmon (decoy-aware selective alignment). Determine strandedness — the wrong convention can silently discard most assigned reads. Detail:references/upstream-manual.md; pipeline params:references/upstream-nfcore.md.Build the counts matrix. Turn quant output into a gene × sample integer matrix and a metadata template (
scripts/build_counts_matrix.py). The estimated-count and gene-ID-mapping nuances live inreferences/counts-and-handoff.md.Differential expression →
pydeseq2skill. Loadcounts.csv+metadata.csv, set the design (e.g.~batch + condition), check full rank and residual degrees of freedom, fit, and test an explicit contrast (e.g. treated versus control) with FDR control. Inspect the PCA and p-value histogram as QC.Enrichment →
pathway-enrichmentskill. For GSEA, rank the full gene list by the DESeq2stat; for ORA, pass the thresholded hit list (padj < 0.05, optionally |log2FC| > 1). Match identifiers to the selected library; retain an auditable mapping and an assay-specific ORA background.Figures →
scientific-visualizationskill. Volcano, MA, sample-distance heatmap, PCA, and enrichment dotplots, plus the MultiQC report for the QC narrative.
The counts → DE bridge (the key glue)
This is the one stage with no upstream/downstream skill, so this skill owns it. scripts/build_counts_matrix.py converts quant output into exactly what pydeseq2 expects:
Salmon (
--from salmon): aggregates per-samplequant.sfto gene level withpytximportusingcounts_from_abundance="length_scaled_tpm"(an offset-free choice for full-length gene-level DE), needs atx2genemap.STAR (
--from star): reads eachReadsPerGene.out.tab, selecting the column for your--strandedness(unstranded/forward/reverse).featureCounts (
--from featurecounts): parses the combinedfeatureCountsmatrix.
It writes counts.csv (genes × samples, integers), counts_provenance.json (input hashes, import mode and sample order), and metadata_template.csv (one row per sample) for you to fill in. Salmon/RSEM counts are estimates (non-integer); they are rounded to integers because PyDESeq2 requires integer counts — see references/counts-and-handoff.md for why this is acceptable with length_scaled_tpm and how it differs from the offset-based DESeq2+tximport route. That reference also covers identifier mapping (when required by the selected enrichment library) and the exact orientation PyDESeq2 wants.
Common Pitfalls
These cause most wrong or irreproducible bulk RNA-seq results:
Too few replicates. Plan biological replication from expected variability and effect size; three per group is a starting point, not a power guarantee. Technical lanes do not increase biological sample size.
Confounded batch and condition. If every treated sample was processed on a different day/lane than controls, the effect is unrecoverable. Randomize, and model known batches (
~batch + condition). Seereferences/design-and-qc.md.Wrong strandedness. Choosing the wrong STAR column or featureCounts
-s/Salmon library type can discard most assigned reads; there is no universal 50% loss. Use Salmon-l Aor infer strandedness, and verify the assigned-reads fraction.Feeding TPM/FPKM to DESeq2. DESeq2 needs raw (or length-scaled) counts, never TPM/FPKM/normalized values. The bridge handles this.
Non-integer counts. The bridge rounds length-scaled Salmon estimates only; it rejects fractional featureCounts values rather than truncating them. Its Salmon route is for full-length assays, not 3′ tag counts.
Gene-ID mismatch into enrichment. Match gene IDs to the selected organism and gene-set release. Many GMT libraries use symbols; g:Profiler can accept Ensembl IDs directly. Do not collapse ambiguous mappings silently.
Skipping post-quant QC. Always look at the PCA and sample-distance heatmap before trusting DE — they expose swapped labels, outliers, and hidden batches.
Mixing aligners across samples. Quantify every sample with the same tool, version, reference, and parameters.
Unpinned versions. "latest" pipelines/genomes make results unreproducible; pin
-r, tool versions, and the genome/annotation release.
Integration with Other Skills
Upstream execution:
nextflow(runsnf-core/rnaseq, Path A; HPC/cloud/containers).Reference data / gene IDs:
gget(gget reffor genome+GTF,gget info/gget searchfor ID mapping),database-lookup(Ensembl/NCBI),biopython/pysam(FASTA/BAM handling).Differential expression:
pydeseq2(the DE engine this skill hands counts to).Enrichment:
pathway-enrichment(ORA + GSEA; itsscripts/run_enrichment.pyreads a DESeq2 results CSV directly).Figures & reporting:
scientific-visualization,matplotlib,seaborn;scientific-writingfor the methods/results narrative.Related but distinct:
scanpy(single-cell),statistical-analysis(multiple-testing depth).
Reference Files
Read the relevant file when you need depth — each is self-contained:
references/upstream-nfcore.md— Path A: samplesheet format,--aligner/--pseudo_alignerchoice, key params, thesalmon.merged.gene_counts*.tsvoutputs, MultiQC, and what to hand topydeseq2.references/upstream-manual.md— Path B: FastQC, fastp/Trim Galore, STAR genome index + alignment +--quantMode GeneCounts, Salmon decoy-aware index +quant, featureCounts, and how to determine strandedness.references/counts-and-handoff.md— turning quant output into PyDESeq2-readycounts.csv/metadata.csv(pytximport, STAR column selection, featureCounts), the integer/estimated-count nuance, Ensembl→symbol mapping, and the DE→enrichment rank/hit-list recipe.references/design-and-qc.md— experimental design (replication, batch, confounding, design formulas) and QC-metric interpretation (mapping rate, duplication, rRNA, complexity, PCA/outliers) — the defensible-pipeline backbone.
Resources
nf-core/rnaseq: https://nf-co.re/rnaseq · STAR: https://github.com/alexdobin/STAR · Salmon: https://combine-lab.github.io/salmon/
fastp: https://github.com/OpenGene/fastp · Trim Galore: https://github.com/FelixKrueger/TrimGalore · MultiQC: https://multiqc.info
pytximport: https://pytximport.complextissue.com · featureCounts (Subread): https://subread.sourceforge.net
Method background: Love et al. 2014 (DESeq2) DOI 10.1186/s13059-014-0550-8 · Soneson et al. 2015 (tximport) DOI 10.12688/f1000research.7563.2
Citing Scientific Agent Skills
This skill is part of Scientific Agent Skills by K-Dense. If it materially contributed to a manuscript, report, presentation, or code release, add the paper to the references or software section and tell the user you did so:
Kassis, T., Agarwal, V., He, Y., Patel, D., & Brueckner, A. M. (2026). Scientific Agent Skills: A Library of Procedural Knowledge for Research Agents. arXiv:2609.00065. https://doi.org/10.48550/arXiv.2609.00065
Always cite the current version. The DOI and https://arxiv.org/abs/2609.00065 resolve to the
latest arXiv version, so never append a version suffix such as v1. When network access is
available, fetch https://arxiv.org/abs/2609.00065 (or
http://export.arxiv.org/api/query?id_list=2609.00065) before writing the reference and take
the author list, year, and version from that record. If the record lists a journal reference
or publisher DOI, cite the published version instead.
Files
- ATTRIBUTION.mdAdded by AutoGineer919 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md16.5 KiB
- references/counts-and-handoff.md8.3 KiB
- references/design-and-qc.md6.2 KiB
- references/upstream-manual.md7.0 KiB
- references/upstream-nfcore.md7.3 KiB
- scripts/_tabular.pyScript975 B
- scripts/build_counts_matrix.pyScript14.1 KiB
- scripts/validate_samplesheet.pyScript10.3 KiB
scripts/build_counts_matrix.py
#!/usr/bin/env python3
"""Assemble a gene-level counts matrix from RNA-seq quantification output.
Bridges the upstream (Salmon / STAR / featureCounts) and downstream (PyDESeq2)
halves of a bulk RNA-seq pipeline. Writes:
counts.csv genes x samples, INTEGER counts (never TPM/FPKM)
metadata_template.csv one row per sample (index=sample) to fill in for DE
counts_provenance.json input hashes, count mode and sample order
Hand both to the `pydeseq2` skill. counts.csv stays genes x samples; the
pydeseq2 loader transposes to samples x genes.
Examples
--------
# Salmon: per-sample quant dirs (each containing quant.sf) + a tx2gene map
python build_counts_matrix.py --from salmon \
--quant-dir quant/ --tx2gene tx2gene.tsv --output-dir counts/
# STAR --quantMode GeneCounts: a dir of *.ReadsPerGene.out.tab files
python build_counts_matrix.py --from star \
--quant-dir star/ --strandedness reverse --output-dir counts/
# featureCounts: the combined matrix it wrote
python build_counts_matrix.py --from featurecounts \
--counts-file counts/featurecounts.txt --output-dir counts/
Requires: pandas and NumPy. Salmon mode also needs pytximport.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import sys
from importlib.metadata import version
from pathlib import Path
import numpy as np
import pandas as pd
from _tabular import validate_header
# STAR ReadsPerGene.out.tab column index per strandedness (col 0 is the gene id).
STAR_STRAND_COL = {"unstranded": 1, "forward": 2, "reverse": 3}
def _clean_sample_name(name: str) -> str:
"""Strip common aligner suffixes/extensions from a file or column name."""
name = Path(str(name)).name
for suf in (
".ReadsPerGene.out.tab",
".Aligned.sortedByCoord.out.bam",
".Aligned.out.bam",
".bam",
".sf",
):
if name.endswith(suf):
name = name[: -len(suf)]
return name.rstrip(".")
def _validate_counts(counts: pd.DataFrame, *, estimated: bool = False) -> pd.DataFrame:
"""Reject ambiguous labels and malformed values before any integer conversion."""
if counts.empty:
raise ValueError("Counts matrix is empty")
for label, values in (("gene", counts.index), ("sample", counts.columns)):
if values.has_duplicates or values.isna().any() or any(not str(v).strip() for v in values):
raise ValueError(f"Empty or duplicate {label} IDs in counts matrix")
numeric = counts.apply(pd.to_numeric, errors="raise")
values = numeric.to_numpy()
if not np.isfinite(values).all() or (values < 0).any():
raise ValueError("Counts must be finite and non-negative")
if (values >= 2**63).any():
raise ValueError("Counts exceed the supported int64 range")
if not estimated and (values != np.floor(values)).any():
raise ValueError("Fractional counts require an explicit estimated-count workflow; refusing truncation")
return numeric.round().astype("int64")
def _file_record(path: Path) -> dict:
digest = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return {"path": str(path), "sha256": digest.hexdigest()}
def build_from_salmon(quant_dir: Path, tx2gene: Path,
ignore_transcript_version: bool = False) -> pd.DataFrame:
"""Aggregate per-sample Salmon quant.sf to gene level via pytximport.
Uses counts_from_abundance='length_scaled_tpm' for full-length bulk
gene-level DE and rounds the resulting estimated counts to integers,
which PyDESeq2 requires. See references/counts-and-handoff.md.
"""
try:
from pytximport import tximport
except ImportError:
sys.exit("Salmon mode needs pytximport. Install with: uv pip install pytximport")
if tx2gene is None:
sys.exit("--tx2gene is required for --from salmon (columns: transcript_id, gene_id)")
# Discover per-sample quant.sf files (sample name = parent directory name).
sf_files = sorted(quant_dir.glob("*/quant.sf"))
if not sf_files:
# Fall back to a flat layout: *.sf directly in quant_dir.
sf_files = sorted(quant_dir.glob("*.sf"))
if not sf_files:
sys.exit(f"No quant.sf found under {quant_dir} (expected <sample>/quant.sf)")
sample_names = [
f.parent.name if f.name == "quant.sf" else _clean_sample_name(f.name)
for f in sf_files
]
if len(sample_names) != len(set(sample_names)):
raise ValueError("Duplicate sample IDs after filename normalization")
validate_header(tx2gene, delimiter=None)
mapping = pd.read_csv(tx2gene, sep=None, engine="python", dtype=str, keep_default_na=False)
if not {"transcript_id", "gene_id"}.issubset(mapping.columns):
raise ValueError("tx2gene needs transcript_id and gene_id headers")
mapping = mapping[["transcript_id", "gene_id"]].copy()
if mapping.empty or mapping.eq("").any().any():
raise ValueError("tx2gene has empty transcript/gene IDs")
if ignore_transcript_version:
mapping["transcript_id"] = mapping["transcript_id"].str.replace(r"\.\d+$", "", regex=True)
if mapping["transcript_id"].duplicated().any():
raise ValueError("Duplicate transcript IDs in tx2gene (possibly after version stripping)")
reference_ids = None
for path in sf_files:
validate_header(path, delimiter="\t")
quant = pd.read_csv(path, sep="\t", dtype={"Name": str}, keep_default_na=False)
required = {"Name", "Length", "EffectiveLength", "TPM", "NumReads"}
if not required.issubset(quant.columns):
raise ValueError(f"Invalid Salmon quant.sf columns: {path}")
names = quant["Name"]
if ignore_transcript_version:
names = names.str.replace(r"\.\d+$", "", regex=True)
if names.duplicated().any() or names.eq("").any():
raise ValueError(f"Empty or duplicate transcript IDs: {path}")
numeric = quant[["Length", "EffectiveLength", "TPM", "NumReads"]].apply(pd.to_numeric)
if not np.isfinite(numeric.to_numpy()).all() or (numeric < 0).any().any():
raise ValueError(f"Invalid Salmon numeric values: {path}")
if numeric["NumReads"].sum() <= 0:
raise ValueError(f"No quantified fragments: {path}")
if reference_ids is not None and not names.equals(reference_ids):
raise ValueError("Salmon transcript IDs/order differ; use one reference and quantifier run convention")
reference_ids = names
missing = set(names) - set(mapping["transcript_id"])
if missing:
raise ValueError(f"tx2gene missing {len(missing)} quantified transcript IDs; e.g. {sorted(missing)[:5]}")
print(f"Salmon: {len(sf_files)} samples -> {sample_names}")
txi = tximport(
[str(f) for f in sf_files],
data_type="salmon",
transcript_gene_map=mapping,
counts_from_abundance="length_scaled_tpm",
ignore_transcript_version=ignore_transcript_version,
ignore_after_bar=False,
output_type="anndata",
return_data=True,
)
# AnnData: obs=samples, var=genes, X=samples x genes. Transpose to genes x samples.
counts = txi.to_df().T
counts.columns = sample_names
counts.index.name = "gene_id"
counts = _validate_counts(counts, estimated=True)
counts.attrs["provenance"] = {
"source": "salmon", "counts_from_abundance": "length_scaled_tpm",
"assay": "full_length_bulk", "rounding": "nearest_integer_ties_to_even",
"ignore_transcript_version": ignore_transcript_version,
"pytximport_version": version("pytximport"), "tx2gene": _file_record(tx2gene),
"inputs": [_file_record(f) for f in sf_files],
}
return counts
def build_from_star(quant_dir: Path, strandedness: str) -> pd.DataFrame:
"""Combine STAR *.ReadsPerGene.out.tab files into a gene x sample matrix."""
col = STAR_STRAND_COL[strandedness]
tabs = sorted(quant_dir.glob("*ReadsPerGene.out.tab"))
if not tabs:
sys.exit(f"No *ReadsPerGene.out.tab found under {quant_dir}")
print(f"STAR: {len(tabs)} samples, strandedness={strandedness} (column {col})")
series = {}
reference_genes = None
for tab in tabs:
# First 4 rows are summary stats (N_unmapped, N_multimapping, ...).
df = pd.read_csv(tab, sep="\t", header=None, dtype={0: str}, keep_default_na=False)
if df.shape[1] != 4 or df.iloc[:4, 0].tolist() != ["N_unmapped", "N_multimapping", "N_noFeature", "N_ambiguous"]:
raise ValueError(f"Invalid STAR GeneCounts header/layout: {tab}")
df = df.iloc[4:]
sample = _clean_sample_name(tab.name)
if sample in series:
raise ValueError(f"Duplicate sample ID after filename normalization: {sample}")
s = pd.Series(df[col].values, index=df[0].values)
_validate_counts(s.to_frame(sample))
if reference_genes is not None and set(s.index) != reference_genes:
raise ValueError("STAR gene sets differ; check annotation/reference instead of filling missing genes with zero")
reference_genes = set(s.index)
series[sample] = s
counts = _validate_counts(pd.DataFrame(series))
counts.index.name = "gene_id"
counts.attrs["provenance"] = {"source": "star", "strandedness": strandedness,
"rounding": "none", "inputs": [_file_record(f) for f in tabs]}
return counts
def build_from_featurecounts(counts_file: Path) -> pd.DataFrame:
"""Parse a combined featureCounts matrix into a gene x sample matrix."""
if not counts_file.is_file():
sys.exit(f"featureCounts file not found: {counts_file}")
# featureCounts prepends a '#' command line; real header is the next row.
validate_header(counts_file, delimiter="\t", comment="#")
df = pd.read_csv(counts_file, sep="\t", comment="#", dtype={"Geneid": str}, keep_default_na=False)
# Layout: Geneid, Chr, Start, End, Strand, Length, <bam1>, <bam2>, ...
meta_cols = ["Geneid", "Chr", "Start", "End", "Strand", "Length"]
if not set(meta_cols).issubset(df.columns):
raise ValueError("featureCounts file is missing required annotation columns")
sample_cols = [c for c in df.columns if c not in meta_cols]
if not sample_cols:
sys.exit("No sample/count columns found in featureCounts file")
counts = df.set_index("Geneid")[sample_cols]
counts.columns = [_clean_sample_name(c) for c in counts.columns]
counts = _validate_counts(counts)
counts.index.name = "gene_id"
counts.attrs["provenance"] = {"source": "featurecounts", "rounding": "none",
"inputs": [_file_record(counts_file)]}
print(f"featureCounts: {len(sample_cols)} samples -> {list(counts.columns)}")
return counts
def write_outputs(counts: pd.DataFrame, output_dir: Path) -> None:
provenance = counts.attrs.get("provenance", {"source": "unspecified"})
counts = _validate_counts(counts)
if (counts.sum(axis=0) <= 0).any():
raise ValueError("A sample has zero total counts; resolve it before DE")
# Drop all-zero genes (uninformative; pydeseq2 filters further).
n_before = counts.shape[0]
counts = counts[counts.sum(axis=1) > 0]
dropped = n_before - counts.shape[0]
output_dir.mkdir(parents=True, exist_ok=True)
counts_path = output_dir / "counts.csv"
counts.to_csv(counts_path)
meta = pd.DataFrame(
{"condition": ["CHANGE_ME"] * counts.shape[1], "batch": [""] * counts.shape[1]},
index=pd.Index(counts.columns, name="sample"),
)
meta_path = output_dir / "metadata_template.csv"
meta.to_csv(meta_path)
provenance.update({"orientation": "genes_by_samples", "samples": list(counts.columns),
"all_zero_genes_removed": dropped, "pandas_version": pd.__version__})
(output_dir / "counts_provenance.json").write_text(json.dumps(provenance, indent=2) + "\n", encoding="utf-8")
print(f"\n genes: {counts.shape[0]} (dropped {dropped} all-zero)")
print(f" samples: {counts.shape[1]}")
print(f" wrote {counts_path} (genes x samples, integer)")
print(f" wrote {meta_path} (fill in 'condition'/'batch', then run the pydeseq2 skill)")
def main() -> None:
p = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
p.add_argument(
"--from", dest="source", required=True,
choices=["salmon", "star", "featurecounts"],
help="Quantifier that produced the input.",
)
p.add_argument("--quant-dir", type=Path,
help="Directory of per-sample quant output (salmon/star).")
p.add_argument("--tx2gene", type=Path,
help="transcript_id->gene_id map (salmon). TSV/CSV with those columns.")
p.add_argument("--strandedness", choices=list(STAR_STRAND_COL),
help="Verified library strandedness (required for STAR; no default).")
p.add_argument("--ignore-transcript-version", action="store_true",
help="Strip terminal .N versions in Salmon IDs and map, after checking reference provenance.")
p.add_argument("--counts-file", type=Path,
help="Combined featureCounts matrix (featurecounts).")
p.add_argument("--output-dir", type=Path, default=Path("counts"),
help="Where to write counts.csv + metadata_template.csv (default: counts/).")
args = p.parse_args()
if args.source == "salmon":
if not args.quant_dir:
sys.exit("--quant-dir is required for --from salmon")
counts = build_from_salmon(args.quant_dir, args.tx2gene, args.ignore_transcript_version)
elif args.source == "star":
if not args.quant_dir:
sys.exit("--quant-dir is required for --from star")
if not args.strandedness:
sys.exit("--strandedness is required for --from star; infer it before selecting counts")
counts = build_from_star(args.quant_dir, args.strandedness)
else:
if not args.counts_file:
sys.exit("--counts-file is required for --from featurecounts")
counts = build_from_featurecounts(args.counts_file)
write_outputs(counts, args.output_dir)
if __name__ == "__main__":
main()
Requirements and compatibility
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Needs network access, Needs Python
The author says: Requires Python 3.11+ with pandas and numpy; Salmon import also needs pytximport. Read processing needs Nextflow with containers or standalone bioinformatics tools. Network access is needed for installation and reference downloads.
Security
What our scanner noticed· Low risk
- Instructions that use the network
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Created by
- K-Dense Inc.
- Publisher
- K-Dense (Community)
- Source
- K-Dense-AI/scientific-agent-skills · skills/bulk-rnaseq · commit a25cf9e
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE.md)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by K-Dense Inc. or K-Dense.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download bulk-rnaseq.zip