surge-io 0.1.7

Surge I/O — Parser/writer for MATPOWER, PSS/E RAW, IEEE CDF, XIIDM, UCTE, and JSON case formats
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
// SPDX-License-Identifier: LicenseRef-PolyForm-Noncommercial-1.0.0
//! CGMES Operational Limits (OL) full hierarchy parser.
//!
//! Parses the complete IEC 61970-302 OperationalLimits package:
//! - **OperationalLimitSet** — container attached to a Terminal or Equipment
//! - **OperationalLimitType** — duration (PATL/TATL/IATL) and direction
//! - **ActivePowerLimit** — MW limits
//! - **ApparentPowerLimit** — MVA limits
//! - **CurrentLimit** — Ampere limits (converted to MVA via base_kv)
//! - **VoltageLimit** — kV limits
//!
//! The resulting `OperationalLimits` structure is stored on `Network.cim.operational_limits`
//! alongside the existing `rate_a/rate_b/rate_c` and `vmin/vmax` fields which remain
//! the primary solver inputs.

use std::collections::HashMap;

use surge_network::Network;
use surge_network::network::op_limits::{
    LimitDirection, LimitDuration, LimitKind, OperationalLimit, OperationalLimitSet,
};

use super::indices::CgmesIndices;
use super::types::{CimObj, ObjMap};

/// Build the full operational limits model from parsed CGMES objects.
///
/// This is called after `CgmesIndices::build()` and after buses/branches have been
/// assigned internal bus numbers, so Terminal → bus resolution is available.
pub(crate) fn build_operational_limits(
    objects: &ObjMap,
    idx: &CgmesIndices,
    network: &mut Network,
) {
    // -----------------------------------------------------------------------
    // Pass 1: Collect OperationalLimitType → (duration, direction, mrid)
    // -----------------------------------------------------------------------
    let olt_map: HashMap<&str, (LimitDuration, LimitDirection)> = objects
        .iter()
        .filter(|(_, o)| o.class == "OperationalLimitType")
        .map(|(id, o)| {
            let duration = parse_duration(o);
            let direction = parse_direction(o);
            (id.as_str(), (duration, direction))
        })
        .collect();

    // -----------------------------------------------------------------------
    // Pass 2: Collect OperationalLimitSet → (terminal_id, equipment_mrid, name)
    // -----------------------------------------------------------------------
    struct OlsInfo {
        name: String,
        terminal_id: Option<String>,
        equipment_mrid: Option<String>,
    }

    let mut ols_map: HashMap<&str, OlsInfo> = HashMap::new();

    for (ols_id, o) in objects
        .iter()
        .filter(|(_, o)| o.class == "OperationalLimitSet")
    {
        let name = o.get_text("name").unwrap_or_default().to_string();

        let (terminal_id, equipment_mrid) = if let Some(term_id) = o.get_ref("Terminal") {
            let eq_mrid = objects
                .get(term_id)
                .and_then(|t| t.get_ref("ConductingEquipment"))
                .map(|s| s.to_string());
            (Some(term_id.to_string()), eq_mrid)
        } else if let Some(eq_id) = o.get_ref("Equipment") {
            (None, Some(eq_id.to_string()))
        } else {
            (None, None)
        };

        ols_map.insert(
            ols_id.as_str(),
            OlsInfo {
                name,
                terminal_id,
                equipment_mrid,
            },
        );
    }

    // -----------------------------------------------------------------------
    // Pass 3: Collect all limit values and attach to their sets
    // -----------------------------------------------------------------------
    // Accumulate limits per OLS mRID
    let mut limits_by_ols: HashMap<&str, Vec<(LimitKind, OperationalLimit)>> = HashMap::new();

    // 3a. ApparentPowerLimit
    for (_, obj) in objects
        .iter()
        .filter(|(_, o)| o.class == "ApparentPowerLimit")
    {
        if let Some((ols_id, limit)) = parse_limit_value(obj, LimitKind::ApparentPower, &olt_map) {
            limits_by_ols
                .entry(ols_id)
                .or_default()
                .push((LimitKind::ApparentPower, limit));
        }
    }

    // 3b. ActivePowerLimit
    for (_, obj) in objects
        .iter()
        .filter(|(_, o)| o.class == "ActivePowerLimit")
    {
        if let Some((ols_id, limit)) = parse_limit_value(obj, LimitKind::ActivePower, &olt_map) {
            limits_by_ols
                .entry(ols_id)
                .or_default()
                .push((LimitKind::ActivePower, limit));
        }
    }

    // 3c. CurrentLimit — stored in Amps (raw); conversion to MVA is caller's job
    for (_, obj) in objects.iter().filter(|(_, o)| o.class == "CurrentLimit") {
        if let Some((ols_id, limit)) = parse_limit_value(obj, LimitKind::Current, &olt_map) {
            limits_by_ols
                .entry(ols_id)
                .or_default()
                .push((LimitKind::Current, limit));
        }
    }

    // 3d. VoltageLimit
    for (_, obj) in objects.iter().filter(|(_, o)| o.class == "VoltageLimit") {
        if let Some((ols_id, limit)) = parse_limit_value(obj, LimitKind::Voltage, &olt_map) {
            limits_by_ols
                .entry(ols_id)
                .or_default()
                .push((LimitKind::Voltage, limit));
        }
    }

    // -----------------------------------------------------------------------
    // Pass 4: Resolve Terminal → bus number, build OperationalLimitSet structs
    // -----------------------------------------------------------------------
    let eq_terminals = &idx.eq_terminals;

    for (ols_id, info) in &ols_map {
        let limits = match limits_by_ols.remove(ols_id) {
            Some(v) if !v.is_empty() => v,
            _ => continue, // skip sets with no limits
        };

        // Resolve bus number from terminal
        let bus = info
            .terminal_id
            .as_deref()
            .and_then(|tid| {
                let term = objects.get(tid)?;
                let tn_id = term.get_ref("TopologicalNode")?;
                idx.tn_bus(tn_id)
            })
            .unwrap_or(0);

        // Determine from_end: terminal sequence number 1 = from, 2 = to
        let from_end = info.terminal_id.as_deref().and_then(|tid| {
            let eq_mrid = info.equipment_mrid.as_deref()?;
            let terms = eq_terminals.get(eq_mrid)?;
            if terms.len() >= 2 {
                let pos = terms.iter().position(|t| t == tid)?;
                Some(pos == 0)
            } else {
                None
            }
        });

        let ols = OperationalLimitSet {
            mrid: ols_id.to_string(),
            name: info.name.clone(),
            bus,
            equipment_mrid: info.equipment_mrid.clone(),
            from_end,
            limits,
        };

        network
            .cim
            .operational_limits
            .limit_sets
            .insert(ols_id.to_string(), ols);
    }

    if !network.cim.operational_limits.is_empty() {
        tracing::info!(
            limit_sets = network.cim.operational_limits.limit_sets.len(),
            total_limits = network.cim.operational_limits.total_limit_count(),
            "Operational limits parsed from CGMES"
        );
    }
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/// Parse the duration category from an `OperationalLimitType` object.
fn parse_duration(obj: &CimObj) -> LimitDuration {
    // Check isInfiniteDuration flag
    if let Some(s) = obj.get_text("isInfiniteDuration")
        && s.eq_ignore_ascii_case("true")
    {
        return LimitDuration::Permanent;
    }

    // Check acceptableDuration
    if let Some(dur) = obj.parse_f64("acceptableDuration") {
        if dur <= 0.0 || dur < 1.0 {
            return LimitDuration::Instantaneous;
        }
        if dur >= 1e9 {
            return LimitDuration::Permanent;
        }
        return LimitDuration::Temporary(dur);
    }

    // Check limitType for PATL/TATL/IATL keywords
    let lt = obj
        .get_ref("limitType")
        .or_else(|| obj.get_text("limitType"))
        .map(|s| s.to_lowercase())
        .unwrap_or_default();

    if lt.contains("patl") || lt.contains("permanent") || lt.contains("normal") {
        return LimitDuration::Permanent;
    }
    if lt.contains("iatl") || lt.contains("instantaneous") {
        return LimitDuration::Instantaneous;
    }
    if lt.contains("tatl") || lt.contains("temporary") || lt.contains("emergency") {
        // No specific duration available, use 900s (15 min) as default TATL
        return LimitDuration::Temporary(900.0);
    }

    // Default: treat as permanent (PATL)
    LimitDuration::Permanent
}

/// Parse the direction from an `OperationalLimitType` object.
fn parse_direction(obj: &CimObj) -> LimitDirection {
    let dir = obj
        .get_ref("direction")
        .map(|r| r.rsplit(['#', '.']).next().unwrap_or(r).to_lowercase())
        .unwrap_or_default();

    // Also check limitType for voltage direction hints
    let lt = obj
        .get_ref("limitType")
        .or_else(|| obj.get_text("limitType"))
        .map(|s| s.to_lowercase())
        .unwrap_or_default();

    if dir.contains("high") || lt.contains("high") {
        LimitDirection::High
    } else if dir.contains("low") || lt.contains("low") {
        LimitDirection::Low
    } else {
        LimitDirection::AbsoluteValue
    }
}

/// Parse a single limit value object and return (ols_mrid, OperationalLimit).
fn parse_limit_value<'a>(
    obj: &'a CimObj,
    _kind: LimitKind,
    olt_map: &HashMap<&str, (LimitDuration, LimitDirection)>,
) -> Option<(&'a str, OperationalLimit)> {
    let ols_id = obj.get_ref("OperationalLimitSet")?;
    let value = obj
        .parse_f64("value")
        .filter(|v| v.is_finite() && *v > 0.0)?;

    let (duration, direction, limit_type_mrid) =
        if let Some(olt_id) = obj.get_ref("OperationalLimitType") {
            let (dur, dir) = olt_map
                .get(olt_id)
                .copied()
                .unwrap_or((LimitDuration::Permanent, LimitDirection::AbsoluteValue));
            (dur, dir, Some(olt_id.to_string()))
        } else {
            (
                LimitDuration::Permanent,
                LimitDirection::AbsoluteValue,
                None,
            )
        };

    Some((
        ols_id,
        OperationalLimit {
            value,
            duration,
            direction,
            limit_type_mrid,
        },
    ))
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cgmes::types::{CimObj, CimVal};

    /// Helper: create a minimal CIM object with the given class and attributes.
    fn cim_obj(class: &str, attrs: &[(&str, CimVal)]) -> CimObj {
        let mut o = CimObj::new(class);
        for (k, v) in attrs {
            o.attrs.insert(k.to_string(), v.clone());
        }
        o
    }

    fn text(s: &str) -> CimVal {
        CimVal::Text(s.to_string())
    }

    fn reference(s: &str) -> CimVal {
        CimVal::Ref(s.to_string())
    }

    #[test]
    fn test_parse_duration_patl() {
        let obj = cim_obj(
            "OperationalLimitType",
            &[("isInfiniteDuration", text("true"))],
        );
        assert_eq!(parse_duration(&obj), LimitDuration::Permanent);
    }

    #[test]
    fn test_parse_duration_tatl_with_seconds() {
        let obj = cim_obj(
            "OperationalLimitType",
            &[("acceptableDuration", text("1200"))],
        );
        assert_eq!(parse_duration(&obj), LimitDuration::Temporary(1200.0));
    }

    #[test]
    fn test_parse_duration_iatl() {
        let obj = cim_obj("OperationalLimitType", &[("acceptableDuration", text("0"))]);
        assert_eq!(parse_duration(&obj), LimitDuration::Instantaneous);
    }

    #[test]
    fn test_parse_duration_from_limit_type_keyword() {
        let obj = cim_obj(
            "OperationalLimitType",
            &[("limitType", reference("http://example.com#patl"))],
        );
        assert_eq!(parse_duration(&obj), LimitDuration::Permanent);

        let obj2 = cim_obj(
            "OperationalLimitType",
            &[("limitType", reference("http://example.com#tatl"))],
        );
        assert_eq!(parse_duration(&obj2), LimitDuration::Temporary(900.0));
    }

    #[test]
    fn test_parse_direction() {
        let high = cim_obj(
            "OperationalLimitType",
            &[("direction", reference("http://iec.ch#high"))],
        );
        assert_eq!(parse_direction(&high), LimitDirection::High);

        let low = cim_obj(
            "OperationalLimitType",
            &[("direction", reference("http://iec.ch#low"))],
        );
        assert_eq!(parse_direction(&low), LimitDirection::Low);

        let abs = cim_obj(
            "OperationalLimitType",
            &[("direction", reference("http://iec.ch#absoluteValue"))],
        );
        assert_eq!(parse_direction(&abs), LimitDirection::AbsoluteValue);
    }

    #[test]
    fn test_parse_limit_value_apparent_power() {
        let olt_map: HashMap<&str, (LimitDuration, LimitDirection)> = HashMap::from([(
            "olt1",
            (LimitDuration::Permanent, LimitDirection::AbsoluteValue),
        )]);

        let obj = cim_obj(
            "ApparentPowerLimit",
            &[
                ("OperationalLimitSet", reference("ols1")),
                ("OperationalLimitType", reference("olt1")),
                ("value", text("500.0")),
            ],
        );

        let (ols_id, limit) = parse_limit_value(&obj, LimitKind::ApparentPower, &olt_map).unwrap();
        assert_eq!(ols_id, "ols1");
        assert!((limit.value - 500.0).abs() < 1e-9);
        assert_eq!(limit.duration, LimitDuration::Permanent);
        assert_eq!(limit.direction, LimitDirection::AbsoluteValue);
        assert_eq!(limit.limit_type_mrid.as_deref(), Some("olt1"));
    }

    #[test]
    fn test_parse_limit_value_missing_set_returns_none() {
        let olt_map: HashMap<&str, (LimitDuration, LimitDirection)> = HashMap::new();
        let obj = cim_obj("ActivePowerLimit", &[("value", text("100.0"))]);
        assert!(parse_limit_value(&obj, LimitKind::ActivePower, &olt_map).is_none());
    }

    #[test]
    fn test_operational_limits_accessors() {
        let mut ol = surge_network::network::op_limits::OperationalLimits::default();
        assert!(ol.is_empty());
        assert_eq!(ol.total_limit_count(), 0);

        ol.limit_sets.insert(
            "set1".to_string(),
            surge_network::network::op_limits::OperationalLimitSet {
                mrid: "set1".to_string(),
                name: "Set 1".to_string(),
                bus: 1,
                equipment_mrid: Some("eq1".to_string()),
                from_end: Some(true),
                limits: vec![
                    (
                        LimitKind::ApparentPower,
                        OperationalLimit {
                            value: 500.0,
                            duration: LimitDuration::Permanent,
                            direction: LimitDirection::AbsoluteValue,
                            limit_type_mrid: None,
                        },
                    ),
                    (
                        LimitKind::ApparentPower,
                        OperationalLimit {
                            value: 600.0,
                            duration: LimitDuration::Temporary(900.0),
                            direction: LimitDirection::AbsoluteValue,
                            limit_type_mrid: None,
                        },
                    ),
                ],
            },
        );

        assert!(!ol.is_empty());
        assert_eq!(ol.total_limit_count(), 2);
        assert_eq!(ol.sets_for_equipment("eq1").count(), 1);
        assert_eq!(ol.sets_for_equipment("eq_other").count(), 0);
        assert_eq!(ol.sets_for_bus(1).count(), 1);
        assert_eq!(ol.sets_for_bus(99).count(), 0);
    }
}