1use flexpool_core::BusinessDay;
4use flexpool_rules::RuleBook;
5use flexpool_sim::Series;
6use rust_decimal::prelude::ToPrimitive;
7use serde::Serialize;
8use time::{Date, OffsetDateTime};
9
10use crate::model::{Forecast, LEVELS, Model, builtin};
11
12pub const REFERENCE: Model = Model::NaiveWeek;
14
15#[must_use]
17pub fn pinball(y: f64, q: f64, tau: f64) -> f64 {
18 let d = y - q;
19 (tau * d).max((tau - 1.0) * d)
20}
21
22#[derive(Debug, Clone, PartialEq, Serialize)]
24pub struct DayScore {
25 pub day: Date,
27 pub quantile_score: f64,
29 pub coverage80: f64,
31 pub coverage50: f64,
33 pub mae: f64,
35}
36
37#[must_use]
39pub fn score(
40 forecast: &Forecast,
41 actual: &dyn Fn(OffsetDateTime) -> Option<f64>,
42) -> Option<DayScore> {
43 let (mut qs, mut c80, mut c50, mut mae, mut n) = (0.0, 0, 0, 0.0, 0_u32);
44 for i in &forecast.intervals {
45 let Some(y) = actual(i.start) else { continue };
46 n += 1;
47 qs += LEVELS
48 .iter()
49 .zip(i.q)
50 .map(|(tau, q)| pinball(y, q, *tau))
51 .sum::<f64>()
52 / LEVELS.len() as f64;
53 c80 += u32::from(i.q[0] <= y && y <= i.q[4]);
54 c50 += u32::from(i.q[1] <= y && y <= i.q[3]);
55 mae += (y - i.q[2]).abs();
56 }
57 (n > 0).then(|| {
58 let n = f64::from(n);
59 DayScore {
60 day: forecast.day,
61 quantile_score: qs / n,
62 coverage80: f64::from(c80) / n,
63 coverage50: f64::from(c50) / n,
64 mae: mae / n,
65 }
66 })
67}
68
69#[derive(Debug, Clone, PartialEq, Serialize)]
71pub struct LadderRow {
72 pub model: String,
74 pub builtin: bool,
76 pub days: usize,
78 pub quantile_score: f64,
80 pub skill: Option<f64>,
82 pub coverage80: f64,
84 pub coverage50: f64,
86 pub mae: f64,
88 pub scores: Vec<DayScore>,
90}
91
92#[derive(Debug, Clone, PartialEq, Serialize)]
94pub struct Ladder {
95 pub reference: String,
97 pub days: Vec<Date>,
99 pub rows: Vec<LadderRow>,
101}
102
103impl Ladder {
104 #[must_use]
108 pub fn compute(
109 series: &Series,
110 rules: &RuleBook,
111 now: OffsetDateTime,
112 window: usize,
113 external: &[(String, Vec<Forecast>)],
114 ) -> Self {
115 let known = series.at(now);
116 let actual = |t: OffsetDateTime| {
117 known
118 .containing(t)
119 .ok()
120 .flatten()
121 .and_then(|o| o.value.value().to_f64())
122 };
123 let mut days = Vec::new();
125 let mut date = flexpool_core::calendar::to_berlin(now).date().next_day();
126 for _ in 0..(window + 10) {
127 let Some(d) = date else { break };
128 if let Ok(b) = BusinessDay::new(d)
129 && !known.range(b.start(), b.end()).is_empty()
130 {
131 days.push(b);
132 if days.len() == window {
133 break;
134 }
135 }
136 date = d.previous_day();
137 }
138 days.reverse();
139 let gate = |d: &BusinessDay| rules.gate("da.gate", d.date()).ok().map(|(g, _)| g);
140 let mut rows: Vec<LadderRow> = Vec::new();
141 let mut reference: Vec<DayScore> = Vec::new();
142 for model in Model::ALL {
143 let scores: Vec<DayScore> = days
144 .iter()
145 .filter_map(|d| {
146 let (minutes, _) = rules.da_mtu(d.date()).ok()?;
147 let f = builtin(model, &series.at(gate(d)?), d, minutes).ok()?;
148 score(&f, &actual)
149 })
150 .collect();
151 if model == REFERENCE {
152 reference.clone_from(&scores);
153 }
154 rows.push(row(model.name(), true, scores));
155 }
156 for (name, versions) in external {
157 let scores: Vec<DayScore> = days
158 .iter()
159 .filter_map(|d| {
160 let g = gate(d)?;
161 let f = versions
162 .iter()
163 .filter(|f| f.day == d.date() && f.issued_at <= g)
164 .max_by_key(|f| f.issued_at)?;
165 score(f, &actual)
166 })
167 .collect();
168 rows.push(row(name, false, scores));
169 }
170 for r in &mut rows {
171 let reference: Vec<&DayScore> = reference
172 .iter()
173 .filter(|s| r.scores.iter().any(|x| x.day == s.day))
174 .collect();
175 if !reference.is_empty() && r.days > 0 {
176 #[expect(clippy::cast_precision_loss, reason = "a handful of days")]
177 let ref_qs = reference.iter().map(|s| s.quantile_score).sum::<f64>()
178 / reference.len() as f64;
179 r.skill = (ref_qs > 0.0).then(|| 1.0 - r.quantile_score / ref_qs);
180 }
181 }
182 rows.sort_by(|a, b| {
183 (a.days == 0)
184 .cmp(&(b.days == 0))
185 .then(a.quantile_score.total_cmp(&b.quantile_score))
186 });
187 Self {
188 reference: REFERENCE.name().to_owned(),
189 days: days.iter().map(BusinessDay::date).collect(),
190 rows,
191 }
192 }
193}
194
195fn row(model: &str, builtin: bool, scores: Vec<DayScore>) -> LadderRow {
196 #[expect(clippy::cast_precision_loss, reason = "a handful of days")]
197 let n = scores.len().max(1) as f64;
198 let mean = |f: fn(&DayScore) -> f64| scores.iter().map(f).sum::<f64>() / n;
199 LadderRow {
200 model: model.to_owned(),
201 builtin,
202 days: scores.len(),
203 quantile_score: mean(|s| s.quantile_score),
204 skill: None,
205 coverage80: mean(|s| s.coverage80),
206 coverage50: mean(|s| s.coverage50),
207 mae: mean(|s| s.mae),
208 scores,
209 }
210}