Logo von Samtools Bam Processing

Samtools Bam Processing

Community
jaechang-hits
samtools-bam-processing

CLI-Toolkit für SAM/BAM/CRAM: Alignments sortieren, indizieren, konvertieren, filtern und einer Qualitätskontrolle unterziehen. Zentrale Befehle: view, sort, index, flagstat, stats, depth, markdup, merge. Erforderlich zwischen Alignment und Variant- bzw. Peak-Calling. Verwenden Sie pysam für den nativen BAM-Zugriff in Python und deeptools für normalisierte Coverage-Tracks.

Add to TypingMind

Übersicht

Herausgeberjaechang-hits
RepositorySciAgent-Skills
Skill-Namesamtools-bam-processing
Sterne
381
Forks
45
Mitgelieferte Dateien
Nur Anweisungen
LizenzMIT
Links
  • Anweisungen in Markdown

    Eine SKILL.md-Datei, die das Modell bei Bedarf lädt. So werden nur dann Token verbraucht, wenn eine Anfrage tatsächlich dazu passt.

  • Funktioniert mit jedem LLM

    KI-Skills bestehen aus reinem Markdown, nicht aus anbieterspezifischem Code. Daher funktionieren sie mit GPT, Claude, Gemini, Grok oder einem lokalen Modell.

  • In sich abgeschlossen

    Alles, was das Modell braucht, steht in den Anweisungen — keine zusätzlichen Dateien zum Synchronisieren.

  • Open Source

    Von jaechang-hits auf GitHub veröffentlicht. Prüfen Sie vor der Installation die Quelldateien.

Installation

Installieren Sie den KI-Skill Samtools Bam Processing in TypingMind, um ihn mit jedem LLM zu nutzen, oder fügen Sie ihn einem anderen Agenten hinzu, der SKILL.md lesen kann.

1

In TypingMind installieren

TypingMind installiert einen Skill direkt aus seinem GitHub-Ordner. Dabei liest die App SKILL.md, bündelt die Ressourcendateien und speichert das Ergebnis lokal.

  1. Öffnen Sie die App und gehen Sie zu Plugins → Skills.
  2. Wählen Sie „Von GitHub installieren“.
  3. Fügen Sie die unten angegebene URL des Skill-Ordners ein und bestätigen Sie.
    https://github.com/jaechang-hits/SciAgent-Skills/tree/main/skills/genomics-bioinformatics/alignment/samtools-bam-processing
  4. Aktivieren Sie den Skill in jedem Chat, in dem er verfügbar sein soll.
Plugins → Skills → Skill hinzufügen → Über GitHub-URL. Fügen Sie dann die Ordner-URL ein und klicken Sie auf „Weiter“.
2

In einem anderen Agenten installieren

Jeder Agent, der das Agent-Skills-Format unterstützt, kann diesen Skill nutzen. Kopieren Sie den Ordner in das Skill-Verzeichnis des jeweiligen Agenten.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/jaechang-hits/SciAgent-Skills.git /tmp/SciAgent-Skills
mkdir -p .claude/skills
cp -r /tmp/SciAgent-Skills/skills/genomics-bioinformatics/alignment/samtools-bam-processing .claude/skills/samtools-bam-processing
Starten Sie Claude Code nach dem Kopieren neu, damit der neue Skill erkannt wird.

In TypingMind verwenden

Aktivieren Sie Samtools Bam Processing in einem beliebigen Chat in TypingMind. Den Rest übernimmt das Modell. Name und Beschreibung des Skills stehen im System-Prompt. Sobald eine Anfrage passt, lädt das Modell selbstständig die vollständigen Anweisungen — Sie müssen den Skill nie manuell aufrufen, und er verbraucht erst Token, wenn er tatsächlich genutzt wird.

Das Modell lädt Samtools Bam Processing automatisch, sobald eine passende Anfrage gestellt wird.

Funktioniert mit jedem KI-Modell

KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher ist Samtools Bam Processing nicht an das Modell gebunden, für das der Skill geschrieben wurde. Installieren Sie ihn einmal in TypingMind und nutzen Sie ihn mit GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder einem selbst betriebenen lokalen Modell — alles mit Ihren eigenen API-Schlüsseln.

  • Wird nur bei Bedarf geladen

    Der System-Prompt enthält nur den Namen und die Beschreibung. Die Anweisungen werden bei der ersten passenden Anfrage geladen. Ein ungenutzter Skill verursacht daher keine Kosten.

  • Modell im laufenden Chat wechseln

    Da der Skill aus Anweisungen statt aus Code besteht, funktioniert er auch nach einem Modellwechsel — das nächste Modell liest dieselbe SKILL.md-Datei.

Skill-Anweisungen

Dies ist der Inhalt von SKILL.md, den das Modell lädt. Lesen Sie ihn vor der Installation — ein Skill besteht aus Anweisungen, denen Ihr Modell folgt.

samtools — SAM/BAM/CRAM Alignment Toolkit

Overview

samtools is the standard command-line toolkit for processing sequence alignment files in SAM, BAM, and CRAM formats. It handles the complete alignment file lifecycle: format conversion, coordinate sorting, index creation, quality control statistics, read filtering, duplicate marking, and multi-file merging. samtools is a near-universal component of NGS pipelines between alignment (STAR, BWA) and downstream analysis (variant calling, peak calling, coverage).

When to Use

  • Sorting BAM files by coordinate after alignment (required before indexing)
  • Indexing sorted BAM files for random access and region queries
  • Converting between SAM, BAM, and CRAM formats to save storage
  • Generating alignment QC metrics: mapping rates, insert sizes, per-chromosome stats
  • Filtering reads by mapping quality, FLAG bits, or genomic regions
  • Marking or removing PCR duplicates before variant calling
  • Merging multiple BAM files from different lanes or samples
  • Calculating per-base depth or coverage breadth for target regions
  • Use pysam instead for Python-native BAM manipulation in custom scripts
  • Use deeptools bamCoverage instead when you need normalized bigWig coverage tracks
  • Use mosdepth instead for whole-genome per-base depth (faster, parallelized)

Prerequisites

  • Installation: samtools 1.17+ recommended
  • Input requirements: SAM/BAM/CRAM files; CRAM requires FASTA reference
  • Companion tools: samtools faidx for FASTA indexing; samtools sort before samtools index

Check before installing: The tool may already be available in the current environment (e.g., inside a pixi / conda env). Run command -v samtools first and skip the install commands below if it returns a path. When running inside a pixi project, invoke the tool via pixi run samtools rather than bare samtools.

bash
# Bioconda (recommended)
conda install -c bioconda samtools

# Homebrew (macOS)
brew install samtools

# Verify
samtools --version | head -1

Pre-flight Interview

Settle these with the user before writing any analysis code.

yaml
decisions:
  - id: D1
    param: mappingQualityFloor
    kind: required
    source: user
    ask: "Below what mapping confidence should reads be dropped? Everything counted downstream inherits this cut."
    default: "0 - keep every alignment, including ambiguously placed ones"

  - id: D2
    param: flagFilter
    kind: required
    source: user
    ask: "Which read classes should be excluded - unmapped, secondary, supplementary, failed-QC, duplicates?"
    default: "keep all classes"

  - id: D3
    param: duplicateHandling
    kind: required
    source: user
    ask: "Should duplicates be marked and left in place, or physically removed from the file?"
    default: "marked, not removed - downstream tools can then choose"

  - id: D4
    param: sortOrder
    kind: derived
    source: upstream
    ask: "Does the next step need coordinate order, or name order for mate pairing?"
    default: "coordinate"

  - id: D5
    param: outputFormat
    kind: optional
    source: user
    ask: "Write BAM, or CRAM against a reference to save space?"
    default: "BAM"

  - id: D6
    param: opticalDuplicateDistance
    kind: optional_conditional
    source: data
    ask: "Should optical duplicates be distinguished from PCR duplicates, using this platform's pixel distance?"
    default: "not distinguished"

  - id: D7
    param: threadsAndMemory
    kind: never_ask
    source: data
    reason: "Compression threads and per-thread sort memory affect runtime and peak RAM, not the records"
    default: "available cores, 768M per thread"

D1 and D2 look like plumbing and are not. A MAPQ floor silently removes multi-mapping regions - paralogs, recent duplications, repeat-adjacent genes - from everything computed afterwards, and a run that keeps secondary alignments counts the same fragment several times. Neither is visible in the output file.

Quick Start

bash
# Typical post-alignment workflow: sort → index → QC
samtools sort -@ 8 -o sorted.bam input.bam
samtools index sorted.bam
samtools flagstat sorted.bam

Core API

Module 1: BAM/SAM I/O and Format Conversion

Convert between SAM/BAM/CRAM formats and extract subsets.

bash
# SAM → BAM (saves ~75% disk space)
samtools view -b -h input.sam -o output.bam

# BAM → CRAM (saves additional 40-50%)
samtools view -C -T reference.fa input.bam -o output.cram

# Filter: mapping quality ≥20, exclude unmapped (-F 4)
samtools view -q 20 -F 4 input.bam -o filtered.bam

# Extract specific region (requires index)
samtools view -h sorted.bam "chr1:1000000-2000000" -o region.bam

# Count reads matching filter
samtools view -c -F 4 input.bam
# Output: 45231923 (number of mapped reads)
bash
# Extract reads as FASTQ (for realignment or de novo assembly)
samtools fastq -@ 4 -1 R1.fastq.gz -2 R2.fastq.gz -0 unpaired.fastq.gz input.bam

# Extract reads as FASTA
samtools fasta input.bam > reads.fasta

# Filter by read group
samtools view -r SAMPLE_001 multi_rg.bam -o sample001.bam

Module 2: Sorting and Indexing

Organize BAM files for efficient random access.

bash
# Sort by coordinate (required before indexing)
samtools sort -@ 8 -m 2G input.bam -o sorted.bam

# Sort by read name (required for fixmate/markdup)
samtools sort -n -@ 8 input.bam -o namesorted.bam

# Index sorted BAM (creates sorted.bam.bai)
samtools index sorted.bam

# For chromosomes > 512 Mbp: use CSI index instead
samtools index -c sorted.bam

# Group reads by name (fast, for fixmate — no full sort needed)
samtools collate -o collated.bam input.bam

Module 3: Quality Control and Statistics

Generate alignment QC metrics and coverage reports.

bash
# Quick summary: total, mapped, paired, properly paired
samtools flagstat sorted.bam
# Example output:
# 50000000 + 0 in total (QC-passed reads + QC-failed reads)
# 48523111 + 0 mapped (97.05% : N/A)
# 50000000 + 0 paired in sequencing
# 48490234 + 0 properly paired (96.98% : N/A)

# Per-chromosome mapped/unmapped read counts
samtools idxstats sorted.bam
# chr1  248956422  12345678  0
# chr2  242193529  11234567  0

# Comprehensive stats (insert sizes, GC content, base quality)
samtools stats -r reference.fa sorted.bam > full_stats.txt
grep "^SN" full_stats.txt | cut -f2,3  # Summary Numbers only

# Coverage report (min/max/mean per region/chromosome)
samtools coverage sorted.bam
bash
# Per-base read depth for specific regions
samtools depth -b target_regions.bed sorted.bam > depth.txt
# Output: chr  pos  depth (e.g., chr1  1000  45)

# Statistics split by read group
samtools stats -S RG sorted.bam > per_rg_stats.txt

Module 4: Read Filtering and FLAG Operations

Filter reads using SAM FLAG bits for specific subsets.

bash
# FLAG reference — common masks:
# 1    = paired         4  = unmapped
# 2    = proper pair    8  = mate unmapped
# 16   = reverse strand 64 = R1 (first in pair)
# 128  = R2             256= secondary alignment
# 1024 = PCR duplicate  2048= supplementary

# Extract properly paired, mapped reads (FLAG 2 set, 4 unset)
samtools view -f 2 -F 4 sorted.bam -o proper_pairs.bam

# Extract R1 reads only
samtools view -f 64 sorted.bam -o R1.bam

# Remove secondary and supplementary alignments
samtools view -F 2304 sorted.bam -o primary.bam

# Extract reads from BED file regions
samtools view -L regions.bed -b sorted.bam -o regions.bam

Module 5: Duplicate Handling

Mark or remove PCR duplicates before variant calling.

bash
# Full duplicate marking workflow (collate → fixmate → sort → markdup)
samtools collate -@ 8 -o collated.bam input.bam
samtools fixmate -m -@ 8 collated.bam fixmated.bam
samtools sort -@ 8 -o sorted.bam fixmated.bam
samtools markdup -@ 8 sorted.bam marked.bam
samtools index marked.bam

# Check duplication rate
samtools flagstat marked.bam | grep "duplicates"
# Output: 2345678 + 0 duplicates (4.83%)
bash
# NovaSeq optical duplicate detection (2500 pixel distance)
samtools markdup -d 2500 sorted.bam marked_novaseq.bam

# Remove duplicates instead of marking
samtools markdup -r sorted.bam deduped.bam

# Get duplication stats without writing output
samtools markdup -s sorted.bam /dev/null

Module 6: Multi-file Operations and Region Analysis

Merge BAM files and perform region-level analysis.

bash
# Merge multiple BAM files (all must be sorted)
samtools merge -@ 8 merged.bam lane1.bam lane2.bam lane3.bam

# Merge files listed in a text file (one per line)
samtools merge -b bam_list.txt -@ 8 merged.bam

# Merge with read group tags from filenames
samtools merge -r merged.bam sample1.bam sample2.bam

# Extract specific chromosome region from merged output
samtools view -h merged.bam chr1 -b -o chr1.bam

Key Concepts

SAM FLAG Bits

FLAGS encode read properties as a sum of bit values. Common filtering patterns:

Common Filter-f (require)-F (exclude)Selects
Mapped reads—4All aligned reads
Proper pairs2—Properly paired, both mapped
Unique primary—2308No secondary/supplementary/duplicate
R1 only64—First-in-pair reads
Unmapped4—Failed to align

CRAM vs BAM vs SAM

FormatSizeSpeedRequires
SAM~10× BAMSlow I/ONothing
BAM1×Fast.bai index for random access
CRAM~0.6× BAMSlightly slowerReference FASTA + index

Use CRAM for long-term storage; BAM for active analysis.

Common Workflows

Workflow 1: Post-Alignment QC and Preparation

Goal: Convert aligner output to analysis-ready BAM with QC metrics.

bash
#!/bin/bash
SAMPLE="sample_001"
REF="reference.fa"
THREADS=8

# 1. Sort and index (aligner often outputs unsorted SAM/BAM)
samtools sort -@ $THREADS -o ${SAMPLE}.sorted.bam ${SAMPLE}.bam
samtools index ${SAMPLE}.sorted.bam

# 2. QC metrics
samtools flagstat ${SAMPLE}.sorted.bam > ${SAMPLE}.flagstat.txt
samtools stats -r $REF ${SAMPLE}.sorted.bam > ${SAMPLE}.stats.txt
samtools coverage ${SAMPLE}.sorted.bam > ${SAMPLE}.coverage.txt

# 3. Per-chromosome stats
samtools idxstats ${SAMPLE}.sorted.bam > ${SAMPLE}.idxstats.txt

echo "QC complete: $(grep 'mapped (' ${SAMPLE}.flagstat.txt | head -1)"

Workflow 2: Full Duplicate-Marking Pipeline

Goal: Prepare BAM for GATK or other variant callers requiring deduplicated input.

bash
#!/bin/bash
INPUT="aligned.bam"
FINAL="deduped.bam"
THREADS=8

# Collate → fixmate → sort → markdup
samtools collate -@ $THREADS -o collated.bam $INPUT
samtools fixmate -m -@ $THREADS collated.bam fixmated.bam
samtools sort -@ $THREADS -o sorted.bam fixmated.bam
samtools markdup -@ $THREADS -s sorted.bam $FINAL

# Clean up intermediates
rm collated.bam fixmated.bam sorted.bam

# Index and verify
samtools index $FINAL
samtools flagstat $FINAL | grep "duplic"
# Expected: 3-15% duplicates (WGS); 10-30% for amplicon

Key Parameters

ParameterCommandDefaultRange/OptionsEffect
-@Most01–N coresAdditional compression/I/O threads
-msort768Me.g., 2G, 4GMemory per thread for sorting
-qview00–60Minimum mapping quality filter
-fview0FLAG bitsInclude reads with ALL bits set
-Fview0FLAG bitsExclude reads with ANY bit set
-bview—flagOutput BAM format
-Cview—flagOutput CRAM (requires -T)
-Tview—FASTA pathReference for CRAM output
-dmarkdup00–2500Optical duplicate pixel distance
-rmarkdup—flagRemove duplicates (vs just mark)
-nsort—flagSort by read name instead of position
-cindex—flagCreate CSI index (needed for chr > 512 Mb)

Best Practices

  1. Always sort before indexing: samtools index requires coordinate-sorted input. Attempting to index an unsorted BAM will fail or produce incorrect results.

  2. Use -@ for all production runs: Most samtools commands are I/O-bound. Adding -@ 8 provides near-linear speedup for compression/decompression with minimal overhead.

  3. Run flagstat before any analysis: samtools flagstat runs in seconds and catches alignment failures (low mapping rate, unexpected paired-end rates) before wasting time on downstream steps.

  4. Use the collate → fixmate → sort → markdup pipeline: Running samtools markdup directly on coordinate-sorted BAM without fixmate produces incorrect duplicate detection. The mate information added by fixmate -m is essential.

  5. Prefer CRAM for archiving: CRAM reduces storage 40-50% vs BAM with no loss. Always store the reference FASTA alongside CRAM files.

  6. Use -L bed_file for targeted analyses: Restricting samtools view to BED-defined target regions (WES capture, amplicons) dramatically reduces I/O for downstream steps.

Common Recipes

Recipe: Batch Flagstat for Multiple Samples

bash
# Process all BAM files in directory
for bam in *.sorted.bam; do
    echo "=== $bam ==="
    samtools flagstat $bam | grep -E "mapped|properly paired|duplicates"
done

Recipe: Extract Unmapped Reads for De Novo Assembly

bash
# Pull both unmapped reads (useful for pathogen detection)
samtools view -f 4 -b input.bam -o unmapped.bam
samtools fastq -@ 4 -1 unmapped_R1.fastq -2 unmapped_R2.fastq unmapped.bam
echo "Unmapped pairs ready for de novo assembly"

Recipe: Downsample BAM to Target Coverage

bash
# Estimate current depth, then subsample to ~30×
TOTAL=$(samtools flagstat input.bam | grep "mapped (" | head -1 | awk '{print $1}')
GENOME_SIZE=3100000000  # hg38
READ_LEN=150
CURRENT_COV=$(echo "scale=1; $TOTAL * $READ_LEN / $GENOME_SIZE" | bc)
TARGET_FRAC=$(echo "scale=3; 30 / $CURRENT_COV" | bc)
echo "Current: ${CURRENT_COV}×; subsample fraction: $TARGET_FRAC"
samtools view -b -s $TARGET_FRAC input.bam -o downsampled.bam
samtools index downsampled.bam

Troubleshooting

ProblemCauseSolution
[bam_index_build2] fail to indexBAM not sorted by coordinateSort first: samtools sort -o sorted.bam input.bam
BAI index too large for chromosomeChromosome > 512 MbpUse CSI index: samtools index -c input.bam
CRAM: reference not foundMissing or wrong reference FASTASet REF_PATH env var or use -T ref.fa
Duplicate marking incorrectfixmate step skippedRun full pipeline: collate → fixmate → sort → markdup
flagstat shows 0% properly pairedPaired-end BAM missing mate infoRun samtools fixmate to populate mate coordinates
Very slow sortingLow memory per threadIncrease -m 4G; reduce -@ if memory-limited
Region query returns nothingBAM not indexed or wrong coordsRun samtools index; use 1-based coords: chr1:1000-2000
[E::hts_open_format] fail to openFile path wrong or BAM corruptVerify path; test with samtools quickcheck file.bam

Related Skills

  • deeptools-ngs-analysis — normalized bigWig coverage tracks and ChIP-seq visualization downstream of samtools
  • pysam-genomic-files — Python API for BAM manipulation in custom scripts
  • bedtools-genomic-intervals — genomic interval operations on BAM/BED files produced by samtools

References

Häufig gestellte Fragen

Was macht der KI-Skill Samtools Bam Processing?

CLI-Toolkit für SAM/BAM/CRAM: Alignments sortieren, indizieren, konvertieren, filtern und einer Qualitätskontrolle unterziehen. Zentrale Befehle: view, sort, index, flagstat, stats, depth, markdup, merge. Erforderlich zwischen Alignment und Variant- bzw. Peak-Calling. Verwenden Sie pysam für den nativen BAM-Zugriff in Python und deeptools für normalisierte Coverage-Tracks.

Warum Samtools Bam Processing in TypingMind nutzen?

Weil Sie den Skill einmal installieren und mit jedem Modell verwenden können. Samtools Bam Processing besteht aus reinem Markdown statt aus anbieterspezifischem Code. So funktioniert derselbe Skill mit GPT-5, Claude, Gemini, Grok oder einem lokalen Modell – und Sie können das Modell mitten im Chat wechseln, ohne dass der Skill seine Funktion verliert. TypingMind verwendet Ihre eigenen API-Schlüssel. Sie bezahlen die Anbieter daher direkt statt über ein Abonnement pro Nutzerplatz, und Ihre Skills und Chats bleiben in Ihrem eigenen Speicher.

Wie installiere ich Samtools Bam Processing in TypingMind?

Öffnen Sie in TypingMind Plugins → Skills → Von GitHub installieren und fügen Sie https://github.com/jaechang-hits/SciAgent-Skills/tree/main/skills/genomics-bioinformatics/alignment/samtools-bam-processing ein. TypingMind liest die Datei SKILL.md und installiert den Skill, den Sie für jeden Chat einzeln aktivieren können.

Welche KI-Modelle können Samtools Bam Processing nutzen?

Jedes Modell, das Sie mit TypingMind verbinden. KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher können GPT, Claude, Gemini, Grok und lokale Modelle diesen Skill laden, wenn eine Anfrage dazu passt.

Wie viele KI-Modelle kann ich mit Samtools Bam Processing verwenden?

So viele Sie möchten. In TypingMind können Sie Samtools Bam Processing mit jedem Modell verwenden, das Skills unterstützt, etwa mit GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama. Dabei nutzen Sie Ihre eigenen API-Schlüssel.

Ist der KI-Skill Samtools Bam Processing kostenlos?

Ja. Der Skill wird von jaechang-hits auf GitHub unter der Lizenz MIT veröffentlicht. Sie bezahlen nur Ihren eigenen KI-Anbieter für die verwendeten Token.

Was sind KI-Skills?

Ein KI-Skill ist ein wiederverwendbares Anweisungspaket, das einem KI-Modell vermittelt, wie es eine bestimmte Aufgabe erledigt. Es folgt dem offenen Format Agent Skills: Die Datei SKILL.md enthält den Namen und die Beschreibung des Skills. Hinzu kommen bei Bedarf Skripte, Vorlagen oder Referenzdateien für das Modell. Das Modell liest die Anweisungen nur, wenn Ihre Anfrage zum Skill passt. Ein installierter Skill verursacht daher erst Kosten, wenn er verwendet wird.

Wie unterscheiden sich KI-Skills von Plugins oder MCP-Servern?

Ein Plugin oder MCP-Server stellt einem Modell neue aufrufbare Tools bereit – Code, der auf einem System ausgeführt wird und ein Ergebnis zurückgibt. Ein KI-Skill vermittelt dem Modell stattdessen Wissen und Vorgehensweisen: wie es eine Aufgabe angeht, welche Schritte es befolgt und wie eine gute Ausgabe aussieht. Skills bestehen aus reinem Markdown und kommen daher ohne Server, API-Schlüssel und Laufzeitumgebung aus. Sie funktionieren mit jedem Modell.

Alle anzeigen

Jetzt eigenen KI-Arbeitsbereich einrichten

Abonnieren Sie unseren Newsletter und erfahren Sie mehr über neue Funktionen und kommende Gewinnspiele 👇