Skip to content

Sketching api for sequence data passed via an iterator - #76

Merged
johnlees merged 12 commits into
bacpop:mainfrom
tmaklin:sketching-api
Jul 27, 2026
Merged

johnlees merged 12 commits into
bacpop:mainfrom
tmaklin:sketching-api

Conversation

@tmaklin

@tmaklin tmaklin commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

as discussed in #75

This breaks backwards compatibility for code that relies on the NtHashIterator::new or AaHashIterator::new constructor, let me know if this is a problem as it's possible to implement the PR with the old, now unused, constructors intact.

I didn't end up doing the PathBuf rewrite as strings are used everywhere else in the code to point to files so thought it'd be better to keep everything consistent.

btw needletail >=0.6 compiles for wasm32 if you only enable the flate2 compression, I think this would allow merging some of the wasm32 and non-wasm32 code if you want to simplify things at some point.

Changes

Adds the following non-wasm32 code:

  • Change hash iterators to take an iterator over (Vec<u8>, Option<Vec<u8>>) instead of file paths.
  • Add a wrapper over needletail that provides this iterator.
  • Add a sketch_data function that does not rely on file paths.
  • Make sketch_files use sketch_data after reading the required data.
  • Add a SketchingOpts struct that stores the parameters needed to sketch a (single) sample.
    • Defaults to values used in the CLI when possible.
    • SketchingOpts doesn't fill the sample name or k-mer sizes by default.
  • Add a from_sketches constructor for MultiSketch that assigns indexes to each sketch and populates sketch_bins so that the constructed MultiSketch can be used with the other functions.

Example usage for sketch_data

use sketchlib::sketch::{Sketch, SketchingOpts};
use sketchlib::sketch::sketch_data;

use std::collections::HashSet;
use std::path::PathBuf;

/// Iterator for needletail records
pub struct NeedletailFilterIterator {
    reader: Box<dyn needletail::FastxReader>,
    want_ids: HashSet<u32>,
    current_idx: u32,
}

impl NeedletailFilterIterator {
    /// Construct from needletail readers
    pub fn new(
        reader: Box<dyn needletail::FastxReader>,
        want_ids: HashSet<u32>,
    ) -> Self {
        Self {
            reader,
            want_ids,
            current_idx: 0_u32,
        }
    }
}

impl Iterator for NeedletailFilterIterator {
    type Item = (Vec<u8>, Option<Vec<u8>>);

    fn next(
        &mut self,
    ) -> Option<(Vec<u8>, Option<Vec<u8>>)> {
        while let Some(try_record) = self.reader.next() {
            if self.want_ids.contains(&self.current_idx) {
                let record = try_record.expect("Invalid fastX record");
                let seq = record.seq();
                let qual = record.qual().map(|qual| qual.to_vec());
                self.current_idx += 1;
                return Some((seq.to_vec(), qual))
            }
            self.current_idx += 1;
        }
        None
    }
}

/// Sketch a fastX file filtered by the index of reads to include in the sketch
pub fn sketch_reads_with_filter(
    fastx_path: &PathBuf,
    want_ids: HashSet<u32>,
    opts: SketchingOpts,
) -> Vec<Sketch> {
    let reader = needletail::parse_fastx_file(fastx_path).unwrap();
    let mut filtered_iters = vec![NeedletailFilterIterator::new(reader, want_ids)];

    sketch_data(&mut filtered_iters, opts)
}

@johnlees

Copy link
Copy Markdown
Member

@vrbouza any initial thoughts on the WASM implications (if any) here?

@vrbouza

vrbouza commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Hi Tommy, all looks nice from the wasm dimension, except from one subtlety: with these changes, super::hashing::HashType; needs to be imported for wasm also in src/sketch/mod.rs. So just adding

#[cfg(target_family = "wasm")]
use super::hashing::HashType;

should fix the compilation! (I know this cfg gate is different from the others, but in my dev. branch I am already working with this to support wasm64 compilation, so better if you could use directly target_family hehe). You can test with cargo build --release --target wasm32-unknown-unknown.

@tmaklin

tmaklin commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

fixed, compiles to wasm32-unknown-unknown now

@johnlees johnlees linked an issue Jul 24, 2026 that may be closed by this pull request
@johnlees

Copy link
Copy Markdown
Member

Thanks Tommi, this looks good!

Would you mind adding your example API use case above to the docstring above sketch_data? I think if you put them in a block (e.g. https://github.com/bacpop/ska.rust/blob/master/src/merge_ska_array.rs#L71-L107) it should be run as part of the tests too.

I can fix the codecov CI after merging

@tmaklin

tmaklin commented Jul 24, 2026

Copy link
Copy Markdown
Contributor Author

done!

@johnlees
johnlees merged commit e849794 into bacpop:main Jul 27, 2026
1 of 2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Sketch sequences in memory without writing to disk

3 participants