pku-yuangroup/openai4s/bio-alignment-files-alignment-filtering
Claude Code and agent skill by pku-yuangroup/openai4s
- community
Checking that the SKILL.md file is still in the repository.
Filter alignments by flags, mapping quality, and regions using samtools view and pysam. Use when extracting specific reads, removing low-quality alignments, or subsetting to target regions.
Install
npx vskill@latest install pku-yuangroup/openai4s/bio-alignment-files-alignment-filteringSKILL.md
The same SKILL.md was published earlier as pku-yuangroup/openai4s/bio-alignment-files-alignment-filtering.
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>thenhelp(module.function)to check signatures - CLI:
<tool> --versionthen<tool> --helpto 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.
Alignment Filtering
"Filter my BAM file to keep only high-quality reads" -> Select reads by FLAG bits, mapping quality, and genomic regions using samtools view or pysam.
- CLI:
samtools viewwith-F/-f/-q/-Lflags (samtools) - Python:
pysam.AlignmentFileiteration with attribute filters (pysam)
Filter alignments by flags, quality, and regions using samtools and pysam.
Filter Flags
| Option | Description | |
|---|---|---|
-f FLAG | Include reads with ALL bits set | |
-F FLAG | Exclude reads with ANY bits set | |
-G FLAG | Exclude reads with ALL bits set | |
-q MAPQ | Minimum mapping quality | |
-L BED | Include reads overlapping regions |
Common FLAG Values
| Flag | Hex | Meaning | |
|---|---|---|---|
| 1 | 0x1 | Paired | |
| 2 | 0x2 | Proper pair | |
| 4 | 0x4 | Unmapped | |
| 8 | 0x8 | Mate unmapped | |
| 16 | 0x10 | Reverse strand | |
| 32 | 0x20 | Mate reverse strand | |
| 64 | 0x40 | First in pair (read1) | |
| 128 | 0x80 | Second in pair (read2) | |
| 256 | 0x100 | Secondary alignment | |
| 512 | 0x200 | Failed QC | |
| 1024 | 0x400 | Duplicate | |
| 2048 | 0x800 | Supplementary |
Filter by FLAG
Keep Only Mapped Reads
Keep Only Unmapped Reads
Keep Only Properly Paired
Remove Duplicates
Remove Secondary and Supplementary
Keep Only Primary Alignments
Keep Read1 Only
Keep Read2 Only
Forward Strand Only
Reverse Strand Only
Filter by Mapping Quality
Minimum MAPQ
MAPQ and Mapped
Aligner-Aware MAPQ Thresholds
MAPQ scales differ by aligner; the same -q 30 filter does different things. See sam-bam-basics for the full MAPQ-by-aligner table. Filtering recommendations:
| Aligner | "Drop ambiguous" | "High confidence" | |
|---|---|---|---|
| BWA-MEM / BWA-MEM2 | -q 1 | -q 30 (or -q 60 for unique only) | |
| Bowtie2 | -q 1 | -q 23 (Bowtie2 MAPQ maxes at 42 end-to-end; 23 is a community "uniquely mapped" convention derived from analysis of Bowtie2's MAPQ scoring, not stated in the official manual) | |
| STAR | -q 255 | -q 255 (STAR emits only MAPQ 0/1/3/255, 255 = unique; -q 60 is therefore equivalent to -q 255 -- there are no values between 3 and 255) | |
| HISAT2 | -q 1 | -q 60 | |
| minimap2 (DNA, long-read) | -q 1 | -q 60 | |
| pbmm2 (PacBio) | -q 1 | -q 60 |
For Phred-scaled aligners (BWA, minimap2), MAPQ Q maps to ~10^(-Q/10) probability of wrong mapping. For STAR, the only emitted values are 0/1/3/255 (sentinels, not probabilities).
Drop Ambiguous Across Aligners (Universal)
Filter by Region
Single Region
Multiple Regions
Regions from BED File
Combine Region and Quality
Combined Filters
Standard Quality Filter
Goal: Produce a clean BAM containing only primary, mapped, non-duplicate reads with high mapping confidence.
Approach: Combine FLAG exclusion (-F for unmapped + secondary + duplicate + supplementary) with a MAPQ threshold.
Reference (samtools 1.19+):
Variant Calling Prep -- Assay-Aware
Goal: Choose a filter that matches what the downstream caller expects. Stripping supplementary alignments breaks SV callers; requiring proper-pair drops valid spliced RNA-seq reads.
| Assay / caller | Recommended filter | Why | |
|---|---|---|---|
| Germline WGS short-variant (HaplotypeCaller, DeepVariant) | -f 2 -F 3328 -q 20 | Primary, no dup, proper pair, MAPQ>=20 | |
| Somatic short-variant (Mutect2, Strelka2) | -F 3328 -q 1 | Drop only MAPQ=0; somatic callers handle low MAPQ; chimeric reads at SVs may carry real somatic SNVs | |
| Long-read short-variant (clair3, DeepVariant ONT) | -F 3328 -q 5 | Long-read MAPQ scale is lower | |
| Long-read SV (Sniffles, cuteSV) | -F 1024 only | Keep supplementary -- SA tag is the SV signal | |
| Short-read SV (Manta, GRIDSS, Delly, SvABA) | -F 1024 only | Same -- supplementary required | |
| ChIP-seq peak calling | -F 1804 -q 30 | Drop dup + secondary + unmapped + mate-unmapped + QC-fail (supplementary reads are kept -- 1804 has no 2048 bit) | |
| ATAC-seq | -F 1804 -q 30 -f 2 | Same plus proper pair | |
| RNA-seq quantification (STAR) | -q 255 | Unique only (STAR sentinel) | |
| RNA-seq quantification (HISAT2) | -F 256 -q 60 | Different aligner semantics | |
RNA-seq variant (after SplitNCigarReads) | -F 3328 -q 20 | Standard germline after split-N-trim | |
| Panel / amplicon | After samtools ampliconclip; -F 1024 -q 20 | Primer overlap makes proper-pair unreliable | |
| ctDNA / cfDNA (UMI) | After fgbio consensus; do not pre-filter raw |
Reference (samtools 1.19+):
Cost of getting this wrong: filtering -F 2304 or -F 3328 before SV calling produces zero SV calls -- a single-flag mistake that silently invalidates the analysis.
Subsample Reads (Deterministic, Pair-Consistent)
samtools view -s SEED.FRAC -- integer is the hash seed; fractional is the keep fraction. The hash is on QNAME, so:
- Mate consistency: read1 and read2 are kept or dropped together.
- Reproducibility: same seed + same fraction returns the same reads.
- Sequential downsampling requires different seeds. With the same seed the keep-sets are nested, so
-s 1.5then-s 1.25keeps a nested 1/4 (25%) of the original, not 12.5%. Use different integer seeds for independent samples.
A subsampled BAM without an integer seed (-s 0.1) is non-reproducible -- production pipelines should reject it.
Expression Filtering
samtools view -e EXPR (or --expr, since samtools 1.12; the sclen helper used below and improved null-tag handling arrived in 1.16) supports arbitrary expression filtering on tags, FLAG, MAPQ, RNAME, CIGAR, etc. Powerful for filtering by NM, AS, NH, cs, etc. that the FLAG-based filters cannot reach:
Note: in samtools 1.16+, ![NM] is true only if NM is missing (was buggy in earlier versions); NULL values from missing tags propagate through arithmetic.
Filter by Read Group
pysam Python Alternative
Basic Filtering
Filter with Function
Goal: Apply a multi-criteria quality filter to produce clean alignments for downstream analysis.
Approach: Define a predicate checking mapped status, primary alignment, duplicate flag, and MAPQ; stream reads through it.
Reference (pysam 0.22+):
Filter by Region
Filter from BED File
Goal: Extract only reads overlapping target regions defined in a BED file.
Approach: Parse BED into a list of (chrom, start, end) tuples, then fetch reads from each region and write to output.
Reference (pysam 0.22+):
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/bioskills/bio-alignment-files-alignment-filtering/SKILL.md
Popularity
- 7-day trend score
- 5
Not refreshed yet.
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Grok Build (Cursor)
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/pku-yuangroup/openai4s/bio-alignment-files-alignment-filtering)