[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EBDQNB8J0H7PYAWD0AW2FG":3,"skill-same:01M7EBDQNB8J0H7PYAWD0AW2FG":62},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7EBDQNB8J0H7PYAWD0AW2FG","bio-alignment-filtering",null,"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.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-filtering\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-alignment-filtering\ndescription: 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.\ntool_type: cli\nprimary_tool: samtools\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"alignment-files\u002Falignment-filtering\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: pysam 0.22+, samtools 1.19+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Alignment Filtering\n\n**\"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.\n- CLI: `samtools view` with `-F`\u002F`-f`\u002F`-q`\u002F`-L` flags (samtools)\n- Python: `pysam.AlignmentFile` iteration with attribute filters (pysam)\n\nFilter alignments by flags, quality, and regions using samtools and pysam.\n\n## Filter Flags\n\n| Option | Description |\n|--------|-------------|\n| `-f FLAG` | Include reads with ALL bits set |\n| `-F FLAG` | Exclude reads with ANY bits set |\n| `-G FLAG` | Exclude reads with ALL bits set |\n| `-q MAPQ` | Minimum mapping quality |\n| `-L BED` | Include reads overlapping regions |\n\n## Common FLAG Values\n\n| Flag | Hex | Meaning |\n|------|-----|---------|\n| 1 | 0x1 | Paired |\n| 2 | 0x2 | Proper pair |\n| 4 | 0x4 | Unmapped |\n| 8 | 0x8 | Mate unmapped |\n| 16 | 0x10 | Reverse strand |\n| 32 | 0x20 | Mate reverse strand |\n| 64 | 0x40 | First in pair (read1) |\n| 128 | 0x80 | Second in pair (read2) |\n| 256 | 0x100 | Secondary alignment |\n| 512 | 0x200 | Failed QC |\n| 1024 | 0x400 | Duplicate |\n| 2048 | 0x800 | Supplementary |\n\n## Filter by FLAG\n\n### Keep Only Mapped Reads\n```bash\nsamtools view -F 4 -o mapped.bam input.bam\n```\n\n### Keep Only Unmapped Reads\n```bash\nsamtools view -f 4 -o unmapped.bam input.bam\n```\n\n### Keep Only Properly Paired\n```bash\nsamtools view -f 2 -o proper.bam input.bam\n```\n\n### Remove Duplicates\n```bash\nsamtools view -F 1024 -o nodup.bam input.bam\n```\n\n### Remove Secondary and Supplementary\n```bash\nsamtools view -F 2304 -o primary.bam input.bam\n```\n\n### Keep Only Primary Alignments\n```bash\nsamtools view -F 256 -F 2048 -o primary.bam input.bam\n# Or combined: -F 2304\n```\n\n### Keep Read1 Only\n```bash\nsamtools view -f 64 -o read1.bam input.bam\n```\n\n### Keep Read2 Only\n```bash\nsamtools view -f 128 -o read2.bam input.bam\n```\n\n### Forward Strand Only\n```bash\nsamtools view -F 16 -o forward.bam input.bam\n```\n\n### Reverse Strand Only\n```bash\nsamtools view -f 16 -o reverse.bam input.bam\n```\n\n## Filter by Mapping Quality\n\n### Minimum MAPQ\n```bash\nsamtools view -q 30 -o highqual.bam input.bam\n```\n\n### MAPQ and Mapped\n```bash\nsamtools view -F 4 -q 30 -o filtered.bam input.bam\n```\n\n### Aligner-Aware MAPQ Thresholds\n\nMAPQ 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:\n\n| Aligner | \"Drop ambiguous\" | \"High confidence\" |\n|---------|------------------|-------------------|\n| BWA-MEM \u002F BWA-MEM2 | `-q 1` | `-q 30` (or `-q 60` for unique only) |\n| 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) |\n| **STAR** | `-q 255` | `-q 255` (STAR emits only MAPQ 0\u002F1\u002F3\u002F255, 255 = unique; `-q 60` is therefore equivalent to `-q 255` -- there are no values between 3 and 255) |\n| HISAT2 | `-q 1` | `-q 60` |\n| minimap2 (DNA, long-read) | `-q 1` | `-q 60` |\n| pbmm2 (PacBio) | `-q 1` | `-q 60` |\n\nFor Phred-scaled aligners (BWA, minimap2), MAPQ Q maps to ~10^(-Q\u002F10) probability of wrong mapping. For STAR, the only emitted values are 0\u002F1\u002F3\u002F255 (sentinels, not probabilities).\n\n### Drop Ambiguous Across Aligners (Universal)\n```bash\nsamtools view -q 1 in.bam   # exclude MAPQ=0; works for all aligners\n```\n\n## Filter by Region\n\n### Single Region\n```bash\nsamtools view -o region.bam input.bam chr1:1000000-2000000\n```\n\n### Multiple Regions\n```bash\nsamtools view -o regions.bam input.bam chr1:1000-2000 chr2:3000-4000\n```\n\n### Regions from BED File\n```bash\nsamtools view -L targets.bed -o targets.bam input.bam\n```\n\n### Combine Region and Quality\n```bash\nsamtools view -q 30 -L targets.bed -o filtered.bam input.bam\n```\n\n## Combined Filters\n\n### Standard Quality Filter\n\n**Goal:** Produce a clean BAM containing only primary, mapped, non-duplicate reads with high mapping confidence.\n\n**Approach:** Combine FLAG exclusion (-F for unmapped + secondary + duplicate + supplementary) with a MAPQ threshold.\n\n**Reference (samtools 1.19+):**\n```bash\nsamtools view -F 3332 -q 30 -o filtered.bam input.bam\n# 3332 = 4 (unmapped) + 256 (secondary) + 1024 (duplicate) + 2048 (supplementary)\n```\n\n### Variant Calling Prep -- Assay-Aware\n\n**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.\n\n| Assay \u002F caller | Recommended filter | Why |\n|----------------|-------------------|-----|\n| Germline WGS short-variant (HaplotypeCaller, DeepVariant) | `-f 2 -F 3328 -q 20` | Primary, no dup, proper pair, MAPQ>=20 |\n| 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 |\n| Long-read short-variant (clair3, DeepVariant ONT) | `-F 3328 -q 5` | Long-read MAPQ scale is lower |\n| Long-read SV (Sniffles, cuteSV) | `-F 1024` only | **Keep supplementary** -- SA tag is the SV signal |\n| Short-read SV (Manta, GRIDSS, Delly, SvABA) | `-F 1024` only | Same -- supplementary required |\n| 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) |\n| ATAC-seq | `-F 1804 -q 30 -f 2` | Same plus proper pair |\n| RNA-seq quantification (STAR) | `-q 255` | Unique only (STAR sentinel) |\n| RNA-seq quantification (HISAT2) | `-F 256 -q 60` | Different aligner semantics |\n| RNA-seq variant (after `SplitNCigarReads`) | `-F 3328 -q 20` | Standard germline after split-N-trim |\n| Panel \u002F amplicon | After `samtools ampliconclip`; `-F 1024 -q 20` | Primer overlap makes proper-pair unreliable |\n| ctDNA \u002F cfDNA (UMI) | After fgbio consensus; do not pre-filter raw | |\n\n**Reference (samtools 1.19+):**\n```bash\n# Short-variant germline\nsamtools view -f 2 -F 3328 -q 20 -o clean.bam input.bam\n# 3328 = 256 (secondary) + 1024 (duplicate) + 2048 (supplementary)\n\n# SV calling: KEEP supplementary\nsamtools view -F 1024 -o sv_input.bam input.bam   # NOT -F 2304 or -F 3328\n\n# ChIP-seq \u002F ATAC-seq common filter\nsamtools view -F 1804 -q 30 -o filtered.bam input.bam\n# 1804 = 4 + 8 + 256 + 512 + 1024 = unmapped + mate-unmapped + secondary + QC-fail + duplicate\n```\n\n**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.\n\n## Subsample Reads (Deterministic, Pair-Consistent)\n\n`samtools view -s SEED.FRAC` -- integer is the hash seed; fractional is the keep fraction. The hash is on QNAME, so:\n1. Mate consistency: read1 and read2 are kept or dropped together.\n2. Reproducibility: same seed + same fraction returns the same reads.\n3. **Sequential downsampling requires different seeds.** With the same seed the keep-sets are nested, so `-s 1.5` then `-s 1.25` keeps a nested 1\u002F4 (25%) of the original, not 12.5%. Use different integer seeds for independent samples.\n\n```bash\n# 10% with seed 42 (always the same reads; pair-consistent)\nsamtools view -s 42.1 -b -o subset.bam input.bam\n\n# Sequential cuts with INDEPENDENT seeds\nsamtools view -s 1.5 -b in.bam > half1.bam\nsamtools view -s 2.25 -b half1.bam > quarter.bam   # 12.5% of original\n\n# Coverage-matching to a target read count\ntotal=$(samtools view -c -F 2304 input.bam)\ntarget=10000000\nfrac=$(awk -v t=$target -v n=$total 'BEGIN{printf \"%.6f\", t\u002Fn}')\nsamtools view -s \"1.${frac#*.}\" -b -o matched.bam input.bam\n\n# Tumor-normal coverage matching (pull tumor down to normal)\nnormal_reads=$(samtools view -c -F 2308 normal.bam)\ntumor_reads=$(samtools view -c -F 2308 tumor.bam)\nif [ \"$tumor_reads\" -gt \"$normal_reads\" ]; then\n    frac=$(awk -v n=$normal_reads -v t=$tumor_reads 'BEGIN{printf \"%.6f\", n\u002Ft}')\n    samtools view -s \"1.${frac#*.}\" -b -o tumor_matched.bam tumor.bam\nfi\n```\n\nA subsampled BAM without an integer seed (`-s 0.1`) is non-reproducible -- production pipelines should reject it.\n\n## Expression Filtering\n\n`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:\n```bash\n# Reads with >=2 mismatches (NM tag)\nsamtools view -e '[NM] >= 2' in.bam\n\n# Soft clip on the left, on chr1\nsamtools view -e 'cigar=~\"^[0-9]+S\" && rname==\"chr1\"' in.bam\n\n# Combine with FLAG and MAPQ\nsamtools view -F 2308 -q 30 -e '[NM] \u003C= 5 && [AS] >= 100' in.bam\n\n# Drop reads with low mapped fraction (samtools-internal helpers)\nsamtools view -e 'sclen \u002F qlen \u003C 0.2' in.bam\n```\n\nNote: 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.\n\n## Filter by Read Group\n```bash\nsamtools view -r library_A in.bam              # single read group\nsamtools view -R rg_list.txt in.bam            # multiple via file (one ID per line)\n```\n\n## pysam Python Alternative\n\n### Basic Filtering\n```python\nimport pysam\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('filtered.bam', 'wb', header=infile.header) as outfile:\n        for read in infile:\n            if read.is_unmapped:\n                continue\n            if read.mapping_quality \u003C 30:\n                continue\n            if read.is_duplicate:\n                continue\n            outfile.write(read)\n```\n\n### Filter with Function\n\n**Goal:** Apply a multi-criteria quality filter to produce clean alignments for downstream analysis.\n\n**Approach:** Define a predicate checking mapped status, primary alignment, duplicate flag, and MAPQ; stream reads through it.\n\n**Reference (pysam 0.22+):**\n```python\nimport pysam\n\ndef passes_filter(read):\n    if read.is_unmapped:\n        return False\n    if read.is_secondary or read.is_supplementary:\n        return False\n    if read.is_duplicate:\n        return False\n    if read.mapping_quality \u003C 30:\n        return False\n    return True\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('filtered.bam', 'wb', header=infile.header) as outfile:\n        for read in infile:\n            if passes_filter(read):\n                outfile.write(read)\n```\n\n### Filter by Region\n```python\nimport pysam\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('region.bam', 'wb', header=infile.header) as outfile:\n        for read in infile.fetch('chr1', 1000000, 2000000):\n            outfile.write(read)\n```\n\n### Filter from BED File\n\n**Goal:** Extract only reads overlapping target regions defined in a BED file.\n\n**Approach:** Parse BED into a list of (chrom, start, end) tuples, then fetch reads from each region and write to output.\n\n**Reference (pysam 0.22+):**\n```python\nimport pysam\n\ndef read_bed(bed_path):\n    regions = []\n    with open(bed_path) as f:\n        for line in f:\n            if line.startswith('#'):\n                continue\n            parts = line.strip().split('\\t')\n            regions.append((parts[0], int(parts[1]), int(parts[2])))\n    return regions\n\nregions = read_bed('targets.bed')\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('targets.bam', 'wb', header=infile.header) as outfile:\n        for chrom, start, end in regions:\n            for read in infile.fetch(chrom, start, end):\n                outfile.write(read)\n```\n\n### Subsample (Pair-Consistent)\n\nHash on QNAME so mates stay together (a fresh `random.random()` per read drops mates inconsistently and breaks paired-end tools):\n```python\nimport pysam\nimport zlib\n\nfraction = 0.1\nseed = 42\nthreshold = int(0xffffffff * fraction)\n\ndef template_hash(qname, seed):\n    return zlib.crc32(qname.encode()) ^ seed\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('subset.bam', 'wb', header=infile.header) as outfile:\n        for read in infile:\n            if template_hash(read.query_name, seed) \u003C= threshold:\n                outfile.write(read)\n```\n\n## Quick Reference\n\n| Task | samtools command |\n|------|------------------|\n| Mapped only | `view -F 4` |\n| Unmapped only | `view -f 4` |\n| Properly paired | `view -f 2` |\n| Primary only | `view -F 2304` |\n| No duplicates | `view -F 1024` |\n| High MAPQ | `view -q 30` |\n| Region | `view file.bam chr1:1-1000` |\n| BED regions | `view -L file.bed` |\n| Subsample 10% (reproducible) | `view -s 42.1` |\n| Standard filter | `view -F 3332 -q 30` |\n\n## Common Filter Combinations\n\n| Purpose | Flags |\n|---------|-------|\n| Clean reads | `-F 3332 -q 30` (mapped, primary, no dups, high qual) |\n| Variant calling | `-f 2 -F 3328 -q 20` (proper pair, primary, no dups) |\n| Coverage analysis | `-F 1284 -q 1` (mapped, no secondary, no dups; supplementary retained) |\n| Count unique | `-F 2304` (primary only) |\n\nFlag breakdowns:\n- 2304 = 256 + 2048 (secondary + supplementary)\n- 3328 = 256 + 1024 + 2048 (secondary + duplicate + supplementary)\n- 3332 = 4 + 256 + 1024 + 2048 (unmapped + secondary + duplicate + supplementary)\n- 1284 = 4 + 256 + 1024 (unmapped + secondary + duplicate)\n\n## Related Skills\n\n- sam-bam-basics - FLAG semantics, MAPQ-by-aligner, secondary vs supplementary\n- alignment-sorting - Sort before\u002Fafter filtering\n- alignment-indexing - Required for region filtering\n- alignment-amplicon-clipping - Primer clipping for amplicon panels\n- duplicate-handling - Mark duplicates before filtering\n- bam-statistics - Check filter effects\n","## Version Compatibility\n\nReference examples tested with: pysam 0.22+, samtools 1.19+\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show \u003Cpackage>` then `help(module.function)` to check signatures\n- CLI: `\u003Ctool> --version` then `\u003Ctool> --help` to confirm flags\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed\npackage and adapt the example to match the actual API rather than retrying.\n\n# Alignment Filtering\n\n**\"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.\n- CLI: `samtools view` with `-F`\u002F`-f`\u002F`-q`\u002F`-L` flags (samtools)\n- Python: `pysam.AlignmentFile` iteration with attribute filters (pysam)\n\nFilter alignments by flags, quality, and regions using samtools and pysam.\n\n## Filter Flags\n\n| Option | Description |\n|--------|-------------|\n| `-f FLAG` | Include reads with ALL bits set |\n| `-F FLAG` | Exclude reads with ANY bits set |\n| `-G FLAG` | Exclude reads with ALL bits set |\n| `-q MAPQ` | Minimum mapping quality |\n| `-L BED` | Include reads overlapping regions |\n\n## Common FLAG Values\n\n| Flag | Hex | Meaning |\n|------|-----|---------|\n| 1 | 0x1 | Paired |\n| 2 | 0x2 | Proper pair |\n| 4 | 0x4 | Unmapped |\n| 8 | 0x8 | Mate unmapped |\n| 16 | 0x10 | Reverse strand |\n| 32 | 0x20 | Mate reverse strand |\n| 64 | 0x40 | First in pair (read1) |\n| 128 | 0x80 | Second in pair (read2) |\n| 256 | 0x100 | Secondary alignment |\n| 512 | 0x200 | Failed QC |\n| 1024 | 0x400 | Duplicate |\n| 2048 | 0x800 | Supplementary |\n\n## Filter by FLAG\n\n### Keep Only Mapped Reads\n```bash\nsamtools view -F 4 -o mapped.bam input.bam\n```\n\n### Keep Only Unmapped Reads\n```bash\nsamtools view -f 4 -o unmapped.bam input.bam\n```\n\n### Keep Only Properly Paired\n```bash\nsamtools view -f 2 -o proper.bam input.bam\n```\n\n### Remove Duplicates\n```bash\nsamtools view -F 1024 -o nodup.bam input.bam\n```\n\n### Remove Secondary and Supplementary\n```bash\nsamtools view -F 2304 -o primary.bam input.bam\n```\n\n### Keep Only Primary Alignments\n```bash\nsamtools view -F 256 -F 2048 -o primary.bam input.bam\n# Or combined: -F 2304\n```\n\n### Keep Read1 Only\n```bash\nsamtools view -f 64 -o read1.bam input.bam\n```\n\n### Keep Read2 Only\n```bash\nsamtools view -f 128 -o read2.bam input.bam\n```\n\n### Forward Strand Only\n```bash\nsamtools view -F 16 -o forward.bam input.bam\n```\n\n### Reverse Strand Only\n```bash\nsamtools view -f 16 -o reverse.bam input.bam\n```\n\n## Filter by Mapping Quality\n\n### Minimum MAPQ\n```bash\nsamtools view -q 30 -o highqual.bam input.bam\n```\n\n### MAPQ and Mapped\n```bash\nsamtools view -F 4 -q 30 -o filtered.bam input.bam\n```\n\n### Aligner-Aware MAPQ Thresholds\n\nMAPQ 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:\n\n| Aligner | \"Drop ambiguous\" | \"High confidence\" |\n|---------|------------------|-------------------|\n| BWA-MEM \u002F BWA-MEM2 | `-q 1` | `-q 30` (or `-q 60` for unique only) |\n| 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) |\n| **STAR** | `-q 255` | `-q 255` (STAR emits only MAPQ 0\u002F1\u002F3\u002F255, 255 = unique; `-q 60` is therefore equivalent to `-q 255` -- there are no values between 3 and 255) |\n| HISAT2 | `-q 1` | `-q 60` |\n| minimap2 (DNA, long-read) | `-q 1` | `-q 60` |\n| pbmm2 (PacBio) | `-q 1` | `-q 60` |\n\nFor Phred-scaled aligners (BWA, minimap2), MAPQ Q maps to ~10^(-Q\u002F10) probability of wrong mapping. For STAR, the only emitted values are 0\u002F1\u002F3\u002F255 (sentinels, not probabilities).\n\n### Drop Ambiguous Across Aligners (Universal)\n```bash\nsamtools view -q 1 in.bam   # exclude MAPQ=0; works for all aligners\n```\n\n## Filter by Region\n\n### Single Region\n```bash\nsamtools view -o region.bam input.bam chr1:1000000-2000000\n```\n\n### Multiple Regions\n```bash\nsamtools view -o regions.bam input.bam chr1:1000-2000 chr2:3000-4000\n```\n\n### Regions from BED File\n```bash\nsamtools view -L targets.bed -o targets.bam input.bam\n```\n\n### Combine Region and Quality\n```bash\nsamtools view -q 30 -L targets.bed -o filtered.bam input.bam\n```\n\n## Combined Filters\n\n### Standard Quality Filter\n\n**Goal:** Produce a clean BAM containing only primary, mapped, non-duplicate reads with high mapping confidence.\n\n**Approach:** Combine FLAG exclusion (-F for unmapped + secondary + duplicate + supplementary) with a MAPQ threshold.\n\n**Reference (samtools 1.19+):**\n```bash\nsamtools view -F 3332 -q 30 -o filtered.bam input.bam\n# 3332 = 4 (unmapped) + 256 (secondary) + 1024 (duplicate) + 2048 (supplementary)\n```\n\n### Variant Calling Prep -- Assay-Aware\n\n**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.\n\n| Assay \u002F caller | Recommended filter | Why |\n|----------------|-------------------|-----|\n| Germline WGS short-variant (HaplotypeCaller, DeepVariant) | `-f 2 -F 3328 -q 20` | Primary, no dup, proper pair, MAPQ>=20 |\n| 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 |\n| Long-read short-variant (clair3, DeepVariant ONT) | `-F 3328 -q 5` | Long-read MAPQ scale is lower |\n| Long-read SV (Sniffles, cuteSV) | `-F 1024` only | **Keep supplementary** -- SA tag is the SV signal |\n| Short-read SV (Manta, GRIDSS, Delly, SvABA) | `-F 1024` only | Same -- supplementary required |\n| 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) |\n| ATAC-seq | `-F 1804 -q 30 -f 2` | Same plus proper pair |\n| RNA-seq quantification (STAR) | `-q 255` | Unique only (STAR sentinel) |\n| RNA-seq quantification (HISAT2) | `-F 256 -q 60` | Different aligner semantics |\n| RNA-seq variant (after `SplitNCigarReads`) | `-F 3328 -q 20` | Standard germline after split-N-trim |\n| Panel \u002F amplicon | After `samtools ampliconclip`; `-F 1024 -q 20` | Primer overlap makes proper-pair unreliable |\n| ctDNA \u002F cfDNA (UMI) | After fgbio consensus; do not pre-filter raw | |\n\n**Reference (samtools 1.19+):**\n```bash\n# Short-variant germline\nsamtools view -f 2 -F 3328 -q 20 -o clean.bam input.bam\n# 3328 = 256 (secondary) + 1024 (duplicate) + 2048 (supplementary)\n\n# SV calling: KEEP supplementary\nsamtools view -F 1024 -o sv_input.bam input.bam   # NOT -F 2304 or -F 3328\n\n# ChIP-seq \u002F ATAC-seq common filter\nsamtools view -F 1804 -q 30 -o filtered.bam input.bam\n# 1804 = 4 + 8 + 256 + 512 + 1024 = unmapped + mate-unmapped + secondary + QC-fail + duplicate\n```\n\n**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.\n\n## Subsample Reads (Deterministic, Pair-Consistent)\n\n`samtools view -s SEED.FRAC` -- integer is the hash seed; fractional is the keep fraction. The hash is on QNAME, so:\n1. Mate consistency: read1 and read2 are kept or dropped together.\n2. Reproducibility: same seed + same fraction returns the same reads.\n3. **Sequential downsampling requires different seeds.** With the same seed the keep-sets are nested, so `-s 1.5` then `-s 1.25` keeps a nested 1\u002F4 (25%) of the original, not 12.5%. Use different integer seeds for independent samples.\n\n```bash\n# 10% with seed 42 (always the same reads; pair-consistent)\nsamtools view -s 42.1 -b -o subset.bam input.bam\n\n# Sequential cuts with INDEPENDENT seeds\nsamtools view -s 1.5 -b in.bam > half1.bam\nsamtools view -s 2.25 -b half1.bam > quarter.bam   # 12.5% of original\n\n# Coverage-matching to a target read count\ntotal=$(samtools view -c -F 2304 input.bam)\ntarget=10000000\nfrac=$(awk -v t=$target -v n=$total 'BEGIN{printf \"%.6f\", t\u002Fn}')\nsamtools view -s \"1.${frac#*.}\" -b -o matched.bam input.bam\n\n# Tumor-normal coverage matching (pull tumor down to normal)\nnormal_reads=$(samtools view -c -F 2308 normal.bam)\ntumor_reads=$(samtools view -c -F 2308 tumor.bam)\nif [ \"$tumor_reads\" -gt \"$normal_reads\" ]; then\n    frac=$(awk -v n=$normal_reads -v t=$tumor_reads 'BEGIN{printf \"%.6f\", n\u002Ft}')\n    samtools view -s \"1.${frac#*.}\" -b -o tumor_matched.bam tumor.bam\nfi\n```\n\nA subsampled BAM without an integer seed (`-s 0.1`) is non-reproducible -- production pipelines should reject it.\n\n## Expression Filtering\n\n`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:\n```bash\n# Reads with >=2 mismatches (NM tag)\nsamtools view -e '[NM] >= 2' in.bam\n\n# Soft clip on the left, on chr1\nsamtools view -e 'cigar=~\"^[0-9]+S\" && rname==\"chr1\"' in.bam\n\n# Combine with FLAG and MAPQ\nsamtools view -F 2308 -q 30 -e '[NM] \u003C= 5 && [AS] >= 100' in.bam\n\n# Drop reads with low mapped fraction (samtools-internal helpers)\nsamtools view -e 'sclen \u002F qlen \u003C 0.2' in.bam\n```\n\nNote: 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.\n\n## Filter by Read Group\n```bash\nsamtools view -r library_A in.bam              # single read group\nsamtools view -R rg_list.txt in.bam            # multiple via file (one ID per line)\n```\n\n## pysam Python Alternative\n\n### Basic Filtering\n```python\nimport pysam\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('filtered.bam', 'wb', header=infile.header) as outfile:\n        for read in infile:\n            if read.is_unmapped:\n                continue\n            if read.mapping_quality \u003C 30:\n                continue\n            if read.is_duplicate:\n                continue\n            outfile.write(read)\n```\n\n### Filter with Function\n\n**Goal:** Apply a multi-criteria quality filter to produce clean alignments for downstream analysis.\n\n**Approach:** Define a predicate checking mapped status, primary alignment, duplicate flag, and MAPQ; stream reads through it.\n\n**Reference (pysam 0.22+):**\n```python\nimport pysam\n\ndef passes_filter(read):\n    if read.is_unmapped:\n        return False\n    if read.is_secondary or read.is_supplementary:\n        return False\n    if read.is_duplicate:\n        return False\n    if read.mapping_quality \u003C 30:\n        return False\n    return True\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('filtered.bam', 'wb', header=infile.header) as outfile:\n        for read in infile:\n            if passes_filter(read):\n                outfile.write(read)\n```\n\n### Filter by Region\n```python\nimport pysam\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('region.bam', 'wb', header=infile.header) as outfile:\n        for read in infile.fetch('chr1', 1000000, 2000000):\n            outfile.write(read)\n```\n\n### Filter from BED File\n\n**Goal:** Extract only reads overlapping target regions defined in a BED file.\n\n**Approach:** Parse BED into a list of (chrom, start, end) tuples, then fetch reads from each region and write to output.\n\n**Reference (pysam 0.22+):**\n```python\nimport pysam\n\ndef read_bed(bed_path):\n    regions = []\n    with open(bed_path) as f:\n        for line in f:\n            if line.startswith('#'):\n                continue\n            parts = line.strip().split('\\t')\n            regions.append((parts[0], int(parts[1]), int(parts[2])))\n    return regions\n\nregions = read_bed('targets.bed')\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('targets.bam', 'wb', header=infile.header) as outfile:\n        for chrom, start, end in regions:\n            for read in infile.fetch(chrom, start, end):\n                outfile.write(read)\n```\n\n### Subsample (Pair-Consistent)\n\nHash on QNAME so mates stay together (a fresh `random.random()` per read drops mates inconsistently and breaks paired-end tools):\n```python\nimport pysam\nimport zlib\n\nfraction = 0.1\nseed = 42\nthreshold = int(0xffffffff * fraction)\n\ndef template_hash(qname, seed):\n    return zlib.crc32(qname.encode()) ^ seed\n\nwith pysam.AlignmentFile('input.bam', 'rb') as infile:\n    with pysam.AlignmentFile('subset.bam', 'wb', header=infile.header) as outfile:\n        for read in infile:\n            if template_hash(read.query_name, seed) \u003C= threshold:\n                outfile.write(read)\n```\n\n## Quick Reference\n\n| Task | samtools command |\n|------|------------------|\n| Mapped only | `view -F 4` |\n| Unmapped only | `view -f 4` |\n| Properly paired | `view -f 2` |\n| Primary only | `view -F 2304` |\n| No duplicates | `view -F 1024` |\n| High MAPQ | `view -q 30` |\n| Region | `view file.bam chr1:1-1000` |\n| BED regions | `view -L file.bed` |\n| Subsample 10% (reproducible) | `view -s 42.1` |\n| Standard filter | `view -F 3332 -q 30` |\n\n## Common Filter Combinations\n\n| Purpose | Flags |\n|---------|-------|\n| Clean reads | `-F 3332 -q 30` (mapped, primary, no dups, high qual) |\n| Variant calling | `-f 2 -F 3328 -q 20` (proper pair, primary, no dups) |\n| Coverage analysis | `-F 1284 -q 1` (mapped, no secondary, no dups; supplementary retained) |\n| Count unique | `-F 2304` (primary only) |\n\nFlag breakdowns:\n- 2304 = 256 + 2048 (secondary + supplementary)\n- 3328 = 256 + 1024 + 2048 (secondary + duplicate + supplementary)\n- 3332 = 4 + 256 + 1024 + 2048 (unmapped + secondary + duplicate + supplementary)\n- 1284 = 4 + 256 + 1024 (unmapped + secondary + duplicate)\n\n## Related Skills\n\n- sam-bam-basics - FLAG semantics, MAPQ-by-aligner, secondary vs supplementary\n- alignment-sorting - Sort before\u002Fafter filtering\n- alignment-indexing - Required for region filtering\n- alignment-amplicon-clipping - Primer clipping for amplicon panels\n- duplicate-handling - Mark duplicates before filtering\n- bam-statistics - Check filter effects\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","cli","2026-09-20","alignment-files\u002Falignment-filtering\u002FSKILL.md","samtools","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-alignment-filtering","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-filtering",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-filtering",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-filtering","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-filtering\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Ffilter_bam.py","SCRIPT","脚本",2414,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-filtering\u002Fexamples\u002Ffilter_bam.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",7471,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-filtering\u002Fusage-guide.md",[63,71,78,85,92,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":70},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":70},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":70},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":70},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":70},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":70},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]