metering

Allocation

The UTILTS Berechnungsformel, the § 42b community allocation, § 42c Energy Sharing eligibility, and charging sessions placed on the settlement grid.

The Berechnungsformel

A Marktlokation that is not one Messlokation is computed by a formula the Netzbetreiber transmits (UTILTS AHB 1.1, MIG 1.1e, PID 25001). allocation::formula::Formula is that vocabulary and its evaluator; parsing the message is the EDIFACT layer's job. Each Rechenschritt is one of:

StepOperatorsValue per interval
SumZ69 Addition / Z70 SubtraktionΣ ±operand
Quotientone Z81 Dividend, one Z80 Divisordividend ÷ divisor, cut toward zero to FORMULA_QUOTIENT_DP
ProductZ82 FaktorΠ operand
Positiveone Z83 Positivwertmax(0, step)

An operand is another step or a Messlokation, whose Z87 Energieflussrichtung selects the register (never a sign) and whose loss and split factors apply first. A zero divisor gives 0 for that interval, reported — BDEW AWH Beispiele von Berechnungsformeln für das Solarpaket 1: "Ist die Energiemenge einer Marktlokation zugeordneten Messlokation = 0, so ist auch der Verbrauch der Marktlokation auf 0 zu setzen." Formula::new refuses a missing or self-referencing step, a cycle, an empty step, and an unreferenced step.

use metering::allocation::formula::{Formula, SplitFactor};
use metering::{DayBoundary, Direction, MeloId, MeterInterval, QualityFlag, Resolution, Series};
use jiff::Timestamp;
use metering::dec;

let plant: MeloId = "DE0001234567890000000000000000001".parse().unwrap();
let tenant: MeloId = "DE0001234567890000000000000000002".parse().unwrap();
let noon: Timestamp = "2026-06-01T12:00Z".parse()?;
let one = |kwh| {
    let iv = MeterInterval::quarter_hour(noon, kwh, QualityFlag::Measured).unwrap();
    Series::new(Resolution::QUARTER_HOUR, DayBoundary::Strom, vec![iv]).unwrap()
};
let (generation, consumption) = (one(dec!(100)), one(dec!(20)));

// AWH Beispiel 1: MaLo Verbrauch = Pos(MeLo2 Verbrauch − 10 % MeLo1 Erzeugung).
let formula = Formula::constant_share(tenant, plant, SplitFactor::new(dec!(0.1)).unwrap()).unwrap();
let out = formula
    .eval(|melo, direction| match (*melo == plant, direction) {
        (true, Direction::Export) => Some(&generation),
        (false, Direction::Import) => Some(&consumption),
        _ => None,
    })
    .unwrap();
assert_eq!(out.series.as_slice()[0].value(), dec!(10.0));
# Ok::<(), Box<dyn std::error::Error>>(())

§ 42b — Gemeinschaftliche Gebäudeversorgung

Supply the requested electricity window, plant export, and each participant’s import in kWh to community::allocate. Bind each profile to its contracted MeLo and direction before calling. Use one recorded agreement covering the whole window.

The allocator checks every elapsed quarter in [from, to). A Berlin clock-change day has 92 or 100 quarters. A measured zero and a billable Ersatzwert both count. Matching gaps, hourly profiles, and faulty or unknown values refuse the allocation. AllocationError::Unavailable identifies the plant or participant and the earliest failing instant. Ties select the plant first, then the lowest participant ID. Observations outside the requested window do not enter the result.

Agreement keyNominal share
ConstantGeneration times the agreed factor (UTILTS ZG6, AWH example 1)
ProportionalGeneration weighted by positive consumption (AWH example 3)
EqualSharesEqual weights (§ 42b Abs. 5 Satz 3 EnWG)
CascadingRe-offer unused energy according to the contracted weights

For proportional and equal keys, choose where to truncate to six places toward zero. ShareRounding::Fraction cuts the fraction before multiplying by the pool, as in the Berechnungsformel. ShareRounding::Quantity cuts the nominal kWh. Each participant’s consumption caps its credit. Any uncredited generation remains in the residual. The constant key multiplies by its agreed factor exactly, with no cut; a cascading key truncates each quantity it offers.

allocate returns an Allocation, which you index like its rows. It also records the window and the rounding it was computed under, and holds exact totals over the window: per participant (consumption, allocated, net_grid_draw) and for the plant (generation, pool, allocated, residual). A month is settled in one call; sum nothing yourself. A total that a Decimal cannot hold refuses with AllocationError::TotalOverflow naming the plant or the participant. It is never rounded to fit. With serde, an Allocation stores its window, rounding and rows, and reading it back recomputes the totals.

use metering::allocation::community::{AllocationKey, ShareRounding, allocate};
use metering::{DayBoundary, MeloId, MeterInterval, QualityFlag, Resolution, Series};
use metering::dec;

let window = ("2026-06-01T12:00Z".parse()?, "2026-06-01T12:15Z".parse()?);
let one = |kwh| {
    let iv = MeterInterval::quarter_hour(window.0, kwh, QualityFlag::Measured)?;
    Ok::<_, Box<dyn std::error::Error>>(Series::new(Resolution::QUARTER_HOUR, DayBoundary::Strom, vec![iv])?)
};
let plant = one(dec!(10))?;
let imports = [one(dec!(4))?, one(dec!(4))?, one(dec!(4))?];
let ids: [MeloId; 3] = [
    "DE0001234567890000000000000000001".parse()?,
    "DE0001234567890000000000000000002".parse()?,
    "DE0001234567890000000000000000003".parse()?,
];
let participants: Vec<_> = ids.into_iter().zip(&imports).collect();
let out = allocate(window, &plant, &participants, &AllocationKey::EqualShares, ShareRounding::Quantity)?;
let row = &out[0];
assert_eq!(row.shares[0].allocated, dec!(3.333333));
assert_eq!(row.residual, dec!(0.000001));
assert_eq!(row.allocated() + row.residual, row.pool());

let tenant = out.participant(&ids[0]).unwrap();       // the window, for one invoice
assert_eq!((tenant.allocated, tenant.net_grid_draw), (dec!(3.333333), dec!(0.666667)));
assert_eq!(out.rounding(), ShareRounding::Quantity);   // the evidence names its policy
# Ok::<(), Box<dyn std::error::Error>>(())

§ 42c — Energy Sharing eligibility

Abs. 1 admits a point only when consumption and generation are measured by "Zählerstandsgangmessung nach § 2 Satz 1 Nummer 27 des Messstellenbetriebsgesetzes oder durch eine viertelstündliche registrierende Leistungsmessung" — so an RLM meter qualifies, and an iMSys not configured for Zählerstandsgangmessung does not. Dates are under Regulatory basis.

QuestionFunctionFrom
Can the point produce quarter-hour values?assess_capability (refuses contradictory input)master data
Is it producing them?assess_delivery (billable quarter-hours against the window's real length)the observed series
Bothcombine_readiness → SharingReadiness—

Capable but not delivering is a configuration order, not a rollout. No Aufteilungsschlüssel is published for § 42c; the keys above are arithmetic.

Sessions on the grid

split_session places register readings over a span (a Charge Detail Record, a device log) on the grid; merge_sessions adds sessions on one grid. Σ slot energy = last reading − first reading, exactly. A slot bracketed by readings is Measured; one split pro rata is Estimated. Slots come from DayBoundary::bucket, so the autumn's repeated hour is there.

use metering::allocation::session::{MeterSample, SessionSplitConfig, split_session};
use metering::QualityFlag;
use metering::dec;

// Meter start 12:07, clock-aligned values at 12:15 and 12:30, stop 12:37.
let samples = [
    MeterSample::new("2026-06-01T12:07Z".parse()?, dec!(998)),
    MeterSample::new("2026-06-01T12:15Z".parse()?, dec!(1000)),
    MeterSample::new("2026-06-01T12:30Z".parse()?, dec!(1006)),
    MeterSample::new("2026-06-01T12:37Z".parse()?, dec!(1008)),
];
let series = split_session(&samples, &SessionSplitConfig::quarter_hourly()).unwrap();
assert_eq!(series.as_slice()[1].value(), dec!(6));
assert!(series.iter().all(|s| s.quality() == QualityFlag::Measured));
assert_eq!(series.billable_total(), Some(dec!(10)));
# Ok::<(), Box<dyn std::error::Error>>(())