flexpool-sim 0.5.0

flexpool replay: bitemporal series with decision-time views, synthetic and imported market days, scenarios and a forward-only test clock. No I/O, no real clock.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! Scenario files: one small TOML file that drives the demo, a test or a bug report.
//!
//! ```toml
//! name = "demo"
//! day  = "2025-10-02"
//! [market]
//! source = "synthetic"   # or "file"
//! seed   = 7
//! [clock]
//! start = "2025-10-01T10:00:00+02:00"   # optional; default 10:00 Berlin on the day before
//! [[fault]]                               # optional, any number: disturb one asset
//! asset = "bess-hamburg-1"
//! kind  = "offline"                       # or "stuck"
//! from  = "2025-10-02T12:00:00+02:00"
//! to    = "2025-10-02T13:00:00+02:00"
//! [dso]                                   # optional: a grid operator asks the pool for flexibility
//! congestion_point = "ea1.2026-11.netz-nord.example:cp-hh-nord"
//! request_at       = "2025-10-01T16:00:00+02:00"
//! isps             = [69, 76]             # first and last quarter of the delivery day, from 1
//! min_kw           = -400                 # the requested band, one direction
//! max_kw           = -100
//! dispute_isp      = 72                   # optional: the operator settles this quarter differently
//! ```
//!
//! Whether a fault's asset exists is checked against the portfolio by the caller.

use std::path::PathBuf;

use flexpool_core::{AssetId, BusinessDay};
use flexpool_telemetry::sim::{Fault, FaultKind};
use serde::Deserialize;
use time::format_description::well_known::Rfc3339;
use time::{Date, OffsetDateTime};

/// Where the scenario's market data comes from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum MarketSource {
    /// The deterministic synthetic generator.
    Synthetic {
        /// Seed.
        seed: u64,
        /// Earlier days generated as history (forecasting), each known from its own publication.
        history_days: u16,
    },
    /// A CSV data file, relative to the scenario file.
    File {
        /// Path as written in the scenario.
        path: PathBuf,
    },
}

/// Earlier synthetic days generated by default (the forecast models' 28-day window).
pub const DEFAULT_HISTORY_DAYS: u16 = 28;
/// At most this many earlier days.
pub const MAX_HISTORY_DAYS: u16 = 60;

/// A validated scenario.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Scenario {
    /// Name.
    pub name: String,
    /// The delivery (business) day replayed.
    pub day: Date,
    /// Market data source.
    pub market: MarketSource,
    /// Where the clock starts.
    pub start: OffsetDateTime,
    /// Where the clock stops.
    pub end: OffsetDateTime,
    /// Planned disturbances of assets, in file order.
    pub faults: Vec<Fault>,
    /// A grid operator that asks for flexibility, orders and settles on the test clock.
    pub dso: Option<Dso>,
}

/// A simulated grid operator: one request for a band of deviation behind a congestion point.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Dso {
    /// The congestion point, a UFTP entity address (`ea1.…:…`).
    pub congestion_point: String,
    /// When the request arrives.
    pub request_at: OffsetDateTime,
    /// First and last quarter of the delivery day it asks for, from 1.
    pub isps: (u32, u32),
    /// The requested band in kW of deviation, one direction: both ≤ 0 (less consumption) or
    /// both ≥ 0 (more).
    pub min_kw: i64,
    /// See `min_kw`.
    pub max_kw: i64,
    /// A quarter the operator settles differently, to show a dispute.
    pub dispute_isp: Option<u32>,
}

/// One problem with a scenario file.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{location}: {message}")]
pub struct ScenarioProblem {
    /// Key or `(file)`.
    pub location: String,
    /// What is wrong.
    pub message: String,
}

#[derive(Deserialize)]
struct Raw {
    name: Option<String>,
    day: Option<toml::Value>,
    market: Option<RawMarket>,
    clock: Option<RawClock>,
    fault: Option<Vec<RawFault>>,
    dso: Option<RawDso>,
}

#[derive(Deserialize)]
struct RawDso {
    congestion_point: Option<String>,
    request_at: Option<String>,
    isps: Option<Vec<i64>>,
    min_kw: Option<i64>,
    max_kw: Option<i64>,
    dispute_isp: Option<i64>,
}

#[derive(Deserialize)]
struct RawFault {
    asset: Option<String>,
    kind: Option<String>,
    from: Option<String>,
    to: Option<String>,
}

#[derive(Deserialize)]
struct RawMarket {
    source: Option<String>,
    seed: Option<u64>,
    file: Option<String>,
    history_days: Option<i64>,
}

#[derive(Deserialize)]
struct RawClock {
    start: Option<String>,
    end: Option<String>,
}

const KNOWN: &[(&str, &[&str])] = &[
    ("", &["name", "day", "market", "clock", "fault", "dso"]),
    ("market", &["source", "seed", "file", "history_days"]),
    ("clock", &["start", "end"]),
    (
        "dso",
        &[
            "congestion_point",
            "request_at",
            "isps",
            "min_kw",
            "max_kw",
            "dispute_isp",
        ],
    ),
];

/// Every key the format does not know, reported alongside the other problems.
fn unknown_keys(table: &toml::Table) -> Vec<ScenarioProblem> {
    let mut out = Vec::new();
    for (section, keys) in KNOWN {
        let t = if section.is_empty() {
            Some(table)
        } else {
            table.get(*section).and_then(toml::Value::as_table)
        };
        for key in t.into_iter().flat_map(toml::Table::keys) {
            if !keys.contains(&key.as_str()) {
                let location = if section.is_empty() {
                    key.clone()
                } else {
                    format!("{section}.{key}")
                };
                out.push(problem(&location, "unknown key"));
            }
        }
    }
    let faults = table.get("fault").and_then(toml::Value::as_array);
    for (i, f) in faults.into_iter().flatten().enumerate() {
        for key in f.as_table().into_iter().flat_map(toml::Table::keys) {
            if !["asset", "kind", "from", "to"].contains(&key.as_str()) {
                out.push(problem(&format!("fault[{}].{key}", i + 1), "unknown key"));
            }
        }
    }
    out
}

fn faults(raw: Vec<RawFault>, problems: &mut Vec<ScenarioProblem>) -> Vec<Fault> {
    let mut out = Vec::new();
    for (i, f) in raw.into_iter().enumerate() {
        let at = |k: &str| format!("fault[{}].{k}", i + 1);
        let asset = match f.asset.map(AssetId::parse) {
            Some(Ok(id)) => Some(id),
            Some(Err(e)) => {
                problems.push(problem(&at("asset"), e.to_string()));
                None
            }
            None => {
                problems.push(problem(&at("asset"), "required"));
                None
            }
        };
        let kind = match f.kind.as_deref() {
            Some("offline") => Some(FaultKind::Offline),
            Some("stuck") => Some(FaultKind::Stuck),
            Some("tripped") => Some(FaultKind::Tripped),
            Some(other) => {
                problems.push(problem(
                    &at("kind"),
                    format!("{other:?} must be \"offline\", \"stuck\" or \"tripped\""),
                ));
                None
            }
            None => {
                problems.push(problem(
                    &at("kind"),
                    "required: \"offline\", \"stuck\" or \"tripped\"",
                ));
                None
            }
        };
        let mut when = |k: &str, v: Option<String>| match v {
            Some(s) => instant(&at(k), &s, problems),
            None => {
                problems.push(problem(&at(k), "required"));
                None
            }
        };
        let (from, to) = (when("from", f.from), when("to", f.to));
        if let (Some(from), Some(to)) = (from, to)
            && to <= from
        {
            problems.push(problem(&at("to"), "must be after from"));
            continue;
        }
        if let (Some(asset), Some(kind), Some(from), Some(to)) = (asset, kind, from, to) {
            out.push(Fault {
                asset,
                kind,
                from: from.unix_timestamp(),
                to: to.unix_timestamp(),
            });
        }
    }
    out
}

fn dso(raw: RawDso, quarters: u16, problems: &mut Vec<ScenarioProblem>) -> Option<Dso> {
    let before = problems.len();
    let cp = raw.congestion_point.unwrap_or_default();
    if !(cp.starts_with("ea1.") && cp.contains(':')) {
        problems.push(problem(
            "dso.congestion_point",
            format!("{cp:?} is not a UFTP entity address like ea1.2026-11.netz.example:cp-1"),
        ));
    }
    let request_at = match raw.request_at {
        Some(s) => instant("dso.request_at", &s, problems),
        None => {
            problems.push(problem("dso.request_at", "required"));
            None
        }
    };
    let n = i64::from(quarters);
    let isps = match raw.isps.as_deref() {
        Some(&[a, b]) if 1 <= a && a <= b && b <= n => {
            Some((u32::try_from(a).ok()?, u32::try_from(b).ok()?))
        }
        _ => {
            problems.push(problem(
                "dso.isps",
                format!("[first, last] within 1–{n}, first ≤ last"),
            ));
            None
        }
    };
    let (min_kw, max_kw) = (raw.min_kw.unwrap_or(0), raw.max_kw.unwrap_or(0));
    if raw.min_kw.is_none() || raw.max_kw.is_none() {
        problems.push(problem("dso", "min_kw and max_kw are required"));
    } else if min_kw > max_kw || (min_kw < 0 && max_kw > 0) || (min_kw == 0 && max_kw == 0) {
        problems.push(problem(
            "dso.max_kw",
            "the band needs min_kw ≤ max_kw on one side of zero (UFTP: a requested deviation has one direction)",
        ));
    }
    let dispute_isp = match (raw.dispute_isp, isps) {
        (None, _) => None,
        (Some(d), Some((a, b))) if (i64::from(a)..=i64::from(b)).contains(&d) => {
            u32::try_from(d).ok()
        }
        (Some(_), _) => {
            problems.push(problem("dso.dispute_isp", "must lie within dso.isps"));
            None
        }
    };
    let (Some(request_at), Some(isps), true) = (request_at, isps, problems.len() == before) else {
        return None;
    };
    Some(Dso {
        congestion_point: cp,
        request_at,
        isps,
        min_kw,
        max_kw,
        dispute_isp,
    })
}

/// The data file a scenario names, read best-effort so its problems can be reported even when
/// other fields are invalid.
#[must_use]
pub fn data_file(text: &str) -> Option<PathBuf> {
    let table: toml::Table = text.parse().ok()?;
    let market = table.get("market")?.as_table()?;
    (market.get("source")?.as_str()? == "file")
        .then(|| market.get("file")?.as_str().map(PathBuf::from))?
}

fn problem(location: &str, message: impl Into<String>) -> ScenarioProblem {
    ScenarioProblem {
        location: location.to_owned(),
        message: message.into(),
    }
}

fn instant(location: &str, s: &str, problems: &mut Vec<ScenarioProblem>) -> Option<OffsetDateTime> {
    match OffsetDateTime::parse(s, &Rfc3339) {
        Ok(t) => Some(t.to_offset(time::UtcOffset::UTC)),
        Err(_) => {
            problems.push(problem(
                location,
                format!("{s:?} is not an RFC 3339 instant like 2025-10-01T10:00:00+02:00"),
            ));
            None
        }
    }
}

impl Scenario {
    /// Parses scenario TOML, collecting every problem. File existence is the caller's concern.
    ///
    /// # Errors
    /// Every problem, each with its key.
    pub fn parse(text: &str) -> Result<Self, Vec<ScenarioProblem>> {
        let table: toml::Table = text.parse().map_err(|e: toml::de::Error| {
            let at = e.span().map_or_else(
                || "(file)".into(),
                |s| format!("(file) at byte {}", s.start),
            );
            vec![problem(&at, e.message())]
        })?;
        // Unknown keys are problems like any other, not an abort: every problem in one run.
        let mut problems = unknown_keys(&table);
        let raw: Raw = match toml::Value::Table(table).try_into() {
            Ok(raw) => raw,
            Err(e) => {
                problems.push(problem("(file)", e.message()));
                return Err(problems);
            }
        };
        let name = raw.name.unwrap_or_else(|| {
            problems.push(problem("name", "required"));
            String::new()
        });
        let date_fmt = time::macros::format_description!("[year]-[month]-[day]");
        let day = match raw.day {
            None => {
                problems.push(problem("day", "required, e.g. day = \"2025-10-02\""));
                None
            }
            Some(toml::Value::Datetime(d)) => {
                Date::parse(&d.to_string(), date_fmt).ok().or_else(|| {
                    problems.push(problem("day", format!("{d} is not a calendar date")));
                    None
                })
            }
            Some(toml::Value::String(s)) => Date::parse(&s, date_fmt).ok().or_else(|| {
                problems.push(problem(
                    "day",
                    format!("{s:?} is not a date like 2025-10-02"),
                ));
                None
            }),
            Some(other) => {
                problems.push(problem("day", format!("{other} is not a date")));
                None
            }
        };
        let business = day.and_then(|d| match BusinessDay::new(d) {
            Ok(b) => Some(b),
            Err(e) => {
                problems.push(problem("day", e.to_string()));
                None
            }
        });
        let market = match raw.market {
            None => {
                problems.push(problem(
                    "market",
                    "required: [market] source = \"synthetic\" or \"file\"",
                ));
                None
            }
            Some(m) => match (m.source.as_deref(), m.seed, m.file) {
                (Some("synthetic"), Some(seed), None) => match m.history_days {
                    None => Some(MarketSource::Synthetic {
                        seed,
                        history_days: DEFAULT_HISTORY_DAYS,
                    }),
                    Some(d) => match u16::try_from(d).ok().filter(|d| *d <= MAX_HISTORY_DAYS) {
                        Some(history_days) => Some(MarketSource::Synthetic { seed, history_days }),
                        None => {
                            problems.push(problem(
                                "market.history_days",
                                format!("{d} must be 0–{MAX_HISTORY_DAYS}"),
                            ));
                            None
                        }
                    },
                },
                (Some("synthetic"), None, None) => {
                    problems.push(problem(
                        "market.seed",
                        "required for source = \"synthetic\"",
                    ));
                    None
                }
                (Some("file"), None, Some(_)) if m.history_days.is_some() => {
                    problems.push(problem(
                        "market.history_days",
                        "applies to source = \"synthetic\" only; a data file holds one day",
                    ));
                    None
                }
                (Some("file"), None, Some(file)) => Some(MarketSource::File {
                    path: PathBuf::from(file),
                }),
                (Some("file"), None, None) => {
                    problems.push(problem("market.file", "required for source = \"file\""));
                    None
                }
                (Some(s @ ("synthetic" | "file")), _, _) => {
                    problems.push(problem(
                        "market",
                        format!(
                            "source = {s:?} takes {} only",
                            if s == "file" { "file" } else { "seed" }
                        ),
                    ));
                    None
                }
                (other, _, _) => {
                    problems.push(problem(
                        "market.source",
                        format!("{other:?} must be \"synthetic\" or \"file\""),
                    ));
                    None
                }
            },
        };
        let clock = raw.clock.unwrap_or(RawClock {
            start: None,
            end: None,
        });
        let start = clock
            .start
            .as_deref()
            .and_then(|s| instant("clock.start", s, &mut problems));
        let end = clock
            .end
            .as_deref()
            .and_then(|s| instant("clock.end", s, &mut problems));
        let faults = faults(raw.fault.unwrap_or_default(), &mut problems);
        let (Some(business), Some(market)) = (business, market) else {
            return Err(problems);
        };
        let dso = raw.dso.and_then(|d| dso(d, business.len(), &mut problems));
        // Default start: 10:00 Berlin on the day before delivery = 2 h before the day-ahead gate.
        let start = start.unwrap_or_else(|| business.start() - time::Duration::hours(14));
        let end = end.unwrap_or_else(|| business.end());
        if end <= start {
            problems.push(problem("clock.end", "must be after clock.start"));
        }
        if let Some(d) = &dso
            && !(start..end).contains(&d.request_at)
        {
            problems.push(problem(
                "dso.request_at",
                "must lie within the clock's range",
            ));
        }
        if !problems.is_empty() {
            return Err(problems);
        }
        Ok(Self {
            name,
            day: business.date(),
            market,
            start,
            end,
            faults,
            dso,
        })
    }
}