flexibility 0.1.0

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, IEC 104 converters.
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
//! Flexibility a power box cannot hold: storage, whose limits are on the **level** it reaches,
//! not only on the power per ISP. A car that must have 30 kWh by 07:00, a battery kept between
//! 1 and 9 kWh, a heat buffer between two temperatures: power bounds per ISP plus bounds on the
//! stored energy at ISP boundaries (the fill-level or virtual-battery model).
//!
//! The level is the initial level plus the exact integral of power, consumption (charging)
//! positive. Losses and self-discharge are not modelled. Power is constant within an ISP, so the
//! level's extremes are at the boundaries, and checking every boundary is exact.
//!
//! ```
//! use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
//! use flexibility::*;
//! let berlin = TimeZone::get("Europe/Berlin")?;
//! let night = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?.slice(1..=28)?;
//! let charger = Provenance::new("emob.example", "charger-11kW", night.start());
//! let car = Provenance::new("emob.example", "departure", night.start());
//!
//! let all = Window::new(night.start(), night.end())?;
//! let power = Envelope::unbounded(night.clone()).apply(&Limit::band(all, kw!(0), kw!(11), charger)?)?;
//! let ev = EnergyEnvelope::new(power, kwh!(0)).level_at(night.local(time(7, 0, 0, 0))?, Level::at_least(kwh!(30)), car)?;
//!
//! // 4 kW all night fits the charger, and misses the departure energy.
//! let plan = Schedule::new(Series::filled(night, kw!(4)), Provenance::new("emob.example", "plan-1", all.from()));
//! let report = ev.check(&plan)?;
//! assert!(report.power.is_empty());
//! assert_eq!(
//!     report.level[0].to_string(),
//!     "after ISP 28 (06:45–07:00 +01:00): level 28 kWh below min 30 kWh set by emob.example departure"
//! );
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use std::fmt;

use jiff::Timestamp;

use crate::{Energy, Envelope, Error, Grid, IspLabel, Provenance, Schedule, Violation};

/// Bounds on a stored level: an optional minimum and maximum energy, the minimum never above the
/// maximum.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Level {
    min: Option<Energy>,
    max: Option<Energy>,
}

impl Level {
    /// A level between `min` and `max`, both optional and inclusive.
    ///
    /// # Errors
    /// [`Error::InvertedLevel`] if `min` is above `max`.
    pub fn new(min: Option<Energy>, max: Option<Energy>) -> Result<Level, Error> {
        if let (Some(min), Some(max)) = (min, max)
            && min > max
        {
            return Err(Error::InvertedLevel { min, max });
        }
        Ok(Level { min, max })
    }

    /// At least `min`: a departure energy, a reserve.
    #[must_use]
    pub const fn at_least(min: Energy) -> Level {
        Level {
            min: Some(min),
            max: None,
        }
    }

    /// At most `max`: a capacity.
    #[must_use]
    pub const fn at_most(max: Energy) -> Level {
        Level {
            min: None,
            max: Some(max),
        }
    }

    /// Between `min` and `max`: a state-of-charge window.
    ///
    /// # Errors
    /// [`Error::InvertedLevel`] if `min` is above `max`.
    pub fn between(min: Energy, max: Energy) -> Result<Level, Error> {
        Level::new(Some(min), Some(max))
    }

    /// The lowest allowed level, if any.
    #[must_use]
    pub const fn min(self) -> Option<Energy> {
        self.min
    }

    /// The highest allowed level, if any.
    #[must_use]
    pub const fn max(self) -> Option<Energy> {
        self.max
    }

    /// Whether `level` lies within the bounds.
    #[must_use]
    pub fn contains(self, level: Energy) -> bool {
        self.min.is_none_or(|m| level >= m) && self.max.is_none_or(|m| level <= m)
    }
}

impl fmt::Display for Level {
    /// `min 30 kWh`, `max 9 kWh`, `1 kWh to 9 kWh` or `unbounded`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match (self.min, self.max) {
            (None, None) => f.write_str("unbounded"),
            (None, Some(max)) => write!(f, "max {max}"),
            (Some(min), None) => write!(f, "min {min}"),
            (Some(min), Some(max)) => write!(f, "{min} to {max}"),
        }
    }
}

/// One side of a boundary's level bound and the index of the provenance that set it.
type Sourced = Option<(Energy, usize)>;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub(crate) struct LevelSlot {
    pub(crate) min: Sourced,
    pub(crate) max: Sourced,
}

impl LevelSlot {
    pub(crate) fn level(self) -> Level {
        Level {
            min: self.min.map(|(e, _)| e),
            max: self.max.map(|(e, _)| e),
        }
    }
}

/// Power bounds per ISP and bounds on the stored level after each ISP, from an initial level.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EnergyEnvelope {
    power: Envelope,
    initial: Energy,
    /// Slot *k* bounds the level after the *k*-th ISP of the grid.
    levels: Vec<LevelSlot>,
    provenances: Vec<Provenance>,
}

/// Which level bound a plan breaks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LevelBroken {
    /// Below this minimum.
    Below(Energy),
    /// Above this maximum.
    Above(Energy),
}

/// One ISP boundary at which a plan's level leaves its bounds.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LevelViolation {
    /// The ISP the boundary ends.
    pub after: IspLabel,
    /// The level the plan reaches there.
    pub level: Energy,
    /// The bound it breaks.
    pub broken: LevelBroken,
    /// Who set that bound.
    pub source: Provenance,
}

impl fmt::Display for LevelViolation {
    /// `after ISP 28 (06:45–07:00 +01:00): level 28 kWh below min 30 kWh set by emob.example
    /// departure`.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (side, bound) = match self.broken {
            LevelBroken::Below(e) => ("below min", e),
            LevelBroken::Above(e) => ("above max", e),
        };
        write!(
            f,
            "after {}: level {} {side} {bound} set by {}",
            self.after, self.level, self.source
        )
    }
}

/// Everything wrong with one plan against an [`EnergyEnvelope`]: power and level.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
pub struct Report {
    /// Every ISP whose power leaves the power envelope.
    pub power: Vec<Violation>,
    /// Every boundary whose level leaves its bounds.
    pub level: Vec<LevelViolation>,
}

impl Report {
    /// Whether the plan fits: no power and no level violation.
    #[must_use]
    pub fn fits(&self) -> bool {
        self.power.is_empty() && self.level.is_empty()
    }
}

fn stricter(left: Sourced, right: Sourced, right_wins: impl Fn(Energy, Energy) -> bool) -> Sourced {
    match (left, right) {
        (Some(l), Some(r)) => Some(if right_wins(l.0, r.0) { r } else { l }),
        (l, None) => l,
        (None, r) => r,
    }
}

pub(crate) fn overflow(left: i128) -> Error {
    Error::Overflow {
        quantity: "energy",
        operation: "level",
        left,
        right: None,
    }
}

impl EnergyEnvelope {
    /// Storage behind `power`, holding `initial` at the start of the grid, with no level bound
    /// yet. A device without storage is one with no level bound ever set.
    #[must_use]
    pub fn new(power: Envelope, initial: Energy) -> EnergyEnvelope {
        let levels = vec![LevelSlot::default(); power.grid().count() as usize];
        EnergyEnvelope {
            power,
            initial,
            levels,
            provenances: Vec::new(),
        }
    }

    pub(crate) fn from_parts(
        power: Envelope,
        initial: Energy,
        levels: Vec<LevelSlot>,
        provenances: Vec<Provenance>,
    ) -> EnergyEnvelope {
        EnergyEnvelope {
            power,
            initial,
            levels,
            provenances,
        }
    }

    pub(crate) fn slots(&self) -> &[LevelSlot] {
        &self.levels
    }

    /// The power bounds per ISP.
    #[must_use]
    pub fn power(&self) -> &Envelope {
        &self.power
    }

    /// The grid.
    #[must_use]
    pub fn grid(&self) -> &Grid {
        self.power.grid()
    }

    /// The level at the start of the grid.
    #[must_use]
    pub fn initial(&self) -> Energy {
        self.initial
    }

    /// The level bound after ISP `isp`; `None` outside the grid.
    #[must_use]
    pub fn level_after(&self, isp: u32) -> Option<Level> {
        let i = self.grid().index(isp)? as usize;
        self.levels.get(i).map(|s| s.level())
    }

    /// Who set the level bound after ISP `isp` on each side: (minimum, maximum).
    #[must_use]
    pub fn level_sources(&self, isp: u32) -> Option<(Option<&Provenance>, Option<&Provenance>)> {
        let i = self.grid().index(isp)? as usize;
        let slot = self.levels.get(i)?;
        let source = |s: Sourced| s.and_then(|(_, k)| self.provenances.get(k));
        Some((source(slot.min), source(slot.max)))
    }

    fn add(
        &self,
        indices: impl Iterator<Item = usize>,
        level: Level,
        provenance: Provenance,
    ) -> Result<EnergyEnvelope, Error> {
        let mut next = self.clone();
        let k = next
            .provenances
            .iter()
            .position(|p| p == &provenance)
            .unwrap_or_else(|| {
                next.provenances.push(provenance);
                next.provenances.len() - 1
            });
        for i in indices {
            if let Some(slot) = next.levels.get_mut(i) {
                slot.min = stricter(slot.min, level.min.map(|e| (e, k)), |l, r| r > l);
                slot.max = stricter(slot.max, level.max.map(|e| (e, k)), |l, r| r < l);
                if let (Some((min, _)), Some((max, _))) = (slot.min, slot.max)
                    && min > max
                {
                    let grid = self.power.grid();
                    return Err(Error::EmptyLevel {
                        after: grid.label_total(grid.first() + u32::try_from(i).unwrap_or(0)),
                        min,
                        max,
                    });
                }
            }
        }
        Ok(next)
    }

    /// This envelope with `level` in force at instant `at`, which must end an ISP of the grid:
    /// a departure energy, a fill level at a deadline. On a side already bounded there, the
    /// stricter bound is kept with its source.
    ///
    /// # Errors
    /// [`Error::NotABoundary`] if `at` does not end an ISP of the grid; [`Error::EmptyLevel`]
    /// if, with the bounds already set there, no level is allowed.
    pub fn level_at(
        &self,
        at: Timestamp,
        level: Level,
        provenance: Provenance,
    ) -> Result<EnergyEnvelope, Error> {
        let grid = self.grid();
        let i = (0..grid.count())
            .find(|&i| {
                grid.interval(grid.first() + i)
                    .is_some_and(|w| w.until() == at)
            })
            .ok_or_else(|| Error::NotABoundary {
                at,
                grid: grid.clone(),
            })?;
        self.add(std::iter::once(i as usize), level, provenance)
    }

    /// This envelope with `level` in force after every ISP: a capacity, a state-of-charge window.
    /// The initial level must already be inside it.
    ///
    /// # Errors
    /// [`Error::InitialLevel`] if the initial level is outside `level`; [`Error::EmptyLevel`] if,
    /// with the bounds already set, a boundary allows no level.
    pub fn level_always(
        &self,
        level: Level,
        provenance: Provenance,
    ) -> Result<EnergyEnvelope, Error> {
        if !level.contains(self.initial) {
            return Err(Error::InitialLevel {
                initial: self.initial,
                level,
            });
        }
        self.add(0..self.levels.len(), level, provenance)
    }

    /// Whether any level bound is set.
    #[must_use]
    pub fn has_levels(&self) -> bool {
        self.levels
            .iter()
            .any(|s| s.min.is_some() || s.max.is_some())
    }

    /// Every power violation of `plan` and every boundary whose level leaves its bounds, in ISP
    /// order. The level starts from [`initial`](EnergyEnvelope::initial).
    ///
    /// # Errors
    /// [`Error::GridMismatch`] if `plan` is on another grid; [`Error::Overflow`] if a level
    /// leaves the energy range.
    pub fn check(&self, plan: &Schedule) -> Result<Report, Error> {
        let power = plan.check(&self.power)?;
        let seconds = i128::from(self.grid().isp().minutes()) * 60;
        let mut level = i128::from(self.initial.watt_seconds());
        let mut violations = Vec::new();
        for ((isp, p), slot) in plan.series().iter().zip(&self.levels) {
            level += i128::from(p.watts()) * seconds;
            let e = Energy::from_watt_seconds(i64::try_from(level).map_err(|_| overflow(level))?);
            let broken = match (slot.min, slot.max) {
                (Some((min, k)), _) if e < min => Some((LevelBroken::Below(min), k)),
                (_, Some((max, k))) if e > max => Some((LevelBroken::Above(max), k)),
                _ => None,
            };
            if let Some((broken, k)) = broken
                && let Some(source) = self.provenances.get(k)
            {
                violations.push(LevelViolation {
                    after: self.grid().label_total(isp),
                    level: e,
                    broken,
                    source: source.clone(),
                });
            }
        }
        Ok(Report {
            power,
            level: violations,
        })
    }
}