refactor: improve de Bruijn graph traversal and longtig generation

- Refactored Node representation using compact bitfields for neighbor counts
  and nucleotides; added count_neighbors helper to compute_degrees()
- Introduced StartIter iterator for unitig/longtigu generation with revised
  traversal semantics (e.g., interior node marking)
- Added nucleotide() accessor to Kmer type for 2-bit extraction at position i
- Renamed unitig.rs → longtigs, updated CLI command and output filenames to reflect "long t ig"
- Extended extract_kmers() in scripts/compare.py with duplication statistics
```
This commit is contained in:
Eric Coissac committed 2026-05-02 16:31:08 +02:00
1 parent 35840b9d73
commit 86e9cb7026
7 files changed
+669 -107

No files matched your search

+141
View File
@@ -0,0 +1,141 @@
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 LongtigArgs {
/// 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: LongtigArgs) {
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 longtigs 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("longtig.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, false).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)
);
}
+1
View File
@@ -1,5 +1,6 @@
pub mod count;
pub mod fasta;
pub mod longtig;
pub mod partition;
pub mod superkmer;
pub mod unitig;
+8 -5
View File
@@ -82,9 +82,9 @@ pub fn run(args: UnitigArgs) {
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 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());
@@ -112,7 +112,10 @@ pub fn run(args: UnitigArgs) {
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());
info!(
"partition {i}/{n}: {n_kmers} canonical k-mers → {}",
out_path.display()
);
g.compute_degrees();
@@ -125,7 +128,7 @@ pub fn run(args: UnitigArgs) {
eprintln!("error creating gzip writer: {e}");
std::process::exit(1)
});
g.write_fasta(&mut writer).unwrap_or_else(|e| {
g.write_fasta(&mut writer, true).unwrap_or_else(|e| {
eprintln!("write error on partition {i}: {e}");
std::process::exit(1)
});
+6 -1
View File
@@ -23,11 +23,15 @@ enum Commands {
Fasta(cmd::fasta::FastaArgs),
/// Build de Bruijn unitigs for all partitions and write to unitig.fasta.gz
Unitig(cmd::unitig::UnitigArgs),
/// Build de Bruijn longtigs for all partitions and write to longtig.fasta.gz
Longtig(cmd::longtig::LongtigArgs),
}
fn main() {
fmt()
.with_env_filter(EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")))
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info")),
)
.with_writer(std::io::stderr)
.init();
@@ -47,6 +51,7 @@ fn main() {
Commands::Count(args) => cmd::count::run(args),
Commands::Fasta(args) => cmd::fasta::run(args),
Commands::Unitig(args) => cmd::unitig::run(args),
Commands::Longtig(args) => cmd::longtig::run(args),
}
#[cfg(feature = "profiling")]