(feat): refactor superkmer to use obipipeline with flat transforms

- Replace crossbeam-channel-based threading model
- Introduce obipipeline crate with Stage::Transform/Flat support  
- Replace single input + format detection by multiple inputs via PathIter
- Implement pipeline stages: open_chunks → normalize → build_superkmers (flat) + write_batch
- Add SharedFlatFn for 1→N transformations with delta tracking in scheduler loop
This commit is contained in:
Eric Coissac committed 2026-04-24 21:08:09 +02:00
1 parent f1c8fc85c9
commit d4e4289aff
5 files changed
+540 -489

No files matched your search

+3 -3
View File
@@ -12,6 +12,6 @@ obikseq = { path = "../obikseq" }
obiread = { path = "../obiread" }
obiskbuilder = { path = "../obiskbuilder" }
obifastwrite = { path = "../obifastwrite" }
clap = { version = "4", features = ["derive"] }
crossbeam-channel = "0.5"
obikrope = { path = "../obikrope" }
obipipeline = { path = "../obipipeline" }
clap = { version = "4", features = ["derive"] }
obikrope = { path = "../obikrope" }
+80 -104
View File
@@ -1,17 +1,19 @@
use std::io::{self, BufWriter, Write};
use std::thread;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use clap::Args;
use crossbeam_channel::bounded;
use obifastwrite::write_scatter;
use obikrope::Rope;
use obikseq::superkmer::SuperKmer;
use obipipeline::{WorkerPool, make_pipeline};
use obiskbuilder::SuperKmerIter;
#[derive(Args)]
pub struct SuperkmerArgs {
/// Input: file path, URL (http/https), or `-` for stdin
pub input: String,
/// Input files or directories (FASTA/FASTQ, optionally gzip-compressed)
#[arg(num_args = 1..)]
pub inputs: Vec<String>,
/// k-mer size
#[arg(short, long, default_value_t = 31)]
@@ -34,36 +36,70 @@ pub struct SuperkmerArgs {
pub partitions: u64,
/// Number of worker threads
#[arg(short = 'T', long, default_value_t = 4)]
#[arg(short = 'T', long, default_value_t = 16)]
pub threads: usize,
/// Force input format: fasta or fastq (default: auto-detect from extension)
#[arg(long)]
pub format: Option<String>,
}
#[derive(Clone, Copy)]
enum Format {
Fasta,
Fastq,
enum PipelineData {
Path(PathBuf),
RawChunk(Rope),
NormChunk(Rope),
Batch(Vec<(u64, SuperKmer)>),
}
fn detect_format(source: &str, hint: Option<&str>) -> Format {
if let Some(h) = hint {
return match h.to_lowercase().as_str() {
"fastq" | "fq" => Format::Fastq,
_ => Format::Fasta,
};
}
if source.ends_with(".fq")
|| source.ends_with(".fastq")
|| source.ends_with(".fq.gz")
|| source.ends_with(".fastq.gz")
{
Format::Fastq
} else {
Format::Fasta
// SAFETY: Rope contains Cell<u8> which is !Sync, but pipeline ownership transfers
// exclusively through channels — no item is ever shared across threads.
unsafe impl Send for PipelineData {}
unsafe impl Sync for PipelineData {}
// ── Stage functions ───────────────────────────────────────────────────────────
/// Opens a sequence file and returns an iterator over its raw Rope chunks.
/// Chunk-level I/O errors are logged and skipped.
fn open_chunks(path: PathBuf) -> io::Result<impl Iterator<Item = Rope>> {
let path_str = path
.to_str()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "non-UTF-8 path"))?;
let iter = obiread::read_sequence_chunks(path_str)?;
Ok(iter.filter_map(|r| match r {
Ok(rope) => Some(rope),
Err(e) => {
eprintln!("chunk read error: {e}");
None
}
}))
}
/// Normalises a raw sequence chunk (FASTA or FASTQ) into a compact ACGT/NUL rope.
fn normalize(rope: Rope, k: usize) -> io::Result<Rope> {
obiread::normalize_sequence_chunk(rope, k)
}
/// Extracts all super-kmers from a normalised rope.
fn build_superkmers(
rope: Rope,
k: usize,
m: usize,
level_max: usize,
theta: f64,
) -> Vec<(u64, SuperKmer)> {
SuperKmerIter::new(&rope, k, m, level_max, theta).collect()
}
/// Writes a batch of super-kmers to the output sink.
fn write_batch(
batch: Vec<(u64, SuperKmer)>,
out: &Mutex<BufWriter<io::Stdout>>,
partitions: u64,
k: usize,
m: usize,
) -> io::Result<()> {
let mut w = out.lock().unwrap();
for (min_hash, sk) in batch {
let partition = (mix64(min_hash) % partitions) as u32;
write_scatter(&sk, &mut *w, k, m, partition, min_hash)?;
}
Ok(())
}
#[inline]
@@ -75,9 +111,9 @@ fn mix64(x: u64) -> u64 {
x ^ (x >> 31)
}
// ── Entry point ───────────────────────────────────────────────────────────────
pub fn run(args: SuperkmerArgs) {
let format = detect_format(&args.input, args.format.as_deref());
let input = args.input.clone();
let k = args.kmer_size;
let m = args.minimizer_size;
let theta = args.theta;
@@ -85,81 +121,21 @@ pub fn run(args: SuperkmerArgs) {
let partitions = args.partitions;
let n_workers = args.threads.max(1);
// raw chunks (reader → workers)
let (raw_tx, raw_rx) = bounded::<Rope>(n_workers * 2);
// superkmer batches (workers → output)
let (sk_tx, sk_rx) = bounded::<Vec<(u64, SuperKmer)>>(n_workers * 2);
let paths = args.inputs.iter().map(PathBuf::from).collect();
let path_source = obiread::PathIter::new(paths);
// ── reader thread ─────────────────────────────────────────────────────────
let reader = thread::spawn(move || {
let file = obiread::xopen(&input).expect("cannot open input");
match format {
Format::Fasta => {
for chunk in obiread::fasta_chunks(file) {
raw_tx.send(chunk.expect("read error")).unwrap();
}
}
Format::Fastq => {
for chunk in obiread::fastq_chunks(file) {
raw_tx.send(chunk.expect("read error")).unwrap();
}
}
}
// raw_tx drops here → workers observe disconnect
});
let out = Arc::new(Mutex::new(BufWriter::new(io::stdout())));
let out_sink = Arc::clone(&out);
// ── worker threads ────────────────────────────────────────────────────────
let workers: Vec<_> = (0..n_workers)
.map(|_| {
let raw_rx = raw_rx.clone();
let sk_tx = sk_tx.clone();
thread::spawn(move || {
for raw_chunk in raw_rx {
let norm = match format {
Format::Fasta => obiread::normalize::normalize_fasta_chunk(raw_chunk, k),
Format::Fastq => obiread::normalize::normalize_fastq_chunk(raw_chunk, k),
};
const BATCH_SIZE: usize = 10_000;
let mut batch = Vec::with_capacity(BATCH_SIZE);
for sk in SuperKmerIter::new(&norm, k, m, level_max, theta) {
batch.push(sk);
if batch.len() == BATCH_SIZE {
sk_tx
.send(std::mem::replace(
&mut batch,
Vec::with_capacity(BATCH_SIZE),
))
.unwrap();
}
}
if !batch.is_empty() {
sk_tx.send(batch).unwrap();
}
}
// sk_tx clone drops here
})
})
.collect();
let pipeline = make_pipeline! {
PipelineData,
source path_source => Path,
||? open_chunks : Path => RawChunk,
|? { move |rope| normalize(rope, k) } : RawChunk => NormChunk,
| { move |rope| build_superkmers(rope, k, m, level_max, theta) }: NormChunk => Batch,
sink? { move |batch| write_batch(batch, &out_sink, partitions, k, m) } @ Batch,
};
// drop the extra sk_tx clone held by this thread so the output thread exits
drop(sk_tx);
// ── output thread ─────────────────────────────────────────────────────────
let output = thread::spawn(move || {
let stdout = io::stdout();
let mut out = BufWriter::new(stdout.lock());
for batch in sk_rx {
for (min_hash, sk) in batch {
let partition = (mix64(min_hash) % partitions) as u32;
write_scatter(&sk, &mut out, k, m, partition, min_hash).expect("write error");
}
}
out.flush().expect("flush error");
});
reader.join().expect("reader thread panicked");
for w in workers {
w.join().expect("worker thread panicked");
}
output.join().expect("output thread panicked");
WorkerPool::new(pipeline, n_workers, 1).run();
out.lock().unwrap().flush().expect("flush error");
}