Bio Sam Bam Basics logo

Bio Sam Bam Basics

Organization
PKU-YuanGroup
bio-sam-bam-basics

View, convert, and understand SAM/BAM/CRAM alignment files using samtools and pysam. Use when inspecting alignments, converting between formats, or understanding alignment file structure.

Overview

PublisherPKU-YuanGroup
RepositoryOpenAI4S
Skill namebio-sam-bam-basics
Stars
622
Forks
72
Bundled files
3
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 3 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by PKU-YuanGroup on GitHub. Read the source before you install it.

Installation

Install the Bio Sam Bam Basics AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/PKU-YuanGroup/OpenAI4S/tree/main/skills/bioskills/bio-alignment-files-sam-bam-basics
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/PKU-YuanGroup/OpenAI4S.git /tmp/OpenAI4S
mkdir -p .claude/skills
cp -r /tmp/OpenAI4S/skills/bioskills/bio-alignment-files-sam-bam-basics .claude/skills/bio-sam-bam-basics
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Bio Sam Bam Basics in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Bio Sam Bam Basics on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Bio Sam Bam Basics is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Version Compatibility

Reference examples tested with: pysam 0.22+, samtools 1.19+

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

  • Python: pip show <package> then help(module.function) to check signatures
  • CLI: <tool> --version then <tool> --help to confirm flags

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

SAM/BAM/CRAM Basics

"Read a BAM file" -> Open a binary alignment file and iterate over aligned reads with their mapping coordinates, flags, and quality scores.

  • Python: pysam.AlignmentFile() (pysam)
  • CLI: samtools view (samtools)
  • R: scanBam() (Rsamtools)

View and convert alignment files using samtools and pysam.

Format Overview

FormatDescriptionUse Case
SAMText format, human-readableDebugging, small files
BAMBinary compressed SAMStandard storage format
CRAMReference-based compressionLong-term archival, smaller than BAM

SAM Format Structure

@HD VN:1.6 SO:coordinate
@SQ SN:chr1 LN:248956422
@RG ID:sample1 SM:sample1
@PG ID:bwa PN:bwa VN:0.7.17
read1  0   chr1  100  60  50M  *  0  0  ACGT...  FFFF...  NM:i:0

Header lines start with @:

  • @HD - Header metadata (version, sort order)
  • @SQ - Reference sequence dictionary
  • @RG - Read group information
  • @PG - Program used to create file

Alignment fields (tab-separated):

  1. QNAME - Read name
  2. FLAG - Bitwise flag
  3. RNAME - Reference name
  4. POS - 1-based position
  5. MAPQ - Mapping quality
  6. CIGAR - Alignment description
  7. RNEXT - Mate reference
  8. PNEXT - Mate position
  9. TLEN - Template length
  10. SEQ - Read sequence
  11. QUAL - Base qualities
  12. Optional tags (NM:i:0, MD:Z:50, etc.)

samtools view

View BAM as SAM

bash
samtools view input.bam | head

View with Header

bash
samtools view -h input.bam | head -100

View Header Only

bash
samtools view -H input.bam

View Specific Region

bash
samtools view input.bam chr1:1000-2000

Count Alignments

bash
samtools view -c input.bam

Format Conversion

Goal: Convert between SAM (text), BAM (binary), and CRAM (reference-compressed) alignment formats.

Approach: Use samtools view with format flags (-b for BAM, -C for CRAM, -h for SAM with header). CRAM requires a reference FASTA with -T.

BAM to SAM

bash
samtools view -h -o output.sam input.bam

SAM to BAM

bash
samtools view -b -o output.bam input.sam

BAM to CRAM

bash
samtools view -C -T reference.fa -o output.cram input.bam

CRAM to BAM

bash
samtools view -b -T reference.fa -o output.bam input.cram

Pipe Conversion

bash
samtools view -b input.sam > output.bam

Common Flags

FlagDecimalMeaning
0x11Paired
0x22Proper pair
0x44Unmapped
0x88Mate unmapped
0x1016Reverse strand
0x2032Mate reverse strand
0x4064First in pair
0x80128Second in pair
0x100256Secondary alignment
0x200512Failed QC
0x4001024PCR duplicate
0x8002048Supplementary

Decode Flags (Bidirectional)

bash
# Number to mnemonics
samtools flags 147
# 0x93 147 PAIRED,PROPER_PAIR,REVERSE,READ2

# Mnemonics to number
samtools flags PAIRED,PROPER_PAIR,REVERSE,READ2   # 147

Secondary vs Supplementary (Different Semantics)

Two different concepts that are routinely conflated:

BitNameMeaningFilter implication
0x100 (256)SecondaryAn alternative candidate alignment for the same read; not the primary location-F 256 is correct for SNV/indel calling on short reads
0x800 (2048)SupplementaryA piece of a chimeric/split alignment (the read is split across loci)Carries SA:Z tag; required by SV callers (Manta, Sniffles, cuteSV, GRIDSS, Delly)

-F 2304 removes both. Strip supplementary only when downstream is small-variant calling; keep supplementary for SV calling, fusion detection, or any analysis that follows split-reads.

MAPQ Is Not Portable Across Aligners

samtools view -q 30 does different things depending on what produced the BAM. MAPQ is an aligner-specific scale, not a universal probability:

AlignerMAPQ scale"Unique" sentinelCommon gotcha
BWA-MEM / BWA-MEM20-6060-q 30 is sensible "high confidence"
minimap2 (DNA / pbmm2)0-6060Spec-compliant
HISAT20-6060Spec-compliant
Bowtie20-4242 (rare)-q 60 drops everything; -q 23 is a common "uniquely mapped" convention (not a probabilistic 99% threshold)
STAR0, 1, 3, 255255 = uniquely mapped (sentinel, not a quality)-q 255 for "unique only"; -q 30 accidentally keeps unique only too
DRAGEN0 to --mapq-max (default 60)varies-q 30 still meaningful; distribution shape differs
Cell Ranger / STARsoloinherits STAR255Same trap as STAR

Verify the actual scale of any unfamiliar BAM:

bash
samtools view input.bam | awk '{print $5}' | sort -un | head
samtools view -H input.bam | grep '^@PG' | head -1   # which aligner produced this BAM

0-Based vs 1-Based Coordinates (Footgun)

ContextCoordinate system
SAM text POS1-based, inclusive
samtools view chr1:100-2001-based, closed interval
samtools faidx chr1:100-2001-based, closed interval
BAM binary internal0-based, half-open
pysam read.reference_start0-based
bam.fetch('chr1', 100, 200)0-based, half-open
BED files0-based, half-open
VCF1-based
GFF/GTF1-based, inclusive

samtools view bam chr1:100-200 and bam.fetch('chr1', 100, 200) return different read sets at boundaries.

CIGAR Operations

OpDescription
MAlignment match (can be mismatch)
IInsertion to reference
DDeletion from reference
NSkipped region (introns in RNA-seq; do NOT count as covered bases)
SSoft clipping (sequence in SEQ but not aligned)
HHard clipping (sequence not in SEQ)
=Sequence match (explicit)
XSequence mismatch (explicit)
PPadding (rare; multiple-sequence-alignment context)

Example: 50M2I30M = 50 bases match, 2 base insertion, 30 bases match

CIGAR M is overloaded -- it is the union of = and X. Some aligners emit =/X directly (e.g. minimap2 with --eqx); bcftools / Picard often need M and rebuild MD/NM with samtools calmd. N operations break naive coverage calculations: a 1000 bp RNA-seq read with one 50 kb intron does not cover 50 kb. Distinguish soft-clip (S, bases retained) from hard-clip (H, bases discarded -- irreversible).

Context-Specific Tags

Beyond the standard fields, downstream tools depend on optional tags whose presence depends on aligner and assay. Inspect with samtools view input.bam | head -1 | tr '\t' '\n' or pysam read.get_tag('XX').

TagSet byMeaningRequired by
NM:ibwa, samtools calmdEdit distance to referencemapDamage, many filters
MD:Zbwa, samtools calmdMismatch positions (text)bcftools mpileup BAQ, IGV mismatch coloring
MC:Zsamtools fixmate -mMate CIGARsamtools markdup
ms:isamtools fixmate -mMate score (lowercase per SAMtags)samtools markdup
RG:Zaligner from -RRead group IDGATK BQSR, MarkDuplicates LB lookup
SA:ZAll split-read alignersComma-list of supplementary coordsSniffles, Manta, cuteSV, GRIDSS, Delly
NH:iSTAR, HISAT2Number of reported hitsfeatureCounts multimapper handling, Salmon
HI:iSTARHit index among NH (1-based by default; --outSAMattrIHstart 0 for 0-based)RSEM
XS:ASTAR (--outSAMstrandField intronMotif), HISAT2Strand inferred from splice motifStringTie, Cufflinks
ts:Aminimap2 -ax spliceTranscript strand from splice motifStringTie
CB:ZCell Ranger, STARsoloCorrected cell barcodescRNA quantification
UB:ZCell Ranger, STARsoloCorrected UMIUMI-aware dedup
RX:Zfgbio AnnotateBamWithUmisRaw UMI (bulk)fgbio GroupReadsByUmi
MI:Zfgbio GroupReadsByUmiMolecular identifier (UMI group)CallMolecularConsensusReads, duplex calling
cs:Zminimap2 --csCompact CIGAR-with-basespaftools, SV tools

Missing tags fail in two modes: silently wrong (featureCounts ignoring multimappers without NH; markdup marking nothing without MC/MS) or loudly (consensus tools rejecting input without MD).

Provenance: @PG Chain

The @PG lines record every tool that touched the BAM, linked through PP (previous program) tags. This is the audit trail.

bash
samtools view -H input.bam | grep '^@PG'

A clean germline pipeline:

@PG ID:bwa-mem PN:bwa VN:0.7.17
@PG ID:samtools.1 PN:samtools VN:1.20 PP:bwa-mem CL:samtools sort
@PG ID:samtools.2 PN:samtools VN:1.20 PP:samtools.1 CL:samtools fixmate
@PG ID:samtools.3 PN:samtools VN:1.20 PP:samtools.2 CL:samtools markdup

A broken/missing chain (no PP, unknown tools, gaps) means the BAM cannot be reliably reproduced. Production pipelines often reject inputs without a complete chain.

CRAM Reference Resolution (Critical)

CRAM stores reads relative to a reference; without it, the file is unreadable. htslib resolves the reference in this order:

  1. Command-line -T ref.fa / --reference
  2. REF_CACHE env var (local MD5-named cache; searched before REF_PATH)
  3. REF_PATH env var (colon-separated; each element matched by the @SQ M5: MD5). A remote server such as EBI ENA is consulted only if its URL is present here -- it was the built-in default through htslib 1.21, but that default was removed in 1.22 to reduce EBI load, so modern htslib does no network lookup unless that URL is added explicitly.
  4. Local file named in the @SQ UR: header tag (local / file:// paths only; http/ftp URIs in UR: are ignored)

On HPC nodes without internet, populate a local cache once:

bash
mkdir -p $HOME/cram_cache
seq_cache_populate.pl -root $HOME/cram_cache reference.fa
export REF_CACHE=$HOME/cram_cache/%2s/%2s/%s
export REF_PATH=$REF_CACHE   # local only; no network/ENA lookup

samtools quickcheck -v file.cram   # header + EOF only
samtools view -c file.cram          # forces full decode; proves reference reachable

CRAM can be made irreversibly lossy, but the archive profile is NOT how: --output-fmt-option archive is a lossless maximum-compression preset (fqzcomp quality codec, name tokenization, larger slices) that does not alter bases or qualities. Irreversible loss comes instead from explicit quality binning (e.g. Illumina 8-bin), which must be applied deliberately and is harmful for low-coverage / somatic / forensic / archival data. Convert against the exact reference the BAM was aligned to (matched by @SQ M5:); a different reference silently corrupts bases on read-back.

pysam Python Alternative

Goal: Read and manipulate alignment data programmatically in Python.

Approach: Use pysam.AlignmentFile to open BAM/CRAM files, iterate over reads, and access properties like coordinates, flags, CIGAR, and tags.

Open and Iterate

python
import pysam

with pysam.AlignmentFile('input.bam', 'rb') as bam:
    for read in bam:
        print(f'{read.query_name}\t{read.reference_name}:{read.reference_start}')

Access Header

python
with pysam.AlignmentFile('input.bam', 'rb') as bam:
    for sq in bam.header['SQ']:
        print(f'{sq["SN"]}: {sq["LN"]} bp')

Read Alignment Properties

python
with pysam.AlignmentFile('input.bam', 'rb') as bam:
    for read in bam:
        print(f'Name: {read.query_name}')
        print(f'Flag: {read.flag}')
        print(f'Chrom: {read.reference_name}')
        print(f'Pos: {read.reference_start}')  # 0-based
        print(f'MAPQ: {read.mapping_quality}')
        print(f'CIGAR: {read.cigarstring}')
        print(f'Seq: {read.query_sequence}')
        print(f'Qual: {read.query_qualities}')
        break

Check Flag Properties

python
with pysam.AlignmentFile('input.bam', 'rb') as bam:
    for read in bam:
        if read.is_paired and read.is_proper_pair:
            if read.is_reverse:
                strand = '-'
            else:
                strand = '+'
            print(f'{read.query_name} on {strand} strand')

Fetch Region

python
with pysam.AlignmentFile('input.bam', 'rb') as bam:
    for read in bam.fetch('chr1', 1000, 2000):
        print(read.query_name)

Convert BAM to SAM

python
with pysam.AlignmentFile('input.bam', 'rb') as infile:
    with pysam.AlignmentFile('output.sam', 'w', header=infile.header) as outfile:
        for read in infile:
            outfile.write(read)

Convert to CRAM

python
with pysam.AlignmentFile('input.bam', 'rb') as infile:
    with pysam.AlignmentFile('output.cram', 'wc', reference_filename='reference.fa', header=infile.header) as outfile:
        for read in infile:
            outfile.write(read)

Quick Reference

Tasksamtoolspysam
View BAMsamtools view file.bamAlignmentFile('file.bam', 'rb')
View headersamtools view -H file.bambam.header
Count readssamtools view -c file.bamsum(1 for _ in bam)
Get regionsamtools view file.bam chr1:1-1000bam.fetch('chr1', 0, 1000)
BAM to SAMsamtools view -h -o out.sam in.bamOpen with 'w' mode
SAM to BAMsamtools view -b -o out.bam in.samOpen with 'wb' mode
BAM to CRAMsamtools view -C -T ref.fa -o out.cram in.bamOpen with 'wc' mode

Related Skills

  • alignment-indexing - Create indices for random access (required for fetch/region queries)
  • alignment-sorting - Sort alignments by coordinate or name
  • alignment-filtering - Filter alignments by flags, quality, regions
  • alignment-validation - Sequence dictionary cross-validation (M5 checksums)
  • bam-statistics - Generate statistics from alignment files
  • reference-operations - REF_PATH/REF_CACHE setup for CRAM
  • sequence-io/read-sequences - Parse FASTA/FASTQ input files

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Bio Sam Bam Basics AI skill do?

View, convert, and understand SAM/BAM/CRAM alignment files using samtools and pysam. Use when inspecting alignments, converting between formats, or understanding alignment file structure.

Why use Bio Sam Bam Basics on TypingMind?

Because you install it once and use it with any model. Bio Sam Bam Basics is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Bio Sam Bam Basics in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/PKU-YuanGroup/OpenAI4S/tree/main/skills/bioskills/bio-alignment-files-sam-bam-basics. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Bio Sam Bam Basics?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Bio Sam Bam Basics?

As many as you like. As long as a model supports skills, you can use Bio Sam Bam Basics with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Bio Sam Bam Basics AI skill free?

Yes. It is published on GitHub by PKU-YuanGroup under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇