[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EBG4NGVXJ0FPN1KVWYT60W":3,"skill-same:01M7EBG4NGVXJ0FPN1KVWYT60W":66},{"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},"01M7EBG4NGVXJ0FPN1KVWYT60W","bio-alignment-validation",null,"Validate alignment quality with insert size distribution, proper pairing rates, GC bias, strand balance, and other post-alignment metrics. Use when verifying alignment data quality before variant calling or quantification.","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-validation\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-alignment-validation\ndescription: Validate alignment quality with insert size distribution, proper pairing rates, GC bias, strand balance, and other post-alignment metrics. Use when verifying alignment data quality before variant calling or quantification.\ntool_type: mixed\nprimary_tool: samtools\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"alignment-files\u002Falignment-validation\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: matplotlib 3.8+, numpy 1.26+, picard 3.1+, 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 Validation\n\nPost-alignment quality control to verify alignment quality and identify issues.\n\n**\"Check alignment quality\"** -> Compute post-alignment QC metrics (mapping rate, pairing, insert size, strand balance) to identify issues before downstream analysis.\n- CLI: `samtools flagstat`, `samtools stats`, Picard `CollectAlignmentSummaryMetrics`\n- Python: `pysam.AlignmentFile` iteration with metric calculations\n\n## Two Different Validations\n\n| Concern | Tools | What it catches |\n|---------|-------|-----------------|\n| **File integrity** | `samtools quickcheck`, `picard ValidateSamFile` | Truncation, missing EOF, malformed records, wrong CIGAR, MAPQ out of range |\n| **Sequence dictionary identity** | `samtools dict` + M5 diff | BAM aligned to wrong reference flavor \u002F different decoy \u002F chr vs no-chr |\n| **QC metrics** | `samtools stats`, `flagstat`, `mosdepth`, Picard `CollectMultipleMetrics` \u002F `CollectHsMetrics` \u002F `CollectWgsMetrics` | Are the data biologically reasonable for the assay? |\n| **Contamination \u002F sample swap** | `verifybamid2`, `somalier`, Picard `CrosscheckFingerprints` | Cross-sample contamination, tumor-normal swap, mislabeled sample |\n\nA file can pass `quickcheck` and still be malformed in ways that crash GATK three hours into HaplotypeCaller. Conversely, a QC-poor BAM can be structurally valid.\n\n### File Integrity\n```bash\n# Fast: header + EOF block check (misses mid-file truncation, invalid CIGAR)\nsamtools quickcheck -v in.bam || echo \"QUICKCHECK FAILED\"\nsamtools quickcheck -v *.bam > bad_bams.fofn   # one fail-line per bad file\n\n# Slow but thorough: structural validation\npicard ValidateSamFile I=in.bam MODE=SUMMARY R=ref.fa\n\n# Production: ignore expected-but-noisy\npicard ValidateSamFile I=in.bam MODE=SUMMARY R=ref.fa \\\n    IGNORE=INVALID_MAPPING_QUALITY \\\n    IGNORE=MISMATCH_FLAG_MATE_NEG_STRAND\n```\n\nCI-safe one-liner:\n```bash\ntest -s in.bam \\\n  && samtools quickcheck -v in.bam \\\n  && [ $(samtools view -c -F 2304 in.bam) -gt 1000 ] \\\n  || { echo \"BAM failed integrity\"; exit 1; }\n```\n\n### Sequence Dictionary Cross-Validation (M5)\n```bash\n# Compare per-contig MD5 between BAM and reference\ndiff \\\n    \u003C(samtools view -H in.bam | grep '^@SQ' | tr '\\t' '\\n' | grep '^M5:' | sort) \\\n    \u003C(samtools dict ref.fa | grep '^@SQ' | tr '\\t' '\\n' | grep '^M5:' | sort)\n```\n\nIf M5s differ, the BAM was aligned to a different sequence than the current reference (even if contig names match). Concrete failure modes: GRCh38 vs GRCh38.p13 vs GRCh38_no_alt (alt contigs differ); UCSC `chr1` vs Ensembl `1` (names differ, M5s match -- pure renaming); soft-masked vs unmasked (M5 matches -- case is normalized to uppercase before hashing, so lowercase soft-masking is invisible to M5). Note hard-masking is different: it replaces bases with `N`, changing the sequence, so its M5 does NOT match the unmasked reference. The M5 tag is the only definitive identity check.\n\n### Contamination and Sample Swap\n\nNo alignment QC is complete without these in production:\n```bash\n# Cross-sample contamination\nverifybamid2 --SVDPrefix \u002Fresources\u002F1000g.b38.vcf.gz.SVD \\\n    --Reference ref.fa --BamFile sample.bam --Output sample.contam\n# FREEMIX > 0.03 is the commonly used contamination-concern threshold; values escalate from there.\n\n# Relatedness, sex check, sample swap detection\nsomalier extract -d extracted\u002F -s \u002Fresources\u002Fsites.GRCh38.vcf.gz \\\n    -f ref.fa sample.bam\nsomalier relate --infer extracted\u002F*.somalier\n\n# Tumor\u002Fnormal pairing verification\npicard CrosscheckFingerprints I=tumor.bam I=normal.bam \\\n    HAPLOTYPE_MAP=Homo_sapiens_assembly38.haplotype_database.txt\n# LOD > 5 = same individual; \u003C -5 = different\n```\n\nSample-swap rates of 0.5-1% in production cohorts are typical. Without `somalier` or `CrosscheckFingerprints`, swaps are detected only when a downstream finding contradicts clinical expectation.\n\n## Insert Size Distribution\n\n**Goal:** Verify that the fragment length distribution matches the library preparation protocol.\n\n**Approach:** Extract template_length from properly paired reads and compare the distribution to expected values for the library type.\n\n### samtools stats\n\n```bash\nsamtools stats input.bam > stats.txt\ngrep \"^IS\" stats.txt | cut -f2,3 > insert_sizes.txt\n```\n\n### Picard CollectInsertSizeMetrics\n\n```bash\njava -jar picard.jar CollectInsertSizeMetrics \\\n    I=input.bam \\\n    O=insert_metrics.txt \\\n    H=insert_histogram.pdf\n```\n\n### Expected Insert Sizes by Library\n\n| Library | Mean insert | Distribution shape | Diagnostic |\n|---------|-------------|-------------------|-----------|\n| TruSeq DNA PCR-free WGS | 400-500 bp | Roughly Gaussian, tight\u002Fsharp | Sharpest, most symmetric peak (no PCR bias); bimodality = degraded sample |\n| TruSeq DNA Nano (PCR) WGS | 300-400 bp | Gaussian, broadened by PCR amplification bias | |\n| Twist \u002F IDT exome capture | 250-350 bp | Gaussian | |\n| TruSeq Stranded mRNA | 200-300 bp | Right-skewed (transcript distribution) | Long tail = poor size selection |\n| Ribo-Zero rRNA-depleted | 250-400 bp | Right-skewed | |\n| Smart-seq2 \u002F Smart-seq3 | 200-700 bp | Broad | |\n| 10x Chromium (3') | n\u002Fa -- not informative | n\u002Fa | |\n| TruSeq ChIP | 200-400 bp | Sharp | |\n| ATAC-seq (Buenrostro \u002F Omni-ATAC) | Multimodal | Peaks at ~50, ~180, ~370 bp | **Missing multimodal pattern = bad library**; missing ~180 bp mononucleosome peak = over-transposition (Tn5 over-titrated) or degraded DNA |\n| Hi-C \u002F Micro-C | Multimodal | Peak at ligation-junction size | |\n| cfDNA \u002F ctDNA | 160-180 bp | Multimodal; ~167 bp mononucleosomal + ~340 dinuc | Tumor-derived shorter (~145 bp); shape itself is a biomarker |\n| FFPE | 100-250 bp | Right-skewed, broad | |\n| aDNA | 30-80 bp | Sharp left-skewed | |\n| ONT (native) | 1-30 kb | n\u002Fa | |\n| PacBio HiFi | 10-25 kb | Sharp peak | |\n\nFor ATAC, the multimodal pattern *is* the QC. If the mononucleosomal peak (~180 bp) is absent, Tn5 was over-titrated, under-titrated, or DNA was degraded. Use ATACseqQC `fragSizeDist()` for the standard ATAC fragment-size diagnostic.\n\n### Python Insert Size Analysis\n\n```python\nimport pysam\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_insert_sizes(bam_file, max_reads=100000):\n    sizes = []\n    bam = pysam.AlignmentFile(bam_file, 'rb')\n    for i, read in enumerate(bam.fetch()):\n        if i >= max_reads:\n            break\n        if read.is_proper_pair and not read.is_secondary and read.template_length > 0:\n            sizes.append(read.template_length)\n    bam.close()\n    return sizes\n\nsizes = get_insert_sizes('sample.bam')\nprint(f'Median insert size: {np.median(sizes):.0f}')\nprint(f'Mean insert size: {np.mean(sizes):.0f}')\nprint(f'Std dev: {np.std(sizes):.0f}')\n\nplt.hist(sizes, bins=100, range=(0, 1000))\nplt.xlabel('Insert Size')\nplt.ylabel('Count')\nplt.savefig('insert_size_dist.pdf')\n```\n\n## Proper Pairing Rate\n\nPercentage of reads correctly paired.\n\n### samtools flagstat\n\n```bash\nsamtools flagstat input.bam\n\nsamtools flagstat input.bam | grep \"properly paired\"\n```\n\n### Calculate Pairing Rate\n\n```bash\nproper=$(samtools view -c -f 2 input.bam)\nmapped=$(samtools view -c -F 4 input.bam)\nrate=$(echo \"scale=4; $proper \u002F $mapped * 100\" | bc)\necho \"Proper pairing rate: ${rate}%\"\n```\n\n### Expected Rates\n\n| Metric | Good | Marginal | Poor |\n|--------|------|----------|------|\n| Proper pair | > 90% | 80-90% | \u003C 80% |\n| Mapped | > 95% | 90-95% | \u003C 90% |\n| Singletons | \u003C 5% | 5-10% | > 10% |\n\n## GC Bias\n\nGC content correlation with coverage.\n\n### Picard CollectGcBiasMetrics\n\n```bash\njava -jar picard.jar CollectGcBiasMetrics \\\n    I=input.bam \\\n    O=gc_bias_metrics.txt \\\n    CHART=gc_bias_chart.pdf \\\n    S=gc_summary.txt \\\n    R=reference.fa\n```\n\n### deepTools computeGCBias\n\n```bash\ncomputeGCBias \\\n    -b input.bam \\\n    --effectiveGenomeSize 2913022398 \\\n    -g hg38.2bit \\\n    -o gc_bias.txt \\\n    --biasPlot gc_bias.pdf\n```\n\n### Interpret GC Bias\n\n| Issue | Symptom |\n|-------|---------|\n| Under-representation | Low GC coverage drops |\n| Over-representation | High GC coverage elevated |\n| PCR bias | Strong correlation |\n\n## Strand Balance\n\nA balanced 0.48-0.52 forward\u002Freverse ratio applies to WGS \u002F WES \u002F generic DNA-seq on autosomes. Expected to deviate for: stranded RNA-seq (deliberately strand-asymmetric -- verify with RSeQC `infer_experiment.py`), bisulfite (CT vs GA), small-RNA \u002F strand-specific RNA-seq, and chrY\u002FchrM regions. Per-chromosome strand imbalance >5% on autosomes is a field-convention rule of thumb (no single primary citation) — it picks up aligner artifacts; on chrX\u002FchrY it suggests sex-mismatch.\n\n### Calculate Strand Ratio\n\n```bash\nforward=$(samtools view -c -F 16 input.bam)\nreverse=$(samtools view -c -f 16 input.bam)\necho \"Forward: $forward\"\necho \"Reverse: $reverse\"\nratio=$(echo \"scale=4; $forward \u002F $reverse\" | bc)\necho \"F\u002FR ratio: $ratio\"\n```\n\n### Check Strand Bias per Chromosome\n\n```bash\nfor chr in chr1 chr2 chr3; do\n    fwd=$(samtools view -c -F 16 input.bam $chr)\n    rev=$(samtools view -c -f 16 input.bam $chr)\n    echo \"$chr: F=$fwd R=$rev ratio=$(echo \"scale=2; $fwd\u002F$rev\" | bc)\"\ndone\n```\n\n## Mapping Quality Distribution\n\n### Extract MAPQ Distribution\n\n```bash\nsamtools view input.bam | cut -f5 | sort -n | uniq -c | sort -k2 -n\n```\n\n### Calculate Mean MAPQ\n\n```bash\nsamtools view input.bam | awk '{sum+=$5; count++} END {print \"Mean MAPQ:\", sum\u002Fcount}'\n```\n\n### MAPQ Distribution Is Bimodal and Aligner-Specific\n\nMean MAPQ is misleading; distributions are bimodal (0 and aligner-max). For aligner-specific scales and \"unique mapping\" sentinels, see sam-bam-basics. The fraction of primary mapped reads at MAPQ >= 30 is a more informative summary than the mean.\n\n## Chromosome Coverage Balance\n\n### Calculate Per-Chromosome Coverage\n\n```bash\nsamtools idxstats input.bam | awk '{print $1, $3\u002F$2}' | head -25\n```\n\n### Check for Aneuploidy \u002F Sex Chromosome Imbalance\n\nMedian-normalized per-autosome coverage (1.0 = expected diploid; 0.5 = monosomy\u002Fsex; 1.5 = trisomy):\n```bash\nsamtools idxstats in.bam | awk '$2>0 && $1!~\u002F^chr[XYM]|^GL|^KI|^chrUn|^chrEBV\u002F {\n    cov[$1] = $3 \u002F $2\n}\nEND {\n    n = asort(cov, sorted)\n    med = sorted[int(n\u002F2)+1]\n    for (c in cov) printf \"%s\\t%.3f\\n\", c, cov[c]\u002Fmed\n}'\n```\n\nFor full ancestry \u002F contamination \u002F relatedness checking, use `verifybamid2`, `somalier`, or `peddy` -- they account for population AFs, not just per-contig depth.\n\n## Mismatch Rate\n\n### Picard CollectAlignmentSummaryMetrics\n\n```bash\njava -jar picard.jar CollectAlignmentSummaryMetrics \\\n    I=input.bam \\\n    R=reference.fa \\\n    O=alignment_summary.txt\n```\n\n### Key Metrics\n\n| Metric | Description | Good Value |\n|--------|-------------|------------|\n| PCT_PF_READS_ALIGNED | Mapped % | > 95% |\n| PF_MISMATCH_RATE | Mismatches | \u003C 1% |\n| PF_INDEL_RATE | Indels | \u003C 0.1% |\n| STRAND_BALANCE | Strand ratio | ~0.5 |\n\n## Comprehensive Validation Script\n\n**Goal:** Run all key alignment QC checks in a single pass and generate a summary report.\n\n**Approach:** Combine samtools flagstat, stats, idxstats, and strand counts into one script that outputs pass\u002Fwarn\u002Ffail calls.\n\n```bash\n#!\u002Fbin\u002Fbash\nBAM=$1\nREF=$2\nNAME=$(basename $BAM .bam)\nOUTDIR=${3:-qc}\n\nmkdir -p $OUTDIR\n\necho \"=== Alignment Validation: $NAME ===\" | tee $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Flagstat ---\" | tee -a $OUTDIR\u002Freport.txt\nsamtools flagstat $BAM | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Mapping Rate ---\" | tee -a $OUTDIR\u002Freport.txt\nmapped=$(samtools view -c -F 4 $BAM)\ntotal=$(samtools view -c $BAM)\nrate=$(echo \"scale=2; $mapped \u002F $total * 100\" | bc)\necho \"Mapping rate: ${rate}%\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Proper Pairing ---\" | tee -a $OUTDIR\u002Freport.txt\nproper=$(samtools view -c -f 2 $BAM)\npair_rate=$(echo \"scale=2; $proper \u002F $mapped * 100\" | bc)\necho \"Proper pairing: ${pair_rate}%\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Insert Size ---\" | tee -a $OUTDIR\u002Freport.txt\nsamtools stats $BAM | grep \"insert size average\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Strand Balance ---\" | tee -a $OUTDIR\u002Freport.txt\nfwd=$(samtools view -c -F 16 $BAM)\nrev=$(samtools view -c -f 16 $BAM)\nstrand_ratio=$(echo \"scale=3; $fwd \u002F $rev\" | bc)\necho \"Forward: $fwd, Reverse: $rev, Ratio: $strand_ratio\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Chromosome Coverage ---\" | tee -a $OUTDIR\u002Freport.txt\nsamtools idxstats $BAM | head -25 | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\nReport: $OUTDIR\u002Freport.txt\"\n```\n\n## Python Validation Module\n\nA skeleton; full implementation is in `examples\u002Fvalidate_alignment.py`:\n```python\nimport pysam\n\nclass AlignmentValidator:\n    def __init__(self, bam_file):\n        self.bam = pysam.AlignmentFile(bam_file, 'rb')\n\n    def report(self, sample_size=100000):\n        # Sample reads, compute mapping rate, proper-pair rate, MAPQ dist, strand balance\n        # See examples\u002Fvalidate_alignment.py for full implementation\n        ...\n```\n\nThe first-N-reads sampling pattern is biased toward chr1 (different GC content and complexity than chrM\u002FchrX\u002FchrY\u002Falt contigs). For unbiased per-chromosome statistics, use `samtools view -s 42.01 input.bam` (the `INT.FRAC` form uses `INT` as the seed; specify an explicit nonzero seed so the subsample is documented and consistent across paired runs) instead of head-of-file iteration.\n\n## Quality Thresholds Summary\n\n| Metric | Good | Warning | Fail |\n|--------|------|---------|------|\n| Mapping rate | > 95% | 90-95% | \u003C 90% |\n| Proper pairing | > 90% | 80-90% | \u003C 80% |\n| Duplicate rate (assay-specific) | see bam-statistics decision table | -- | -- |\n| Strand balance | 0.48-0.52 | 0.45-0.55 | Outside |\n| Mean MAPQ | > 40 | 30-40 | \u003C 30 |\n| GC bias | \u003C 1.2x | 1.2-1.5x | > 1.5x (field-convention bands; Picard CollectGcBiasMetrics does not prescribe specific cutoffs) |\n\n## Related Skills\n\n- bam-statistics - Per-assay metric thresholds, depth\u002Fcoverage tools, mosdepth\n- alignment-filtering - Aligner-specific MAPQ thresholds (canonical home)\n- duplicate-handling - Library-aware dedup decisions\n- sam-bam-basics - MAPQ-by-aligner table\n- chip-seq\u002Fchipseq-qc - ChIP-specific QC (FRiP, NSC, RSC)\n","## Version Compatibility\n\nReference examples tested with: matplotlib 3.8+, numpy 1.26+, picard 3.1+, 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 Validation\n\nPost-alignment quality control to verify alignment quality and identify issues.\n\n**\"Check alignment quality\"** -> Compute post-alignment QC metrics (mapping rate, pairing, insert size, strand balance) to identify issues before downstream analysis.\n- CLI: `samtools flagstat`, `samtools stats`, Picard `CollectAlignmentSummaryMetrics`\n- Python: `pysam.AlignmentFile` iteration with metric calculations\n\n## Two Different Validations\n\n| Concern | Tools | What it catches |\n|---------|-------|-----------------|\n| **File integrity** | `samtools quickcheck`, `picard ValidateSamFile` | Truncation, missing EOF, malformed records, wrong CIGAR, MAPQ out of range |\n| **Sequence dictionary identity** | `samtools dict` + M5 diff | BAM aligned to wrong reference flavor \u002F different decoy \u002F chr vs no-chr |\n| **QC metrics** | `samtools stats`, `flagstat`, `mosdepth`, Picard `CollectMultipleMetrics` \u002F `CollectHsMetrics` \u002F `CollectWgsMetrics` | Are the data biologically reasonable for the assay? |\n| **Contamination \u002F sample swap** | `verifybamid2`, `somalier`, Picard `CrosscheckFingerprints` | Cross-sample contamination, tumor-normal swap, mislabeled sample |\n\nA file can pass `quickcheck` and still be malformed in ways that crash GATK three hours into HaplotypeCaller. Conversely, a QC-poor BAM can be structurally valid.\n\n### File Integrity\n```bash\n# Fast: header + EOF block check (misses mid-file truncation, invalid CIGAR)\nsamtools quickcheck -v in.bam || echo \"QUICKCHECK FAILED\"\nsamtools quickcheck -v *.bam > bad_bams.fofn   # one fail-line per bad file\n\n# Slow but thorough: structural validation\npicard ValidateSamFile I=in.bam MODE=SUMMARY R=ref.fa\n\n# Production: ignore expected-but-noisy\npicard ValidateSamFile I=in.bam MODE=SUMMARY R=ref.fa \\\n    IGNORE=INVALID_MAPPING_QUALITY \\\n    IGNORE=MISMATCH_FLAG_MATE_NEG_STRAND\n```\n\nCI-safe one-liner:\n```bash\ntest -s in.bam \\\n  && samtools quickcheck -v in.bam \\\n  && [ $(samtools view -c -F 2304 in.bam) -gt 1000 ] \\\n  || { echo \"BAM failed integrity\"; exit 1; }\n```\n\n### Sequence Dictionary Cross-Validation (M5)\n```bash\n# Compare per-contig MD5 between BAM and reference\ndiff \\\n    \u003C(samtools view -H in.bam | grep '^@SQ' | tr '\\t' '\\n' | grep '^M5:' | sort) \\\n    \u003C(samtools dict ref.fa | grep '^@SQ' | tr '\\t' '\\n' | grep '^M5:' | sort)\n```\n\nIf M5s differ, the BAM was aligned to a different sequence than the current reference (even if contig names match). Concrete failure modes: GRCh38 vs GRCh38.p13 vs GRCh38_no_alt (alt contigs differ); UCSC `chr1` vs Ensembl `1` (names differ, M5s match -- pure renaming); soft-masked vs unmasked (M5 matches -- case is normalized to uppercase before hashing, so lowercase soft-masking is invisible to M5). Note hard-masking is different: it replaces bases with `N`, changing the sequence, so its M5 does NOT match the unmasked reference. The M5 tag is the only definitive identity check.\n\n### Contamination and Sample Swap\n\nNo alignment QC is complete without these in production:\n```bash\n# Cross-sample contamination\nverifybamid2 --SVDPrefix \u002Fresources\u002F1000g.b38.vcf.gz.SVD \\\n    --Reference ref.fa --BamFile sample.bam --Output sample.contam\n# FREEMIX > 0.03 is the commonly used contamination-concern threshold; values escalate from there.\n\n# Relatedness, sex check, sample swap detection\nsomalier extract -d extracted\u002F -s \u002Fresources\u002Fsites.GRCh38.vcf.gz \\\n    -f ref.fa sample.bam\nsomalier relate --infer extracted\u002F*.somalier\n\n# Tumor\u002Fnormal pairing verification\npicard CrosscheckFingerprints I=tumor.bam I=normal.bam \\\n    HAPLOTYPE_MAP=Homo_sapiens_assembly38.haplotype_database.txt\n# LOD > 5 = same individual; \u003C -5 = different\n```\n\nSample-swap rates of 0.5-1% in production cohorts are typical. Without `somalier` or `CrosscheckFingerprints`, swaps are detected only when a downstream finding contradicts clinical expectation.\n\n## Insert Size Distribution\n\n**Goal:** Verify that the fragment length distribution matches the library preparation protocol.\n\n**Approach:** Extract template_length from properly paired reads and compare the distribution to expected values for the library type.\n\n### samtools stats\n\n```bash\nsamtools stats input.bam > stats.txt\ngrep \"^IS\" stats.txt | cut -f2,3 > insert_sizes.txt\n```\n\n### Picard CollectInsertSizeMetrics\n\n```bash\njava -jar picard.jar CollectInsertSizeMetrics \\\n    I=input.bam \\\n    O=insert_metrics.txt \\\n    H=insert_histogram.pdf\n```\n\n### Expected Insert Sizes by Library\n\n| Library | Mean insert | Distribution shape | Diagnostic |\n|---------|-------------|-------------------|-----------|\n| TruSeq DNA PCR-free WGS | 400-500 bp | Roughly Gaussian, tight\u002Fsharp | Sharpest, most symmetric peak (no PCR bias); bimodality = degraded sample |\n| TruSeq DNA Nano (PCR) WGS | 300-400 bp | Gaussian, broadened by PCR amplification bias | |\n| Twist \u002F IDT exome capture | 250-350 bp | Gaussian | |\n| TruSeq Stranded mRNA | 200-300 bp | Right-skewed (transcript distribution) | Long tail = poor size selection |\n| Ribo-Zero rRNA-depleted | 250-400 bp | Right-skewed | |\n| Smart-seq2 \u002F Smart-seq3 | 200-700 bp | Broad | |\n| 10x Chromium (3') | n\u002Fa -- not informative | n\u002Fa | |\n| TruSeq ChIP | 200-400 bp | Sharp | |\n| ATAC-seq (Buenrostro \u002F Omni-ATAC) | Multimodal | Peaks at ~50, ~180, ~370 bp | **Missing multimodal pattern = bad library**; missing ~180 bp mononucleosome peak = over-transposition (Tn5 over-titrated) or degraded DNA |\n| Hi-C \u002F Micro-C | Multimodal | Peak at ligation-junction size | |\n| cfDNA \u002F ctDNA | 160-180 bp | Multimodal; ~167 bp mononucleosomal + ~340 dinuc | Tumor-derived shorter (~145 bp); shape itself is a biomarker |\n| FFPE | 100-250 bp | Right-skewed, broad | |\n| aDNA | 30-80 bp | Sharp left-skewed | |\n| ONT (native) | 1-30 kb | n\u002Fa | |\n| PacBio HiFi | 10-25 kb | Sharp peak | |\n\nFor ATAC, the multimodal pattern *is* the QC. If the mononucleosomal peak (~180 bp) is absent, Tn5 was over-titrated, under-titrated, or DNA was degraded. Use ATACseqQC `fragSizeDist()` for the standard ATAC fragment-size diagnostic.\n\n### Python Insert Size Analysis\n\n```python\nimport pysam\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef get_insert_sizes(bam_file, max_reads=100000):\n    sizes = []\n    bam = pysam.AlignmentFile(bam_file, 'rb')\n    for i, read in enumerate(bam.fetch()):\n        if i >= max_reads:\n            break\n        if read.is_proper_pair and not read.is_secondary and read.template_length > 0:\n            sizes.append(read.template_length)\n    bam.close()\n    return sizes\n\nsizes = get_insert_sizes('sample.bam')\nprint(f'Median insert size: {np.median(sizes):.0f}')\nprint(f'Mean insert size: {np.mean(sizes):.0f}')\nprint(f'Std dev: {np.std(sizes):.0f}')\n\nplt.hist(sizes, bins=100, range=(0, 1000))\nplt.xlabel('Insert Size')\nplt.ylabel('Count')\nplt.savefig('insert_size_dist.pdf')\n```\n\n## Proper Pairing Rate\n\nPercentage of reads correctly paired.\n\n### samtools flagstat\n\n```bash\nsamtools flagstat input.bam\n\nsamtools flagstat input.bam | grep \"properly paired\"\n```\n\n### Calculate Pairing Rate\n\n```bash\nproper=$(samtools view -c -f 2 input.bam)\nmapped=$(samtools view -c -F 4 input.bam)\nrate=$(echo \"scale=4; $proper \u002F $mapped * 100\" | bc)\necho \"Proper pairing rate: ${rate}%\"\n```\n\n### Expected Rates\n\n| Metric | Good | Marginal | Poor |\n|--------|------|----------|------|\n| Proper pair | > 90% | 80-90% | \u003C 80% |\n| Mapped | > 95% | 90-95% | \u003C 90% |\n| Singletons | \u003C 5% | 5-10% | > 10% |\n\n## GC Bias\n\nGC content correlation with coverage.\n\n### Picard CollectGcBiasMetrics\n\n```bash\njava -jar picard.jar CollectGcBiasMetrics \\\n    I=input.bam \\\n    O=gc_bias_metrics.txt \\\n    CHART=gc_bias_chart.pdf \\\n    S=gc_summary.txt \\\n    R=reference.fa\n```\n\n### deepTools computeGCBias\n\n```bash\ncomputeGCBias \\\n    -b input.bam \\\n    --effectiveGenomeSize 2913022398 \\\n    -g hg38.2bit \\\n    -o gc_bias.txt \\\n    --biasPlot gc_bias.pdf\n```\n\n### Interpret GC Bias\n\n| Issue | Symptom |\n|-------|---------|\n| Under-representation | Low GC coverage drops |\n| Over-representation | High GC coverage elevated |\n| PCR bias | Strong correlation |\n\n## Strand Balance\n\nA balanced 0.48-0.52 forward\u002Freverse ratio applies to WGS \u002F WES \u002F generic DNA-seq on autosomes. Expected to deviate for: stranded RNA-seq (deliberately strand-asymmetric -- verify with RSeQC `infer_experiment.py`), bisulfite (CT vs GA), small-RNA \u002F strand-specific RNA-seq, and chrY\u002FchrM regions. Per-chromosome strand imbalance >5% on autosomes is a field-convention rule of thumb (no single primary citation) — it picks up aligner artifacts; on chrX\u002FchrY it suggests sex-mismatch.\n\n### Calculate Strand Ratio\n\n```bash\nforward=$(samtools view -c -F 16 input.bam)\nreverse=$(samtools view -c -f 16 input.bam)\necho \"Forward: $forward\"\necho \"Reverse: $reverse\"\nratio=$(echo \"scale=4; $forward \u002F $reverse\" | bc)\necho \"F\u002FR ratio: $ratio\"\n```\n\n### Check Strand Bias per Chromosome\n\n```bash\nfor chr in chr1 chr2 chr3; do\n    fwd=$(samtools view -c -F 16 input.bam $chr)\n    rev=$(samtools view -c -f 16 input.bam $chr)\n    echo \"$chr: F=$fwd R=$rev ratio=$(echo \"scale=2; $fwd\u002F$rev\" | bc)\"\ndone\n```\n\n## Mapping Quality Distribution\n\n### Extract MAPQ Distribution\n\n```bash\nsamtools view input.bam | cut -f5 | sort -n | uniq -c | sort -k2 -n\n```\n\n### Calculate Mean MAPQ\n\n```bash\nsamtools view input.bam | awk '{sum+=$5; count++} END {print \"Mean MAPQ:\", sum\u002Fcount}'\n```\n\n### MAPQ Distribution Is Bimodal and Aligner-Specific\n\nMean MAPQ is misleading; distributions are bimodal (0 and aligner-max). For aligner-specific scales and \"unique mapping\" sentinels, see sam-bam-basics. The fraction of primary mapped reads at MAPQ >= 30 is a more informative summary than the mean.\n\n## Chromosome Coverage Balance\n\n### Calculate Per-Chromosome Coverage\n\n```bash\nsamtools idxstats input.bam | awk '{print $1, $3\u002F$2}' | head -25\n```\n\n### Check for Aneuploidy \u002F Sex Chromosome Imbalance\n\nMedian-normalized per-autosome coverage (1.0 = expected diploid; 0.5 = monosomy\u002Fsex; 1.5 = trisomy):\n```bash\nsamtools idxstats in.bam | awk '$2>0 && $1!~\u002F^chr[XYM]|^GL|^KI|^chrUn|^chrEBV\u002F {\n    cov[$1] = $3 \u002F $2\n}\nEND {\n    n = asort(cov, sorted)\n    med = sorted[int(n\u002F2)+1]\n    for (c in cov) printf \"%s\\t%.3f\\n\", c, cov[c]\u002Fmed\n}'\n```\n\nFor full ancestry \u002F contamination \u002F relatedness checking, use `verifybamid2`, `somalier`, or `peddy` -- they account for population AFs, not just per-contig depth.\n\n## Mismatch Rate\n\n### Picard CollectAlignmentSummaryMetrics\n\n```bash\njava -jar picard.jar CollectAlignmentSummaryMetrics \\\n    I=input.bam \\\n    R=reference.fa \\\n    O=alignment_summary.txt\n```\n\n### Key Metrics\n\n| Metric | Description | Good Value |\n|--------|-------------|------------|\n| PCT_PF_READS_ALIGNED | Mapped % | > 95% |\n| PF_MISMATCH_RATE | Mismatches | \u003C 1% |\n| PF_INDEL_RATE | Indels | \u003C 0.1% |\n| STRAND_BALANCE | Strand ratio | ~0.5 |\n\n## Comprehensive Validation Script\n\n**Goal:** Run all key alignment QC checks in a single pass and generate a summary report.\n\n**Approach:** Combine samtools flagstat, stats, idxstats, and strand counts into one script that outputs pass\u002Fwarn\u002Ffail calls.\n\n```bash\n#!\u002Fbin\u002Fbash\nBAM=$1\nREF=$2\nNAME=$(basename $BAM .bam)\nOUTDIR=${3:-qc}\n\nmkdir -p $OUTDIR\n\necho \"=== Alignment Validation: $NAME ===\" | tee $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Flagstat ---\" | tee -a $OUTDIR\u002Freport.txt\nsamtools flagstat $BAM | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Mapping Rate ---\" | tee -a $OUTDIR\u002Freport.txt\nmapped=$(samtools view -c -F 4 $BAM)\ntotal=$(samtools view -c $BAM)\nrate=$(echo \"scale=2; $mapped \u002F $total * 100\" | bc)\necho \"Mapping rate: ${rate}%\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Proper Pairing ---\" | tee -a $OUTDIR\u002Freport.txt\nproper=$(samtools view -c -f 2 $BAM)\npair_rate=$(echo \"scale=2; $proper \u002F $mapped * 100\" | bc)\necho \"Proper pairing: ${pair_rate}%\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Insert Size ---\" | tee -a $OUTDIR\u002Freport.txt\nsamtools stats $BAM | grep \"insert size average\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Strand Balance ---\" | tee -a $OUTDIR\u002Freport.txt\nfwd=$(samtools view -c -F 16 $BAM)\nrev=$(samtools view -c -f 16 $BAM)\nstrand_ratio=$(echo \"scale=3; $fwd \u002F $rev\" | bc)\necho \"Forward: $fwd, Reverse: $rev, Ratio: $strand_ratio\" | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\n--- Chromosome Coverage ---\" | tee -a $OUTDIR\u002Freport.txt\nsamtools idxstats $BAM | head -25 | tee -a $OUTDIR\u002Freport.txt\n\necho -e \"\\nReport: $OUTDIR\u002Freport.txt\"\n```\n\n## Python Validation Module\n\nA skeleton; full implementation is in `examples\u002Fvalidate_alignment.py`:\n```python\nimport pysam\n\nclass AlignmentValidator:\n    def __init__(self, bam_file):\n        self.bam = pysam.AlignmentFile(bam_file, 'rb')\n\n    def report(self, sample_size=100000):\n        # Sample reads, compute mapping rate, proper-pair rate, MAPQ dist, strand balance\n        # See examples\u002Fvalidate_alignment.py for full implementation\n        ...\n```\n\nThe first-N-reads sampling pattern is biased toward chr1 (different GC content and complexity than chrM\u002FchrX\u002FchrY\u002Falt contigs). For unbiased per-chromosome statistics, use `samtools view -s 42.01 input.bam` (the `INT.FRAC` form uses `INT` as the seed; specify an explicit nonzero seed so the subsample is documented and consistent across paired runs) instead of head-of-file iteration.\n\n## Quality Thresholds Summary\n\n| Metric | Good | Warning | Fail |\n|--------|------|---------|------|\n| Mapping rate | > 95% | 90-95% | \u003C 90% |\n| Proper pairing | > 90% | 80-90% | \u003C 80% |\n| Duplicate rate (assay-specific) | see bam-statistics decision table | -- | -- |\n| Strand balance | 0.48-0.52 | 0.45-0.55 | Outside |\n| Mean MAPQ | > 40 | 30-40 | \u003C 30 |\n| GC bias | \u003C 1.2x | 1.2-1.5x | > 1.5x (field-convention bands; Picard CollectGcBiasMetrics does not prescribe specific cutoffs) |\n\n## Related Skills\n\n- bam-statistics - Per-assay metric thresholds, depth\u002Fcoverage tools, mosdepth\n- alignment-filtering - Aligner-specific MAPQ thresholds (canonical home)\n- duplicate-handling - Library-aware dedup decisions\n- sam-bam-basics - MAPQ-by-aligner table\n- chip-seq\u002Fchipseq-qc - ChIP-specific QC (FRiP, NSC, RSC)\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","mixed","2026-09-20","alignment-files\u002Falignment-validation\u002FSKILL.md","samtools","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-alignment-validation","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-validation",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-validation",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-alignment-validation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-validation\u002FSKILL.md",true,[50,56,60],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fvalidate_alignment.py","SCRIPT","脚本",3541,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-validation\u002Fexamples\u002Fvalidate_alignment.py",{"path":57,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":58,"sourceHtmlUrl":59},"examples\u002Fvalidate_alignment.sh",1244,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-validation\u002Fexamples\u002Fvalidate_alignment.sh",{"path":61,"resourceType":62,"resourceTypeDesc":63,"sizeBytes":64,"sourceHtmlUrl":65},"usage-guide.md","REFERENCE","参考文档",8378,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-alignment-validation\u002Fusage-guide.md",[67,75,82,89,96,103],{"skillNo":68,"name":69,"nameZh":6,"description":70,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":74},"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":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":74},"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":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":74},"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":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":74},"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":97,"name":98,"nameZh":6,"description":99,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":100,"categories":101,"keywords":102,"publishedAt":74},"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":104,"name":105,"nameZh":6,"description":106,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":107,"categories":108,"keywords":109,"publishedAt":74},"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",[],[]]