refactor: implement RoutableSuperKmer and update k-mer indexing pipeline

Replace raw SuperkMer routing with a new RoutableSuperKimer type that embeds canonical sequences and precomputed minimizers, enabling direct partition routing via hash. Update the build pipeline to yield RoutableSuperKmers throughout (builder, scatterer), refactor FASTA/unitig export commands to use the new type and compressed outputs (.fasta.gz, .unitigs.fasta.zst), revise SuperKmer header to store n_kmers instead of seql (avoiding 256-byte wrap), and update documentation to reflect minimizer-based theory, two evidence-encoding strategies for unitig-MPHF indexing (global offset vs. ID+rank), and the new obipipeline library architecture with parallel workers, biased scheduling, and error handling.
This commit is contained in:
Eric Coissac committed 2026-05-01 09:33:26 +02:00
1 parent 4e26e3bd40
commit 27f5e88a7b
72 files changed
+10093 -1626

No files matched your search

+6
View File
@@ -13,9 +13,15 @@ obiread = { path = "../obiread" }
obiskbuilder = { path = "../obiskbuilder" }
obifastwrite = { path = "../obifastwrite" }
obipipeline = { path = "../obipipeline" }
obidebruinj = { path = "../obidebruinj" }
clap = { version = "4", features = ["derive"] }
obikrope = { path = "../obikrope" }
obikpartitionner = { path = "../obikpartitionner" }
obiskio = { path = "../obiskio" }
niffler = "3"
rayon = "1"
ph = "0.11"
memmap2 = "0.9"
tracing = "0.1.44"
tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] }
pprof = { version = "0.13", features = ["prost-codec"], optional = true }
+2 -2
View File
@@ -3,7 +3,7 @@ use std::path::PathBuf;
use clap::Args;
use obikrope::Rope;
use obikseq::superkmer::SuperKmer;
use obikseq::RoutableSuperKmer;
// ── Shared arguments ──────────────────────────────────────────────────────────
@@ -57,7 +57,7 @@ pub enum PipelineData {
Path(PathBuf),
RawChunk(Rope),
NormChunk(Rope),
Batch(Vec<SuperKmer>),
Batch(Vec<RoutableSuperKmer>),
}
// SAFETY: Rope contains Cell<u8> which is !Sync, but pipeline ownership transfers
+84
View File
@@ -0,0 +1,84 @@
use std::fs::File;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use clap::Args;
use niffler::Level;
use niffler::send::compression::Format;
use obifastwrite::write_count;
use obikpartitionner::KmerPartition;
use obiskio::SKFileReader;
use rayon::prelude::*;
use tracing::info;
#[derive(Args)]
pub struct FastaArgs {
/// Root of the k-mer partition directory (produced by the `partition` command)
pub partition: PathBuf,
/// Dump dereplicated super-kmers as FASTA (→ <partition>/dereplicated.skmer.fasta.gz)
#[arg(long)]
pub super_kmers: bool,
}
pub fn run(args: FastaArgs) {
if !args.super_kmers {
eprintln!("error: specify at least one output mode (--super-kmers)");
std::process::exit(1);
}
let kp = KmerPartition::open(&args.partition).unwrap_or_else(|e| {
eprintln!("error opening partition: {e}");
std::process::exit(1)
});
if args.super_kmers {
dump_super_kmers(&kp, &args.partition);
}
}
fn dump_super_kmers(kp: &KmerPartition, partition_dir: &PathBuf) {
let k = kp.kmer_size();
let m = kp.minimizer_size();
let n = kp.n_partitions();
info!("writing {n} partition FASTA files (parallel)");
let total = AtomicUsize::new(0);
(0..n).into_par_iter().for_each(|i| {
let part_dir = partition_dir.join(format!("part_{i:05}"));
let in_path = part_dir.join("dereplicated.skmer.zst");
if !in_path.exists() {
return;
}
let out_path = part_dir.join("dereplicated.skmer.fasta.gz");
let file = File::create(&out_path).unwrap_or_else(|e| {
eprintln!("error creating {}: {e}", out_path.display());
std::process::exit(1)
});
let mut writer = niffler::send::get_writer(Box::new(file), Format::Gzip, Level::Six)
.unwrap_or_else(|e| {
eprintln!("error creating gzip writer: {e}");
std::process::exit(1)
});
let mut reader = SKFileReader::open(&in_path, k).unwrap_or_else(|e| {
eprintln!("error opening {}: {e}", in_path.display());
std::process::exit(1)
});
let mut count = 0usize;
for sk in reader.iter() {
write_count(&sk, &mut writer, k, m, i as u32).unwrap_or_else(|e| {
eprintln!("write error: {e}");
std::process::exit(1)
});
count += 1;
}
info!("partition {i}: {count} super-kmers → {}", out_path.display());
total.fetch_add(count, Ordering::Relaxed);
});
info!("wrote {} super-kmers total", total.load(Ordering::Relaxed));
}
+2
View File
@@ -1,3 +1,5 @@
pub mod count;
pub mod fasta;
pub mod partition;
pub mod superkmer;
pub mod unitig;
+4 -4
View File
@@ -2,7 +2,7 @@ use std::path::PathBuf;
use clap::Args;
use obikpartitionner::KmerPartition;
use obikseq::superkmer::SuperKmer;
use obikseq::RoutableSuperKmer;
use tracing::info;
use crate::cli::{CommonArgs, PipelineData, open_chunks};
@@ -39,14 +39,14 @@ pub fn run(args: PartitionArgs) {
let path_source = args.common.seqfile_paths();
let pipe = obipipeline::make_pipe! {
PipelineData : PathBuf => Vec<SuperKmer>,
PipelineData : PathBuf => Vec<RoutableSuperKmer>,
||? { |path| open_chunks(path) } : Path => RawChunk,
|? { move |rope| obiread::normalize_sequence_chunk(rope, k) } : RawChunk => NormChunk,
| { move |rope| obiskbuilder::build_superkmers(rope, k, m, level_max, theta) }: NormChunk => Batch,
};
for mut batch in pipe.apply(path_source, n_workers, 1) {
kp.write_batch(&mut batch).unwrap_or_else(|e| {
for batch in pipe.apply(path_source, n_workers, 1) {
kp.write_batch(batch).unwrap_or_else(|e| {
eprintln!("error: {e}");
std::process::exit(1)
});
+6 -9
View File
@@ -3,7 +3,7 @@ use std::path::PathBuf;
use clap::Args;
use obifastwrite::write_scatter;
use obikseq::superkmer::SuperKmer;
use obikseq::RoutableSuperKmer;
use crate::cli::{CommonArgs, PipelineData, open_chunks};
@@ -16,20 +16,17 @@ pub struct SuperkmerArgs {
// ── Stage functions ───────────────────────────────────────────────────────────
fn write_batch(
batch: Vec<SuperKmer>,
batch: Vec<RoutableSuperKmer>,
out: &mut BufWriter<io::Stdout>,
partition_bits: usize,
k: usize,
m: usize,
) -> io::Result<()> {
let partition_mask = (1u64 << partition_bits) - 1;
for sk in batch {
let minimizer = sk
.kmer(sk.minimizer_pos() as usize, m)
.map_err(io::Error::other)?
.canonical(m);
for rsk in batch {
let minimizer = *rsk.minimizer();
let partition = (minimizer.hash(m) & partition_mask) as usize;
write_scatter(&sk, out, k, m, partition, minimizer)?;
write_scatter(rsk.superkmer(), out, k, m, partition, minimizer)?;
}
Ok(())
}
@@ -47,7 +44,7 @@ pub fn run(args: SuperkmerArgs) {
let path_source = args.common.seqfile_paths();
let pipe = obipipeline::make_pipe! {
PipelineData : PathBuf => Vec<SuperKmer>,
PipelineData : PathBuf => Vec<RoutableSuperKmer>,
||? { |path| open_chunks(path) } : Path => RawChunk,
|? { move |rope| obiread::normalize_sequence_chunk(rope, k) } : RawChunk => NormChunk,
| { move |rope| obiskbuilder::build_superkmers(rope, k, m, level_max, theta) }: NormChunk => Batch,
+138
View File
@@ -0,0 +1,138 @@
use std::fs::File;
use std::path::PathBuf;
use std::sync::atomic::{AtomicUsize, Ordering};
use clap::Args;
use niffler::Level;
use niffler::send::compression::Format;
use obidebruinj::GraphDeBruijn;
use obikpartitionner::KmerPartition;
use obiskio::SKFileReader;
use ph::fmph::GOFunction;
use rayon::prelude::*;
use tracing::info;
#[derive(Args)]
pub struct UnitigArgs {
/// Root of the k-mer partition directory (produced by the `partition` command)
pub partition: PathBuf,
/// Minimum kmer abundance (inclusive); kmers below this threshold are excluded
#[arg(long, default_value_t = 1)]
pub min_abundance: u32,
/// Maximum kmer abundance (inclusive); kmers above this threshold are excluded
#[arg(long)]
pub max_abundance: Option<u32>,
}
pub fn run(args: UnitigArgs) {
let kp = KmerPartition::open(&args.partition).unwrap_or_else(|e| {
eprintln!("error opening partition: {e}");
std::process::exit(1)
});
let k = kp.kmer_size();
let n = kp.n_partitions();
info!("building unitigs from {n} partitions (k={k}, parallel)");
let total_kmers = AtomicUsize::new(0);
(0..n).into_par_iter().for_each(|i| {
let part_dir = args.partition.join(format!("part_{i:05}"));
let in_path = part_dir.join("dereplicated.skmer.zst");
if !in_path.exists() {
return;
}
let out_path = part_dir.join("unitig.fasta.gz");
let mut g = GraphDeBruijn::new(k);
let mphf_path = part_dir.join("mphf1.bin");
let counts_path = part_dir.join("counts1.bin");
let filter_active = (args.min_abundance > 1 || args.max_abundance.is_some())
&& mphf_path.exists()
&& counts_path.exists();
let mphf_opt: Option<GOFunction> = if filter_active {
let mut f = File::open(&mphf_path).unwrap_or_else(|e| {
eprintln!("error opening {}: {e}", mphf_path.display());
std::process::exit(1)
});
Some(GOFunction::read(&mut f).unwrap_or_else(|e| {
eprintln!("error reading MPHF {}: {e}", mphf_path.display());
std::process::exit(1)
}))
} else {
None
};
let counts_mmap_opt = if filter_active {
let cf = File::open(&counts_path).unwrap_or_else(|e| {
eprintln!("error opening {}: {e}", counts_path.display());
std::process::exit(1)
});
Some(unsafe {
memmap2::Mmap::map(&cf).unwrap_or_else(|e| {
eprintln!("error mmapping {}: {e}", counts_path.display());
std::process::exit(1)
})
})
} else {
None
};
let counts_slice: Option<&[u32]> = counts_mmap_opt.as_ref().map(|m| unsafe {
std::slice::from_raw_parts(m.as_ptr() as *const u32, m.len() / 4)
});
let mut reader = SKFileReader::open(&in_path, k).unwrap_or_else(|e| {
eprintln!("error opening {}: {e}", in_path.display());
std::process::exit(1)
});
for sk in reader.iter() {
for kmer in sk.iter_canonical_kmers(k) {
let accept = match (&mphf_opt, counts_slice) {
(Some(mphf), Some(counts)) => {
if let Some(slot) = mphf.get(&kmer) {
let ab = counts[slot as usize];
ab >= args.min_abundance
&& args.max_abundance.map_or(true, |max| ab <= max)
} else {
false
}
}
_ => true,
};
if accept {
g.push(kmer);
}
}
}
let n_kmers = g.len();
total_kmers.fetch_add(n_kmers, Ordering::Relaxed);
info!("partition {i}/{n}: {n_kmers} canonical k-mers → {}", out_path.display());
g.compute_degrees();
let file = File::create(&out_path).unwrap_or_else(|e| {
eprintln!("error creating {}: {e}", out_path.display());
std::process::exit(1)
});
let mut writer = niffler::send::get_writer(Box::new(file), Format::Gzip, Level::Six)
.unwrap_or_else(|e| {
eprintln!("error creating gzip writer: {e}");
std::process::exit(1)
});
g.write_fasta(&mut writer).unwrap_or_else(|e| {
eprintln!("write error on partition {i}: {e}");
std::process::exit(1)
});
});
info!(
"done — {} total canonical k-mers across all partitions",
total_kmers.load(Ordering::Relaxed)
);
}
+6
View File
@@ -19,6 +19,10 @@ enum Commands {
Partition(cmd::partition::PartitionArgs),
/// Count kmers from an existing dereplicated partition directory
Count(cmd::count::CountArgs),
/// Export partition data to FASTA (--super-kmers: dereplicated super-kmers)
Fasta(cmd::fasta::FastaArgs),
/// Build de Bruijn unitigs for all partitions and write to unitig.fasta.gz
Unitig(cmd::unitig::UnitigArgs),
}
fn main() {
@@ -41,6 +45,8 @@ fn main() {
Commands::Superkmer(args) => cmd::superkmer::run(args),
Commands::Partition(args) => cmd::partition::run(args),
Commands::Count(args) => cmd::count::run(args),
Commands::Fasta(args) => cmd::fasta::run(args),
Commands::Unitig(args) => cmd::unitig::run(args),
}
#[cfg(feature = "profiling")]