Skip to main content

frequenz_microgrid_component_graph/graph/
formulas.rs

1// License: MIT
2// Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3
4//! Methods for building formulas for various microgrid metrics.
5
6use std::collections::BTreeSet;
7
8use crate::ComponentGraph;
9use crate::Edge;
10use crate::Error;
11use crate::Node;
12use crate::component_category::CategoryPredicates;
13
14mod expr;
15mod fallback;
16mod formula;
17mod generators;
18mod traversal;
19
20use expr::Expr;
21pub use formula::Formula;
22
23/// Formulas for various microgrid metrics.
24impl<N, E> ComponentGraph<N, E>
25where
26    N: Node,
27    E: Edge,
28{
29    /// Returns the consumer formula for the graph.
30    ///
31    /// The result is not clamped, so it can be negative, for example when
32    /// unmodeled production is larger than the consumption. With
33    /// `include_phantom_loads_in_consumer_formula`, each of its terms is
34    /// clamped at zero instead.
35    pub fn consumer_formula(&self) -> Result<Formula, Error> {
36        generators::consumer::ConsumerFormulaBuilder::try_new(self)?.build()
37    }
38
39    /// Returns the grid formula for the graph.
40    pub fn grid_formula(&self) -> Result<Formula, Error> {
41        generators::grid::GridFormulaBuilder::try_new(self)?.build()
42    }
43
44    /// Returns the producer formula for the graph.
45    ///
46    /// The result is not clamped: a producer that draws power adds a positive
47    /// value, so the total can be positive.
48    pub fn producer_formula(&self) -> Result<Formula, Error> {
49        generators::producer::ProducerFormulaBuilder::try_new(self)?.build()
50    }
51
52    /// Returns the battery formula with the given battery IDs.
53    ///
54    /// If `battery_ids` is `None`, the formula will contain all batteries in
55    /// the graph.
56    pub fn battery_formula(&self, battery_ids: Option<BTreeSet<u64>>) -> Result<Formula, Error> {
57        generators::battery::BatteryFormulaBuilder::try_new(self, battery_ids)?.build()
58    }
59
60    /// Returns the CHP formula for the graph.
61    pub fn chp_formula(&self, chp_ids: Option<BTreeSet<u64>>) -> Result<Formula, Error> {
62        generators::category::category_formula(
63            self,
64            chp_ids,
65            |node| node.is_chp(),
66            "a CHP",
67            self.config.prefer_meters_in_chp_formula(),
68        )
69    }
70
71    /// Returns the PV formula for the graph.
72    pub fn pv_formula(&self, pv_inverter_ids: Option<BTreeSet<u64>>) -> Result<Formula, Error> {
73        generators::category::category_formula(
74            self,
75            pv_inverter_ids,
76            |node| node.is_pv_inverter(),
77            "a PV inverter",
78            self.config.prefer_meters_in_pv_formula(),
79        )
80    }
81
82    /// Returns the wind_turbine formula for the graph.
83    pub fn wind_turbine_formula(
84        &self,
85        wind_turbine_ids: Option<BTreeSet<u64>>,
86    ) -> Result<Formula, Error> {
87        generators::category::category_formula(
88            self,
89            wind_turbine_ids,
90            |node| node.is_wind_turbine(),
91            "a wind turbine",
92            self.config.prefer_meters_in_wind_turbine_formula(),
93        )
94    }
95
96    /// Returns the EV charger formula for the graph.
97    pub fn ev_charger_formula(
98        &self,
99        ev_charger_ids: Option<BTreeSet<u64>>,
100    ) -> Result<Formula, Error> {
101        generators::category::category_formula(
102            self,
103            ev_charger_ids,
104            |node| node.is_ev_charger(),
105            "an EV charger",
106            self.config.prefer_meters_in_ev_charger_formula(),
107        )
108    }
109
110    /// Returns the formula for a specific component by its ID.
111    ///
112    /// A component that provides no telemetry has no reading to emit, so its
113    /// formula is `None`.
114    ///
115    /// Returns an error when `component_id` is not in the graph.
116    pub fn component_formula(&self, component_id: u64) -> Result<Formula, Error> {
117        if !self.component(component_id)?.provides_telemetry() {
118            return Ok(Expr::None.into());
119        }
120        Ok(Expr::component(component_id).into())
121    }
122
123    /// Returns the grid coalesce formula for the graph.
124    ///
125    /// This formula is used for non-aggregating metrics like AC voltage or
126    /// frequency.
127    ///
128    /// The formula is a `COALESCE` expression that includes all meters,
129    /// PV inverters, and battery inverters that are directly connected to the
130    /// grid.
131    ///
132    /// A component that provides no telemetry is skipped. When no component
133    /// provides telemetry, the formula is `None`.
134    pub fn grid_coalesce_formula(&self) -> Result<Formula, Error> {
135        generators::grid_coalesce::GridCoalesceFormulaBuilder::try_new(self)?.build()
136    }
137
138    /// Returns the battery AC coalesce formula for the given components.
139    ///
140    /// This formula is used for non-aggregating metrics like AC voltage or
141    /// frequency.
142    ///
143    /// The formula is a `COALESCE` expression that includes all the specified
144    /// battery meters and corresponding inverters.
145    ///
146    /// When the `battery_ids` parameter is `None`, it will include all the
147    /// battery meters and inverters in the graph.
148    ///
149    /// A component that provides no telemetry is skipped. When no component
150    /// provides telemetry, the formula is `None`.
151    pub fn battery_ac_coalesce_formula(
152        &self,
153        battery_ids: Option<BTreeSet<u64>>,
154    ) -> Result<Formula, Error> {
155        generators::battery_ac_coalesce::BatteryAcCoalesceFormulaBuilder::try_new(
156            self,
157            battery_ids,
158        )?
159        .build()
160    }
161
162    /// Returns the PV AC coalesce formula for the given components.
163    ///
164    /// This formula is used for non-aggregating metrics like AC voltage or
165    /// frequency.
166    ///
167    /// The formula is a `COALESCE` expression that includes all the specified
168    /// PV meters and corresponding inverters.
169    ///
170    /// When the `pv_inverter_ids` parameter is `None`, it will include all the
171    /// PV meters and inverters in the graph.
172    ///
173    /// A component that provides no telemetry is skipped. When no component
174    /// provides telemetry, the formula is `None`.
175    pub fn pv_ac_coalesce_formula(
176        &self,
177        pv_inverter_ids: Option<BTreeSet<u64>>,
178    ) -> Result<Formula, Error> {
179        generators::pv_ac_coalesce::PVAcCoalesceFormulaBuilder::try_new(self, pv_inverter_ids)?
180            .build()
181    }
182
183    /// Returns the AC coalesce formula for a specific component by its ID.
184    ///
185    /// A component that provides no telemetry has no reading to emit, so its
186    /// formula is `None`.
187    ///
188    /// Returns an error when `component_id` is not in the graph.
189    pub fn component_ac_coalesce_formula(&self, component_id: u64) -> Result<Formula, Error> {
190        if !self.component(component_id)?.provides_telemetry() {
191            return Ok(Expr::None.into());
192        }
193        Ok(Expr::component(component_id).into())
194    }
195
196    /// Returns the steam boiler formula for the graph.
197    pub fn steam_boiler_formula(
198        &self,
199        steam_boiler_ids: Option<BTreeSet<u64>>,
200    ) -> Result<Formula, Error> {
201        generators::category::category_formula(
202            self,
203            steam_boiler_ids,
204            |node| node.is_steam_boiler(),
205            "a steam boiler",
206            self.config.prefer_meters_in_steam_boiler_formula(),
207        )
208    }
209}
210
211#[cfg(test)]
212mod tests {
213    use crate::{
214        ComponentCategory, Error, InverterType, OperationalMode,
215        graph::test_utils::ComponentGraphBuilder,
216    };
217
218    /// `component_formula` and `component_ac_coalesce_formula` return the bare
219    /// reading of the requested component — no meter fallback, even when the
220    /// component sits behind a meter the category formulas would drill into.
221    #[test]
222    fn test_component_formula() -> Result<(), Error> {
223        let mut builder = ComponentGraphBuilder::new();
224        let grid = builder.grid();
225        let meter = builder.meter();
226        let inverter = builder.battery_inverter();
227        let battery = builder.battery();
228        builder.connect(grid, meter);
229        builder.connect(meter, inverter);
230        builder.connect(inverter, battery);
231
232        let graph = builder.build(None)?;
233        let inv = inverter.component_id();
234
235        assert_eq!(graph.component_formula(inv)?.to_string(), format!("#{inv}"));
236        assert_eq!(
237            graph.component_ac_coalesce_formula(inv)?.to_string(),
238            format!("#{inv}")
239        );
240        Ok(())
241    }
242
243    /// A component that provides no telemetry has no reading, so both formula
244    /// variants are `None`.
245    #[test]
246    fn test_component_formula_no_telemetry() -> Result<(), Error> {
247        let mut builder = ComponentGraphBuilder::new();
248        let grid = builder.grid();
249        let meter = builder.meter();
250        let inverter = builder.add_component_with_mode(
251            ComponentCategory::Inverter(InverterType::Battery),
252            OperationalMode::ControlOnly,
253        );
254        let battery = builder.battery();
255        builder.connect(grid, meter);
256        builder.connect(meter, inverter);
257        builder.connect(inverter, battery);
258
259        let graph = builder.build(None)?;
260        let inv = inverter.component_id();
261
262        assert_eq!(graph.component_formula(inv)?.to_string(), "None");
263        assert_eq!(
264            graph.component_ac_coalesce_formula(inv)?.to_string(),
265            "None"
266        );
267        Ok(())
268    }
269
270    /// The no-telemetry check has no category test, so a meter with no
271    /// telemetry gets `None` like any other component. The meter here is not
272    /// the grid meter, whose term is already null for its own reason.
273    ///
274    /// Topology (ids): `Grid:0 → Meter:1 → Meter:2 (no telemetry) → PV:3`.
275    #[test]
276    fn test_component_formula_no_telemetry_meter() -> Result<(), Error> {
277        let mut builder = ComponentGraphBuilder::new();
278        let grid = builder.grid();
279        let grid_meter = builder.meter();
280        let silent_meter =
281            builder.add_component_with_mode(ComponentCategory::Meter, OperationalMode::Inactive);
282        let pv = builder.solar_inverter();
283        builder.connect(grid, grid_meter);
284        builder.connect(grid_meter, silent_meter);
285        builder.connect(silent_meter, pv);
286
287        let graph = builder.build(None)?;
288        let id = silent_meter.component_id();
289
290        assert_eq!(graph.component_formula(id)?.to_string(), "None");
291        assert_eq!(graph.component_ac_coalesce_formula(id)?.to_string(), "None");
292        Ok(())
293    }
294
295    /// Both component formula variants check the given id and return an error
296    /// when it is not in the graph.
297    #[test]
298    fn test_component_formula_unknown_id() -> Result<(), Error> {
299        let mut builder = ComponentGraphBuilder::new();
300        let grid = builder.grid();
301        let meter = builder.meter();
302        builder.connect(grid, meter);
303        let graph = builder.build(None)?;
304
305        assert!(
306            graph
307                .component_formula(99)
308                .is_err_and(|e| e == Error::component_not_found("Component with id 99 not found."))
309        );
310        assert!(
311            graph
312                .component_ac_coalesce_formula(99)
313                .is_err_and(|e| e == Error::component_not_found("Component with id 99 not found."))
314        );
315        Ok(())
316    }
317}