I have this function to query a timestep series. Currently, it returns the first next value after the queried time (non-inclusively). I need to be able to get the last value inclusively and be able to get the next value non-inclusively.
Create a better interface to this function, maybe using std::ops::Bound, and maybe create query_before and query_after functions or something. But feel free to do something else if you think it's preferred.
use std::ops::Bound;
/// Represents the query direction for time series lookups
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryDirection {
/// Find the last value at or before the given time
Before,
/// Find the first value after the given time
After,
}
impl<'a> From<&'a QueryDirection> for Bound<&'a NaiveDateTime> {
fn from(direction: &'a QueryDirection) -> Self {
match direction {
QueryDirection::Before => Bound::Included,
QueryDirection::After => Bound::Excluded,
}
}
}
impl From<QueryDirection> for Bound<NaiveDateTime> {
fn from(direction: QueryDirection) -> Self {
match direction {
QueryDirection::Before => Bound::Included,
QueryDirection::After => Bound::Excluded,
}
}
}
impl YourType {
/// Queries the time series data based on the provided time and direction.
///
/// # Arguments
/// * `time` - The reference time for the query
/// * `direction` - Specifies whether to find the value before/at the time or after the time
///
/// # Returns
/// * A row from the dataset matching the query criteria
///
/// # Errors
/// * Returns an HDF5 error if data access fails
/// * Returns `QueryError::NoMatchingData` if no data matches the criteria
pub fn query(
&self,
time: &NaiveDateTime,
direction: QueryDirection,
) -> Result<ndarray::Array1<i32>, hdf5::Error> {
// Find the date index for the query time
let date_index = match self.days_map.get(&time.date()) {
Some(idx) => *idx,
None => {
// If the exact date isn't found, find the appropriate date based on direction
match direction {
QueryDirection::Before => {
if let Some((_, idx)) = self.days_map.upper_bound(Bound::Excluded(&time.date())).peek_prev() {
*idx
} else {
return Err(hdf5::Error::Internal("No data before the requested time".into()));
}
},
QueryDirection::After => {
if let Some((_, idx)) = self.days_map.lower_bound(Bound::Excluded(&time.date())).peek_next() {
*idx
} else {
return Err(hdf5::Error::Internal("No data after the requested time".into()));
}
}
}
}
};
// Determine the search range
let search_end_idx = match self.days_map.lower_bound(Bound::Excluded(&time.date())).peek_next() {
Some((_, next_day_idx)) => *next_day_idx,
None => self.data.shape()[0], // If no next day, search to the end
};
let search_range = self.data.slice(s![date_index..search_end_idx, ..]);
// Convert query time to timestamp for comparison
let query_timestamp = Self::time_to_timestamp(time, self.timestamp_factor);
// Find the appropriate index based on direction
let row_index = match direction {
QueryDirection::Before => {
let pos = search_range
.column(0)
.to_vec()
.partition_point(|ts| ts <= &query_timestamp);
// If pos is 0, no value is <= query_timestamp
if pos == 0 {
return Err(hdf5::Error::Internal("No data at or before the requested time".into()));
}
// Return the last value that's <= query_timestamp
pos - 1
},
QueryDirection::After => {
let pos = search_range
.column(0)
.to_vec()
.partition_point(|ts| ts <= &query_timestamp);
// If pos is at the end, no value is > query_timestamp
if pos >= search_range.shape()[0] {
return Err(hdf5::Error::Internal("No data after the requested time".into()));
}
pos
}
};
Ok(search_range.row(row_index).to_owned())
}
/// Convenience method to query the last value at or before the given time
pub fn query_before(&self, time: &NaiveDateTime) -> Result<ndarray::Array1<i32>, hdf5::Error> {
self.query(time, QueryDirection::Before)
}
/// Convenience method to query the first value after the given time
pub fn query_after(&self, time: &NaiveDateTime) -> Result<ndarray::Array1<i32>, hdf5::Error> {
self.query(time, QueryDirection::After)
}
}