//! The six panel installers og runs: `--ancestry-panel`, //! `--ancestry-fine-panel`, `--mocha-data`, `--ancient-panel`, `--archaic` //! and `--consumer-sites`. Each does what its bash function in //! scripts/setup.sh does: the same downloads ([`Run::fetch`]), the same //! container runs with the same arguments (bcftools, plink2, EIGENSOFT, //! Picard, MoChA's bcftools), the same messages, the same files and the //! same exit status. The steps bash ran in the host shell (awk, sort, cut, //! gzip) are Rust here, with the same bytes; og's own panel tools (`og //! ancient`, `og archaic`, `og ancestry-fine`, `og consumer build-sites`, //! `og setup genetic-map`) run as og on the host instead of inside //! OG_IMAGE ([`og_tool`]). //! //! The stamps (`panel/DONE`, `model/DONE`, `maps/DONE`, `chrN.stamp`, the //! MoChA and archaic `DONE`, the ancient `DONE`) are built by the //! functions below from the same inputs as bash's, byte for byte: a stamp //! that changed by one character would rebuild every existing install //! (tests/panels.rs compares each with the string setup.sh builds). use super::{Ported, Run, keep, nonempty, sha256}; use crate::engine::{Place, RunIn}; use crate::fetch::{self, Sources}; use crate::images::{self, Engine}; use std::fs; use std::io::{Read, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; /// The keys this module runs. `--ancestry-panel` installs the download of /// its source row; the others build what they install, and /// tests/panels.rs ties each installed path to the setup.sh line that /// makes it. pub const PORTED: &[Ported] = &[ Ported::downloaded("ancestry-panel"), Ported::made("ancestry-fine-panel", "tests/panels.rs").unchecked(&[( "reference/ancestry_fine/${ANCESTRY_FINE_PANEL}/panel/DONE", "model/DONE, which is checked, is written after it: a finished model means a finished panel", )]), Ported::made("mocha-data", "tests/panels.rs").unchecked(&[( "reference/mocha-${MOCHA_PANEL_VERSION}/DONE", "opt-in data validate-setup.sh has no line for", )]), Ported::made("ancient-panel", "tests/panels.rs").unchecked(&[( "reference/ancient/aadr_${AADR_VERSION}/DONE", "opt-in data validate-setup.sh has no line for; main.nf checks this DONE before step 44", )]), Ported::made("archaic", "tests/panels.rs").unchecked(&[( "reference/archaic/${ARCHAIC_DATA_VERSION}/DONE", "opt-in data validate-setup.sh has no line for; main.nf checks this DONE before step 43", )]), Ported::made("consumer-sites", "tests/panels.rs"), ]; /// setup.sh's URLs of the panels that versions.env does not hold; setup.sh /// keeps the same lines while it has its bash installers (tests/panels.rs /// compares them, and scripts/ci/check-links.sh asks setup.sh's). pub const HG19_TO_HG38_CHAIN_URL: &str = "https://hgdownload.soe.ucsc.edu/goldenPath/hg19/liftOver/hg19ToHg38.over.chain.gz"; pub const ANCESTRY_FINE_META_URL: &str = "https://storage.googleapis.com/gcp-public-data--gnomad/release/3.1/secondary_analyses/hgdp_1kg_v2/metadata_and_qc/gnomad_meta_updated.tsv"; pub const ANCESTRY_FINE_MAP_URL: &str = "https://bochet.gcc.biostat.washington.edu/beagle/genetic_maps/plink.GRCh38.map.zip"; pub const ANCESTRY_FINE_MAP_MIRROR_URL: &str = "https://web.archive.org/web/20260306143720id_/https://bochet.gcc.biostat.washington.edu/beagle/genetic_maps/plink.GRCh38.map.zip"; pub const ARCHAIC_URL: &str = "https://cdna.eva.mpg.de/neandertal/Vindija/VCF"; pub const ARCHAIC_FILTERBED_URL: &str = "https://cdna.eva.mpg.de/neandertal/Vindija/FilterBed"; pub const ARCHAIC_1KG_SITES_URL: &str = "https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/release/20130502/ALL.wgs.phase3_shapeit2_mvncall_integrated_v5c.20130502.sites.vcf.gz"; pub const ARCHAIC_STRICT_MASK_URL: &str = "https://ftp.1000genomes.ebi.ac.uk/vol1/ftp/data_collections/1000_genomes_project/working/20160622_genome_mask_GRCh38/StrictMask/20160622.allChr.mask.bed"; pub const ARCHAIC_SEGDUPS_URL: &str = "https://hgdownload.soe.ucsc.edu/goldenPath/hg19/database/genomicSuperDups.txt.gz"; pub const ARCHAIC_CHAIN_URL: &str = "https://hgdownload.soe.ucsc.edu/goldenPath/hg19/liftOver/hg19ToHg38.over.chain.gz"; /// The version of the table og archaic table and strict write. pub const ARCHAIC_TABLE_FORMAT: &str = "archaic-table-v1"; /// What code= held when bin/archaic_report.py built the table: a stamp /// with it is accepted once and rewritten (one release after 1.0.0). pub const ARCHAIC_TABLE_PYTHON_SHA256: &str = "6bdc4c99a8d80d96179551e37022a3cd5324f650577b9fd64e27d84383e0f1d7"; /// The command lines bash hands to a container shell (`sh -c` or `bash /// -euo pipefail -c`), verbatim: the container runs the same program. pub const PGSC_UNPACK_SH: &str = r#"cd "$2" && tar -xf "$1" --wildcards "GRCh38_*_ALL.pgen" "GRCh38_*_ALL.psam" "GRCh38_*_ALL.pvar.zst""#; pub const FINE_SAMPLES_SH: &str = r#"bcftools query -l "$1" 2>/dev/null"#; pub const FINE_PANEL_SH: &str = r#" cd "$(dirname "$3")"; trap "rm -f ./*.bcf.csi" EXIT r=(); [ -z "$4" ] || r=(-R "$4" --regions-overlap pos) { bcftools view "${r[@]}" --force-samples -S "$2" -m2 -M2 -v snps -Ou "$1" \ | bcftools view -q 0.05:minor -Ou \ | bcftools annotate -x ID,INFO,^FORMAT/GT -Ou \ | bcftools +prune -n 1 -w "$5" -N maxAF -Oz -o "$3.part"; } 2> >(grep -v bcf_hdr_check_sanity >&2) bcftools index -t "$3.part" mv "$3.part.tbi" "$3.tbi"; mv "$3.part" "$3""#; pub const FINE_SITES_SH: &str = r#"cd "$1"; for c in $2; do bcftools query -f "%CHROM\t%POS\t%REF\t%ALT\n" "$c.vcf.gz"; done"#; pub const FINE_MODEL_SH: &str = r#" for c in $4; do bcftools view -S "$2" -Ou "$1/$c.vcf.gz" | bcftools +prune -m 0.1 -w 500kb -Ob -o "$3/$c.bcf"; done for c in $4; do echo "$3/$c.bcf"; done > "$3/bcfs.txt" bcftools concat -f "$3/bcfs.txt" -Oz -o "$3/adm.vcf.gz""#; pub const MOCHA_CUT_SH: &str = r#" r=(); [ -z "$3" ] || r=(-R "$3") bcftools query "${r[@]}" -i "AC>1 && END-POS+1>10000 && (SVTYPE==\"CNV\" || SVTYPE==\"DEL\" || SVTYPE==\"DUP\")" \ -f "%CHROM\t%POS0\t%END\t%SVTYPE\n" "$1" > "$4.part" bcftools view --no-version "${r[@]}" -m2 -M2 -v snps -c 2 -Ou "$1" \ | bcftools annotate --no-version -x ID,QUAL,FILTER,INFO,^FMT/GT -Oz -o "$2.part" bcftools index -f -t "$2.part" mv "$4.part" "$4"; mv "$2.part.tbi" "$2.tbi"; mv "$2.part" "$2""#; pub const ANCIENT_EIGENSOFT_SH: &str = r#" convertf -p "$1/convertf.par" > "$1/convertf.log" smartpca -p "$1/panel.par" > "$1/panel.log" smartpca -p "$1/check.par" > "$1/check.log""#; pub const ARCHAIC_MODERN_SH: &str = r#" r=(-r "$2"); [ ! -s "$4" ] || r=(-R "$4") bcftools view "${r[@]}" -m2 -M2 -v snps -Ou "$1" \ | bcftools query -f "%POS\t%REF\t%ALT\t%INFO/AF\t%INFO/AFR_AF\t%INFO/AMR_AF\t%INFO/EAS_AF\t%INFO/EUR_AF\t%INFO/SAS_AF\n" > "$3/modern.tsv" bcftools view -r "$2" -v indels -Ou "$1" \ | bcftools query -f "%POS\t%REF\t%ALT\n" > "$3/indels.tsv""#; pub const ARCHAIC_GENOTYPES_SH: &str = r#" r=(); [ ! -s "$4" ] || r=(-T "$4") for g in Altai Vindija33.19 Denisova; do bcftools query "${r[@]}" -i "GT=\"alt\"" -f "%POS\n" "$1/$g.chr$2.vcf.gz" done > "$3/nonref.pos" { cut -f1 "$3/modern.tsv"; cat "$3/nonref.pos"; } | sort -nu | awk -v c="$2" "{print c \"\t\" \$1}" > "$3/keep.tsv" for g in Altai Vindija33.19 Denisova; do bcftools query -T "$3/keep.tsv" -i "GT!=\"mis\"" -f "%POS\t%REF\t%ALT\t[%GT]\n" "$1/$g.chr$2.vcf.gz" > "$3/$g.tsv" done"#; pub const ARCHAIC_LIFTED_SH: &str = r#"bcftools query -i "CHROM==\"chr$2\"" -f "%CHROM\t%POS\t%REF\t%ALT\t%INFO/Altai\t%INFO/Vindija\t%INFO/Denisova\t%INFO/AF_ALL\t%INFO/AF_AFR\t%INFO/AF_AMR\t%INFO/AF_EAS\t%INFO/AF_EUR\t%INFO/AF_SAS\n" "$1" > "$3/lifted.tsv""#; /// Every program above, for the test that finds each in setup.sh. pub const SHELL_PROGRAMS: [&str; 10] = [ PGSC_UNPACK_SH, FINE_SAMPLES_SH, FINE_PANEL_SH, FINE_SITES_SH, FINE_MODEL_SH, MOCHA_CUT_SH, ANCIENT_EIGENSOFT_SH, ARCHAIC_MODERN_SH, ARCHAIC_GENOTYPES_SH, ARCHAIC_LIFTED_SH, ]; /// Runs KEY when it is one of [`PORTED`]; its exit status. pub fn run(key: &str, r: &Run, out: &mut dyn Write, err: &mut dyn Write) -> Option { let res = match key { "ancestry-panel" => ancestry_panel(r, out, err), "ancestry-fine-panel" => ancestry_fine_panel(r, out, err), "mocha-data" => mocha_data(r, out, err), "ancient-panel" => ancient_panel(r, out, err), "archaic" => archaic(r, out, err), "consumer-sites" => consumer_sites(r, out, err), _ => return None, }; let _ = out.flush(); Some(match res { Ok(()) => 0, Err(c) => c, }) } /// An installer's result: `Err` carries its exit status (1 after a /// warning, 2 where bash's run_in exits 2). pub type Step = Result<(), u8>; fn p(s: &str) -> PathBuf { PathBuf::from(s) } fn show(p: &Path) -> String { p.to_string_lossy().into_owned() } /// `echo MSG; return 1`. fn warn(out: &mut dyn Write, msg: &str) -> u8 { let _ = writeln!(out, "{msg}"); 1 } /// `$(cat FILE)`: the file without its trailing newlines, "" when it /// cannot be read. pub fn cat(f: &Path) -> String { fs::read(f) .map(|b| { String::from_utf8_lossy(&b) .trim_end_matches('\n') .to_owned() }) .unwrap_or_default() } /// `$(wc -l < FILE | tr -d ' ')`: its newlines, "" when it cannot be read. pub fn wc_l(f: &Path) -> String { fs::read(f) .map(|b| b.iter().filter(|&&c| c == b'\n').count().to_string()) .unwrap_or_default() } /// The newlines of FILE as a number (0 when it cannot be read). fn lines_of(f: &Path) -> i64 { wc_l(f).parse().unwrap_or(0) } /// `echo "TEXT" > FILE`. fn echo_to(f: &Path, text: &str, err: &mut dyn Write) -> Step { write_file(f, format!("{text}\n").as_bytes(), err) } fn write_file(f: &Path, bytes: &[u8], err: &mut dyn Write) -> Step { fs::write(f, bytes).map_err(|e| { let _ = writeln!(err, "ERROR: cannot write {}: {e}", show(f)); 1 }) } /// `mkdir -p DIR...`, with mkdir's message when one fails. fn mkdirs(dirs: &[&Path], err: &mut dyn Write) -> Step { let mut ok = true; for d in dirs { ok &= keep::mkdir_p(&show(d), err); } ok.then_some(()).ok_or(1) } /// [`keep::rm_rf`] of one path. fn rm_rf(f: &Path, err: &mut dyn Write) { keep::rm_rf(&[show(f).as_str()], err); } /// [`keep::mv`]: `mv SRC DEST`, its status as a step. fn mv(src: &Path, dest: &Path, err: &mut dyn Write) -> Step { if keep::mv(&show(src), &show(dest), err) { Ok(()) } else { Err(1) } } /// `cp SRC DEST`. fn cp(src: &Path, dest: &Path, err: &mut dyn Write) -> Step { cp_file(src, dest).map_err(|e| { let _ = writeln!(err, "cp: cannot copy '{}': {e}", show(src)); 1 }) } /// The bytes of `cp SRC DEST` (no -p): a new DEST gets SRC's mode less the /// umask, an existing one keeps its own mode. `fs::copy` would give DEST /// SRC's mode as it is. pub fn cp_file(src: &Path, dest: &Path) -> std::io::Result<()> { use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; let mut from = fs::File::open(src)?; let mode = from.metadata()?.permissions().mode() & 0o7777; let mut to = fs::OpenOptions::new() .write(true) .create(true) .truncate(true) .mode(mode) .open(dest)?; std::io::copy(&mut from, &mut to).map(|_| ()) } /// `[ -s F ] && [ "$(_digest sha256 F)" = WANT ]`. fn has_sha(f: &Path, want: &str) -> bool { nonempty(f) && sha256(f) == want } /// `[ -s F ] && [ "$(_digest md5 F)" = WANT ]`. fn has_md5(f: &Path, want: &str) -> bool { nonempty(f) && fetch::digest(fetch::Kind::Md5, f).unwrap_or_default() == want } /// The sha256 of TEXT (`_digest sha256 <(printf ...)`). pub fn sha256_of(text: &[u8]) -> String { use sha2::{Digest, Sha256}; let h = Sha256::digest(text); h.iter().map(|b| format!("{b:02x}")).collect() } /// The names in DIR matching the glob PREFIX*SUFFIX, sorted as bash sorts /// a glob in the C locale; names starting with a dot are not matched. fn glob(dir: &Path, prefix: &str, suffix: &str) -> Vec { let mut v: Vec = fs::read_dir(dir) .into_iter() .flatten() .flatten() .filter_map(|e| { let n = e.file_name().to_string_lossy().into_owned(); (!n.starts_with('.') && n.len() >= prefix.len() + suffix.len() && n.starts_with(prefix) && n.ends_with(suffix)) .then(|| e.path()) }) .collect(); v.sort(); v } /// One field of the environment or versions.env (`${NAME:-}`). fn val(r: &Run, k: &str) -> String { r.version(k) } /// `${NAME:-}` of the environment alone (a setting no versions.env holds). fn env(r: &Run, k: &str) -> String { r.vars.nonempty(k).unwrap_or("").to_owned() } /// THREADS as common.sh sets it (8 when unset or empty). fn threads(r: &Run) -> String { r.vars.nonempty("THREADS").unwrap_or("8").to_owned() } /// `dl NAME`: where setup keeps the raw download NAME. fn dl(r: &Run, name: &str) -> PathBuf { p(&format!( "{}/{name}", r.vars.get("OG_DOWNLOADS").unwrap_or("") )) } /// `cpath HOST`: its container path, or common.sh's message on ERR. fn cpath(r: &Run, host: &Path, err: &mut dyn Write) -> Result { crate::engine::cpath( &r.genome, r.vars.nonempty("OG_DOWNLOADS"), &host.to_string_lossy(), ) .map_err(|m| { let _ = writeln!(err, "{m}"); 1 }) } /// REF_FASTA's container path (REF_FASTA_C). fn ref_c(r: &Run, err: &mut dyn Write) -> Result { cpath(r, &p(r.vars.get("REF_FASTA").unwrap_or("")), err) } /// REF_DICT: REF_FASTA without `.gz` and its last extension, plus `.dict`. pub fn ref_dict(fasta: &str) -> String { let f = fasta.strip_suffix(".gz").unwrap_or(fasta); let stem = f.rfind('.').map_or(f, |i| &f[..i]); format!("{stem}.dict") } /// `source_of ID [--part P] FIELD` (path, url or value), its error on ERR. fn source( r: &Run, id: &str, part: Option<&str>, field: &str, err: &mut dyn Write, ) -> Result { let res = (|| -> Result { let ctx = r.ctx()?; let s = Sources::read(&ctx.root)?; let row = s.get(id)?; match field { "path" => Ok(ctx.path(row, part)?.to_string_lossy().into_owned()), "url" => ctx.url(row, part), "value" => ctx.value(&s, row, part), f => Err(format!( "og setup source: no field '{f}' (path, url, check, value, bytes)" )), } })(); res.map_err(|m| { let _ = writeln!(err, "{m}"); 1 }) } /// [`keep::done_with`] of FILES. fn done_with(r: &Run, files: &[&Path], out: &mut dyn Write, err: &mut dyn Write) { let names: Vec = files.iter().map(|f| show(f)).collect(); let names: Vec<&str> = names.iter().map(String::as_str).collect(); keep::done_with(r, &names, out, err); } /// [`keep::adopt`] of OLD and NEW. fn adopt( r: &Run, old: &Path, new: &Path, check: Option<&keep::Check>, out: &mut dyn Write, err: &mut dyn Write, ) { keep::adopt(r, &show(old), &show(new), check, out, err); } /// `need_og WHAT` (and the two installers that spell it out): og for the /// containers of a run, built when `rust/og.sh check --required` fails; /// false after setup.sh's warning. fn need_og(r: &Run, what: &str, out: &mut dyn Write) -> bool { let _ = out.flush(); let og_sh = r.root.join("rust/og.sh"); let checked = crate::child::status( Command::new(&og_sh) .args(["check", "--required"]) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()), ) .is_ok_and(|s| s.success()); if checked || crate::child::status(Command::new(&og_sh).arg("install").stdin(Stdio::null())) .is_ok_and(|s| s.success()) { return true; } let _ = writeln!( out, "[WARN] Could not build og, which {what}: run {} --og and look at its error.", r.script ); false } /// `ensure_image VAR STEP` for each VAR, stopping at the first that fails. fn ensure(r: &Run, vars: &[&str], step: &str, out: &mut dyn Write, err: &mut dyn Write) -> Step { let e = Engine::from_vars(&r.vars); for v in vars { let _ = out.flush(); if !images::ensure_image(&e, &val(r, v), step, &r.vars, out, err) { return Err(1); } } Ok(()) } /// Where a run's standard output goes. enum To<'a> { Terminal, /// `> FILE`. File(&'a Path), /// `> FILE 2>&1`. Both(&'a Path), /// `$(...)`. Capture, } /// Spawns COMMAND with its output sent to TO; its exit status (1 when it /// could not start) and what it printed when captured. fn spawn( mut c: Command, to: To, out: &mut dyn Write, err: &mut dyn Write, ) -> Result<(bool, Vec), u8> { let _ = out.flush(); let _ = err.flush(); let _ = std::io::stdout().flush(); let open = |f: &Path, err: &mut dyn Write| { fs::File::create(f).map_err(|e| { let _ = writeln!(err, "ERROR: cannot write {}: {e}", show(f)); 1u8 }) }; match to { To::Terminal => {} To::File(f) => { c.stdout(open(f, err)?); } To::Both(f) => { let h = open(f, err)?; let h2 = h.try_clone().map_err(|_| 1u8)?; c.stdout(h).stderr(h2); } To::Capture => { c.stdout(Stdio::piped()); } } c.stdin(Stdio::null()); let Ok((mut child, ticket)) = crate::child::spawn(&mut c) else { return Ok((false, Vec::new())); }; let mut got = Vec::new(); if let Some(mut so) = child.stdout.take() { let _ = so.read_to_end(&mut got); } let ok = child.wait().is_ok_and(|s| s.success()); ticket.done(); Ok((ok, got)) } /// `run_in [--net] [--rw DIR]... REST...` of common.sh with the output /// sent to TO: its success, and what it printed when captured. A folder /// outside the install folder stops setup with exit 2, as run_in does. fn run_in( r: &Run, net: bool, rw: &[&Path], rest: &[String], to: To, out: &mut dyn Write, err: &mut dyn Write, ) -> Result<(bool, Vec), u8> { let spec = RunIn { net, root: false, rw: rw.iter().map(|d| show(d)).collect(), }; let argv = spec.argv(&Place::from_vars(&r.vars), rest).map_err(|m| { let _ = writeln!(err, "{m}"); 2u8 })?; let mut c = Command::new(Engine::from_vars(&r.vars).cmd); c.args(argv); spawn(c, to, out, err) } /// One of og's own panel tools, run by this og on the host where bash ran /// `/pgp-bin/og ARGS` in OG_IMAGE: the container's environment (PATH, /// HOME=/tmp), this process's umask. fn og_tool( r: &Run, args: &[String], to: To, out: &mut dyn Write, err: &mut dyn Write, ) -> Result<(bool, Vec), u8> { let mut c = Command::new(&r.og); c.args(args).env_clear().env("HOME", "/tmp"); for k in ["PATH", "TMPDIR"] { if let Some(v) = std::env::var_os(k) { c.env(k, v); } } spawn(c, to, out, err) } fn s(x: &str) -> String { x.to_owned() } fn args(v: &[&str]) -> Vec { v.iter().map(|x| (*x).to_owned()).collect() } /// `tail -n N FILE...` on the terminal. fn tail(n: &str, files: &[PathBuf], out: &mut dyn Write) { let mut c = Command::new("tail"); c.args(["-n", n]).args(files).stderr(Stdio::null()); let _ = spawn(c, To::Terminal, out, &mut std::io::sink()); } /// The fields of an awk record split by the default FS (spaces and tabs). pub fn awk_fields(line: &str) -> Vec<&str> { line.split([' ', '\t']).filter(|f| !f.is_empty()).collect() } /// awk's records: the lines of TEXT, a last one without a newline included. pub fn awk_records(text: &str) -> Vec<&str> { let t = text.strip_suffix('\n').unwrap_or(text); if text.is_empty() { return Vec::new(); } t.split('\n').collect() } /// Whether awk reads FIELD as a number (a strnum). fn looks_numeric(f: &str) -> bool { let t = f.trim_matches([' ', '\t', '\n']); let b = t.strip_prefix(['+', '-']).unwrap_or(t); let (m, e) = match b.find(['e', 'E']) { Some(i) => (&b[..i], Some(&b[i + 1..])), None => (b, None), }; let mantissa = !m.is_empty() && m.chars().filter(|&c| c == '.').count() <= 1 && m.chars().all(|c| c.is_ascii_digit() || c == '.') && m.chars().any(|c| c.is_ascii_digit()); let exp = e.is_none_or(|e| { let e = e.strip_prefix(['+', '-']).unwrap_or(e); !e.is_empty() && e.chars().all(|c| c.is_ascii_digit()) }); mantissa && exp } /// awk's `FIELD == C` for a constant or `-v` value C: numbers compare as /// numbers, anything else as strings. pub fn awk_eq(field: &str, c: &str) -> bool { if looks_numeric(field) && looks_numeric(c) { let n = |x: &str| { x.trim_matches([' ', '\t', '\n']) .parse::() .unwrap_or(f64::NAN) }; return n(field) == n(c); } field == c } /// The chromosomes a regions BED names, as bash lists them: each first /// field `chr1` to `chr22` (CHR true) or `1` to `22`, sorted as numbers, /// once each, each followed by a space. pub fn regions_chroms(bed: &str, chr: bool) -> String { let mut n: Vec = awk_records(bed) .into_iter() .filter_map(|l| awk_fields(l).first().copied()) .filter_map(|f| { let d = if chr { f.strip_prefix("chr")? } else { f }; let ok = match d.as_bytes() { [a] => (b'1'..=b'9').contains(a), [b'1', b] => b.is_ascii_digit(), [b'2', b] => (b'0'..=b'2').contains(b), _ => false, }; ok.then(|| d.parse().ok()).flatten() }) .collect(); n.sort_unstable(); n.dedup(); n.iter() .map(|c| { if chr { format!("chr{c} ") } else { format!("{c} ") } }) .collect() } /// chr1 to chr22 (or 1 to 22), each followed by a space. pub fn all_chroms(chr: bool) -> String { (1..=22) .map(|c| { if chr { format!("chr{c} ") } else { format!("{c} ") } }) .collect() } /// `${chroms% }`: one trailing space off. fn trim1(s: &str) -> &str { s.strip_suffix(' ').unwrap_or(s) } // --- Stamps -------------------------------------------------------------------------- /// The fine panel's `panel/DONE` and `chrN.stamp`. pub fn fine_panel_stamp(pins: &str, rstamp: &str, thin: &str, keep: &str, image: &str) -> String { let regions = if rstamp.is_empty() { "all" } else { rstamp }; format!("pins={pins} regions={regions} thin={thin} keep={keep} bcftools={image}") } /// The fine panel's `model/DONE`. pub fn fine_model_stamp(sites: &str, samples: &str) -> String { format!("panel={sites} samples={samples} freqs=og-1") } /// `maps/DONE` of the fine panel (install_fine_maps). pub fn fine_maps_stamp(map: &str, chroms: &str) -> String { format!("map={map} chroms={}", trim1(chroms)) } /// MoChA's `DONE` and `panel/chrN.stamp`. pub fn mocha_stamp(manifest: &str, rstamp: &str, image: &str) -> String { format!("manifest={manifest} regions={rstamp} bcftools={image} cnp=1") } /// The sha256 of the archaic masks' pins, one per line. pub fn archaic_masks(pins: [&str; 5]) -> String { let mut t = String::new(); for x in pins { t.push_str(x); t.push('\n'); } sha256_of(t.as_bytes()) } /// The archaic `DONE` and `chrN.stamp`. pub fn archaic_stamp( version: &str, rstamp: &str, bcftools: &str, picard: &str, masks: &str, code: &str, ) -> String { format!( "data={version} regions={rstamp} bcftools={bcftools} picard={picard} masks={masks} code={code}" ) } /// The stamp a table bin/archaic_report.py built holds: STAMP with code= /// its sha256. pub fn archaic_legacy(stamp: &str) -> String { let head = stamp.rfind(" code=").map_or(stamp, |i| &stamp[..i]); format!("{head} code={ARCHAIC_TABLE_PYTHON_SHA256}") } /// The ancient panel's `DONE`: the release, the sites placed on GRCh38 /// (the lines of sites_grch38.tsv less its header) and the day it was built. pub fn ancient_done(release: &str, site_lines: i64, day: &str) -> String { format!( "release\t{release}\nsites_grch38\t{}\nbuilt\t{day}\n", site_lines - 1 ) } /// `date -u '+%Y-%m-%d'` of SECS since 1970. pub fn utc_day(secs: u64) -> String { let days = i64::try_from(secs / 86_400).unwrap_or(0); let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z.rem_euclid(146_097); let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; let y = yoe + era * 400 + i64::from(m <= 2); format!("{y:04}-{m:02}-{d:02}") } /// ancient_smartpca_par GENO SNP IND POPLIST OUT, with THREADS. pub fn smartpca_par( geno: &str, snp: &str, ind: &str, poplist: &str, out: &str, threads: &str, ) -> String { [ format!("genotypename: {geno}"), format!("snpname: {snp}"), format!("indivname: {ind}"), format!("poplistname: {poplist}"), format!("evecoutname: {out}.evec"), format!("evaloutname: {out}.eval"), s("lsqproject: YES"), s("numoutevec: 10"), s("numoutlieriter: 0"), s("hashcheck: NO"), format!("numthreads: {threads}"), ] .iter() .map(|l| format!("{l}\n")) .collect() } /// The convertf parameters of the ancient panel (R: the raw folder, P: the /// panel being built, both container paths). pub fn convertf_par(raw: &str, part: &str) -> String { [ format!("genotypename: {raw}/aadr.geno"), format!("snpname: {raw}/aadr.snp"), format!("indivname: {part}/panel.ind"), format!("poplistname: {part}/poplist.txt"), s("outputformat: EIGENSTRAT"), format!("genooutfilename: {part}/moderns.geno"), format!("snpoutfilename: {part}/moderns.snp"), format!("indoutfilename: {part}/moderns.ind"), s("hashcheck: NO"), ] .iter() .map(|l| format!("{l}\n")) .collect() } /// plink2's memory in MB: three quarters of the host's RAM (MemTotal of /// /proc/meminfo, or hw.memsize where there is no /proc/meminfo; 16 GiB /// when sysctl does not answer), at most 8000. pub fn plink_mem_mb(meminfo: Option<&str>, memsize: Option<&str>) -> String { let mb = match meminfo { Some(t) => { let v: Vec = awk_records(t) .into_iter() .filter(|l| l.starts_with("MemTotal:")) .map(|l| { let kb = awk_fields(l) .get(1) .and_then(|x| awk_number(x)) .unwrap_or(0.0); format!("{}", (kb * 3.0 / 4.0 / 1024.0).trunc() as i64) }) .collect(); v.join("\n") } None => { let b: i128 = memsize .map(str::trim) .and_then(|x| x.parse().ok()) .unwrap_or(17_179_869_184); (b * 3 / 4 / 1_048_576).to_string() } }; match mb.parse::() { Ok(n) if n <= 8000 => n.to_string(), _ => s("8000"), } } /// awk's numeric value of a field: its leading number. fn awk_number(x: &str) -> Option { let t = x.trim_start_matches([' ', '\t']); let end = t .char_indices() .take_while(|&(i, c)| c.is_ascii_digit() || c == '.' || (i == 0 && (c == '-' || c == '+'))) .map(|(i, c)| i + c.len_utf8()) .last() .unwrap_or(0); t[..end].parse().ok().or(Some(0.0)) } /// The panel's common biallelic SNVs from plink2's .pvar files: chrN, /// position, REF and ALT of each ACGT SNV, sorted (LC_ALL=C sort -u -k1,1 /// -k2,2n -k3,3 -k4,4), as setup.sh's awk and sort write them. pub fn ancestry_sites(pvars: &[String]) -> Vec { let mut rows: Vec<(String, f64, String, String, String)> = Vec::new(); let mut col: std::collections::HashMap = std::collections::HashMap::new(); for text in pvars { for line in awk_records(text) { if line.starts_with("##") { continue; } let f: Vec<&str> = line.split('\t').collect(); if line.starts_with('#') { for (i, name) in f.iter().enumerate() { col.insert((*name).to_owned(), i + 1); } continue; } let get = |name: &str| -> &str { match col.get(name).copied().unwrap_or(0) { 0 => line, i => f.get(i - 1).copied().unwrap_or(""), } }; let chr = get("#CHROM"); let chr = chr.strip_prefix("chr").unwrap_or(chr); let (r, a) = (get("REF"), get("ALT")); let base = |x: &str| matches!(x, "A" | "C" | "G" | "T"); if base(r) && base(a) { let pos = get("POS"); rows.push(( format!("chr{chr}"), sort_number(pos), format!("\t{r}"), format!("\t{a}"), format!("chr{chr}\t{pos}\t{r}\t{a}"), )); } } } rows.sort_by(|x, y| { x.0.as_bytes() .cmp(y.0.as_bytes()) .then(x.1.total_cmp(&y.1)) .then(x.2.as_bytes().cmp(y.2.as_bytes())) .then(x.3.as_bytes().cmp(y.3.as_bytes())) }); rows.dedup_by(|x, y| x.0 == y.0 && x.1 == y.1 && x.2 == y.2 && x.3 == y.3); let mut o = Vec::new(); for row in rows { o.extend_from_slice(row.4.as_bytes()); o.push(b'\n'); } o } /// `sort -n`'s value of a key: its leading number, 0 when it has none. fn sort_number(k: &str) -> f64 { let t = k.trim_start_matches([' ', '\t']); let neg = t.starts_with('-'); let d = t.strip_prefix('-').unwrap_or(t); let end = d .find(|c: char| !(c.is_ascii_digit() || c == '.')) .unwrap_or(d.len()); let v: f64 = d[..end].parse().unwrap_or(0.0); if neg { -v } else { v } } /// chrC's exclusion list of the archaic table, before gzip: UCSC's /// segmental duplications on chrC (from genomicSuperDups.txt, decompressed) /// and each 1000 Genomes indel with 5 bp each side past its longer allele, /// sorted by start and end (`sort -k2,2n -k3,3n`). pub fn archaic_exclude(segdups: &str, indels: &str, c: &str) -> Vec { let want = format!("chr{c}"); let mut rows: Vec<(f64, f64, String)> = Vec::new(); for l in awk_records(segdups) { let f = awk_fields(l); if f.get(1).copied().unwrap_or("") == want { let (a, b) = ( f.get(2).copied().unwrap_or(""), f.get(3).copied().unwrap_or(""), ); rows.push((sort_number(a), sort_number(b), format!("{c}\t{a}\t{b}"))); } } for l in awk_records(indels) { let f: Vec<&str> = l.split('\t').collect(); let get = |i: usize| f.get(i).copied().unwrap_or(""); let mut n = get(1).chars().count(); for a in get(2).split(',') { n = n.max(a.chars().count()); } let pos = awk_number(get(0)).unwrap_or(0.0); let start = (pos - 6.0).max(0.0); let end = pos + 5.0 + n as f64; let (a, b) = (awk_num_text(start), awk_num_text(end)); rows.push((start, end, format!("{c}\t{a}\t{b}"))); } rows.sort_by(|x, y| { x.0.total_cmp(&y.0) .then(x.1.total_cmp(&y.1)) .then(x.2.as_bytes().cmp(y.2.as_bytes())) }); let mut o = Vec::new(); for r in rows { o.extend_from_slice(r.2.as_bytes()); o.push(b'\n'); } o } /// A number as awk's print writes it: an integer whole, else %.6g. fn awk_num_text(v: f64) -> String { if v.fract() == 0.0 && v.abs() < 1e16 { format!("{}", v as i64) } else { let t = format!("{v:.5e}"); format!("{}", t.parse::().unwrap_or(v)) } } /// awk's NR at END over TEXT. pub fn awk_nr(text: &[u8]) -> usize { if text.is_empty() { return 0; } let n = text.iter().filter(|&&c| c == b'\n').count(); n + usize::from(text.last() != Some(&b'\n')) } /// The pins.tsv line of a chromosome from its HEAD response (carriage /// returns removed): chrN, the crc32c and the size, or `None` when either /// is missing. pub fn fine_pin_line(c: &str, head: &str) -> Option { let (mut h, mut n) = (String::new(), String::new()); for l in awk_records(head) { let f = awk_fields(l); let (k, v) = ( f.first().copied().unwrap_or(""), f.get(1).copied().unwrap_or(""), ); if k.to_lowercase() == "x-goog-hash:" && v.starts_with("crc32c=") { h = v.chars().skip(7).collect(); } if k.to_lowercase() == "content-length:" { n = v.to_owned(); } } (!h.is_empty() && !n.is_empty()).then(|| format!("{c}\t{h}\t{n}")) } /// awk -F'\t' 'NR > 1 && COND {print COLS}' over TEXT, COLS tab-joined. pub fn tsv_select(text: &str, cond: Option<(usize, &str)>, cols: &[usize]) -> String { let mut o = String::new(); for (i, l) in awk_records(text).into_iter().enumerate() { if i == 0 { continue; } let f: Vec<&str> = l.split('\t').collect(); let get = |k: usize| f.get(k - 1).copied().unwrap_or(""); if let Some((k, v)) = cond && !awk_eq(get(k), v) { continue; } let row: Vec<&str> = cols.iter().map(|&k| get(k)).collect(); o.push_str(&row.join("\t")); o.push('\n'); } o } /// `cut -f1,2`: the first two tab-separated fields of each line (a line /// without a tab whole). pub fn cut_12(text: &[u8]) -> Vec { let mut o = Vec::new(); let t = text.strip_suffix(b"\n").unwrap_or(text); if text.is_empty() { return o; } for l in t.split(|&c| c == b'\n') { let mut tabs = l .iter() .enumerate() .filter(|(_, c)| **c == b'\t') .map(|(i, _)| i); match (tabs.next(), tabs.next()) { (Some(_), Some(j)) => o.extend_from_slice(&l[..j]), _ => o.extend_from_slice(l), } o.push(b'\n'); } o } /// `awk '$1 == N {print $2}'` of a manifest: the second field of each line /// whose first is N, joined by newlines. pub fn field2_of(text: &str, name: &str) -> String { awk_records(text) .into_iter() .filter_map(|l| { let f = awk_fields(l); (f.first().is_some_and(|x| awk_eq(x, name))) .then(|| f.get(1).copied().unwrap_or("").to_owned()) }) .collect::>() .join("\n") } /// `awk '$1 == C'` (default FS) of TEXT: the whole lines. pub fn lines_where_first(text: &str, c: &str) -> String { let mut o = String::new(); for l in awk_records(text) { if awk_fields(l).first().is_some_and(|x| awk_eq(x, c)) { o.push_str(l); o.push('\n'); } } o } /// archaic_filterbed_sha: the sha256 versions.env pins for chromosome C in /// LIST ("CHROM:sha256 ..."). pub fn filterbed_sha(list: &str, c: &str) -> Option { list.split_whitespace() .find(|v| v.split(':').next() == Some(c)) .map(|v| v.split_once(':').map_or(v, |(_, h)| h).to_owned()) } /// The sha256 of a gzip file's content (consumer_sites_digest), read until /// the stream ends or breaks. pub fn gunzip_sha256(f: &Path) -> String { use sha2::{Digest, Sha256}; let mut h = Sha256::new(); if let Ok(file) = fs::File::open(f) { let mut d = flate2::read::MultiGzDecoder::new(std::io::BufReader::new(file)); let mut buf = vec![0u8; 1 << 20]; while let Ok(n) = d.read(&mut buf) { if n == 0 { break; } h.update(&buf[..n]); } } h.finalize().iter().map(|b| format!("{b:02x}")).collect() } /// `| gzip -c > FILE`: the host's gzip, as bash ran it, so the file holds /// the same bytes; false (after gzip's own message) when it failed. fn gzip_to(f: &Path, bytes: &[u8], err: &mut dyn Write) -> Step { let _ = err.flush(); let fail = |m: String, err: &mut dyn Write| { let _ = writeln!(err, "{m}"); 1u8 }; let file = fs::File::create(f) .map_err(|e| fail(format!("ERROR: cannot write {}: {e}", show(f)), err))?; let mut c = Command::new("gzip"); c.arg("-c").stdin(Stdio::piped()).stdout(file); let (mut child, ticket) = crate::child::spawn(&mut c) .map_err(|e| fail(format!("ERROR: cannot run gzip: {e}"), err))?; let fed = child .stdin .take() .is_some_and(|mut i| i.write_all(bytes).is_ok()); let ok = child.wait().is_ok_and(|s| s.success()); ticket.done(); if fed && ok { Ok(()) } else { Err(1) } } /// `gzip -dc FILE`, what it gives until it ends or breaks. fn gunzip(f: &Path) -> Vec { let mut o = Vec::new(); if let Ok(file) = fs::File::open(f) { let _ = flate2::read::MultiGzDecoder::new(std::io::BufReader::new(file)).read_to_end(&mut o); } o } fn text(f: &Path) -> String { fs::read(f) .map(|b| String::from_utf8_lossy(&b).into_owned()) .unwrap_or_default() } // --- --ancestry-panel ---------------------------------------------------------------- /// install_ancestry_panel: pgsc_calc's reference panel (PGSC_PANEL, or /// ANCESTRY_PANEL_NAME) and its common GRCh38 biallelic SNVs. pub fn ancestry_panel(r: &Run, out: &mut dyn Write, err: &mut dyn Write) -> Step { let name = r .vars .nonempty("ANCESTRY_PANEL_NAME") .map_or_else(|| val(r, "PGSC_PANEL"), str::to_owned); let dir = p(&format!("{}/reference/pgsc_calc", r.genome)); let panel = dir.join(format!("{name}.tar.zst")); let sites = dir.join(format!("{name}_GRCh38_sites.tsv")); if nonempty(&panel) && nonempty(&sites) { let _ = writeln!( out, "[OK] ancestry panel {name} (steps 25 and 26) already present." ); return Ok(()); } if !nonempty(&panel) { let _ = writeln!( out, "Downloading pgsc_calc's ancestry panel {name} (the 1000 Genomes panel is about 7 GB; an interrupted download resumes)..." ); } let url = source(r, "pgsc_ancestry_panel", None, "url", err)?; let md5s = source(r, "pgsc_ancestry_panel", None, "value", err)?; let url = format!( "{}/{name}.tar.zst", url.rsplit_once('/').map_or(url.as_str(), |(a, _)| a) ); if !nonempty(&panel) && !r.fetch(&url, &panel, "md5", &md5s, err) { return Err(warn( out, &format!( "[WARN] Could not download the ancestry panel; run: {} --ancestry-panel {}", r.script, r.genome ), )); } let _ = writeln!( out, " Listing the panel's common GRCh38 SNVs (plink2 on the panel's genotypes)..." ); let tmp = dir.join(format!(".{name}.sites.tmp")); rm_rf(&tmp, err); mkdirs(&[&tmp], err)?; let (pc, tc) = (cpath(r, &panel, err)?, cpath(r, &tmp, err)?); let unpack = [ val(r, "PGSC_ZSTD_IMAGE"), s("sh"), s("-c"), s(PGSC_UNPACK_SH), s("_"), pc, tc, ]; if !run_in(r, false, &[&dir], &unpack, To::Terminal, out, err)?.0 { rm_rf(&tmp, err); return Err(warn( out, &format!( "[WARN] Could not unpack the GRCh38 genotypes of {}; run: {} --ancestry-panel {}", show(&panel), r.script, r.genome ), )); } let prefix = fs::read_dir(&tmp) .into_iter() .flatten() .flatten() .map(|e| e.file_name().to_string_lossy().into_owned()) .find(|n| { n.starts_with("GRCh38_") && n.ends_with("_ALL.pgen") && n.len() >= "GRCh38__ALL.pgen".len() }) .map(|n| show(&tmp.join(n.strip_suffix(".pgen").unwrap_or(&n)))); let meminfo = fs::read_to_string("/proc/meminfo").ok(); let memsize = if meminfo.is_none() { crate::child::output( Command::new("sysctl") .args(["-n", "hw.memsize"]) .stdin(Stdio::null()) .stderr(Stdio::null()), ) .ok() .filter(|o| o.status.success()) .map(|o| String::from_utf8_lossy(&o.stdout).into_owned()) } else { None }; let mem = plink_mem_mb(meminfo.as_deref(), memsize.as_deref()); let mut ok = prefix.is_some(); let log = tmp.join("plink2.log"); if let Some(prefix) = &prefix { let prefix_c = cpath(r, &p(prefix), err)?; for c in 1..=22 { if !ok { break; } let outc = cpath(r, &tmp.join(format!("common_{c}")), err)?; let a = [ val(r, "PLINK2_IMAGE"), s("plink2"), s("--pfile"), prefix_c.clone(), s("vzs"), s("--chr"), c.to_string(), s("--allow-extra-chr"), s("--snps-only"), s("just-acgt"), s("--max-alleles"), s("2"), s("--maf"), s("0.05"), s("--make-just-pvar"), s("--threads"), threads(r), s("--memory"), mem.clone(), s("--out"), outc, ]; let ran = run_in(r, false, &[&dir], &a, To::Both(&log), out, err)?.0; if !ran && !text(&log).contains("No variants remaining") { let t = fs::read(&log).unwrap_or_default(); let mut n = 0; let mut head = Vec::new(); for b in t { if n == 40 { break; } head.push(b); if b == b'\n' { n += 1; } } let _ = out.write_all(&head); ok = false; } } } let part = p(&format!("{}.part", show(&sites))); let pvars = glob(&tmp, "common_", ".pvar"); let mut listed = ok && !pvars.is_empty(); if listed { let mut texts = Vec::new(); for f in &pvars { match fs::read(f) { Ok(b) => texts.push(String::from_utf8_lossy(&b).into_owned()), Err(_) => listed = false, } } let rows = ancestry_sites(&texts); listed = listed && write_file(&part, &rows, err).is_ok() && !rows.is_empty(); } if !listed { rm_rf(&tmp, err); rm_rf(&part, err); return Err(warn( out, &format!( "[WARN] Could not list the common GRCh38 SNVs of {}; run: {} --ancestry-panel {}", show(&panel), r.script, r.genome ), )); } rm_rf(&tmp, err); mv(&part, &sites, err)?; let _ = writeln!( out, "[OK] ancestry panel {name} (steps 25 and 26): {} ({} common GRCh38 SNVs in {name}_GRCh38_sites.tsv)", show(&panel), wc_l(&sites) ); Ok(()) } // --- --ancestry-fine-panel ----------------------------------------------------------- /// ancestry_fine_pins: one line per chromosome file of the panel (chrN, /// crc32c, size), from a HEAD request each, written to PINS as they come. fn fine_pins(r: &Run, pins: &Path, err: &mut dyn Write) -> bool { fine_pins_with(r, pins, std::time::Duration::from_secs(5), err) } /// The tries of each file's HEAD in ancestry_fine_pins. curl --retry asks /// again after a timeout or a 408, 429 or 5xx answer only; the bucket can /// also answer once without the crc32c or the size, or with another error. pub const FINE_PIN_TRIES: u32 = 3; /// fine_pins with PAUSE between two tries of a file (setup.sh's is 5 s). pub fn fine_pins_with( r: &Run, pins: &Path, pause: std::time::Duration, err: &mut dyn Write, ) -> bool { let mut lines = String::new(); let res = (|| -> Result<(), ()> { if fetch::on_path("curl").is_none() { let _ = writeln!( err, "ERROR: --ancestry-fine-panel needs curl to check the panel's files" ); return Err(()); } for c in 1..=22 { let part = c.to_string(); let u = source(r, "ancestry_fine_bcf", Some(&part), "url", err).map_err(|_| ())?; let mut line = None; for n in 1..=FINE_PIN_TRIES { // `line=$(curl | tr | awk) && break` under pipefail: a try // counts when curl and awk both succeed. let o = crate::child::output( Command::new("curl") .stdin(Stdio::null()) .args([ "-fsI", "--connect-timeout", "20", "--max-time", "60", "--retry", "3", "--retry-delay", "5", &u, ]) .stderr(Stdio::inherit()), ); line = o.ok().filter(|o| o.status.success()).and_then(|o| { let head = String::from_utf8_lossy(&o.stdout).replace('\r', ""); fine_pin_line(&format!("chr{c}"), &head) }); if line.is_some() { break; } if n < FINE_PIN_TRIES { std::thread::sleep(pause); } } let Some(l) = line else { let _ = writeln!( err, "ERROR: no crc32c or size for the panel's chr{c} file ({u})" ); return Err(()); }; lines.push_str(&l); lines.push('\n'); } Ok(()) })(); let wrote = fs::write(pins, lines.as_bytes()).is_ok(); res.is_ok() && wrote } /// install_fine_maps DIR CHROMS: the genetic map of each chromosome of /// CHROMS in DIR/maps, cut from the PLINK zip by og; maps/DONE written last. pub fn fine_maps( r: &Run, dir: &Path, chroms: &str, out: &mut dyn Write, err: &mut dyn Write, ) -> Step { let stamp = fine_maps_stamp(&val(r, "ANCESTRY_FINE_MAP_SHA256"), chroms); let maps = dir.join("maps"); let whole = chroms .split_whitespace() .all(|c| nonempty(&maps.join(format!("{c}.map")))); if whole && cat(&maps.join("DONE")) == stamp { return Ok(()); } rm_rf(&maps.join("DONE"), err); if !need_og(r, "unpacks the genetic map", out) { return Err(1); } let mut a = args(&["setup", "genetic-map", "--zip"]); a.push(show(&maps.join("plink.GRCh38.map.zip"))); a.push(s("--out")); a.push(show(&maps)); a.extend(chroms.split_whitespace().map(str::to_owned)); if !og_tool(r, &a, To::Terminal, out, err)?.0 { return Err(warn(out, "[WARN] Could not unpack the genetic map")); } echo_to(&maps.join("DONE"), &stamp, err) } /// install_ancestry_fine_panel: the reference of step 26b. pub fn ancestry_fine_panel(r: &Run, out: &mut dyn Write, err: &mut dyn Write) -> Step { let fine = val(r, "ANCESTRY_FINE_PANEL"); let dir = r.vars.nonempty("ANCESTRY_FINE_DIR").map_or_else( || p(&format!("{}/reference/ancestry_fine/{fine}", r.genome)), p, ); let regions = env(r, "ANCESTRY_FINE_REGIONS"); let exclude = env(r, "ANCESTRY_FINE_EXCLUDE"); let smap = env(r, "ANCESTRY_FINE_SAMPLE_MAP"); let thin = r .vars .nonempty("ANCESTRY_FINE_THIN") .unwrap_or("2kb") .to_owned(); let script = r.script.clone(); let g = r.genome.clone(); let retry = format!("run: {script} --ancestry-fine-panel {g}"); cpath(r, &dir, err)?; let chr22 = source(r, "ancestry_fine_bcf", Some("22"), "url", err)?; let folder = chr22 .rsplit_once('/') .map_or(chr22.as_str(), |(a, _)| a) .to_owned(); let _ = writeln!( out, "Installing the fine-grained ancestry panel {fine} (step 26b) in {}", show(&dir) ); let _ = writeln!( out, " Step 26b finds the fractions and paints the chromosomes with og." ); ensure( r, &["OG_IMAGE", "BCFTOOLS_HTTPS_IMAGE", "BEAGLE_IMAGE"], "26b", out, err, )?; if !need_og(r, "writes the panel's sample table", out) { return Err(1); } let (panel, maps, model) = (dir.join("panel"), dir.join("maps"), dir.join("model")); mkdirs(&[&panel, &maps, &model], err)?; let _ = writeln!( out, " Checking the panel's files against ANCESTRY_FINE_PANEL_SHA256..." ); let pins = dir.join("pins.tsv"); let _ = out.flush(); if !fine_pins(r, &pins, err) { return Err(warn( out, &format!("[WARN] Could not read the panel's files at {folder}; {retry}"), )); } let pins_sha = val(r, "ANCESTRY_FINE_PANEL_SHA256"); if sha256(&pins) != pins_sha { let _ = writeln!( out, "[WARN] The panel's files at {folder} are not the ones ANCESTRY_FINE_PANEL_SHA256 pins (see {}).", show(&pins) ); let _ = writeln!( out, " The bucket replaced a file: read what changed before moving the pin in versions.env." ); return Err(1); } let downloads = [ ( ANCESTRY_FINE_META_URL, dir.join("meta.tsv"), val(r, "ANCESTRY_FINE_META_SHA256"), "", ), ( ANCESTRY_FINE_MAP_URL, maps.join("plink.GRCh38.map.zip"), val(r, "ANCESTRY_FINE_MAP_SHA256"), ANCESTRY_FINE_MAP_MIRROR_URL, ), ]; for (url, dest, sha, mirror) in &downloads { if has_sha(dest, sha) || r.fetch(url, dest, "sha256", sha, err) { continue; } if !mirror.is_empty() { rm_rf(&p(&format!("{}.part", show(dest))), err); let _ = writeln!( out, " Trying the mirror of {}: {mirror}", url.rsplit('/').next().unwrap_or(url) ); if r.fetch(mirror, dest, "sha256", sha, err) { continue; } } return Err(warn( out, &format!("[WARN] Could not download {url}; {retry}"), )); } let bed = dir.join("regions.bed"); let (rstamp, chroms) = if regions.is_empty() { rm_rf(&bed, err); (String::new(), all_chroms(true)) } else { if !nonempty(&p(®ions)) { return Err(warn( out, &format!("[WARN] ANCESTRY_FINE_REGIONS={regions} is not a file"), )); } cp(&p(®ions), &bed, err)?; (sha256(&bed), regions_chroms(&text(&bed), true)) }; // samples.tsv: from the metadata, or the table given. let samples_part = dir.join("bcf_samples.txt.part"); let q = [ val(r, "BCFTOOLS_HTTPS_IMAGE"), s("sh"), s("-c"), s(FINE_SAMPLES_SH), s("_"), chr22.clone(), ]; if !run_in(r, true, &[&dir], &q, To::File(&samples_part), out, err)?.0 || !nonempty(&samples_part) { rm_rf(&samples_part, err); return Err(warn( out, &format!("[WARN] Could not read the panel's sample list; {retry}"), )); } mv(&samples_part, &dir.join("bcf_samples.txt"), err)?; let table_part = dir.join("samples.tsv.part"); if !smap.is_empty() { let first = text(&p(&smap)); let first = first.split('\n').next().unwrap_or(""); let header_ok = fs::metadata(&smap).is_ok() && first == "sample\tpopulation\tcontinent\tregion\treference\tpaint"; if !header_ok { return Err(warn( out, &format!( "[WARN] ANCESTRY_FINE_SAMPLE_MAP={smap} does not start with the header of samples.tsv" ), )); } cp(&p(&smap), &table_part, err)?; let a = vec![ s("ancestry-fine"), s("check-map"), s("--map"), show(&table_part), ]; if !og_tool(r, &a, To::Terminal, out, err)?.0 { rm_rf(&table_part, err); return Err(warn( out, &format!("[WARN] ANCESTRY_FINE_SAMPLE_MAP={smap} has a group too small to model"), )); } } else { let a = vec![ s("ancestry-fine"), s("panel-map"), s("--meta"), show(&dir.join("meta.tsv")), s("--bcf-samples"), show(&dir.join("bcf_samples.txt")), s("--exclude"), exclude.clone(), s("--paint-per-group"), r.vars .nonempty("ANCESTRY_FINE_PAINT_PER_GROUP") .unwrap_or("200") .to_owned(), s("--out"), show(&table_part), ]; if !og_tool(r, &a, To::Terminal, out, err)?.0 { rm_rf(&table_part, err); return Err(warn(out, "[WARN] Could not write the panel's sample table")); } } let samples = dir.join("samples.tsv"); mv(&table_part, &samples, err)?; let keep = panel.join("keep.txt"); write_file( &keep, tsv_select(&text(&samples), None, &[1]).as_bytes(), err, )?; // panel/: redone when the pins, the regions or the people kept change. let pstamp = fine_panel_stamp( &pins_sha, &rstamp, &thin, &sha256(&keep), &val(r, "BCFTOOLS_HTTPS_IMAGE"), ); if cat(&panel.join("DONE")) != pstamp { rm_rf(&panel.join("DONE"), err); rm_rf(&model.join("DONE"), err); let pins_text = text(&pins); for c in chroms.split_whitespace() { let tbi = panel.join(format!("{c}.vcf.gz.tbi")); if nonempty(&tbi) && cat(&panel.join(format!("{c}.stamp"))) == pstamp { continue; } let n = c.strip_prefix("chr").unwrap_or(c); let mut src = source(r, "ancestry_fine_bcf", Some(n), "url", err)?; let mut net = true; let mut bcf = None; if rstamp.is_empty() { let b = p(&source(r, "ancestry_fine_bcf", Some(n), "path", err)?); let crc = tsv_where(&pins_text, c); if !r.fetch(&src, &b, "crc32c", &crc, err) { return Err(warn( out, &format!("[WARN] Could not download {c} of the panel; {retry}"), )); } src = cpath(r, &b, err)?; net = false; bcf = Some(b); } let _ = writeln!(out, " {c}: reading the panel's common SNVs..."); let bed_c = if rstamp.is_empty() { String::new() } else { cpath(r, &bed, err)? }; let a = [ val(r, "BCFTOOLS_HTTPS_IMAGE"), s("bash"), s("-euo"), s("pipefail"), s("-c"), s(FINE_PANEL_SH), s("_"), src, cpath(r, &keep, err)?, cpath(r, &panel.join(format!("{c}.vcf.gz")), err)?, bed_c, thin.clone(), ]; if !run_in(r, net, &[&dir], &a, To::Terminal, out, err)?.0 { return Err(warn( out, &format!("[WARN] Could not read {c} of the panel; {retry}"), )); } echo_to(&panel.join(format!("{c}.stamp")), &pstamp, err)?; if let Some(b) = &bcf { done_with(r, &[b], out, err); } } // sites.tsv and positions.tsv. let part = panel.join("sites.tsv.part"); let a = [ val(r, "BCFTOOLS_IMAGE"), s("bash"), s("-euo"), s("pipefail"), s("-c"), s(FINE_SITES_SH), s("_"), cpath(r, &panel, err)?, chroms.clone(), ]; if !run_in(r, false, &[&dir], &a, To::File(&part), out, err)?.0 || !nonempty(&part) { return Err(warn(out, "[WARN] Could not list the panel's sites")); } write_file( &panel.join("positions.tsv"), &cut_12(&fs::read(&part).unwrap_or_default()), err, )?; mv(&part, &panel.join("sites.tsv"), err)?; echo_to(&panel.join("DONE"), &pstamp, err)?; } let _ = writeln!( out, " panel: {} SNVs of {} people", wc_l(&panel.join("sites.tsv")), wc_l(&keep) ); fine_maps(r, &dir, &chroms, out, err)?; // model/: redone when samples.tsv or the panel changes. let mstamp = fine_model_stamp(&sha256(&panel.join("sites.tsv")), &sha256(&samples)); if cat(&model.join("DONE")) != mstamp { let tmp = model.join("tmp"); rm_rf(&tmp, err); rm_rf(&model.join("DONE"), err); mkdirs(&[&tmp], err)?; let reft = tmp.join("ref.txt"); let st = text(&samples); write_file(&reft, tsv_select(&st, Some((5, "1")), &[1]).as_bytes(), err)?; let _ = writeln!( out, " model: LD pruning on {} reference individuals, then each group's allele frequencies...", wc_l(&reft) ); let a = [ val(r, "BCFTOOLS_IMAGE"), s("bash"), s("-euo"), s("pipefail"), s("-c"), s(FINE_MODEL_SH), s("_"), cpath(r, &panel, err)?, cpath(r, &reft, err)?, cpath(r, &tmp, err)?, chroms.clone(), ]; let mut fit = None; if run_in(r, false, &[&dir], &a, To::Terminal, out, err)?.0 { let f = vec![ s("ancestry-fine"), s("freqs"), s("--vcf"), show(&tmp.join("adm.vcf.gz")), s("--samples"), show(&samples), s("--out"), show(&tmp), ]; let (ok, got) = og_tool(r, &f, To::Capture, out, err)?; if ok { fit = Some( String::from_utf8_lossy(&got) .trim_end_matches('\n') .to_owned(), ); } } let Some(fit) = fit else { return Err(warn( out, "[WARN] Could not count the reference groups' allele frequencies", )); }; let _ = writeln!(out, " model: {fit}"); write_file( &tmp.join("paint_map.tsv"), tsv_select(&st, Some((6, "1")), &[1, 3]).as_bytes(), err, )?; for e in [ "ref.bim", "ref.fam", "ref.geno", "continent.P", "region.P", "levels.tsv", "paint_map.tsv", ] { mv(&tmp.join(e), &model.join(e), err)?; } rm_rf(&tmp, err); rm_rf(&model.join("ref.bed"), err); echo_to(&model.join("DONE"), &mstamp, err)?; } let _ = writeln!( out, "[OK] fine-grained ancestry panel {fine} (step 26b): {} ({} SNVs in the model, {} painting references)", show(&dir), wc_l(&model.join("ref.bim")), wc_l(&model.join("paint_map.tsv")) ); Ok(()) } /// `awk -F'\t' -v c=C '$1 == c {print $2}'`, joined by newlines. fn tsv_where(text: &str, c: &str) -> String { awk_records(text) .into_iter() .filter_map(|l| { let f: Vec<&str> = l.split('\t').collect(); awk_eq(f[0], c).then(|| f.get(1).copied().unwrap_or("").to_owned()) }) .collect::>() .join("\n") } // --- --mocha-data -------------------------------------------------------------------- /// install_mocha_data: MoChA's phasing panel for step 51. pub fn mocha_data(r: &Run, out: &mut dyn Write, err: &mut dyn Write) -> Step { let version = val(r, "MOCHA_PANEL_VERSION"); let dir = r .vars .nonempty("MOCHA_DATA") .map_or_else(|| p(&format!("{}/reference/mocha-{version}", r.genome)), p); let regions = env(r, "MOCHA_REGIONS"); let retry = format!("run: {} --mocha-data {}", r.script, r.genome); cpath(r, &dir, err)?; let _ = writeln!( out, "Installing MoChA's phasing panel {version} (step 51) in {}", show(&dir) ); ensure(r, &["MOCHA_IMAGE", "BEAGLE_IMAGE"], "51", out, err)?; let raw = dl(r, &format!("mocha-{version}")); let (panel, maps) = (dir.join("panel"), dir.join("maps")); mkdirs(&[&panel, &maps, &raw], err)?; let old = dir.join("raw"); for x in glob(&old, "", "").into_iter().filter(|x| x.exists()) { let n = x.file_name().map(|n| n.to_owned()).unwrap_or_default(); adopt(r, &x, &raw.join(n), None, out, err); } let _ = fs::remove_dir(&old); let manifest = dir.join("manifest.txt"); let msha = val(r, "MOCHA_PANEL_MANIFEST_SHA256"); if !has_sha(&manifest, &msha) && !r.fetch( &format!("{}/20220804_manifest.txt", val(r, "MOCHA_PANEL_URL")), &manifest, "sha256", &msha, err, ) { return Err(warn( out, &format!( "[WARN] Could not read the panel's manifest ({}); {retry}", val(r, "MOCHA_PANEL_URL") ), )); } let bed = dir.join("regions.bed"); let (rstamp, chroms) = if regions.is_empty() { rm_rf(&bed, err); (s("all"), all_chroms(true)) } else { if !nonempty(&p(®ions)) { return Err(warn( out, &format!("[WARN] MOCHA_REGIONS={regions} is not a file"), )); } cp(&p(®ions), &bed, err)?; (sha256(&bed), regions_chroms(&text(&bed), true)) }; let stamp = mocha_stamp(&msha, &rstamp, &val(r, "MOCHA_IMAGE")); if cat(&dir.join("DONE")) == stamp { let _ = writeln!( out, "[OK] MoChA's phasing panel (step 51) already installed: {}", show(&dir) ); return Ok(()); } rm_rf(&dir.join("DONE"), err); let mtext = text(&manifest); for c in chroms.split_whitespace() { if nonempty(&panel.join(format!("{c}.vcf.gz.tbi"))) && panel.join(format!("{c}.cnp.bed")).exists() && cat(&panel.join(format!("{c}.stamp"))) == stamp { continue; } let n = c.strip_prefix("chr").unwrap_or(c); let f = source(r, "mocha_panel", Some(n), "path", err)?; let f = f.rsplit('/').next().unwrap_or(&f).to_owned(); for e in ["", ".tbi"] { let row = if e.is_empty() { "mocha_panel" } else { "mocha_panel_index" }; let url = source(r, row, Some(n), "url", err)?; let md5 = field2_of(&mtext, &format!("{f}{e}")); if md5.is_empty() { return Err(warn( out, &format!("[WARN] {f}{e} is not in the panel's manifest"), )); } let dest = raw.join(format!("{f}{e}")); if has_md5(&dest, &md5) { continue; } if !r.fetch(&url, &dest, "md5", &md5, err) { return Err(warn( out, &format!("[WARN] Could not download {f}{e}; {retry}"), )); } } let _ = writeln!( out, " {c}: the biallelic SNVs seen twice or more, genotypes only, and the common CNVs..." ); let bed_c = if regions.is_empty() { String::new() } else { cpath(r, &bed, err)? }; let a = [ val(r, "MOCHA_IMAGE"), s("bash"), s("-euo"), s("pipefail"), s("-c"), s(MOCHA_CUT_SH), s("_"), cpath(r, &raw.join(&f), err)?, cpath(r, &panel.join(format!("{c}.vcf.gz")), err)?, bed_c, cpath(r, &panel.join(format!("{c}.cnp.bed")), err)?, ]; if !run_in(r, false, &[&dir], &a, To::Terminal, out, err)?.0 { return Err(warn(out, &format!("[WARN] Could not cut {c} of the panel"))); } echo_to(&panel.join(format!("{c}.stamp")), &stamp, err)?; done_with(r, &[&raw.join(&f), &raw.join(format!("{f}.tbi"))], out, err); } // The genetic map: the PLINK GRCh38 map of step 26b, from its host or the mirror. let map = maps.join("plink.GRCh38.map.zip"); let msha2 = val(r, "ANCESTRY_FINE_MAP_SHA256"); if !has_sha(&map, &msha2) && !r.fetch(ANCESTRY_FINE_MAP_URL, &map, "sha256", &msha2, err) { rm_rf(&p(&format!("{}.part", show(&map))), err); let _ = writeln!(out, " Trying the mirror: {ANCESTRY_FINE_MAP_MIRROR_URL}"); if !r.fetch(ANCESTRY_FINE_MAP_MIRROR_URL, &map, "sha256", &msha2, err) { return Err(warn( out, &format!("[WARN] Could not download the genetic map; {retry}"), )); } } if !need_og(r, "unpacks the genetic map", out) { return Err(1); } let mut a = args(&["setup", "genetic-map", "--zip"]); a.push(show(&map)); a.push(s("--out")); a.push(show(&maps)); a.extend(chroms.split_whitespace().map(str::to_owned)); if !og_tool(r, &a, To::Terminal, out, err)?.0 { return Err(warn(out, "[WARN] Could not unpack the genetic map")); } // for c in $chroms; do cat panel/c.cnp.bed; done > cnps.bed.part && mv let mut cnps = Vec::new(); let mut last_ok = true; for c in chroms.split_whitespace() { let f = panel.join(format!("{c}.cnp.bed")); match fs::read(&f) { Ok(b) => { cnps.extend_from_slice(&b); last_ok = true; } Err(e) => { let _ = writeln!(err, "cat: {}: {e}", show(&f)); last_ok = false; } } } let cnps_part = dir.join("cnps.bed.part"); if write_file(&cnps_part, &cnps, err).is_ok() && last_ok { mv(&cnps_part, &dir.join("cnps.bed"), err)?; } echo_to(&dir.join("DONE"), &stamp, err)?; let du = crate::child::output( Command::new("du") .args(["-sh"]) .arg(&dir) .stdin(Stdio::null()) .stderr(Stdio::null()), ) .map(|o| { String::from_utf8_lossy(&o.stdout) .split(['\t', '\n']) .next() .unwrap_or("") .to_owned() }) .unwrap_or_default(); let _ = writeln!( out, "[OK] MoChA's phasing panel (step 51, {}): {} ({du}, {} common CNVs)", trim1(&chroms), show(&dir), wc_l(&dir.join("cnps.bed")) ); Ok(()) } // --- --ancient-panel ----------------------------------------------------------------- /// install_ancient_panel: the panel of step 44 from the AADR's 1240K files. pub fn ancient_panel(r: &Run, out: &mut dyn Write, err: &mut dyn Write) -> Step { let v = val(r, "AADR_VERSION"); let src = env(r, "ANCIENT_SOURCE_DIR"); let base = p(&format!("{}/reference/ancient", r.genome)); let dir = base.join(format!("aadr_{v}")); let part = base.join(format!(".aadr_{v}.part")); let old = base.join(format!("raw_{v}")); let mut chain = p(&format!( "{}/reference/liftover/hg19ToHg38.over.chain.gz", r.genome )); let retry = format!("run: {} --ancient-panel {}", r.script, r.genome); if nonempty(&dir.join("DONE")) { let _ = writeln!( out, "[OK] ancient populations panel AADR {v} (step 44) already present: {}", show(&dir) ); return Ok(()); } let fasta = r.vars.get("REF_FASTA").unwrap_or("").to_owned(); for f in [fasta.clone(), format!("{fasta}.fai")] { if !nonempty(&p(&f)) { return Err(warn( out, &format!( "[WARN] {f} is missing: install the reference first ({} {}).", r.script, r.genome ), )); } } let chain_env = env(r, "ANCIENT_CHAIN"); if chain_env.is_empty() && !nonempty(&chain) { let _ = writeln!( out, " {} See docs/44-ancient.md.", crate::components::UCSC_CHAIN_TERMS ); } let _ = writeln!( out, "Installing the ancient populations panel, AADR {v} 1240K (step 44) in {}", show(&dir) ); ensure(r, &["EIGENSOFT_IMAGE"], "44", out, err)?; if !need_og( r, "chooses the ancient panel's people and places its sites", out, ) { return Err(1); } let raw = if src.is_empty() { dl(r, &format!("aadr-{v}")) } else { old.clone() }; mkdirs(&[&raw], err)?; for e in ["anno", "ind", "snp", "geno"] { let f = raw.join(format!("aadr.{e}")); if !src.is_empty() { let first = glob(&p(&src), "", &format!(".{e}")).into_iter().next(); if first.is_none_or(|x| cp_file(&x, &f).is_err()) { return Err(warn( out, &format!("[WARN] ANCIENT_SOURCE_DIR={src} has no .{e} file."), )); } continue; } let up = e.to_uppercase(); let url = format!( "https://dataverse.harvard.edu/api/access/datafile/{}", val(r, &format!("AADR_{up}_ID")) ); let md5 = val(r, &format!("AADR_{up}_MD5")); let was = old.join(format!("aadr.{e}")); if has_md5(&was, &md5) { adopt( r, &was, &f, Some(&keep::Check { url: &url, sum: Some(("md5", &md5)), }), out, err, ); } if e == "geno" { let _ = writeln!( out, " Downloading the AADR genotypes (7.1 GB; an interrupted download resumes)..." ); } if !r.fetch(&url, &f, "md5", &md5, err) { return Err(warn( out, &format!( "[WARN] Could not download the AADR {v} .{e} file; run: {} --ancient-panel {}", r.script, r.genome ), )); } } if !chain_env.is_empty() { chain = p(&chain_env); } else if !r.fetch( HG19_TO_HG38_CHAIN_URL, &chain, "sha256", &val(r, "HG19_TO_HG38_CHAIN_SHA256"), err, ) { return Err(warn( out, &format!( "[WARN] Could not download UCSC's hg19ToHg38 chain; run: {} --ancient-panel {}", r.script, r.genome ), )); } rm_rf(&part, err); mkdirs(&[&part], err)?; let (pc, rc) = (cpath(r, &part, err)?, cpath(r, &raw, err)?); if cpath(r, &chain, err).is_err() { return Err(warn( out, &format!( "[WARN] the chain file {} must be inside GENOME_DIR.", show(&chain) ), )); } let _ = writeln!( out, " [1/5] Choosing the present-day reference people and the ancient people to project..." ); let _ = writeln!(out, " [2/5] Placing the 1240K sites on GRCh38..."); let rawh = |n: &str| show(&raw.join(n)); let parth = |n: &str| show(&part.join(n)); let select = vec![ s("ancient"), s("select"), s("--anno"), rawh("aadr.anno"), s("--ind"), rawh("aadr.ind"), s("--out-ind"), parth("panel.ind"), s("--poplist"), parth("poplist.txt"), s("--ancients"), parth("ancients.tsv"), ]; let lift = vec![ s("ancient"), s("lift"), s("--snp"), rawh("aadr.snp"), s("--chain"), show(&chain), s("--fasta"), fasta.clone(), s("--out"), parth("sites_grch38.tsv"), ]; if !og_tool(r, &select, To::Terminal, out, err)?.0 || !og_tool(r, &lift, To::Terminal, out, err)?.0 { return Err(warn( out, "[WARN] Could not choose the panel's people or place its sites (the lines above say why).", )); } let t = threads(r); write_file( &part.join("convertf.par"), convertf_par(&rc, &pc).as_bytes(), err, )?; write_file( &part.join("panel.par"), smartpca_par( &format!("{rc}/aadr.geno"), &format!("{rc}/aadr.snp"), &format!("{pc}/panel.ind"), &format!("{pc}/poplist.txt"), &format!("{pc}/panel"), &t, ) .as_bytes(), err, )?; write_file( &part.join("check.par"), smartpca_par( &format!("{pc}/moderns.geno"), &format!("{pc}/moderns.snp"), &format!("{pc}/moderns.ind"), &format!("{pc}/poplist.txt"), &format!("{pc}/check"), &t, ) .as_bytes(), err, )?; let _ = writeln!( out, " [3/5] The present-day people in EIGENSTRAT format (convertf)..." ); let _ = writeln!( out, " [4/5] The axes, with the ancient people projected (smartpca, lsqproject)..." ); let _ = writeln!( out, " [5/5] The same axes again from the present-day people alone, as step 44 runs..." ); let a = [ s("--cpus"), t.clone(), s("--memory"), s("12g"), val(r, "EIGENSOFT_IMAGE"), s("sh"), s("-euc"), s(ANCIENT_EIGENSOFT_SH), s("_"), pc.clone(), ]; if !run_in(r, false, &[&part], &a, To::Terminal, out, err)?.0 { tail("20", &glob(&part, "", ".log"), out); return Err(warn( out, &format!( "[WARN] EIGENSOFT failed on the AADR files (logs in {}); {retry}", show(&part) ), )); } let align = vec![ s("ancient"), s("align"), s("--panel-evec"), parth("panel.evec"), s("--run-evec"), parth("check.evec"), ]; if !og_tool(r, &align, To::Terminal, out, err)?.0 { return Err(warn( out, &format!( "[WARN] The two smartpca runs on the same present-day people gave different axes (logs in {}).", show(&part) ), )); } rm_rf(&part.join("check.evec"), err); rm_rf(&part.join("check.eval"), err); let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0); write_file( &part.join("DONE"), ancient_done(&v, lines_of(&part.join("sites_grch38.tsv")), &utc_day(now)).as_bytes(), err, )?; rm_rf(&dir, err); mv(&part, &dir, err)?; rm_rf(&old, err); if src.is_empty() { done_with(r, &[&raw], out, err); } let _ = writeln!( out, "[OK] ancient populations panel AADR {v} (step 44): {} ({} present-day people, {} ancient people)", show(&dir), wc_l(&dir.join("moderns.ind")), lines_of(&dir.join("ancients.tsv")) - 1 ); Ok(()) } // --- --archaic ----------------------------------------------------------------------- /// install_archaic: the table of step 43. pub fn archaic(r: &Run, out: &mut dyn Write, err: &mut dyn Write) -> Step { let version = val(r, "ARCHAIC_DATA_VERSION"); let dir = r.vars.nonempty("ARCHAIC_DIR").map_or_else( || p(&format!("{}/reference/archaic/{version}", r.genome)), p, ); let regions = env(r, "ARCHAIC_REGIONS"); let genomes = [ ("Altai", "Altai"), ("Vindija33.19", "Vindija"), ("Denisova", "Denisova"), ]; let retry = format!("run: {} --archaic {}", r.script, r.genome); cpath(r, &dir, err)?; let chain = dir.join("hg19ToHg38.over.chain.gz"); let chain_sha = val(r, "ARCHAIC_CHAIN_SHA256"); if !has_sha(&chain, &chain_sha) { let _ = writeln!( out, " {} See docs/43-archaic.md.", crate::components::UCSC_CHAIN_TERMS ); } let _ = writeln!( out, "Installing the archaic data {version} (step 43) in {}", show(&dir) ); ensure( r, &["BCFTOOLS_IMAGE", "PICARD_IMAGE", "OG_IMAGE", "IBDMIX_IMAGE"], "43", out, err, )?; if !need_og(r, "builds the archaic table", out) { return Err(1); } let dict = ref_dict(r.vars.get("REF_FASTA").unwrap_or("")); if !nonempty(&p(&dict)) { return Err(warn( out, &format!( "[WARN] {dict} is missing: run {} {} first (it writes the sequence dictionary)", r.script, r.genome ), )); } let adl = dl(r, &format!("archaic-{version}")); let (md5, mask, exclude) = (dir.join("md5"), dir.join("mask"), dir.join("exclude")); mkdirs(&[&md5, &adl, &dir.join("work"), &mask, &exclude], err)?; let old = dir.join("download"); for x in glob(&old, "", "").into_iter().filter(|x| x.exists()) { let n = x.file_name().map(|n| n.to_owned()).unwrap_or_default(); adopt(r, &x, &adl.join(n), None, out, err); } let _ = fs::remove_dir(&old); for (g, k) in [ ("Altai", "ARCHAIC_ALTAI_MD5SUMS_SHA256"), ("Vindija33.19", "ARCHAIC_VINDIJA_MD5SUMS_SHA256"), ("Denisova", "ARCHAIC_DENISOVA_MD5SUMS_SHA256"), ] { let f = md5.join(format!("{g}.txt")); let k = val(r, k); if has_sha(&f, &k) { continue; } if !r.fetch( &format!("{ARCHAIC_URL}/{g}/md5sums.txt"), &f, "sha256", &k, err, ) { return Err(warn( out, &format!( "[WARN] The md5 list of {g} at {ARCHAIC_URL}/{g}/ is not the one versions.env pins: read what changed before moving the pin." ), )); } } if !has_sha(&chain, &chain_sha) && !r.fetch(ARCHAIC_CHAIN_URL, &chain, "sha256", &chain_sha, err) { return Err(warn( out, &format!("[WARN] Could not download UCSC's hg19ToHg38 chain; {retry}"), )); } let strict = dir.join("strict_GRCh38.bed"); let strict_sha = val(r, "ARCHAIC_STRICT_MASK_SHA256"); if !has_sha(&strict, &strict_sha) && !r.fetch(ARCHAIC_STRICT_MASK_URL, &strict, "sha256", &strict_sha, err) { return Err(warn( out, &format!("[WARN] Could not download the 1000 Genomes GRCh38 strict mask; {retry}"), )); } let segdups = dir.join("segdups_hg19.txt.gz"); let seg_sha = val(r, "ARCHAIC_SEGDUPS_SHA256"); if !has_sha(&segdups, &seg_sha) && !r.fetch(ARCHAIC_SEGDUPS_URL, &segdups, "sha256", &seg_sha, err) { return Err(warn( out, &format!("[WARN] Could not download UCSC's segmental duplications; {retry}"), )); } let bed = dir.join("regions.bed"); let (rstamp, chroms) = if regions.is_empty() { rm_rf(&bed, err); (s("all"), all_chroms(false)) } else { if !nonempty(&p(®ions)) { return Err(warn( out, &format!("[WARN] ARCHAIC_REGIONS={regions} is not a file"), )); } cp(&p(®ions), &bed, err)?; (sha256(&bed), regions_chroms(&text(&bed), false)) }; if chroms.trim().is_empty() { return Err(warn( out, &format!("[WARN] ARCHAIC_REGIONS={regions} names no autosome (1 to 22)"), )); } let masks = archaic_masks([ &strict_sha, &seg_sha, &val(r, "ARCHAIC_FILTERBED_SHA256_ALTAI"), &val(r, "ARCHAIC_FILTERBED_SHA256_VINDIJA"), &val(r, "ARCHAIC_FILTERBED_SHA256_DENISOVA"), ]); let stamp = archaic_stamp( &version, &rstamp, &val(r, "BCFTOOLS_IMAGE"), &val(r, "PICARD_IMAGE"), &masks, ARCHAIC_TABLE_FORMAT, ); let legacy = archaic_legacy(&stamp); let have = chroms .split_whitespace() .all(|c| nonempty(&dir.join(format!("chr{c}.tsv.gz")))); let mut stamps = vec![dir.join("DONE")]; stamps.extend(glob(&dir, "chr", ".stamp")); for f in &stamps { if cat(f) == legacy { echo_to(f, &stamp, err)?; } } if have && cat(&dir.join("DONE")) == stamp { let _ = writeln!(out, "[OK] archaic data {version} (step 43): {}", show(&dir)); return Ok(()); } rm_rf(&dir.join("DONE"), err); let sites = adl.join("1kg_sites.vcf.gz"); let sites_tbi = p(&format!("{}.tbi", show(&sites))); let bcftools = val(r, "BCFTOOLS_IMAGE"); for c in chroms.split_whitespace() { let table = dir.join(format!("chr{c}.tsv.gz")); let cstamp = dir.join(format!("chr{c}.stamp")); if nonempty(&table) && cat(&cstamp) == stamp { continue; } if !nonempty(&sites_tbi) { let md5k = val(r, "ARCHAIC_1KG_SITES_MD5"); if !has_md5(&sites, &md5k) && !r.fetch(ARCHAIC_1KG_SITES_URL, &sites, "md5", &md5k, err) { return Err(warn( out, &format!("[WARN] Could not download the 1000 Genomes sites file; {retry}"), )); } let a = [ bcftools.clone(), s("bcftools"), s("index"), s("-t"), s("-f"), cpath(r, &sites, err)?, ]; if !run_in(r, false, &[&adl], &a, To::Terminal, out, err)?.0 { return Err(warn( out, &format!("[WARN] Could not index {}", show(&sites)), )); } } let wk = dir.join("work").join(c); rm_rf(&wk, err); mkdirs(&[&wk], err)?; let wbed = wk.join("regions.bed"); if !regions.is_empty() { write_file(&wbed, lines_where_first(&text(&bed), c).as_bytes(), err)?; } let _ = writeln!( out, " chr{c}: the 1000 Genomes SNVs and their frequencies..." ); let a = [ bcftools.clone(), s("bash"), s("-euo"), s("pipefail"), s("-c"), s(ARCHAIC_MODERN_SH), s("_"), cpath(r, &sites, err)?, s(c), cpath(r, &wk, err)?, cpath(r, &wbed, err)?, ]; if !run_in(r, false, &[&dir], &a, To::Terminal, out, err)?.0 { return Err(warn( out, &format!("[WARN] Could not read chr{c} of the 1000 Genomes sites"), )); } let ex = archaic_exclude( &String::from_utf8_lossy(&gunzip(&segdups)), &text(&wk.join("indels.tsv")), c, ); let exf = exclude.join(format!("chr{c}.bed.gz")); gzip_to(&exf, &ex, err)?; let n = awk_nr(&gunzip(&exf)); if n < 100 { return Err(warn( out, &format!( "[WARN] the exclusion list of chr{c} has {n} regions: the segmental duplications or the 1000 Genomes indels did not arrive" ), )); } let _ = writeln!( out, " chr{c}: {n} excluded regions (segmental duplications and indel neighbourhoods)" ); for (g, name) in genomes { let f = adl.join(format!("{g}.chr{c}.vcf.gz")); let list = format!("file://{}", show(&md5.join(format!("{g}.txt")))); if !r.fetch( &format!("{ARCHAIC_URL}/{g}/chr{c}_mq25_mapab100.vcf.gz"), &f, "md5", &list, err, ) { return Err(warn( out, &format!( "[WARN] Could not download chr{c} of {g}; run: {} --archaic {} (it resumes)", r.script, r.genome ), )); } let list_var = format!("ARCHAIC_FILTERBED_SHA256_{}", name.to_uppercase()); let Some(k) = filterbed_sha(&val(r, &list_var), c) else { let _ = writeln!( err, "ERROR: versions.env pins no FilterBed sha256 for {name} chromosome {c}" ); return Err(1); }; let m = mask.join(format!("{g}.chr{c}.bed.gz")); if !has_sha(&m, &k) && !r.fetch( &format!("{ARCHAIC_FILTERBED_URL}/{g}/chr{c}_mask.bed.gz"), &m, "sha256", &k, err, ) { return Err(warn( out, &format!( "[WARN] Could not download the FilterBed of chr{c} of {g}; run: {} --archaic {} (it resumes)", r.script, r.genome ), )); } } let _ = writeln!( out, " chr{c}: the archaic genotypes at those SNVs and at every archaic non-reference site..." ); let a = [ bcftools.clone(), s("bash"), s("-euo"), s("pipefail"), s("-c"), s(ARCHAIC_GENOTYPES_SH), s("_"), cpath(r, &adl, err)?, s(c), cpath(r, &wk, err)?, cpath(r, &wbed, err)?, ]; if !run_in(r, false, &[&dir], &a, To::Terminal, out, err)?.0 { return Err(warn( out, &format!("[WARN] Could not read the archaic genotypes of chr{c}"), )); } let wh = |n: &str| show(&wk.join(n)); let mut t = vec![ s("archaic"), s("table"), s("--chrom"), s(c), s("--modern"), wh("modern.tsv"), ]; for (g, name) in genomes { t.push(s("--archaic")); t.push(format!("{name}={}", wh(&format!("{g}.tsv")))); } for (g, name) in genomes { t.push(s("--mask")); t.push(format!( "{name}={}", show(&mask.join(format!("{g}.chr{c}.bed.gz"))) )); } t.extend([s("--exclude"), show(&exf), s("--out"), wh("hg19.vcf")]); if !og_tool(r, &t, To::Terminal, out, err)?.0 { return Err(warn(out, &format!("[WARN] Could not merge chr{c}"))); } let _ = writeln!( out, " chr{c}: lifting to GRCh38 (Picard LiftoverVcf, UCSC's chain)..." ); let log = wk.join("liftover.log"); let a = [ s("--cpus"), s("2"), s("--memory"), s("10g"), val(r, "PICARD_IMAGE"), s("java"), s("-Xmx8g"), s("-jar"), s("/usr/picard/picard.jar"), s("LiftoverVcf"), format!("I={}", cpath(r, &wk.join("hg19.vcf"), err)?), format!("O={}", cpath(r, &wk.join("hg38.vcf"), err)?), format!("CHAIN={}", cpath(r, &chain, err)?), format!("R={}", ref_c(r, err)?), format!("REJECT={}", cpath(r, &wk.join("rejected.vcf"), err)?), s("WARN_ON_MISSING_CONTIG=true"), format!("TMP_DIR={}", cpath(r, &wk, err)?), ]; if !run_in(r, false, &[&dir], &a, To::Both(&log), out, err)?.0 { tail("20", std::slice::from_ref(&log), out); return Err(warn(out, &format!("[WARN] Picard could not lift chr{c}"))); } let a = [ bcftools.clone(), s("bash"), s("-euo"), s("pipefail"), s("-c"), s(ARCHAIC_LIFTED_SH), s("_"), cpath(r, &wk.join("hg38.vcf"), err)?, s(c), cpath(r, &wk, err)?, ]; if !run_in(r, false, &[&dir], &a, To::Terminal, out, err)?.0 { return Err(warn( out, &format!("[WARN] Could not read the lifted chr{c}"), )); } let sbed = wk.join("strict.bed"); write_file( &sbed, lines_where_first(&text(&strict), &format!("chr{c}")).as_bytes(), err, )?; if !nonempty(&sbed) { return Err(warn( out, &format!( "[WARN] the GRCh38 strict mask has no interval on chr{c}: {}", show(&strict) ), )); } let st = vec![ s("archaic"), s("strict"), s("--chrom"), s(c), s("--strict"), show(&sbed), s("--rows"), wh("lifted.tsv"), s("--out"), wh("marked.tsv"), ]; if !og_tool(r, &st, To::Terminal, out, err)?.0 { return Err(warn( out, &format!("[WARN] Could not mark the strict mask on chr{c}"), )); } let tpart = dir.join(format!("chr{c}.tsv.gz.part")); let mut rows = b"chrom\tpos\tref\talt\tAltai\tVindija\tDenisova\tAF_ALL\tAF_AFR\tAF_AMR\tAF_EAS\tAF_EUR\tAF_SAS\n".to_vec(); let marked = match fs::read(wk.join("marked.tsv")) { Ok(b) => b, Err(e) => { let _ = writeln!(err, "cat: {}: {e}", wh("marked.tsv")); let _ = gzip_to(&tpart, &rows, &mut std::io::sink()); return Err(warn( out, &format!("[WARN] Could not write chr{c} of the table"), )); } }; rows.extend_from_slice(&marked); if gzip_to(&tpart, &rows, &mut std::io::sink()).is_err() { return Err(warn( out, &format!("[WARN] Could not write chr{c} of the table"), )); } let n = awk_nr(&gunzip(&tpart)) as i64 - 1; if n < 1 { let _ = writeln!(out, "[WARN] chr{c} of the table has no row"); rm_rf(&tpart, err); return Err(1); } mv(&tpart, &table, err)?; echo_to(&cstamp, &stamp, err)?; let rejected = fs::read(wk.join("rejected.vcf")) .map(|b| { let t = String::from_utf8_lossy(&b).into_owned(); awk_records(&t) .iter() .filter(|l| !l.starts_with('#')) .count() }) .unwrap_or(0); let _ = writeln!(out, " chr{c}: {n} sites ({rejected} not lifted)"); for (g, _) in genomes { done_with(r, &[&adl.join(format!("{g}.chr{c}.vcf.gz"))], out, err); } rm_rf(&wk, err); } // A table of other chromosomes left by an earlier install with other regions goes. let chosen = format!(" {chroms} "); for v in glob(&dir, "chr", ".tsv.gz") { let name = v .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let c = name.strip_suffix(".tsv.gz").unwrap_or(&name); let c = c.strip_prefix("chr").unwrap_or(c); if !chosen.contains(&format!(" {c} ")) { rm_rf(&v, err); rm_rf(&dir.join(format!("chr{c}.stamp")), err); for m in glob(&mask, "", &format!(".chr{c}.bed.gz")) { rm_rf(&m, err); } rm_rf(&exclude.join(format!("chr{c}.bed.gz")), err); } } rm_rf(&dir.join("work"), err); done_with(r, &[&sites, &sites_tbi], out, err); echo_to(&dir.join("DONE"), &stamp, err)?; let _ = writeln!( out, "[OK] archaic data {version} (step 43): {} ({} chromosomes)", show(&dir), chroms.split_whitespace().count() ); Ok(()) } // --- --consumer-sites ---------------------------------------------------------------- /// consumer_sites_pin_check TABLE WHAT: the site table against /// CONSUMER_SITES_TABLE_SHA256, said on OUT; false when it differs. fn consumer_pin_check(r: &Run, table: &Path, what: &str, out: &mut dyn Write) -> bool { let got = gunzip_sha256(table); let pin = val(r, "CONSUMER_SITES_TABLE_SHA256"); if got == pin { let _ = writeln!( out, "[OK] Site table of step 40 {what}: {}, the same as the pinned build", show(table) ); return true; } let _ = writeln!( out, "[WARN] Site table of step 40 {what}: {} differs from the pinned build (content sha256 {got}, pinned {pin}).", show(table) ); false } /// install_consumer_sites: the site table of step 40 from the 23andMe v5 /// site list, dbSNP and UCSC's hg19ToHg38 chain (each site's strand). A /// table already there is kept only when it is the pinned build; any other /// is built again in its place, and a built table that differs from the pin /// fails. pub fn consumer_sites(r: &Run, out: &mut dyn Write, err: &mut dyn Write) -> Step { let build = val(r, "CONSUMER_DBSNP_BUILD"); let dir = p(&format!("{}/reference/consumer", r.genome)); let table = dir.join(format!("23andme_v5_sites_dbsnp{build}.tsv.gz")); let dropped = dir.join(format!("23andme_v5_dropped_dbsnp{build}.tsv")); let chain = p(&format!( "{}/reference/liftover/hg19ToHg38.over.chain.gz", r.genome )); if nonempty(&table) { if consumer_pin_check(r, &table, "already present", out) { return Ok(()); } let _ = writeln!( out, " It was built by another version of og consumer build-sites: building it again in its place." ); } let tpl = p(&source(r, "consumer_sites_template", None, "path", err)?); let url = source(r, "consumer_sites_template", None, "url", err)?; if !r.fetch(&url, &tpl, "sha256", &val(r, "CONSUMER_SITES_SHA256"), err) { return Err(warn( out, "[WARN] Could not download the 23andMe v5 site list.", )); } if !nonempty(&chain) { let _ = writeln!( out, " {} See docs/40-export-consumer.md.", crate::components::UCSC_CHAIN_TERMS ); } if !r.fetch( HG19_TO_HG38_CHAIN_URL, &chain, "sha256", &val(r, "HG19_TO_HG38_CHAIN_SHA256"), err, ) { return Err(warn( out, &format!( "[WARN] Could not download UCSC's hg19ToHg38 chain; run: {} --consumer-sites {}", r.script, r.genome ), )); } let db = p(&source(r, "dbsnp", None, "path", err)?); let url = source(r, "dbsnp", None, "url", err)?; let md5 = val(r, "CONSUMER_DBSNP_MD5"); let name = db.file_name().map(|n| n.to_owned()).unwrap_or_default(); adopt( r, &dir.join(name), &db, Some(&keep::Check { url: &url, sum: Some(("md5", &md5)), }), out, err, ); let _ = writeln!( out, "dbSNP {build} for GRCh38 (about 30 GB, kept in {}; a copy already there with the pinned md5 is used)...", r.vars.get("OG_DOWNLOADS").unwrap_or("") ); if !r.fetch(&url, &db, "md5", &md5, err) { return Err(warn( out, &format!( "[WARN] Could not download dbSNP {build}. Run this command again: the download resumes." ), )); } if !need_og(r, "builds the site table", out) { return Err(1); } let _ = writeln!( out, "Building the site table (reads the whole dbSNP file once)..." ); let a = vec![ s("consumer"), s("build-sites"), s("--template"), show(&tpl), s("--dbsnp"), show(&db), s("--chain"), show(&chain), s("--out"), show(&table), s("--dropped"), show(&dropped), s("--source"), format!( "23andme2vcf {} 23andme_v5_hg19_ref.txt.gz; dbSNP {build} GCF_000001405.40; UCSC hg19ToHg38.over.chain.gz", val(r, "CONSUMER_SITES_COMMIT") ), ]; if !og_tool(r, &a, To::Terminal, out, err)?.0 { rm_rf(&table, err); return Err(warn( out, "[WARN] Could not build the site table of step 40; the dbSNP download is kept: run this command again.", )); } done_with(r, &[&db], out, err); if !consumer_pin_check( r, &table, &format!( "built (dropped sites and their reasons: {})", show(&dropped) ), out, ) { return Err(warn( out, " The inputs match their pins, so this checkout's og consumer build-sites does not give the pinned table.", )); } Ok(()) }