refactor: extract obikindex crate and remove deprecated CLI commands
Extracted core indexing logic, state tracking, and metadata management into a new `obikindex` crate. Refactored the `index` and `unitig` commands to leverage the `KmerIndex` abstraction and state-driven pipeline transitions. Removed obsolete CLI subcommands (`count`, `fasta`, `longtig`, `partition`) and their associated pipeline steps. Updated FASTA writing utilities for single-line output and deterministic identifiers, and refreshed workspace dependencies.
This commit is contained in:
1 parent
f8cfb493b8
commit
17c9e076bd
24 files changed
+792
-1593
No files matched your search
+14
-22
@@ -8,28 +8,20 @@ name = "obikmer"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
obikseq = { path = "../obikseq" }
|
||||
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" }
|
||||
obisys = { path = "../obisys" }
|
||||
obiskio = { path = "../obiskio" }
|
||||
obicompactvec = { path = "../obicompactvec" }
|
||||
obilayeredmap = { path = "../obilayeredmap" }
|
||||
niffler = "3"
|
||||
rayon = "1"
|
||||
ph = "0.11"
|
||||
memmap2 = "0.9"
|
||||
epserde = "0.8"
|
||||
ptr_hash = "1.1"
|
||||
cacheline-ef = "1.1"
|
||||
indicatif = "0.17"
|
||||
tracing = "0.1.44"
|
||||
obikseq = { path = "../obikseq" }
|
||||
obiread = { path = "../obiread" }
|
||||
obiskbuilder = { path = "../obiskbuilder" }
|
||||
obifastwrite = { path = "../obifastwrite" }
|
||||
obipipeline = { path = "../obipipeline" }
|
||||
obikrope = { path = "../obikrope" }
|
||||
obikpartitionner = { path = "../obikpartitionner" }
|
||||
obisys = { path = "../obisys" }
|
||||
obiskio = { path = "../obiskio" }
|
||||
obikindex = { path = "../obikindex" }
|
||||
clap = { version = "4", features = ["derive"] }
|
||||
rayon = "1"
|
||||
indicatif = "0.17"
|
||||
tracing = "0.1.44"
|
||||
tracing-subscriber = { version = "0.3", features = ["fmt", "env-filter"] }
|
||||
pprof = { version = "0.13", features = ["prost-codec"], optional = true }
|
||||
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
use clap::Args;
|
||||
use obikpartitionner::KmerPartition;
|
||||
use std::path::PathBuf;
|
||||
use tracing::info;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct CountArgs {
|
||||
/// Partition directory produced by the `partition` command
|
||||
#[arg(short, long)]
|
||||
pub partition: PathBuf,
|
||||
}
|
||||
|
||||
pub fn run(args: CountArgs) {
|
||||
let kp = KmerPartition::open(&args.partition).unwrap_or_else(|e| {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1)
|
||||
});
|
||||
|
||||
info!("counting kmers in {}", args.partition.display());
|
||||
kp.count_kmer().unwrap_or_else(|e| {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1)
|
||||
});
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
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 = kp.part_dir(i);
|
||||
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).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));
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obikpartitionner::KmerPartition;
|
||||
use obikindex::{IndexConfig, IndexState, KmerIndex};
|
||||
use obikseq::{set_k, set_m};
|
||||
use obisys::Reporter;
|
||||
use tracing::info;
|
||||
|
||||
use crate::cli::CommonArgs;
|
||||
use crate::steps::{build_index, dereplicate_and_count, scatter};
|
||||
use crate::steps::scatter;
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct IndexArgs {
|
||||
/// Output partition directory
|
||||
/// Output index directory
|
||||
#[arg(short, long)]
|
||||
pub output: PathBuf,
|
||||
|
||||
@@ -19,6 +19,10 @@ pub struct IndexArgs {
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub force: bool,
|
||||
|
||||
/// Genome label (default: input filename without path/extension)
|
||||
#[arg(long)]
|
||||
pub label: Option<String>,
|
||||
|
||||
/// Minimum kmer abundance (inclusive)
|
||||
#[arg(long, default_value_t = 1)]
|
||||
pub min_abundance: u32,
|
||||
@@ -43,53 +47,71 @@ pub fn run(args: IndexArgs) {
|
||||
let output = args.output.clone();
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
// ── Stage 1: scatter (skipped if partition already exists) ───────────────
|
||||
let kp = if output.join("partition.meta").exists() {
|
||||
info!("resuming from existing partition at {}", output.display());
|
||||
let kp = KmerPartition::open(&output).unwrap_or_else(|e| {
|
||||
eprintln!("error opening partition: {e}");
|
||||
// ── Open or create the index ─────────────────────────────────────────────
|
||||
let mut idx = if KmerIndex::exists(&output) {
|
||||
info!("resuming from existing index at {}", output.display());
|
||||
KmerIndex::open(&output).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
set_k(kp.kmer_size());
|
||||
set_m(kp.minimizer_size());
|
||||
kp
|
||||
})
|
||||
} else {
|
||||
let k = args.common.kmer_size;
|
||||
set_k(k);
|
||||
let m = args.common.minimizer_size;
|
||||
set_m(m);
|
||||
let theta = args.common.theta;
|
||||
let level_max = args.common.level_max;
|
||||
let n_workers = args.common.threads.max(1);
|
||||
|
||||
let mut kp =
|
||||
KmerPartition::create(&output, args.common.partition_bits, k, m, args.force)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
scatter(&mut kp, args.common.seqfile_paths(), k, level_max, theta, n_workers, &mut rep);
|
||||
kp
|
||||
let config = IndexConfig {
|
||||
kmer_size: args.common.kmer_size,
|
||||
minimizer_size: args.common.minimizer_size,
|
||||
n_bits: args.common.partition_bits,
|
||||
with_counts: args.with_counts,
|
||||
};
|
||||
KmerIndex::create(&output, config, args.label.clone(), args.force).unwrap_or_else(|e| {
|
||||
eprintln!("error creating index: {e}");
|
||||
std::process::exit(1);
|
||||
})
|
||||
};
|
||||
|
||||
set_k(idx.kmer_size());
|
||||
set_m(idx.minimizer_size());
|
||||
|
||||
// ── Stage 2: dereplicate + count (skipped if already done) ───────────────
|
||||
if !output.join("kmer_spectrum_raw.json").exists() {
|
||||
dereplicate_and_count(&kp, &mut rep);
|
||||
// ── Stage 1: scatter ─────────────────────────────────────────────────────
|
||||
if idx.state() < IndexState::Scattered {
|
||||
let first_path = args.common.inputs.first().map(PathBuf::from);
|
||||
let k = idx.kmer_size();
|
||||
let level_max = args.common.level_max;
|
||||
let theta = args.common.theta;
|
||||
let n_workers = args.common.threads.max(1);
|
||||
|
||||
scatter(idx.partition_mut(), args.common.seqfile_paths(), k, level_max, theta, n_workers, &mut rep);
|
||||
|
||||
idx.mark_scattered(first_path.as_deref()).unwrap_or_else(|e| {
|
||||
eprintln!("error marking scatter done: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
} else {
|
||||
info!("kmer counts already present, skipping dereplicate + count");
|
||||
info!("scatter already done, skipping");
|
||||
}
|
||||
|
||||
// ── Stage 2: dereplicate + count ─────────────────────────────────────────
|
||||
if idx.state() < IndexState::Counted {
|
||||
idx.dereplicate_and_count(&mut rep).unwrap_or_else(|e| {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
} else {
|
||||
info!("dereplicate+count already done, skipping");
|
||||
}
|
||||
|
||||
// ── Stage 3: build layered index ─────────────────────────────────────────
|
||||
build_index(
|
||||
&kp,
|
||||
args.min_abundance,
|
||||
args.max_abundance,
|
||||
args.with_counts,
|
||||
args.keep_intermediate,
|
||||
&mut rep,
|
||||
);
|
||||
if idx.state() < IndexState::Indexed {
|
||||
idx.build_layers(
|
||||
args.min_abundance,
|
||||
args.max_abundance,
|
||||
args.keep_intermediate,
|
||||
&mut rep,
|
||||
).unwrap_or_else(|e| {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
} else {
|
||||
info!("index already built, skipping");
|
||||
}
|
||||
|
||||
rep.print();
|
||||
}
|
||||
@@ -1,143 +0,0 @@
|
||||
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 obikseq::set_k;
|
||||
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();
|
||||
set_k(k);
|
||||
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 = kp.part_dir(i);
|
||||
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();
|
||||
|
||||
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).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() {
|
||||
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,7 +1,3 @@
|
||||
pub mod count;
|
||||
pub mod fasta;
|
||||
pub mod index;
|
||||
pub mod longtig;
|
||||
pub mod partition;
|
||||
pub mod superkmer;
|
||||
pub mod unitig;
|
||||
@@ -1,49 +0,0 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Args;
|
||||
use obikpartitionner::KmerPartition;
|
||||
use obisys::Reporter;
|
||||
use obikseq::{set_k, set_m};
|
||||
|
||||
use crate::cli::CommonArgs;
|
||||
use crate::steps::{dereplicate_and_count, scatter};
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct PartitionArgs {
|
||||
/// Output partition directory
|
||||
#[arg(short, long)]
|
||||
pub output: PathBuf,
|
||||
|
||||
/// Overwrite output directory if it already exists
|
||||
#[arg(long, default_value_t = false)]
|
||||
pub force: bool,
|
||||
|
||||
#[command(flatten)]
|
||||
pub common: CommonArgs,
|
||||
}
|
||||
|
||||
// ── Entry point ───────────────────────────────────────────────────────────────
|
||||
|
||||
pub fn run(args: PartitionArgs) {
|
||||
let k = args.common.kmer_size;
|
||||
set_k(k);
|
||||
let m = args.common.minimizer_size;
|
||||
set_m(m);
|
||||
let theta = args.common.theta;
|
||||
let level_max = args.common.level_max;
|
||||
let n_workers = args.common.threads.max(1);
|
||||
|
||||
let mut kp = KmerPartition::create(&args.output, args.common.partition_bits, k, m, args.force)
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error: {e}");
|
||||
std::process::exit(1)
|
||||
});
|
||||
|
||||
let path_source = args.common.seqfile_paths();
|
||||
let mut rep = Reporter::new();
|
||||
|
||||
scatter(&mut kp, path_source, k, level_max, theta, n_workers, &mut rep);
|
||||
dereplicate_and_count(&kp, &mut rep);
|
||||
|
||||
rep.print();
|
||||
}
|
||||
+26
-115
@@ -1,143 +1,54 @@
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Mutex;
|
||||
|
||||
use clap::Args;
|
||||
use niffler::Level;
|
||||
use niffler::send::compression::Format;
|
||||
use obidebruinj::GraphDeBruijn;
|
||||
use obikpartitionner::KmerPartition;
|
||||
use obifastwrite::write_unitig;
|
||||
use obikindex::KmerIndex;
|
||||
use obikseq::set_k;
|
||||
use obiskio::SKFileReader;
|
||||
use ph::fmph::GOFunction;
|
||||
use obiskio::UnitigFileReader;
|
||||
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>,
|
||||
/// Index directory produced by the `index` command
|
||||
pub index: PathBuf,
|
||||
}
|
||||
|
||||
pub fn run(args: UnitigArgs) {
|
||||
let kp = KmerPartition::open(&args.partition).unwrap_or_else(|e| {
|
||||
eprintln!("error opening partition: {e}");
|
||||
let idx = KmerIndex::open(&args.index).unwrap_or_else(|e| {
|
||||
eprintln!("error opening index: {e}");
|
||||
std::process::exit(1)
|
||||
});
|
||||
|
||||
let k = kp.kmer_size();
|
||||
let k = idx.kmer_size();
|
||||
set_k(k);
|
||||
let n = kp.n_partitions();
|
||||
info!("building unitigs from {n} partitions (k={k}, parallel)");
|
||||
let n = idx.n_partitions();
|
||||
info!("dumping unitigs from {n} partitions (k={k})");
|
||||
|
||||
let total_kmers = AtomicUsize::new(0);
|
||||
let stdout = Mutex::new(BufWriter::new(io::stdout()));
|
||||
|
||||
(0..n).into_par_iter().for_each(|i| {
|
||||
let part_dir = kp.part_dir(i);
|
||||
let in_path = part_dir.join("dereplicated.skmer.zst");
|
||||
if !in_path.exists() {
|
||||
let path = idx.layer_unitigs_path(i, 0);
|
||||
if !path.exists() {
|
||||
return;
|
||||
}
|
||||
let out_path = part_dir.join("unitig.fasta.gz");
|
||||
|
||||
let mut g = GraphDeBruijn::new();
|
||||
|
||||
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).unwrap_or_else(|e| {
|
||||
eprintln!("error opening {}: {e}", in_path.display());
|
||||
let reader = UnitigFileReader::open(&path).unwrap_or_else(|e| {
|
||||
eprintln!("error opening unitigs (partition {i}): {e}");
|
||||
std::process::exit(1)
|
||||
});
|
||||
for sk in reader.iter() {
|
||||
for kmer in sk.iter_canonical_kmers() {
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
for j in 0..reader.len() {
|
||||
let unitig = reader.unitig(j);
|
||||
let mut out = stdout.lock().unwrap();
|
||||
write_unitig(&unitig, k, i, j, &mut *out).unwrap_or_else(|e| {
|
||||
eprintln!("write error: {e}");
|
||||
std::process::exit(1)
|
||||
});
|
||||
}
|
||||
|
||||
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, true).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)
|
||||
);
|
||||
stdout.into_inner().unwrap().flush().expect("flush error");
|
||||
}
|
||||
+5
-17
@@ -14,20 +14,12 @@ struct Cli {
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Extract super-kmers from a sequence file (scatter phase)
|
||||
/// Extract super-kmers from a sequence file and write to stdout
|
||||
Superkmer(cmd::superkmer::SuperkmerArgs),
|
||||
/// Partition super-kmers on disk by minimizer
|
||||
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),
|
||||
/// Build de Bruijn longtigs for all partitions and write to longtig.fasta.gz
|
||||
Longtig(cmd::longtig::LongtigArgs),
|
||||
/// Build the complete genome index (scatter → dereplicate → count → layered MPHF)
|
||||
Index(cmd::index::IndexArgs),
|
||||
/// Dump unitigs from a built index to stdout (debug)
|
||||
Unitig(cmd::unitig::UnitigArgs),
|
||||
}
|
||||
|
||||
fn main() {
|
||||
@@ -50,12 +42,8 @@ fn main() {
|
||||
let cli = Cli::parse();
|
||||
match cli.command {
|
||||
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),
|
||||
Commands::Longtig(args) => cmd::longtig::run(args),
|
||||
Commands::Index(args) => cmd::index::run(args),
|
||||
Commands::Index(args) => cmd::index::run(args),
|
||||
Commands::Unitig(args) => cmd::unitig::run(args),
|
||||
}
|
||||
|
||||
#[cfg(feature = "profiling")]
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use cacheline_ef::{CachelineEf, CachelineEfVec};
|
||||
use epserde::prelude::*;
|
||||
use indicatif::{ProgressBar, ProgressStyle};
|
||||
use obicompactvec::PersistentCompactIntMatrix;
|
||||
use obicompactvec::PersistentCompactIntVec;
|
||||
use obidebruinj::GraphDeBruijn;
|
||||
use obikpartitionner::KmerPartition;
|
||||
use obilayeredmap::layer::Layer;
|
||||
use obiskio::{SKFileMeta, SKFileReader};
|
||||
use obisys::{Reporter, Stage};
|
||||
use ptr_hash::{PtrHash, bucket_fn::CubicEps, hash::Xx64};
|
||||
use rayon::prelude::*;
|
||||
use tracing::info;
|
||||
|
||||
type Mphf = PtrHash<u64, CubicEps, CachelineEfVec<Vec<CachelineEf>>, Xx64, Vec<u8>>;
|
||||
|
||||
/// Build the layered MPHF index for all partitions in parallel.
|
||||
///
|
||||
/// Default mode (with_counts = false): set membership only (`Layer<()>`).
|
||||
/// With counts (with_counts = true): count matrix per kmer (`Layer<PersistentCompactIntMatrix>`).
|
||||
///
|
||||
/// Skips any partition whose `index/layer_0/mphf.bin` already exists (resume).
|
||||
/// Reports the "index" stage to `rep`.
|
||||
pub fn build_index(
|
||||
kp: &KmerPartition,
|
||||
min_ab: u32,
|
||||
max_ab: Option<u32>,
|
||||
with_counts: bool,
|
||||
keep_intermediate: bool,
|
||||
rep: &mut Reporter,
|
||||
) {
|
||||
let n = kp.n_partitions();
|
||||
let t = Stage::start("index");
|
||||
let total_kmers = AtomicUsize::new(0);
|
||||
let filter_active = min_ab > 1 || max_ab.is_some();
|
||||
let need_counts = filter_active || with_counts;
|
||||
|
||||
let pb = Arc::new(Mutex::new(
|
||||
ProgressBar::new(n as u64).with_style(
|
||||
ProgressStyle::with_template("index — [{bar:20}] {pos}/{len} | {msg}").unwrap(),
|
||||
),
|
||||
));
|
||||
|
||||
(0..n).into_par_iter().for_each(|i| {
|
||||
let part_dir = kp.part_dir(i);
|
||||
let dedup_path = part_dir.join("dereplicated.skmer.zst");
|
||||
if !dedup_path.exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
let layer_dir = part_dir.join("index").join("layer_0");
|
||||
if layer_dir.join("mphf.bin").exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
// Load partition MPHF + counts when needed for filtering or count payload
|
||||
let mphf1_opt: Option<Mphf> = if need_counts {
|
||||
let p = part_dir.join("mphf1.bin");
|
||||
p.exists().then(|| Mphf::load_full(&p).ok()).flatten()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let counts1_opt: Option<PersistentCompactIntVec> = if need_counts {
|
||||
let p = part_dir.join("counts1.bin");
|
||||
p.exists()
|
||||
.then(|| PersistentCompactIntVec::open(&p).ok())
|
||||
.flatten()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// Build de Bruijn graph with optional abundance filter
|
||||
let mut g = GraphDeBruijn::new();
|
||||
let mut reader = SKFileReader::open(&dedup_path).unwrap_or_else(|e| {
|
||||
eprintln!("error opening {}: {e}", dedup_path.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
for sk in reader.iter() {
|
||||
for kmer in sk.iter_canonical_kmers() {
|
||||
let accept = if filter_active {
|
||||
match (&mphf1_opt, &counts1_opt) {
|
||||
(Some(mphf), Some(counts)) => {
|
||||
let ab = counts.get(mphf.index(&kmer.raw()));
|
||||
ab >= min_ab && max_ab.map_or(true, |max| ab <= max)
|
||||
}
|
||||
_ => true,
|
||||
}
|
||||
} else {
|
||||
true
|
||||
};
|
||||
if accept {
|
||||
g.push(kmer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let n_kmers = g.len();
|
||||
total_kmers.fetch_add(n_kmers, Ordering::Relaxed);
|
||||
g.compute_degrees();
|
||||
|
||||
// Write unitigs to layer_0/unitigs.bin
|
||||
fs::create_dir_all(&layer_dir).unwrap_or_else(|e| {
|
||||
eprintln!("error creating {}: {e}", layer_dir.display());
|
||||
std::process::exit(1);
|
||||
});
|
||||
let mut uw = Layer::<()>::unitig_writer(&layer_dir).unwrap_or_else(|e| {
|
||||
eprintln!("error creating unitig writer (partition {i}): {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
for unitig in g.iter_unitig() {
|
||||
uw.write(&unitig).unwrap_or_else(|e| {
|
||||
eprintln!("error writing unitig (partition {i}): {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}
|
||||
uw.close().unwrap_or_else(|e| {
|
||||
eprintln!("error closing unitig writer (partition {i}): {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
|
||||
// Build MPHF layer — mode depends on --with-counts
|
||||
if with_counts {
|
||||
Layer::<PersistentCompactIntMatrix>::build(&layer_dir, |kmer| {
|
||||
match (&mphf1_opt, &counts1_opt) {
|
||||
(Some(mphf), Some(counts)) => counts.get(mphf.index(&kmer.raw())),
|
||||
_ => 1,
|
||||
}
|
||||
})
|
||||
.unwrap_or_else(|e| {
|
||||
eprintln!("error building count layer (partition {i}): {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
} else {
|
||||
Layer::<()>::build(&layer_dir).unwrap_or_else(|e| {
|
||||
eprintln!("error building set layer (partition {i}): {e}");
|
||||
std::process::exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
let pb = pb.lock().unwrap();
|
||||
pb.inc(1);
|
||||
pb.set_message(format!("{i}: {n_kmers} kmers"));
|
||||
});
|
||||
|
||||
pb.lock().unwrap().finish_and_clear();
|
||||
info!(
|
||||
"done — {} total kmers indexed",
|
||||
total_kmers.load(Ordering::Relaxed)
|
||||
);
|
||||
|
||||
// ── Cleanup intermediate build files ──────────────────────────────────────
|
||||
if !keep_intermediate {
|
||||
for i in 0..n {
|
||||
let part_dir = kp.part_dir(i);
|
||||
remove_if_exists(&part_dir.join("dereplicated.skmer.zst"));
|
||||
remove_if_exists(&SKFileMeta::sidecar_path(&part_dir.join("dereplicated.skmer.zst")));
|
||||
remove_if_exists(&part_dir.join("mphf1.bin"));
|
||||
remove_if_exists(&part_dir.join("counts1.bin"));
|
||||
}
|
||||
}
|
||||
|
||||
rep.push(t.stop());
|
||||
}
|
||||
|
||||
fn remove_if_exists(path: &Path) {
|
||||
if let Err(e) = fs::remove_file(path) {
|
||||
if e.kind() != std::io::ErrorKind::NotFound {
|
||||
eprintln!("warning: could not remove {}: {e}", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
use obikpartitionner::KmerPartition;
|
||||
use obisys::{Reporter, Stage};
|
||||
|
||||
/// Dereplicate then count kmers. Reports each stage to `rep`.
|
||||
pub fn dereplicate_and_count(kp: &KmerPartition, rep: &mut Reporter) {
|
||||
let t = Stage::start("dereplicate");
|
||||
kp.dereplicate().expect("dereplicate error");
|
||||
rep.push(t.stop());
|
||||
|
||||
let t = Stage::start("count_kmer");
|
||||
kp.count_kmer().expect("count kmer error");
|
||||
rep.push(t.stop());
|
||||
}
|
||||
@@ -1,7 +1,3 @@
|
||||
mod build_index;
|
||||
mod dereplicate_and_count;
|
||||
mod scatter;
|
||||
|
||||
pub use build_index::build_index;
|
||||
pub use dereplicate_and_count::dereplicate_and_count;
|
||||
pub use scatter::scatter;
|
||||
Reference in new issue
Block a user