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
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
//! The ISP grid, windows of time, and ISP labels in local time.

use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::RangeInclusive;

use jiff::civil::{Date, Time};
use jiff::tz::{AmbiguousOffset, Offset, TimeZone};
use jiff::{SignedDuration, Timestamp};

use crate::Error;

/// The largest grid: one leap year of 1-minute ISPs. Larger grids are refused before
/// anything is allocated.
pub const MAX_ISPS: u32 = 527_040;

const NANOS_PER_MINUTE: i128 = 60_000_000_000;

/// The length of one imbalance settlement period (ISP), in whole minutes that divide a day.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IspDuration(u16);

impl IspDuration {
    /// The European default since 2025: 15 minutes.
    pub const FIFTEEN_MINUTES: IspDuration = IspDuration(15);

    /// An ISP of `minutes`.
    ///
    /// # Errors
    /// [`Error::IspDuration`] unless `minutes` divides 1440 (a day) evenly.
    pub fn from_minutes(minutes: u16) -> Result<IspDuration, Error> {
        if minutes == 0 || 1440 % minutes != 0 {
            return Err(Error::IspDuration { minutes });
        }
        Ok(IspDuration(minutes))
    }

    /// The length in minutes.
    #[must_use]
    pub const fn minutes(self) -> u16 {
        self.0
    }

    fn nanos(self) -> i128 {
        i128::from(self.0) * NANOS_PER_MINUTE
    }
}

impl IspDuration {
    /// Reads the canonical text `PT15M`.
    pub(crate) fn from_canonical(text: &str) -> Option<IspDuration> {
        let minutes = text.strip_prefix("PT")?.strip_suffix('M')?;
        if minutes.starts_with('0') || !minutes.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        IspDuration::from_minutes(minutes.parse().ok()?).ok()
    }
}

impl fmt::Display for IspDuration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "PT{}M", self.0)
    }
}

/// A non-empty, half-open interval of time `[from, until)`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Window {
    from: Timestamp,
    until: Timestamp,
}

impl Window {
    /// `[from, until)`.
    ///
    /// # Errors
    /// [`Error::EmptyWindow`] unless `until` is after `from`.
    pub fn new(from: Timestamp, until: Timestamp) -> Result<Window, Error> {
        if until <= from {
            return Err(Error::EmptyWindow { from, until });
        }
        Ok(Window { from, until })
    }

    /// The start, included.
    #[must_use]
    pub fn from(self) -> Timestamp {
        self.from
    }

    /// The end, excluded.
    #[must_use]
    pub fn until(self) -> Timestamp {
        self.until
    }
}

impl fmt::Display for Window {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} to {}", self.from, self.until)
    }
}

/// A run of `count` ISPs of equal length from `start`, labelled in a time zone.
///
/// ISPs are numbered from 1, as UFTP numbers them per day. A [slice](Grid::slice) keeps its
/// parent's numbers: the evening of a day grid is ISPs 69 to 76, not 1 to 8, so a settlement
/// line names the ISP the wire and the meter name.
///
/// Two grids are equal when start, ISP duration, count and numbering are: the zone is how the
/// grid is *shown* and how local times are *read*, not which ISPs it has. Values on different
/// grids are never combined.
#[derive(Debug, Clone)]
pub struct Grid {
    start: Timestamp,
    isp: IspDuration,
    count: u32,
    first: u32,
    zone: TimeZone,
}

impl PartialEq for Grid {
    fn eq(&self, other: &Grid) -> bool {
        self.start == other.start
            && self.isp == other.isp
            && self.count == other.count
            && self.first == other.first
    }
}

impl Eq for Grid {}

impl Hash for Grid {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.start.hash(state);
        self.isp.hash(state);
        self.count.hash(state);
        self.first.hash(state);
    }
}

impl Grid {
    /// `count` ISPs of `isp` from `start`, labelled in `zone`.
    ///
    /// # Errors
    /// [`Error::GridSize`] outside `1..=MAX_ISPS`; [`Error::TimeRange`] if the grid ends
    /// outside the representable time range.
    pub fn new(
        start: Timestamp,
        isp: IspDuration,
        count: u32,
        zone: TimeZone,
    ) -> Result<Grid, Error> {
        if count == 0 || count > MAX_ISPS {
            return Err(Error::GridSize {
                count: u64::from(count),
            });
        }
        let grid = Grid {
            start,
            isp,
            count,
            first: 1,
            zone,
        };
        grid.offset(count)
            .ok_or(Error::TimeRange { start, count })?;
        Ok(grid)
    }

    /// The ISPs of `date` in `zone`, from its start of day to the next. Days on which the
    /// clocks change have fewer or more ISPs: 92 or 100 quarter hours in Central Europe.
    ///
    /// # Errors
    /// [`Error::Day`] if the date has no start of day in the zone, or its length is not a
    /// whole number of ISPs (a 30-minute DST shift with one-hour ISPs).
    pub fn day(date: Date, zone: &TimeZone, isp: IspDuration) -> Result<Grid, Error> {
        let day_error = |reason| Error::Day {
            date,
            zone: zone_name(zone),
            reason,
        };
        let start_of = |d: Date| {
            d.to_zoned_datetime(zone.clone())
                .and_then(|z| z.start_of_day())
                .map(|z| z.timestamp())
        };
        let start = start_of(date).map_err(|_| day_error("the day has no start"))?;
        let next = date
            .tomorrow()
            .and_then(start_of)
            .map_err(|_| day_error("the next day has no start"))?;
        let length = next.as_nanosecond() - start.as_nanosecond();
        if length <= 0 || length % isp.nanos() != 0 {
            return Err(day_error("the day is not a whole number of ISPs"));
        }
        let count = u32::try_from(length / isp.nanos())
            .map_err(|_| day_error("the day has too many ISPs"))?;
        Grid::new(start, isp, count, zone.clone())
    }

    /// The run of ISPs `isps` as a grid of its own, keeping this grid's ISP numbers: the
    /// evening slice of a day grid is ISPs 69 to 76.
    ///
    /// # Errors
    /// [`Error::IspRange`] unless `isps` is a non-empty range within `1..=count`.
    pub fn slice(&self, isps: RangeInclusive<u32>) -> Result<Grid, Error> {
        let (first, last) = (*isps.start(), *isps.end());
        let refuse = || Error::IspRange {
            first,
            last,
            count: self.count,
        };
        let (Some(from), Some(_)) = (self.index(first), self.index(last)) else {
            return Err(refuse());
        };
        if last < first {
            return Err(refuse());
        }
        let start = self.offset(from).ok_or_else(refuse)?;
        let mut grid = Grid::new(start, self.isp, last - first + 1, self.zone.clone())?;
        grid.first = first;
        Ok(grid)
    }

    /// A grid numbered from `first`, as a [slice](Grid::slice) of a larger one would be: for a
    /// grid read back from its canonical text.
    pub(crate) fn numbered(
        start: Timestamp,
        isp: IspDuration,
        count: u32,
        first: u32,
        zone: TimeZone,
    ) -> Result<Grid, Error> {
        if count == 0 {
            return Err(Error::GridSize { count: 0 });
        }
        if first == 0
            || first
                .checked_add(count - 1)
                .is_none_or(|last| last > MAX_ISPS)
        {
            return Err(Error::IspRange {
                first,
                last: first.saturating_add(count.saturating_sub(1)),
                count: MAX_ISPS,
            });
        }
        let mut grid = Grid::new(start, isp, count, zone)?;
        grid.first = first;
        Ok(grid)
    }

    /// The number of the first ISP: 1, or where a [slice](Grid::slice) starts.
    #[must_use]
    pub fn first(&self) -> u32 {
        self.first
    }

    /// The numbers of the ISPs, first to last.
    #[must_use]
    pub fn numbers(&self) -> RangeInclusive<u32> {
        // first + count - 1 fits: a slice lies inside a grid numbered from 1.
        self.first..=self.first.saturating_add(self.count - 1)
    }

    /// The position of ISP `isp` from 0, or `None` if it is not on this grid.
    pub(crate) fn index(&self, isp: u32) -> Option<u32> {
        isp.checked_sub(self.first).filter(|&i| i < self.count)
    }

    /// The same ISPs, labelled in `zone`.
    #[must_use]
    pub fn with_zone(mut self, zone: TimeZone) -> Grid {
        self.zone = zone;
        self
    }

    /// The zone the grid is labelled in and local times are read in.
    #[must_use]
    pub fn zone(&self) -> &TimeZone {
        &self.zone
    }

    /// The start of ISP 1.
    #[must_use]
    pub fn start(&self) -> Timestamp {
        self.start
    }

    /// The end of the last ISP.
    #[must_use]
    pub fn end(&self) -> Timestamp {
        // Checked in `new`.
        self.offset(self.count).unwrap_or(self.start)
    }

    /// The ISP duration.
    #[must_use]
    pub fn isp(&self) -> IspDuration {
        self.isp
    }

    /// The number of ISPs.
    #[must_use]
    pub fn count(&self) -> u32 {
        self.count
    }

    /// The local date the grid starts on.
    #[must_use]
    pub fn date(&self) -> Date {
        self.zone.to_datetime(self.start).date()
    }

    /// The half-open interval `[start, end)` of ISP `isp`, or `None` if it is not on the grid.
    #[must_use]
    pub fn interval(&self, isp: u32) -> Option<Window> {
        let i = self.index(isp)?;
        Some(Window {
            from: self.offset(i)?,
            until: self.offset(i + 1)?,
        })
    }

    /// ISP `isp` with its local interval, for people to read; `None` if it is not on the grid.
    #[must_use]
    pub fn label(&self, isp: u32) -> Option<IspLabel> {
        let w = self.interval(isp)?;
        Some(IspLabel {
            isp,
            from: w.from,
            until: w.until,
            offset: self.zone.to_offset(w.from),
        })
    }

    /// `label`, for an ISP the caller took from this grid; falls back to an empty interval at
    /// the start instead of panicking.
    pub(crate) fn label_total(&self, isp: u32) -> IspLabel {
        self.label(isp).unwrap_or(IspLabel {
            isp,
            from: self.start,
            until: self.start,
            offset: self.zone.to_offset(self.start),
        })
    }

    /// The ISP containing `t`, or `None` before the start or at or after the end.
    #[must_use]
    pub fn isp_at(&self, t: Timestamp) -> Option<u32> {
        let since = t.as_nanosecond() - self.start.as_nanosecond();
        if since < 0 {
            return None;
        }
        let index = u32::try_from(since / self.isp.nanos()).ok()?;
        (index < self.count).then_some(self.first + index)
    }

    /// The ISPs that `window` overlaps, even partly; `None` if it overlaps none.
    #[must_use]
    pub fn isps(&self, window: Window) -> Option<RangeInclusive<u32>> {
        if window.until <= self.start || window.from >= self.end() {
            return None;
        }
        let first = self.isp_at(window.from.max(self.start))?;
        let last_instant = window
            .until
            .min(self.end())
            .checked_sub(SignedDuration::from_nanos(1));
        let last = self.isp_at(last_instant.ok()?)?;
        Some(first..=last)
    }

    /// The instant of local wall-clock `time` on the grid's first date, in its zone.
    ///
    /// # Errors
    /// [`Error::LocalTime`] if the clocks skip `time` on that date (spring forward) or show it
    /// twice (fall back): it is refused rather than guessed.
    pub fn local(&self, time: Time) -> Result<Timestamp, Error> {
        self.local_on(self.date(), time)
    }

    /// The window from local `from` to local `until` on the grid's first date; an `until` at
    /// or before `from` is on the next day, so `22:00` to `02:00` crosses midnight.
    ///
    /// ```
    /// use flexibility::jiff::{civil::{date, time}, tz::TimeZone};
    /// use flexibility::{Grid, IspDuration};
    /// let berlin = TimeZone::get("Europe/Berlin")?;
    /// let grid = Grid::day(date(2026, 12, 1), &berlin, IspDuration::FIFTEEN_MINUTES)?;
    /// let evening = grid.window(time(17, 0, 0, 0), time(19, 0, 0, 0))?;
    /// assert_eq!(grid.isps(evening), Some(69..=76));
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Errors
    /// [`Error::LocalTime`] for a skipped or repeated local time; [`Error::Day`] if the next
    /// date does not exist.
    pub fn window(&self, from: Time, until: Time) -> Result<Window, Error> {
        let date = self.date();
        let start = self.local_on(date, from)?;
        let end_date = if until <= from {
            date.tomorrow().map_err(|_| Error::Day {
                date,
                zone: zone_name(&self.zone),
                reason: "the next day does not exist",
            })?
        } else {
            date
        };
        let end = self.local_on(end_date, until)?;
        Window::new(start, end)
    }

    fn local_on(&self, date: Date, time: Time) -> Result<Timestamp, Error> {
        let refuse = |reason| Error::LocalTime {
            date,
            time,
            zone: zone_name(&self.zone),
            reason,
        };
        let ambiguous = self.zone.to_ambiguous_timestamp(date.to_datetime(time));
        match ambiguous.offset() {
            AmbiguousOffset::Unambiguous { .. } => ambiguous
                .unambiguous()
                .map_err(|_| refuse("outside the representable range")),
            AmbiguousOffset::Gap { .. } => Err(refuse("skipped: the clocks jump over it")),
            AmbiguousOffset::Fold { .. } => Err(refuse("ambiguous: the clocks show it twice")),
        }
    }

    fn offset(&self, isps: u32) -> Option<Timestamp> {
        let nanos = i128::from(isps) * self.isp.nanos();
        let nanos = i64::try_from(nanos).ok()?;
        self.start
            .checked_add(SignedDuration::from_nanos(nanos))
            .ok()
    }
}

pub(crate) fn zone_name(zone: &TimeZone) -> String {
    zone.iana_name().unwrap_or("unnamed").to_owned()
}

impl fmt::Display for Grid {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.first == 1 {
            write!(f, "{} ISPs", self.count)?;
        } else {
            write!(f, "ISPs {}–{}", self.first, self.first + (self.count - 1))?;
        }
        write!(
            f,
            " of {} from {} ({})",
            self.isp,
            self.start,
            zone_name(&self.zone)
        )
    }
}

/// An ISP number with its interval and the local UTC offset at its start: what a person reads.
///
/// Displays as `ISP 69 (17:00–17:15 +01:00)`. On the repeated hour of a fall-back day the
/// offset tells the two 02:00 ISPs apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IspLabel {
    isp: u32,
    from: Timestamp,
    until: Timestamp,
    offset: Offset,
}

impl IspLabel {
    /// The ISP number, from 1.
    #[must_use]
    pub fn isp(self) -> u32 {
        self.isp
    }

    /// The ISP's interval.
    #[must_use]
    pub fn window(self) -> Window {
        Window {
            from: self.from,
            until: self.until,
        }
    }
}

impl fmt::Display for IspLabel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let from = self.offset.to_datetime(self.from);
        let until = self.offset.to_datetime(self.until);
        let seconds = self.offset.seconds();
        let sign = if seconds < 0 { '-' } else { '+' };
        let s = seconds.unsigned_abs();
        write!(
            f,
            "ISP {} ({:02}:{:02}–{:02}:{:02} {sign}{:02}:{:02})",
            self.isp,
            from.hour(),
            from.minute(),
            until.hour(),
            until.minute(),
            s / 3_600,
            (s % 3_600) / 60
        )
    }
}