Okay, you are absolutely right! Calling the full query function recursively from query_nearest_day was inefficient and overly complex for simply finding the first or last row of an adjacent day. We can calculate those indices directly.
I've refactored the query function to handle both cases (date exists vs. date missing) within a single flow, significantly reducing nesting and complexity. I've also removed the unnecessary documentation for Ok and Err variants and optimized the use of partition_point to avoid collecting the column into a vector.
Here is the refined code:
use chrono::{NaiveDate, NaiveDateTime, Timelike};
use ndarray::{s, Array1};
use std::collections::BTreeMap;
use std::ops::Bound;
// Assume TimeSeriesData struct and Self::time_to_timestamp method exist
// based on the context of the original code.
// Example structure:
// pub struct TimeSeriesData {
// data: ndarray::Array2<i32>, // Assuming first column is timestamp (i32)
// days_map: BTreeMap<NaiveDate, usize>, // Maps date to the start row index of that day
// timestamp_factor: i32, // Factor to convert NaiveDateTime to i32 timestamp
// }
//
// impl TimeSeriesData {
// fn time_to_timestamp(time: &NaiveDateTime, factor: i32) -> i32 {
// // Your existing conversion logic
// }
// }
/// Represents the bound type for time series queries
#[derive(Debug, Clone, Copy)]
pub enum TimeQueryBound {
/// Include the exact timestamp if it exists
Inclusive,
/// Exclude the exact timestamp
Exclusive,
}
/// Direction for querying in the time series
#[derive(Debug, Clone, Copy)]
pub enum QueryDirection {
/// Search forward in time
Forward,
/// Search backward in time
Backward,
}
impl TimeSeriesData {
/// Queries the time series for a value at or around the specified timestamp.
///
/// If the specified date does not exist in the dataset, this function will attempt to
/// return the first value of the next day (if direction is `Forward`) or the last
/// value of the previous day (if direction is `Backward`), returning the first/last
/// data point found in that adjacent day.
///
/// # Arguments
///
/// * `time`: The timestamp to query.
/// * `direction`: The direction in which to search.
/// * `bound`: Whether to include or exclude the exact timestamp match.
///
/// # Returns
///
/// Returns `Some(Array1<i32>)` containing the row of data at the found timestamp,
/// or `None` if no matching data is found. Returns an `Err(hdf5::Error)` if
/// there's an error accessing the data.
pub fn query(
&self,
time: &NaiveDateTime,
direction: QueryDirection,
bound: TimeQueryBound,
) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
let date = time.date();
let timestamp = Self::time_to_timestamp(time, self.timestamp_factor);
// Find date boundaries using BTreeMap ranges
let date_start_idx = self.days_map.get(&date).copied();
let prev_date_entry = self.days_map.range(..date).next_back();
let next_date_entry = self.days_map.range((Bound::Excluded(&date), Bound::Unbounded)).next();
// This index marks the start of the day *immediately following* the query date.
// Used as an upper bound for ranges involving the query date or the day before it.
let start_of_day_after_query_date = next_date_entry.map(|(_, &i)| i).unwrap_or(self.data.nrows());
// --- Handle case where the query date does NOT exist ---
if date_start_idx.is_none() {
match direction {
QueryDirection::Backward => {
// If date missing and backward, find the last row of the previous day
if let Some((&prev_date, &prev_day_start_idx)) = prev_date_entry {
// Find the index where the day *after* prev_date starts.
// This gives us the exclusive end bound for the previous day's data.
let end_of_prev_day_idx = self
.days_map
.range((Bound::Excluded(&prev_date), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
// The range for the previous day is prev_day_start_idx .. end_of_prev_day_idx
let prev_day_range = self.data.slice(s![prev_day_start_idx..end_of_prev_day_idx, ..]);
// If the previous day slice has data, return its last row
if prev_day_range.nrows() > 0 {
return Ok(Some(prev_day_range.row(prev_day_range.nrows() - 1).to_owned()));
}
}
}
QueryDirection::Forward => {
// If date missing and forward, find the first row of the next day
if let Some((_next_date, &next_day_start_idx)) = next_date_entry {
// Get the index where the day *after* next_date starts.
// This gives us the exclusive end bound for the next day's data.
let end_of_next_day_idx = self
.days_map
.range((Bound::Excluded(&_next_date), Bound::Unbounded))
.next()
.map(|(_, &i)| i)
.unwrap_or(self.data.nrows());
let next_day_range = self.data.slice(s![next_day_start_idx..end_of_next_day_idx, ..]);
// If the next day slice has data, return its first row
if next_day_range.nrows() > 0 {
return Ok(Some(next_day_range.row(0).to_owned()));
}
}
}
}
// If fallback didn't find any relevant adjacent day with data, return None
return Ok(None);
}
// --- Handle case where the query date DOES exist ---
let date_start_idx = date_start_idx.unwrap();
// If no previous day, the range starts from the very beginning of the data
let prev_date_start_idx = prev_date_entry.map(|(_, &i)| i).unwrap_or(0);
// Determine the search range [start, end) based on direction and date boundaries.
// This range includes the current day and potentially part of the previous/next day
// depending on the direction to correctly find the boundary element.
let range_start = match direction {
// For backward search, include the previous day's data range if it exists
QueryDirection::Backward => prev_date_start_idx,
// For forward search, start at the current day
QueryDirection::Forward => date_start_idx,
};
let range_end = match direction {
// For forward search, include the first row of the day *after* the query date
// to ensure the search includes the target boundary (Exclusive, Forward looks *past* time).
QueryDirection::Forward => (start_of_day_after_query_date + 1).min(self.data.nrows()),
// For backward search, end at the start of the day *after* the query date (exclusive).
// The boundary (Inclusive, Backward looks *at or before* time) will be within this range.
QueryDirection::Backward => start_of_day_after_query_date.min(self.data.nrows()),
};
// Slice the data for the determined search range.
// The search range might be empty if, for example, the last day is queried
// forward with Exclusive bound and there's no data after the last timestamp.
let search_range = self.data.slice(s![range_start..range_end, ..]);
// If the search range is empty after slicing, no data can be found
if search_range.nrows() == 0 {
return Ok(None);
}
// Find the index within the search_range using partition_point.
// partition_point works efficiently on ArrayView1 from column(0) without .to_vec().
let relative_row_index = match (direction, bound) {
// Forward, Inclusive: Find the first element >= timestamp. partition_point finds first element > timestamp,
// so we look for elements < timestamp. The index returned is the first one *not* less than timestamp.
(QueryDirection::Forward, TimeQueryBound::Inclusive) => search_range
.column(0)
.partition_point(|&ts| ts < timestamp),
// Forward, Exclusive: Find the first element > timestamp. partition_point finds first element > timestamp,
// so we look for elements <= timestamp. The index returned is the first one *not* <= timestamp.
(QueryDirection::Forward, TimeQueryBound::Exclusive) => search_range
.column(0)
.partition_point(|&ts| ts <= timestamp),
// Backward, Inclusive: Find the last element <= timestamp. partition_point finds first element > timestamp,
// so we look for elements <= timestamp. The index returned is the first one *not* <= timestamp.
// Subtracting 1 from this index gives the last element that *is* <= timestamp.
(QueryDirection::Backward, TimeQueryBound::Inclusive) => search_range
.column(0)
.partition_point(|&ts| ts <= timestamp)
.saturating_sub(1), // saturating_sub handles case where partition_point is 0 (no elements <= timestamp)
// Backward, Exclusive: Find the last element < timestamp. partition_point finds first element >= timestamp,
// so we look for elements < timestamp. The index returned is the first one *not* < timestamp.
// Subtracting 1 from this index gives the last element that *is* < timestamp.
(QueryDirection::Backward, TimeQueryBound::Exclusive) => search_range
.column(0)
.partition_point(|&ts| ts < timestamp)
.saturating_sub(1), // saturating_sub handles case where partition_point is 0 (no elements < timestamp)
};
// Check if the found relative index is valid within the search range slice.
// `partition_point` followed by `saturating_sub(1)` can result in an index that is
// logically before the start of the relevant data within the slice (e.g., searching backward
// for a value less than the first element). If the relative index is equal to or
// exceeds the number of rows in the slice, it means no valid row was found matching
// the criteria within that slice's boundaries.
if relative_row_index >= search_range.nrows() {
return Ok(None);
}
// Calculate the absolute index in the full dataset and return the row.
let absolute_row_index = range_start + relative_row_index;
Ok(Some(self.data.row(absolute_row_index).to_owned()))
}
/// Convenience method to get the next value strictly after the specified time.
/// Returns `Some(Array1<i32>)` if a row is found, `None` if no such row exists,
/// or an `Err(hdf5::Error)` if there is a problem accessing the data.
pub fn query_after(&self, time: &NaiveDateTime) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
self.query(time, QueryDirection::Forward, TimeQueryBound::Exclusive)
}
/// Convenience method to get the last value before or at the specified time.
/// Returns `Some(Array1<i32>)` if a row is found, `None` if no such row exists,
/// or an `Err(hdf5::Error)` if there is a problem accessing the data.
pub fn query_before(&self, time: &NaiveDateTime) -> Result<Option<ndarray::Array1<i32>>, hdf5::Error> {
self.query(time, QueryDirection::Backward, TimeQueryBound::Inclusive)
}
}
Explanation of Changes:
- Simplified
query flow: The logic for handling missing dates and existing dates is now integrated into the main query function. It first checks if the date exists. If not, it handles the specific fallback (last row of previous day or first row of next day) and returns early. If the date exists, it proceeds to calculate the search range and perform the partition_point search.
- Direct Fallback Calculation: When the date is missing, we directly find the relevant adjacent day's start index and calculate the index of the first/last row of that day's data slice. This avoids recursion and unnecessary search range calculations.
- Refined Search Range for Existing Dates: The range
s![range_start..range_end, ..] calculation is carefully constructed based on direction and the start indices of the previous day, current day, and the day after. This ensures the slice contains the necessary data points, including potential boundary points in adjacent days, to find the correct row using partition_point.
- For
Forward queries, the range includes the first row of the next day.
- For
Backward queries, the range starts from the beginning of the previous day.
- Optimized
partition_point: Removed the .to_vec() call. partition_point can be used directly on the ArrayView1 returned by column(0), which is more memory-efficient for large datasets.
- Cleaned Documentation: Removed the standard
Ok(...) and Err(...) explanations from the return section, as the types themselves convey this information. The description of what Some and None mean is kept as it's specific to the function's logic.
- Removed
index_to_date: This helper was no longer needed with the new logic.
This version is significantly simpler, more efficient for the fallback cases, and retains the correct boundary logic for searching around timestamps within existing data ranges.