|
| 1 | +# SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | +# Copyright (C) 2026 dial481 |
| 3 | +"""PLINK1 binary format (.bed/.bim/.fam) exporter.""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +from typing import TYPE_CHECKING |
| 8 | + |
| 9 | +from allelix.utils.allele import complement, is_strand_ambiguous |
| 10 | + |
| 11 | +if TYPE_CHECKING: |
| 12 | + from collections.abc import Iterator |
| 13 | + from pathlib import Path |
| 14 | + |
| 15 | + from allelix.models import Variant |
| 16 | + |
| 17 | +_BED_MAGIC = bytes([0x6C, 0x1B, 0x01]) |
| 18 | + |
| 19 | +_CHROM_CODES = { |
| 20 | + "X": "23", |
| 21 | + "Y": "24", |
| 22 | + "MT": "26", |
| 23 | +} |
| 24 | + |
| 25 | + |
| 26 | +def _orient_genotype( |
| 27 | + allele1: str, |
| 28 | + allele2: str, |
| 29 | + ref: str, |
| 30 | + alt: str, |
| 31 | +) -> tuple[str, str] | None: |
| 32 | + """Map user alleles to {ref, alt} in a consistent orientation. |
| 33 | +
|
| 34 | + Returns None for palindromic sites, indels, or alleles that don't fit. |
| 35 | + Both alleles are tested in the same orientation — no mixed-strand. |
| 36 | + """ |
| 37 | + if len(allele1) != 1 or len(allele2) != 1: |
| 38 | + return None |
| 39 | + if is_strand_ambiguous(ref, alt): |
| 40 | + return None |
| 41 | + |
| 42 | + pair = {allele1, allele2} |
| 43 | + if pair <= {ref, alt}: |
| 44 | + return (allele1, allele2) |
| 45 | + |
| 46 | + c1, c2 = complement(allele1), complement(allele2) |
| 47 | + if {c1, c2} <= {ref, alt}: |
| 48 | + return (c1, c2) |
| 49 | + |
| 50 | + return None |
| 51 | + |
| 52 | + |
| 53 | +def export_plink( |
| 54 | + variants: Iterator[Variant], |
| 55 | + prefix: Path, |
| 56 | + build: str, |
| 57 | + ref_alt_map: dict[str, tuple[str, str]] | None = None, |
| 58 | +) -> tuple[int, int, int, int]: |
| 59 | + """Write .bed/.bim/.fam from parsed variants. |
| 60 | +
|
| 61 | + Args: |
| 62 | + variants: Parsed variant iterator (consumed once). |
| 63 | + prefix: Base path for output files. |
| 64 | + build: Genome build label (informational, not used for liftover). |
| 65 | + ref_alt_map: ``{rsid: (ref, alt)}`` from gnomAD coordinate resolution. |
| 66 | + When provided, uses ref/alt to assign A1/A2 for proper allele coding. |
| 67 | + When None or rsid missing, falls back to ``A2="0"`` for homozygotes. |
| 68 | +
|
| 69 | + Returns: |
| 70 | + ``(variants_written, no_calls_skipped, indels_skipped, monomorphic_count)`` |
| 71 | +
|
| 72 | + Note: |
| 73 | + No-call variants and indels (multi-character alleles) are dropped. |
| 74 | + PLINK1 BIM is SNV-only (single-character A1/A2). Indels would |
| 75 | + produce non-standard BIM rows that downstream tools may reject. |
| 76 | + """ |
| 77 | + fam_path = prefix.with_suffix(".fam") |
| 78 | + bim_path = prefix.with_suffix(".bim") |
| 79 | + bed_path = prefix.with_suffix(".bed") |
| 80 | + |
| 81 | + fam_path.write_text("0\tSAMPLE\t0\t0\t0\t-9\n") |
| 82 | + |
| 83 | + written = 0 |
| 84 | + skipped = 0 |
| 85 | + indels = 0 |
| 86 | + monomorphic = 0 |
| 87 | + |
| 88 | + with bim_path.open("w") as bim_f, bed_path.open("wb") as bed_f: |
| 89 | + bed_f.write(_BED_MAGIC) |
| 90 | + |
| 91 | + for v in variants: |
| 92 | + if v.is_no_call: |
| 93 | + skipped += 1 |
| 94 | + continue |
| 95 | + |
| 96 | + if len(v.allele1) != 1 or len(v.allele2) != 1: |
| 97 | + indels += 1 |
| 98 | + continue |
| 99 | + |
| 100 | + chrom_code = _CHROM_CODES.get(v.chromosome, v.chromosome) |
| 101 | + a1: str |
| 102 | + a2: str |
| 103 | + bed_code: int |
| 104 | + |
| 105 | + if ref_alt_map and v.rsid in ref_alt_map: |
| 106 | + ref, alt = ref_alt_map[v.rsid] |
| 107 | + resolved = _orient_genotype(v.allele1, v.allele2, ref, alt) |
| 108 | + if resolved is not None: |
| 109 | + r1, r2 = resolved |
| 110 | + a1 = ref |
| 111 | + a2 = alt |
| 112 | + a2_count = sum(1 for a in (r1, r2) if a == alt) |
| 113 | + if a2_count == 0: |
| 114 | + bed_code = 0b00 |
| 115 | + elif a2_count == 1: |
| 116 | + bed_code = 0b10 |
| 117 | + else: |
| 118 | + bed_code = 0b11 |
| 119 | + else: |
| 120 | + a1, a2, bed_code, is_mono = _fallback_coding(v) |
| 121 | + if is_mono: |
| 122 | + monomorphic += 1 |
| 123 | + else: |
| 124 | + a1, a2, bed_code, is_mono = _fallback_coding(v) |
| 125 | + if is_mono: |
| 126 | + monomorphic += 1 |
| 127 | + |
| 128 | + bim_f.write(f"{chrom_code}\t{v.rsid}\t0\t{v.position}\t{a1}\t{a2}\n") |
| 129 | + bed_f.write(bytes([bed_code])) |
| 130 | + written += 1 |
| 131 | + |
| 132 | + return written, skipped, indels, monomorphic |
| 133 | + |
| 134 | + |
| 135 | +def _fallback_coding(v: Variant) -> tuple[str, str, int, bool]: |
| 136 | + """Fallback allele coding when ref/alt is unknown. |
| 137 | +
|
| 138 | + Returns ``(a1, a2, bed_code, is_monomorphic)``. |
| 139 | + """ |
| 140 | + if v.is_heterozygous: |
| 141 | + alleles = sorted([v.allele1, v.allele2]) |
| 142 | + return alleles[0], alleles[1], 0b10, False |
| 143 | + |
| 144 | + return v.allele1, "0", 0b00, True |
0 commit comments