[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EG9ZXRQVB8F50A3J8PY5VS":3,"skill-same:01M7EG9ZXRQVB8F50A3J8PY5VS":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},"01M7EG9ZXRQVB8F50A3J8PY5VS","bio-vcf-manipulation",null,"Combine, split, sort, intersect, and subset VCF\u002FBCF files with bcftools merge, concat, isec, sort, view, and reheader. Use when merging different samples into a cohort VCF, concatenating per-chromosome or per-region call sets for the same samples, intersecting or complementing call sets from different callers, subsetting samples\u002Fregions, harmonizing sample names and","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-vcf-manipulation\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-vcf-manipulation\ndescription: Combine, split, sort, intersect, and subset VCF\u002FBCF files with bcftools merge, concat, isec, sort, view, and reheader. Use when merging different samples into a cohort VCF, concatenating per-chromosome or per-region call sets for the same samples, intersecting or complementing call sets from different callers, subsetting samples\u002Fregions, harmonizing sample names and ##contig headers, or recomputing AC\u002FAN\u002FAF after subsetting. Covers the normalize-before-combine rule, the single-sample-merge 0\u002F0-fabrication trap (merge is not joint genotyping), merge vs concat vs isec selection, and the --naive concat and -R-vs-T region caveats. Not for structural-variant merging by breakpoint fuzz (see variant-calling\u002Fstructural-variant-calling) or joint genotyping of gVCFs (see variant-calling\u002Fjoint-calling).\ntool_type: cli\nprimary_tool: bcftools\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"variant-calling\u002Fvcf-manipulation\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: bcftools 1.19+, cyvcf2 0.30+\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\nThe `+fill-tags` plugin ships with bcftools; `--naive-force` and `-m snp-ins-del` are recent additions -- confirm with `bcftools concat --help` \u002F `bcftools merge --help` on the installed build.\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# VCF Manipulation\n\nCombine, split, sort, intersect, and subset VCF\u002FBCF files with bcftools.\n\n**\"Combine, compare, or restructure my VCFs\"** -> Pick the operation from what changes (samples vs regions vs set membership), and normalize first so the same biological variant is recognized as the same row.\n- CLI: `bcftools merge` (add samples), `bcftools concat` (add regions), `bcftools isec` (set operations), `bcftools view` (subset), `bcftools sort` \u002F `bcftools reheader` (order and header fixes)\n\n## The governing principle: normalize BEFORE combining\n\nEvery combine operation here -- merge, concat `-d` dedup, isec, and downstream annotate -- keys on the `(CHROM, POS, REF, ALT)` tuple, and `bcftools isec` defaults to `-c none` (an ALT must match exactly to count as the same variant). An indel that is not left-aligned + parsimonious, an un-split multiallelic, or an un-decomposed MNP is a **structurally valid** VCF line carrying a *different* tuple for the *same* biological event. The combine then silently mis-joins: isec reports false discordance, merge emits duplicate rows and splits the allele frequency, dedup misses the duplicate. Nothing errors -- the counts are simply wrong.\n\nDecision: **normalize (left-align + parsimony against the SAME reference, split multiallelics) every input before any merge\u002Fconcat-dedup\u002Fisec\u002Fannotate.** This matters most for indels in homopolymers\u002FSTRs, where callers legitimately disagree on POS. It is safe to skip only when a single caller produced all inputs and no cross-file matching or database lookup follows. The canonical incantation is `bcftools norm -m-any -f ref.fa`; see variant-calling\u002Fvariant-normalization for the full pipeline, MNP atomization, and the vt-vs-bcftools discordance -- do NOT re-derive that here, cross-reference it.\n\n## merge vs concat vs isec (choose by what differs)\n\n| Operation | Inputs differ in | Produces | Requires index | Fails \u002F misused when |\n|-----------|------------------|----------|----------------|----------------------|\n| `bcftools merge` | **samples** (same sites) | one multi-sample VCF (columns unioned) | yes | given the SAME sample split by region -> use concat; given single-sample VCFs and treated as joint genotyping -> fabricates 0\u002F0 (see trap below) |\n| `bcftools concat` | **regions** (same samples, e.g. per-chromosome) | one VCF spanning all regions (rows appended) | only with `-a` | inputs from DIFFERENT samples -> use merge; inputs overlap without `-a`; `--naive` used when headers\u002Fsample-order differ |\n| `bcftools isec` | neither -- same cohort, compare membership | per-input private\u002Fshared partition dirs | yes | inputs not normalized to identical representation -> false discordance |\n\nCommon confusion: `concat -a` (`--allow-overlaps`) resolves duplicate records from the SAME sample across overlapping region files; it does NOT union genotypes across different samples -- that is merge. If bcftools reports a \"different samples\" error, the operation is inverted.\n\n## The merge trap: `bcftools merge` is not joint genotyping\n\nWhen merging single-sample VCFs, a site called in sample A but simply **absent** from sample B's file is ambiguous: was B confidently homozygous reference there, or was B never covered\u002Fcalled? A project VCF cannot answer this. `bcftools merge` fills B's genotype with `.\u002F.` (missing) by default, and `-0\u002F--missing-to-ref` overrides it to `0\u002F0` -- but **both are guesses**, because merge has no evidence for the unseen site. `-0` therefore **fabricates** hom-ref genotypes and inflates the reference-allele count (see the vcf-basics `.\u002F.`-is-not-`0\u002F0` distinction). Use `-0` only when every input truly covered every site (e.g. gVCF-derived, or a shared target with confirmed coverage), never as a convenience to remove `.\u002F.`.\n\nDecision: to build a multi-sample callset with correct hom-ref-vs-no-data resolution, **joint-genotype gVCFs** (`GenomicsDBImport`\u002F`CombineGVCFs` -> `GenotypeGVCFs`), do not `bcftools merge` single-sample project VCFs -- see variant-calling\u002Fjoint-calling. Reserve `bcftools merge` for combining already-jointly-genotyped cohorts, or samples that share a target with known coverage.\n\nMerge also requires two harmonizations, or it silently drops or mis-collapses records:\n- **Consistent representation.** All inputs must be normalized and split the same way first. If cohort A is split biallelic and cohort B keeps multiallelics, merge mis-collapses the shared site. Normalize all inputs identically (governing principle above).\n- **Matching `##contig` headers and sample names.** Merge unions sample columns; duplicate sample names abort unless `--force-samples` renames them, and mismatched contig naming (`chr1` vs `1`) prevents sites from aligning. Fix names\u002Fcontigs with `bcftools reheader` first.\n\n## bcftools merge (combine different samples)\n\n```bash\n# Union samples across per-sample (already joint-genotyped or shared-target) VCFs\nbcftools merge -l files.txt -Oz -o cohort.vcf.gz    # -l: one VCF path per line\nbcftools index cohort.vcf.gz\n```\n\n- `-m, --merge` controls multiallelic collapse at shared sites (default `both`): `-m none` keeps a SNP and an indel at one POS as separate records; `-m snps`\u002F`-m indels` restrict which types collapse. Leave the default unless a downstream tool needs types kept apart.\n- `--force-samples` disambiguates colliding sample names; `-r chr:beg-end` restricts to a region (inputs must be indexed).\n\n## bcftools concat (stitch regions for the same samples)\n\n```bash\n# Genome-wide file from per-chromosome calls (same samples, disjoint regions)\nbcftools concat chr{1..22}.vcf.gz chrX.vcf.gz -Oz -o genome.vcf.gz\n```\n\n- `-a, --allow-overlaps` is needed when region files overlap (e.g. windowed calling); pair with `-d\u002F--rm-dups \u003Csnps|indels|both|all|exact>` to output a duplicate once. `-a` requires indexed inputs.\n- `-n, --naive` concatenates BCF\u002FVCF blocks WITHOUT recompression -- very fast for a large per-chromosome set, but it does only a header-compatibility check and requires identical headers and identical sample order across all files; it cannot reorder or reconcile anything. `--naive-force` skips even the header check and will silently produce a corrupt file if headers differ -- avoid it unless the files were provably produced identically.\n- concat does NOT sort across file boundaries; overlapping unsorted inputs need `-a`, and the final file may still need `bcftools sort`.\n\n## bcftools sort (order by CHROM then POS)\n\n```bash\nbcftools sort -T \u002Fscratch\u002Ftmp -m 4G input.vcf.gz -Oz -o sorted.vcf.gz   # -T tempdir, -m spill threshold for large files\n```\n\nAn unsorted VCF breaks everything downstream: `tabix`\u002F`bcftools index` require coordinate-sorted input to build the index, and merge\u002Fisec\u002F`view -r` all depend on that index for random access. Sort after any operation that can leave records out of order (naive concat of misordered files, some reheader edits). `-T`\u002F`-m` bound memory for genome-scale files.\n\n## bcftools isec (set operations on call sets)\n\n```bash\n# Normalize BOTH first (governing principle), then partition\nbcftools norm -m-any -f ref.fa gatk.vcf.gz     -Oz -o gatk.norm.vcf.gz\nbcftools norm -m-any -f ref.fa freebayes.vcf.gz -Oz -o fb.norm.vcf.gz\nbcftools isec -p comparison -Oz gatk.norm.vcf.gz fb.norm.vcf.gz\n```\n\n`-p dir` writes the four-way partition (`-Oz` to compress):\n\n| File | Contents |\n|------|----------|\n| `0000.vcf[.gz]` | private to file 1 |\n| `0001.vcf[.gz]` | private to file 2 |\n| `0002.vcf[.gz]` | shared, file-1 records (file-1 INFO\u002FFORMAT) |\n| `0003.vcf[.gz]` | shared, file-2 records (file-2 INFO\u002FFORMAT) |\n\n`0002` and `0003` are the SAME sites with each file's own annotations -- pick by which annotations are needed downstream. Select membership instead of the full partition with `-n` and route records with `-w` (1-based file indices):\n\n| Flag | Meaning |\n|------|---------|\n| `-n=2 -w1` | present in exactly 2 files, output file-1 records |\n| `-n+2 -w1` | present in >=2 files |\n| `-n~10 -w1` | present in file1 but NOT file2 (boolean mask) |\n| `-C` | complement: positions only in file1, missing in the rest |\n\n`-c, --collapse` sets what counts as \"the same record\"; the default `none` demands an exact REF+ALT match (why normalization is mandatory first), whereas `-c all` matches on position alone and ignores ALT -- rarely what a caller comparison wants.\n\n## Subsetting samples and regions (`bcftools view`)\n\n```bash\nbcftools view -s sample1,sample2 input.vcf.gz -Oz -o subset.vcf.gz   # -s ^s3 to EXCLUDE; -S file for a list\nbcftools view -r chr1:1e6-2e6      input.vcf.gz -Oz -o region.vcf.gz  # -R file.bed for many regions\n```\n\nTwo nuances that bite:\n- **`-r`\u002F`-R` (regions) vs `-t`\u002F`-T` (targets).** `-r`\u002F`-R` use the index to JUMP to regions (fast, require an index) and consider both POS and an indel's end; `-t`\u002F`-T` STREAM the whole file filtering on POS (no index needed, slower). With `-R`, overlapping regions in the BED can emit a record MORE THAN ONCE and out of order -- deduplicate\u002Fsort after, or use non-overlapping regions.\n- **Stale INFO counts after subsetting.** Dropping samples makes INFO `AC\u002FAN\u002FAF` wrong. `bcftools view -s` updates `AC\u002FAN` by default (unless `-I\u002F--no-update`), but recompute the full tag set explicitly: `bcftools +fill-tags subset.vcf.gz -Oz -o out.vcf.gz -- -t AC,AN,AF`.\n\n## Header harmonization (`bcftools reheader`)\n\n```bash\nprintf 'old_name\\tnew_name\\n' > rename.txt\nbcftools reheader -s rename.txt input.vcf.gz -o renamed.vcf.gz   # -s renames samples only, no record rewrite\n```\n\n`reheader` rewrites only the header (fast, no record pass): `-s` maps sample names, `-h` swaps in a whole new header, `-f ref.fa.fai` fixes `##contig` lines to match a reference. Harmonize sample names and contigs BEFORE merge so columns and sites align.\n\n## Structural variants merge differently -- do NOT use `bcftools merge`\n\nFor SVs (`\u003CDEL>`\u002F`\u003CDUP>`\u002F`\u003CINV>`\u002FBND), \"the same event\" is fuzzy: breakpoints disagree by CIPOS\u002FCIEND margins, so tuple-exact bcftools operations treat one deletion called by two tools as two variants. SV merging needs coordinate-and-size (ideally sequence) aware tools -- Truvari, SURVIVOR, or Jasmine -- whose distance\u002Fsize parameters ARE the result. Use bcftools here only for small variants; route SV consensus to variant-calling\u002Fstructural-variant-calling.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Union samples | `bcftools merge -l files.txt -Oz -o cohort.vcf.gz` |\n| Stitch regions | `bcftools concat chr{1..22}.vcf.gz -Oz -o genome.vcf.gz` |\n| Fast stitch (identical headers) | `bcftools concat --naive chr*.bcf -Ob -o all.bcf` |\n| Sort | `bcftools sort -T tmp input.vcf -Oz -o sorted.vcf.gz` |\n| Compare callers | `bcftools isec -p dir a.norm.vcf.gz b.norm.vcf.gz` |\n| Shared only | `bcftools isec -n=2 -w1 a.vcf.gz b.vcf.gz -Oz -o shared.vcf.gz` |\n| Subset samples | `bcftools view -s s1,s2 in.vcf.gz -Oz -o out.vcf.gz` |\n| Recompute AC\u002FAN\u002FAF | `bcftools +fill-tags in.vcf.gz -- -t AC,AN,AF` |\n| Rename samples | `bcftools reheader -s names.txt in.vcf.gz` |\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| `different samples` on concat | merge\u002Fconcat inverted (different samples given to concat) | Use merge for samples, concat for regions |\n| False discordance in isec | inputs not normalized to one representation | `bcftools norm -m-any -f ref.fa` both first (see variant-normalization) |\n| Duplicate rows \u002F split AF after merge | inputs represented inconsistently, or un-normalized indels | Normalize + split all inputs identically before merge |\n| Fabricated `0\u002F0` genotypes, inflated ref-allele count | `-0\u002F--missing-to-ref` on single-sample merge (not joint genotyping) | Drop `-0`; joint-genotype gVCFs instead (joint-calling) |\n| `not sorted` \u002F index build fails | unsorted records | `bcftools sort` then re-index |\n| `--naive` output corrupt | headers or sample order differ across inputs | Reheader to a common header, or drop `--naive` |\n| Records duplicated \u002F out of order after `-R` | overlapping regions in the BED | Use non-overlapping regions, then sort\u002Fdedup |\n| Sample-name conflict aborts merge | duplicate sample names across files | `--force-samples`, or `reheader -s` first |\n| Stale `AF` after subsetting samples | INFO not fully recomputed | `bcftools +fill-tags -- -t AC,AN,AF` |\n\n## Related Skills\n\n- variant-calling\u002Fvariant-normalization - Normalize (left-align, split, atomize) before any merge\u002Fisec -- the load-bearing prerequisite\n- variant-calling\u002Fjoint-calling - Joint-genotype gVCFs instead of merging single-sample VCFs (correct hom-ref vs no-data)\n- variant-calling\u002Fvcf-basics - VCF fields, the `.\u002F.`-is-not-`0\u002F0` distinction, sample\u002Fregion query\n- variant-calling\u002Fstructural-variant-calling - SV merging by breakpoint fuzz (Truvari\u002FSURVIVOR\u002FJasmine), not bcftools\n- variant-calling\u002Ffiltering-best-practices - Filter call sets before combining\n- variant-calling\u002Fvcf-statistics - Sanity-check Ti\u002FTv and counts after manipulation\n- variant-calling\u002Fvariant-calling - Upstream variant discovery that produces input VCFs\n\n## References\n\n- Danecek P, Bonfield JK, Liddle J, et al. Twelve years of SAMtools and BCFtools. *GigaScience.* 2021;10(2):giab008. doi:10.1093\u002Fgigascience\u002Fgiab008 (bcftools merge\u002Fconcat\u002Fisec\u002Fnorm\u002Fview\u002Freheader reference implementation)\n- Tan A, Abecasis GR, Kang HM. Unified representation of genetic variants. *Bioinformatics.* 2015;31(13):2202-2204. doi:10.1093\u002Fbioinformatics\u002Fbtv112 (why normalization before tuple-keyed merge\u002Fisec is mandatory)\n","## Version Compatibility\n\nReference examples tested with: bcftools 1.19+, cyvcf2 0.30+\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\nThe `+fill-tags` plugin ships with bcftools; `--naive-force` and `-m snp-ins-del` are recent additions -- confirm with `bcftools concat --help` \u002F `bcftools merge --help` on the installed build.\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# VCF Manipulation\n\nCombine, split, sort, intersect, and subset VCF\u002FBCF files with bcftools.\n\n**\"Combine, compare, or restructure my VCFs\"** -> Pick the operation from what changes (samples vs regions vs set membership), and normalize first so the same biological variant is recognized as the same row.\n- CLI: `bcftools merge` (add samples), `bcftools concat` (add regions), `bcftools isec` (set operations), `bcftools view` (subset), `bcftools sort` \u002F `bcftools reheader` (order and header fixes)\n\n## The governing principle: normalize BEFORE combining\n\nEvery combine operation here -- merge, concat `-d` dedup, isec, and downstream annotate -- keys on the `(CHROM, POS, REF, ALT)` tuple, and `bcftools isec` defaults to `-c none` (an ALT must match exactly to count as the same variant). An indel that is not left-aligned + parsimonious, an un-split multiallelic, or an un-decomposed MNP is a **structurally valid** VCF line carrying a *different* tuple for the *same* biological event. The combine then silently mis-joins: isec reports false discordance, merge emits duplicate rows and splits the allele frequency, dedup misses the duplicate. Nothing errors -- the counts are simply wrong.\n\nDecision: **normalize (left-align + parsimony against the SAME reference, split multiallelics) every input before any merge\u002Fconcat-dedup\u002Fisec\u002Fannotate.** This matters most for indels in homopolymers\u002FSTRs, where callers legitimately disagree on POS. It is safe to skip only when a single caller produced all inputs and no cross-file matching or database lookup follows. The canonical incantation is `bcftools norm -m-any -f ref.fa`; see variant-calling\u002Fvariant-normalization for the full pipeline, MNP atomization, and the vt-vs-bcftools discordance -- do NOT re-derive that here, cross-reference it.\n\n## merge vs concat vs isec (choose by what differs)\n\n| Operation | Inputs differ in | Produces | Requires index | Fails \u002F misused when |\n|-----------|------------------|----------|----------------|----------------------|\n| `bcftools merge` | **samples** (same sites) | one multi-sample VCF (columns unioned) | yes | given the SAME sample split by region -> use concat; given single-sample VCFs and treated as joint genotyping -> fabricates 0\u002F0 (see trap below) |\n| `bcftools concat` | **regions** (same samples, e.g. per-chromosome) | one VCF spanning all regions (rows appended) | only with `-a` | inputs from DIFFERENT samples -> use merge; inputs overlap without `-a`; `--naive` used when headers\u002Fsample-order differ |\n| `bcftools isec` | neither -- same cohort, compare membership | per-input private\u002Fshared partition dirs | yes | inputs not normalized to identical representation -> false discordance |\n\nCommon confusion: `concat -a` (`--allow-overlaps`) resolves duplicate records from the SAME sample across overlapping region files; it does NOT union genotypes across different samples -- that is merge. If bcftools reports a \"different samples\" error, the operation is inverted.\n\n## The merge trap: `bcftools merge` is not joint genotyping\n\nWhen merging single-sample VCFs, a site called in sample A but simply **absent** from sample B's file is ambiguous: was B confidently homozygous reference there, or was B never covered\u002Fcalled? A project VCF cannot answer this. `bcftools merge` fills B's genotype with `.\u002F.` (missing) by default, and `-0\u002F--missing-to-ref` overrides it to `0\u002F0` -- but **both are guesses**, because merge has no evidence for the unseen site. `-0` therefore **fabricates** hom-ref genotypes and inflates the reference-allele count (see the vcf-basics `.\u002F.`-is-not-`0\u002F0` distinction). Use `-0` only when every input truly covered every site (e.g. gVCF-derived, or a shared target with confirmed coverage), never as a convenience to remove `.\u002F.`.\n\nDecision: to build a multi-sample callset with correct hom-ref-vs-no-data resolution, **joint-genotype gVCFs** (`GenomicsDBImport`\u002F`CombineGVCFs` -> `GenotypeGVCFs`), do not `bcftools merge` single-sample project VCFs -- see variant-calling\u002Fjoint-calling. Reserve `bcftools merge` for combining already-jointly-genotyped cohorts, or samples that share a target with known coverage.\n\nMerge also requires two harmonizations, or it silently drops or mis-collapses records:\n- **Consistent representation.** All inputs must be normalized and split the same way first. If cohort A is split biallelic and cohort B keeps multiallelics, merge mis-collapses the shared site. Normalize all inputs identically (governing principle above).\n- **Matching `##contig` headers and sample names.** Merge unions sample columns; duplicate sample names abort unless `--force-samples` renames them, and mismatched contig naming (`chr1` vs `1`) prevents sites from aligning. Fix names\u002Fcontigs with `bcftools reheader` first.\n\n## bcftools merge (combine different samples)\n\n```bash\n# Union samples across per-sample (already joint-genotyped or shared-target) VCFs\nbcftools merge -l files.txt -Oz -o cohort.vcf.gz    # -l: one VCF path per line\nbcftools index cohort.vcf.gz\n```\n\n- `-m, --merge` controls multiallelic collapse at shared sites (default `both`): `-m none` keeps a SNP and an indel at one POS as separate records; `-m snps`\u002F`-m indels` restrict which types collapse. Leave the default unless a downstream tool needs types kept apart.\n- `--force-samples` disambiguates colliding sample names; `-r chr:beg-end` restricts to a region (inputs must be indexed).\n\n## bcftools concat (stitch regions for the same samples)\n\n```bash\n# Genome-wide file from per-chromosome calls (same samples, disjoint regions)\nbcftools concat chr{1..22}.vcf.gz chrX.vcf.gz -Oz -o genome.vcf.gz\n```\n\n- `-a, --allow-overlaps` is needed when region files overlap (e.g. windowed calling); pair with `-d\u002F--rm-dups \u003Csnps|indels|both|all|exact>` to output a duplicate once. `-a` requires indexed inputs.\n- `-n, --naive` concatenates BCF\u002FVCF blocks WITHOUT recompression -- very fast for a large per-chromosome set, but it does only a header-compatibility check and requires identical headers and identical sample order across all files; it cannot reorder or reconcile anything. `--naive-force` skips even the header check and will silently produce a corrupt file if headers differ -- avoid it unless the files were provably produced identically.\n- concat does NOT sort across file boundaries; overlapping unsorted inputs need `-a`, and the final file may still need `bcftools sort`.\n\n## bcftools sort (order by CHROM then POS)\n\n```bash\nbcftools sort -T \u002Fscratch\u002Ftmp -m 4G input.vcf.gz -Oz -o sorted.vcf.gz   # -T tempdir, -m spill threshold for large files\n```\n\nAn unsorted VCF breaks everything downstream: `tabix`\u002F`bcftools index` require coordinate-sorted input to build the index, and merge\u002Fisec\u002F`view -r` all depend on that index for random access. Sort after any operation that can leave records out of order (naive concat of misordered files, some reheader edits). `-T`\u002F`-m` bound memory for genome-scale files.\n\n## bcftools isec (set operations on call sets)\n\n```bash\n# Normalize BOTH first (governing principle), then partition\nbcftools norm -m-any -f ref.fa gatk.vcf.gz     -Oz -o gatk.norm.vcf.gz\nbcftools norm -m-any -f ref.fa freebayes.vcf.gz -Oz -o fb.norm.vcf.gz\nbcftools isec -p comparison -Oz gatk.norm.vcf.gz fb.norm.vcf.gz\n```\n\n`-p dir` writes the four-way partition (`-Oz` to compress):\n\n| File | Contents |\n|------|----------|\n| `0000.vcf[.gz]` | private to file 1 |\n| `0001.vcf[.gz]` | private to file 2 |\n| `0002.vcf[.gz]` | shared, file-1 records (file-1 INFO\u002FFORMAT) |\n| `0003.vcf[.gz]` | shared, file-2 records (file-2 INFO\u002FFORMAT) |\n\n`0002` and `0003` are the SAME sites with each file's own annotations -- pick by which annotations are needed downstream. Select membership instead of the full partition with `-n` and route records with `-w` (1-based file indices):\n\n| Flag | Meaning |\n|------|---------|\n| `-n=2 -w1` | present in exactly 2 files, output file-1 records |\n| `-n+2 -w1` | present in >=2 files |\n| `-n~10 -w1` | present in file1 but NOT file2 (boolean mask) |\n| `-C` | complement: positions only in file1, missing in the rest |\n\n`-c, --collapse` sets what counts as \"the same record\"; the default `none` demands an exact REF+ALT match (why normalization is mandatory first), whereas `-c all` matches on position alone and ignores ALT -- rarely what a caller comparison wants.\n\n## Subsetting samples and regions (`bcftools view`)\n\n```bash\nbcftools view -s sample1,sample2 input.vcf.gz -Oz -o subset.vcf.gz   # -s ^s3 to EXCLUDE; -S file for a list\nbcftools view -r chr1:1e6-2e6      input.vcf.gz -Oz -o region.vcf.gz  # -R file.bed for many regions\n```\n\nTwo nuances that bite:\n- **`-r`\u002F`-R` (regions) vs `-t`\u002F`-T` (targets).** `-r`\u002F`-R` use the index to JUMP to regions (fast, require an index) and consider both POS and an indel's end; `-t`\u002F`-T` STREAM the whole file filtering on POS (no index needed, slower). With `-R`, overlapping regions in the BED can emit a record MORE THAN ONCE and out of order -- deduplicate\u002Fsort after, or use non-overlapping regions.\n- **Stale INFO counts after subsetting.** Dropping samples makes INFO `AC\u002FAN\u002FAF` wrong. `bcftools view -s` updates `AC\u002FAN` by default (unless `-I\u002F--no-update`), but recompute the full tag set explicitly: `bcftools +fill-tags subset.vcf.gz -Oz -o out.vcf.gz -- -t AC,AN,AF`.\n\n## Header harmonization (`bcftools reheader`)\n\n```bash\nprintf 'old_name\\tnew_name\\n' > rename.txt\nbcftools reheader -s rename.txt input.vcf.gz -o renamed.vcf.gz   # -s renames samples only, no record rewrite\n```\n\n`reheader` rewrites only the header (fast, no record pass): `-s` maps sample names, `-h` swaps in a whole new header, `-f ref.fa.fai` fixes `##contig` lines to match a reference. Harmonize sample names and contigs BEFORE merge so columns and sites align.\n\n## Structural variants merge differently -- do NOT use `bcftools merge`\n\nFor SVs (`\u003CDEL>`\u002F`\u003CDUP>`\u002F`\u003CINV>`\u002FBND), \"the same event\" is fuzzy: breakpoints disagree by CIPOS\u002FCIEND margins, so tuple-exact bcftools operations treat one deletion called by two tools as two variants. SV merging needs coordinate-and-size (ideally sequence) aware tools -- Truvari, SURVIVOR, or Jasmine -- whose distance\u002Fsize parameters ARE the result. Use bcftools here only for small variants; route SV consensus to variant-calling\u002Fstructural-variant-calling.\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Union samples | `bcftools merge -l files.txt -Oz -o cohort.vcf.gz` |\n| Stitch regions | `bcftools concat chr{1..22}.vcf.gz -Oz -o genome.vcf.gz` |\n| Fast stitch (identical headers) | `bcftools concat --naive chr*.bcf -Ob -o all.bcf` |\n| Sort | `bcftools sort -T tmp input.vcf -Oz -o sorted.vcf.gz` |\n| Compare callers | `bcftools isec -p dir a.norm.vcf.gz b.norm.vcf.gz` |\n| Shared only | `bcftools isec -n=2 -w1 a.vcf.gz b.vcf.gz -Oz -o shared.vcf.gz` |\n| Subset samples | `bcftools view -s s1,s2 in.vcf.gz -Oz -o out.vcf.gz` |\n| Recompute AC\u002FAN\u002FAF | `bcftools +fill-tags in.vcf.gz -- -t AC,AN,AF` |\n| Rename samples | `bcftools reheader -s names.txt in.vcf.gz` |\n\n## Common Errors\n\n| Symptom | Cause | Fix |\n|---------|-------|-----|\n| `different samples` on concat | merge\u002Fconcat inverted (different samples given to concat) | Use merge for samples, concat for regions |\n| False discordance in isec | inputs not normalized to one representation | `bcftools norm -m-any -f ref.fa` both first (see variant-normalization) |\n| Duplicate rows \u002F split AF after merge | inputs represented inconsistently, or un-normalized indels | Normalize + split all inputs identically before merge |\n| Fabricated `0\u002F0` genotypes, inflated ref-allele count | `-0\u002F--missing-to-ref` on single-sample merge (not joint genotyping) | Drop `-0`; joint-genotype gVCFs instead (joint-calling) |\n| `not sorted` \u002F index build fails | unsorted records | `bcftools sort` then re-index |\n| `--naive` output corrupt | headers or sample order differ across inputs | Reheader to a common header, or drop `--naive` |\n| Records duplicated \u002F out of order after `-R` | overlapping regions in the BED | Use non-overlapping regions, then sort\u002Fdedup |\n| Sample-name conflict aborts merge | duplicate sample names across files | `--force-samples`, or `reheader -s` first |\n| Stale `AF` after subsetting samples | INFO not fully recomputed | `bcftools +fill-tags -- -t AC,AN,AF` |\n\n## Related Skills\n\n- variant-calling\u002Fvariant-normalization - Normalize (left-align, split, atomize) before any merge\u002Fisec -- the load-bearing prerequisite\n- variant-calling\u002Fjoint-calling - Joint-genotype gVCFs instead of merging single-sample VCFs (correct hom-ref vs no-data)\n- variant-calling\u002Fvcf-basics - VCF fields, the `.\u002F.`-is-not-`0\u002F0` distinction, sample\u002Fregion query\n- variant-calling\u002Fstructural-variant-calling - SV merging by breakpoint fuzz (Truvari\u002FSURVIVOR\u002FJasmine), not bcftools\n- variant-calling\u002Ffiltering-best-practices - Filter call sets before combining\n- variant-calling\u002Fvcf-statistics - Sanity-check Ti\u002FTv and counts after manipulation\n- variant-calling\u002Fvariant-calling - Upstream variant discovery that produces input VCFs\n\n## References\n\n- Danecek P, Bonfield JK, Liddle J, et al. Twelve years of SAMtools and BCFtools. *GigaScience.* 2021;10(2):giab008. doi:10.1093\u002Fgigascience\u002Fgiab008 (bcftools merge\u002Fconcat\u002Fisec\u002Fnorm\u002Fview\u002Freheader reference implementation)\n- Tan A, Abecasis GR, Kang HM. Unified representation of genetic variants. *Bioinformatics.* 2015;31(13):2202-2204. doi:10.1093\u002Fbioinformatics\u002Fbtv112 (why normalization before tuple-keyed merge\u002Fisec is mandatory)\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","variant-calling\u002Fvcf-manipulation\u002FSKILL.md","bcftools","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-vcf-manipulation","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-vcf-manipulation",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-vcf-manipulation",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-vcf-manipulation","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-vcf-manipulation\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fcompare_vcfs.sh","SCRIPT","脚本",1858,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-vcf-manipulation\u002Fexamples\u002Fcompare_vcfs.sh",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",14785,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-vcf-manipulation\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",[],[]]