flexibility 0.4.0

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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! OpenADR 3 capacity limits and usage reports, behind the `openadr` feature.
//!
//! - [`limits`] (at the VEN): an event's `IMPORT_CAPACITY_LIMIT` and `EXPORT_CAPACITY_LIMIT`
//!   intervals as [`Limit`]s, a consumption cap and a feed-in cap, each over its interval's own
//!   window. Applied to an [`Envelope`](crate::Envelope), an interval that covers part of an ISP
//!   constrains the whole ISP, the strict reading.
//! - [`event`] (at the VTN): the inverse, caps as the event to publish, which [`limits`] reads
//!   back unchanged.
//! - [`usage`]: a report resource's `USAGE` readings (energy per interval) as average power
//!   per ISP.
//!
//! The `openadr` crate's `IntervalExpander` places the intervals in time: inherited periods,
//! subdivided payloads, an event's `duration` looping and truncating. A value's unit comes
//! from the event's payload descriptor, or its programme's (User Guide ยง7.6), and is required:
//! *"meaning is indicated by units in associated eventPayloadDescriptor"* (the payload
//! definitions), so there is no default, and this crate does not guess. Limits are `KW`, usage
//! `KWH`; both are exact decimals, so a limit must be whole watts, and usage is rounded only as
//! named.
//!
//! ```
//! use flexibility::openadr::{self, wire::model::{EventRequest, ObjectId}};
//! use flexibility::{Envelope, Grid, IspDuration, Limit, Provenance, Window, w};
//! # use flexibility::jiff::{Timestamp, tz::TimeZone};
//! # let start: Timestamp = "2026-12-01T16:00:00Z".parse()?;
//! let grid = Grid::new(start, IspDuration::FIFTEEN_MINUTES, 8, TimeZone::UTC)?;
//! let fms = Provenance::new("fms.example", "site-7", start);
//!
//! // The VTN publishes 250.001 kW for the first hour: exact, no float on the way.
//! let hour = Window::new(start, "2026-12-01T17:00:00Z".parse()?)?;
//! let cap = Limit::consumption_cap(hour, w!(250_001), fms.clone());
//! let json = serde_json::to_string(&openadr::event(ObjectId::new("site-caps")?, &[cap.clone()])?)?;
//! assert!(json.contains(r#""values":[250.001]"#) && json.contains(r#""duration":"PT1H""#));
//!
//! // The VEN reads it back as the same cap and keeps its plan within it.
//! let received: EventRequest = serde_json::from_str(&json)?;
//! let horizon = Window::new(grid.start(), grid.end())?;
//! let caps = openadr::limits(&received, None, horizon, start, &fms)?;
//! assert_eq!(caps, [cap]);
//! let envelope = Envelope::unbounded(grid).apply(&caps[0])?;
//! assert_eq!(envelope.bounds(3).unwrap().max(), Some(w!(250_001)));
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use jiff::{SignedDuration, Timestamp};

use crate::power::div_round;
use crate::{Error, Grid, Limit, Power, Provenance, Rounding, Series, Window};

/// The `openadr` crate this feature maps to.
pub use ::openadr as wire;

use wire::core::{ExpandedInterval, IntervalExpander};
use wire::model::{
    Decimal, Duration, EventPayloadDescriptor, EventRequest, Interval, IntervalPeriod, ObjectId,
    PayloadType, Program, ReportRequest, StartTime, Unit, Value, ValuesMap,
};

const PROTOCOL: &str = "OpenADR";
const IMPORT: &str = "IMPORT_CAPACITY_LIMIT";
const EXPORT: &str = "EXPORT_CAPACITY_LIMIT";
const USAGE: &str = "USAGE";

fn refuse(field: &'static str, value: &impl ToString, reason: &'static str) -> Error {
    Error::Unrepresentable {
        protocol: PROTOCOL,
        field,
        value: value.to_string(),
        reason,
    }
}

fn to_wire(t: Timestamp) -> wire::model::Timestamp {
    t.into()
}

fn from_wire(t: wire::model::Timestamp) -> Timestamp {
    t.into()
}

fn expanded(e: &impl ToString) -> Error {
    refuse("intervals", e, "cannot be placed in time")
}

/// The one value of a payload, as `(mantissa, scale)` and its text: a number, or refused.
fn decimal(field: &'static str, values: &[Value]) -> Result<((i128, u32), String), Error> {
    match values {
        [v] => v
            .as_decimal()
            .map(|d| ((d.mantissa(), d.scale()), d.to_string()))
            .ok_or_else(|| refuse(field, &format!("{v:?}"), "is not a number")),
        _ => Err(refuse(
            field,
            &format!("{} values", values.len()),
            "has not exactly one value",
        )),
    }
}

/// `mantissa ยท 10^-scale ยท factor / divisor` as watts, rounded as named.
fn scaled(
    field: &'static str,
    (mantissa, scale): (i128, u32),
    factor: i128,
    divisor: i128,
    rounding: Rounding,
) -> Result<Power, Error> {
    let too_big = || refuse(field, &mantissa, "is outside the range of watts");
    let n = mantissa.checked_mul(factor).ok_or_else(too_big)?;
    let d = 10_i128
        .checked_pow(scale)
        .and_then(|p| p.checked_mul(divisor))
        .ok_or_else(too_big)?;
    let w = div_round(n, d, rounding)?;
    i64::try_from(w)
        .map(Power::from_watts)
        .map_err(|_| too_big())
}

/// The unit of `payload`: the event's own descriptor, whole, else its programme's default
/// [UG ยง7.6]; a programme with another id contributes nothing.
fn unit_of<'a>(
    event: &'a EventRequest,
    program: Option<&'a Program>,
    payload: &str,
) -> Option<&'a Unit> {
    event
        .payload_descriptor(payload)
        .or_else(|| {
            program
                .filter(|p| p.id == event.program_id)
                .and_then(|p| p.content.event_payload_descriptor(payload))
        })
        .and_then(|d| d.units.as_ref())
}

/// The capacity limits `event` sets within `window`, its units from its payload descriptors or,
/// where it has none for a type, from `program`'s (the programme it belongs to): one [`Limit`] per interval with an
/// `IMPORT_CAPACITY_LIMIT` (a consumption cap) or an `EXPORT_CAPACITY_LIMIT` (a feed-in cap).
/// `received` is the instant `StartTime::Now` (`0001-01-01`) means. An open-ended interval
/// lasts until `window` ends; an interval with `randomizeStart` is held until its end plus the
/// randomization, the latest any VEN may still apply it. Other payload types (prices,
/// subscriptions, reservations) are not limits and are left alone.
///
/// # Errors
/// [`Error::Unrepresentable`] for a limit without `KW` units in the event's payload
/// descriptor, a value that is not one non-negative whole number of watts, two limits of one
/// type in an interval, a negative `randomizeStart`, or intervals the expander cannot place; [`Error::EmptyWindow`] for a zero-length interval.
pub fn limits(
    event: &EventRequest,
    program: Option<&Program>,
    window: Window,
    received: Timestamp,
    provenance: &Provenance,
) -> Result<Vec<Limit>, Error> {
    let expander = IntervalExpander::at(to_wire(received));
    let intervals = expander
        .expand_window(event, to_wire(window.from()), to_wire(window.until()))
        .map_err(|e| expanded(&e))?;
    let mut out = Vec::new();
    for interval in &intervals {
        for payload in [IMPORT, EXPORT] {
            let Some(values) = only(&interval.payloads, payload)? else {
                continue;
            };
            if unit_of(event, program, payload) != Some(&Unit::Kw) {
                return Err(refuse(
                    "units",
                    &format!("{payload}: {:?}", unit_of(event, program, payload)),
                    "is not KW; OpenADR names no default unit",
                ));
            }
            let (value, text) = decimal(payload, &values.values)?;
            let power = scaled(payload, value, 1_000, 1, Rounding::Exact).map_err(|e| match e {
                Error::Inexact { .. } => {
                    refuse(payload, &text, "kW is not a whole number of watts")
                }
                other => other,
            })?;
            if power < Power::ZERO {
                return Err(refuse(
                    payload,
                    &power,
                    "is negative; a capacity limit is a magnitude",
                ));
            }
            let span = span(interval, window)?;
            out.push(if payload == IMPORT {
                Limit::consumption_cap(span, power, provenance.clone())
            } else {
                Limit::feed_in_cap(span, power, provenance.clone())?
            });
        }
    }
    Ok(out)
}

/// The event that carries `limits` to a VEN, in programme `program`: each consumption cap an
/// `IMPORT_CAPACITY_LIMIT`, each feed-in cap an `EXPORT_CAPACITY_LIMIT` of its magnitude, in exact
/// `KW` with a `KW` descriptor, one interval per limit in the order given. Caps that follow one
/// another without a gap, all of one length, share the event's period; others carry their own.
/// [`limits`] over a window holding them, with their provenance, gives `limits` back, also
/// through JSON. Targets, name, priority and report descriptors are the caller's to set.
///
/// # Errors
/// [`Error::Unrepresentable`] for no limits, a limit that is not one consumption or feed-in cap
/// of at least 0 W (a band, a floor), a fraction of a kW at 10ยนโต W or more (more digits than a
/// JSON number is sure to carry, which the `openadr` crate would refuse to send), or a window
/// OpenADR's duration cannot hold.
pub fn event(program: ObjectId, limits: &[Limit]) -> Result<EventRequest, Error> {
    let (first, rest) = limits.split_first().ok_or_else(|| {
        refuse(
            "intervals",
            &"0 limits",
            "is empty; an event carries limits",
        )
    })?;
    let length = |l: &Limit| l.window().from().duration_until(l.window().until());
    let shared = rest.iter().zip(limits).all(|(next, prev)| {
        next.window().from() == prev.window().until() && length(next) == length(first)
    });
    let period = |l: &Limit| -> Result<IntervalPeriod, Error> {
        let w = l.window();
        let duration = Duration::try_from(length(l))
            .map_err(|_| refuse("duration", &w, "does not fit an OpenADR duration"))?;
        Ok(IntervalPeriod::new(
            StartTime::At(to_wire(w.from())),
            duration,
        ))
    };
    let mut types = Vec::new();
    let mut intervals = Vec::with_capacity(limits.len());
    for (id, limit) in limits.iter().enumerate() {
        let b = limit.bounds();
        let (payload, watts) = match (b.min(), b.max()) {
            (None, Some(max)) if max >= Power::ZERO => (IMPORT, max),
            (Some(min), None) if min <= Power::ZERO => (EXPORT, min.checked_neg()?),
            _ => {
                return Err(refuse(
                    "bounds",
                    &b,
                    "is not one consumption or feed-in cap of at least 0 W, all OpenADR's capacity limits carry",
                ));
            }
        };
        let value = kw(payload, watts)?;
        let id = i32::try_from(id).map_err(|_| {
            refuse(
                "intervals",
                &limits.len(),
                "is more than an interval id counts",
            )
        })?;
        let mut interval = Interval::new(id, vec![ValuesMap::single(kind(payload)?, value)]);
        if !shared {
            interval = interval.with_period(period(limit)?);
        }
        intervals.push(interval);
        if !types.contains(&payload) {
            types.push(payload);
        }
    }
    let descriptors = types
        .into_iter()
        .map(|t| Ok(EventPayloadDescriptor::new(kind(t)?).with_units(Unit::Kw)))
        .collect::<Result<_, Error>>()?;
    let event = EventRequest::new(program)
        .with_intervals(intervals)
        .with_payload_descriptors(descriptors);
    Ok(if shared {
        event.with_interval_period(period(first)?)
    } else {
        event
    })
}

fn kind(name: &'static str) -> Result<PayloadType, Error> {
    name.parse()
        .map_err(|_| refuse("type", &name, "is not an OpenADR payload type"))
}

/// `watts` as kW: an integer when whole, else three decimals. Below 10ยนโต W that is at most
/// fifteen significant digits, which a JSON number (binary64) always carries exactly.
fn kw(payload: &'static str, watts: Power) -> Result<Value, Error> {
    let w = watts.watts();
    if w % 1_000 == 0 {
        return Ok(Value::Integer(w / 1_000));
    }
    if w >= 1_000_000_000_000_000 {
        return Err(refuse(
            payload,
            &watts,
            "has a fraction of a kW beyond the fifteen digits OpenADR's JSON carries exactly",
        ));
    }
    Ok(Value::Number(Decimal::new(w, 3)))
}

/// The one payload of type `name` in an interval, if any; two of the same type are refused
/// rather than one of them silently read.
fn only<'a>(
    payloads: &'a [wire::model::ValuesMap],
    name: &'static str,
) -> Result<Option<&'a wire::model::ValuesMap>, Error> {
    let mut found = payloads.iter().filter(|p| p.value_type.as_str() == name);
    let first = found.next();
    if found.next().is_some() {
        return Err(refuse(
            name,
            &"two payloads",
            "appears twice in one interval",
        ));
    }
    Ok(first)
}

/// The window an interval holds: its start until its end (or `window`'s end), plus any
/// start randomization.
fn span(interval: &ExpandedInterval, window: Window) -> Result<Window, Error> {
    let from = from_wire(interval.start);
    let mut until = match interval.end {
        Some(end) => from_wire(end),
        None => window.until(),
    };
    if let Some(r) = &interval.randomize_start {
        let nanos = r
            .as_nanos()
            .ok_or_else(|| refuse("randomizeStart", &r, "is not a fixed length"))?;
        if nanos < 0 {
            return Err(refuse(
                "randomizeStart",
                &r,
                "is negative; a start is only delayed",
            ));
        }
        until = i64::try_from(nanos)
            .ok()
            .and_then(|n| until.checked_add(SignedDuration::from_nanos(n)).ok())
            .ok_or_else(|| refuse("randomizeStart", &r, "ends outside the time range"))?;
    }
    Window::new(from, until)
}

/// The average power per ISP of `grid` from the `USAGE` readings of resource `resource` in
/// `report`: energy per interval (`KWH`) รท the ISP length, rounded as named. `event` places
/// readings that carry only the event's interval ids. Every interval must be exactly one ISP
/// of `grid`, and every ISP must have one reading: a missing quarter is refused, not invented.
/// `USAGE` is consumed energy, so the power is never negative.
///
/// # Errors
/// [`Error::Unrepresentable`] for a missing or repeated resource, `USAGE` without `KWH` units, a
/// reading that is not one non-negative number or appears twice in one interval, an interval that is not one ISP of `grid`, an ISP read twice or
/// not at all, or intervals the expander cannot place; [`Error::Inexact`] for a fraction of a
/// watt under [`Rounding::Exact`].
pub fn usage(
    report: &ReportRequest,
    resource: &str,
    event: Option<&EventRequest>,
    grid: &Grid,
    rounding: Rounding,
) -> Result<Series<Power>, Error> {
    let units = report
        .payload_descriptor(USAGE)
        .and_then(|d| d.units.as_ref());
    if units != Some(&Unit::Kwh) {
        return Err(refuse(
            "units",
            &format!("{USAGE}: {units:?}"),
            "is not KWH; OpenADR names no default unit",
        ));
    }
    let mut named = report
        .resources
        .iter()
        .filter(|r| r.resource_name.as_str() == resource);
    let r = named
        .next()
        .ok_or_else(|| refuse("resourceName", &resource, "is not in the report"))?;
    if named.next().is_some() {
        return Err(refuse(
            "resourceName",
            &resource,
            "appears twice in the report",
        ));
    }
    // A reading has a time of its own: a start of "now" lands outside every grid.
    let expander = IntervalExpander::at(wire::model::Timestamp::MIN);
    let readings = expander.expand_report(r, event).map_err(|e| expanded(&e))?;
    let seconds = i128::from(grid.isp().minutes()) * 60;
    let mut values: Vec<Option<Power>> = vec![None; grid.count() as usize];
    for reading in &readings {
        let Some(payload) = only(&reading.payloads, USAGE)? else {
            continue;
        };
        let from = from_wire(reading.start);
        let Some(until) = reading.end.map(from_wire) else {
            return Err(refuse(
                "intervalPeriod",
                &from,
                "has no end; a reading is one ISP",
            ));
        };
        let isp = grid
            .isps(Window::new(from, until)?)
            .filter(|r| r.start() == r.end())
            .map(|r| *r.start())
            .filter(|&isp| {
                grid.interval(isp)
                    .is_some_and(|w| w.from() == from && w.until() == until)
            })
            .ok_or_else(|| {
                refuse(
                    "intervalPeriod",
                    &from,
                    "is not exactly one ISP of the grid",
                )
            })?;
        let (value, text) = decimal(USAGE, &payload.values)?;
        if value.0 < 0 {
            return Err(refuse(
                USAGE,
                &text,
                "is negative; USAGE is consumed energy",
            ));
        }
        let power = scaled(USAGE, value, 3_600_000, seconds, rounding)?;
        let slot = &mut values[(isp - grid.first()) as usize];
        if slot.replace(power).is_some() {
            return Err(refuse("intervalPeriod", &from, "is read twice"));
        }
    }
    let values = grid
        .numbers()
        .zip(values)
        .map(|(isp, v)| {
            v.ok_or_else(|| {
                let label = grid
                    .label(isp)
                    .map_or_else(|| isp.to_string(), |l| l.to_string());
                refuse("intervals", &label, "has no USAGE reading")
            })
        })
        .collect::<Result<Vec<_>, Error>>()?;
    Series::new(grid.clone(), values)
}