pop-1kgp / scripts /export.py
dev-prescience's picture
Add high-coverage 1000 Genomes PLINK panel
3ae2f5f verified
Raw History Blame Contribute Delete
7.22 kB
#!/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())