[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EF7QMGV7VF24CVBWXMC53C":3,"skill-same:01M7EF7QMGV7VF24CVBWXMC53C":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},"01M7EF7QMGV7VF24CVBWXMC53C","bio-reference-operations",null,"Generate consensus sequences and manage reference files using samtools. Use when creating consensus from alignments, indexing references, or creating sequence dictionaries.","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-reference-operations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-reference-operations\ndescription: Generate consensus sequences and manage reference files using samtools. Use when creating consensus from alignments, indexing references, or creating sequence dictionaries.\ntool_type: cli\nprimary_tool: samtools\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"alignment-files\u002Freference-operations\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: GATK 4.5+, bcftools 1.19+, 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# Reference Operations\n\nGenerate consensus sequences and manage reference files using samtools.\n\n**\"Prepare a reference genome\"** -> Index the FASTA and create a sequence dictionary for downstream tools.\n- CLI: `samtools faidx ref.fa` + `samtools dict ref.fa -o ref.dict`\n- Python: `pysam.FastaFile('ref.fa')` (auto-uses .fai index)\n\n**\"Build a consensus from BAM\"** -> Derive the most-supported base at each position from aligned reads.\n- CLI: `samtools consensus input.bam -o consensus.fa`\n- Python: iterate pileup columns and take majority base (pysam)\n\n## samtools faidx - Index Reference FASTA\n\nCreate index for random access to reference sequences.\n\n### Create Index\n```bash\nsamtools faidx reference.fa\n# Creates reference.fa.fai\n```\n\n### Fetch Region from Reference\n```bash\nsamtools faidx reference.fa chr1:1000-2000\n```\n\n### Fetch Multiple Regions\n```bash\nsamtools faidx reference.fa chr1:1000-2000 chr2:3000-4000\n```\n\n### Fetch Entire Chromosome\n```bash\nsamtools faidx reference.fa chr1\n```\n\n### Output to File\n```bash\nsamtools faidx reference.fa chr1:1000-2000 > region.fa\n```\n\n### Reverse Complement\n```bash\nsamtools faidx -i reference.fa chr1:1000-2000\n```\n\n### FAI File Format\n```\nchr1    248956422    6    60    61\nchr2    242193529    253105708    60    61\n```\nColumns: name, length, offset, line bases, line width\n\n## samtools dict - Create Sequence Dictionary\n\nCreate SAM header dictionary for reference (used by GATK, Picard).\n\n### Create Dictionary\n```bash\nsamtools dict reference.fa -o reference.dict\n```\n\n### With Assembly Info\n```bash\nsamtools dict -a GRCh38 -s \"Homo sapiens\" reference.fa -o reference.dict\n```\n\n### Dictionary Format\n```\n@HD VN:1.0 SO:unsorted\n@SQ SN:chr1 LN:248956422 M5:6aef897c3d6ff0c78aff06ac189178dd UR:file:reference.fa\n@SQ SN:chr2 LN:242193529 M5:f98db672eb0993dcfdabafe2a882905c UR:file:reference.fa\n```\n\nThe `M5:` (MD5) tag is the only definitive reference-identity check -- two references named \"GRCh38\" with different decoy\u002Falt content have different M5s. CRAM enforces M5 match on read-back. See alignment-validation for BAM-vs-reference M5 cross-check.\n\n### GRCh38 Is Not One Reference\n\n| Reference flavor | ALT | Decoy | EBV | HLA | Use case |\n|------------------|-----|-------|-----|-----|----------|\n| GRCh38 no-alt | no | no | no | no | Conservative analyses |\n| GRCh38 + decoy + EBV (1000G analysis set) | no | yes | yes | no | Cohort projects |\n| GRCh38 ALT + decoy + EBV + HLA (Broad \u002F hs38DH) | yes | yes | yes | yes | GATK Best Practices |\n| T2T-CHM13 v2.0 | n\u002Fa | n\u002Fa | n\u002Fa | n\u002Fa | Distinct coordinates -- NOT interchangeable |\n\nMixing no-alt and ALT-aware BAMs in one cohort produces inconsistent multi-mapping behavior at HLA, KIR, and segmental-duplication regions. Standardize before joint calling.\n\n### Contig Naming: The Silent Killer\n\n| Convention | Source | chr1 | mitochondrion |\n|-----------|--------|------|---------------|\n| UCSC (hg19, hg38) | UCSC Genome Browser | chr1 | chrM |\n| Ensembl (GRCh37, GRCh38) | Ensembl, ENA | 1 | MT |\n| NCBI RefSeq (recent) | NCBI | chr1 | chrM |\n| 1000G analysis sets | 1000G GRCh38 analysis set | chr1 | chrM |\n\nA BAM with `@SQ SN:chr1` cannot be analyzed against a `1`-named reference (and vice versa). Detect:\n```bash\nsamtools view -H sample.bam | grep '^@SQ' | head -3\nsamtools dict ref.fa | head -3\n```\n\nConvert: `bcftools annotate --rename-chrs` for VCF; for BAM there is no clean conversion -- re-align.\n\n## samtools consensus - Generate Consensus\n\nCreate consensus sequence from alignments.\n\n### Basic Consensus\n```bash\nsamtools consensus input.bam -o consensus.fa\n```\n\n### From Specific Region\n```bash\nsamtools consensus -r chr1:1000-2000 input.bam -o region_consensus.fa\n```\n\n### Output Formats\n```bash\n# FASTA (default)\nsamtools consensus -f fasta input.bam -o consensus.fa\n\n# FASTQ (includes quality)\nsamtools consensus -f fastq input.bam -o consensus.fq\n```\n\n### Quality Options\n```bash\n# Minimum depth to call base\nsamtools consensus -d 5 input.bam -o consensus.fa\n\n# Call all positions (including low coverage)\nsamtools consensus -a input.bam -o consensus.fa\n```\n\n### IUPAC Ambiguity for Heterozygotes\n```bash\n# Emit IUPAC codes (R, Y, S, W, K, M, B, D, H, V, N) for heterozygous columns\n# --ambig is REQUIRED -- without it, output is restricted to A,C,G,T,N,*\nsamtools consensus --ambig --het-fract 0.2 --call-fract 0.5 input.bam -o consensus.fa\n```\n\n`--het-fract` controls the fraction of the second-most-common base relative to the most common required to call a heterozygote (verify the default for the installed version with `samtools consensus --help`; the manpage documents none). Without `--ambig`, columns where the second base passes `--het-fract` resolve to `N` rather than the IUPAC code. `--show-ins` \u002F `--show-del` control insertion \u002F deletion display, not ambiguity.\n\n### Platform-Aware Consensus\n```bash\n# Default: Bayesian algorithm (no --config needed)\nsamtools consensus -f fasta input.bam -o consensus.fa\n\n# Platform-specific profiles (samtools 1.17+; verify via samtools consensus --help for installed version)\nsamtools consensus --config hifi       input.bam -o consensus.fa   # PacBio HiFi\nsamtools consensus --config r10.4_sup  input.bam -o consensus.fa   # ONT R10.4+ (r10.4_dup for duplex)\nsamtools consensus --config ultima     input.bam -o consensus.fa   # Ultima Genomics\nsamtools consensus --config hiseq      input.bam -o consensus.fa   # Illumina\n\n# Report ref base where consensus unavailable (low coverage; -T added in samtools 1.22)\nsamtools consensus -T ref.fa input.bam -o consensus.fa\n```\n\n### samtools consensus vs bcftools consensus\n\nDifferent operations -- conflating them produces nonsense:\n\n| Tool | Input | Output | Use case |\n|------|-------|--------|----------|\n| `samtools consensus` | BAM | Consensus FASTA derived from reads (Bayesian) | Viral, de novo \u002F amplicon, low-coverage species |\n| `bcftools consensus` | reference + VCF | Reference with VCF variants applied | Apply called variants (haplotype reconstruction, custom ref for re-mapping) |\n\nFor viral consensus from BAM:\n```bash\n# Modern: samtools consensus\nsamtools consensus --config hiseq -d 10 --het-fract 0.5 \\\n    --show-ins yes --show-del yes input.bam -o consensus.fa\n\n# Apply called variants to reference (different question)\nbcftools consensus -f reference.fa variants.vcf.gz -o sample_consensus.fa\nbcftools consensus -f reference.fa -H 1 phased.vcf.gz -o haplotype1.fa   # phased haplotype 1\n```\n\nFor bacterial \u002F phage assembly polishing, prefer Pilon (short-read) or medaka (ONT); `samtools consensus` is not iterative.\n\n## pysam Python Alternative\n\n### Fetch from Indexed FASTA\n```python\nimport pysam\n\nwith pysam.FastaFile('reference.fa') as ref:\n    seq = ref.fetch('chr1', 999, 2000)  # 0-based\n    print(seq)\n```\n\n### Get Reference Lengths\n```python\nwith pysam.FastaFile('reference.fa') as ref:\n    for name in ref.references:\n        length = ref.get_reference_length(name)\n        print(f'{name}: {length:,} bp')\n```\n\n### Fetch All Chromosomes\n```python\nwith pysam.FastaFile('reference.fa') as ref:\n    for chrom in ref.references:\n        seq = ref.fetch(chrom)\n        print(f'>{chrom}')\n        print(seq[:100] + '...')\n```\n\n### Generate Simple Consensus\n```python\nimport pysam\nfrom collections import Counter\n\ndef consensus_at_position(bam, chrom, pos):\n    bases = Counter()\n    for pileup in bam.pileup(chrom, pos, pos + 1, truncate=True):\n        if pileup.pos == pos:\n            for read in pileup.pileups:\n                if not read.is_del and not read.is_refskip:\n                    bases[read.alignment.query_sequence[read.query_position]] += 1\n    if bases:\n        return bases.most_common(1)[0][0]\n    return 'N'\n\nwith pysam.AlignmentFile('input.bam', 'rb') as bam:\n    consensus = consensus_at_position(bam, 'chr1', 1000000)\n    print(f'Consensus at chr1:1000000 = {consensus}')\n```\n\n### Build Consensus Sequence (Pedagogical Only)\n\nThe Python majority-vote consensus below is illustrative, NOT production. `samtools consensus` is Bayesian, quality-aware, and platform-aware; majority vote ignores base qualities and produces wrong calls on low-coverage \u002F low-quality regions. Use for teaching pileup iteration mechanics; use `samtools consensus` for any real consensus.\n\n```python\nimport pysam\nfrom collections import Counter\n\ndef build_consensus(bam_path, chrom, start, end, min_depth=3):\n    consensus = []\n\n    with pysam.AlignmentFile(bam_path, 'rb') as bam:\n        for pileup in bam.pileup(chrom, start, end, truncate=True):\n            bases = Counter()\n            for read in pileup.pileups:\n                if not read.is_del and not read.is_refskip:\n                    base = read.alignment.query_sequence[read.query_position]\n                    bases[base] += 1\n\n            if sum(bases.values()) >= min_depth:\n                consensus.append(bases.most_common(1)[0][0])\n            else:\n                consensus.append('N')\n\n    return ''.join(consensus)\n```\n\n### Create Dictionary Header\n```python\nimport pysam\n\ndef create_dict_header(fasta_path):\n    header = {'HD': {'VN': '1.6', 'SO': 'unsorted'}, 'SQ': []}\n\n    with pysam.FastaFile(fasta_path) as ref:\n        for name in ref.references:\n            length = ref.get_reference_length(name)\n            header['SQ'].append({'SN': name, 'LN': length})\n\n    return header\n\nheader = create_dict_header('reference.fa')\nfor sq in header['SQ'][:5]:\n    print(f'{sq[\"SN\"]}: {sq[\"LN\"]:,} bp')\n```\n\n## Reference Preparation Workflow\n\n**Goal:** Set up a reference genome with all indices needed by common analysis tools.\n\n**Approach:** Create FASTA index (.fai), sequence dictionary (.dict), and aligner-specific indices in sequence.\n\n### Prepare Reference for Analysis\n```bash\n# 1. Index FASTA for samtools\u002Fpysam\nsamtools faidx reference.fa\n\n# 2. Create sequence dictionary for GATK\u002FPicard\nsamtools dict reference.fa -o reference.dict\n\n# 3. Pre-populate CRAM REF_CACHE (for offline HPC nodes)\nseq_cache_populate.pl -root $REF_CACHE_DIR reference.fa\n```\n\nFor aligner-specific indices (BWA, Bowtie2, STAR, minimap2, Salmon), see read-alignment.\n\n### Check Reference Setup\n```bash\n# Verify FAI exists\nls -la reference.fa.fai\n\n# Verify dict exists\nhead reference.dict\n\n# Test fetch\nsamtools faidx reference.fa chr1:1-100\n```\n\n## Common Operations\n\n### Extract Chromosome\n```bash\nsamtools faidx reference.fa chr1 > chr1.fa\nsamtools faidx chr1.fa  # Index the subset\n```\n\n### Get Chromosome Sizes\n```bash\ncut -f1,2 reference.fa.fai > chrom.sizes\n```\n\n### Subset Reference\n```bash\nsamtools faidx reference.fa chr1 chr2 chr3 > subset.fa\nsamtools faidx subset.fa\n```\n\n### Compare Consensus to Reference\n```bash\n# Generate consensus\nsamtools consensus input.bam -o consensus.fa\n\n# Align consensus back to reference\nminimap2 -a reference.fa consensus.fa > comparison.sam\n```\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Index FASTA | `samtools faidx ref.fa` |\n| Fetch region | `samtools faidx ref.fa chr1:1-1000` |\n| Create dict | `samtools dict ref.fa -o ref.dict` |\n| Build consensus | `samtools consensus in.bam -o out.fa` |\n| Chrom sizes | `cut -f1,2 ref.fa.fai` |\n\n## Related Skills\n\n- sam-bam-basics - CRAM reference resolution (REF_PATH, REF_CACHE)\n- alignment-indexing - faidx for reference access\n- alignment-validation - BAM-vs-reference M5 cross-validation\n- pileup-generation - Pileup for consensus building\n- variant-calling\u002Fvcf-basics - VCF I\u002FO for `bcftools consensus`\n- variant-calling\u002Fconsensus-sequences - Consensus from VCF (different operation)\n- read-alignment\u002Fbwa-alignment - BWA index preparation\n- sequence-io\u002Fread-sequences - Parse FASTA with Biopython\n","## Version Compatibility\n\nReference examples tested with: GATK 4.5+, bcftools 1.19+, 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# Reference Operations\n\nGenerate consensus sequences and manage reference files using samtools.\n\n**\"Prepare a reference genome\"** -> Index the FASTA and create a sequence dictionary for downstream tools.\n- CLI: `samtools faidx ref.fa` + `samtools dict ref.fa -o ref.dict`\n- Python: `pysam.FastaFile('ref.fa')` (auto-uses .fai index)\n\n**\"Build a consensus from BAM\"** -> Derive the most-supported base at each position from aligned reads.\n- CLI: `samtools consensus input.bam -o consensus.fa`\n- Python: iterate pileup columns and take majority base (pysam)\n\n## samtools faidx - Index Reference FASTA\n\nCreate index for random access to reference sequences.\n\n### Create Index\n```bash\nsamtools faidx reference.fa\n# Creates reference.fa.fai\n```\n\n### Fetch Region from Reference\n```bash\nsamtools faidx reference.fa chr1:1000-2000\n```\n\n### Fetch Multiple Regions\n```bash\nsamtools faidx reference.fa chr1:1000-2000 chr2:3000-4000\n```\n\n### Fetch Entire Chromosome\n```bash\nsamtools faidx reference.fa chr1\n```\n\n### Output to File\n```bash\nsamtools faidx reference.fa chr1:1000-2000 > region.fa\n```\n\n### Reverse Complement\n```bash\nsamtools faidx -i reference.fa chr1:1000-2000\n```\n\n### FAI File Format\n```\nchr1    248956422    6    60    61\nchr2    242193529    253105708    60    61\n```\nColumns: name, length, offset, line bases, line width\n\n## samtools dict - Create Sequence Dictionary\n\nCreate SAM header dictionary for reference (used by GATK, Picard).\n\n### Create Dictionary\n```bash\nsamtools dict reference.fa -o reference.dict\n```\n\n### With Assembly Info\n```bash\nsamtools dict -a GRCh38 -s \"Homo sapiens\" reference.fa -o reference.dict\n```\n\n### Dictionary Format\n```\n@HD VN:1.0 SO:unsorted\n@SQ SN:chr1 LN:248956422 M5:6aef897c3d6ff0c78aff06ac189178dd UR:file:reference.fa\n@SQ SN:chr2 LN:242193529 M5:f98db672eb0993dcfdabafe2a882905c UR:file:reference.fa\n```\n\nThe `M5:` (MD5) tag is the only definitive reference-identity check -- two references named \"GRCh38\" with different decoy\u002Falt content have different M5s. CRAM enforces M5 match on read-back. See alignment-validation for BAM-vs-reference M5 cross-check.\n\n### GRCh38 Is Not One Reference\n\n| Reference flavor | ALT | Decoy | EBV | HLA | Use case |\n|------------------|-----|-------|-----|-----|----------|\n| GRCh38 no-alt | no | no | no | no | Conservative analyses |\n| GRCh38 + decoy + EBV (1000G analysis set) | no | yes | yes | no | Cohort projects |\n| GRCh38 ALT + decoy + EBV + HLA (Broad \u002F hs38DH) | yes | yes | yes | yes | GATK Best Practices |\n| T2T-CHM13 v2.0 | n\u002Fa | n\u002Fa | n\u002Fa | n\u002Fa | Distinct coordinates -- NOT interchangeable |\n\nMixing no-alt and ALT-aware BAMs in one cohort produces inconsistent multi-mapping behavior at HLA, KIR, and segmental-duplication regions. Standardize before joint calling.\n\n### Contig Naming: The Silent Killer\n\n| Convention | Source | chr1 | mitochondrion |\n|-----------|--------|------|---------------|\n| UCSC (hg19, hg38) | UCSC Genome Browser | chr1 | chrM |\n| Ensembl (GRCh37, GRCh38) | Ensembl, ENA | 1 | MT |\n| NCBI RefSeq (recent) | NCBI | chr1 | chrM |\n| 1000G analysis sets | 1000G GRCh38 analysis set | chr1 | chrM |\n\nA BAM with `@SQ SN:chr1` cannot be analyzed against a `1`-named reference (and vice versa). Detect:\n```bash\nsamtools view -H sample.bam | grep '^@SQ' | head -3\nsamtools dict ref.fa | head -3\n```\n\nConvert: `bcftools annotate --rename-chrs` for VCF; for BAM there is no clean conversion -- re-align.\n\n## samtools consensus - Generate Consensus\n\nCreate consensus sequence from alignments.\n\n### Basic Consensus\n```bash\nsamtools consensus input.bam -o consensus.fa\n```\n\n### From Specific Region\n```bash\nsamtools consensus -r chr1:1000-2000 input.bam -o region_consensus.fa\n```\n\n### Output Formats\n```bash\n# FASTA (default)\nsamtools consensus -f fasta input.bam -o consensus.fa\n\n# FASTQ (includes quality)\nsamtools consensus -f fastq input.bam -o consensus.fq\n```\n\n### Quality Options\n```bash\n# Minimum depth to call base\nsamtools consensus -d 5 input.bam -o consensus.fa\n\n# Call all positions (including low coverage)\nsamtools consensus -a input.bam -o consensus.fa\n```\n\n### IUPAC Ambiguity for Heterozygotes\n```bash\n# Emit IUPAC codes (R, Y, S, W, K, M, B, D, H, V, N) for heterozygous columns\n# --ambig is REQUIRED -- without it, output is restricted to A,C,G,T,N,*\nsamtools consensus --ambig --het-fract 0.2 --call-fract 0.5 input.bam -o consensus.fa\n```\n\n`--het-fract` controls the fraction of the second-most-common base relative to the most common required to call a heterozygote (verify the default for the installed version with `samtools consensus --help`; the manpage documents none). Without `--ambig`, columns where the second base passes `--het-fract` resolve to `N` rather than the IUPAC code. `--show-ins` \u002F `--show-del` control insertion \u002F deletion display, not ambiguity.\n\n### Platform-Aware Consensus\n```bash\n# Default: Bayesian algorithm (no --config needed)\nsamtools consensus -f fasta input.bam -o consensus.fa\n\n# Platform-specific profiles (samtools 1.17+; verify via samtools consensus --help for installed version)\nsamtools consensus --config hifi       input.bam -o consensus.fa   # PacBio HiFi\nsamtools consensus --config r10.4_sup  input.bam -o consensus.fa   # ONT R10.4+ (r10.4_dup for duplex)\nsamtools consensus --config ultima     input.bam -o consensus.fa   # Ultima Genomics\nsamtools consensus --config hiseq      input.bam -o consensus.fa   # Illumina\n\n# Report ref base where consensus unavailable (low coverage; -T added in samtools 1.22)\nsamtools consensus -T ref.fa input.bam -o consensus.fa\n```\n\n### samtools consensus vs bcftools consensus\n\nDifferent operations -- conflating them produces nonsense:\n\n| Tool | Input | Output | Use case |\n|------|-------|--------|----------|\n| `samtools consensus` | BAM | Consensus FASTA derived from reads (Bayesian) | Viral, de novo \u002F amplicon, low-coverage species |\n| `bcftools consensus` | reference + VCF | Reference with VCF variants applied | Apply called variants (haplotype reconstruction, custom ref for re-mapping) |\n\nFor viral consensus from BAM:\n```bash\n# Modern: samtools consensus\nsamtools consensus --config hiseq -d 10 --het-fract 0.5 \\\n    --show-ins yes --show-del yes input.bam -o consensus.fa\n\n# Apply called variants to reference (different question)\nbcftools consensus -f reference.fa variants.vcf.gz -o sample_consensus.fa\nbcftools consensus -f reference.fa -H 1 phased.vcf.gz -o haplotype1.fa   # phased haplotype 1\n```\n\nFor bacterial \u002F phage assembly polishing, prefer Pilon (short-read) or medaka (ONT); `samtools consensus` is not iterative.\n\n## pysam Python Alternative\n\n### Fetch from Indexed FASTA\n```python\nimport pysam\n\nwith pysam.FastaFile('reference.fa') as ref:\n    seq = ref.fetch('chr1', 999, 2000)  # 0-based\n    print(seq)\n```\n\n### Get Reference Lengths\n```python\nwith pysam.FastaFile('reference.fa') as ref:\n    for name in ref.references:\n        length = ref.get_reference_length(name)\n        print(f'{name}: {length:,} bp')\n```\n\n### Fetch All Chromosomes\n```python\nwith pysam.FastaFile('reference.fa') as ref:\n    for chrom in ref.references:\n        seq = ref.fetch(chrom)\n        print(f'>{chrom}')\n        print(seq[:100] + '...')\n```\n\n### Generate Simple Consensus\n```python\nimport pysam\nfrom collections import Counter\n\ndef consensus_at_position(bam, chrom, pos):\n    bases = Counter()\n    for pileup in bam.pileup(chrom, pos, pos + 1, truncate=True):\n        if pileup.pos == pos:\n            for read in pileup.pileups:\n                if not read.is_del and not read.is_refskip:\n                    bases[read.alignment.query_sequence[read.query_position]] += 1\n    if bases:\n        return bases.most_common(1)[0][0]\n    return 'N'\n\nwith pysam.AlignmentFile('input.bam', 'rb') as bam:\n    consensus = consensus_at_position(bam, 'chr1', 1000000)\n    print(f'Consensus at chr1:1000000 = {consensus}')\n```\n\n### Build Consensus Sequence (Pedagogical Only)\n\nThe Python majority-vote consensus below is illustrative, NOT production. `samtools consensus` is Bayesian, quality-aware, and platform-aware; majority vote ignores base qualities and produces wrong calls on low-coverage \u002F low-quality regions. Use for teaching pileup iteration mechanics; use `samtools consensus` for any real consensus.\n\n```python\nimport pysam\nfrom collections import Counter\n\ndef build_consensus(bam_path, chrom, start, end, min_depth=3):\n    consensus = []\n\n    with pysam.AlignmentFile(bam_path, 'rb') as bam:\n        for pileup in bam.pileup(chrom, start, end, truncate=True):\n            bases = Counter()\n            for read in pileup.pileups:\n                if not read.is_del and not read.is_refskip:\n                    base = read.alignment.query_sequence[read.query_position]\n                    bases[base] += 1\n\n            if sum(bases.values()) >= min_depth:\n                consensus.append(bases.most_common(1)[0][0])\n            else:\n                consensus.append('N')\n\n    return ''.join(consensus)\n```\n\n### Create Dictionary Header\n```python\nimport pysam\n\ndef create_dict_header(fasta_path):\n    header = {'HD': {'VN': '1.6', 'SO': 'unsorted'}, 'SQ': []}\n\n    with pysam.FastaFile(fasta_path) as ref:\n        for name in ref.references:\n            length = ref.get_reference_length(name)\n            header['SQ'].append({'SN': name, 'LN': length})\n\n    return header\n\nheader = create_dict_header('reference.fa')\nfor sq in header['SQ'][:5]:\n    print(f'{sq[\"SN\"]}: {sq[\"LN\"]:,} bp')\n```\n\n## Reference Preparation Workflow\n\n**Goal:** Set up a reference genome with all indices needed by common analysis tools.\n\n**Approach:** Create FASTA index (.fai), sequence dictionary (.dict), and aligner-specific indices in sequence.\n\n### Prepare Reference for Analysis\n```bash\n# 1. Index FASTA for samtools\u002Fpysam\nsamtools faidx reference.fa\n\n# 2. Create sequence dictionary for GATK\u002FPicard\nsamtools dict reference.fa -o reference.dict\n\n# 3. Pre-populate CRAM REF_CACHE (for offline HPC nodes)\nseq_cache_populate.pl -root $REF_CACHE_DIR reference.fa\n```\n\nFor aligner-specific indices (BWA, Bowtie2, STAR, minimap2, Salmon), see read-alignment.\n\n### Check Reference Setup\n```bash\n# Verify FAI exists\nls -la reference.fa.fai\n\n# Verify dict exists\nhead reference.dict\n\n# Test fetch\nsamtools faidx reference.fa chr1:1-100\n```\n\n## Common Operations\n\n### Extract Chromosome\n```bash\nsamtools faidx reference.fa chr1 > chr1.fa\nsamtools faidx chr1.fa  # Index the subset\n```\n\n### Get Chromosome Sizes\n```bash\ncut -f1,2 reference.fa.fai > chrom.sizes\n```\n\n### Subset Reference\n```bash\nsamtools faidx reference.fa chr1 chr2 chr3 > subset.fa\nsamtools faidx subset.fa\n```\n\n### Compare Consensus to Reference\n```bash\n# Generate consensus\nsamtools consensus input.bam -o consensus.fa\n\n# Align consensus back to reference\nminimap2 -a reference.fa consensus.fa > comparison.sam\n```\n\n## Quick Reference\n\n| Task | Command |\n|------|---------|\n| Index FASTA | `samtools faidx ref.fa` |\n| Fetch region | `samtools faidx ref.fa chr1:1-1000` |\n| Create dict | `samtools dict ref.fa -o ref.dict` |\n| Build consensus | `samtools consensus in.bam -o out.fa` |\n| Chrom sizes | `cut -f1,2 ref.fa.fai` |\n\n## Related Skills\n\n- sam-bam-basics - CRAM reference resolution (REF_PATH, REF_CACHE)\n- alignment-indexing - faidx for reference access\n- alignment-validation - BAM-vs-reference M5 cross-validation\n- pileup-generation - Pileup for consensus building\n- variant-calling\u002Fvcf-basics - VCF I\u002FO for `bcftools consensus`\n- variant-calling\u002Fconsensus-sequences - Consensus from VCF (different operation)\n- read-alignment\u002Fbwa-alignment - BWA index preparation\n- sequence-io\u002Fread-sequences - Parse FASTA with Biopython\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\u002Freference-operations\u002FSKILL.md","samtools","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-reference-operations","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-reference-operations",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-reference-operations",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-reference-operations","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-reference-operations\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fprepare_reference.sh","SCRIPT","脚本",837,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-reference-operations\u002Fexamples\u002Fprepare_reference.sh",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",7264,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-reference-operations\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",[],[]]