revrt 0.1.3

A library for optimizing transmission infrastructure for electrical grid.
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
466
467
468
469
470
471
472
//! A scenario for routing
//!
//! A `Scenario` encapsulates the cost surface and everything required to
//! define that, such as the input features and the cost function.
//!
//! A typical scenario uses a cost function that weights several
//! features to determine the cost per grid point.
//!
//! Given the relatively high resolution and the desire on routing long
//! distances, the data involved can be relatively large. A major
//! accomplishment of this crate is in this module, by working in chunks
//! with asynchronous I/O we keep the memory footprint low while
//! sustaining high performance as possible.

use std::collections::HashSet;
use std::path::PathBuf;

use tracing::trace;

use super::cost_as_u64;
use crate::routing::features::Features;
use crate::{ArrayIndex, Result};

/// Scenario state required to evaluate routing moves.
///
/// A scenario owns the derived routing dataset together with the feature
/// metadata used to open and validate the underlying store. It provides
/// helpers for neighborhood lookups, retry-aware soft barrier filtering,
/// and reporting information about the active barrier groups.
pub(super) struct Scenario {
    /// Derived dataset containing cost arrays and barrier masks.
    pub dataset: crate::dataset::Dataset,
    #[allow(dead_code)]
    /// Source feature metadata kept alive for scenario lifetime management.
    features: Features,
}

impl Scenario {
    /// Open a scenario backed by a swap dataset.
    ///
    /// # Arguments
    /// `store_path`: Path to the source dataset store.
    /// `cost_function`: Cost function used to derive routing costs and
    ///                  barrier masks.
    /// `cache_size`: Maximum cache size for dataset-backed reads.
    /// `swap_fp`: Filesystem path where the swap dataset should be created.
    ///
    /// # Returns
    /// A `Scenario` whose dataset materializes derived arrays in the swap
    /// location while reusing the source feature definitions.
    pub(super) fn new_with_swap<P: AsRef<std::path::Path>>(
        store_path: P,
        cost_function: crate::cost::CostFunction,
        cache_size: u64,
        swap_fp: PathBuf,
    ) -> Result<Self> {
        trace!("Opening scenario with: {:?}", store_path.as_ref());

        let features = Features::open(&store_path)?;
        let dataset = crate::dataset::Dataset::open_with_swap(
            store_path,
            cost_function,
            cache_size,
            swap_fp,
        )?;

        Ok(Self { dataset, features })
    }

    /// Open a scenario that derives routing data directly from the source.
    ///
    /// # Arguments
    /// `store_path`: Path to the source dataset store.
    /// `cost_function`: Cost function used to derive routing costs and
    ///                  barrier masks.
    /// `cache_size`: Maximum cache size for dataset-backed reads.
    ///
    /// # Returns
    /// A `Scenario` ready to serve neighborhood and barrier queries.
    pub(super) fn new<P: AsRef<std::path::Path>>(
        store_path: P,
        cost_function: crate::cost::CostFunction,
        cache_size: u64,
    ) -> Result<Self> {
        trace!("Opening scenario with: {:?}", store_path.as_ref());

        let features = Features::open(&store_path)?;
        let dataset = crate::dataset::Dataset::open(store_path, cost_function, cache_size)?;

        Ok(Self { dataset, features })
    }

    /// Return retry-aware successor cells for a routing attempt.
    ///
    /// The returned successors exclude non-finite or non-positive costs and
    /// any cells covered by currently active soft barrier groups. If the
    /// starting cell itself is masked by an active soft barrier, no
    /// successors are returned.
    ///
    /// # Arguments
    /// `position`: Current grid position whose neighbors should be explored.
    /// `dropped_soft_groups`: Number of lowest-importance soft barrier
    ///                        groups that should be ignored for this retry.
    ///
    /// # Returns
    /// Neighbor positions and integer-encoded traversal costs suitable for
    /// routing expansion.
    pub(super) fn successors_for_attempt(
        &self,
        position: &ArrayIndex,
        dropped_soft_groups: usize,
    ) -> Vec<(ArrayIndex, u64)> {
        let neighbors = self.dataset.get_3x3(position);
        let soft_barrier_cells: HashSet<_> = self
            .dataset
            .get_3x3_soft_barrier_cells(position, dropped_soft_groups)
            .into_iter()
            .collect();

        if soft_barrier_cells.contains(position) {
            return Vec::new();
        }

        let neighbors = neighbors
            .into_iter()
            .filter(|(p, c)| c.is_finite() && *c > 0.0 && !soft_barrier_cells.contains(p))
            .map(|(p, c)| (p, cost_as_u64(c)))
            .collect();
        trace!("Adjusting neighbors' types: {:?}", neighbors);
        neighbors
    }

    /// Count the configured soft barrier groups.
    ///
    /// # Returns
    /// Number of retry stages available for progressively dropping soft
    /// barrier groups.
    pub(super) fn soft_barrier_group_count(&self) -> usize {
        self.dataset.soft_barrier_groups().len()
    }

    /// List barrier layer names dropped for a retry state.
    ///
    /// # Arguments
    /// `dropped_soft_groups`: Number of soft barrier groups dropped in
    ///                        ascending importance order.
    ///
    /// # Returns
    /// Barrier layer names belonging to the dropped groups.
    pub(super) fn dropped_barrier_layers(&self, dropped_soft_groups: usize) -> Vec<String> {
        let mut dropped_barrier_layers = Vec::new();

        for (__, layers) in self
            .dataset
            .soft_barrier_groups()
            .iter()
            .take(dropped_soft_groups)
        {
            for layer in layers {
                dropped_barrier_layers.push(layer.layer_name().to_string());
            }
        }

        dropped_barrier_layers
    }

    /// Return the scenario grid dimensions.
    ///
    /// # Returns
    /// Tuple of `(rows, cols)` describing the routing grid shape.
    pub(super) fn grid_shape(&self) -> (u64, u64) {
        self.dataset.grid_shape
    }
}

#[cfg(test)]
mod tests {
    use super::Scenario;
    use crate::ArrayIndex;

    #[test]
    fn successors_keep_hard_barriers_after_soft_groups_drop() {
        let store = crate::dataset::samples::ZarrTestBuilder::new()
            .dimensions(1, 3, 3)
            .chunks(1, 3, 3)
            .layer(crate::dataset::samples::LayerConfig::constant("cost", 1.0))
            .layer(crate::dataset::samples::LayerConfig::new(
                "hard_barrier",
                crate::dataset::samples::FillStrategy::Values(vec![
                    0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                ]),
            ))
            .layer(crate::dataset::samples::LayerConfig::new(
                "soft_barrier",
                crate::dataset::samples::FillStrategy::Values(vec![
                    0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                ]),
            ))
            .build()
            .unwrap();
        let cost_function = crate::cost::CostFunction::from_json(
            r#"{
                "cost_layers": [{"layer_name": "cost"}],
                "barrier_layers": [
                    {
                        "layer_name": "hard_barrier",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0
                    },
                    {
                        "layer_name": "soft_barrier",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0,
                        "barrier_importance": 1
                    }
                ],
                "ignore_invalid_costs": false
            }"#,
        )
        .unwrap();
        let scenario = Scenario::new(store.path(), cost_function, 1_000).unwrap();

        let start = ArrayIndex { i: 1, j: 1 };
        let initial_successors = scenario.successors_for_attempt(&start, 0);
        let relaxed_successors = scenario.successors_for_attempt(&start, 1);

        assert!(
            !initial_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 0, j: 1 })
        );
        assert!(
            !initial_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 1, j: 0 })
        );

        assert!(
            !relaxed_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 0, j: 1 })
        );
        assert!(
            relaxed_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 1, j: 0 })
        );
    }

    #[test]
    fn successors_return_empty_when_start_is_hard_barrier() {
        let store = crate::dataset::samples::ZarrTestBuilder::new()
            .dimensions(1, 3, 3)
            .chunks(1, 3, 3)
            .layer(crate::dataset::samples::LayerConfig::constant("cost", 1.0))
            .layer(crate::dataset::samples::LayerConfig::new(
                "hard_barrier",
                crate::dataset::samples::FillStrategy::Values(vec![
                    0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
                ]),
            ))
            .build()
            .unwrap();
        let cost_function = crate::cost::CostFunction::from_json(
            r#"{
                "cost_layers": [{"layer_name": "cost"}],
                "barrier_layers": [
                    {
                        "layer_name": "hard_barrier",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0
                    }
                ],
                "ignore_invalid_costs": false
            }"#,
        )
        .unwrap();
        let scenario = Scenario::new(store.path(), cost_function, 1_000).unwrap();

        let successors = scenario.successors_for_attempt(&ArrayIndex { i: 1, j: 1 }, 0);

        assert!(successors.is_empty());
    }

    #[test]
    fn successors_use_cumulative_soft_masks_by_retry_state() {
        let store = crate::dataset::samples::ZarrTestBuilder::new()
            .dimensions(1, 3, 3)
            .chunks(1, 3, 3)
            .layer(crate::dataset::samples::LayerConfig::constant("cost", 1.0))
            .layer(crate::dataset::samples::LayerConfig::new(
                "soft_barrier_low",
                crate::dataset::samples::FillStrategy::Values(vec![
                    0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                ]),
            ))
            .layer(crate::dataset::samples::LayerConfig::new(
                "soft_barrier_high",
                crate::dataset::samples::FillStrategy::Values(vec![
                    0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                ]),
            ))
            .build()
            .unwrap();
        let cost_function = crate::cost::CostFunction::from_json(
            r#"{
                "cost_layers": [{"layer_name": "cost"}],
                "barrier_layers": [
                    {
                        "layer_name": "soft_barrier_low",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0,
                        "barrier_importance": 1
                    },
                    {
                        "layer_name": "soft_barrier_high",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0,
                        "barrier_importance": 2
                    }
                ],
                "ignore_invalid_costs": false
            }"#,
        )
        .unwrap();
        let scenario = Scenario::new(store.path(), cost_function, 1_000).unwrap();

        let start = ArrayIndex { i: 1, j: 1 };
        let initial_successors = scenario.successors_for_attempt(&start, 0);
        let retry_one_successors = scenario.successors_for_attempt(&start, 1);
        let retry_two_successors = scenario.successors_for_attempt(&start, 2);

        assert_eq!(scenario.soft_barrier_group_count(), 2);
        assert!(
            !initial_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 1, j: 0 })
        );
        assert!(
            !initial_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 0, j: 1 })
        );
        assert!(
            retry_one_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 1, j: 0 })
        );
        assert!(
            !retry_one_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 0, j: 1 })
        );
        assert!(
            retry_two_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 1, j: 0 })
        );
        assert!(
            retry_two_successors
                .iter()
                .any(|(p, _)| *p == ArrayIndex { i: 0, j: 1 })
        );
    }

    #[test]
    fn successors_return_empty_when_start_is_in_active_soft_mask() {
        let store = crate::dataset::samples::ZarrTestBuilder::new()
            .dimensions(1, 3, 3)
            .chunks(1, 3, 3)
            .layer(crate::dataset::samples::LayerConfig::constant("cost", 1.0))
            .layer(crate::dataset::samples::LayerConfig::new(
                "soft_barrier",
                crate::dataset::samples::FillStrategy::Values(vec![
                    0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0,
                ]),
            ))
            .build()
            .unwrap();
        let cost_function = crate::cost::CostFunction::from_json(
            r#"{
                "cost_layers": [{"layer_name": "cost"}],
                "barrier_layers": [
                    {
                        "layer_name": "soft_barrier",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0,
                        "barrier_importance": 1
                    }
                ],
                "ignore_invalid_costs": false
            }"#,
        )
        .unwrap();
        let scenario = Scenario::new(store.path(), cost_function, 1_000).unwrap();

        assert!(
            scenario
                .successors_for_attempt(&ArrayIndex { i: 1, j: 1 }, 0)
                .is_empty()
        );
        assert!(
            !scenario
                .successors_for_attempt(&ArrayIndex { i: 1, j: 1 }, 1)
                .is_empty()
        );
    }

    #[test]
    fn dropped_barrier_layers_follows_soft_barrier_groups() {
        let store = crate::dataset::samples::ZarrTestBuilder::new()
            .dimensions(1, 3, 3)
            .chunks(1, 3, 3)
            .layer(crate::dataset::samples::LayerConfig::constant("cost", 1.0))
            .layer(crate::dataset::samples::LayerConfig::new(
                "soft_barrier_low_a",
                crate::dataset::samples::FillStrategy::Constant(0.0),
            ))
            .layer(crate::dataset::samples::LayerConfig::new(
                "soft_barrier_low_b",
                crate::dataset::samples::FillStrategy::Constant(0.0),
            ))
            .layer(crate::dataset::samples::LayerConfig::new(
                "soft_barrier_high",
                crate::dataset::samples::FillStrategy::Constant(0.0),
            ))
            .build()
            .unwrap();
        let cost_function = crate::cost::CostFunction::from_json(
            r#"{
                "cost_layers": [{"layer_name": "cost"}],
                "barrier_layers": [
                    {
                        "layer_name": "soft_barrier_low_a",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0,
                        "barrier_importance": 1
                    },
                    {
                        "layer_name": "soft_barrier_low_b",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0,
                        "barrier_importance": 1
                    },
                    {
                        "layer_name": "soft_barrier_high",
                        "barrier_operator": "eq",
                        "barrier_threshold": 1.0,
                        "barrier_importance": 2
                    }
                ],
                "ignore_invalid_costs": false
            }"#,
        )
        .unwrap();
        let scenario = Scenario::new(store.path(), cost_function, 1_000).unwrap();

        assert!(scenario.dropped_barrier_layers(0).is_empty());
        assert_eq!(
            scenario.dropped_barrier_layers(1),
            vec!["soft_barrier_low_a", "soft_barrier_low_b"]
        );
        assert_eq!(
            scenario.dropped_barrier_layers(2),
            vec![
                "soft_barrier_low_a",
                "soft_barrier_low_b",
                "soft_barrier_high"
            ]
        );
    }
}