File size: 7,216 Bytes
3ae2f5f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
#!/usr/bin/env python3
"""Friendly CLI for exporting per-participant 1000 Genomes files."""

from __future__ import annotations

import argparse
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from typing import Optional


SCRIPT_DIR = Path(__file__).resolve().parent
REPO_ROOT = SCRIPT_DIR.parent
DEFAULT_PRESET = "superpop-mf-10-vcf"
ALL_SHARDS = [*(f"chr{i:02d}" for i in range(1, 23)), "chrX", "chrY", "chrMT"]


def parser() -> argparse.ArgumentParser:
    result = argparse.ArgumentParser(
        description="Export compact, per-participant files from the 1KGP PLINK dataset.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )
    selection = result.add_mutually_exclusive_group()
    selection.add_argument(
        "--preset",
        metavar="NAME",
        help=f"named preset under presets/ (default when no selection is given: {DEFAULT_PRESET})",
    )
    selection.add_argument(
        "--participants",
        nargs="+",
        metavar="IID",
        help="one or more 1KGP participant IDs",
    )
    selection.add_argument(
        "--participants-file",
        type=Path,
        metavar="TSV",
        help="TSV whose first column contains participant IDs",
    )
    result.add_argument(
        "-f",
        "--format",
        choices=("vcf.gz", "vcf", "bcf"),
        default="vcf.gz",
        help="per-participant output format",
    )
    result.add_argument(
        "-r",
        "--records",
        choices=("variants", "called", "all"),
        default="all",
        help="variants=ALT calls only; called=all nonmissing calls; all=every cohort site",
    )
    result.add_argument(
        "-o",
        "--destination",
        type=Path,
        help="output directory",
    )
    result.add_argument(
        "-c",
        "--chromosomes",
        nargs="+",
        metavar="CHR",
        help="chromosomes such as 1 2 X Y MT; omit for the complete genome",
    )
    result.add_argument(
        "-t",
        "--threads",
        type=int,
        default=min(os.cpu_count() or 4, 12),
        help="native compression worker threads",
    )
    result.add_argument("--force", action="store_true", help="rebuild cached chromosome exports")
    result.add_argument("--check", action="store_true", help="check dependencies and exit")
    result.add_argument("--list-presets", action="store_true", help="list named presets and exit")
    result.add_argument("--dry-run", action="store_true", help="print the resolved export without running it")
    return result


def presets() -> list[str]:
    root = REPO_ROOT / "presets"
    if not root.is_dir():
        return []
    return sorted(path.name for path in root.iterdir() if (path / "samples.tsv").is_file())


def dependency_paths() -> dict[str, Optional[str]]:
    bundled_plink = REPO_ROOT / ".tools" / "plink2-20260818" / "plink2"
    return {
        "plink2": str(bundled_plink) if os.access(bundled_plink, os.X_OK) else shutil.which("plink2"),
        "bcftools": shutil.which("bcftools"),
        "zstd": shutil.which("zstd"),
    }


def check_dependencies() -> bool:
    found = dependency_paths()
    for name, path in found.items():
        print(f"{name:9} {path or 'NOT FOUND'}")
    return all(found.values())


def normalize_chromosome(value: str) -> str:
    raw = value.removeprefix("chr")
    upper = raw.upper()
    if upper in {"X", "Y"}:
        shard = f"chr{upper}"
    elif upper in {"M", "MT"}:
        shard = "chrMT"
    else:
        try:
            number = int(raw)
        except ValueError as error:
            raise argparse.ArgumentTypeError(f"unknown chromosome: {value}") from error
        shard = f"chr{number:02d}"
    if shard not in ALL_SHARDS:
        raise argparse.ArgumentTypeError(f"unknown chromosome: {value}")
    return shard


def default_destination(name: str) -> Path:
    return REPO_ROOT / "export" / name


def main() -> int:
    args = parser().parse_args()

    if args.list_presets:
        for name in presets():
            print(name)
        return 0
    if args.check:
        return 0 if check_dependencies() else 127
    if args.threads < 1:
        parser().error("--threads must be a positive integer")

    temporary_manifest: Optional[Path] = None
    if args.participants:
        participants = list(dict.fromkeys(args.participants))
        if len(participants) != len(args.participants):
            parser().error("--participants contains duplicate IDs")
        work = REPO_ROOT / "work" / "export-cli"
        work.mkdir(parents=True, exist_ok=True)
        handle = tempfile.NamedTemporaryFile(
            mode="w", prefix="participants-", suffix=".tsv", dir=work, delete=False
        )
        with handle:
            handle.write("#IID\n")
            handle.writelines(f"{participant}\n" for participant in participants)
        temporary_manifest = Path(handle.name)
        manifest = temporary_manifest
        export_name = "participants"
    elif args.participants_file:
        manifest = args.participants_file.expanduser().resolve()
        if not manifest.is_file():
            parser().error(f"participant file not found: {manifest}")
        export_name = manifest.stem
    else:
        preset = args.preset or DEFAULT_PRESET
        if preset not in presets():
            parser().error(f"unknown preset: {preset}; use --list-presets")
        manifest = REPO_ROOT / "presets" / preset / "samples.tsv"
        export_name = preset

    destination = (args.destination or default_destination(export_name)).expanduser().resolve()
    shards = ALL_SHARDS
    if args.chromosomes:
        try:
            shards = list(dict.fromkeys(normalize_chromosome(item) for item in args.chromosomes))
        except argparse.ArgumentTypeError as error:
            parser().error(str(error))

    command = [
        str(SCRIPT_DIR / "export-individual-vcfs.sh"),
        "--samples",
        str(manifest),
        "--output-dir",
        str(destination),
        "--format",
        args.format,
        "--records",
        args.records,
    ]
    environment = os.environ.copy()
    environment["THREADS"] = str(args.threads)
    environment["SHARDS"] = " ".join(shards)
    if args.force:
        environment["FORCE"] = "1"

    print(f"Participants: {manifest}")
    print(f"Destination:  {destination}")
    print(f"Format:       {args.format}")
    print(f"Records:      {args.records}")
    print(f"Chromosomes:  {' '.join(shards)}")
    print(f"Threads:      {args.threads}")
    sys.stdout.flush()
    if args.dry_run:
        if temporary_manifest:
            temporary_manifest.unlink(missing_ok=True)
        return 0

    missing = [name for name, path in dependency_paths().items() if not path]
    if missing:
        print(f"Missing required tools: {', '.join(missing)}", file=sys.stderr)
        print("Run scripts/export.py --check to inspect the toolchain.", file=sys.stderr)
        return 127

    try:
        return subprocess.run(command, env=environment, check=False).returncode
    finally:
        if temporary_manifest:
            temporary_manifest.unlink(missing_ok=True)


if __name__ == "__main__":
    raise SystemExit(main())