一键导入
sequence-statistics
Compute length, GC, N50, L50, and per-file summaries for FASTA/FASTQ — including the N50 trick and modern streaming stats with Polars.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Compute length, GC, N50, L50, and per-file summaries for FASTA/FASTQ — including the N50 trick and modern streaming stats with Polars.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
| name | sequence-statistics |
| description | Compute length, GC, N50, L50, and per-file summaries for FASTA/FASTQ — including the N50 trick and modern streaming stats with Polars. |
| license | MIT |
fastq-quality-scores).QUAST or assembly-stats (BioContainers).FastQC / MultiQC / fastp -j.ors-bioinformatics-sequence-vcf-statistics.biopython>=1.83numpy>=1.26 for streaming percentilespolars>=1.0 for tidy summariesfrom Bio import SeqIO
from Bio.SeqUtils import gc_fraction
"
for rec in SeqIO.parse("genome.fasta", "fasta"):
print(rec.id, len(rec.seq), f"{gc_fraction(rec.seq):.3f}")
from Bio import SeqIO
for rec in SeqIO.parse("reads.fastq", "fastq"):
q = rec.letter_annotations["phred_quality"]
print(rec.id, len(rec.seq), sum(q)/len(q))
from pathlib import Path
import polars as pl
from Bio import SeqIO
from Bio.SeqUtils import gc_fraction
import numpy as np
def summarize(path, fmt):
lengths, gcs = [], []
for rec in SeqIO.parse(path, fmt):
lengths.append(len(rec.seq))
gcs.append(gc_fraction(rec.seq))
if not lengths:
return None
arr = np.array(lengths)
return {
"file": path.name,
"records": len(arr),
"total_bp": int(arr.sum()),
"min_len": int(arr.min()),
"median_len": float(np.median(arr)),
"mean_len": float(arr.mean()),
"max_len": int(arr.max()),
"mean_gc": float(np.mean(gcs)),
}
rows = [summarize(p, "fasta") for p in sorted(Path(".").glob("*.fasta"))]
pl.DataFrame([r for r in rows if r]).write_csv("per_file_stats.csv")
import numpy as np
def assembly_stats(lengths):
a = np.sort(np.asarray(lengths))[::-1] # descending
total = a.sum()
if total == 0:
return {}
cum = np.cumsum(a)
def nx(p):
cutoff = total * p / 100.0
idx = np.searchsorted(cum, cutoff, side="left")
return int(a[min(idx, len(a) - 1)])
l50 = int(np.searchsorted(cum, total * 0.5, side="left") + 1)
# auN: area under the length-vs-cumulative curve, normalized
aun = float(np.trapz(a, cum) / total)
return {
"n_contigs": len(a),
"total_bp": int(total),
"n50": nx(50), "l50": l50,
"n90": nx(90),
"auN": aun,
}
import numpy as np
from Bio import SeqIO
def streaming_n50(path, fmt, expected_n=None):
# Reservoir sample for very large assemblies
sample = []
for rec in SeqIO.parse(path, fmt):
sample.append(len(rec.seq))
return assembly_stats(sample)
(For genuinely huge assemblies — billions of contigs — use the reservoir sampling variant; otherwise just sort.)
from collections import Counter
from Bio import SeqIO
counts = Counter()
for rec in SeqIO.parse("genome.fasta", "fasta"):
counts.update(str(rec.seq).upper())
total = sum(counts.values())
for base in "ACGTNUacgtnu":
print(f"{base}\t{counts[base]}\t{counts[base]/total:.4f}")
import numpy as np
import polars as pl
from Bio import SeqIO
lens = np.array([len(r.seq) for r in SeqIO.parse("reads.fastq", "fastq")])
df = pl.DataFrame({"length": lens})
print(df.select([
pl.col("length").min().alias("min"),
pl.col("length").mean().alias("mean"),
pl.col("length").median().alias("median"),
pl.col("length").max().alias("max"),
pl.col("length").std().alias("sd"),
]))
from collections import Counter
from Bio import SeqIO
from Bio.Seq import Seq
def kmer_counts(path, k=6):
c = Counter()
for rec in SeqIO.parse(path, "fasta"):
s = str(rec.seq).upper()
for i in range(len(s) - k + 1):
c[s[i:i+k]] += 1
return c
kc = kmer_counts("genome.fasta", k=6)
kc.most_common(10)
Bio.SeqUtils.gc_fraction excludes Ns by default — confirm with gc_fraction(rec.seq) (default) vs manual sum(G+C)/len(seq). The latter is biased by ambiguous bases.QUAST is that length; "L50" is the index (number of contigs covering 50% of the assembly).list comprehension to a generator and use islice or a reservoir.gc_fraction deprecated signature. In Biopython 1.83+ it's gc_fraction(seq); old code used GC(seq).sum(lengths) == total_bp for a FASTA where Ns are counted as bases.[min, max].| Need | Tool |
|---|---|
| Assembly stats (gold standard) | QUAST, assembly-stats (BioContainers) |
| FASTQ read stats | seqkit stats, fastp --json |
| K-mer spectra | jellyfish, kmc |
| Genome size / heterozygosity | GenomeScope2 |
Bio.SeqUtils: https://biopython.org/docs/latest/api/Bio.SeqUtils.htmlors-bioinformatics-sequence-fastq-quality-scores, ors-bioinformatics-sequence-batch-sequence-processing.bio-sequence-statistics (bioSkills-main/sequence-io/sequence-statistics).Other skills in this category:
Pass work between ORS skills with a Material Passport — a structured JSON envelope that captures inputs, outputs, decisions, and provenance so a downstream skill can resume without re-deriving context. Use when one skill produces output that another skill must consume, especially across category boundaries (e.g. analysis → writing, sequencing → statistics).
Discover and maintain `## Cross-references` between ORS skills. Given a new or edited skill, suggest related skills (same category, shared tags, complementary workflows). Verify all xref slugs resolve to existing SKILL.md files. Use when adding a new skill, when sibling skills move, or when an audit reveals dangling xrefs.
7-mode AI failure-mode checklist applied before publishing any ORS artifact (skill, manuscript section, dataset card, agent output). Catches: fabricated citations, silent failures, scope creep, missing provenance, unsupervised writes, version drift, hallucinated APIs. Use as the final pass before any 'publish', 'release', 'merge', or 'finalize' action.
Version, changelog, and marketplace workflow for ORS skills. Semver discipline, breaking-change protocol, marketplace.json update, README refresh, and the v0.X.Y → v1.0.0 graduation criteria. Use when bumping a skill version, publishing a release, or upgrading the ORS package version.
Author a new ORS skill from scratch using the v0.4.0 schema. Produces a valid SKILL.md (frontmatter + metadata + sections) following spec/skill-format.md, guided by spec/author-guide.md, validated by scripts/validate-skills.py. Use when a user says 'add a new skill', 'create a skill for X', or 'I want to contribute a skill'.
Process many FASTA/FASTQ/GenBank files in batch — merge, split, convert, summarize, organize — using Biopython 1.83+.