feat: Implement query subcommand for sequence-to-genome mapping
This change introduces the `query` CLI command and its supporting infrastructure for sequence-to-genome mapping and k-mer matching. It adds a `QueryLayer` abstraction backed by MPHF and persistent matrices, exposes the index partition for direct querying, and implements `Hash`/`Eq` for `RoutableSuperKmer`. The command ingests sequence batches, deduplicates superkmers, routes them to index partitions for parallel exact or 1-mismatch matching, and outputs results as FASTA records annotated with JSON metadata. Includes `serde_json` dependency addition, module exports, and documentation updates.
This commit is contained in:
1 parent
c8e591fc78
commit
13599dd444
13 files changed
+762
-19
No files matched your search
@@ -19,6 +19,7 @@ obisys = { path = "../obisys" }
|
||||
obiskio = { path = "../obiskio" }
|
||||
obikindex = { path = "../obikindex" }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
kodama = "0.2"
|
||||
speedytree = "0.1"
|
||||
rayon = "1"
|
||||
|
||||
@@ -2,6 +2,7 @@ pub mod distance;
|
||||
pub mod dump;
|
||||
pub mod index;
|
||||
pub mod merge;
|
||||
pub mod query;
|
||||
pub mod rebuild;
|
||||
pub mod superkmer;
|
||||
pub mod unitig;
|
||||
@@ -0,0 +1,281 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obikindex::KmerIndex;
|
||||
use obiread::record::{SeqRecord, parse_chunk};
|
||||
use obiread::chunk::read_sequence_chunks;
|
||||
use obikseq::{RoutableSuperKmer, set_k, set_m};
|
||||
use obiskbuilder::SuperKmerIter;
|
||||
use tracing::info;
|
||||
|
||||
// ── CLI ───────────────────────────────────────────────────────────────────────
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct QueryArgs {
|
||||
/// Index directory
|
||||
pub index: PathBuf,
|
||||
|
||||
/// Input sequences (FASTA/FASTQ, optionally gzip-compressed)
|
||||
#[arg(num_args = 1..)]
|
||||
pub inputs: Vec<String>,
|
||||
|
||||
/// Also report per-position coverage vectors (cov_<i> per genome)
|
||||
#[arg(long)]
|
||||
pub detail: bool,
|
||||
|
||||
/// Enable 1-mismatch approximate matching
|
||||
#[arg(long)]
|
||||
pub mismatch: bool,
|
||||
|
||||
/// Count k-mers absent from the index (adds kmer_missing annotation)
|
||||
#[arg(long)]
|
||||
pub count_missing: bool,
|
||||
|
||||
/// Report per-genome presence (0/1) instead of raw counts
|
||||
#[arg(long)]
|
||||
pub force_presence: bool,
|
||||
|
||||
/// Minimum accumulated match count to declare a genome present (implies --force-presence)
|
||||
#[arg(long, default_value_t = 1)]
|
||||
pub presence_threshold: u32,
|
||||
|
||||
/// Number of worker threads
|
||||
#[arg(
|
||||
short = 'T',
|
||||
long,
|
||||
default_value_t = std::thread::available_parallelism()
|
||||
.map(|n| n.get())
|
||||
.unwrap_or(1)
|
||||
)]
|
||||
pub threads: usize,
|
||||
}
|
||||
|
||||
// ── SKDesc — one occurrence of a superkmer in the batch ───────────────────────
|
||||
|
||||
/// Describes one occurrence of a superkmer in the query batch.
|
||||
pub struct SKDesc {
|
||||
/// Index of the source sequence within the batch.
|
||||
pub seq_idx: u32,
|
||||
/// Kmer offset of the first kmer of this superkmer within its sequence.
|
||||
/// Computed as the cumulative number of kmers emitted before this superkmer
|
||||
/// in the same sequence. Used for `--detail` coverage vectors.
|
||||
pub kmer_offset: u32,
|
||||
}
|
||||
|
||||
// ── QueryBatch ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// A batch of query sequences with their superkmers deduplicated.
|
||||
///
|
||||
/// Each unique `RoutableSuperKmer` maps to all the (seq_idx, kmer_offset)
|
||||
/// positions it occupies across the batch. The superkmer is queried once
|
||||
/// per partition; the result is broadcast to every SKDesc entry.
|
||||
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>>,
|
||||
/// Per-sequence total kmer count (kmer_count + kmer_missing).
|
||||
pub n_kmers: Vec<u32>,
|
||||
/// Deduplicated superkmer map.
|
||||
pub map: HashMap<RoutableSuperKmer, Vec<SKDesc>>,
|
||||
}
|
||||
|
||||
impl QueryBatch {
|
||||
/// Build a batch from a vec of parsed sequence records.
|
||||
pub fn from_records(
|
||||
records: Vec<SeqRecord>,
|
||||
k: usize,
|
||||
level_max: usize,
|
||||
theta: f64,
|
||||
) -> 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 mut map: HashMap<RoutableSuperKmer, Vec<SKDesc>> = HashMap::new();
|
||||
|
||||
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 n = (rsk.seql() - k + 1) as u32;
|
||||
map.entry(rsk)
|
||||
.or_default()
|
||||
.push(SKDesc { seq_idx: seq_idx as u32, kmer_offset });
|
||||
kmer_offset += n;
|
||||
}
|
||||
|
||||
ids.push(record.id);
|
||||
seqs.push(record.sequence);
|
||||
n_kmers.push(kmer_offset);
|
||||
}
|
||||
|
||||
Self { ids, seqs, n_kmers, map }
|
||||
}
|
||||
|
||||
/// Split the superkmer map by partition index.
|
||||
///
|
||||
/// Returns a vec of length `n_partitions`; each slot holds the RSK refs
|
||||
/// whose minimizer routes to that partition.
|
||||
pub fn split_by_partition(&self, n_partitions: usize) -> Vec<Vec<&RoutableSuperKmer>> {
|
||||
let mask = (n_partitions as u64) - 1;
|
||||
let mut by_part: Vec<Vec<&RoutableSuperKmer>> = vec![Vec::new(); n_partitions];
|
||||
for rsk in self.map.keys() {
|
||||
let part = (rsk.minimizer().seq_hash() & mask) as usize;
|
||||
by_part[part].push(rsk);
|
||||
}
|
||||
by_part
|
||||
}
|
||||
}
|
||||
|
||||
// ── Per-sequence accumulator ──────────────────────────────────────────────────
|
||||
|
||||
struct SeqAcc {
|
||||
kmer_count: u32,
|
||||
kmer_missing: u32,
|
||||
/// Per-genome accumulated count (count mode) or presence sum (presence mode).
|
||||
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],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Entry point ───────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn run(args: QueryArgs) {
|
||||
let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
set_k(idx.kmer_size());
|
||||
set_m(idx.minimizer_size());
|
||||
|
||||
let k = idx.kmer_size();
|
||||
let n_genomes = idx.meta().genomes.len();
|
||||
let n_partitions = idx.n_partitions();
|
||||
let with_counts = idx.meta().config.with_counts;
|
||||
|
||||
info!(
|
||||
"query: k={k}, {} genome(s), with_counts={with_counts}, mismatch={}, detail={}",
|
||||
n_genomes, args.mismatch, args.detail
|
||||
);
|
||||
|
||||
if args.mismatch {
|
||||
eprintln!("warning: --mismatch not yet implemented, ignored");
|
||||
}
|
||||
if args.detail {
|
||||
eprintln!("warning: --detail not yet implemented, ignored");
|
||||
}
|
||||
|
||||
let paths: Vec<PathBuf> = args.inputs.iter().map(PathBuf::from).collect();
|
||||
let mut out = BufWriter::new(io::stdout());
|
||||
|
||||
for path in &paths {
|
||||
let chunks = read_sequence_chunks(path.to_str().unwrap_or(""))
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error opening {}: {e}", path.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
for chunk_result in chunks {
|
||||
let chunk = chunk_result.unwrap_or_else(|e| {
|
||||
eprintln!("read error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let records = parse_chunk(&chunk, k);
|
||||
if records.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let batch = QueryBatch::from_records(records, k, 6, 0.7);
|
||||
let n_seqs = batch.ids.len();
|
||||
|
||||
let mut accs: Vec<SeqAcc> = (0..n_seqs).map(|_| SeqAcc::new(n_genomes)).collect();
|
||||
|
||||
let by_part = batch.split_by_partition(n_partitions);
|
||||
|
||||
for (part_idx, part_sks) in by_part.iter().enumerate() {
|
||||
if part_sks.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let kmer_results = idx
|
||||
.partition()
|
||||
.query_partition(part_idx, part_sks, k, n_genomes, with_counts)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("query error on partition {part_idx}: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
let presence = args.force_presence || !with_counts;
|
||||
let threshold = args.presence_threshold;
|
||||
|
||||
for (rsk, sk_kmer_results) in part_sks.iter().zip(kmer_results.iter()) {
|
||||
let descs = batch.map.get(*rsk).expect("rsk must be in map");
|
||||
for desc in descs {
|
||||
let acc = &mut accs[desc.seq_idx as usize];
|
||||
for hit in sk_kmer_results.iter() {
|
||||
match hit {
|
||||
None => acc.kmer_missing += 1,
|
||||
Some(row) => {
|
||||
acc.kmer_count += 1;
|
||||
for (g, &v) in row.iter().enumerate() {
|
||||
acc.genome_totals[g] += if presence {
|
||||
u32::from(v >= threshold)
|
||||
} else {
|
||||
v
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
emit_batch(&batch, &accs, idx.meta(), args.count_missing, &mut out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Output ────────────────────────────────────────────────────────────────────
|
||||
|
||||
fn emit_batch(
|
||||
batch: &QueryBatch,
|
||||
accs: &[SeqAcc],
|
||||
meta: &obikindex::meta::IndexMeta,
|
||||
count_missing: bool,
|
||||
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, label) in meta.genomes.iter().enumerate() {
|
||||
match_map.insert(label.clone(), acc.genome_totals[g].into());
|
||||
}
|
||||
ann.insert("kmer_strict_matches".into(), match_map.into());
|
||||
|
||||
let ann_str = serde_json::to_string(&ann).unwrap_or_else(|_| "{}".to_string());
|
||||
|
||||
// OBITools4 FASTA format: >id {"key":value,...}
|
||||
let _ = writeln!(out, ">{id} {ann_str}");
|
||||
let _ = out.write_all(seq);
|
||||
let _ = out.write_all(b"\n");
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,8 @@ enum Commands {
|
||||
Merge(cmd::merge::MergeArgs),
|
||||
/// Filter and compact an existing index into a new single-layer index
|
||||
Rebuild(cmd::rebuild::RebuildArgs),
|
||||
/// 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(cmd::dump::DumpArgs),
|
||||
/// Compute pairwise distance matrix between genomes; optionally build NJ/UPGMA trees
|
||||
@@ -54,6 +56,7 @@ fn main() {
|
||||
Commands::Merge(args) => cmd::merge::run(args),
|
||||
Commands::Dump(args) => cmd::dump::run(args),
|
||||
Commands::Rebuild(args) => cmd::rebuild::run(args),
|
||||
Commands::Query(args) => cmd::query::run(args),
|
||||
Commands::Distance(args) => cmd::distance::run(args),
|
||||
Commands::Unitig(args) => cmd::unitig::run(args),
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user