Rename CLI to obikmer2, add phylo commands, and unify index caching
Restructure the workspace and rename the CLI application to obikmer2. Replace direct KmerIndex usage across all commands with Arc-wrapped IndexCache to enable shared ownership. Introduce builder patterns for algorithmic operations and integrate explicit progress tracking. Add new Phylo, NameTree, and Convert subcommands with expanded CLI flags. Consolidate module structure, update dependency specifications, and remove legacy directories.
This commit is contained in:
1 parent
e101f629e6
commit
95fa0c93b2
61 files changed
+1034
-6797
No files matched your search
+14
-17
@@ -10,34 +10,31 @@ path = "src/main.rs"
|
||||
[dependencies]
|
||||
obikseq = { path = "../obikseq" }
|
||||
obiread = { path = "../obiread" }
|
||||
obiskbuilder = { path = "../obiskbuilder" }
|
||||
obifastwrite = { path = "../obifastwrite" }
|
||||
obidebruinj = { path = "../obidebruinj" }
|
||||
obipipeline = { path = "../obipipeline" }
|
||||
obikrope = { path = "../obikrope" }
|
||||
obisys = { path = "../obisys" }
|
||||
obiskio = { path = "../obiskio" }
|
||||
obikindex = { path = "../obikindex", default-features = false }
|
||||
obikindexer = { path = "../obikindexer" }
|
||||
obikfilter = { path = "../obikfilter" }
|
||||
obikstats = { path = "../obikstats" }
|
||||
obikalgorithm = { path = "../obikalgorithm" }
|
||||
obikmerge = { path = "../obikmerge" }
|
||||
obikfilter = { path = "../obikfilter" }
|
||||
obikselect = { path = "../obikselect" }
|
||||
obikdump = { path = "../obikdump" }
|
||||
obikrebuild = { path = "../obikrebuild" }
|
||||
obikstats = { path = "../obikstats" }
|
||||
obikquery = { path = "../obikquery" }
|
||||
obikidxcache = { path = "../obikidxcache" }
|
||||
obikphylo = { path = "../obikphylo" }
|
||||
obitaxonomy = { path = "../obitaxonomy" }
|
||||
obikrope = { path = "../obikrope" }
|
||||
obifastwrite = { path = "../obifastwrite" }
|
||||
obiskbuilder = { path = "../obiskbuilder" }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
serde_yaml = "0.9.33"
|
||||
csv = "1"
|
||||
kodama = "0.3.0"
|
||||
speedytree = "0.1"
|
||||
rayon = "1"
|
||||
indicatif = "0.18"
|
||||
ndarray = "0.17"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_yaml = "0.9"
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] }
|
||||
pprof = { version = "0.15", features = ["prost-codec"], optional = true }
|
||||
|
||||
[features]
|
||||
default = ["numa"]
|
||||
numa = ["obisys/numa"]
|
||||
profiling = ["dep:pprof"]
|
||||
@@ -116,10 +116,13 @@ fn run_annotate(args: &AnnotateArgs) {
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let headers = rdr.headers().unwrap_or_else(|e| {
|
||||
eprintln!("error reading CSV headers: {e}");
|
||||
std::process::exit(1);
|
||||
}).clone();
|
||||
let headers = rdr
|
||||
.headers()
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error reading CSV headers: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
.clone();
|
||||
|
||||
let id_col_idx = headers.iter().position(|h| h == args.id_col).unwrap_or_else(|| {
|
||||
eprintln!("error: id column '{}' not found in CSV", args.id_col);
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obikindex::KmerIndex;
|
||||
use obikindex::layer::IndexMode;
|
||||
use obikrebuild::IndexReindex;
|
||||
use obisys::Reporter;
|
||||
use tracing::info;
|
||||
|
||||
use crate::cli::block_size_to_bits;
|
||||
use super::index::resolve_approx_params;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ConvertArgs {
|
||||
/// Index directory to convert (modified in-place)
|
||||
pub index: PathBuf,
|
||||
|
||||
#[command(flatten)]
|
||||
mode: ModeArgs,
|
||||
|
||||
/// Fingerprint bits per slot (b) — required with --hybrid-evidence
|
||||
/// when the source index is currently exact (there is no existing
|
||||
/// fingerprint to inherit `b` from); rejected otherwise (the source
|
||||
/// already fixes `b`, either from its own --approx-evidence or from
|
||||
/// an already-approximate/hybrid index being converted to hybrid).
|
||||
#[arg(long, value_name = "BITS")]
|
||||
pub evidence_bits: Option<u8>,
|
||||
|
||||
/// Findere z parameter: number of consecutive *stored* k-mers (length
|
||||
/// = the index's own k-mer size, fixed forever at `index` build time)
|
||||
/// that must all match to confirm a hit.
|
||||
///
|
||||
/// WARNING: this does NOT shorten the indexed k-mer length the way
|
||||
/// `-z` does at `index` build time — that length can never change
|
||||
/// after the fact. Instead it *extends* the effective match window:
|
||||
/// requiring z consecutive stored k-mers of length s to all match is
|
||||
/// equivalent to requiring (s + z − 1) consecutive identical bases in
|
||||
/// the query. E.g. on a k=31 index, z=2 requires 32 consecutive
|
||||
/// matching bases, not 30 — going from z=1 to z=2 makes matching
|
||||
/// *stricter*, it does not "index shorter k-mers".
|
||||
#[arg(short = 'z', long)]
|
||||
pub findere_z: Option<u8>,
|
||||
|
||||
/// Target false-positive rate per z-window (e.g. 0.01) — derives `b`
|
||||
/// or `z` when one of them isn't given directly (see `index --fp` for
|
||||
/// the same resolution rules).
|
||||
#[arg(long)]
|
||||
pub fp: Option<f64>,
|
||||
|
||||
/// Block size for exact evidence `.idx` (number of unitigs per block).
|
||||
/// Ignored when converting to pure approximate evidence.
|
||||
#[arg(long, default_value_t = 1)]
|
||||
pub block_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
#[group(required = true, multiple = false)]
|
||||
struct ModeArgs {
|
||||
/// Convert to exact evidence (zero false positives).
|
||||
#[arg(long)]
|
||||
exact_evidence: bool,
|
||||
|
||||
/// Convert to approximate (fingerprint-only) evidence. Value = fingerprint bits per slot (b).
|
||||
#[arg(long, value_name = "BITS")]
|
||||
approx_evidence: Option<u8>,
|
||||
|
||||
/// Convert to hybrid evidence (both exact and approximate bundles kept).
|
||||
#[arg(long)]
|
||||
hybrid_evidence: bool,
|
||||
}
|
||||
|
||||
pub fn run(args: ConvertArgs) {
|
||||
// Modifies the index in place; acquired before opening so a concurrent
|
||||
// writer can't slip in between the open and the convert below.
|
||||
let _lock = obisys::DirLock::acquire(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error locking index directory {}: {e}", args.index.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let current = idx.meta().config().evidence.clone();
|
||||
|
||||
let target = if args.mode.exact_evidence {
|
||||
warn_if_evidence_params_given(&args, "--exact-evidence");
|
||||
info!("target: exact evidence");
|
||||
IndexMode::Exact
|
||||
} else if let Some(bits) = args.mode.approx_evidence {
|
||||
let (z, b, fp) = resolve_approx_params(args.findere_z, Some(bits), args.fp);
|
||||
info!("target: approximate evidence — b={b}, z={z}, fp={fp:.2e}");
|
||||
IndexMode::Approx { b, z }
|
||||
} else {
|
||||
debug_assert!(args.mode.hybrid_evidence);
|
||||
match current {
|
||||
IndexMode::Exact => {
|
||||
let bits = args.evidence_bits.unwrap_or_else(|| {
|
||||
eprintln!(
|
||||
"error: --hybrid-evidence requires --evidence-bits when starting from an exact index"
|
||||
);
|
||||
std::process::exit(1);
|
||||
});
|
||||
let (z, b, fp) = resolve_approx_params(args.findere_z, Some(bits), args.fp);
|
||||
info!("target: hybrid evidence — b={b}, z={z}, fp={fp:.2e}");
|
||||
IndexMode::Hybrid { b, z }
|
||||
}
|
||||
IndexMode::Approx { b, z } | IndexMode::Hybrid { b, z } => {
|
||||
if args.evidence_bits.is_some() || args.findere_z.is_some() || args.fp.is_some() {
|
||||
eprintln!(
|
||||
"error: --evidence-bits/-z/--fp are not allowed with --hybrid-evidence \
|
||||
when the source index is already approximate/hybrid — its existing \
|
||||
b={b}, z={z} are reused as-is"
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
info!("target: hybrid evidence — reusing existing b={b}, z={z}");
|
||||
IndexMode::Hybrid { b, z }
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let block_bits = block_size_to_bits(args.block_size);
|
||||
let mut rep = Reporter::new();
|
||||
idx.reindex(target, block_bits, &mut rep).unwrap_or_else(|e| {
|
||||
eprintln!("convert error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
rep.print();
|
||||
}
|
||||
|
||||
fn warn_if_evidence_params_given(args: &ConvertArgs, mode: &str) {
|
||||
if args.evidence_bits.is_some() || args.findere_z.is_some() || args.fp.is_some() {
|
||||
eprintln!("warning: --evidence-bits/-z/--fp ignored with {mode}");
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
use std::io::{self, BufWriter};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use clap::Args;
|
||||
use obikdump::IndexDump;
|
||||
use obikfilter::KmerFilter;
|
||||
use obikindex::KmerIndex;
|
||||
use obisys::progress_bar;
|
||||
use tracing::info;
|
||||
|
||||
use super::predicate::FilterArgs;
|
||||
use super::predicate::GroupFilterArgs;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct DumpArgs {
|
||||
@@ -26,34 +29,35 @@ pub struct DumpArgs {
|
||||
pub head: Option<usize>,
|
||||
|
||||
#[command(flatten)]
|
||||
pub filter: FilterArgs,
|
||||
pub group_filter: GroupFilterArgs,
|
||||
}
|
||||
|
||||
pub fn run(args: DumpArgs) {
|
||||
let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
let idx = Arc::new(KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}));
|
||||
|
||||
let n_genomes = idx.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
}).len();
|
||||
info!(
|
||||
"dumping {} partitions, {} genome(s)",
|
||||
"dumping {} partition(s), {} genome(s)",
|
||||
idx.n_partitions(),
|
||||
n_genomes
|
||||
);
|
||||
|
||||
let filters = args.filter.build_filters(&idx.meta());
|
||||
let filters: Vec<Box<dyn KmerFilter>> = vec![Box::new(args.group_filter.build_filter(&idx.meta()))];
|
||||
let pb = progress_bar("dump", idx.n_partitions() as u64, "partitions");
|
||||
|
||||
let stdout = io::stdout();
|
||||
let mut out = BufWriter::new(stdout.lock());
|
||||
|
||||
idx.dump(&mut out, args.force_presence, args.debug, args.head, &filters, || pb.inc(1)).unwrap_or_else(|e| {
|
||||
eprintln!("dump error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
idx.dump(&mut out, args.force_presence, args.debug, args.head, &filters, || pb.inc(1))
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("dump error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
}
|
||||
@@ -1,15 +1,17 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use clap::Args;
|
||||
use obikindex::{KmerIndex, MergeMode};
|
||||
use obikindex::filter::{MaxTotalCount, MinComplexity, MinTotalCount};
|
||||
use obisys::Reporter;
|
||||
use obikalgorithm::Algorithm;
|
||||
use obikfilter::{Filter, KmerFilter, MaxTotalCount, MinComplexity, MinTotalCount};
|
||||
use obikindex::KmerIndex;
|
||||
use obisys::{Progress, Reporter, Stage, progress_bar};
|
||||
use tracing::info;
|
||||
|
||||
use super::predicate::FilterArgs as KmerFilterArgs;
|
||||
use super::predicate::GroupFilterArgs;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct FilterCmdArgs {
|
||||
pub struct FilterArgs {
|
||||
/// Source index directory
|
||||
pub source: PathBuf,
|
||||
|
||||
@@ -18,7 +20,7 @@ pub struct FilterCmdArgs {
|
||||
pub output: PathBuf,
|
||||
|
||||
#[command(flatten)]
|
||||
pub filter: KmerFilterArgs,
|
||||
pub group_filter: GroupFilterArgs,
|
||||
|
||||
/// Minimum total count across all genomes (count index only)
|
||||
#[arg(long)]
|
||||
@@ -28,15 +30,11 @@ pub struct FilterCmdArgs {
|
||||
#[arg(long)]
|
||||
pub max_total_count: Option<u32>,
|
||||
|
||||
/// Minimum normalized entropy (complexity) to keep a k-mer — same metric
|
||||
/// as `obikmer index`'s --theta, applied here to k-mers already committed
|
||||
/// to the source index (reconstructed from unitigs.bin). K-mers scoring
|
||||
/// below this are removed.
|
||||
/// Minimum normalized entropy (complexity) to keep a k-mer
|
||||
#[arg(long)]
|
||||
pub min_complexity: Option<f64>,
|
||||
|
||||
/// Maximum sub-word size for the complexity computation (see `obikmer
|
||||
/// index`'s --level-max). Only used when --min-complexity is set.
|
||||
/// Maximum sub-word size for the complexity computation (only used when --min-complexity is set)
|
||||
#[arg(long, default_value_t = 6)]
|
||||
pub complexity_level_max: usize,
|
||||
|
||||
@@ -44,34 +42,23 @@ pub struct FilterCmdArgs {
|
||||
#[arg(long)]
|
||||
pub presence: bool,
|
||||
|
||||
/// Pack the output's presence matrices in the dense format instead of the default sparse one
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub dense: bool,
|
||||
|
||||
/// Overwrite existing output directory
|
||||
#[arg(short, long)]
|
||||
pub force: bool,
|
||||
}
|
||||
|
||||
pub fn run(args: FilterCmdArgs) {
|
||||
let src = KmerIndex::open(&args.source).unwrap_or_else(|e| {
|
||||
pub fn run(args: FilterArgs) {
|
||||
let src = Arc::new(KmerIndex::open(&args.source).unwrap_or_else(|e| {
|
||||
eprintln!("error opening source index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let mode = if args.presence || !src.meta().config.with_counts {
|
||||
MergeMode::Presence
|
||||
} else {
|
||||
MergeMode::Count
|
||||
};
|
||||
|
||||
let n_genomes = src.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
}).len();
|
||||
info!(
|
||||
"filter: {} genome(s), mode={:?}, source={}",
|
||||
n_genomes, mode, args.source.display()
|
||||
);
|
||||
|
||||
let mut filters = args.filter.build_filters(&src.meta());
|
||||
}));
|
||||
|
||||
let mut filters: Vec<Box<dyn KmerFilter>> =
|
||||
vec![Box::new(args.group_filter.build_filter(&src.meta()))];
|
||||
if let Some(v) = args.min_total_count {
|
||||
filters.push(Box::new(MinTotalCount { total: v }));
|
||||
}
|
||||
@@ -82,20 +69,32 @@ pub fn run(args: FilterCmdArgs) {
|
||||
filters.push(Box::new(MinComplexity { level_max: args.complexity_level_max, theta }));
|
||||
}
|
||||
|
||||
// Source is opened read-only above and needs no lock; only the
|
||||
// destination is written.
|
||||
let _lock = obisys::DirLock::acquire(&args.output).unwrap_or_else(|e| {
|
||||
eprintln!("error locking output directory {}: {e}", args.output.display());
|
||||
let n_genomes = src.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}).len();
|
||||
info!(
|
||||
"filter: {} genome(s), source={}",
|
||||
n_genomes, args.source.display()
|
||||
);
|
||||
|
||||
let mut rep = Reporter::new();
|
||||
KmerIndex::rebuild(&args.output, &src, &filters, mode, args.force, &mut rep)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error filtering index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let t = Stage::start("filter");
|
||||
let pb = progress_bar("filter", src.n_partitions() as u64, "partitions");
|
||||
let mut alg = Filter::new(Arc::clone(&src), &args.output, &filters)
|
||||
.presence(args.presence)
|
||||
.force(args.force)
|
||||
.sparse(!args.dense)
|
||||
.on_progress(|_: Progress| pb.inc(1));
|
||||
|
||||
let dst = alg.run().unwrap_or_else(|e| {
|
||||
eprintln!("error filtering index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
rep.push(t.stop());
|
||||
|
||||
info!("filtered index → {}", dst.dir().display());
|
||||
alg.reporter().print();
|
||||
rep.print();
|
||||
info!("filtered index → {}", args.output.display());
|
||||
}
|
||||
@@ -168,16 +168,6 @@ pub fn run(args: IndexArgs) {
|
||||
let output = args.output.clone();
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
// Locked for the whole build (including a possible --force removal +
|
||||
// recreation below): a second `index` run resuming/overwriting the same
|
||||
// output directory concurrently would otherwise corrupt it. Unlinking
|
||||
// the lock file via --force's remove_dir_all is safe — the held file
|
||||
// descriptor keeps the lock regardless of the directory entry.
|
||||
let _lock = obisys::DirLock::acquire(&output).unwrap_or_else(|e| {
|
||||
eprintln!("error locking output directory {}: {e}", output.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
// ── Resolve evidence kind ────────────────────────────────────────────────
|
||||
let (evidence, effective_kmer_size) = if args.approx {
|
||||
let (z, b, fp) = resolve_approx_params(args.findere_z, args.evidence_bits, args.fp);
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obikindex::{KmerIndex, MergeMode};
|
||||
use obisys::Reporter;
|
||||
use obikalgorithm::Algorithm;
|
||||
use obikindex::KmerIndex;
|
||||
use obikmerge::{Merge, MergeMode};
|
||||
use obisys::{Progress, Reporter, Stage, progress_bar};
|
||||
use tracing::info;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -27,20 +29,23 @@ pub struct MergeArgs {
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub rename_duplicates: bool,
|
||||
|
||||
/// Fraction of available RAM reserved as memory budget for parallel partition merging.
|
||||
/// Reduce if OOM occurs despite the adaptive scheduler (e.g. --budget-fraction 0.3).
|
||||
#[arg(long, default_value_t = 0.5)]
|
||||
pub budget_fraction: f64,
|
||||
/// Pack the output's presence matrices in the dense format instead of the default sparse one
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub dense: bool,
|
||||
}
|
||||
|
||||
pub fn run(args: MergeArgs) {
|
||||
let sources: Vec<KmerIndex> = args.sources.iter().map(|p| {
|
||||
info!("opening source index: {}", p.display());
|
||||
KmerIndex::open(p).unwrap_or_else(|e| {
|
||||
eprintln!("error opening source index {}: {e}", p.display());
|
||||
std::process::exit(1);
|
||||
let sources: Vec<KmerIndex> = args
|
||||
.sources
|
||||
.iter()
|
||||
.map(|p| {
|
||||
info!("opening source index: {}", p.display());
|
||||
KmerIndex::open(p).unwrap_or_else(|e| {
|
||||
eprintln!("error opening source index {}: {e}", p.display());
|
||||
std::process::exit(1);
|
||||
})
|
||||
})
|
||||
}).collect();
|
||||
.collect();
|
||||
|
||||
// Auto-detect mode: count if all sources have count data, presence otherwise.
|
||||
// --force-presence overrides to presence regardless.
|
||||
@@ -52,34 +57,53 @@ pub fn run(args: MergeArgs) {
|
||||
};
|
||||
info!(
|
||||
"merge mode: {}",
|
||||
if mode == MergeMode::Count { "count" } else { "presence/absence" }
|
||||
if mode == MergeMode::Count {
|
||||
"count"
|
||||
} else {
|
||||
"presence/absence"
|
||||
}
|
||||
);
|
||||
|
||||
let source_refs: Vec<&KmerIndex> = sources.iter().collect();
|
||||
|
||||
|
||||
let n_genomes: usize = sources.iter().map(|s| {
|
||||
s.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
}).len()
|
||||
}).sum();
|
||||
let n_genomes: usize = sources
|
||||
.iter()
|
||||
.map(|s| {
|
||||
s.meta()
|
||||
.genomes()
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
.len()
|
||||
})
|
||||
.sum();
|
||||
info!(
|
||||
"merging {} index(es), {} genome(s) total → {}",
|
||||
sources.len(), n_genomes, args.output.display()
|
||||
sources.len(),
|
||||
n_genomes,
|
||||
args.output.display()
|
||||
);
|
||||
|
||||
// Only the destination is written; sources are opened read-only above
|
||||
// and need no lock.
|
||||
let _lock = obisys::DirLock::acquire(&args.output).unwrap_or_else(|e| {
|
||||
eprintln!("error locking output directory {}: {e}", args.output.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let mut rep = Reporter::new();
|
||||
KmerIndex::merge(&args.output, &source_refs, mode, args.force, args.rename_duplicates, args.budget_fraction, &mut rep).unwrap_or_else(|e| {
|
||||
let t = Stage::start("merge");
|
||||
let n_partitions = source_refs.first().map(|s| s.n_partitions()).unwrap_or(0);
|
||||
let pb = progress_bar("merge", n_partitions as u64, "partitions");
|
||||
|
||||
let mut merge = Merge::new(&source_refs, &args.output, mode)
|
||||
.force(args.force)
|
||||
.rename_duplicates(args.rename_duplicates)
|
||||
.sparse(!args.dense)
|
||||
.on_progress(|_: Progress| pb.inc(1));
|
||||
|
||||
let dst = merge.run().unwrap_or_else(|e| {
|
||||
eprintln!("error merging: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
rep.push(t.stop());
|
||||
|
||||
info!("merge done — output at {}", dst.dir().display());
|
||||
merge.reporter().print();
|
||||
rep.print();
|
||||
}
|
||||
@@ -1,16 +1,15 @@
|
||||
pub mod annotate;
|
||||
pub mod filter;
|
||||
pub mod pack;
|
||||
pub(crate) mod predicate;
|
||||
pub mod select;
|
||||
pub mod utils;
|
||||
pub mod phylo;
|
||||
pub mod convert;
|
||||
pub mod dump;
|
||||
pub mod estimate;
|
||||
pub mod filter;
|
||||
pub mod index;
|
||||
pub mod merge;
|
||||
pub mod nametree;
|
||||
pub mod pack;
|
||||
mod predicate;
|
||||
pub mod phylo;
|
||||
pub mod query;
|
||||
pub mod reindex;
|
||||
pub mod select;
|
||||
pub mod superkmer;
|
||||
pub mod unitig;
|
||||
pub mod utils;
|
||||
@@ -1,146 +0,0 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use clap::Args;
|
||||
use tracing::info;
|
||||
|
||||
// ── Translate a numerically-labelled tree export back to real taxon names ──
|
||||
//
|
||||
// TNT/PhyG write bare numeric leaf labels (1-based, in the same order as the
|
||||
// FASTA fed to them) — this reads that order back from the FASTA header
|
||||
// line and emits a NEXUS `translate` table alongside the tree(s), unchanged
|
||||
// otherwise. Readable directly by FigTree/PearTree/`ape` etc.
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct NameTreeArgs {
|
||||
/// Tree file to translate: a TNT-style NEXUS export (`tree NAME = [&U]
|
||||
/// ...;`, topology on the same or the next line) or a plain Newick file
|
||||
/// (single `(...);` tree, no header)
|
||||
pub tree: PathBuf,
|
||||
|
||||
/// FASTA file whose record order gives the numeric taxon labels
|
||||
/// (1-based) — typically the `_sankoff.fasta`/`_snp.fasta` used to
|
||||
/// produce `tree`
|
||||
#[arg(long)]
|
||||
pub fasta: PathBuf,
|
||||
|
||||
/// Output NEXUS file (taxa block + translate table + tree(s), topology
|
||||
/// unchanged)
|
||||
#[arg(short, long)]
|
||||
pub output: PathBuf,
|
||||
}
|
||||
|
||||
pub fn run(args: NameTreeArgs) {
|
||||
let labels = read_fasta_labels(&args.fasta);
|
||||
if labels.is_empty() {
|
||||
eprintln!("error: no FASTA headers found in {}", args.fasta.display());
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
let content = std::fs::read_to_string(&args.tree).unwrap_or_else(|e| {
|
||||
eprintln!("error reading {}: {e}", args.tree.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
let trees = extract_trees(&content);
|
||||
if trees.is_empty() {
|
||||
eprintln!("error: no tree found in {}", args.tree.display());
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
write_named_nexus(&labels, &trees, &args.output);
|
||||
}
|
||||
|
||||
fn read_fasta_labels(path: &Path) -> Vec<String> {
|
||||
let content = std::fs::read_to_string(path).unwrap_or_else(|e| {
|
||||
eprintln!("error reading {}: {e}", path.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
content.lines()
|
||||
.filter(|l| l.starts_with('>'))
|
||||
.map(|l| {
|
||||
let header = &l[1..];
|
||||
// `obifastwrite::write_record` appends a ` {json}` annotation —
|
||||
// not part of the taxon name.
|
||||
match header.find(" {") {
|
||||
Some(pos) => header[..pos].to_string(),
|
||||
None => header.to_string(),
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Finds every `tree NAME = [&U] TOPOLOGY;` (rooting comment optional,
|
||||
/// topology on the same line or the next non-empty one), or — if none of
|
||||
/// that syntax is found — treats the whole file as one bare Newick tree.
|
||||
fn extract_trees(content: &str) -> Vec<(String, String)> {
|
||||
let lines: Vec<&str> = content.lines().collect();
|
||||
let mut trees = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < lines.len() {
|
||||
let line = lines[i].trim();
|
||||
if let Some(rest) = line.strip_prefix("tree ") {
|
||||
if let Some(eq_pos) = rest.find('=') {
|
||||
let name = rest[..eq_pos].trim().to_string();
|
||||
let mut after_eq = rest[eq_pos + 1..].trim();
|
||||
if after_eq.starts_with('[') {
|
||||
if let Some(close) = after_eq.find(']') {
|
||||
after_eq = after_eq[close + 1..].trim();
|
||||
}
|
||||
}
|
||||
let topo = if after_eq.starts_with('(') {
|
||||
after_eq.to_string()
|
||||
} else {
|
||||
i += 1;
|
||||
while i < lines.len() && lines[i].trim().is_empty() {
|
||||
i += 1;
|
||||
}
|
||||
lines.get(i).map(|s| s.trim().to_string()).unwrap_or_default()
|
||||
};
|
||||
if topo.starts_with('(') {
|
||||
trees.push((name, topo));
|
||||
}
|
||||
}
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
|
||||
if trees.is_empty() {
|
||||
let trimmed = content.trim();
|
||||
if trimmed.starts_with('(') && trimmed.ends_with(';') {
|
||||
trees.push(("tree_1".to_string(), trimmed.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
trees
|
||||
}
|
||||
|
||||
fn write_named_nexus(labels: &[String], trees: &[(String, String)], output: &Path) {
|
||||
let mut out = String::new();
|
||||
out.push_str("#NEXUS\n\n");
|
||||
out.push_str("begin taxa;\n");
|
||||
out.push_str(&format!(" dimensions ntax={};\n", labels.len()));
|
||||
out.push_str(" taxlabels\n");
|
||||
for lab in labels {
|
||||
out.push_str(&format!(" {lab}\n"));
|
||||
}
|
||||
out.push_str(" ;\nend;\n\n");
|
||||
out.push_str("begin trees;\n");
|
||||
out.push_str(" translate\n");
|
||||
let tr_lines: Vec<String> = labels.iter().enumerate()
|
||||
.map(|(i, lab)| format!(" {} {lab}", i + 1))
|
||||
.collect();
|
||||
out.push_str(&tr_lines.join(",\n"));
|
||||
out.push_str(";\n");
|
||||
for (name, topo) in trees {
|
||||
out.push_str(&format!(" tree {name} = [&U] {topo}\n"));
|
||||
}
|
||||
out.push_str("end;\n");
|
||||
|
||||
std::fs::write(output, &out).unwrap_or_else(|e| {
|
||||
eprintln!("error writing {}: {e}", output.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
info!(
|
||||
"named tree(s) → {} ({} tree{}, {} taxa)",
|
||||
output.display(), trees.len(), if trees.len() == 1 { "" } else { "s" }, labels.len(),
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use clap::Args;
|
||||
use obikindex::KmerIndex;
|
||||
use obisys::{Reporter, Stage};
|
||||
use obikrebuild::IndexCompact;
|
||||
use obisys::{Reporter, Stage, progress_bar};
|
||||
use tracing::info;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -10,13 +12,17 @@ pub struct PackArgs {
|
||||
/// Index directory to pack
|
||||
pub index: PathBuf,
|
||||
|
||||
/// Pack presence matrices into the sparse, deduplicated on-disk format
|
||||
/// instead of the dense one — see `DevDocMD/architecture/siblings.md`.
|
||||
/// Smaller and faster for single-row access on real, sparse data;
|
||||
/// column-oriented access (`--metric` distance matrices) is much
|
||||
/// slower on the sparse format.
|
||||
#[arg(long)]
|
||||
pub sparse: bool,
|
||||
/// Compact every partition's accumulated layers into one before packing
|
||||
/// — undoes the multi-layer stopgap `merge` leaves behind.
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub compact_layers: bool,
|
||||
|
||||
/// Pack presence and count matrices into the dense on-disk format instead
|
||||
/// of the default sparse, deduplicated one. Dense is faster for
|
||||
/// column-oriented access (`--metric` distance matrices); sparse is
|
||||
/// smaller and faster for single-row access on real, sparse data.
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub dense: bool,
|
||||
}
|
||||
|
||||
pub fn run(args: PackArgs) {
|
||||
@@ -27,10 +33,10 @@ pub fn run(args: PackArgs) {
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
let idx = Arc::new(KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}));
|
||||
|
||||
let n_genomes = idx.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
@@ -43,13 +49,24 @@ pub fn run(args: PackArgs) {
|
||||
);
|
||||
|
||||
let mut rep = Reporter::new();
|
||||
let t = Stage::start("pack");
|
||||
|
||||
idx.pack_matrices(args.sparse).unwrap_or_else(|e| {
|
||||
if args.compact_layers {
|
||||
let t = Stage::start("compact layers");
|
||||
let pb = progress_bar("compact", idx.n_partitions() as u64, "partitions");
|
||||
idx.compact_layers(|| pb.inc(1)).unwrap_or_else(|e| {
|
||||
eprintln!("compact error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
rep.push(t.stop());
|
||||
}
|
||||
|
||||
let t = Stage::start("pack");
|
||||
idx.pack_matrices(!args.dense).unwrap_or_else(|e| {
|
||||
eprintln!("pack error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
rep.push(t.stop());
|
||||
|
||||
rep.print();
|
||||
}
|
||||
+234
-219
@@ -1,10 +1,16 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obikindex::DistanceMetric;
|
||||
use obikphylo::{DistanceMetric, SnpDistanceKind};
|
||||
|
||||
/// `--distance` value — either one of `obikphylo::DistanceMetric`'s
|
||||
/// whole-index metrics (routed to `IndexCache::distance`) or one of
|
||||
/// `obikphylo::SnpDistanceKind`'s `snp-*` corrections (routed to
|
||||
/// `SiblingExt::snp_distance`, the sibling-annex pipeline) — two genuinely
|
||||
/// different code paths behind one CLI vocabulary, see
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`, "`--distance` unification".
|
||||
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
|
||||
pub enum MetricArg {
|
||||
pub enum DistanceArg {
|
||||
Jaccard,
|
||||
Mash,
|
||||
Hamming,
|
||||
@@ -17,88 +23,105 @@ pub enum MetricArg {
|
||||
Hellinger,
|
||||
#[value(name = "hellinger-euclidean")]
|
||||
HellingerEuclidean,
|
||||
#[value(name = "snp-raw")]
|
||||
SnpRaw,
|
||||
#[value(name = "snp-jc")]
|
||||
SnpJc,
|
||||
#[value(name = "snp-k2p")]
|
||||
SnpK2p,
|
||||
#[value(name = "snp-k81")]
|
||||
SnpK81,
|
||||
#[value(name = "snp-f81")]
|
||||
SnpF81,
|
||||
#[value(name = "snp-t92")]
|
||||
SnpT92,
|
||||
#[value(name = "snp-tn93")]
|
||||
SnpTn93,
|
||||
#[value(name = "snp-tv")]
|
||||
SnpTv,
|
||||
}
|
||||
|
||||
impl From<MetricArg> for DistanceMetric {
|
||||
fn from(m: MetricArg) -> Self {
|
||||
match m {
|
||||
MetricArg::Jaccard => DistanceMetric::Jaccard,
|
||||
MetricArg::Mash => DistanceMetric::Mash,
|
||||
MetricArg::Hamming => DistanceMetric::Hamming,
|
||||
MetricArg::BrayCurtis => DistanceMetric::BrayCurtis,
|
||||
MetricArg::RelfreqBrayCurtis => DistanceMetric::RelfreqBrayCurtis,
|
||||
MetricArg::Euclidean => DistanceMetric::Euclidean,
|
||||
MetricArg::RelfreqEuclidean => DistanceMetric::RelfreqEuclidean,
|
||||
MetricArg::Hellinger => DistanceMetric::Hellinger,
|
||||
MetricArg::HellingerEuclidean => DistanceMetric::HellingerEuclidean,
|
||||
}
|
||||
impl DistanceArg {
|
||||
/// `Some` for the whole-index metrics, `None` for `snp-*` values.
|
||||
pub fn as_classic(self) -> Option<DistanceMetric> {
|
||||
Some(match self {
|
||||
DistanceArg::Jaccard => DistanceMetric::Jaccard,
|
||||
DistanceArg::Mash => DistanceMetric::Mash,
|
||||
DistanceArg::Hamming => DistanceMetric::Hamming,
|
||||
DistanceArg::BrayCurtis => DistanceMetric::BrayCurtis,
|
||||
DistanceArg::RelfreqBrayCurtis => DistanceMetric::RelfreqBrayCurtis,
|
||||
DistanceArg::Euclidean => DistanceMetric::Euclidean,
|
||||
DistanceArg::RelfreqEuclidean => DistanceMetric::RelfreqEuclidean,
|
||||
DistanceArg::Hellinger => DistanceMetric::Hellinger,
|
||||
DistanceArg::HellingerEuclidean => DistanceMetric::HellingerEuclidean,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// `Some` for the `snp-*` values, `None` for the whole-index metrics.
|
||||
pub fn as_snp(self) -> Option<SnpDistanceKind> {
|
||||
Some(match self {
|
||||
DistanceArg::SnpRaw => SnpDistanceKind::Raw,
|
||||
DistanceArg::SnpJc => SnpDistanceKind::Jc,
|
||||
DistanceArg::SnpK2p => SnpDistanceKind::K2p,
|
||||
DistanceArg::SnpK81 => SnpDistanceKind::K81,
|
||||
DistanceArg::SnpF81 => SnpDistanceKind::F81,
|
||||
DistanceArg::SnpT92 => SnpDistanceKind::T92,
|
||||
DistanceArg::SnpTn93 => SnpDistanceKind::Tn93,
|
||||
DistanceArg::SnpTv => SnpDistanceKind::Tv,
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Genome-vs-genome distance computation: the whole-index `--distance` path
|
||||
/// (classic metrics + `snp-*` corrections/NJ/UPGMA), annex construction
|
||||
/// (`--sibling-annex`), annex diagnostics (`--sibling-stats`,
|
||||
/// `--sibling-hist`), entropy reporting (`--shannon`), SNP pseudo-alignment
|
||||
/// sampling (`--pseudo-alignment`, `--subsample`, `--free-loss`,
|
||||
/// `--no-ambiguity`, `--entropy`/`--entropy-sd`), Sankoff cost-matrix
|
||||
/// calibration (`--sankoff`, `--sankoff-ratio-ceiling`) and its TNT/PhyG/
|
||||
/// IQ-TREE exports (`--tnt`, `--phyg`, `--iqtree`/`--iqtree-min-freq`,
|
||||
/// `--sankoff-cost-scale`), and Family Overlap (`--family-overlap`,
|
||||
/// `--min-shared-family`).
|
||||
#[derive(Args)]
|
||||
pub struct PhyloArgs {
|
||||
/// Index directory
|
||||
pub index: PathBuf,
|
||||
|
||||
/// Distance metric to compute
|
||||
#[arg(long, value_enum, default_value = "jaccard")]
|
||||
pub metric: MetricArg,
|
||||
|
||||
/// Minimum count to consider a kmer present when computing Jaccard on count indexes
|
||||
#[arg(long, default_value = "1")]
|
||||
pub presence_threshold: u32,
|
||||
|
||||
/// Also output the shared-kmer count matrix (CSV)
|
||||
#[arg(long)]
|
||||
pub shared_kmers: bool,
|
||||
|
||||
/// Compute and write a Neighbor-Joining tree (Newick)
|
||||
#[arg(long)]
|
||||
pub nj: bool,
|
||||
|
||||
/// Compute and write a UPGMA tree (Newick)
|
||||
#[arg(long)]
|
||||
pub upgma: bool,
|
||||
|
||||
/// Build the sibling-count/minorant annex on this (multi-genome) index
|
||||
/// — see `DevDocMD/theory/evolutionary_distances.md`, Step 2b. Construction
|
||||
/// only; does not by itself compute or write any statistics.
|
||||
#[arg(long)]
|
||||
pub sibling_annex: bool,
|
||||
|
||||
/// Exclude a genome (by its exact label) from every computation below
|
||||
/// that reads the sibling annex — `--raw-snp-distance`/`--raw-snp-counts`,
|
||||
/// `--snp`, and `--sankoff` (and everything `--sankoff` implies: the
|
||||
/// cardinality/composition transition models, the exported
|
||||
/// matrix/alignment, `--tnt`/`--phyg`/`--iqtree`). Repeatable. Does
|
||||
/// *not* affect the plain `--metric` distance matrix/NJ/UPGMA path (a
|
||||
/// different, unrelated computation). Applied by zeroing the excluded
|
||||
/// genome's row/column after `raw_snp_distance` runs (a pair with zero
|
||||
/// counts is already skipped by `base_pair_tally`/`cardinality_tally`,
|
||||
/// so this needs no change to the underlying traversal) and by
|
||||
/// dropping its row from `snp_pseudo_alignment`'s output — the annex
|
||||
/// is still built/scanned for the excluded genome too, just not used
|
||||
/// afterward. For a genome with almost no informative sites shared
|
||||
/// with anything else (see `DevDocMD/theory/evolutionary_distances.md`,
|
||||
/// the IQ-TREE/Mash rogue-taxon discussion), its presence can
|
||||
/// otherwise silently bias the transition models.
|
||||
/// Exclude a genome (by its exact label) — from `--pseudo-alignment`'s
|
||||
/// sampling (a family whose only polymorphism lived in an excluded
|
||||
/// genome is discarded during sampling, not filtered afterward — see
|
||||
/// `obikphylo::siblings::extensions::SiblingExt::snp_pseudo_alignment`'s
|
||||
/// own docs) and from the distance matrix / shared-kmer matrix CSV
|
||||
/// output (row and column both dropped; the underlying computation
|
||||
/// itself is unaffected). Repeatable.
|
||||
#[arg(long = "exclude-genome", value_name = "LABEL")]
|
||||
pub exclude_genome: Vec<String>,
|
||||
|
||||
/// Auto-exclude any genome whose mean shared-family count against every
|
||||
/// other genome (same statistic as `--family-overlap`'s matrix, averaged
|
||||
/// over each row excluding the diagonal) falls below this threshold —
|
||||
/// same exclusion machinery as `--exclude-genome`, applied on top of it
|
||||
/// rather than instead of it. Empirically, genomes below ~1000 shared
|
||||
/// families on the 20-genome benchmark are exactly the ones that placed
|
||||
/// themselves arbitrarily under `--tnt`/`--iqtree` (near-zero branch
|
||||
/// lengths, grafted inside unrelated clades) — too little real
|
||||
/// constraint on where they belong. See
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`, "Locus dropout under
|
||||
/// incomplete coverage".
|
||||
/// Auto-exclude any genome whose mean shared-variable-family count
|
||||
/// against every other genome (`FamilyOverlap::mean_row` — the same
|
||||
/// per-row statistic `--family-overlap`'s own matrix shows) falls below
|
||||
/// this threshold — same exclusion machinery as `--exclude-genome`,
|
||||
/// applied on top of it rather than instead of it. Applies to the
|
||||
/// `snp-*` `--distance`/`--pseudo-alignment`/`--sankoff` computations
|
||||
/// below (all sibling-annex-based); does *not* affect the whole-index
|
||||
/// `--distance` metrics (jaccard, hamming, bray-curtis, ...) or their
|
||||
/// matrix/NJ/UPGMA output — a genome with too little SNP-family
|
||||
/// coverage to trust is a different concern from one whose plain k-mer
|
||||
/// profile is simply divergent. Requires the Family Overlap annex
|
||||
/// (built on demand if missing, same as every other annex here — see
|
||||
/// `obikphylo::siblings::extensions::SiblingExt::family_overlap`'s own
|
||||
/// docs).
|
||||
#[arg(long, value_name = "N")]
|
||||
pub min_shared_family: Option<f64>,
|
||||
|
||||
/// Build (or rebuild) the sibling-count/minorant annex — independent of
|
||||
/// the distance metric below, meant to be run routinely, ahead of any
|
||||
/// SNP-family distance computation that will later consume it.
|
||||
#[arg(long)]
|
||||
pub sibling_annex: bool,
|
||||
|
||||
/// Tally the sibling-count distribution (CSV) of an already-built annex
|
||||
/// (run with `--sibling-annex` first, in this invocation or an earlier
|
||||
/// one). A separate, occasional diagnostic pass — not run every time the
|
||||
@@ -109,124 +132,83 @@ pub struct PhyloArgs {
|
||||
/// Print just the global family-size histogram (1-4 members) of an
|
||||
/// already-built annex — the `global` row `--sibling-stats` also
|
||||
/// writes, but without the per-genome breakdown, so it skips
|
||||
/// `--sibling-stats`'s cross-partition resolution entirely: reads only
|
||||
/// the already-open annex mask and each layer's own `unitigs.bin`, cost
|
||||
/// independent of the rest of the index. A quick sanity check that the
|
||||
/// annex itself is sound, decoupled from `--sibling-stats`'s much
|
||||
/// heavier per-genome pass.
|
||||
/// `--sibling-stats`'s cross-partition resolution entirely (annex bits
|
||||
/// only).
|
||||
#[arg(long)]
|
||||
pub sibling_hist: bool,
|
||||
|
||||
/// Compute the raw p-distance restricted to loci that are single-copy
|
||||
/// in both genomes of each pair (an already-built sibling annex is
|
||||
/// required — run with `--sibling-annex` first, in this invocation or
|
||||
/// an earlier one). A quick way to test the central-position SNP
|
||||
/// estimator against a real index; not the full `SnpTally` design.
|
||||
#[arg(long)]
|
||||
pub raw_snp_distance: bool,
|
||||
|
||||
/// Write the raw per-pair counts (`n_snp`, `n_shared`, `n_eligible`)
|
||||
/// behind `--raw-snp-distance`'s ratio, one row per genome pair — a
|
||||
/// diagnostic table, not a matrix. The ratio alone can't distinguish
|
||||
/// "identical at every eligible locus" from "almost no eligible loci
|
||||
/// at all" (e.g. `0.0` from 0/2 looks the same as `0.0` from 0/2000),
|
||||
/// and that distinction matters a lot for genome pairs near the edge
|
||||
/// of what central-position families can resolve (see
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`, "Run 3" and the
|
||||
/// IQ-TREE/Mash comparison). Same annex requirement as
|
||||
/// `--raw-snp-distance`.
|
||||
#[arg(long)]
|
||||
pub raw_snp_counts: bool,
|
||||
|
||||
/// Write a SNP-only pseudo-alignment (FASTA, IUPAC-coded) from an
|
||||
/// already-built sibling annex — one row per genome, one column per
|
||||
/// variable family (monomorphic families skipped), no flanking
|
||||
/// sequence. See `DevDocMD/theory/evolutionary_distances.md`,
|
||||
/// "Multi-genome framing: family as pseudo-alignment column".
|
||||
#[arg(long)]
|
||||
pub snp: bool,
|
||||
|
||||
/// Cap the number of variable families (non-monomorphic minorants,
|
||||
/// `family_size() >= 2`) retained by `--snp`/`--sankoff` (and everything
|
||||
/// `--sankoff` implies) and `--shannon`, to (approximately) this many —
|
||||
/// sampled proportionally per layer, so the pseudo-alignment/entropy
|
||||
/// report stays usable on an index far larger than the sample itself
|
||||
/// (mandatory, not optional, once the index is large enough that a full
|
||||
/// pseudo-alignment can't be materialized at all). See
|
||||
/// `DevDocMD/architecture/siblings.md`, "`--subsample`/`--shannon`". If the
|
||||
/// index has fewer non-monomorphic minorants than this, every one of
|
||||
/// them is kept — no error, no under/over-shoot handling needed.
|
||||
#[arg(long, value_name = "N")]
|
||||
pub subsample: Option<usize>,
|
||||
|
||||
/// Enable entropy-biased selection: instead of a uniform draw among
|
||||
/// eligible families, weight each candidate by an unnormalised Gaussian
|
||||
/// kernel on its own entropy15 (`w = exp(-(entropy-mu)^2/(2*sigma^2))`,
|
||||
/// `1` exactly at `entropy == mu`, decaying smoothly away from it — no
|
||||
/// hard cutoff). Activates as soon as `--entropy` or `--entropy-sd` is
|
||||
/// given; the other defaults to `1.0`/`0.5` if unset. Combines with
|
||||
/// `--subsample N` (the joint accept probability is `p0 * w`, `p0`
|
||||
/// chosen so the expected count is approximately `N`) or works alone
|
||||
/// (a pure soft entropy filter over the whole index, no size target).
|
||||
/// First use on an index pays a one-time cost building a per-layer
|
||||
/// entropy annex (a full, unsampled scan); every later run reuses it.
|
||||
/// See `DevDocMD/architecture/siblings.md`, "Entropy-biased selection".
|
||||
#[arg(long, value_name = "MU")]
|
||||
pub entropy: Option<f64>,
|
||||
|
||||
/// Standard deviation of `--entropy`'s Gaussian kernel. See `--entropy`.
|
||||
#[arg(long, value_name = "SIGMA")]
|
||||
pub entropy_sd: Option<f64>,
|
||||
|
||||
/// Write <prefix>_shannon.csv: per-family Shannon entropy (bits, over
|
||||
/// the 15 non-empty subsets of `{A,C,G,T}`, `∅`/absent genomes excluded
|
||||
/// from the denominator — see `DevDocMD/architecture/siblings.md`,
|
||||
/// "Entropy definition") of every non-monomorphic minorant, one row per
|
||||
/// family. Combine with `--subsample N` for a bounded diagnostic sample
|
||||
/// instead of a full-index pass. Same annex requirement as `--snp`.
|
||||
#[arg(long)]
|
||||
pub shannon: bool,
|
||||
|
||||
/// Write an NxN CSV (`<prefix>_family_overlap.csv`) of, for each genome
|
||||
/// pair, how many variable families (same set `--snp`'s pseudo-alignment
|
||||
/// uses — `family_size() >= 2`) both genomes actually carry a call for
|
||||
/// (neither is `∅`). A direct read of how much informative content two
|
||||
/// genomes actually share at the family level — the diagnostic for why
|
||||
/// a genome with little overlap with anything else (e.g. an
|
||||
/// under-covered or very divergent one) ends up placed unstably by
|
||||
/// `--tnt`/`--iqtree`: little-to-no shared, real data to constrain it.
|
||||
/// Same annex requirement as `--snp`.
|
||||
/// Write the Family Overlap matrix (CSV) — number of shared *variable*
|
||||
/// families per genome pair, index-wide (`obikphylo::siblings::FamilyOverlap`).
|
||||
/// Built on demand if missing (same as every other annex here); no
|
||||
/// `--sibling-annex` prerequisite beyond that. Every genome is written,
|
||||
/// unfiltered by `--exclude-genome`/`--min-shared-family` — a raw
|
||||
/// coverage diagnostic, not a computation those exclusions are meant to
|
||||
/// protect.
|
||||
#[arg(long)]
|
||||
pub family_overlap: bool,
|
||||
|
||||
/// Calibrate a 16-state Sankoff cost matrix and its matching
|
||||
/// pseudo-alignment from an already-built sibling annex (run with
|
||||
/// `--sibling-annex` first, in this invocation or an earlier one), for
|
||||
/// use with TNT/PhyG. See `DevDocMD/theory/evolutionary_distances.md`,
|
||||
/// "Sankoff parsimony as the resolution of the 16-state model problem".
|
||||
/// Write a per-family Shannon entropy report (CSV) — requires an
|
||||
/// already-built sibling annex (`--sibling-annex` first, in this
|
||||
/// invocation or an earlier one). Always a full, unsampled scan of
|
||||
/// every family (`--subsample`/`--entropy`/`--entropy-sd` below only
|
||||
/// apply to `--pseudo-alignment`, not this).
|
||||
#[arg(long)]
|
||||
pub sankoff: bool,
|
||||
pub shannon: bool,
|
||||
|
||||
/// Recode a family's non-detection (`∅`, no member observed in a
|
||||
/// genome) as TNT/PhyG/IQ-TREE's own missing-data symbol (`?`) in
|
||||
/// `--sankoff`'s FASTA and every export built from it (`--tnt`,
|
||||
/// `--phyg`, `--iqtree`), instead of an ordinary, costed 16th alphabet
|
||||
/// state (the default). For genome-skim/reduced-representation inputs
|
||||
/// (coverage often < 1x), non-detection is dominated by sampling
|
||||
/// failure, not true loss — scoring it as a real state risks grouping
|
||||
/// genomes by shared undersampling rather than shared ancestry. `?`
|
||||
/// (not `-`) because `-` still carries gap/indel semantics in these
|
||||
/// tools; a non-detected family is not an observed deletion. See
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`, "Locus dropout under
|
||||
/// incomplete coverage".
|
||||
/// Write a SNP-only pseudo-alignment (FASTA) — requires
|
||||
/// `--subsample <N>` and an already-built sibling annex
|
||||
/// (`--sibling-annex` first, in this invocation or an earlier one).
|
||||
#[arg(long)]
|
||||
pub pseudo_alignment: bool,
|
||||
|
||||
/// Target number of variable sites to sample index-wide for
|
||||
/// `--pseudo-alignment`/`--sankoff` (mandatory for both) and for a
|
||||
/// `snp-*` `--distance` value (optional there: omitted means exhaustive
|
||||
/// — every non-monomorphic minorant of the whole index, not an
|
||||
/// approximation, see `obikphylo::siblings::SiblingExt::snp_distance`'s
|
||||
/// own docs) — a target, not a guarantee when given (proportional
|
||||
/// per-layer sampling; see
|
||||
/// `obikphylo::siblings::SiblingExt::snp_pseudo_alignment`'s own docs).
|
||||
#[arg(long)]
|
||||
pub subsample: Option<usize>,
|
||||
|
||||
/// In `--pseudo-alignment`, treat a genome carrying none of a family's
|
||||
/// observed members (`∅`) as missing data (`?`) rather than a real
|
||||
/// character state.
|
||||
#[arg(long)]
|
||||
pub free_loss: bool,
|
||||
|
||||
/// In `--pseudo-alignment`, treat a genome carrying more than one
|
||||
/// member of a family (ambiguous) as missing data (`?`) rather than an
|
||||
/// IUPAC ambiguity code.
|
||||
#[arg(long)]
|
||||
pub no_ambiguity: bool,
|
||||
|
||||
/// Entropy-biased sampling target (Gaussian kernel mean) for
|
||||
/// `--pseudo-alignment` — activates biasing as soon as this or
|
||||
/// `--entropy-sd` is given; the other defaults to 1.0/0.5.
|
||||
#[arg(long)]
|
||||
pub entropy: Option<f64>,
|
||||
|
||||
/// Entropy-biased sampling kernel width (Gaussian standard deviation)
|
||||
/// for `--pseudo-alignment` — see `--entropy`.
|
||||
#[arg(long)]
|
||||
pub entropy_sd: Option<f64>,
|
||||
|
||||
/// Calibrate a 16-state Sankoff cost matrix (and its matching
|
||||
/// pseudo-alignment) from an already-built sibling annex — requires
|
||||
/// `--subsample <N>`, and shares `--free-loss`/`--no-ambiguity`/
|
||||
/// `--entropy`/`--entropy-sd` with `--pseudo-alignment` (one draw, same
|
||||
/// selection feeds both the alignment and every calibration tally).
|
||||
#[arg(long)]
|
||||
pub sankoff: bool,
|
||||
|
||||
/// Exclude genome pairs whose raw SNP ratio exceeds this value from the
|
||||
/// `p_hat` calibration pooled by `--sankoff` — a pair this close to
|
||||
/// saturation carries no information about `p_hat` and would bias it
|
||||
/// upward if pooled in (unlike a low eligible-loci count, which barely
|
||||
/// moves the pooled estimate either way — see design doc).
|
||||
/// base-pair (composition) calibration `--sankoff` pools — a pair this
|
||||
/// close to substitution saturation carries no information about the
|
||||
/// true substitution spectrum. Does *not* gate the cardinality
|
||||
/// calibration (see `obikphylo::siblings::CardinalityTally`'s own
|
||||
/// docs for why).
|
||||
#[arg(long, default_value = "0.5")]
|
||||
pub sankoff_ratio_ceiling: f64,
|
||||
|
||||
@@ -250,66 +232,99 @@ pub struct PhyloArgs {
|
||||
pub phyg: bool,
|
||||
|
||||
/// Also write <prefix>_iqtree.model and <prefix>_iqtree.fasta, a
|
||||
/// custom-model file and a matching
|
||||
/// recoded alignment for genuine maximum-likelihood inference with
|
||||
/// IQ-TREE (`iqtree3 -s ... --seqtype MORPH -m ...+ASC`) — real branch
|
||||
/// lengths, unlike `--tnt`/`--phyg`'s parsimony step counts. The model
|
||||
/// is the reversible `Q(i,j) = R(i,j)·π_j` construction: `R`
|
||||
/// (exchangeability, symmetric) recovered from the same calibrated
|
||||
/// cost matrix `--sankoff` computes, `π` the real empirical state
|
||||
/// frequencies counted from the alignment (not IQ-TREE's `+FO`/`+F` —
|
||||
/// neither applies to a custom-file model, see
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`). Only the states that
|
||||
/// actually occur in this alignment are kept, compactly renumbered
|
||||
/// (IQ-TREE infers its state count from the alignment itself, and a
|
||||
/// gap in the numbering would silently misalign the model file).
|
||||
/// Implies `--sankoff`.
|
||||
/// custom-model file and a matching recoded alignment for genuine
|
||||
/// maximum-likelihood inference with IQ-TREE (`iqtree3 -s ...
|
||||
/// --seqtype MORPH -m ...+ASC`) — real branch lengths, unlike
|
||||
/// `--tnt`/`--phyg`'s parsimony step counts. The model is the
|
||||
/// reversible `Q(i,j) = R(i,j)·π_j` construction: `R` (exchangeability,
|
||||
/// symmetric) recovered from the same calibrated cost matrix
|
||||
/// `--sankoff` computes, `π` the real empirical state frequencies
|
||||
/// counted from the alignment. Only the states that actually occur in
|
||||
/// this alignment are kept, compactly renumbered (IQ-TREE infers its
|
||||
/// state count from the alignment itself, and a gap in the numbering
|
||||
/// would silently misalign the model file). Implies `--sankoff`.
|
||||
#[arg(long)]
|
||||
pub iqtree: bool,
|
||||
|
||||
/// Under `--iqtree --free-loss`, also recode to `?` (the same
|
||||
/// missing-data treatment as `-`) any state whose empirical frequency
|
||||
/// in the alignment falls below this threshold — not just genuinely
|
||||
/// absent calls. States encoding 3 or 4 simultaneously-observed
|
||||
/// central bases (IUPAC `V`/`H`/`K`.../`N` for 3, `N` for 4) are rare
|
||||
/// by construction and, on real data, land in exactly this low-frequency
|
||||
/// range — more likely assembly/detection noise than a genuine,
|
||||
/// widely-preserved multi-way polymorphism, the same "sampling failure,
|
||||
/// not true signal" reasoning `--free-loss` already applies to absence.
|
||||
/// Confirmed on real data to matter: `iqtree3`'s own "Numerical
|
||||
/// underflow for lh-derivative" warnings and the exact-zero
|
||||
/// exchangeability rows this was meant to fix (see
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`) both trace back to
|
||||
/// states this thin. No effect without `--free-loss` (there is no
|
||||
/// missing-data symbol to recode to otherwise). `<prefix>_iqtree_states.csv`
|
||||
/// reports the frequency actually used to decide.
|
||||
/// absent calls. States encoding 3 or 4 simultaneously-observed central
|
||||
/// bases (IUPAC `V`/`H`/`K`.../`N` for 3, `N` for 4) are rare by
|
||||
/// construction and often land in exactly this low-frequency range —
|
||||
/// more likely assembly/detection noise than a genuine, widely-preserved
|
||||
/// multi-way polymorphism, the same "sampling failure, not true signal"
|
||||
/// reasoning `--free-loss` already applies to absence. No effect
|
||||
/// without `--free-loss` (there is no missing-data symbol to recode to
|
||||
/// otherwise). `<prefix>_iqtree_states.csv` reports the frequency
|
||||
/// actually used to decide.
|
||||
#[arg(long, default_value = "0.001")]
|
||||
pub iqtree_min_freq: f64,
|
||||
|
||||
/// Scale factor applied before rounding real-valued costs to the
|
||||
/// integers both `--tnt`'s smatrix/cost commands and `--phyg`'s `tcm:`
|
||||
/// matrix require. Keep this small: the total tree score is this scale
|
||||
/// times the sum of per-character costs across every character (908k+
|
||||
/// for a typical run here), and there are hints in TNT's own manual
|
||||
/// that at least some of its internal accumulators are 32-bit — a large
|
||||
/// scale risks a silent integer overflow (undetectable, not just a
|
||||
/// crash) far more costly than the resolution a bigger factor would
|
||||
/// buy. Shared between `--tnt` and `--phyg` rather than split into two
|
||||
/// flags: both scale the same calibrated matrix for the same reason
|
||||
/// (integer-only cost commands), and no PhyG-specific accumulator-width
|
||||
/// constraint has actually been found to justify a different default.
|
||||
/// times the sum of per-character costs across every character, and
|
||||
/// there are hints in TNT's own manual that at least some of its
|
||||
/// internal accumulators are 32-bit — a large scale risks a silent
|
||||
/// integer overflow (undetectable, not just a crash) far more costly
|
||||
/// than the resolution a bigger factor would buy. Shared between `--tnt`
|
||||
/// and `--phyg` rather than split into two flags: both scale the same
|
||||
/// calibrated matrix for the same reason (integer-only cost commands).
|
||||
#[arg(long, default_value = "100")]
|
||||
pub sankoff_cost_scale: f64,
|
||||
|
||||
/// Output prefix: <prefix>_dist.csv, <prefix>_shared.csv,
|
||||
/// <prefix>_siblings.csv, <prefix>_sibling_hist.csv, <prefix>_rawsnp.csv,
|
||||
/// <prefix>_rawsnp_counts.csv,
|
||||
/// <prefix>_snp.fasta, <prefix>_family_overlap.csv, <prefix>_shannon.csv,
|
||||
/// <prefix>_sankoff_matrix.csv, <prefix>_sankoff_params.yaml,
|
||||
/// <prefix>_sankoff.fasta, <prefix>_sankoff.tnt, <prefix>_sankoff.tcm,
|
||||
/// <prefix>_sankoff.pg, <prefix>_iqtree.model, <prefix>_iqtree.fasta,
|
||||
/// <prefix>_nj.nwk, <prefix>_upgma.nwk.
|
||||
/// If omitted, the distance matrix is written to stdout.
|
||||
/// Distance to compute — either a whole-index metric (`jaccard`,
|
||||
/// `mash`, `hamming`, `bray-curtis`, ...) or a `snp-*` correction over
|
||||
/// the central-position SNP substitution spectrum (`snp-raw`, `snp-jc`,
|
||||
/// `snp-k2p`, `snp-k81`, `snp-f81`, `snp-t92`, `snp-tn93`, `snp-tv`) —
|
||||
/// the latter route to a different computation entirely
|
||||
/// (`SiblingExt::snp_distance`, requires `--sibling-annex` first; see
|
||||
/// `DevDocMD/theory/evolutionary_distances.md`, "`--distance`
|
||||
/// unification" for the full catalog and why LogDet/Tajima-Nei/F84/
|
||||
/// HKY85 aren't offered yet).
|
||||
#[arg(long, value_enum, default_value = "jaccard")]
|
||||
pub distance: DistanceArg,
|
||||
|
||||
/// Rate-heterogeneity correction (Jin-Nei gamma shape parameter `α`)
|
||||
/// for `snp-*` `--distance` values that support it
|
||||
/// (`obikphylo::SnpDistanceKind::supports_gamma`: every one except
|
||||
/// `snp-raw`/`snp-tv`, which have nothing to correct/are deliberately
|
||||
/// uncorrected). Has no effect on the whole-index metrics. Rejected at
|
||||
/// runtime if given alongside an unsupported `--distance` value.
|
||||
#[arg(long, value_name = "ALPHA")]
|
||||
pub gamma_shape: Option<f64>,
|
||||
|
||||
/// Minimum count to consider a kmer present when computing Jaccard on count indexes
|
||||
#[arg(long, default_value = "1")]
|
||||
pub presence_threshold: u32,
|
||||
|
||||
/// Write the primary distance matrix as plain CSV instead of the
|
||||
/// default relaxed-PHYLIP format (`n` on the first line, then one
|
||||
/// `label<TAB>value...` row per genome — no 10-character label
|
||||
/// truncation, unlike strict PHYLIP, not yet offered here). PHYLIP is
|
||||
/// the default because it's what external NJ tools (PHYLIP `neighbor`,
|
||||
/// FastME, T-REX, SplitsTree) actually read; CSV stays available for
|
||||
/// scripting/inspection. Only affects the primary distance matrix —
|
||||
/// `--shared-kmers` keeps its own CSV-only format regardless of this
|
||||
/// flag.
|
||||
#[arg(long)]
|
||||
pub csv: bool,
|
||||
|
||||
/// Also output the shared-kmer count matrix (CSV)
|
||||
#[arg(long)]
|
||||
pub shared_kmers: bool,
|
||||
|
||||
/// Compute and write a Neighbor-Joining tree (Newick)
|
||||
#[arg(long)]
|
||||
pub nj: bool,
|
||||
|
||||
/// Compute and write a UPGMA tree (Newick)
|
||||
#[arg(long)]
|
||||
pub upgma: bool,
|
||||
|
||||
/// Output prefix: <prefix>_dist.csv, <prefix>_shared.csv, <prefix>_nj.nwk,
|
||||
/// <prefix>_upgma.nwk. If omitted, the distance matrix is written to stdout.
|
||||
#[arg(short, long)]
|
||||
pub output: Option<PathBuf>,
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use obikindex::KmerIndex;
|
||||
use obikphylo::siblings::{SnpAlignment, SnpAlignmentExt};
|
||||
use tracing::info;
|
||||
|
||||
// ── Family overlap: shared-family counts and the `--min-shared-family` /
|
||||
// `--family-overlap` diagnostics built from them ────────────────────────────
|
||||
//
|
||||
// Same variable-family columns as `--snp`'s pseudo-alignment. Off-diagonal
|
||||
// `[i][j]`: number of columns where both genome `i` and genome `j` carry a
|
||||
// call (neither is `∅`) — how much informative family content two genomes
|
||||
// actually share, the direct diagnostic for the rogue-taxon placement seen
|
||||
// under `--free-loss` (a genome with little overlap with anything else has
|
||||
// almost nothing left to constrain it). Diagonal `[i][i]` kept, deliberately
|
||||
// not skipped: with `i == j` the condition "both non-`∅`" degenerates to
|
||||
// "genome `i` non-`∅`", i.e. the total number of variable families genome
|
||||
// `i` carries at all — a genome-level count worth having alongside the
|
||||
// pairwise ones, not a separate computation.
|
||||
|
||||
/// `counts[i][j]` = number of variable-family columns where both genome `i`
|
||||
/// and genome `j` carry a call (neither is `∅`). Shared between
|
||||
/// `write_family_overlap_csv` and `--min-shared-family`'s auto-exclusion so
|
||||
/// both read off the same definition of "shared family".
|
||||
fn family_overlap_counts(alignment: &SnpAlignment) -> Vec<Vec<u64>> {
|
||||
let n = alignment.sequences.len();
|
||||
let mut counts = vec![vec![0u64; n]; n];
|
||||
for i in 0..n {
|
||||
for j in 0..n {
|
||||
counts[i][j] = alignment.sequences[i].iter().zip(alignment.sequences[j].iter())
|
||||
.filter(|&(&a, &b)| a != b'-' && b != b'-')
|
||||
.count() as u64;
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
/// Mean of row `i` in a `family_overlap_counts` matrix, excluding the
|
||||
/// diagonal — how much informative content genome `i` shares with the
|
||||
/// *average* other genome, the statistic `--min-shared-family` thresholds.
|
||||
fn mean_offdiag(counts: &[Vec<u64>], i: usize) -> f64 {
|
||||
let n = counts.len();
|
||||
let sum: u64 = (0..n).filter(|&j| j != i).map(|j| counts[i][j]).sum();
|
||||
sum as f64 / (n - 1) as f64
|
||||
}
|
||||
|
||||
pub(super) fn write_family_overlap_csv(alignment: &SnpAlignment, labels: &[String], output: &Option<PathBuf>) {
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_family_overlap.csv", p.display()))
|
||||
.unwrap_or_else(|| "family_overlap.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n = labels.len();
|
||||
let counts = family_overlap_counts(alignment);
|
||||
write!(f, "genome").unwrap();
|
||||
for g in labels { write!(f, ",{g}").unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
for (i, gi) in labels.iter().enumerate() {
|
||||
write!(f, "{gi}").unwrap();
|
||||
for j in 0..n {
|
||||
write!(f, ",{}", counts[i][j]).unwrap();
|
||||
}
|
||||
writeln!(f).unwrap();
|
||||
}
|
||||
info!("family overlap matrix → {path}");
|
||||
}
|
||||
|
||||
/// Sets `mask[i] = true` for every genome whose mean shared-family count
|
||||
/// (`mean_offdiag`) falls below `threshold`, skipping genomes already
|
||||
/// excluded (`mask[i]` already `true`, e.g. via `--exclude-genome`). Builds
|
||||
/// its own `SnpAlignment` pass — same redundant-per-flag pattern already
|
||||
/// used throughout `run()` (`--snp`/`--sankoff`/`--family-overlap` each call
|
||||
/// `snp_pseudo_alignment` independently too).
|
||||
pub(super) fn apply_min_shared_family_exclusion(
|
||||
idx: &KmerIndex,
|
||||
labels: &[String],
|
||||
threshold: f64,
|
||||
mask: &mut [bool],
|
||||
) {
|
||||
let alignment = idx.snp_pseudo_alignment(None, None).unwrap_or_else(|e| {
|
||||
eprintln!("error computing SNP pseudo-alignment for --min-shared-family: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let counts = family_overlap_counts(&alignment);
|
||||
for (i, label) in labels.iter().enumerate() {
|
||||
if mask[i] {
|
||||
continue; // already excluded via --exclude-genome
|
||||
}
|
||||
let mean = mean_offdiag(&counts, i);
|
||||
if mean < threshold {
|
||||
info!("--min-shared-family: excluding {label} (mean shared families = {mean:.1} < {threshold})");
|
||||
mask[i] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,38 +15,27 @@ use super::sankoff::{STATE_SYMBOL, state_index_table};
|
||||
// performed on it here is different, hence no "sankoff" in these names,
|
||||
// unlike `tnt::write_sankoff_tnt`/`phyg::write_sankoff_phyg`.
|
||||
//
|
||||
// Verified against the locally installed `iqtree3` binary/source (not just
|
||||
// its docs — see `DevDocMD/theory/evolutionary_distances.md`, "Next
|
||||
// direction: genuine ML branch lengths"), because the web documentation's
|
||||
// `-mdef` NEXUS route turned out not to apply to a plain (non-mixture)
|
||||
// custom morphology model. The real mechanism: pass a **file path**
|
||||
// directly as `-m`, containing (as whitespace/newline-separated numbers)
|
||||
// the lower-triangular exchangeability matrix `R` (`k(k-1)/2` values, PAML
|
||||
// row-major order) immediately followed by the `k` state frequencies `π`
|
||||
// on the same stream — `ModelMarkov::readRates`/`readStateFreq` read them
|
||||
// in that exact order, no header, no separator required.
|
||||
// The mechanism: pass a **file path** directly as `-m`, containing (as
|
||||
// whitespace/newline-separated numbers) the lower-triangular exchangeability
|
||||
// matrix `R` (`k(k-1)/2` values, PAML row-major order) immediately followed
|
||||
// by the `k` state frequencies `π` on the same stream —
|
||||
// `ModelMarkov::readRates`/`readStateFreq` read them in that exact order, no
|
||||
// header, no separator required.
|
||||
//
|
||||
// `R` is recovered from the calibrated Sankoff cost matrix via
|
||||
// `R(a,b) = exp(-cost(a,b))` (the cost is `-ln(rate)`, see "A concrete
|
||||
// Sankoff cost matrix"), symmetric by construction (the underlying tally
|
||||
// never captured direction). `π` is the real, empirical, non-uniform
|
||||
// marginal frequency of each state across the whole alignment — precise
|
||||
// enough at this sample size (908k+ sites) without spending IQ-TREE's own
|
||||
// `+FO` ML degrees of freedom re-estimating it (checked: IQ-TREE's `+F`
|
||||
// doesn't work as a shortcut here either, a custom-file model always
|
||||
// requires the frequency line in the file itself). IQ-TREE reconstructs
|
||||
// the (generally asymmetric) rate matrix internally as
|
||||
// `Q(i,j) = R(i,j)·π_j` — reversible for *any* `π`, not just uniform,
|
||||
// because `R` is symmetric.
|
||||
// `R(a,b) = exp(-cost(a,b))` (the cost is `-ln(rate)`), symmetric by
|
||||
// construction (the underlying tally never captured direction). `π` is the
|
||||
// real, empirical, non-uniform marginal frequency of each state across the
|
||||
// whole alignment. IQ-TREE reconstructs the (generally asymmetric) rate
|
||||
// matrix internally as `Q(i,j) = R(i,j)·π_j` — reversible for *any* `π`, not
|
||||
// just uniform, because `R` is symmetric.
|
||||
//
|
||||
// IQ-TREE infers its state count from the highest-ordinal symbol actually
|
||||
// present in the alignment, not from a declared count (`--seqtype
|
||||
// MORPH{N}` was tested and does not override this for real ML analysis,
|
||||
// only for the `--alisim` simulator). So states that never occur anywhere
|
||||
// in this particular alignment are dropped, and the survivors are
|
||||
// renumbered compactly (`0..k-1`, order preserved) rather than leaving
|
||||
// gaps that would silently misalign every value IQ-TREE reads. Both the
|
||||
// model and the alignment must agree on this same renumbering, so it's
|
||||
// present in the alignment, not from a declared count. So states that never
|
||||
// occur anywhere in this particular alignment are dropped, and the
|
||||
// survivors are renumbered compactly (`0..k-1`, order preserved) rather than
|
||||
// leaving gaps that would silently misalign every value IQ-TREE reads. Both
|
||||
// the model and the alignment must agree on this same renumbering, so it's
|
||||
// computed once (`CompactAlphabet`) and shared between them.
|
||||
|
||||
const IQTREE_STATE_SYMBOL: [char; 16] = [
|
||||
@@ -70,19 +59,16 @@ impl CompactAlphabet {
|
||||
|
||||
/// Under `--free-loss`, non-detection (`-`) becomes IQ-TREE's own missing
|
||||
/// symbol (`?`) — ignored when IQ-TREE checks a site's constancy for
|
||||
/// `+ASC`. A family kept as "variable" by `snp_pseudo_alignment`
|
||||
/// (`family_size() >= 2`, a whole-annex property, oblivious to any one
|
||||
/// column's actual calls) can still turn constant *among the genomes that
|
||||
/// actually have data* once the non-detected ones are excluded from that
|
||||
/// check — the same failure mode as the `--exclude-genome`/`drop_excluded`
|
||||
/// fix in `mod.rs` (see `DevDocMD/theory/evolutionary_distances.md`, "Two
|
||||
/// consistency bugs found and fixed post-implementation"), just triggered
|
||||
/// by hiding cells instead of dropping whole rows. Same remedy: rescan
|
||||
/// columns treating `-` as ignored, drop any where the remaining calls
|
||||
/// agree on a single state. Parsimony (`--tnt`/`--phyg`) has no
|
||||
/// no-invariant-site requirement, so this only runs on IQ-TREE's own copy
|
||||
/// of the alignment, never mutating the one the caller also hands to those
|
||||
/// two exports.
|
||||
/// `+ASC`. A family kept as "variable" by the sampling (`family_size() >=
|
||||
/// 2`, a whole-annex property, oblivious to any one column's actual calls)
|
||||
/// can still turn constant *among the genomes that actually have data* once
|
||||
/// the non-detected ones are excluded from that check — the same failure
|
||||
/// mode `--exclude-genome` already had to account for, just triggered by
|
||||
/// hiding cells instead of dropping whole rows. Same remedy: rescan columns
|
||||
/// treating `-` as ignored, drop any where the remaining calls agree on a
|
||||
/// single state. Parsimony (`--tnt`/`--phyg`) has no no-invariant-site
|
||||
/// requirement, so this only runs on IQ-TREE's own copy of the alignment,
|
||||
/// never mutating the one the caller also hands to those two exports.
|
||||
fn drop_ascertainment_noninformative(alignment: &SnpAlignment) -> SnpAlignment {
|
||||
let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0);
|
||||
let keep: Vec<bool> = (0..n_sites)
|
||||
@@ -114,7 +100,7 @@ fn drop_ascertainment_noninformative(alignment: &SnpAlignment) -> SnpAlignment {
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
SnpAlignment { sequences }
|
||||
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone() }
|
||||
}
|
||||
|
||||
/// Recode every occurrence of a byte in `symbols` to `-` — the same
|
||||
@@ -133,7 +119,7 @@ fn recode_symbols_as_absent(alignment: &SnpAlignment, symbols: &[u8]) -> SnpAlig
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
SnpAlignment { sequences }
|
||||
SnpAlignment { sequences, genome_indices: alignment.genome_indices.clone() }
|
||||
}
|
||||
|
||||
fn compact_alphabet(alignment: &SnpAlignment, free_loss: bool) -> CompactAlphabet {
|
||||
@@ -212,7 +198,11 @@ fn write_iqtree_states_csv(alphabet: &CompactAlphabet, output: &Option<PathBuf>)
|
||||
/// Write the `R` (exchangeability) + `π` (frequencies) model file IQ-TREE's
|
||||
/// `-m <file>+ASC` reads. Returns the path, so the caller can print a
|
||||
/// single combined "how to run this" message once the alignment is also
|
||||
/// written.
|
||||
/// written. The one bit of real computation this whole adapter does:
|
||||
/// `R(a,b) = exp(-cost(a,b))`, recovering the exchangeability rate a
|
||||
/// calibrated Sankoff parsimony cost implies for a continuous-time model —
|
||||
/// a one-line inversion of the cost matrix's own `-ln(rate)` construction,
|
||||
/// not a new estimate.
|
||||
fn write_iqtree_model(
|
||||
matrix: &[[f64; 16]; 16],
|
||||
alphabet: &CompactAlphabet,
|
||||
@@ -260,7 +250,7 @@ fn write_iqtree_model(
|
||||
/// Write the pseudo-alignment recoded to the same compact `0..k-1` alphabet
|
||||
/// as `write_iqtree_model`'s matrix — not `--sankoff`'s own IUPAC alphabet,
|
||||
/// since IQ-TREE needs the symbol ordinal itself to match the surviving
|
||||
/// state count (see this module's own doc comment on `MORPH{N}`).
|
||||
/// state count (see this module's own doc comment on state inference).
|
||||
fn write_iqtree_alignment(
|
||||
alignment: &SnpAlignment,
|
||||
labels: &[String],
|
||||
@@ -279,7 +269,7 @@ fn write_iqtree_alignment(
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0);
|
||||
for (label, seq) in labels.iter().zip(alignment.sequences.iter()) {
|
||||
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) {
|
||||
let recoded: Vec<u8> = seq
|
||||
.iter()
|
||||
.map(|&b| {
|
||||
@@ -295,7 +285,7 @@ fn write_iqtree_alignment(
|
||||
.collect();
|
||||
write_record(
|
||||
&recoded,
|
||||
label,
|
||||
&labels[g],
|
||||
&[("n_sites", JsonVal::Num(n_sites as u64))],
|
||||
&mut f,
|
||||
)
|
||||
@@ -335,12 +325,7 @@ pub(super) fn write_iqtree(
|
||||
|
||||
// `--iqtree-min-freq`: fold rare (likely-noisy) states into the same
|
||||
// missing-data treatment `-` already gets under `--free-loss`, then
|
||||
// recompute the alphabet on the further-filtered alignment — see
|
||||
// `args.rs`'s docs on `--iqtree-min-freq` and
|
||||
// `DevDocMD/theory/evolutionary_distances.md` for why (real data:
|
||||
// states encoding 3-4 simultaneous central bases land in exactly this
|
||||
// low-frequency range and correlate with `iqtree3`'s own numerical
|
||||
// instability warnings).
|
||||
// recompute the alphabet on the further-filtered alignment.
|
||||
let refiltered;
|
||||
let alignment = if free_loss {
|
||||
let low_freq_symbols: Vec<u8> = alphabet
|
||||
@@ -397,17 +382,18 @@ pub(super) fn write_iqtree(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn alignment(sequences: Vec<Vec<u8>>) -> SnpAlignment {
|
||||
let genome_indices = (0..sequences.len()).collect();
|
||||
SnpAlignment { sequences, genome_indices }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_loss_excludes_absent_state_and_freq_sums_to_one() {
|
||||
// 3 genomes, 2 sites. Site 0: g1='A', g2='C', g3='-' (absent).
|
||||
// Site 1: g1='-', g2='-', g3='G'. Under free_loss, every '-' must
|
||||
// be excluded from the frequency count entirely (not folded into
|
||||
// state 0) — reproduces a user-reported suspicion that state 0
|
||||
// ("absent") was still being counted despite being recoded to `?`
|
||||
// (IQ-TREE's own missing symbol) in the alignment actually written.
|
||||
let alignment = SnpAlignment {
|
||||
sequences: vec![vec![b'A', b'-'], vec![b'C', b'-'], vec![b'-', b'G']],
|
||||
};
|
||||
// state 0).
|
||||
let alignment = alignment(vec![vec![b'A', b'-'], vec![b'C', b'-'], vec![b'-', b'G']]);
|
||||
|
||||
let alphabet = compact_alphabet(&alignment, true);
|
||||
|
||||
@@ -427,9 +413,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn without_free_loss_absent_state_is_counted_normally() {
|
||||
let alignment = SnpAlignment {
|
||||
sequences: vec![vec![b'A', b'-'], vec![b'C', b'-'], vec![b'-', b'G']],
|
||||
};
|
||||
let alignment = alignment(vec![vec![b'A', b'-'], vec![b'C', b'-'], vec![b'-', b'G']]);
|
||||
|
||||
let alphabet = compact_alphabet(&alignment, false);
|
||||
|
||||
@@ -449,12 +433,10 @@ mod tests {
|
||||
fn states_csv_maps_compact_symbols_back_to_canonical_ones() {
|
||||
// 'A' (state 1) and 'G' (state 4) occur, '-' (state 0) excluded by
|
||||
// --free-loss — compact index 0 -> 'A', compact index 1 -> 'G'.
|
||||
let alignment = SnpAlignment {
|
||||
sequences: vec![vec![b'A', b'-'], vec![b'-', b'G']],
|
||||
};
|
||||
let alignment = alignment(vec![vec![b'A', b'-'], vec![b'-', b'G']]);
|
||||
let alphabet = compact_alphabet(&alignment, true);
|
||||
let output = Some(
|
||||
std::env::temp_dir().join(format!("obikmer_test_iqtree_states_{}", std::process::id())),
|
||||
std::env::temp_dir().join(format!("obikmer2_test_iqtree_states_{}", std::process::id())),
|
||||
);
|
||||
|
||||
let path = write_iqtree_states_csv(&alphabet, &output);
|
||||
@@ -491,11 +473,11 @@ mod tests {
|
||||
sequences[0].push(b'M');
|
||||
sequences[1].push(b'A');
|
||||
sequences[2].push(b'-');
|
||||
let alignment = SnpAlignment { sequences };
|
||||
let alignment = alignment(sequences);
|
||||
let labels = vec!["g1".to_string(), "g2".to_string(), "g3".to_string()];
|
||||
let matrix = [[0.0f64; 16]; 16];
|
||||
let prefix = std::env::temp_dir().join(format!(
|
||||
"obikmer_test_iqtree_minfreq_{}",
|
||||
"obikmer2_test_iqtree_minfreq_{}",
|
||||
std::process::id()
|
||||
));
|
||||
let output = Some(prefix.clone());
|
||||
|
||||
+327
-245
@@ -1,70 +1,54 @@
|
||||
mod args;
|
||||
mod family_overlap;
|
||||
mod iqtree;
|
||||
mod outputs;
|
||||
mod phyg;
|
||||
mod phylip;
|
||||
mod sankoff;
|
||||
mod tnt;
|
||||
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::sync::Arc;
|
||||
|
||||
use kodama::{Method, linkage};
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikindex::KmerIndex;
|
||||
use obikphylo::{
|
||||
cardinality_transition_probs, composition_transition_probs, pairwise_cost_matrix,
|
||||
siblings::{
|
||||
DistanceExt, EntropyBias, RawSnpDistanceOutput, SankoffBundleExt, ShannonEntropyExt,
|
||||
SiblingExt, SiblingStatsExt, SnpAlignment, SnpAlignmentExt,
|
||||
},
|
||||
use obikphylo::siblings::{
|
||||
EntropyBias, SiblingExt, cardinality_transition_probs, composition_transition_probs,
|
||||
pairwise_cost_matrix,
|
||||
};
|
||||
use obikphylo::{Metrics, neighbor_joining, upgma};
|
||||
use obisys::{Reporter, Stage};
|
||||
use speedytree::{DistanceMatrix, Hybrid, NeighborJoiningSolver, to_newick};
|
||||
use tracing::info;
|
||||
|
||||
pub use args::PhyloArgs;
|
||||
use family_overlap::{apply_min_shared_family_exclusion, write_family_overlap_csv};
|
||||
use iqtree::write_iqtree;
|
||||
use outputs::{write_raw_snp_counts_csv, write_raw_snp_distance_csv, write_sibling_hist_csv, write_sibling_stats_csv, write_snp_fasta, upgma_to_newick};
|
||||
use phyg::write_sankoff_phyg;
|
||||
use phylip::write_phylip_relaxed;
|
||||
use sankoff::{write_sankoff_alignment_fasta, write_sankoff_matrix_csv, write_sankoff_params};
|
||||
use tnt::write_sankoff_tnt;
|
||||
|
||||
pub use args::PhyloArgs;
|
||||
|
||||
pub fn run(args: PhyloArgs) {
|
||||
let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
let idx = Arc::new(KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}));
|
||||
|
||||
|
||||
let labels: Vec<String> = idx.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
}).iter().map(|g| g.label.clone()).collect();
|
||||
let labels: Vec<String> = idx
|
||||
.meta()
|
||||
.genomes()
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
.iter()
|
||||
.map(|g| g.label.clone())
|
||||
.collect();
|
||||
let n = labels.len();
|
||||
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
// ── Entropy-biased selection (`--entropy`/`--entropy-sd`) ──────────────
|
||||
// Activates as soon as either is given; the other defaults to 1.0/0.5.
|
||||
// See `DevDocMD/architecture/siblings.md`, "Entropy-biased selection".
|
||||
let entropy_bias = if args.entropy.is_some() || args.entropy_sd.is_some() {
|
||||
Some(EntropyBias {
|
||||
mu: args.entropy.unwrap_or(1.0),
|
||||
sigma: args.entropy_sd.unwrap_or(0.5),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// ── Genome exclusion (`--exclude-genome`) ───────────────────────────────
|
||||
// Applied by zeroing a `RawSnpDistanceOutput`'s excluded rows/columns
|
||||
// (`zero_excluded_pairs`) — `base_pair_tally`/`cardinality_tally`
|
||||
// already skip any pair with zero total counts, so this needs no
|
||||
// change to `obikindex`'s traversal — and by dropping the excluded
|
||||
// genome's row from a `SnpAlignment` plus the matching label
|
||||
// (`drop_excluded`), since an all-`∅` row for an "excluded" genome
|
||||
// would otherwise still
|
||||
// reach TNT/PhyG/IQ-TREE as a real (empty) taxon.
|
||||
// ── Genome exclusion (`--exclude-genome`) ───────────────────────────────────
|
||||
// Resolved once, up front: `snp_pseudo_alignment` needs it baked into
|
||||
// sampling itself (see its own docs), and the distance/shared-kmer CSV
|
||||
// writers below just skip these rows/columns at write time — the
|
||||
// underlying `cache.distance(...)` computation is unaffected either way.
|
||||
let exclude_mask: Vec<bool> = {
|
||||
let mut mask = vec![false; n];
|
||||
for label in &args.exclude_genome {
|
||||
@@ -76,259 +60,371 @@ pub fn run(args: PhyloArgs) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(threshold) = args.min_shared_family {
|
||||
apply_min_shared_family_exclusion(&idx, &labels, threshold, &mut mask);
|
||||
}
|
||||
mask
|
||||
};
|
||||
let zero_excluded_pairs = |result: &mut RawSnpDistanceOutput| {
|
||||
for i in 0..n {
|
||||
if !exclude_mask[i] {
|
||||
continue;
|
||||
}
|
||||
for j in 0..n {
|
||||
result.snp[[i, j]] = 0;
|
||||
result.snp[[j, i]] = 0;
|
||||
result.shared[[i, j]] = 0;
|
||||
result.shared[[j, i]] = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
// `snp_pseudo_alignment`'s "variable family" criterion
|
||||
// (`mask.family_size() >= 2`) is a property of the annex, computed
|
||||
// over *every* genome in the index — unaffected by `--exclude-genome`.
|
||||
// So dropping excluded rows alone can leave columns that are variable
|
||||
// only thanks to an excluded genome now monomorphic among the
|
||||
// survivors — silently wrong data for TNT/PhyG, and a hard failure
|
||||
// for IQ-TREE's `+ASC` (verified: excluding 2 taxa on the 20-genome
|
||||
// benchmark left 116,351 such columns). Re-check variability among the
|
||||
// *kept* genomes only, after dropping rows, and drop those columns too.
|
||||
let drop_excluded = |alignment: SnpAlignment| -> (SnpAlignment, Vec<String>) {
|
||||
let mut sequences: Vec<Vec<u8>> = alignment.sequences.into_iter().enumerate()
|
||||
.filter(|(i, _)| !exclude_mask[*i])
|
||||
.map(|(_, seq)| seq)
|
||||
.collect();
|
||||
let kept_labels: Vec<String> = labels.iter().enumerate()
|
||||
.filter(|(i, _)| !exclude_mask[*i])
|
||||
.map(|(_, l)| l.clone())
|
||||
.collect();
|
||||
|
||||
if exclude_mask.iter().any(|&excluded| excluded) && !sequences.is_empty() {
|
||||
let n_sites = sequences[0].len();
|
||||
let keep_col: Vec<bool> = (0..n_sites)
|
||||
.map(|site| sequences.iter().any(|seq| seq[site] != sequences[0][site]))
|
||||
.collect();
|
||||
for seq in &mut sequences {
|
||||
let mut kept = Vec::with_capacity(seq.len());
|
||||
for (site, &b) in seq.iter().enumerate() {
|
||||
if keep_col[site] {
|
||||
kept.push(b);
|
||||
}
|
||||
}
|
||||
*seq = kept;
|
||||
}
|
||||
}
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
(SnpAlignment { sequences }, kept_labels)
|
||||
};
|
||||
// Every partition/layer this needs is opened once, up front, and
|
||||
// handed to `Metrics::distance`/`SiblingExt::build_sibling_annex`
|
||||
// — see `obikquery`'s own use of `IndexCache` for the same reasoning
|
||||
// (one open, many in-memory reads).
|
||||
let cache = IndexCache::new(Arc::clone(&idx), None);
|
||||
|
||||
// ── Sibling-count/minorant annex (independent of the distance metric) ──
|
||||
// Construction (`--sibling-annex`) and stats (`--sibling-stats`) are
|
||||
// deliberately decoupled: the annex is meant to be (re)built routinely,
|
||||
// the distribution only occasionally, on demand.
|
||||
// Meant to be (re)built routinely, ahead of any SNP-family distance
|
||||
// computation that will later consume it.
|
||||
if args.sibling_annex {
|
||||
// Writes into the index directory — hold an exclusive lock for the
|
||||
// duration so a second, concurrent `--sibling-annex` run on the same
|
||||
// index can't corrupt these writes (see obisys::DirLock).
|
||||
// duration so a second, concurrent `--sibling-annex` run on the
|
||||
// same index can't corrupt these writes (see obisys::DirLock).
|
||||
let _lock = obisys::DirLock::acquire(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error locking index directory {}: {e}", args.index.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
info!("building sibling-count/minorant annex");
|
||||
let t = Stage::start("sibling_annex");
|
||||
idx.build_sibling_annex().unwrap_or_else(|e| {
|
||||
cache.build_sibling_annex().unwrap_or_else(|e| {
|
||||
eprintln!("error building sibling annex: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
}
|
||||
|
||||
// ── Sibling-count distribution (`--sibling-stats`) ──────────────────────────
|
||||
if args.sibling_stats {
|
||||
let t = Stage::start("sibling_stats");
|
||||
let stats = idx.sibling_annex_stats().unwrap_or_else(|e| {
|
||||
let stats = cache.sibling_annex_stats().unwrap_or_else(|e| {
|
||||
eprintln!("error computing sibling-annex stats: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
write_sibling_stats_csv(&stats, &labels, &args.output);
|
||||
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_siblings.csv", p.display()))
|
||||
.unwrap_or_else(|| "siblings.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
// One row per genome (4 columns, family size 1-4: number of
|
||||
// families of that size for which the genome carries at least one
|
||||
// member), plus a `global` row — the actual deduplicated
|
||||
// family-size histogram (`stats.counts`), NOT a sum of the
|
||||
// per-genome columns (a family shared by several genomes would
|
||||
// otherwise be counted once per genome it appears in).
|
||||
writeln!(f, "genome,1,2,3,4").unwrap();
|
||||
for (label, counts) in labels.iter().zip(stats.per_genome.iter()) {
|
||||
writeln!(f, "{label},{},{},{},{}", counts[0], counts[1], counts[2], counts[3]).unwrap();
|
||||
}
|
||||
writeln!(
|
||||
f, "global,{},{},{},{}",
|
||||
stats.counts[0], stats.counts[1], stats.counts[2], stats.counts[3],
|
||||
).unwrap();
|
||||
info!("sibling-count distribution → {path}");
|
||||
}
|
||||
|
||||
// ── Family-size histogram (`--sibling-hist`) ────────────────────────────────
|
||||
if args.sibling_hist {
|
||||
let t = Stage::start("sibling_hist");
|
||||
let counts = idx.sibling_family_size_histogram().unwrap_or_else(|e| {
|
||||
let counts = cache.sibling_family_size_histogram().unwrap_or_else(|e| {
|
||||
eprintln!("error computing sibling family-size histogram: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
write_sibling_hist_csv(&counts, &args.output);
|
||||
}
|
||||
if args.raw_snp_distance {
|
||||
let t = Stage::start("raw_snp_distance");
|
||||
let mut result = idx.raw_snp_distance().unwrap_or_else(|e| {
|
||||
eprintln!("error computing raw SNP distance: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
zero_excluded_pairs(&mut result);
|
||||
write_raw_snp_distance_csv(&result, &labels, &args.output);
|
||||
}
|
||||
if args.raw_snp_counts {
|
||||
let t = Stage::start("raw_snp_distance");
|
||||
let mut result = idx.raw_snp_distance().unwrap_or_else(|e| {
|
||||
eprintln!("error computing raw SNP distance: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
zero_excluded_pairs(&mut result);
|
||||
write_raw_snp_counts_csv(&result, &labels, &args.output);
|
||||
}
|
||||
if args.snp {
|
||||
let t = Stage::start("snp_pseudo_alignment");
|
||||
let alignment = idx.snp_pseudo_alignment(args.subsample, entropy_bias).unwrap_or_else(|e| {
|
||||
eprintln!("error computing SNP pseudo-alignment: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
let (alignment, kept_labels) = drop_excluded(alignment);
|
||||
write_snp_fasta(&alignment, &kept_labels, &args.output);
|
||||
}
|
||||
if args.family_overlap {
|
||||
let t = Stage::start("snp_pseudo_alignment");
|
||||
let alignment = idx.snp_pseudo_alignment(args.subsample, entropy_bias).unwrap_or_else(|e| {
|
||||
eprintln!("error computing SNP pseudo-alignment: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
let (alignment, kept_labels) = drop_excluded(alignment);
|
||||
write_family_overlap_csv(&alignment, &kept_labels, &args.output);
|
||||
}
|
||||
if args.shannon {
|
||||
let t = Stage::start("shannon_entropy");
|
||||
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_shannon.csv", p.display()))
|
||||
.unwrap_or_else(|| "shannon.csv".into());
|
||||
idx.shannon_entropy_csv(std::path::Path::new(&path), args.subsample, entropy_bias).unwrap_or_else(|e| {
|
||||
.map(|p| format!("{}_sibling_hist.csv", p.display()))
|
||||
.unwrap_or_else(|| "sibling_hist.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
writeln!(f, "size,count").unwrap();
|
||||
for (size, count) in counts.iter().enumerate() {
|
||||
writeln!(f, "{},{count}", size + 1).unwrap();
|
||||
}
|
||||
let total: u64 = counts.iter().sum();
|
||||
info!(
|
||||
"family-size histogram → {path} (total {total} famil{})",
|
||||
if total == 1 { "y" } else { "ies" }
|
||||
);
|
||||
}
|
||||
|
||||
// ── Family Overlap matrix (`--family-overlap`) ──────────────────────────────
|
||||
if args.family_overlap {
|
||||
let t = Stage::start("family_overlap");
|
||||
let overlap = cache.family_overlap().unwrap_or_else(|e| {
|
||||
eprintln!("error computing family overlap: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_family_overlap.csv", p.display()))
|
||||
.unwrap_or_else(|| "family_overlap.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
write!(f, "genome").unwrap();
|
||||
for label in &labels { write!(f, ",{label}").unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
for (i, label) in labels.iter().enumerate() {
|
||||
write!(f, "{label}").unwrap();
|
||||
for j in 0..n { write!(f, ",{}", overlap.get(i, j)).unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
}
|
||||
info!("family-overlap matrix → {path}");
|
||||
}
|
||||
|
||||
// ── Shannon entropy report (`--shannon`) ────────────────────────────────────
|
||||
if args.shannon {
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_entropy.csv", p.display()))
|
||||
.unwrap_or_else(|| "entropy.csv".into());
|
||||
info!("computing per-family Shannon entropy");
|
||||
let t = Stage::start("shannon_entropy");
|
||||
cache.shannon_entropy_csv(std::path::Path::new(&path)).unwrap_or_else(|e| {
|
||||
eprintln!("error computing Shannon entropy: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
info!("per-family Shannon entropy → {path}");
|
||||
info!("entropy report → {path}");
|
||||
}
|
||||
if args.sankoff || args.tnt || args.phyg || args.iqtree {
|
||||
// One shared, possibly-subsampled/entropy-biased selection, one
|
||||
// pass to derive `included[i,j]`, one more fused pass for
|
||||
// base_pair_tally + cardinality_tally + the pseudo-alignment — see
|
||||
// `DevDocMD/architecture/siblings.md`, "`--free-loss`/`--tnt`
|
||||
// pipeline" and "Wired into `pack`...".
|
||||
let t = Stage::start("raw_snp_distance");
|
||||
let bundle = idx.sankoff_bundle(args.subsample, entropy_bias, args.sankoff_ratio_ceiling, &exclude_mask).unwrap_or_else(|e| {
|
||||
eprintln!("error computing sankoff inputs: {e}");
|
||||
|
||||
// ── `--min-shared-family` auto-exclusion ────────────────────────────────────
|
||||
// Layered on top of `--exclude-genome`, not instead of it — a separate
|
||||
// mask (not folded into `exclude_mask` itself) since it must reach
|
||||
// `--pseudo-alignment`/`--sankoff`/`snp-*` `--distance` only, never the
|
||||
// whole-index metrics' `kept`/`--shared-kmers` output (see
|
||||
// `args::PhyloArgs::min_shared_family`'s own docs on why).
|
||||
let snp_exclude_mask: Vec<bool> = match args.min_shared_family {
|
||||
Some(threshold) => {
|
||||
let overlap = cache.family_overlap().unwrap_or_else(|e| {
|
||||
eprintln!("error computing family overlap: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let mut mask = exclude_mask.clone();
|
||||
for (g, excluded) in mask.iter_mut().enumerate() {
|
||||
if *excluded {
|
||||
continue;
|
||||
}
|
||||
let mean = overlap.mean_row(g);
|
||||
if mean < threshold {
|
||||
info!(
|
||||
"auto-excluding {} (--min-shared-family: mean shared-family count {mean:.1} < {threshold})",
|
||||
labels[g]
|
||||
);
|
||||
*excluded = true;
|
||||
}
|
||||
}
|
||||
mask
|
||||
}
|
||||
None => exclude_mask.clone(),
|
||||
};
|
||||
|
||||
// Shared by `--pseudo-alignment` and `--sankoff` — same activation rule:
|
||||
// either flag given activates entropy-biased sampling, the other
|
||||
// defaults to 1.0/0.5.
|
||||
let entropy_bias = if args.entropy.is_some() || args.entropy_sd.is_some() {
|
||||
Some(EntropyBias {
|
||||
mu: args.entropy.unwrap_or(1.0),
|
||||
sigma: args.entropy_sd.unwrap_or(0.5),
|
||||
})
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// ── SNP pseudo-alignment (`--pseudo-alignment`) ─────────────────────────────
|
||||
if args.pseudo_alignment {
|
||||
let Some(subsample_n) = args.subsample else {
|
||||
eprintln!("error: --pseudo-alignment requires --subsample <N>");
|
||||
std::process::exit(1);
|
||||
});
|
||||
};
|
||||
|
||||
info!("sampling SNP pseudo-alignment (target {subsample_n} site(s))");
|
||||
let t = Stage::start("pseudo_alignment");
|
||||
let alignment = cache
|
||||
.snp_pseudo_alignment(subsample_n, args.free_loss, args.no_ambiguity, &snp_exclude_mask, entropy_bias)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error building pseudo-alignment: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
let (base_tally, card_tally) = (bundle.base_pair_tally, bundle.cardinality_tally);
|
||||
|
||||
let p_card = cardinality_transition_probs(&card_tally);
|
||||
let p_comp = composition_transition_probs(&base_tally);
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_alignment.fasta", p.display()))
|
||||
.unwrap_or_else(|| "alignment.fasta".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n_sites = alignment.sequences.first().map_or(0, Vec::len);
|
||||
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) {
|
||||
obifastwrite::write_plain_record(seq, &labels[g], &mut f).unwrap();
|
||||
}
|
||||
info!("pseudo-alignment ({n_sites} site(s), {} genome(s)) → {path}", alignment.genome_indices.len());
|
||||
}
|
||||
|
||||
// ── Sankoff cost-matrix calibration (`--sankoff`, `--tnt`, `--phyg`, `--iqtree`) ──
|
||||
if args.sankoff || args.tnt || args.phyg || args.iqtree {
|
||||
let Some(subsample_n) = args.subsample else {
|
||||
eprintln!("error: --sankoff requires --subsample <N>");
|
||||
std::process::exit(1);
|
||||
};
|
||||
|
||||
info!("sampling Sankoff calibration bundle (target {subsample_n} site(s))");
|
||||
let t = Stage::start("sankoff_bundle");
|
||||
let bundle = cache
|
||||
.sankoff_bundle(
|
||||
subsample_n,
|
||||
args.free_loss,
|
||||
args.no_ambiguity,
|
||||
&snp_exclude_mask,
|
||||
entropy_bias,
|
||||
args.sankoff_ratio_ceiling,
|
||||
)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error computing Sankoff calibration bundle: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
|
||||
let p_card = cardinality_transition_probs(&bundle.cardinality_tally);
|
||||
let p_comp = composition_transition_probs(&bundle.base_pair_tally);
|
||||
let matrix = pairwise_cost_matrix(&p_card, &p_comp, args.free_loss);
|
||||
write_sankoff_matrix_csv(&matrix, &args.output);
|
||||
write_sankoff_params(&card_tally, &p_card, &base_tally, &p_comp, args.sankoff_ratio_ceiling, &args.output);
|
||||
|
||||
let (alignment, kept_labels) = drop_excluded(bundle.alignment);
|
||||
write_sankoff_alignment_fasta(&alignment, &kept_labels, &args.output, args.free_loss);
|
||||
write_sankoff_matrix_csv(&matrix, &args.output);
|
||||
write_sankoff_params(
|
||||
&bundle.cardinality_tally,
|
||||
&p_card,
|
||||
&bundle.base_pair_tally,
|
||||
&p_comp,
|
||||
args.sankoff_ratio_ceiling,
|
||||
&args.output,
|
||||
);
|
||||
write_sankoff_alignment_fasta(&bundle.alignment, &labels, &args.output, args.free_loss);
|
||||
|
||||
if args.tnt {
|
||||
write_sankoff_tnt(&matrix, &alignment, &kept_labels, &args.output, args.sankoff_cost_scale, args.free_loss);
|
||||
write_sankoff_tnt(
|
||||
&matrix,
|
||||
&bundle.alignment,
|
||||
&labels,
|
||||
&args.output,
|
||||
args.sankoff_cost_scale,
|
||||
args.free_loss,
|
||||
);
|
||||
}
|
||||
if args.phyg {
|
||||
write_sankoff_phyg(&matrix, &args.output, args.sankoff_cost_scale);
|
||||
}
|
||||
if args.iqtree {
|
||||
write_iqtree(&matrix, &alignment, &kept_labels, &args.output, args.free_loss, args.iqtree_min_freq);
|
||||
write_iqtree(
|
||||
&matrix,
|
||||
&bundle.alignment,
|
||||
&labels,
|
||||
&args.output,
|
||||
args.free_loss,
|
||||
args.iqtree_min_freq,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// `--sibling-annex`/`--sibling-stats`/`--raw-snp-distance`/`--snp`/
|
||||
// `--sankoff`/`--tnt` are their own operation, not a modifier on top of
|
||||
// a distance-metric computation — a metric was never requested by
|
||||
// asking for any of them, so there is nothing for the rest of this
|
||||
// function to compute. Not a historical accident to keep: stop here
|
||||
// rather than always also running a Jaccard (or whichever `--metric`
|
||||
// defaults to) pass and printing an unrequested matrix.
|
||||
if args.sibling_annex
|
||||
|| args.sibling_stats
|
||||
|| args.sibling_hist
|
||||
|| args.raw_snp_distance
|
||||
|| args.raw_snp_counts
|
||||
|| args.snp
|
||||
|| args.family_overlap
|
||||
|| args.shannon
|
||||
|| args.sankoff
|
||||
|| args.tnt
|
||||
|| args.phyg
|
||||
|| args.iqtree
|
||||
{
|
||||
rep.print();
|
||||
return;
|
||||
}
|
||||
|
||||
info!(
|
||||
"computing {:?} distances for {} genome(s)",
|
||||
args.metric, n
|
||||
);
|
||||
|
||||
let need_shared = args.shared_kmers || args.nj || args.upgma;
|
||||
let t = Stage::start("distance");
|
||||
let result = idx
|
||||
.distance(args.metric.into(), need_shared, args.presence_threshold)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error computing distances: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
|
||||
// ── Distance matrix → CSV ─────────────────────────────────────────────────
|
||||
let write_dist_csv = |w: &mut dyn Write| {
|
||||
write!(w, "genome").unwrap();
|
||||
for g in &labels { write!(w, ",{g}").unwrap(); }
|
||||
writeln!(w).unwrap();
|
||||
for (i, g) in labels.iter().enumerate() {
|
||||
write!(w, "{g}").unwrap();
|
||||
for j in 0..n {
|
||||
write!(w, ",{:.6}", result.matrix[[i, j]]).unwrap();
|
||||
// ── Distance computation: classic whole-index metric vs. `snp-*` ───────────
|
||||
// Two genuinely different code paths behind one `--distance` value — see
|
||||
// `args::DistanceArg`'s own docs.
|
||||
let (matrix, shared_kmers) = match args.distance.as_classic() {
|
||||
Some(metric) => {
|
||||
info!("computing {metric:?} distances for {n} genome(s)");
|
||||
let need_shared = args.shared_kmers || args.nj || args.upgma;
|
||||
let t = Stage::start("distance");
|
||||
let result = cache
|
||||
.distance(metric, need_shared, args.presence_threshold)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error computing distances: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
(result.matrix, result.shared_kmers)
|
||||
}
|
||||
None => {
|
||||
if args.shared_kmers {
|
||||
eprintln!("error: --shared-kmers has no meaning for a snp-* --distance value");
|
||||
std::process::exit(1);
|
||||
}
|
||||
let kind = args.distance.as_snp().expect("DistanceArg is always classic or snp");
|
||||
info!(
|
||||
"computing {kind:?} SNP distance for {n} genome(s){}",
|
||||
match args.subsample {
|
||||
Some(n) => format!(" (subsampled, target {n} site(s))"),
|
||||
None => " (exhaustive)".into(),
|
||||
}
|
||||
);
|
||||
let t = Stage::start("snp_distance");
|
||||
let matrix = cache
|
||||
.snp_distance(
|
||||
kind,
|
||||
args.subsample,
|
||||
args.free_loss,
|
||||
args.no_ambiguity,
|
||||
&snp_exclude_mask,
|
||||
entropy_bias,
|
||||
args.gamma_shape,
|
||||
)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error computing SNP distance: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.push(t.stop());
|
||||
(matrix, None)
|
||||
}
|
||||
};
|
||||
|
||||
// Rows/columns kept in every matrix output below — the computation
|
||||
// above runs over every genome regardless; only the writers skip
|
||||
// excluded ones.
|
||||
let kept: Vec<usize> = (0..n).filter(|&i| !exclude_mask[i]).collect();
|
||||
|
||||
// ── Distance matrix → relaxed PHYLIP (default) or CSV (`--csv`) ────────────
|
||||
let write_dist = |w: &mut dyn Write| {
|
||||
if args.csv {
|
||||
write!(w, "genome").unwrap();
|
||||
for &j in &kept { write!(w, ",{}", labels[j]).unwrap(); }
|
||||
writeln!(w).unwrap();
|
||||
for &i in &kept {
|
||||
write!(w, "{}", labels[i]).unwrap();
|
||||
for &j in &kept {
|
||||
write!(w, ",{:.6}", matrix[[i, j]]).unwrap();
|
||||
}
|
||||
writeln!(w).unwrap();
|
||||
}
|
||||
} else {
|
||||
write_phylip_relaxed(w, &labels, &kept, &matrix);
|
||||
}
|
||||
};
|
||||
|
||||
match &args.output {
|
||||
Some(prefix) => {
|
||||
let path = format!("{}_dist.csv", prefix.display());
|
||||
let suffix = if args.csv { "_dist.csv" } else { "_dist.phy" };
|
||||
let path = format!("{}{suffix}", prefix.display());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
write_dist_csv(&mut f);
|
||||
write_dist(&mut f);
|
||||
info!("distance matrix → {path}");
|
||||
}
|
||||
None => {
|
||||
let stdout = io::stdout();
|
||||
let mut out = BufWriter::new(stdout.lock());
|
||||
write_dist_csv(&mut out);
|
||||
write_dist(&mut out);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Shared-kmer matrix → CSV ──────────────────────────────────────────────
|
||||
if args.shared_kmers {
|
||||
if let Some(shared) = &result.shared_kmers {
|
||||
if let Some(shared) = &shared_kmers {
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_shared.csv", p.display()))
|
||||
.unwrap_or_else(|| "shared.csv".into());
|
||||
@@ -337,31 +433,24 @@ pub fn run(args: PhyloArgs) {
|
||||
std::process::exit(1);
|
||||
}));
|
||||
write!(f, "genome").unwrap();
|
||||
for g in &labels { write!(f, ",{g}").unwrap(); }
|
||||
for &j in &kept { write!(f, ",{}", labels[j]).unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
for (i, g) in labels.iter().enumerate() {
|
||||
write!(f, "{g}").unwrap();
|
||||
for j in 0..n { write!(f, ",{}", shared[[i, j]]).unwrap(); }
|
||||
for &i in &kept {
|
||||
write!(f, "{}", labels[i]).unwrap();
|
||||
for &j in &kept { write!(f, ",{}", shared[[i, j]]).unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
}
|
||||
info!("shared-kmer matrix → {path}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── NJ tree via speedytree ────────────────────────────────────────────────
|
||||
// ── NJ tree ────────────────────────────────────────────────────────────────
|
||||
if args.nj {
|
||||
let rows: Vec<Vec<f64>> = (0..n)
|
||||
.map(|i| (0..n).map(|j| result.matrix[[i, j]]).collect())
|
||||
.collect();
|
||||
let dm = DistanceMatrix::build(rows, labels.clone()).unwrap_or_else(|e| {
|
||||
eprintln!("error building distance matrix for NJ: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let tree = NeighborJoiningSolver::<Hybrid>::default(dm).solve().unwrap_or_else(|e| {
|
||||
let tree = neighbor_joining(&matrix, &labels).unwrap_or_else(|e| {
|
||||
eprintln!("error computing NJ tree: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let newick = to_newick(&tree);
|
||||
let newick = tree.to_newick();
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_nj.nwk", p.display()))
|
||||
.unwrap_or_else(|| "nj.nwk".into());
|
||||
@@ -372,16 +461,9 @@ pub fn run(args: PhyloArgs) {
|
||||
info!("NJ tree → {path}");
|
||||
}
|
||||
|
||||
// ── UPGMA tree via kodama ─────────────────────────────────────────────────
|
||||
// ── UPGMA tree ───────────────────────────────────────────────────────────────
|
||||
if args.upgma {
|
||||
let mut condensed: Vec<f64> = Vec::with_capacity(n * (n - 1) / 2);
|
||||
for i in 0..n {
|
||||
for j in (i + 1)..n {
|
||||
condensed.push(result.matrix[[i, j]]);
|
||||
}
|
||||
}
|
||||
let dendro = linkage(&mut condensed, n, Method::Average);
|
||||
let newick = upgma_to_newick(&dendro, &labels);
|
||||
let newick = upgma(&matrix, &labels).to_newick();
|
||||
let path = args.output.as_ref()
|
||||
.map(|p| format!("{}_upgma.nwk", p.display()))
|
||||
.unwrap_or_else(|| "upgma.nwk".into());
|
||||
|
||||
@@ -1,187 +0,0 @@
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use obifastwrite::{JsonVal, write_record};
|
||||
use obikphylo::siblings::{RawSnpDistanceOutput, SiblingAnnexStats, SnpAlignment};
|
||||
use tracing::info;
|
||||
|
||||
// ── Family-size distribution → CSV ──────────────────────────────────────────
|
||||
//
|
||||
// Each row is a family (the up-to-4 k-mers sharing flanks, differing only at
|
||||
// the centre), counted once — at its minorant — regardless of how many of
|
||||
// its members are observed. Family size 1..4 (not "sibling count" 0..3):
|
||||
// see `DevDocMD/theory/evolutionary_distances.md`, "Definitions".
|
||||
|
||||
pub(super) fn write_sibling_stats_csv(stats: &SiblingAnnexStats, labels: &[String], output: &Option<PathBuf>) {
|
||||
// One row per genome (4 columns, family size 1-4: number of families of
|
||||
// that size for which the genome carries at least one member), plus a
|
||||
// `global` row — the actual deduplicated family-size histogram
|
||||
// (`stats.counts`), NOT a sum of the per-genome columns (a family shared
|
||||
// by several genomes would otherwise be counted once per genome it
|
||||
// appears in, inflating the total beyond the real family count).
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_siblings.csv", p.display()))
|
||||
.unwrap_or_else(|| "siblings.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
writeln!(f, "genome,1,2,3,4").unwrap();
|
||||
for (label, counts) in labels.iter().zip(stats.per_genome.iter()) {
|
||||
writeln!(f, "{label},{},{},{},{}", counts[0], counts[1], counts[2], counts[3]).unwrap();
|
||||
}
|
||||
writeln!(
|
||||
f, "global,{},{},{},{}",
|
||||
stats.counts[0], stats.counts[1], stats.counts[2], stats.counts[3],
|
||||
).unwrap();
|
||||
let total: u64 = stats.counts.iter().sum();
|
||||
info!("family-size distribution → {path} (total {total} famil{})",
|
||||
if total == 1 { "y" } else { "ies" });
|
||||
}
|
||||
|
||||
// ── Raw single-copy SNP distance → CSV ──────────────────────────────────────
|
||||
//
|
||||
// p_hat[i,j] = snp[i,j] / (snp[i,j] + shared[i,j]) over loci single-copy in
|
||||
// both i and j — see `RawSnpDistanceOutput` / `KmerIndex::raw_snp_distance`.
|
||||
// A single file: the distance matrix, with an eligible-loci count alongside
|
||||
// each value so a 0/0 pair (no eligible locus at all) is distinguishable
|
||||
// from a genuinely identical pair.
|
||||
|
||||
pub(super) fn write_raw_snp_distance_csv(result: &RawSnpDistanceOutput, labels: &[String], output: &Option<PathBuf>) {
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_rawsnp.csv", p.display()))
|
||||
.unwrap_or_else(|| "rawsnp.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n = labels.len();
|
||||
write!(f, "genome").unwrap();
|
||||
for g in labels { write!(f, ",{g}").unwrap(); }
|
||||
writeln!(f).unwrap();
|
||||
for (i, g) in labels.iter().enumerate() {
|
||||
write!(f, "{g}").unwrap();
|
||||
for j in 0..n {
|
||||
let snp = result.snp[[i, j]];
|
||||
let shared = result.shared[[i, j]];
|
||||
let eligible = snp + shared;
|
||||
if eligible == 0 {
|
||||
write!(f, ",NA").unwrap();
|
||||
} else {
|
||||
write!(f, ",{:.6}", snp as f64 / eligible as f64).unwrap();
|
||||
}
|
||||
}
|
||||
writeln!(f).unwrap();
|
||||
}
|
||||
info!("raw single-copy SNP distance matrix → {path}");
|
||||
}
|
||||
|
||||
// ── Global family-size histogram (annex-only, no per-genome pass) → CSV ────
|
||||
|
||||
pub(super) fn write_sibling_hist_csv(counts: &[u64; 4], output: &Option<PathBuf>) {
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_sibling_hist.csv", p.display()))
|
||||
.unwrap_or_else(|| "sibling_hist.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
writeln!(f, "size,count").unwrap();
|
||||
for (size, count) in counts.iter().enumerate() {
|
||||
writeln!(f, "{},{count}", size + 1).unwrap();
|
||||
}
|
||||
let total: u64 = counts.iter().sum();
|
||||
info!("family-size histogram → {path} (total {total} famil{})",
|
||||
if total == 1 { "y" } else { "ies" });
|
||||
}
|
||||
|
||||
// ── Raw single-copy SNP distance → per-pair diagnostic counts ──────────────
|
||||
//
|
||||
// A pair table (one row per unordered genome pair), not a matrix: the ratio
|
||||
// alone can't distinguish "identical across every eligible locus" from
|
||||
// "almost no eligible locus at all" — both can read `0.0`/`NA` in
|
||||
// `--raw-snp-distance`'s output. Distinguishing them matters most exactly
|
||||
// where it's easy to miss: genome pairs near the edge of what
|
||||
// central-position families can resolve at all (deep cross-lineage splits,
|
||||
// see `DevDocMD/theory/evolutionary_distances.md`, "Run 3" and the later
|
||||
// IQ-TREE/Mash comparison — a `ratio=0.0` backed by 2 eligible loci is not
|
||||
// the same claim as one backed by 2000).
|
||||
|
||||
pub(super) fn write_raw_snp_counts_csv(result: &RawSnpDistanceOutput, labels: &[String], output: &Option<PathBuf>) {
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_rawsnp_counts.csv", p.display()))
|
||||
.unwrap_or_else(|| "rawsnp_counts.csv".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n = labels.len();
|
||||
writeln!(f, "genome_a,genome_b,n_snp,n_shared,n_eligible,ratio").unwrap();
|
||||
for i in 0..n {
|
||||
for j in (i + 1)..n {
|
||||
let snp = result.snp[[i, j]];
|
||||
let shared = result.shared[[i, j]];
|
||||
let eligible = snp + shared;
|
||||
write!(f, "{},{},{snp},{shared},{eligible}", labels[i], labels[j]).unwrap();
|
||||
if eligible == 0 {
|
||||
writeln!(f, ",NA").unwrap();
|
||||
} else {
|
||||
writeln!(f, ",{:.6}", snp as f64 / eligible as f64).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
info!("raw single-copy SNP distance counts (diagnostic) → {path}");
|
||||
}
|
||||
|
||||
// ── SNP-only pseudo-alignment → FASTA ───────────────────────────────────────
|
||||
//
|
||||
// One record per genome, IUPAC-coded, no flanking sequence — see
|
||||
// `SnpAlignment` / `KmerIndex::snp_pseudo_alignment`. Uses the project's
|
||||
// existing FASTA writer (`obifastwrite::write_record`) rather than
|
||||
// hand-rolling one.
|
||||
|
||||
pub(super) fn write_snp_fasta(alignment: &SnpAlignment, labels: &[String], output: &Option<PathBuf>) {
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_snp.fasta", p.display()))
|
||||
.unwrap_or_else(|| "snp.fasta".into());
|
||||
let mut f = BufWriter::new(std::fs::File::create(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {path}: {e}");
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0);
|
||||
for (label, seq) in labels.iter().zip(alignment.sequences.iter()) {
|
||||
write_record(seq, label, &[("n_sites", JsonVal::Num(n_sites as u64))], &mut f).unwrap_or_else(|e| {
|
||||
eprintln!("error writing {path}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}
|
||||
info!("SNP pseudo-alignment → {path} ({n_sites} site{})",
|
||||
if n_sites == 1 { "" } else { "s" });
|
||||
}
|
||||
|
||||
// ── UPGMA Newick from kodama dendrogram ───────────────────────────────────────
|
||||
|
||||
pub(super) fn upgma_to_newick(dendro: &kodama::Dendrogram<f64>, names: &[String]) -> String {
|
||||
let n = names.len();
|
||||
// node_labels[i]: Newick subtree string for node i (leaves 0..n, internals n..)
|
||||
let mut labels: Vec<String> = names.to_vec();
|
||||
// height of each node: leaves = 0, internal = dissimilarity/2
|
||||
let mut heights: Vec<f64> = vec![0.0; 2 * n - 1];
|
||||
|
||||
for (k, step) in dendro.steps().iter().enumerate() {
|
||||
let new_node = n + k;
|
||||
let h = step.dissimilarity / 2.0;
|
||||
heights[new_node] = h;
|
||||
let c1 = step.cluster1;
|
||||
let c2 = step.cluster2;
|
||||
let bl1 = (h - heights[c1]).max(0.0);
|
||||
let bl2 = (h - heights[c2]).max(0.0);
|
||||
labels.push(format!(
|
||||
"({label1}:{bl1:.6},{label2}:{bl2:.6})",
|
||||
label1 = labels[c1],
|
||||
label2 = labels[c2],
|
||||
));
|
||||
}
|
||||
|
||||
format!("{};", labels.last().unwrap())
|
||||
}
|
||||
@@ -13,11 +13,10 @@ use super::sankoff::{STATE_SYMBOL, scaled_metric_matrix};
|
||||
// as-is via `prefasta:`. PhyG auto-adds its own indel/gap state as an
|
||||
// (n+1)-th row/column of the tcm — inert here since the alignment already
|
||||
// encodes absence as an ordinary state (`0`), never as `-` (see
|
||||
// `sankoff::write_sankoff_alignment_fasta`'s own comment on why, and the
|
||||
// RAxML-era bug that motivated it). The gap row/column below reuses
|
||||
// `matrix[i][0]`/`matrix[0][j]` (cost to/from `∅`) as the closest
|
||||
// principled value for a state that, in practice, is never actually
|
||||
// triggered.
|
||||
// `sankoff::write_sankoff_alignment_fasta`'s own comment on why). The gap
|
||||
// row/column below reuses `matrix[i][0]`/`matrix[0][j]` (cost to/from `∅`)
|
||||
// as the closest principled value for a state that, in practice, is never
|
||||
// actually triggered.
|
||||
|
||||
pub(super) fn write_sankoff_phyg(matrix: &[[f64; 16]; 16], output: &Option<PathBuf>, cost_scale: f64) {
|
||||
let scaled_matrix = scaled_metric_matrix(matrix, cost_scale);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Relaxed-PHYLIP distance-matrix writer — the default output format for
|
||||
//! `--distance` (see `args::PhyloArgs::csv`'s own docs for why): `n` on the
|
||||
//! first line, then one `label<TAB>value...` row per genome. "Relaxed"
|
||||
//! (unlike strict PHYLIP) means no 10-character label truncation/padding —
|
||||
//! just whitespace-separated fields, which every external NJ tool this
|
||||
//! targets (PHYLIP `neighbor`, FastME, T-REX, SplitsTree) already reads,
|
||||
//! and genome labels here routinely exceed strict PHYLIP's 10 characters.
|
||||
|
||||
use std::io::Write;
|
||||
|
||||
use ndarray::Array2;
|
||||
|
||||
pub(super) fn write_phylip_relaxed(w: &mut dyn Write, labels: &[String], indices: &[usize], matrix: &Array2<f64>) {
|
||||
writeln!(w, "{}", indices.len()).unwrap();
|
||||
for &i in indices {
|
||||
write!(w, "{}", labels[i]).unwrap();
|
||||
for &j in indices {
|
||||
write!(w, "\t{:.6}", matrix[[i, j]]).unwrap();
|
||||
}
|
||||
writeln!(w).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,9 @@
|
||||
//! Output writers for `--sankoff` — no calibration logic here, just
|
||||
//! formatting: `obikphylo::siblings::SiblingExt::sankoff_bundle` and the
|
||||
//! `cardinality_transition_probs`/`composition_transition_probs`/
|
||||
//! `pairwise_cost_matrix` calibration functions do all the actual work in
|
||||
//! `mod.rs`, this module only serialises their results.
|
||||
|
||||
use std::io::{BufWriter, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -7,19 +13,22 @@ use tracing::info;
|
||||
|
||||
// ── Sankoff pseudo-alignment → FASTA ────────────────────────────────────────
|
||||
//
|
||||
// Same data as `--snp`'s pseudo-alignment (`SnpAlignment`/
|
||||
// Same data as `--pseudo-alignment`'s output (`SnpAlignment`/
|
||||
// `snp_pseudo_alignment`), re-coded so its symbols match the accompanying
|
||||
// `--sankoff-matrix` output exactly: `0` for the empty/absent state instead
|
||||
// `--sankoff` matrix output exactly: `0` for the empty/absent state instead
|
||||
// of `-`, which TNT/PhyG would otherwise read as their own gap character
|
||||
// rather than our "family absent" state. Unless `free_loss` (`--free-loss`)
|
||||
// is set, in which case `∅` is recoded to `?` instead — TNT/PhyG's own
|
||||
// missing-data symbol, deliberately *not* `-` (still gap/indel semantics in
|
||||
// both tools) — so non-detection costs nothing rather than being scored as
|
||||
// an ordinary, calibrated state transition. See
|
||||
// `DevDocMD/theory/evolutionary_distances.md`, "Locus dropout under incomplete
|
||||
// coverage".
|
||||
// an ordinary, calibrated state transition.
|
||||
|
||||
pub(super) fn write_sankoff_alignment_fasta(alignment: &SnpAlignment, labels: &[String], output: &Option<PathBuf>, free_loss: bool) {
|
||||
pub(super) fn write_sankoff_alignment_fasta(
|
||||
alignment: &SnpAlignment,
|
||||
labels: &[String],
|
||||
output: &Option<PathBuf>,
|
||||
free_loss: bool,
|
||||
) {
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_sankoff.fasta", p.display()))
|
||||
.unwrap_or_else(|| "sankoff.fasta".into());
|
||||
@@ -28,33 +37,31 @@ pub(super) fn write_sankoff_alignment_fasta(alignment: &SnpAlignment, labels: &[
|
||||
std::process::exit(1);
|
||||
}));
|
||||
let absent_symbol = if free_loss { b'?' } else { b'0' };
|
||||
let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0);
|
||||
for (label, seq) in labels.iter().zip(alignment.sequences.iter()) {
|
||||
let n_sites = alignment.sequences.first().map_or(0, Vec::len);
|
||||
for (&g, seq) in alignment.genome_indices.iter().zip(alignment.sequences.iter()) {
|
||||
let recoded: Vec<u8> = seq.iter().map(|&b| if b == b'-' { absent_symbol } else { b }).collect();
|
||||
write_record(&recoded, label, &[("n_sites", JsonVal::Num(n_sites as u64))], &mut f).unwrap_or_else(|e| {
|
||||
eprintln!("error writing {path}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
write_record(&recoded, &labels[g], &[("n_sites", JsonVal::Num(n_sites as u64))], &mut f)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error writing {path}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}
|
||||
info!("Sankoff pseudo-alignment → {path} ({n_sites} site{})",
|
||||
if n_sites == 1 { "" } else { "s" });
|
||||
info!("Sankoff pseudo-alignment ({n_sites} site(s)) → {path}");
|
||||
}
|
||||
|
||||
// ── Sankoff cost matrix → CSV ────────────────────────────────────────────────
|
||||
//
|
||||
// 16 states indexed by bitmask (bit 0=A, 1=C, 2=G, 3=T; state 0 is `∅`),
|
||||
// matching the convention already used for `--snp`'s IUPAC-coded output and
|
||||
// for the external TNT/PhyG scripts this feeds. Calibration report (p_hat,
|
||||
// its variance, how many pairs/loci went into it, the resulting c_ctx) goes
|
||||
// to the log, not the CSV, since it's a run-level fact, not per-cell data.
|
||||
// matching the convention used for `--pseudo-alignment`'s IUPAC-coded output
|
||||
// and for the external TNT/PhyG scripts this feeds.
|
||||
|
||||
// IUPAC ambiguity code per state (same mapping as `siblings::iupac_code`,
|
||||
// already used for `--snp`'s pseudo-alignment — a biologist reads "R" as
|
||||
// "A or G" without needing this file's convention explained), with `0`
|
||||
// standing in for the empty state (`-` would collide with TNT/PhyG's own
|
||||
// gap/range syntax). Bit order: 0=A, 1=C, 2=G, 3=T. This project's
|
||||
// canonical alphabet — `tnt::write_sankoff_tnt` recodes it to TNT's own
|
||||
// default alphabet at the adapter boundary, rather than using it here.
|
||||
/// IUPAC ambiguity code per state (same mapping
|
||||
/// `obikphylo::siblings::algorithms::masking::iupac_code` uses internally
|
||||
/// for `--pseudo-alignment`), with `0` standing in for the empty state (`-`
|
||||
/// would collide with TNT/PhyG's own gap/range syntax). Bit order: 0=A,
|
||||
/// 1=C, 2=G, 3=T. This project's canonical alphabet for every Sankoff
|
||||
/// export (`--tnt`/`--phyg`/`--iqtree` each recode it to their own alphabet
|
||||
/// at their own adapter boundary, rather than using it directly).
|
||||
pub(super) const STATE_SYMBOL: [char; 16] = [
|
||||
'0', 'A', 'C', 'M', 'G', 'R', 'S', 'V', 'T', 'W', 'Y', 'H', 'K', 'D', 'B', 'N',
|
||||
];
|
||||
@@ -70,10 +77,7 @@ pub(super) fn state_index_table() -> [u8; 128] {
|
||||
table
|
||||
}
|
||||
|
||||
pub(super) fn write_sankoff_matrix_csv(
|
||||
matrix: &[[f64; 16]; 16],
|
||||
output: &Option<PathBuf>,
|
||||
) {
|
||||
pub(super) fn write_sankoff_matrix_csv(matrix: &[[f64; 16]; 16], output: &Option<PathBuf>) {
|
||||
let path = output.as_ref()
|
||||
.map(|p| format!("{}_sankoff_matrix.csv", p.display()))
|
||||
.unwrap_or_else(|| "sankoff_matrix.csv".into());
|
||||
@@ -95,14 +99,10 @@ pub(super) fn write_sankoff_matrix_csv(
|
||||
// ── Sankoff calibration parameters → YAML report ────────────────────────────
|
||||
//
|
||||
// Everything `--sankoff` estimates from real data, in one durable,
|
||||
// machine-readable file: `p_hat` and its variance (with how many pairs/loci
|
||||
// went into it), the derived `c_ctx`, and the base-pair substitution tally
|
||||
// (raw counts, not just the derived costs) — kept for the same reason raw
|
||||
// counts are kept anywhere else in this project: costs are a modelling
|
||||
// machine-readable file: the cardinality and base-pair transition tallies
|
||||
// (raw counts, not just the derived probabilities) — costs are a modelling
|
||||
// choice built *from* the counts, and reproducing/re-deriving them later
|
||||
// needs the counts, not just their current derived value. Structured (YAML,
|
||||
// not an ad hoc key=value text file) so R/Python/etc. can load it directly
|
||||
// rather than re-parsing free text.
|
||||
// needs the counts, not just their current derived value.
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
struct CardinalityTransition {
|
||||
@@ -183,16 +183,15 @@ pub(super) fn write_sankoff_params(
|
||||
/// closure* of the result (Floyd-Warshall over the 16 states again, on the
|
||||
/// now-integer values).
|
||||
///
|
||||
/// Unlike this project's earlier cost-matrix construction (a graph closed
|
||||
/// by shortest path, guaranteeing a metric by construction), `matrix` here
|
||||
/// comes from `obikindex::pairwise_cost_matrix`'s row-normalise-then-`-ln`
|
||||
/// composition, which gives no such guarantee — so this closure isn't only
|
||||
/// needed to correct integer-rounding artifacts (two real costs of `1.734`
|
||||
/// each round to `173`, summing to `346`, while their own real sum `3.468`
|
||||
/// rounds to `347` — TNT then reports "triangle inequality violated ...
|
||||
/// Fixed" and silently substitutes its own corrected value), it may also
|
||||
/// be the only thing making the *real-valued* matrix a metric in the first
|
||||
/// place. Re-closing after rounding makes both corrections explicit and
|
||||
/// `pairwise_cost_matrix`'s row-normalise-then-`-ln` construction gives no
|
||||
/// guarantee of being a metric (unlike a cost graph closed by shortest path
|
||||
/// by construction) — so this closure isn't only needed to correct
|
||||
/// integer-rounding artifacts (two real costs of `1.734` each round to
|
||||
/// `173`, summing to `346`, while their own real sum `3.468` rounds to
|
||||
/// `347` — TNT then reports "triangle inequality violated ... Fixed" and
|
||||
/// silently substitutes its own corrected value), it may also be the only
|
||||
/// thing making the *real-valued* matrix a metric in the first place.
|
||||
/// Re-closing after rounding makes both corrections explicit and
|
||||
/// reproducible here instead, rather than left implicit and
|
||||
/// tool-version-dependent.
|
||||
pub(super) fn scaled_metric_matrix(matrix: &[[f64; 16]; 16], cost_scale: f64) -> [[i64; 16]; 16] {
|
||||
|
||||
@@ -40,11 +40,12 @@ pub(super) fn write_sankoff_tnt(
|
||||
}));
|
||||
|
||||
// IUPAC-ish symbol -> bitmask, to translate the alignment (which uses
|
||||
// `STATE_SYMBOL`, `-` already normalised to `0` by `snp_pseudo_alignment`
|
||||
// `STATE_SYMBOL`, `-` already normalised to `0` by `sankoff_bundle`
|
||||
// callers) into TNT's alphabet without re-deriving state indices.
|
||||
let iupac_to_state = state_index_table();
|
||||
|
||||
let n_sites = alignment.sequences.first().map(|s| s.len()).unwrap_or(0);
|
||||
let kept_labels: Vec<&String> = alignment.genome_indices.iter().map(|&g| &labels[g]).collect();
|
||||
writeln!(f, "xread").unwrap();
|
||||
writeln!(f, "mxram 16000;").unwrap();
|
||||
writeln!(f, "taxname =;").unwrap();
|
||||
@@ -55,8 +56,8 @@ pub(super) fn write_sankoff_tnt(
|
||||
"'obikmer central-position SNP families, calibrated Sankoff 16-state encoding'"
|
||||
)
|
||||
.unwrap();
|
||||
writeln!(f, "{n_sites} {}", labels.len()).unwrap();
|
||||
for (label, seq) in labels.iter().zip(alignment.sequences.iter()) {
|
||||
writeln!(f, "{n_sites} {}", kept_labels.len()).unwrap();
|
||||
for (label, seq) in kept_labels.iter().zip(alignment.sequences.iter()) {
|
||||
write!(f, "{label} ").unwrap();
|
||||
for &b in seq {
|
||||
if free_loss && b == b'-' {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
use clap::Args;
|
||||
use obikfilter::{GenomeSelector, GroupFilterParams, GroupQuorumFilter};
|
||||
use obikindex::IndexMeta;
|
||||
use obikfilter::{GroupFilterParams, KmerFilter, MetaPred};
|
||||
|
||||
/// CLI args for ingroup/outgroup filtering — embeddable in any command via `#[command(flatten)]`.
|
||||
/// Ingroup/outgroup metadata-predicate quorum filtering — embeddable in any
|
||||
/// command via `#[command(flatten)]` (`filter`, `dump`).
|
||||
#[derive(Args)]
|
||||
pub struct FilterArgs {
|
||||
pub struct GroupFilterArgs {
|
||||
/// Ingroup predicate (repeatable; AND). Forms: `key=v1|v2`, `key!=v`, `key~path`, `key!~path`, `*`/`all`
|
||||
#[arg(long, value_name = "PRED")]
|
||||
pub ingroup: Vec<String>,
|
||||
@@ -23,12 +24,12 @@ pub struct FilterArgs {
|
||||
#[arg(long, allow_hyphen_values = true)]
|
||||
pub max_count: Option<isize>,
|
||||
|
||||
/// Minimum fraction of ingroup genomes containing the k-mer [0.0–1.0]
|
||||
/// Minimum fraction of ingroup genomes containing the k-mer [0.0-1.0]
|
||||
/// (default 1.0 when --ingroup is set, 0.0 otherwise)
|
||||
#[arg(long)]
|
||||
pub min_frac: Option<f64>,
|
||||
|
||||
/// Maximum fraction of ingroup genomes containing the k-mer [0.0–1.0]
|
||||
/// Maximum fraction of ingroup genomes containing the k-mer [0.0-1.0]
|
||||
#[arg(long)]
|
||||
pub max_frac: Option<f64>,
|
||||
|
||||
@@ -43,11 +44,11 @@ pub struct FilterArgs {
|
||||
#[arg(long, allow_hyphen_values = true)]
|
||||
pub max_outgroup_count: Option<isize>,
|
||||
|
||||
/// Minimum fraction of outgroup genomes containing the k-mer [0.0–1.0]
|
||||
/// Minimum fraction of outgroup genomes containing the k-mer [0.0-1.0]
|
||||
#[arg(long)]
|
||||
pub min_outgroup_frac: Option<f64>,
|
||||
|
||||
/// Maximum fraction of outgroup genomes containing the k-mer [0.0–1.0]
|
||||
/// Maximum fraction of outgroup genomes containing the k-mer [0.0-1.0]
|
||||
#[arg(long)]
|
||||
pub max_outgroup_frac: Option<f64>,
|
||||
|
||||
@@ -56,39 +57,31 @@ pub struct FilterArgs {
|
||||
pub presence_threshold: u32,
|
||||
}
|
||||
|
||||
impl FilterArgs {
|
||||
/// Parse predicates and build a filter list ready to pass to `iter_partition_kmers`.
|
||||
pub fn build_filters(&self, meta: &IndexMeta) -> Vec<Box<dyn KmerFilter>> {
|
||||
let ingroup_preds: Vec<MetaPred> = self.ingroup.iter()
|
||||
.map(|s| MetaPred::parse(s).unwrap_or_else(|e| {
|
||||
eprintln!("error in --ingroup: {e}");
|
||||
std::process::exit(1);
|
||||
}))
|
||||
.collect();
|
||||
let outgroup_preds: Vec<MetaPred> = self.outgroup.iter()
|
||||
.map(|s| MetaPred::parse(s).unwrap_or_else(|e| {
|
||||
eprintln!("error in --outgroup: {e}");
|
||||
std::process::exit(1);
|
||||
}))
|
||||
.collect();
|
||||
let filter = meta.build_group_filter(
|
||||
&ingroup_preds,
|
||||
&outgroup_preds,
|
||||
GroupFilterParams {
|
||||
threshold: self.presence_threshold,
|
||||
min_count: self.min_count,
|
||||
max_count: self.max_count,
|
||||
min_frac: self.min_frac,
|
||||
max_frac: self.max_frac,
|
||||
min_outgroup_count: self.min_outgroup_count,
|
||||
max_outgroup_count: self.max_outgroup_count,
|
||||
min_outgroup_frac: self.min_outgroup_frac,
|
||||
max_outgroup_frac: self.max_outgroup_frac,
|
||||
},
|
||||
).unwrap_or_else(|e| {
|
||||
eprintln!("error in filter parameters: {e}");
|
||||
impl GroupFilterArgs {
|
||||
/// Parse `--ingroup`/`--outgroup` and build the quorum filter. Exits on error.
|
||||
pub fn build_filter(&self, meta: &IndexMeta) -> GroupQuorumFilter {
|
||||
let selector = GenomeSelector::parse(&self.ingroup, &self.outgroup).unwrap_or_else(|e| {
|
||||
eprintln!("error in --ingroup/--outgroup: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
vec![Box::new(filter)]
|
||||
selector
|
||||
.build_group_filter(
|
||||
meta,
|
||||
GroupFilterParams {
|
||||
threshold: self.presence_threshold,
|
||||
min_count: self.min_count,
|
||||
max_count: self.max_count,
|
||||
min_frac: self.min_frac,
|
||||
max_frac: self.max_frac,
|
||||
min_outgroup_count: self.min_outgroup_count,
|
||||
max_outgroup_count: self.max_outgroup_count,
|
||||
min_outgroup_frac: self.min_outgroup_frac,
|
||||
max_outgroup_frac: self.max_outgroup_frac,
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error in filter parameters: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use obikindex::KmerDesc;
|
||||
use obikseq::CanonicalKmer;
|
||||
use obiread::record::SeqRecord;
|
||||
use obiskbuilder::SuperKmerIter;
|
||||
|
||||
/// A batch of query sequences, with k-mers deduplicated directly (not just at
|
||||
/// the superkmer level) and pre-split by partition.
|
||||
///
|
||||
/// Superkmer *construction* (`SuperKmerIter`) is still required — it's the
|
||||
/// mechanism that computes minimizers and partition routing — but the dedup
|
||||
/// key is the canonical k-mer, not the superkmer: two different superkmers
|
||||
/// that happen to share a k-mer (read overlaps, repeats, a SNP splitting an
|
||||
/// otherwise-identical run) are deduplicated too, not just identical whole
|
||||
/// superkmers. This also means each unique k-mer triggers at most one MPHF
|
||||
/// lookup, not one per occurrence.
|
||||
pub struct QueryBatch {
|
||||
/// Sequence ids in batch order.
|
||||
pub ids: Vec<String>,
|
||||
/// Raw sequence bytes (for output), in batch order.
|
||||
pub seqs: Vec<Vec<u8>>,
|
||||
/// Total kmer count per sequence (used for `--detail` coverage allocation).
|
||||
pub n_kmers: Vec<u32>,
|
||||
/// Deduplicated k-mer occurrences, one map per partition.
|
||||
pub by_partition: Vec<HashMap<CanonicalKmer, Vec<KmerDesc>>>,
|
||||
}
|
||||
|
||||
impl QueryBatch {
|
||||
/// Build a batch from a vec of parsed sequence records, deduplicating
|
||||
/// k-mers and routing them to partitions in the same pass.
|
||||
pub fn from_records(
|
||||
records: Vec<SeqRecord>,
|
||||
k: usize,
|
||||
level_max: usize,
|
||||
theta: f64,
|
||||
n_partitions: usize,
|
||||
) -> Self {
|
||||
let mut ids = Vec::with_capacity(records.len());
|
||||
let mut seqs = Vec::with_capacity(records.len());
|
||||
let mut n_kmers = Vec::with_capacity(records.len());
|
||||
let mask = (n_partitions as u64) - 1;
|
||||
let mut by_partition: Vec<HashMap<CanonicalKmer, Vec<KmerDesc>>> =
|
||||
(0..n_partitions).map(|_| HashMap::new()).collect();
|
||||
|
||||
for (seq_idx, record) in records.into_iter().enumerate() {
|
||||
let mut kmer_offset = 0u32;
|
||||
|
||||
for rsk in SuperKmerIter::new(&record.normalized, k, level_max, theta) {
|
||||
let part_idx = (rsk.minimizer().seq_hash() & mask) as usize;
|
||||
let map = &mut by_partition[part_idx];
|
||||
for (j, kmer) in rsk.superkmer().iter_canonical_kmers().enumerate() {
|
||||
map.entry(kmer).or_default().push(KmerDesc {
|
||||
seq_idx: seq_idx as u32,
|
||||
pos: kmer_offset + j as u32,
|
||||
});
|
||||
}
|
||||
let n = (rsk.seql() - k + 1) as u32;
|
||||
kmer_offset += n;
|
||||
}
|
||||
|
||||
ids.push(record.id);
|
||||
seqs.push(record.sequence);
|
||||
n_kmers.push(kmer_offset);
|
||||
}
|
||||
|
||||
Self {
|
||||
ids,
|
||||
seqs,
|
||||
n_kmers,
|
||||
by_partition,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,289 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
use obikindex::KmerIndex;
|
||||
use obikindex::{GenomeInfo, KmerDesc, QueryHit, QueryStats};
|
||||
use obikrope::Rope;
|
||||
use obikseq::CanonicalKmer;
|
||||
use obiread::record::parse_chunk;
|
||||
use tracing::debug;
|
||||
|
||||
use super::batch::QueryBatch;
|
||||
use super::findere::{ConfirmedHit, sparse_findere_for_genome};
|
||||
use super::output::emit_batch;
|
||||
use super::smer_index::SmerIndex;
|
||||
|
||||
pub(super) struct SeqAcc {
|
||||
pub(super) kmer_count: u32,
|
||||
pub(super) kmer_missing: u32,
|
||||
pub(super) genome_totals: Vec<u32>,
|
||||
}
|
||||
|
||||
impl SeqAcc {
|
||||
fn new(n_genomes: usize) -> Self {
|
||||
Self {
|
||||
kmer_count: 0,
|
||||
kmer_missing: 0,
|
||||
genome_totals: vec![0u32; n_genomes],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn process_chunk(
|
||||
idx: &KmerIndex,
|
||||
rope: Rope,
|
||||
k: usize,
|
||||
n_genomes: usize,
|
||||
n_partitions: usize,
|
||||
with_counts: bool,
|
||||
effective_z: usize,
|
||||
detail: bool,
|
||||
count_missing: bool,
|
||||
force_presence: bool,
|
||||
presence_threshold: u32,
|
||||
genomes: &[GenomeInfo],
|
||||
) -> Vec<u8> {
|
||||
let chunk_start = Instant::now();
|
||||
let chunk_bytes = rope.len();
|
||||
|
||||
let records = parse_chunk(&rope, k);
|
||||
if records.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let batch = QueryBatch::from_records(records, k, 6, 0.7, n_partitions);
|
||||
let n_seqs = batch.ids.len();
|
||||
|
||||
// Estimate QueryBatch::by_partition's actual memory footprint: the
|
||||
// k-mer-level dedup map (roadmap point 5) — one HashMap<CanonicalKmer,
|
||||
// Vec<KmerDesc>> per partition, sized by *unique* k-mers, not shrunk by
|
||||
// dedup. On real workloads with a low intra-chunk duplication rate this
|
||||
// can dwarf every other per-chunk structure, including the sparse
|
||||
// Findere ones logged further down — unlike those, chunk_bytes's formula
|
||||
// (run()) does not account for this at all today. Measured by allocated
|
||||
// capacity, not logical length, to reflect real memory pressure
|
||||
// (HashMap/Vec growth slack) — `by_partition` is alive for the entire
|
||||
// process_chunk call (never drained, only iterated by reference), so
|
||||
// this is its footprint for the whole chunk lifetime, not a transient.
|
||||
let hashmap_slot_bytes = (std::mem::size_of::<CanonicalKmer>()
|
||||
+ std::mem::size_of::<Vec<KmerDesc>>()
|
||||
+ 1) as u64; // +1 ≈ hashbrown control byte per slot
|
||||
let by_partition_map_bytes: u64 = batch
|
||||
.by_partition
|
||||
.iter()
|
||||
.map(|m| m.capacity() as u64 * hashmap_slot_bytes)
|
||||
.sum();
|
||||
let by_partition_desc_bytes: u64 = batch
|
||||
.by_partition
|
||||
.iter()
|
||||
.flat_map(|m| m.values())
|
||||
.map(|v| v.capacity() as u64 * std::mem::size_of::<KmerDesc>() as u64)
|
||||
.sum();
|
||||
let by_partition_bytes = by_partition_map_bytes + by_partition_desc_bytes;
|
||||
|
||||
debug!(
|
||||
n_unique_kmers_total = batch.by_partition.iter().map(|m| m.len() as u64).sum::<u64>(),
|
||||
by_partition_map_bytes,
|
||||
by_partition_desc_bytes,
|
||||
by_partition_bytes,
|
||||
chunk_bytes,
|
||||
"by_partition memory retained"
|
||||
);
|
||||
|
||||
// Sparse bookkeeping for the whole chunk:
|
||||
// - smer_index: O(total_smers) — is this s-mer in the index at all.
|
||||
// - by_genome[g]: raw (seq_idx, pos_smer, value) hits for genome g, only
|
||||
// ever containing nonzero entries (query_partition_with never emits a
|
||||
// QueryHit::Value for a zero value) — empty for every genome this chunk
|
||||
// never matched, which is the common case for unrelated queries.
|
||||
let mut smer_index = SmerIndex::new(&batch.n_kmers);
|
||||
let mut by_genome: Vec<Vec<(u32, u32, u32)>> = (0..n_genomes).map(|_| Vec::new()).collect();
|
||||
|
||||
// Dedup-ratio bookkeeping: occurrences (from batch.n_kmers, computed
|
||||
// before dedup) vs. unique k-mers actually queried (query_stats) — the
|
||||
// entire justification for k-mer-level dereplication (see query.md,
|
||||
// Future work point 5). If this ratio stays close to 1.0 on real data,
|
||||
// dereplication isn't paying for itself and that should show up here.
|
||||
let n_occurrences: u64 = batch.n_kmers.iter().map(|&n| n as u64).sum();
|
||||
let mut query_stats = QueryStats::default();
|
||||
|
||||
for (part_idx, kmers) in batch.by_partition.iter().enumerate() {
|
||||
if kmers.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let stats = idx
|
||||
.query_partition_with(
|
||||
part_idx,
|
||||
kmers,
|
||||
n_genomes,
|
||||
with_counts,
|
||||
|event| match event {
|
||||
QueryHit::Found(descs) => {
|
||||
for desc in descs {
|
||||
smer_index.mark_found(desc.seq_idx as usize, desc.pos as usize);
|
||||
}
|
||||
}
|
||||
QueryHit::Value(descs, g, v) => {
|
||||
for desc in descs {
|
||||
by_genome[g].push((desc.seq_idx, desc.pos, v));
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("query error on partition {part_idx}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
query_stats += stats;
|
||||
}
|
||||
|
||||
debug!(
|
||||
n_occurrences,
|
||||
n_unique_kmers = query_stats.n_unique_kmers,
|
||||
n_mphf_calls = query_stats.n_mphf_calls,
|
||||
n_hits = query_stats.n_hits,
|
||||
n_columns_scanned = query_stats.n_columns_scanned,
|
||||
n_col_get_calls = query_stats.n_col_get_calls,
|
||||
"k-mer dedup + column-major fetch"
|
||||
);
|
||||
|
||||
// ── Sparse Findere: per-genome run detection + sliding-window minimum ────
|
||||
//
|
||||
// Confirmed z-windows, per genome, replace the dense win_min matrix:
|
||||
// total retained memory is O(actual hits), not O(total_smers × n_genomes)
|
||||
// — the whole point of this pass. See sparse_findere_for_genome's doc for
|
||||
// why run detection is equivalent to the dense scan's semantics.
|
||||
let presence = force_presence || !with_counts;
|
||||
let threshold = presence_threshold;
|
||||
let z = effective_z;
|
||||
|
||||
let n_kmers_out: Vec<usize> = batch
|
||||
.n_kmers
|
||||
.iter()
|
||||
.map(|&n| {
|
||||
let n = n as usize;
|
||||
if n >= z { n - z + 1 } else { 0 }
|
||||
})
|
||||
.collect();
|
||||
let mut out_offsets = Vec::with_capacity(n_seqs + 1);
|
||||
{
|
||||
let mut total = 0usize;
|
||||
out_offsets.push(0);
|
||||
for &n in &n_kmers_out {
|
||||
total += n;
|
||||
out_offsets.push(total);
|
||||
}
|
||||
}
|
||||
let total_out = *out_offsets.last().unwrap_or(&0);
|
||||
|
||||
let n_dense_would_be = n_occurrences as u64 * n_genomes as u64;
|
||||
let mut n_sparse_entries = 0u64;
|
||||
let mut n_runs_total = 0usize;
|
||||
let mut run_len_total = 0usize;
|
||||
|
||||
let mut confirmed_by_genome: Vec<Vec<ConfirmedHit>> = Vec::with_capacity(n_genomes);
|
||||
for hits in &mut by_genome {
|
||||
n_sparse_entries += hits.len() as u64;
|
||||
let (confirmed, n_runs, run_len) = sparse_findere_for_genome(hits, z, presence, threshold);
|
||||
n_runs_total += n_runs;
|
||||
run_len_total += run_len;
|
||||
confirmed_by_genome.push(confirmed);
|
||||
}
|
||||
|
||||
debug!(
|
||||
n_dense_would_be,
|
||||
n_sparse_entries,
|
||||
n_runs = n_runs_total,
|
||||
avg_run_len = if n_runs_total > 0 { run_len_total as f64 / n_runs_total as f64 } else { 0.0 },
|
||||
z,
|
||||
"sparse Findere"
|
||||
);
|
||||
|
||||
// Actual bytes retained by the sparse hit structures (by_genome +
|
||||
// confirmed_by_genome, both alive simultaneously at this point — see the
|
||||
// chunk-size formula's comment in `run()`), by allocated capacity rather
|
||||
// than logical length so this reflects real memory pressure including
|
||||
// Vec growth slack. `empirical_multiplier` is directly comparable to
|
||||
// BYTES_PER_KMER_PER_GENOME (`run()`) — the ratio a cluster run's logs
|
||||
// need to judge whether that constant is over- or under-conservative for
|
||||
// real data, instead of guessing.
|
||||
const HIT_ENTRY_BYTES: u64 = std::mem::size_of::<(u32, u32, u32)>() as u64;
|
||||
let by_genome_bytes: u64 = by_genome.iter().map(|v| v.capacity() as u64 * HIT_ENTRY_BYTES).sum();
|
||||
let confirmed_bytes: u64 = confirmed_by_genome.iter().map(|v| v.capacity() as u64 * HIT_ENTRY_BYTES).sum();
|
||||
let retained_bytes = by_genome_bytes + confirmed_bytes;
|
||||
|
||||
debug!(
|
||||
by_genome_bytes,
|
||||
confirmed_bytes,
|
||||
retained_bytes,
|
||||
chunk_bytes,
|
||||
empirical_multiplier = retained_bytes as f64 / chunk_bytes.max(1) as f64,
|
||||
"sparse memory retained"
|
||||
);
|
||||
|
||||
// ── Accumulate: genome totals (per genome, from confirmed hits) ──────────
|
||||
let mut accs: Vec<SeqAcc> = (0..n_seqs).map(|_| SeqAcc::new(n_genomes)).collect();
|
||||
let mut confirmed_any = vec![false; total_out];
|
||||
|
||||
for (g, hits) in confirmed_by_genome.iter().enumerate() {
|
||||
for &(seq_idx, pos_out, c) in hits {
|
||||
let abs_out = out_offsets[seq_idx as usize] + pos_out as usize;
|
||||
confirmed_any[abs_out] = true;
|
||||
accs[seq_idx as usize].genome_totals[g] += c;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Accumulate: kmer_count / kmer_missing (per position, genome-independent) ─
|
||||
for seq_idx in 0..n_seqs {
|
||||
let out_n = n_kmers_out[seq_idx];
|
||||
let acc = &mut accs[seq_idx];
|
||||
for pos in 0..out_n {
|
||||
let abs_out = out_offsets[seq_idx] + pos;
|
||||
if confirmed_any[abs_out] {
|
||||
acc.kmer_count += 1;
|
||||
} else if !smer_index.is_in_index(seq_idx, pos) {
|
||||
acc.kmer_missing += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Coverage (--detail): densify only when actually requested ────────────
|
||||
let mut cov: Vec<Vec<Vec<u32>>> = if detail {
|
||||
n_kmers_out.iter().map(|&n| vec![vec![0u32; n]; n_genomes]).collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
if detail {
|
||||
for (g, hits) in confirmed_by_genome.iter().enumerate() {
|
||||
for &(seq_idx, pos_out, c) in hits {
|
||||
cov[seq_idx as usize][g][pos_out as usize] += c;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Capacity estimate: actual sequence + ID bytes, plus JSON overhead per record.
|
||||
// JSON per record ≈ 50 fixed chars + ~20 per genome (label + count value) + 100 (overhead).
|
||||
let seq_bytes: usize = batch.seqs.iter().map(|s| s.len()).sum();
|
||||
let id_bytes: usize = batch.ids.iter().map(|s| s.len()).sum();
|
||||
let cap = seq_bytes + id_bytes + n_seqs * (4 + 50 + n_genomes * 20) + 100;
|
||||
let mut buf = Vec::with_capacity(cap);
|
||||
emit_batch(
|
||||
&batch,
|
||||
&accs,
|
||||
genomes,
|
||||
count_missing,
|
||||
detail,
|
||||
&cov,
|
||||
&mut buf,
|
||||
);
|
||||
|
||||
debug!(
|
||||
chunk_bytes,
|
||||
n_seqs,
|
||||
n_smers = batch.n_kmers.iter().map(|&n| n as u64).sum::<u64>(),
|
||||
wall_ms = chunk_start.elapsed().as_millis() as u64,
|
||||
"process_chunk"
|
||||
);
|
||||
|
||||
buf
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
use std::collections::VecDeque;
|
||||
|
||||
/// One confirmed z-window: genome `g`'s window ending at k-mer `pos` (the
|
||||
/// *leftmost* s-mer of the window, i.e. the k_user-mer's output position) is
|
||||
/// fully present and nonzero, with window-minimum `value`.
|
||||
pub(super) type ConfirmedHit = (u32, u32, u32); // (seq_idx, pos_out, value)
|
||||
|
||||
/// Reduce one genome's raw sparse s-mer hits — `(seq_idx, pos_smer, raw_value)`,
|
||||
/// unsorted, exactly as delivered by `QueryHit::Value` — into confirmed
|
||||
/// z-windows, without ever visiting a position that had no hit at all.
|
||||
///
|
||||
/// A z-window is confirmed only when all z s-mers in it are present *and*
|
||||
/// nonzero for this genome (matching the dense sliding-window's semantics,
|
||||
/// where "not in index" or a zero value both contribute 0 to the window
|
||||
/// minimum) — which can only happen inside a maximal run of consecutive
|
||||
/// `pos_smer` values for the same sequence. `hits` is sorted in place by
|
||||
/// `(seq_idx, pos_smer)` to expose those runs; the monotone-deque
|
||||
/// window-minimum then runs per run, on run-relative indices, identical in
|
||||
/// spirit to the dense version's whole-sequence scan.
|
||||
///
|
||||
/// Returns the confirmed hits plus `(n_runs, total_run_len)` for logging —
|
||||
/// a low average run length relative to `z` means most hits fail to form a
|
||||
/// complete window.
|
||||
pub(super) fn sparse_findere_for_genome(
|
||||
hits: &mut [(u32, u32, u32)],
|
||||
z: usize,
|
||||
presence: bool,
|
||||
threshold: u32,
|
||||
) -> (Vec<ConfirmedHit>, usize, usize) {
|
||||
hits.sort_unstable_by_key(|&(seq, pos, _)| (seq, pos));
|
||||
|
||||
let mut confirmed = Vec::new();
|
||||
let mut n_runs = 0usize;
|
||||
let mut total_run_len = 0usize;
|
||||
let mut dq: VecDeque<(usize, u32)> = VecDeque::new(); // (run-relative index, value)
|
||||
|
||||
let mut i = 0;
|
||||
while i < hits.len() {
|
||||
let seq = hits[i].0;
|
||||
let mut j = i + 1;
|
||||
while j < hits.len() && hits[j].0 == seq && hits[j].1 == hits[j - 1].1 + 1 {
|
||||
j += 1;
|
||||
}
|
||||
let run = &hits[i..j];
|
||||
n_runs += 1;
|
||||
total_run_len += run.len();
|
||||
|
||||
dq.clear();
|
||||
for (k, &(_, pos, val)) in run.iter().enumerate() {
|
||||
while dq.back().map_or(false, |&(_, v)| v >= val) {
|
||||
dq.pop_back();
|
||||
}
|
||||
dq.push_back((k, val));
|
||||
while dq.front().map_or(false, |&(fk, _)| fk + z <= k) {
|
||||
dq.pop_front();
|
||||
}
|
||||
if k + 1 >= z {
|
||||
let win_min = dq.front().unwrap().1;
|
||||
if win_min > 0 {
|
||||
let pos_out = pos + 1 - z as u32;
|
||||
let c = if presence { u32::from(win_min >= threshold) } else { win_min };
|
||||
confirmed.push((seq, pos_out, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
i = j;
|
||||
}
|
||||
|
||||
(confirmed, n_runs, total_run_len)
|
||||
}
|
||||
@@ -1,9 +1,3 @@
|
||||
mod batch;
|
||||
mod chunk;
|
||||
mod findere;
|
||||
mod output;
|
||||
mod smer_index;
|
||||
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -11,16 +5,16 @@ use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
|
||||
use std::time::Instant;
|
||||
|
||||
use clap::Args;
|
||||
use obikidxcache::index_cache::IndexCache;
|
||||
use obikindex::KmerIndex;
|
||||
use obikrope::Rope;
|
||||
use obikindex::layer::IndexMode;
|
||||
use obikquery::process_chunk;
|
||||
use obikrope::Rope;
|
||||
use obipipeline::{Throttled, ThrottleGuard, throttle};
|
||||
use obiread::chunk::read_sequence_chunks_sized;
|
||||
use obisys::{Reporter, Stage, available_memory_bytes, spinner};
|
||||
use tracing::{debug, info};
|
||||
|
||||
use chunk::process_chunk;
|
||||
|
||||
// ── Pipeline data ─────────────────────────────────────────────────────────────
|
||||
|
||||
enum QueryData {
|
||||
@@ -139,24 +133,31 @@ pub fn run(args: QueryArgs) {
|
||||
let with_counts = idx.meta().config.with_counts;
|
||||
let n_workers = args.threads.max(1);
|
||||
|
||||
// Every partition/layer the query might touch is opened once, up front,
|
||||
// and shared (via Arc) across every `obipipeline` worker — a query pass
|
||||
// is then pure in-memory lookups, never a per-chunk disk open (the
|
||||
// previous `obikindex`-based design's cost). `IndexCache` owns its
|
||||
// `Arc<KmerIndex>`, so it's itself `'static`-capable, satisfying
|
||||
// obipipeline's `Send + Sync + 'static` requirement on pipeline data —
|
||||
// see `obikquery::query_layer`'s doc comment for why that rules out a
|
||||
// borrow-based cache here.
|
||||
let cache = Arc::new(IndexCache::new(Arc::clone(&idx), None));
|
||||
|
||||
// Chunk size: each chunk stays in memory for its entire processing lifetime.
|
||||
//
|
||||
// Per-chunk memory is no longer a dense n_genomes-wide buffer (removed in
|
||||
// the sparse Findere rework, see process_chunk) — it now scales with
|
||||
// Per-chunk memory is not a dense n_genomes-wide buffer — it scales with
|
||||
// *actual hit count*, not with total_kmers_in_chunk × n_genomes
|
||||
// unconditionally. BYTES_PER_KMER_PER_GENOME below is therefore a
|
||||
// pathological-case bound, not a typical-case estimate: it protects
|
||||
// against a fully-dense hit pattern (every k-mer of the query matching
|
||||
// every genome — a degenerate case, e.g. low-complexity input theta-
|
||||
// filtering should mostly reject, or an index of near-duplicate genomes),
|
||||
// where by_genome and confirmed_by_genome (process_chunk) both end up
|
||||
// holding one (seq_idx, pos, value) entry — 3 × u32 = 12 bytes, vs. 4
|
||||
// bytes for the old dense encoding, where position was implicit in the
|
||||
// array index — per (k-mer, genome) pair, and *coexist simultaneously*
|
||||
// (by_genome isn't freed before confirmed_by_genome is built), for a
|
||||
// worst case of ~24 bytes/pair before Vec growth slack. `cov` remains
|
||||
// fully dense when --detail is set (unaffected by the sparse rework),
|
||||
// still roughly doubling the n_genomes-scaled cost.
|
||||
// where by_genome and confirmed_by_genome (obikquery::chunk::process_chunk)
|
||||
// both end up holding one (seq_idx, pos, value) entry — 3 × u32 = 12
|
||||
// bytes — per (k-mer, genome) pair, and *coexist simultaneously* (by_genome
|
||||
// isn't freed before confirmed_by_genome is built), for a worst case of
|
||||
// ~24 bytes/pair before Vec growth slack. `cov` remains fully dense when
|
||||
// --detail is set, still roughly doubling the n_genomes-scaled cost.
|
||||
//
|
||||
// For realistic, sparse hit patterns actual memory is far below this
|
||||
// bound — see the "sparse memory retained" debug log in process_chunk,
|
||||
@@ -225,9 +226,7 @@ pub fn run(args: QueryArgs) {
|
||||
|
||||
// Throttled iterator over input file paths: at most `effective_max_open()`
|
||||
// files are open at once. Opening + decompressing + chunking each file is
|
||||
// now a Flat pipeline stage, executed across the `n_workers` pool — not
|
||||
// serialised in the pipe's dedicated source thread (see steps::scatter /
|
||||
// cmd::superkmer for the same pattern applied to indexing).
|
||||
// a Flat pipeline stage, executed across the `n_workers` pool.
|
||||
info!("query: chunk_size={}MiB, max_open_files={}", chunk_bytes / (1024 * 1024), args.effective_max_open());
|
||||
|
||||
let paths: Vec<PathBuf> = args.inputs.iter().map(PathBuf::from).collect();
|
||||
@@ -282,7 +281,7 @@ pub fn run(args: QueryArgs) {
|
||||
}
|
||||
} : Path => Chunk,
|
||||
| {
|
||||
let idx = Arc::clone(&idx);
|
||||
let cache = Arc::clone(&cache);
|
||||
let genomes = Arc::clone(&genomes);
|
||||
let total_bytes = Arc::clone(&total_bytes);
|
||||
let chunks_active = Arc::clone(&chunks_active);
|
||||
@@ -290,7 +289,7 @@ pub fn run(args: QueryArgs) {
|
||||
chunks_active.fetch_add(1, Ordering::Relaxed);
|
||||
let bytes = rope.len() as u64;
|
||||
let out = process_chunk(
|
||||
&idx, rope, k, n_genomes, n_partitions, with_counts,
|
||||
&cache, rope, k, n_genomes, n_partitions, with_counts,
|
||||
effective_z, detail, count_missing, force_presence, presence_threshold,
|
||||
&genomes,
|
||||
);
|
||||
@@ -342,6 +341,3 @@ pub fn run(args: QueryArgs) {
|
||||
rep.push(t.stop());
|
||||
rep.print();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,52 +0,0 @@
|
||||
use std::io::Write;
|
||||
|
||||
use obikindex::GenomeInfo;
|
||||
|
||||
use super::batch::QueryBatch;
|
||||
use super::chunk::SeqAcc;
|
||||
|
||||
pub(super) fn emit_batch(
|
||||
batch: &QueryBatch,
|
||||
accs: &[SeqAcc],
|
||||
genomes: &[GenomeInfo],
|
||||
count_missing: bool,
|
||||
detail: bool,
|
||||
cov: &[Vec<Vec<u32>>],
|
||||
out: &mut impl Write,
|
||||
) {
|
||||
for (seq_idx, (id, seq)) in batch.ids.iter().zip(batch.seqs.iter()).enumerate() {
|
||||
let acc = &accs[seq_idx];
|
||||
let mut ann = serde_json::Map::new();
|
||||
|
||||
ann.insert("kmer_count".into(), acc.kmer_count.into());
|
||||
if count_missing {
|
||||
ann.insert("kmer_missing".into(), acc.kmer_missing.into());
|
||||
}
|
||||
|
||||
let mut match_map = serde_json::Map::new();
|
||||
for (g, genome) in genomes.iter().enumerate() {
|
||||
if acc.genome_totals[g] != 0 {
|
||||
match_map.insert(genome.label.clone(), acc.genome_totals[g].into());
|
||||
}
|
||||
}
|
||||
ann.insert("kmer_strict_matches".into(), match_map.into());
|
||||
|
||||
if detail && !cov.is_empty() {
|
||||
let mut cov_map = serde_json::Map::new();
|
||||
for (g, genome) in genomes.iter().enumerate() {
|
||||
let v: Vec<serde_json::Value> = cov[seq_idx][g].iter().map(|&x| x.into()).collect();
|
||||
cov_map.insert(genome.label.clone(), v.into());
|
||||
}
|
||||
ann.insert("coverage".into(), cov_map.into());
|
||||
}
|
||||
|
||||
// OBITools4 FASTA format: >id {"key":value,...}
|
||||
let _ = out.write_all(b">");
|
||||
let _ = out.write_all(id.as_bytes());
|
||||
let _ = out.write_all(b" ");
|
||||
let _ = serde_json::to_writer(&mut *out, &ann);
|
||||
let _ = out.write_all(b"\n");
|
||||
let _ = out.write_all(seq);
|
||||
let _ = out.write_all(b"\n");
|
||||
}
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
/// Tracks, per (sequence, s-mer position), whether the k-mer was found in the
|
||||
/// index at all — independent of *which* genome(s) matched. Sized
|
||||
/// `total_smers` (one `bool` per s-mer occurrence in the chunk), **not**
|
||||
/// multiplied by `n_genomes`: this is the O(1)-per-position bookkeeping that
|
||||
/// `kmer_missing` needs (the leftmost-s-mer-of-window membership test), kept
|
||||
/// dense because it's already cheap — the `n_genomes`-scaled data lives in
|
||||
/// the sparse per-genome hit lists built alongside it (see `process_chunk`).
|
||||
pub(super) struct SmerIndex {
|
||||
in_index: Vec<bool>, // total_smers
|
||||
offsets: Vec<usize>, // offsets[i]..offsets[i+1] = s-mer range for sequence i
|
||||
}
|
||||
|
||||
impl SmerIndex {
|
||||
pub(super) fn new(n_kmers_per_seq: &[u32]) -> Self {
|
||||
let mut offsets = Vec::with_capacity(n_kmers_per_seq.len() + 1);
|
||||
let mut total = 0usize;
|
||||
offsets.push(0);
|
||||
for &n in n_kmers_per_seq {
|
||||
total += n as usize;
|
||||
offsets.push(total);
|
||||
}
|
||||
Self {
|
||||
in_index: vec![false; total],
|
||||
offsets,
|
||||
}
|
||||
}
|
||||
|
||||
/// Mark the k-mer at (seq, kmer) as found in the index — independent of
|
||||
/// any particular genome's value. Called once per hit k-mer (stage 1 of
|
||||
/// `query_partition_with`), regardless of how the column-major fetch
|
||||
/// (stage 2) later reports per-genome values.
|
||||
pub(super) fn mark_found(&mut self, seq: usize, kmer: usize) {
|
||||
let abs = self.offsets[seq] + kmer;
|
||||
self.in_index[abs] = true;
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(super) fn is_in_index(&self, seq: usize, kmer: usize) -> bool {
|
||||
self.in_index[self.offsets[seq] + kmer]
|
||||
}
|
||||
}
|
||||
@@ -1,233 +0,0 @@
|
||||
use obikrope::Rope;
|
||||
use obikseq::CanonicalKmer;
|
||||
use obiread::record::parse_chunk;
|
||||
|
||||
use super::batch::QueryBatch;
|
||||
use super::findere::sparse_findere_for_genome;
|
||||
|
||||
const K: usize = 11;
|
||||
const M: usize = 5;
|
||||
|
||||
/// Build a `QueryBatch` from raw FASTA text, going through the same
|
||||
/// `Rope` + `parse_chunk` path `process_chunk` uses — avoids hand-building a
|
||||
/// `normalized` `Rope`, which is an implementation detail of `obiread`.
|
||||
///
|
||||
/// `obikseq`'s global K/M params are thread-local under `test-utils` (see
|
||||
/// `obikseq::params`), so setting them here is per-test-thread and does not
|
||||
/// need coordination with other tests.
|
||||
fn batch_from_fasta(fasta: &str, k: usize, n_partitions: usize) -> QueryBatch {
|
||||
obikseq::set_k(k);
|
||||
obikseq::set_m(M);
|
||||
let mut rope = Rope::new(Some("text/fasta"));
|
||||
rope.push(fasta.as_bytes().to_vec());
|
||||
let records = parse_chunk(&rope, k);
|
||||
QueryBatch::from_records(records, k, 6, 0.7, n_partitions)
|
||||
}
|
||||
|
||||
fn total_occurrences(batch: &QueryBatch) -> u64 {
|
||||
batch.n_kmers.iter().map(|&n| n as u64).sum()
|
||||
}
|
||||
|
||||
fn total_unique_kmers(batch: &QueryBatch) -> u64 {
|
||||
batch.by_partition.iter().map(|m| m.len() as u64).sum()
|
||||
}
|
||||
|
||||
// A 60 bp sequence, arbitrary but fixed — no attempt is made to prove it is
|
||||
// free of internal k=11 repeats; the tests below only rely on inequalities
|
||||
// that hold regardless (see each test's comment).
|
||||
const SEQ: &str = "CATTAGCGTACCTGATCAGGTTACAGCTTAGGCATCCAGTTGACCATGACTGGACTTAGC";
|
||||
|
||||
#[test]
|
||||
fn single_sequence_yields_plausible_kmer_counts() {
|
||||
// A single record can still contain internal repeats (SEQ isn't
|
||||
// guaranteed repeat-free at k=11) — this only checks the batch is
|
||||
// internally consistent, not a specific dedup ratio. The cross-record
|
||||
// tests below make the actual, unconditional dedup claims.
|
||||
let fasta = format!(">r1\n{SEQ}\n");
|
||||
let batch = batch_from_fasta(&fasta, K, 1);
|
||||
|
||||
assert_eq!(batch.ids, vec!["r1".to_string()]);
|
||||
let occurrences = total_occurrences(&batch);
|
||||
let unique = total_unique_kmers(&batch);
|
||||
assert!(occurrences > 0, "sequence should yield at least one k-mer");
|
||||
assert!(unique > 0 && unique <= occurrences);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicated_sequence_across_records_deduplicates() {
|
||||
// Two records with byte-identical sequences: every k-mer in record 1
|
||||
// exactly duplicates one in record 0, so unique kmers <= n_kmers[0],
|
||||
// strictly less than the summed occurrences (2 * n_kmers[0]) as long as
|
||||
// the sequence yields at least one k-mer. This holds regardless of
|
||||
// whether SEQ has internal repeats.
|
||||
let fasta = format!(">r1\n{SEQ}\n>r2\n{SEQ}\n");
|
||||
let batch = batch_from_fasta(&fasta, K, 1);
|
||||
|
||||
assert_eq!(batch.ids.len(), 2);
|
||||
let occurrences = total_occurrences(&batch);
|
||||
let unique = total_unique_kmers(&batch);
|
||||
|
||||
assert!(batch.n_kmers[0] > 0);
|
||||
assert_eq!(occurrences, batch.n_kmers[0] as u64 + batch.n_kmers[1] as u64);
|
||||
assert!(
|
||||
unique <= batch.n_kmers[0] as u64,
|
||||
"identical sequences must not produce more unique k-mers than one copy has"
|
||||
);
|
||||
assert!(
|
||||
unique < occurrences,
|
||||
"k-mer-level dedup must collapse at least the cross-record duplication"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicated_sequence_broadcasts_to_both_seq_indices() {
|
||||
// Stronger than the ratio check above: pick any k-mer that hit in both
|
||||
// records and confirm its occurrence list actually references both
|
||||
// seq_idx 0 and seq_idx 1 — this is the specific new capability (dedup
|
||||
// reaching across records/superkmers), not just a smaller unique count.
|
||||
let fasta = format!(">r1\n{SEQ}\n>r2\n{SEQ}\n");
|
||||
let batch = batch_from_fasta(&fasta, K, 1);
|
||||
|
||||
let shared = batch.by_partition[0]
|
||||
.values()
|
||||
.find(|descs| descs.iter().any(|d| d.seq_idx == 0) && descs.iter().any(|d| d.seq_idx == 1));
|
||||
|
||||
assert!(
|
||||
shared.is_some(),
|
||||
"expected at least one k-mer shared between the two identical records"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_records_yield_empty_batch() {
|
||||
let batch = batch_from_fasta("", K, 1);
|
||||
assert!(batch.ids.is_empty());
|
||||
assert_eq!(total_occurrences(&batch), 0);
|
||||
assert_eq!(total_unique_kmers(&batch), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partition_routing_is_a_pure_function_of_the_kmer() {
|
||||
// With n_partitions=4, every occurrence of a given k-mer must land in
|
||||
// the same partition bucket as every other occurrence of that k-mer
|
||||
// (partition routing is derived from the minimizer, shared by
|
||||
// definition among instances of the same k-mer's containing superkmer
|
||||
// in this test's single-sequence-pair setup).
|
||||
let fasta = format!(">r1\n{SEQ}\n>r2\n{SEQ}\n");
|
||||
let batch = batch_from_fasta(&fasta, K, 4);
|
||||
|
||||
let total_unique: u64 = batch.by_partition.iter().map(|m| m.len() as u64).sum();
|
||||
assert!(total_unique > 0);
|
||||
|
||||
// No k-mer key appears in more than one partition's map.
|
||||
let mut seen: std::collections::HashSet<CanonicalKmer> = std::collections::HashSet::new();
|
||||
for map in &batch.by_partition {
|
||||
for kmer in map.keys() {
|
||||
assert!(seen.insert(*kmer), "k-mer routed to more than one partition");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── sparse_findere_for_genome vs. a dense reference implementation ──────────
|
||||
//
|
||||
// No property-testing crate (proptest/quickcheck) is a workspace dependency
|
||||
// (checked before writing this — not adding one for a single test module,
|
||||
// per this project's dependency-approval rule). A tiny deterministic xorshift
|
||||
// PRNG, std-only, stands in for one.
|
||||
|
||||
/// Faithful reimplementation of the pre-phase-5 dense sliding-window scan —
|
||||
/// the algorithm `sparse_findere_for_genome` replaced — used here only as a
|
||||
/// correctness oracle, not in production code. Operates on one genome's
|
||||
/// hits across possibly many sequences, exactly like the sparse version.
|
||||
fn dense_reference_findere(
|
||||
hits: &[(u32, u32, u32)],
|
||||
seq_lens: &[usize],
|
||||
z: usize,
|
||||
presence: bool,
|
||||
threshold: u32,
|
||||
) -> Vec<(u32, u32, u32)> {
|
||||
let mut by_seq: Vec<Vec<u32>> = seq_lens.iter().map(|&n| vec![0u32; n]).collect();
|
||||
for &(seq, pos, val) in hits {
|
||||
by_seq[seq as usize][pos as usize] = val;
|
||||
}
|
||||
|
||||
let mut confirmed = Vec::new();
|
||||
for (seq_idx, values) in by_seq.iter().enumerate() {
|
||||
let n = values.len();
|
||||
let mut dq: std::collections::VecDeque<(usize, u32)> = std::collections::VecDeque::new();
|
||||
for i in 0..n {
|
||||
let v_i = values[i];
|
||||
while dq.front().map_or(false, |&(f, _)| f + z <= i) {
|
||||
dq.pop_front();
|
||||
}
|
||||
while dq.back().map_or(false, |&(_, v)| v >= v_i) {
|
||||
dq.pop_back();
|
||||
}
|
||||
dq.push_back((i, v_i));
|
||||
if i + 1 >= z {
|
||||
let win_min = dq.front().unwrap().1;
|
||||
if win_min > 0 {
|
||||
let pos_out = (i + 1 - z) as u32;
|
||||
let c = if presence { u32::from(win_min >= threshold) } else { win_min };
|
||||
confirmed.push((seq_idx as u32, pos_out, c));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
confirmed
|
||||
}
|
||||
|
||||
/// Minimal std-only xorshift64 PRNG — deterministic, seedable, no dependency.
|
||||
struct Xorshift64(u64);
|
||||
impl Xorshift64 {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
fn range(&mut self, n: u32) -> u32 {
|
||||
(self.next() % n as u64) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sparse_findere_matches_dense_reference_on_random_inputs() {
|
||||
let mut rng = Xorshift64(0x5eed_5eed_5eed_5eedu64);
|
||||
|
||||
for case in 0..200 {
|
||||
let n_seqs = 1 + rng.range(4) as usize;
|
||||
let seq_lens: Vec<usize> = (0..n_seqs).map(|_| 1 + rng.range(30) as usize).collect();
|
||||
let z = 1 + rng.range(4) as usize;
|
||||
let presence = rng.range(2) == 0;
|
||||
let threshold = 1 + rng.range(3);
|
||||
|
||||
// Sparse density varies across cases, including edge cases (empty,
|
||||
// fully dense) — deliberately not uniform, to stress both few-hits
|
||||
// and many-overlapping-runs scenarios.
|
||||
let density = rng.range(101);
|
||||
let mut hits: Vec<(u32, u32, u32)> = Vec::new();
|
||||
for (seq_idx, &len) in seq_lens.iter().enumerate() {
|
||||
for pos in 0..len {
|
||||
if rng.range(100) < density {
|
||||
let val = 1 + rng.range(5); // never 0 — matches QueryHit::Value's invariant
|
||||
hits.push((seq_idx as u32, pos as u32, val));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut sparse_input = hits.clone();
|
||||
let (mut sparse_result, _, _) =
|
||||
sparse_findere_for_genome(&mut sparse_input, z, presence, threshold);
|
||||
let mut dense_result = dense_reference_findere(&hits, &seq_lens, z, presence, threshold);
|
||||
|
||||
sparse_result.sort_unstable();
|
||||
dense_result.sort_unstable();
|
||||
|
||||
assert_eq!(
|
||||
sparse_result, dense_result,
|
||||
"case {case}: n_seqs={n_seqs} seq_lens={seq_lens:?} z={z} presence={presence} \
|
||||
threshold={threshold} density={density} hits={hits:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obikindex::KmerIndex;
|
||||
use obikindex::layer::IndexMode;
|
||||
use obisys::Reporter;
|
||||
use tracing::info;
|
||||
|
||||
use crate::cli::block_size_to_bits;
|
||||
use super::index::resolve_approx_params;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct ReindexArgs {
|
||||
/// Index directory to convert (modified in-place)
|
||||
pub index: PathBuf,
|
||||
|
||||
/// Convert to approximate evidence (default: convert to exact).
|
||||
/// Requires --evidence-bits and/or -z and/or --fp.
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub approx: bool,
|
||||
|
||||
/// Findere z parameter (≥1).
|
||||
#[arg(short = 'z', long, default_value = None)]
|
||||
pub findere_z: Option<u8>,
|
||||
|
||||
/// Fingerprint bits per slot (b).
|
||||
#[arg(long, default_value = None)]
|
||||
pub evidence_bits: Option<u8>,
|
||||
|
||||
/// Target false-positive rate per z-window.
|
||||
#[arg(long, default_value = None)]
|
||||
pub fp: Option<f64>,
|
||||
|
||||
/// Block size for exact evidence `.idx` (number of unitigs per block).
|
||||
/// Ignored when converting to approximate evidence.
|
||||
#[arg(long, default_value_t = 1)]
|
||||
pub block_size: usize,
|
||||
}
|
||||
|
||||
pub fn run(args: ReindexArgs) {
|
||||
let target = if args.approx {
|
||||
let (z, b, fp) = resolve_approx_params(args.findere_z, args.evidence_bits, args.fp);
|
||||
info!("target: approximate evidence — b={b}, z={z}, fp={fp:.2e}");
|
||||
IndexMode::Approx { b, z }
|
||||
} else {
|
||||
info!("target: exact evidence");
|
||||
IndexMode::Exact
|
||||
};
|
||||
|
||||
// Modifies the index in place; acquired before opening so a concurrent
|
||||
// writer can't slip in between the open and the reindex below.
|
||||
let _lock = obisys::DirLock::acquire(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error locking index directory {}: {e}", args.index.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let mut idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
info!(
|
||||
"current evidence: {:?}",
|
||||
idx.meta().config.evidence,
|
||||
);
|
||||
|
||||
let block_bits = block_size_to_bits(args.block_size);
|
||||
let mut rep = Reporter::new();
|
||||
idx.reindex(target, block_bits, &mut rep).unwrap_or_else(|e| {
|
||||
eprintln!("reindex error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
rep.print();
|
||||
}
|
||||
@@ -1,14 +1,12 @@
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::{Args, ValueEnum};
|
||||
use obikindex::{IndexMeta, KmerIndex};
|
||||
use obikindex::{AggOp, OutputCol};
|
||||
use obisys::Reporter;
|
||||
use obikalgorithm::Algorithm;
|
||||
use obikindex::KmerIndex;
|
||||
use obikselect::{AggOp, ColumnSpecParams, Select, build_output_cols};
|
||||
use obisys::{Progress, Reporter, Stage, progress_bar};
|
||||
use tracing::info;
|
||||
|
||||
// ── CLI types ─────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
|
||||
pub enum AggOpArg {
|
||||
Any,
|
||||
@@ -22,12 +20,12 @@ pub enum AggOpArg {
|
||||
impl From<AggOpArg> for AggOp {
|
||||
fn from(a: AggOpArg) -> Self {
|
||||
match a {
|
||||
AggOpArg::Any => AggOp::Any,
|
||||
AggOpArg::All => AggOp::All,
|
||||
AggOpArg::Any => AggOp::Any,
|
||||
AggOpArg::All => AggOp::All,
|
||||
AggOpArg::None => AggOp::None,
|
||||
AggOpArg::Sum => AggOp::Sum,
|
||||
AggOpArg::Min => AggOp::Min,
|
||||
AggOpArg::Max => AggOp::Max,
|
||||
AggOpArg::Sum => AggOp::Sum,
|
||||
AggOpArg::Min => AggOp::Min,
|
||||
AggOpArg::Max => AggOp::Max,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -37,13 +35,9 @@ pub struct SelectArgs {
|
||||
/// Source index directory
|
||||
pub source: PathBuf,
|
||||
|
||||
/// Output index directory (mutually exclusive with --in-place)
|
||||
#[arg(long, conflicts_with = "in_place")]
|
||||
pub output: Option<PathBuf>,
|
||||
|
||||
/// Rewrite the source index in-place (mutually exclusive with --output)
|
||||
#[arg(long)]
|
||||
pub in_place: bool,
|
||||
/// Output index directory
|
||||
#[arg(short, long)]
|
||||
pub output: PathBuf,
|
||||
|
||||
/// Define a named group: `<name>:<pred>` (repeatable; mutually exclusive with --aggregate-by)
|
||||
#[arg(long, value_name = "NAME:PRED", conflicts_with = "aggregate_by")]
|
||||
@@ -69,173 +63,53 @@ pub struct SelectArgs {
|
||||
#[arg(long, default_value = "0")]
|
||||
pub presence_threshold: u32,
|
||||
|
||||
/// Pack the output's presence matrices in the dense format instead of the default sparse one
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub dense: bool,
|
||||
|
||||
/// Overwrite existing output directory
|
||||
#[arg(short, long)]
|
||||
pub force: bool,
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Split a repeatable `<name>:<value>` argument. Exits on malformed input.
|
||||
fn parse_name_value(s: &str, flag: &str) -> (String, String) {
|
||||
match s.find(':') {
|
||||
Some(pos) => (s[..pos].trim().to_string(), s[pos + 1..].to_string()),
|
||||
std::option::Option::None => {
|
||||
None => {
|
||||
eprintln!("error in {flag}: expected <name>:<value>, got: {s}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_agg_op(s: &str) -> AggOp {
|
||||
match s.to_lowercase().as_str() {
|
||||
"any" => AggOp::Any,
|
||||
"all" => AggOp::All,
|
||||
"none" => AggOp::None,
|
||||
"sum" => AggOp::Sum,
|
||||
"min" => AggOp::Min,
|
||||
"max" => AggOp::Max,
|
||||
other => {
|
||||
eprintln!("unknown aggregation operator: {other}; valid: any, all, none, sum, min, max");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn default_op(src_is_count: bool) -> AggOp {
|
||||
if src_is_count { AggOp::Sum } else { AggOp::Any }
|
||||
}
|
||||
|
||||
// ── build_specs ───────────────────────────────────────────────────────────────
|
||||
|
||||
/// Resolve CLI arguments into an ordered list of `OutputCol`.
|
||||
///
|
||||
/// Returns `(specs, output_presence)`.
|
||||
fn build_specs(
|
||||
args: &SelectArgs,
|
||||
meta: &IndexMeta,
|
||||
src_is_count: bool,
|
||||
) -> (Vec<OutputCol>, bool) {
|
||||
let genomes = meta.genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let genomes = &genomes;
|
||||
|
||||
// ── 1. Build group_indices: name → Vec<usize> ────────────────────────────
|
||||
// Also keep insertion order for the default `--select *` case.
|
||||
let mut group_order: Vec<String> = Vec::new();
|
||||
let mut group_indices: HashMap<String, Vec<usize>> = HashMap::new();
|
||||
|
||||
if let Some(ref key) = args.aggregate_by {
|
||||
// One group per unique value of `key`, in sorted order.
|
||||
let mut value_to_indices: BTreeMap<String, Vec<usize>> = BTreeMap::new();
|
||||
for (i, g) in genomes.iter().enumerate() {
|
||||
if let Some(v) = g.meta.get(key) {
|
||||
value_to_indices.entry(v.clone()).or_default().push(i);
|
||||
}
|
||||
}
|
||||
for (v, idxs) in value_to_indices {
|
||||
group_order.push(v.clone());
|
||||
group_indices.insert(v, idxs);
|
||||
}
|
||||
} else {
|
||||
for raw in &args.group {
|
||||
let (name, pred) = parse_name_value(raw, "--group");
|
||||
let idxs = meta.matching_genome_indices(&pred).unwrap_or_else(|e| {
|
||||
eprintln!("error in --group {name}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
if !group_indices.contains_key(&name) {
|
||||
group_order.push(name.clone());
|
||||
}
|
||||
group_indices.insert(name, idxs);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 2. Build per-group ops ────────────────────────────────────────────────
|
||||
let global_op = args.aggregate_op.map(AggOp::from);
|
||||
let mut group_op: HashMap<String, AggOp> = HashMap::new();
|
||||
for raw in &args.group_op {
|
||||
let (name, op_str) = parse_name_value(raw, "--group-op");
|
||||
if !group_indices.contains_key(&name) {
|
||||
eprintln!("--group-op references undefined group: {name}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
group_op.insert(name, parse_agg_op(&op_str));
|
||||
}
|
||||
|
||||
// ── 3. Genome label → index map for pass-through columns ─────────────────
|
||||
let label_to_idx: HashMap<&str, usize> = genomes.iter().enumerate()
|
||||
.map(|(i, g)| (g.label.as_str(), i))
|
||||
.collect();
|
||||
|
||||
// ── 4. Determine output column names ─────────────────────────────────────
|
||||
let col_names: Vec<String> = if let Some(ref sel) = args.select {
|
||||
sel.clone()
|
||||
} else if !group_order.is_empty() {
|
||||
group_order.clone()
|
||||
} else {
|
||||
// Identity: all genomes in original order
|
||||
genomes.iter().map(|g| g.label.clone()).collect()
|
||||
};
|
||||
|
||||
// ── 5. Build OutputCol list ───────────────────────────────────────────────
|
||||
let mut specs: Vec<OutputCol> = Vec::with_capacity(col_names.len());
|
||||
|
||||
for name in &col_names {
|
||||
if let Some(idxs) = group_indices.get(name) {
|
||||
let op = group_op.get(name)
|
||||
.copied()
|
||||
.or(global_op)
|
||||
.unwrap_or_else(|| default_op(src_is_count));
|
||||
specs.push(OutputCol { label: name.clone(), indices: idxs.clone(), op });
|
||||
} else if let Some(&idx) = label_to_idx.get(name.as_str()) {
|
||||
// Pass-through: single-element group with default op.
|
||||
let op = default_op(src_is_count);
|
||||
specs.push(OutputCol { label: name.clone(), indices: vec![idx], op });
|
||||
} else {
|
||||
eprintln!("--select: unknown column '{name}' (not a group name or genome label)");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if specs.is_empty() {
|
||||
eprintln!("select: no output columns defined");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// ── 6. Determine output type ──────────────────────────────────────────────
|
||||
let output_presence = !src_is_count
|
||||
|| specs.iter().all(|s| s.op.is_logical());
|
||||
|
||||
(specs, output_presence)
|
||||
}
|
||||
|
||||
// ── run ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn run(args: SelectArgs) {
|
||||
if !args.in_place && args.output.is_none() {
|
||||
eprintln!("error: one of --output or --in-place must be specified");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// Lock whichever directory actually gets written: the source itself in
|
||||
// --in-place mode, otherwise the (distinct) --output directory. Acquired
|
||||
// before opening the source so a concurrent writer can't slip in between
|
||||
// the open and the write below.
|
||||
let lock_target = if args.in_place { &args.source } else { args.output.as_ref().unwrap() };
|
||||
let _lock = obisys::DirLock::acquire(lock_target).unwrap_or_else(|e| {
|
||||
eprintln!("error locking {}: {e}", lock_target.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let mut src = KmerIndex::open(&args.source).unwrap_or_else(|e| {
|
||||
let src = KmerIndex::open(&args.source).unwrap_or_else(|e| {
|
||||
eprintln!("error opening source index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let group_preds: Vec<(String, String)> =
|
||||
args.group.iter().map(|s| parse_name_value(s, "--group")).collect();
|
||||
let group_ops: Vec<(String, String)> =
|
||||
args.group_op.iter().map(|s| parse_name_value(s, "--group-op")).collect();
|
||||
|
||||
let src_is_count = src.meta().config.with_counts;
|
||||
let (specs, output_presence) = build_specs(&args, &src.meta(), src_is_count);
|
||||
let (specs, output_presence) = build_output_cols(
|
||||
&src.meta(),
|
||||
ColumnSpecParams {
|
||||
group_preds: &group_preds,
|
||||
aggregate_by: args.aggregate_by.as_deref(),
|
||||
group_ops: &group_ops,
|
||||
aggregate_op: args.aggregate_op.map(AggOp::from),
|
||||
select: args.select.as_deref(),
|
||||
src_is_count,
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error building output columns: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let n_genomes = src.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
@@ -249,23 +123,22 @@ pub fn run(args: SelectArgs) {
|
||||
);
|
||||
|
||||
let mut rep = Reporter::new();
|
||||
let t = Stage::start("select");
|
||||
let pb = progress_bar("select", src.n_partitions() as u64, "partitions");
|
||||
let mut alg = Select::new(&src, &args.output, &specs, output_presence)
|
||||
.threshold(args.presence_threshold)
|
||||
.force(args.force)
|
||||
.sparse(!args.dense)
|
||||
.on_progress(|_: Progress| pb.inc(1));
|
||||
|
||||
if args.in_place {
|
||||
src.select_in_place(&specs, args.presence_threshold, output_presence, &mut rep)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("select error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.print();
|
||||
info!("selected in-place → {}", args.source.display());
|
||||
} else {
|
||||
let output = args.output.unwrap();
|
||||
KmerIndex::select(&output, &src, &specs, args.presence_threshold, output_presence, args.force, &mut rep)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("select error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
rep.print();
|
||||
info!("selected index → {}", output.display());
|
||||
}
|
||||
let dst = alg.run().unwrap_or_else(|e| {
|
||||
eprintln!("select error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
rep.push(t.stop());
|
||||
|
||||
info!("selected index → {}", dst.dir().display());
|
||||
alg.reporter().print();
|
||||
rep.print();
|
||||
}
|
||||
@@ -1,17 +1,15 @@
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::io::{self, BufWriter};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use clap::Args;
|
||||
use obidebruinj::GraphDeBruijn;
|
||||
use obifastwrite::write_unitig;
|
||||
use obikdump::IndexUnitigs;
|
||||
use obikfilter::KmerFilter;
|
||||
use obikindex::KmerIndex;
|
||||
use obisys::{Reporter, Stage, progress_bar, spinner};
|
||||
use rayon::prelude::*;
|
||||
use obisys::progress_bar;
|
||||
use tracing::info;
|
||||
|
||||
use super::predicate::FilterArgs;
|
||||
use super::predicate::GroupFilterArgs;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct UnitigArgs {
|
||||
@@ -19,83 +17,31 @@ pub struct UnitigArgs {
|
||||
pub index: PathBuf,
|
||||
|
||||
#[command(flatten)]
|
||||
pub filter: FilterArgs,
|
||||
pub group_filter: GroupFilterArgs,
|
||||
}
|
||||
|
||||
pub fn run(args: UnitigArgs) {
|
||||
let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
let idx = Arc::new(KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}));
|
||||
|
||||
let k = idx.kmer_size();
|
||||
let n = idx.n_partitions();
|
||||
let n_genomes = idx.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
info!(
|
||||
"unitig: building de Bruijn graph from {} partition(s) (k={})",
|
||||
idx.n_partitions(),
|
||||
idx.kmer_size(),
|
||||
);
|
||||
|
||||
let filters: Vec<Box<dyn KmerFilter>> = vec![Box::new(args.group_filter.build_filter(&idx.meta()))];
|
||||
let pb = progress_bar("unitig", idx.n_partitions() as u64, "partitions");
|
||||
|
||||
let mut out = BufWriter::new(io::stdout());
|
||||
|
||||
let n = idx.write_unitigs(&mut out, &filters, || pb.inc(1)).unwrap_or_else(|e| {
|
||||
eprintln!("unitig error: {e}");
|
||||
std::process::exit(1);
|
||||
}).len().max(1);
|
||||
let use_counts = idx.meta().config.with_counts;
|
||||
|
||||
info!("unitig: building de Bruijn graph from {n} partition(s) (k={k})");
|
||||
|
||||
let filters = args.filter.build_filters(&idx.meta());
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
// ── Phase 1 : collect filtered kmers in parallel ──────────────────────────
|
||||
let pb = progress_bar("unitig", n as u64, "partitions");
|
||||
let stage = Stage::start("build graph");
|
||||
let g = (0..n)
|
||||
.into_par_iter()
|
||||
.fold(GraphDeBruijn::new, |mut local_g, i| {
|
||||
idx
|
||||
.iter_partition_kmers(i, use_counts, n_genomes, &filters, |kmer, _row| {
|
||||
local_g.push(kmer);
|
||||
true
|
||||
})
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error reading partition {i}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
pb.inc(1);
|
||||
local_g
|
||||
})
|
||||
.reduce(GraphDeBruijn::new, |mut a, b| {
|
||||
a.merge(b);
|
||||
a
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
rep.push(stage.stop());
|
||||
|
||||
info!("unitig: {} distinct k-mers", g.len());
|
||||
|
||||
// ── Phase 2 : compute degrees ─────────────────────────────────────────────
|
||||
let pb = spinner("degrees");
|
||||
let stage = Stage::start("compute degrees");
|
||||
g.compute_degrees_and_mark_starts();
|
||||
pb.finish_and_clear();
|
||||
rep.push(stage.stop());
|
||||
|
||||
// ── Phase 3 : enumerate unitigs and write as FASTA ───────────────────────
|
||||
let pb = spinner("unitig");
|
||||
let out = Mutex::new(BufWriter::new(io::stdout()));
|
||||
let j = AtomicUsize::new(0);
|
||||
|
||||
let stage = Stage::start("enumerate unitigs");
|
||||
g.for_each_unitig(|nuc_iter| {
|
||||
let unitig: obikseq::unitig::Unitig = nuc_iter.collect();
|
||||
let idx = j.fetch_add(1, Ordering::Relaxed);
|
||||
let mut w = out.lock().unwrap();
|
||||
write_unitig(&unitig, k, 0, idx, &mut *w).unwrap_or_else(|e| {
|
||||
eprintln!("write error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
if idx % 10_000 == 0 {
|
||||
pb.set_message(format!("{idx} unitigs written"));
|
||||
}
|
||||
});
|
||||
pb.finish_and_clear();
|
||||
rep.push(stage.stop());
|
||||
|
||||
out.into_inner().unwrap().flush().expect("flush error");
|
||||
rep.print();
|
||||
info!("unitig: {n} unitig(s) written");
|
||||
}
|
||||
@@ -1,22 +1,26 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
|
||||
use obikalgorithm::Algorithm;
|
||||
use obikindex::{GenomeInfo, KmerIndex};
|
||||
use obikstats::IndexBitsPerKmer;
|
||||
use obikstats::{BitsPerKmer, GenomeKmerCounts};
|
||||
use tracing::info;
|
||||
|
||||
pub(super) fn run_stats(index_path: &PathBuf) {
|
||||
let idx = KmerIndex::open(index_path).unwrap_or_else(|e| {
|
||||
let idx = Arc::new(KmerIndex::open(index_path).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let (total, per_genome) = idx.genome_kmer_counts().unwrap_or_else(|e| {
|
||||
eprintln!("error computing stats: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}));
|
||||
let genomes = idx.meta().genomes().unwrap_or_else(|e| {
|
||||
eprintln!("error reading index metadata: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let (total, per_genome) = GenomeKmerCounts::new(Arc::clone(&idx)).run().unwrap_or_else(|e| {
|
||||
eprintln!("error computing stats: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
println!("genome,n_kmers");
|
||||
for (g, &n) in genomes.iter().zip(per_genome.iter()) {
|
||||
println!("{},{}", g.label, n);
|
||||
@@ -25,14 +29,16 @@ pub(super) fn run_stats(index_path: &PathBuf) {
|
||||
}
|
||||
|
||||
pub(super) fn run_bits_per_kmer(index_path: &PathBuf) {
|
||||
let idx = KmerIndex::open(index_path).unwrap_or_else(|e| {
|
||||
let idx = Arc::new(KmerIndex::open(index_path).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
let stats: IndexBitsPerKmer = idx.bits_per_kmer().unwrap_or_else(|e| {
|
||||
}));
|
||||
|
||||
let stats = BitsPerKmer::new(idx).run().unwrap_or_else(|e| {
|
||||
eprintln!("error computing bits/kmer: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
println!("k-mers : {}", stats.n_kmers);
|
||||
println!("genomes : {}", stats.n_genomes);
|
||||
println!("mphf : {:6.2} bits/kmer", stats.mphf);
|
||||
@@ -44,18 +50,6 @@ pub(super) fn run_bits_per_kmer(index_path: &PathBuf) {
|
||||
println!("total : {:6.2} bits/kmer", stats.total);
|
||||
}
|
||||
|
||||
pub(super) fn run_upgrade_index(index_path: &PathBuf) {
|
||||
let idx = KmerIndex::open(index_path).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
idx.upgrade_layer_meta().unwrap_or_else(|e| {
|
||||
eprintln!("upgrade error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
info!("upgrade-index: layer_meta.json written to all layers that were missing it");
|
||||
}
|
||||
|
||||
pub(super) fn run_rename(index_path: &PathBuf, spec: &str) {
|
||||
let (old_label, new_label) = parse_rename_spec(spec);
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
|
||||
use maintenance::{run_bits_per_kmer, run_stats, run_upgrade_index, run_rename};
|
||||
use maintenance::{run_bits_per_kmer, run_stats, run_rename};
|
||||
use partition_stats::run_partition_stats;
|
||||
|
||||
#[derive(Args)]
|
||||
@@ -18,10 +18,6 @@ pub struct UtilsArgs {
|
||||
#[arg(long, value_name = "NEW=OLD")]
|
||||
pub new_label: Option<String>,
|
||||
|
||||
/// Add missing layer_meta.json files to each layer (single-index only)
|
||||
#[arg(long)]
|
||||
pub upgrade_index: bool,
|
||||
|
||||
/// Print bits-per-kmer statistics (single-index only)
|
||||
#[arg(long)]
|
||||
pub bits_per_kmer: bool,
|
||||
@@ -47,11 +43,6 @@ pub fn run(args: UtilsArgs) {
|
||||
run_rename(single_index(&args), spec);
|
||||
}
|
||||
|
||||
if args.upgrade_index {
|
||||
any = true;
|
||||
run_upgrade_index(single_index(&args));
|
||||
}
|
||||
|
||||
if args.bits_per_kmer {
|
||||
any = true;
|
||||
run_bits_per_kmer(single_index(&args));
|
||||
@@ -70,7 +61,7 @@ pub fn run(args: UtilsArgs) {
|
||||
if !any {
|
||||
eprintln!(
|
||||
"utils: no operation specified. \
|
||||
Available: --new-label, --upgrade-index, --bits-per-kmer, --stats, --partition-stats"
|
||||
Available: --new-label, --bits-per-kmer, --stats, --partition-stats"
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
@@ -24,11 +24,15 @@ fn collect_rows(indexes: &[PathBuf]) -> Vec<PartRow> {
|
||||
let n_parts = idx.n_partitions();
|
||||
for i in 0..n_parts {
|
||||
let mut bytes = 0u64;
|
||||
for l in 0.. {
|
||||
let p = idx.layer_unitigs_path(i, l);
|
||||
if !p.exists() {
|
||||
break;
|
||||
}
|
||||
let n_layers = idx.n_layers(i).unwrap_or_else(|e| {
|
||||
eprintln!("error reading partition {i} of {}: {e}", path.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
for l in 0..n_layers {
|
||||
let p = idx.layer_unitigs_path(i, l).unwrap_or_else(|e| {
|
||||
eprintln!("error reading layer {l} of partition {i} of {}: {e}", path.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
if let Ok(m) = std::fs::metadata(&p) {
|
||||
bytes += m.len();
|
||||
}
|
||||
|
||||
+36
-64
@@ -5,7 +5,7 @@ use clap::{Parser, Subcommand};
|
||||
use tracing_subscriber::{EnvFilter, fmt};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(name = "obikmer", about = "DNA k-mer tools", version)]
|
||||
#[command(name = "obikmer2", about = "DNA k-mer tools", version)]
|
||||
struct Cli {
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
@@ -13,38 +13,35 @@ struct Cli {
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Extract super-kmers from a sequence file and write to stdout
|
||||
Superkmer(cmd::superkmer::SuperkmerArgs),
|
||||
/// Build the complete genome index (scatter → dereplicate → count → layered MPHF)
|
||||
Index(cmd::index::IndexArgs),
|
||||
/// Merge multiple built indexes into one
|
||||
/// Extract super-k-mers from input sequences and scatter them by partition
|
||||
Superkmer(cmd::superkmer::SuperkmerArgs),
|
||||
/// Merge multiple genome indexes into one
|
||||
Merge(cmd::merge::MergeArgs),
|
||||
/// Apply row-level selection (σ) to an index: retain only k-mers matching the predicates
|
||||
Filter(cmd::filter::FilterCmdArgs),
|
||||
/// Project and/or aggregate genome columns into a new or in-place index
|
||||
/// Filter kmers out of an index by genome metadata / abundance / complexity
|
||||
Filter(cmd::filter::FilterArgs),
|
||||
/// Project/aggregate genome columns into a new index
|
||||
Select(cmd::select::SelectArgs),
|
||||
/// Query an index with sequences and annotate matches
|
||||
Query(cmd::query::QueryArgs),
|
||||
/// Dump all indexed kmers as CSV (kmer + per-genome counts or presence)
|
||||
/// Dump an index's kmers as a CSV table
|
||||
Dump(cmd::dump::DumpArgs),
|
||||
/// Add or update genome metadata from a CSV file; or dump metadata as CSV
|
||||
Annotate(cmd::annotate::AnnotateArgs),
|
||||
/// Compute pairwise evolutionary-distance proxies between genomes (metric matrix, NJ/UPGMA
|
||||
/// trees, SNP/Sankoff calibration, TNT/PhyG/IQ-TREE exports)
|
||||
Phylo(cmd::phylo::PhyloArgs),
|
||||
/// Translate a numerically-labelled tree export (TNT/PhyG) back to real taxon names, from
|
||||
/// the FASTA that produced it
|
||||
NameTree(cmd::nametree::NameTreeArgs),
|
||||
/// Dump unitigs from a built index to stdout (debug)
|
||||
/// Query sequences against an index, annotating each with per-genome matches
|
||||
Query(cmd::query::QueryArgs),
|
||||
/// Assemble an index's kmers into unitigs and write them as FASTA
|
||||
Unitig(cmd::unitig::UnitigArgs),
|
||||
/// Estimate approximate-index parameters (z, evidence bits, FP rates) before indexing
|
||||
Estimate(cmd::estimate::EstimateArgs),
|
||||
/// Convert an index's evidence in-place: exact ↔ approx
|
||||
Reindex(cmd::reindex::ReindexArgs),
|
||||
/// Miscellaneous index utilities (--rename, …)
|
||||
Utils(cmd::utils::UtilsArgs),
|
||||
/// Pack matrix column files into single-file format to reduce query I/O
|
||||
/// Pack an index's matrices into single-file, sparse format by default (--dense to opt out), in place
|
||||
Pack(cmd::pack::PackArgs),
|
||||
/// Estimate approximate-evidence false-positive rates for given parameters
|
||||
Estimate(cmd::estimate::EstimateArgs),
|
||||
/// Read/write genome metadata (CSV) on an already-built index
|
||||
Annotate(cmd::annotate::AnnotateArgs),
|
||||
/// Maintenance/inspection operations on already-built indexes
|
||||
Utils(cmd::utils::UtilsArgs),
|
||||
/// Convert an index's evidence representation (exact/approximate/hybrid), in place
|
||||
Convert(cmd::convert::ConvertArgs),
|
||||
/// Genome-vs-genome distance matrix (+ optional NJ/UPGMA tree, sibling-annex-based
|
||||
/// SNP corrections, Sankoff/TNT/PhyG/IQ-TREE exports)
|
||||
Phylo(cmd::phylo::PhyloArgs),
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -55,46 +52,21 @@ fn main() {
|
||||
.with_writer(std::io::stderr)
|
||||
.init();
|
||||
|
||||
#[cfg(feature = "profiling")]
|
||||
let _guard = {
|
||||
let guard = pprof::ProfilerGuardBuilder::default()
|
||||
.frequency(1000)
|
||||
.build()
|
||||
.expect("failed to start pprof profiler");
|
||||
guard
|
||||
};
|
||||
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
Commands::Index(args) => cmd::index::run(args),
|
||||
Commands::Superkmer(args) => cmd::superkmer::run(args),
|
||||
Commands::Index(args) => cmd::index::run(args),
|
||||
Commands::Merge(args) => cmd::merge::run(args),
|
||||
Commands::Dump(args) => cmd::dump::run(args),
|
||||
Commands::Filter(args) => cmd::filter::run(args),
|
||||
Commands::Select(args) => cmd::select::run(args),
|
||||
Commands::Query(args) => cmd::query::run(args),
|
||||
Commands::Annotate(args) => cmd::annotate::run(args),
|
||||
Commands::Phylo(args) => cmd::phylo::run(args),
|
||||
Commands::NameTree(args) => cmd::nametree::run(args),
|
||||
Commands::Unitig(args) => cmd::unitig::run(args),
|
||||
Commands::Estimate(args) => cmd::estimate::run(args),
|
||||
Commands::Reindex(args) => cmd::reindex::run(args),
|
||||
Commands::Utils(args) => cmd::utils::run(args),
|
||||
Commands::Pack(args) => cmd::pack::run(args),
|
||||
}
|
||||
|
||||
#[cfg(feature = "profiling")]
|
||||
{
|
||||
use pprof::protos::Message;
|
||||
if let Ok(report) = _guard.report().build() {
|
||||
let mut bytes = Vec::new();
|
||||
report
|
||||
.pprof()
|
||||
.expect("pprof encode failed")
|
||||
.encode(&mut bytes)
|
||||
.expect("pprof encode failed");
|
||||
std::fs::write("profile.pb", &bytes).expect("cannot write profile.pb");
|
||||
eprintln!("profile written to profile.pb");
|
||||
}
|
||||
Commands::Merge(args) => cmd::merge::run(args),
|
||||
Commands::Filter(args) => cmd::filter::run(args),
|
||||
Commands::Select(args) => cmd::select::run(args),
|
||||
Commands::Dump(args) => cmd::dump::run(args),
|
||||
Commands::Query(args) => cmd::query::run(args),
|
||||
Commands::Unitig(args) => cmd::unitig::run(args),
|
||||
Commands::Pack(args) => cmd::pack::run(args),
|
||||
Commands::Estimate(args) => cmd::estimate::run(args),
|
||||
Commands::Annotate(args) => cmd::annotate::run(args),
|
||||
Commands::Utils(args) => cmd::utils::run(args),
|
||||
Commands::Convert(args) => cmd::convert::run(args),
|
||||
Commands::Phylo(args) => cmd::phylo::run(args),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user