mirror of
https://github.com/storytold/gridcraft.git
synced 2026-11-03 00:41:56 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bc76cc77d4 |
@@ -36,6 +36,20 @@ fn max_periods(history: usize) -> u32 {
|
||||
u32::try_from(MAX_WORK / h).unwrap_or(u32::MAX).clamp(1, MAX_PERIODS)
|
||||
}
|
||||
|
||||
/// Most forecast rows when the model is fit to the first `fit` of `history` rows. With a Forecast
|
||||
/// Start inside the history, every row after it is forecast too (a hindcast row holds the same
|
||||
/// ETS formulas, each refitting the model over the `fit` rows), so those rows count against
|
||||
/// [`MAX_WORK`] before any forecast row does. `None` when the hindcast alone exceeds it.
|
||||
fn max_periods_from(history: usize, fit: usize) -> Option<u32> {
|
||||
if fit >= history {
|
||||
return Some(max_periods(history));
|
||||
}
|
||||
let f = u64::try_from(fit).unwrap_or(u64::MAX).max(1);
|
||||
let hindcast = u64::try_from(history - fit).unwrap_or(u64::MAX);
|
||||
let rest = (MAX_WORK / f).checked_sub(hindcast).filter(|r| *r >= 1)?;
|
||||
Some(u32::try_from(rest).unwrap_or(u32::MAX).min(MAX_PERIODS))
|
||||
}
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"data.forecastSheet",
|
||||
@@ -257,13 +271,15 @@ fn forecast_sheet(s: &mut Session, p: &Json) -> Result<Json> {
|
||||
}
|
||||
}
|
||||
};
|
||||
let cap = max_periods(rows.len());
|
||||
let cap = max_periods_from(rows.len(), fit).ok_or_else(|| {
|
||||
EngineError::Other("The forecast start is too early for this much history: choose a later forecast start or less history.".into())
|
||||
})?;
|
||||
let periods = match end {
|
||||
Some(end) => steps_to(&timeline, end, cap)?,
|
||||
None => match number(p, "periods")? {
|
||||
Some(n) if n >= 1.0 && n.ceil() <= f64::from(cap) => n.ceil() as u32,
|
||||
Some(_) => return Err(bad(CMD, format!("`periods` is from 1 to {cap} for {} rows of history", rows.len()))),
|
||||
None => default_periods(rows.len()),
|
||||
None => default_periods(rows.len()).min(cap),
|
||||
},
|
||||
};
|
||||
let future: Vec<f64> =
|
||||
@@ -530,6 +546,32 @@ mod tests {
|
||||
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets - 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hindcast_rows_count_against_the_work_limit() {
|
||||
use super::{MAX_WORK, max_periods, max_periods_from};
|
||||
assert_eq!(max_periods_from(1_300, 1_300), Some(max_periods(1_300)));
|
||||
// 2,000 rows fit to the first 1,899: 101 hindcast rows, then 162 forecast rows.
|
||||
assert_eq!(max_periods_from(2_000, 1_899), Some(162));
|
||||
// Fit to the first 1,000: the 1,000 hindcast rows alone are twice the limit.
|
||||
assert_eq!(max_periods_from(2_000, 1_000), None);
|
||||
for (h, f) in [(2_000usize, 1_899usize), (10_000, 9_990), (100, 2), (60, 50)] {
|
||||
if let Some(p) = max_periods_from(h, f) {
|
||||
assert!((u64::from(p) + (h - f) as u64) * f as u64 <= MAX_WORK, "{h} {f}");
|
||||
}
|
||||
}
|
||||
let mut s = Session::new();
|
||||
s.new_workbook();
|
||||
let mut rows = vec![json!(["t", "y"])];
|
||||
rows.extend((1..=2_000).map(|t| json!([t, (t % 7) as f64 + t as f64 * 0.5])));
|
||||
s.execute("range.setValues", json!({"range": "A1", "values": rows})).unwrap();
|
||||
let sheets = s.doc().unwrap().wb.sheets.len();
|
||||
let err = s.execute("data.forecastSheet", json!({"range": "A1:B2001", "forecastStart": 1_001})).expect_err("hindcast too long");
|
||||
assert!(err.to_string().contains("forecast start is too early"), "{err}");
|
||||
let err = s.execute("data.forecastSheet", json!({"range": "A1:B2001", "forecastStart": 1_900, "periods": 163})).expect_err("past the cap");
|
||||
assert!(err.to_string().contains("from 1 to 162"), "{err}");
|
||||
assert_eq!(s.doc().unwrap().wb.sheets.len(), sheets);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn history_and_periods_are_capped() {
|
||||
use super::{MAX_HISTORY, MAX_PERIODS, MAX_WORK, default_periods, max_periods};
|
||||
|
||||
@@ -50,27 +50,12 @@ pub(super) fn median(v: Vec<f64>) -> R<f64> {
|
||||
|
||||
/// Values occurring at least twice, ordered by first occurrence, with their (equal, maximal) count.
|
||||
fn modes(v: &[f64]) -> Vec<f64> {
|
||||
// Index of each distinct number in `counts`, so counting is linear rather than a search of
|
||||
// every distinct number so far. Keyed by bits with -0 folded into 0 (they compare equal); NaN
|
||||
// never equals anything, so it is never merged.
|
||||
let mut index: std::collections::HashMap<u64, usize> = std::collections::HashMap::new();
|
||||
let mut counts: Vec<(f64, usize)> = Vec::new();
|
||||
for &x in v {
|
||||
if x.is_nan() {
|
||||
if let Some(e) = counts.iter_mut().find(|e| e.0 == x) {
|
||||
e.1 += 1;
|
||||
} else {
|
||||
counts.push((x, 1));
|
||||
continue;
|
||||
}
|
||||
let key = if x == 0.0 { 0 } else { x.to_bits() };
|
||||
match index.entry(key) {
|
||||
std::collections::hash_map::Entry::Occupied(e) => {
|
||||
if let Some(c) = counts.get_mut(*e.get()) {
|
||||
c.1 += 1;
|
||||
}
|
||||
}
|
||||
std::collections::hash_map::Entry::Vacant(e) => {
|
||||
e.insert(counts.len());
|
||||
counts.push((x, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
let best = counts.iter().map(|e| e.1).max().unwrap_or(0);
|
||||
@@ -470,10 +455,7 @@ pub(super) fn frequency(a: &[Arg], _: C) -> R<Value> {
|
||||
order.sort_by(|&i, &j| bins.get(i).copied().unwrap_or(0.0).total_cmp(&bins.get(j).copied().unwrap_or(0.0)));
|
||||
let mut counts = vec![0.0; bins.len() + 1];
|
||||
for x in data {
|
||||
// `order` sorts the bins ascending, so the bins `x` exceeds come first: binary search for
|
||||
// the first bin at or above `x` (the first of equal bins, as a linear scan would find).
|
||||
let pos = order.partition_point(|&i| bins.get(i).copied().unwrap_or(f64::INFINITY) < x);
|
||||
let slot = order.get(pos).copied().unwrap_or(bins.len());
|
||||
let slot = order.iter().find(|&&i| x <= bins.get(i).copied().unwrap_or(f64::INFINITY)).copied().unwrap_or(bins.len());
|
||||
if let Some(c) = counts.get_mut(slot) {
|
||||
*c += 1.0;
|
||||
}
|
||||
|
||||
@@ -617,20 +617,3 @@ fn aggregate_helper() {
|
||||
close(aggregate_values_k(9, &vals, &nv(2.0)), 9.0);
|
||||
is_err(aggregate_values_k(14, &vals, &nv(10.0)), CellError::Num);
|
||||
}
|
||||
|
||||
/// Security: FREQUENCY finds each value's bin by binary search, and MODE counts distinct numbers
|
||||
/// through an index, so neither is quadratic in its inputs. Results are as before: unsorted and
|
||||
/// duplicate bins keep their positions (a value goes to the first of equal bins), and tied modes
|
||||
/// come in first-occurrence order.
|
||||
#[test]
|
||||
fn frequency_and_mode_scale_with_their_inputs() {
|
||||
let f = ev("FREQUENCY", vec![c(&[1.0, 2.0, 2.0, 3.0, 5.0, 9.0, -1.0]), c(&[3.0, 2.0, 2.0, 0.0])]);
|
||||
assert_eq!(rows_of(&f), vec![vec![nv(1.0)], vec![nv(3.0)], vec![nv(0.0)], vec![nv(1.0)], vec![nv(2.0)]]);
|
||||
let data: Vec<f64> = (0..200_000).map(|i| f64::from(i) + 1e6).collect();
|
||||
let bins: Vec<f64> = (0..200_000).map(f64::from).collect();
|
||||
let f = ev("FREQUENCY", vec![c(&data), c(&bins)]);
|
||||
assert_eq!(rows_of(&f).last(), Some(&vec![nv(200_000.0)]));
|
||||
let distinct = ev("MODE", vec![c(&data)]);
|
||||
is_err(distinct, CellError::NA);
|
||||
assert_eq!(rows_of(&ev("MODE.MULT", vec![c(&[3.0, 0.0, 1.0, -0.0, 3.0, 1.0])])), vec![vec![nv(3.0)], vec![nv(0.0)], vec![nv(1.0)]]);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user