flexibility 0.1.2

Grid flexibility as exact, replayable arithmetic: limits, baselines, UFTP-exact settlement, and UFTP, EEBUS, S2, OpenADR, CSIP-AUS, IEC 104, CLS.EEDI 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
//! The one error type of the crate.

use std::fmt;

use jiff::Timestamp;
use jiff::civil::{Date, Time};

use crate::baseline::MethodId;
use crate::grid::{Grid, IspLabel};
use crate::power::{Deviation, Energy, Power};
use crate::shape::Provenance;

/// Why an operation refused. Every variant names the values involved;
/// [`Display`](fmt::Display) renders it as one line, and [`Error::hint`] suggests a remedy
/// where there is one.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// Arithmetic left the representable range.
    Overflow {
        /// `power`, `deviation` or `energy`.
        quantity: &'static str,
        /// The operation, such as `+` or `negate`.
        operation: &'static str,
        /// The left operand, or the only one.
        left: i128,
        /// The right operand, if any.
        right: Option<i128>,
    },
    /// A magnitude larger than the largest representable power.
    PowerOutOfRange {
        /// The magnitude in watts.
        watts: u64,
    },
    /// An amount that must not be negative was.
    NegativeAmount {
        /// The amount given.
        power: Power,
    },
    /// Power text that is not an exact power with a unit.
    ParsePower {
        /// The text, or its length if it was too long to keep.
        text: String,
        /// Why.
        reason: &'static str,
    },
    /// A division with [`Rounding::Exact`](crate::Rounding::Exact) left a remainder.
    Inexact {
        /// The numerator.
        numerator: i128,
        /// The denominator.
        denominator: i128,
    },
    /// An ISP duration that does not divide a day into whole ISPs.
    IspDuration {
        /// The duration in minutes.
        minutes: u16,
    },
    /// A grid with no ISPs or more than [`MAX_ISPS`](crate::MAX_ISPS).
    GridSize {
        /// The requested number of ISPs.
        count: u64,
    },
    /// A grid whose end lies outside the representable time range.
    TimeRange {
        /// The grid's start.
        start: Timestamp,
        /// The requested number of ISPs.
        count: u32,
    },
    /// A date that has no day grid in the zone.
    Day {
        /// The date.
        date: Date,
        /// The zone's name, or `unnamed`.
        zone: String,
        /// Why.
        reason: &'static str,
    },
    /// A local wall-clock time that is skipped or repeated on its date, or out of range.
    LocalTime {
        /// The date.
        date: Date,
        /// The local time.
        time: Time,
        /// The zone's name, or `unnamed`.
        zone: String,
        /// Why.
        reason: &'static str,
    },
    /// Two values on different grids.
    GridMismatch {
        /// The left operand's grid.
        left: Grid,
        /// The right operand's grid.
        right: Grid,
    },
    /// A series with a different number of values than its grid has ISPs.
    SeriesLength {
        /// The grid's ISP count.
        expected: u32,
        /// The number of values given.
        actual: usize,
    },
    /// A minimum above the maximum.
    InvertedBounds {
        /// The minimum.
        min: Power,
        /// The maximum.
        max: Power,
    },
    /// A device id that is empty, longer than 64 characters or contains a control character.
    DeviceId {
        /// The id, escaped and shortened.
        id: String,
        /// Why.
        reason: &'static str,
    },
    /// A received canonical text that is not a settlement this crate would write: not exactly
    /// canonical, another profile, or lines that break the settlement rule.
    Receipt {
        /// Where in the text: `lines[2].deficiency`; empty for the text as a whole.
        path: String,
        /// Why, with received text escaped and shortened.
        reason: String,
    },
    /// A level whose minimum is above its maximum.
    InvertedLevel {
        /// The minimum.
        min: Energy,
        /// The maximum.
        max: Energy,
    },
    /// Level bounds that together allow no level after an ISP.
    EmptyLevel {
        /// The ISP the boundary ends.
        after: IspLabel,
        /// The combined minimum.
        min: Energy,
        /// The combined maximum.
        max: Energy,
    },
    /// A level that must always hold, which the initial level already breaks.
    InitialLevel {
        /// The initial level.
        initial: Energy,
        /// The level that must always hold.
        level: crate::Level,
    },
    /// An instant that is not a boundary between ISPs of the grid.
    NotABoundary {
        /// The instant.
        at: Timestamp,
        /// The grid.
        grid: Grid,
    },
    /// A deviation band whose minimum is above its maximum.
    InvertedBand {
        /// The minimum.
        min: Deviation,
        /// The maximum.
        max: Deviation,
    },
    /// Two values that must agree do not, such as an order's day and its settlement's.
    Mismatch {
        /// What differs.
        field: &'static str,
        /// Our value.
        ours: String,
        /// Theirs.
        theirs: String,
    },
    /// A protocol value this crate cannot hold, or a message it cannot read without guessing.
    Unrepresentable {
        /// The protocol.
        protocol: &'static str,
        /// The field.
        field: &'static str,
        /// The value, as written.
        value: String,
        /// Why.
        reason: &'static str,
    },
    /// A window whose end is not after its start.
    EmptyWindow {
        /// The window's start.
        from: Timestamp,
        /// The window's end.
        until: Timestamp,
    },
    /// A combination that leaves an ISP with no allowed power.
    EmptyRange {
        /// The first ISP without allowed power.
        isp: IspLabel,
        /// The combined minimum.
        min: Power,
        /// The combined maximum.
        max: Power,
    },
    /// A limit that would allow less than a guarantee in force.
    GuaranteeBreached(Box<Breach>),
    /// A baseline method refused its inputs or parameters.
    Method {
        /// The method.
        method: MethodId,
        /// Why, naming the values involved.
        reason: String,
    },
    /// An operation that needs data got none.
    NoData {
        /// What was missing.
        what: &'static str,
    },
    /// Text that is not `sha256:` and 64 hex digits.
    ParseDigest {
        /// The text, cut to 80 characters.
        text: String,
    },
    /// Text that is not a known method id.
    ParseMethod {
        /// The text, cut to 80 characters.
        text: String,
    },
    /// ISPs outside a grid.
    IspRange {
        /// The first ISP asked for.
        first: u32,
        /// The last ISP asked for.
        last: u32,
        /// The grid's ISP count.
        count: u32,
    },
}

/// Where and how a limit breaks a guarantee.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Breach {
    /// The first ISP the guarantee is broken in.
    pub isp: IspLabel,
    /// The bound the limit sets there.
    pub bound: Power,
    /// The power the guarantee says must stay allowed.
    pub guaranteed: Power,
    /// Who set the limit.
    pub limit: Provenance,
    /// Who set the guarantee.
    pub guarantee: Provenance,
}

impl Error {
    /// A one-line remedy, where the crate knows one.
    ///
    /// ```
    /// use flexibility::Power;
    /// let err = "4.0001 kW".parse::<Power>().unwrap_err();
    /// assert_eq!(err.hint(), Some("power is whole watts: at most three decimals in kW and six in MW"));
    /// ```
    #[must_use]
    pub fn hint(&self) -> Option<&'static str> {
        Some(match self {
            Error::ParsePower { reason, .. } if reason.starts_with("not a whole") => {
                "power is whole watts: at most three decimals in kW and six in MW"
            }
            Error::ParsePower { .. } => "write a number and a unit: 500 W, 4.2 kW, -3 kW, 1.5 MW",
            Error::Inexact { .. } => {
                "name a rounding (Rounding::HalfAwayFromZero) if the contract allows one"
            }
            Error::IspDuration { .. } => {
                "use a length that divides a day: 1, 5, 15, 30 or 60 minutes"
            }
            Error::GridMismatch { .. } => {
                "build both values on the same grid: Grid::day with the same date, zone and ISP duration"
            }
            Error::SeriesLength { .. } => {
                "give one value per ISP; a DST day has 92 or 100 quarter hours"
            }
            Error::LocalTime { .. } => {
                "on a DST day, state the window as instants with Window::new instead of local times"
            }
            Error::EmptyRange { .. } => {
                "two limits contradict each other: one party has to relax its bound for this ISP"
            }
            Error::GuaranteeBreached(_) => {
                "the cap cuts below a guaranteed minimum: raise the cap to the guarantee"
            }
            Error::Mismatch {
                field: "BaselineReference",
                ..
            } => "settle with the method the order names, or agree a new order",
            Error::Mismatch { .. } => {
                "settle the order on its own day and ISP length: uftp::ordered gives that grid"
            }
            Error::Receipt { .. } => {
                "pass the text exactly as received; a re-encoded or edited copy has another digest"
            }
            Error::InitialLevel { .. } => {
                "start from the level the store holds now, within its capacity"
            }
            Error::NotABoundary { .. } => {
                "levels are checked between ISPs: use Grid::local on a quarter hour, or the end of an ISP's Window"
            }
            Error::ParseDigest { .. } => {
                "a digest is `sha256:` and 64 hex digits; prefix a bare sha256sum output with `sha256:`"
            }
            Error::Unrepresentable {
                protocol: "canon@1",
                ..
            } => {
                "a canonical integer stays within ±2^53 (MAX_EXACT); settle a smaller window or pool"
            }
            Error::NegativeAmount { .. } => {
                "give the amount as a positive power; the direction is in the name"
            }
            _ => return None,
        })
    }
}

impl fmt::Display for Error {
    #[allow(clippy::too_many_lines)] // one arm per variant
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Overflow {
                quantity,
                operation,
                left,
                right: Some(right),
            } => write!(f, "{quantity} overflow: {left} {operation} {right}"),
            Self::Overflow {
                quantity,
                operation,
                left,
                ..
            } => write!(f, "{quantity} overflow: {operation} {left}"),
            Self::PowerOutOfRange { watts } => {
                write!(f, "power of {watts} W is larger than {} W", i64::MAX)
            }
            Self::NegativeAmount { power } => write!(f, "amount {power} must not be negative"),
            Self::ParsePower { text, reason } => write!(f, "power `{text}`: {reason}"),
            Self::Inexact {
                numerator,
                denominator,
            } => write!(f, "{numerator} / {denominator} is not exact"),
            Self::IspDuration { minutes } => write!(
                f,
                "an ISP of {minutes} min does not divide a day into whole ISPs"
            ),
            Self::GridSize { count } => write!(
                f,
                "a grid of {count} ISPs is outside 1..={}",
                crate::MAX_ISPS
            ),
            Self::TimeRange { start, count } => write!(
                f,
                "a grid of {count} ISPs from {start} ends outside the representable time range"
            ),
            Self::Day { date, zone, reason } => write!(f, "{date} in {zone}: {reason}"),
            Self::LocalTime {
                date,
                time,
                zone,
                reason,
            } => write!(f, "{date} {time} in {zone} is {reason}"),
            Self::GridMismatch { left, right } => write!(f, "grids differ: {left} and {right}"),
            Self::SeriesLength { expected, actual } => write!(
                f,
                "a series needs {expected} values, one per ISP, but has {actual}"
            ),
            Self::InvertedBounds { min, max } => {
                write!(f, "minimum {min} is above maximum {max}")
            }
            Self::DeviceId { id, reason } => write!(f, "device id {id} {reason}"),
            Self::Receipt { path, reason } if path.is_empty() => write!(f, "receipt: {reason}"),
            Self::Receipt { path, reason } => write!(f, "receipt at `{path}`: {reason}"),
            Self::InvertedLevel { min, max } => {
                write!(f, "minimum level {min} is above maximum {max}")
            }
            Self::EmptyLevel { after, min, max } => write!(
                f,
                "after {after} no level is allowed: minimum {min} is above maximum {max}"
            ),
            Self::InitialLevel { initial, level } => write!(
                f,
                "the initial level {initial} is already outside {level}, which must always hold"
            ),
            Self::NotABoundary { at, grid } => {
                write!(f, "{at} is not a boundary between ISPs of {grid}")
            }
            Self::InvertedBand { min, max } => {
                write!(f, "minimum deviation {min} is above maximum {max}")
            }
            Self::Mismatch {
                field,
                ours,
                theirs,
            } => write!(f, "{field} differs: ours {ours}, theirs {theirs}"),
            Self::Unrepresentable {
                protocol,
                field,
                value,
                reason,
            } => write!(f, "{protocol} {field} `{value}`: {reason}"),
            Self::EmptyWindow { from, until } => {
                write!(f, "window {from} to {until} is empty")
            }
            Self::EmptyRange { isp, min, max } => write!(
                f,
                "{isp} allows no power: minimum {min} is above maximum {max}"
            ),
            Self::Method { method, reason } => write!(f, "{method}: {reason}"),
            Self::NoData { what } => write!(f, "no data: {what}"),
            Self::ParseDigest { text } => {
                write!(f, "digest `{text}` is not `sha256:` and 64 hex digits")
            }
            Self::ParseMethod { text } => write!(f, "`{text}` is not a known method id"),
            Self::IspRange { first, last, count } => {
                write!(f, "ISPs {first} to {last} are not all within 1..={count}")
            }
            Self::GuaranteeBreached(b) => write!(
                f,
                "{}: bound {} ({}) breaks the guarantee of {} ({})",
                b.isp, b.bound, b.limit, b.guaranteed, b.guarantee
            ),
        }
    }
}

impl std::error::Error for Error {}