pub fn iter_domain_window(domain: &[f64], window_size: f64) -> DomainWindowIter<'_> {
DomainWindowIter::new(domain, window_size)
}
#[derive(Debug, Copy, Clone)]
pub struct DomainWindow {
pub index: usize,
pub first: usize,
pub last: usize,
}
impl DomainWindow {
fn new(index: usize, first: usize, last: usize) -> Self {
Self { index, first, last }
}
pub fn len(&self) -> usize {
self.last - self.first + 1
}
pub fn is_empty(&self) -> bool {
self.first > self.last
}
pub fn contains(&self, index: usize) -> bool {
index >= self.first && index <= self.last
}
pub fn iter(&self) -> impl Iterator<Item = usize> {
self.first..=self.last
}
}
pub struct DomainWindowIter<'a> {
domain: &'a [f64],
half_size: f64,
window: Option<DomainWindow>,
}
impl<'a> DomainWindowIter<'a> {
pub fn new(domain: &'a [f64], window_size: f64) -> Self {
Self {
domain,
half_size: (window_size / 2.0).abs(),
window: None,
}
}
}
impl<'a> Iterator for DomainWindowIter<'a> {
type Item = DomainWindow;
fn next(&mut self) -> Option<Self::Item> {
if let Some(window) = &self.window {
if window.index < self.domain.len() - 1 {
let next_index = window.index + 1;
let next_position = self.domain[next_index];
let mut first = window.first;
while self.domain[first] < next_position - self.half_size {
first += 1;
}
let mut last = window.last;
while last < self.domain.len() - 1
&& self.domain[last + 1] <= next_position + self.half_size
{
last += 1;
}
self.window = Some(DomainWindow::new(next_index, first, last));
self.window
} else {
None
}
} else {
let result = self
.domain
.binary_search_by(|probe| probe.partial_cmp(&self.half_size).unwrap());
let end = result.unwrap_or_else(|next_index| next_index - 1);
self.window = Some(DomainWindow::new(0, 0, end));
self.window
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_domain() -> Vec<f64> {
(0..=100).map(|i| i as f64).collect()
}
#[test]
fn test_window() {
let domain = make_domain();
let iter = DomainWindowIter::new(&domain, 6.5);
let half_size = iter.half_size;
for window in iter {
let current_position = domain[window.index];
let indices: Vec<usize> = domain
.iter()
.enumerate()
.filter(|(_i, s)| {
**s >= current_position - half_size && **s <= current_position + half_size
})
.map(|(i, _s)| i)
.collect();
assert_eq!(window.first, indices[0]);
assert_eq!(window.last, indices[indices.len() - 1]);
}
}
}