cimoxide-view 0.8.0

A CGMES or NC model set as views: its grid at substation level, laid out, and its objects as a tree, with validation findings on each; and its files as text: where each object is written, and edits across them
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
//! The model decoded from a set of files, brought up to date with an edit of them by decoding again
//! only the objects the edit touched. Decoding RealGrid's 117 MB anew takes some 0.9 s, and an edit
//! in an editor touches a handful of objects.
//!
//! In each file that changed, the elements of its index before and after are compared in document
//! order: those that differ, came or went write the objects touched. Each is removed from the model
//! and decoded again from what every file writes of it (an EQ file's element and an SSH file's),
//! the files in their order, merged as a load merges them: the model is the one a full decode
//! gives.

use std::collections::BTreeSet;

use cimmodel::CimDataset;

use crate::edit::File;
use crate::index::Element;

/// `model`, decoded from the files as they were, brought up to date with `files` as they are now
/// (in the order the model was decoded from them); `before` holds each file that changed as it
/// was, with its index. The number of objects decoded again.
///
/// An error says why the model can't be patched: a file gone or new, an edit of what is written
/// around the objects (the XML declaration, the root element), an object without an mRID, objects
/// of classes no table knows, or a difference model. The model may then be partly changed: decode
/// it anew. A model with difference models applied ([`CimDataset::apply`]) is the caller's to decode
/// anew.
pub fn refresh(model: &mut CimDataset, before: &[File], files: &[File]) -> Result<usize, String> {
    let mut ids: BTreeSet<&str> = BTreeSet::new();
    for old in before {
        let new = files
            .iter()
            .find(|f| f.name == old.name)
            .ok_or_else(|| format!("`{}` is no longer in the set", old.name))?;
        if old.text == new.text {
            continue;
        }
        touched(old, new, &mut ids)?;
    }
    let ids: BTreeSet<String> = ids.into_iter().map(str::to_string).collect();
    refresh_objects(model, &ids, files)
}

/// `model` with the objects `ids` decoded again from `files` as they are now (in the order the
/// model was decoded from them): for an edit that knows the objects it touched, as
/// [`crate::index::Index::edited`] tells. The number of objects. An error as [`refresh`]'s.
pub fn refresh_objects(
    model: &mut CimDataset,
    ids: &BTreeSet<String>,
    files: &[File],
) -> Result<usize, String> {
    if ids.contains("") {
        return Err("an object without an mRID".into());
    }
    for id in ids {
        model.remove(id);
    }
    for file in files {
        let mut spans: Vec<(usize, usize)> = ids
            .iter()
            .flat_map(|id| file.index.of(id))
            .map(|e| span(file, e))
            .collect();
        if spans.is_empty() {
            continue;
        }
        spans.sort_unstable();
        let body: Vec<&str> = spans.iter().map(|&(s, e)| &file.text[s..e]).collect();
        model.merge(decode(file, &body.join("\n"))?);
    }
    Ok(ids.len())
}

/// Where `e` is written in `file`, as byte offsets.
fn span(file: &File, e: &Element) -> (usize, usize) {
    (
        file.lines.offset(file.text, e.full.start),
        file.lines.offset(file.text, e.full.end),
    )
}

/// The objects whose elements differ between `old` and `new`, two states of one file, added to
/// `ids`.
fn touched<'a>(old: &File<'a>, new: &File<'a>, ids: &mut BTreeSet<&'a str>) -> Result<(), String> {
    let (was, is) = (&old.index.elements, &new.index.elements);
    let (Some(first), Some(last)) = (was.first().zip(is.first()), was.last().zip(is.last())) else {
        return Err("a file without objects".into());
    };
    // Around the objects, the file is written as it was.
    let head = (span(old, first.0).0, span(new, first.1).0);
    let tail = (span(old, last.0).1, span(new, last.1).1);
    if old.text[..head.0] != new.text[..head.1] || old.text[tail.0..] != new.text[tail.1..] {
        return Err("an edit around the objects: the XML declaration or the root element".into());
    }
    let text = |f: &File<'a>, e: &Element| {
        let (s, e) = span(f, e);
        &f.text[s..e]
    };
    // Whether the object of `e` is written in `f` at `from` or after.
    let later = |f: &File, e: &Element, from: usize| {
        f.index
            .places_of(&e.mrid)
            .iter()
            .any(|&k| k as usize >= from)
    };
    let mut mark = |e: &'a Element| {
        if e.mrid.is_empty() {
            Err("an object without an mRID".to_string())
        } else {
            ids.insert(e.mrid.as_str());
            Ok(())
        }
    };
    let (mut i, mut j) = (0, 0);
    while i < was.len() && j < is.len() {
        let (a, b) = (&was[i], &is[j]);
        if a.mrid == b.mrid {
            if text(old, a) != text(new, b) {
                mark(b)?;
            }
            i += 1;
            j += 1;
            continue;
        }
        match (later(new, a, j), later(old, b, i)) {
            // `b` came.
            (true, false) => {
                mark(b)?;
                j += 1;
            }
            // `a` went.
            (false, _) => {
                mark(a)?;
                i += 1;
            }
            // Both moved.
            (true, true) => {
                mark(a)?;
                mark(b)?;
                i += 1;
                j += 1;
            }
        }
    }
    was[i..].iter().try_for_each(&mut mark)?;
    is[j..].iter().try_for_each(&mut mark)?;
    Ok(())
}

/// `body`, whole elements of `file`, decoded as a document of its own: with what `file` writes
/// before its objects (the XML declaration, the root's start tag) and after them.
fn decode(file: &File, body: &str) -> Result<CimDataset, String> {
    let text = file.text;
    let head = file
        .index
        .elements
        .first()
        .map_or(0, |e| file.lines.offset(text, e.full.start));
    let tail = text.rfind("</").unwrap_or(text.len());
    let doc = format!("{}{body}\n{}", &text[..head], &text[tail..]);
    let found = CimDataset::decode_str(&doc).map_err(|e| e.to_string())?;
    if !found.foreign.is_empty() {
        return Err("objects of classes no table knows".into());
    }
    if !found.differences.is_empty() {
        return Err("a difference model".into());
    }
    Ok(found)
}

#[cfg(test)]
mod tests {
    use std::collections::{BTreeMap, HashSet};

    use super::*;
    use crate::edit::{self, Edits};
    use crate::grid::{self, Model};
    use crate::index::Index;
    use crate::text::Range;
    use crate::text::{LineIndex, apply};
    use crate::tree;

    fn micro_grid() -> Vec<(String, String)> {
        let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join(
            "../CGMES-Test-Configurations/v3.0/MicroGrid/MicroGid-BaseCase/MicroGrid-BaseCase-Merged",
        );
        let mut names: Vec<_> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|e| e.unwrap().file_name().into_string().unwrap())
            .filter(|n| n.ends_with(".xml"))
            .collect();
        names.sort();
        names
            .into_iter()
            .map(|n| {
                let text = std::fs::read_to_string(dir.join(&n)).unwrap();
                (n, text)
            })
            .collect()
    }

    fn decode_all(texts: &[(String, String)]) -> CimDataset {
        let mut model = CimDataset::default();
        for (_, t) in texts {
            model.merge(CimDataset::decode_str(t).unwrap());
        }
        model
    }

    /// Each object as written: its class, whether only described, its fields sorted; and each
    /// class's objects, sorted.
    fn snapshot(model: &CimDataset) -> (BTreeMap<String, String>, BTreeMap<String, Vec<String>>) {
        let objects = model
            .entries
            .iter()
            .map(|(id, e)| {
                let mut fields: Vec<String> = e
                    .fields()
                    .iter()
                    .map(|(k, v)| format!("{k}={v:?}"))
                    .collect();
                fields.sort();
                let types: Vec<&str> = e.types().map(|t| t.qualified).collect();
                (id.clone(), format!("{types:?} {} {fields:?}", e.defined()))
            })
            .collect();
        let by_type = model
            .by_type
            .iter()
            .filter(|(_, ids)| !ids.is_empty())
            .map(|(t, ids)| {
                let mut ids = ids.clone();
                ids.sort();
                (t.clone(), ids)
            })
            .collect();
        (objects, by_type)
    }

    /// `edit` made of the files `texts`: the model patched, and decoded anew, alike.
    fn patched_as_decoded(
        texts: &[(String, String)],
        edit: impl for<'a> FnOnce(&[File<'a>]) -> Edits<'a>,
    ) -> usize {
        let lines: Vec<LineIndex> = texts.iter().map(|(_, t)| LineIndex::new(t)).collect();
        let indexes: Vec<Index> = texts.iter().map(|(_, t)| Index::build(t)).collect();
        let files: Vec<File> = texts
            .iter()
            .zip(&lines)
            .zip(&indexes)
            .map(|(((n, t), l), i)| File {
                name: n,
                text: t,
                lines: l,
                index: i,
            })
            .collect();
        let edits: Vec<(String, Vec<_>)> = edit(&files)
            .into_iter()
            .map(|(n, e)| (n.to_string(), e))
            .collect();
        assert!(!edits.is_empty(), "the edit changes nothing");
        let after: Vec<(String, String)> = texts
            .iter()
            .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
                Some((_, e)) => (n.clone(), apply(t, e)),
                None => (n.clone(), t.clone()),
            })
            .collect();

        let mut model = decode_all(texts);
        let changed: Vec<&File> = files
            .iter()
            .filter(|f| edits.iter().any(|(n, _)| n == f.name))
            .collect();
        let before: Vec<File> = changed
            .iter()
            .map(|f| File {
                name: f.name,
                text: f.text,
                lines: f.lines,
                index: f.index,
            })
            .collect();
        let lines: Vec<LineIndex> = after.iter().map(|(_, t)| LineIndex::new(t)).collect();
        let indexes: Vec<Index> = after.iter().map(|(_, t)| Index::build(t)).collect();
        let files: Vec<File> = after
            .iter()
            .zip(&lines)
            .zip(&indexes)
            .map(|(((n, t), l), i)| File {
                name: n,
                text: t,
                lines: l,
                index: i,
            })
            .collect();
        let count = refresh(&mut model, &before, &files).unwrap();
        assert_eq!(snapshot(&model), snapshot(&decode_all(&after)));
        count
    }

    #[test]
    fn a_rename_patched_as_decoded() {
        let texts = micro_grid();
        let model = decode_all(&texts);
        let line = model.by_type["ACLineSegment"][0].clone();
        let n = patched_as_decoded(&texts, |files| {
            edit::rename(files, &line, "_renamed").unwrap()
        });
        // The line under both names, its terminals and what else refers to it.
        assert!(n >= 4, "{n}");
    }

    #[test]
    fn a_deletion_patched_as_decoded() {
        let texts = micro_grid();
        let model = decode_all(&texts);
        let line = model.by_type["ACLineSegment"][1].clone();
        patched_as_decoded(&texts, |files| {
            edit::delete(files, &HashSet::from([line.as_str()])).edits
        });
    }

    #[test]
    fn a_field_set_patched_as_decoded() {
        let texts = micro_grid();
        let model = decode_all(&texts);
        let line = model.by_type["ACLineSegment"][0].clone();
        let n = patched_as_decoded(&texts, |files| {
            edit::set_field(files, "", &line, "IdentifiedObject.name", "renamed").unwrap()
        });
        assert_eq!(n, 1);
    }

    #[test]
    fn a_breaker_added_patched_as_decoded() {
        let texts = micro_grid();
        let model = decode_all(&texts);
        let datasets = [model];
        let m = Model::new(&datasets);
        let g = grid::build(&m);
        let t = tree::build(&m);
        let (sub, inside) = g
            .nodes
            .iter()
            .filter(|n| n.kind == "Substation")
            .find_map(|n| Some((n.id.clone(), g.inside_of(&n.id)?)))
            .unwrap();
        let level = inside.groups[0].id.clone();
        let mut k = 0u8;
        let n = patched_as_decoded(&texts, |files| {
            let op = serde_json::json!({ "op": "add", "class": "Breaker", "level": level });
            let mut random = || {
                k += 1;
                [k; 16]
            };
            crate::topology::apply(files, &t, inside, &op, &mut random)
                .unwrap_or_else(|e| panic!("{sub}: {e}"))
                .edits
        });
        // The breaker, its terminals and connectivity nodes at least.
        assert!(n >= 3, "{n}");
    }

    /// `edits` of the files `texts`, each file's index edited as read anew.
    fn indexes_edited_as_read(
        texts: &[(String, String)],
        edits: &[(String, Vec<crate::text::TextEdit>)],
    ) -> usize {
        let mut all = 0;
        assert!(
            edits.iter().any(|(_, e)| !e.is_empty()),
            "the edit changes nothing"
        );
        for (name, changes) in edits {
            let old = &texts.iter().find(|(n, _)| n == name).unwrap().1;
            let new = apply(old, changes);
            let (old_lines, new_lines) = (LineIndex::new(old), LineIndex::new(&new));
            let (edited, touched) = Index::build(old)
                .edited(old, &old_lines, &new, &new_lines, changes)
                .unwrap_or_else(|_| panic!("{name}: refused"));
            let read = Index::build(&new);
            assert_eq!(
                format!("{:?}", edited.elements),
                format!("{:?}", read.elements),
                "{name}"
            );
            // What differs is among what it touched.
            let was = Index::build(old);
            let before: BTreeMap<&str, String> = was
                .elements
                .iter()
                .map(|e| (e.mrid.as_str(), slice(old, &old_lines, e).to_string()))
                .collect();
            for e in &read.elements {
                if before.get(e.mrid.as_str()).map(String::as_str)
                    != Some(slice(&new, &new_lines, e))
                {
                    assert!(touched.contains(&e.mrid), "{name}: {} not touched", e.mrid);
                }
            }
            all += touched.len();
        }
        all
    }

    fn slice<'t>(text: &'t str, lines: &LineIndex, e: &crate::index::Element) -> &'t str {
        &text[lines.offset(text, e.full.start)..lines.offset(text, e.full.end)]
    }

    /// The edits `edit` makes of the MicroGrid files, by file.
    fn edits_of(
        texts: &[(String, String)],
        edit: impl for<'a> FnOnce(&[File<'a>]) -> Edits<'a>,
    ) -> Vec<(String, Vec<crate::text::TextEdit>)> {
        let lines: Vec<LineIndex> = texts.iter().map(|(_, t)| LineIndex::new(t)).collect();
        let indexes: Vec<Index> = texts.iter().map(|(_, t)| Index::build(t)).collect();
        let files: Vec<File> = texts
            .iter()
            .zip(&lines)
            .zip(&indexes)
            .map(|(((n, t), l), i)| File {
                name: n,
                text: t,
                lines: l,
                index: i,
            })
            .collect();
        edit(&files)
            .into_iter()
            .map(|(n, e)| (n.to_string(), e))
            .collect()
    }

    #[test]
    fn indexes_are_edited_as_read_anew() {
        let texts = micro_grid();
        let model = decode_all(&texts);
        let line = model.by_type["ACLineSegment"][0].clone();
        let other = model.by_type["ACLineSegment"][1].clone();
        indexes_edited_as_read(
            &texts,
            &edits_of(&texts, |f| edit::rename(f, &line, "_renamed").unwrap()),
        );
        indexes_edited_as_read(
            &texts,
            &edits_of(&texts, |f| {
                edit::delete(f, &HashSet::from([other.as_str()])).edits
            }),
        );
        indexes_edited_as_read(
            &texts,
            &edits_of(&texts, |f| {
                edit::set_field(f, "", &line, "IdentifiedObject.name", "a\nname").unwrap()
            }),
        );
        // Objects added before the root's end, and one taken from the start.
        let (name, text) = &texts[4];
        let lines = LineIndex::new(text);
        let ix = Index::build(text);
        let end = text.rfind("</").unwrap();
        let at = |o: usize| lines.position(text, o);
        let first = &ix.elements[1];
        let added = "  <cim:Breaker rdf:ID=\"_new\">\n    <cim:IdentifiedObject.name>New</cim:IdentifiedObject.name>\n  </cim:Breaker>\n";
        let changes = vec![
            crate::text::TextEdit::new(Range::new(first.full.start, first.full.end), String::new()),
            crate::text::TextEdit::new(Range::new(at(end), at(end)), added.to_string()),
        ];
        // The two objects, and those written on the lines they meet: no more is read again.
        let touched = indexes_edited_as_read(&texts, &[(name.clone(), changes)]);
        assert!(touched <= 6, "{touched}");
    }

    /// The grid of `texts` laid out as it is built anew, given that of `before`.
    fn laid_out_as_anew(before: &[(String, String)], texts: &[(String, String)]) -> bool {
        let previous = [decode_all(before)];
        let previous = grid::build(&Model::new(&previous));
        let now = [decode_all(texts)];
        let m = Model::new(&now);
        let kept = format!("{:?}", grid::build_like(&m, Some(previous)).auto);
        kept == format!("{:?}", grid::build(&m).auto)
    }

    /// The automatic layout of the grid of `texts`, built given `previous`, and that grid.
    fn auto_after(texts: &[(String, String)], previous: Option<grid::Grid>) -> grid::Grid {
        let now = [decode_all(texts)];
        grid::build_like(&Model::new(&now), previous)
    }

    /// Where `g`'s automatic layout puts each substation, and routes each line, by their ids.
    fn places(
        g: &grid::Grid,
    ) -> (
        BTreeMap<String, (f64, f64)>,
        BTreeMap<String, crate::schematic::Route>,
    ) {
        let auto = g.auto.as_ref().unwrap();
        let nodes = g
            .nodes
            .iter()
            .enumerate()
            .map(|(i, n)| (n.id.clone(), auto.nodes[&i]))
            .collect();
        let edges = g
            .edges
            .iter()
            .enumerate()
            .filter_map(|(k, e)| {
                let route = auto.edges.get(&k)?.clone();
                Some((
                    e.id.clone(),
                    (route, auto.tracks.get(&k).copied().unwrap_or(0)),
                ))
            })
            .collect();
        (nodes, edges)
    }

    #[test]
    fn a_grid_keeps_its_layout_as_it_would_come_out() {
        let texts = micro_grid();
        let after = |edits: Vec<(String, Vec<crate::text::TextEdit>)>| -> Vec<(String, String)> {
            texts
                .iter()
                .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
                    Some((_, e)) => (n.clone(), apply(t, e)),
                    None => (n.clone(), t.clone()),
                })
                .collect()
        };
        // A field set: the same substations and lines.
        let model = decode_all(&texts);
        let line = model.by_type["ACLineSegment"][0].clone();
        let named = after(edits_of(&texts, |f| {
            edit::set_field(f, "", &line, "IdentifiedObject.name", "renamed").unwrap()
        }));
        assert!(laid_out_as_anew(&texts, &named));
    }

    #[test]
    fn a_grid_keeps_its_layout_as_lines_come_and_go() {
        let texts = micro_grid();
        let model = decode_all(&texts);
        let line = model.by_type["ACLineSegment"][0].clone();
        let edits = edits_of(&texts, |f| {
            edit::delete(f, &HashSet::from([line.as_str()])).edits
        });
        let gone: Vec<(String, String)> = texts
            .iter()
            .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
                Some((_, e)) => (n.clone(), apply(t, e)),
                None => (n.clone(), t.clone()),
            })
            .collect();
        let first = auto_after(&texts, None);
        let (nodes, edges) = places(&first);
        // A line gone: every substation where it was, every other line along its route.
        let without = auto_after(&gone, Some(auto_after(&texts, None)));
        let (kept, routes) = places(&without);
        assert_eq!(kept, nodes);
        assert!(!routes.is_empty());
        for (id, route) in &routes {
            assert_eq!(Some(route), edges.get(id), "{id}");
        }
        assert!(routes.keys().all(|id| !id.starts_with(line.as_str())));
        // The line back: routed between where its substations are; gone again, the layout of
        // before it came, as an addition undone gives back.
        let back = auto_after(
            &texts,
            Some(auto_after(&gone, Some(auto_after(&texts, None)))),
        );
        let (again, back_routes) = places(&back);
        assert_eq!(again, nodes);
        assert_eq!(back_routes.len(), edges.len());
        let undone = auto_after(&gone, Some(back));
        assert_eq!(places(&undone), places(&without));
        // Another model: laid out anew.
        assert_eq!(
            format!("{:?}", auto_after(&texts, Some(grid::Grid::default())).auto),
            format!("{:?}", first.auto)
        );
    }

    /// The grid of the files `edit` makes of `texts`, from that of `texts` with a finding on
    /// each object (as cimlens keeps it, validated) and what the edit touched: as [`grid::build`]
    /// gives it. Whether it was brought up to date, rather than built anew.
    fn rebuilt_as_built(
        texts: &[(String, String)],
        edit: impl for<'a> FnOnce(&[File<'a>]) -> Edits<'a>,
    ) -> bool {
        let edits = edits_of(texts, edit);
        let mut touched = BTreeSet::new();
        let after: Vec<(String, String)> = texts
            .iter()
            .map(|(n, t)| match edits.iter().find(|(m, _)| m == n) {
                Some((_, e)) => {
                    let new = apply(t, e);
                    let (_, ids) = Index::build(t)
                        .edited(t, &LineIndex::new(t), &new, &LineIndex::new(&new), e)
                        .unwrap_or_else(|_| panic!("{n}: refused"));
                    touched.extend(ids);
                    (n.clone(), new)
                }
                None => (n.clone(), t.clone()),
            })
            .collect();
        let before = [decode_all(texts)];
        let found: Vec<(Option<usize>, cimvalidation::Violation)> = before[0]
            .entries
            .keys()
            .map(|id| {
                let v = cimvalidation::Violation {
                    object_id: id.clone(),
                    rule_id: String::new(),
                    class: String::new(),
                    property: String::new(),
                    message: String::new(),
                    severity: "sh:Violation".into(),
                    name: String::new(),
                    description: String::new(),
                };
                (None, v)
            })
            .collect();
        let previous = || {
            let mut g = grid::build(&Model::new(&before));
            g.add_findings(&found);
            g
        };
        let now = [decode_all(&after)];
        let m = Model::new(&now);
        let updated = grid::update(&m, &mut previous(), &touched).is_some();
        // As built given the grid before: its automatic layout carried over.
        let built = grid::build_like(&m, Some(grid::build(&Model::new(&before))));
        assert_eq!(
            grid::rebuild(&m, previous(), &touched).snapshot(),
            built.snapshot()
        );
        updated
    }

    /// The edits of topology operation `op` inside the substation `inside`.
    fn operated<'a>(
        files: &[File<'a>],
        tree: &tree::Tree,
        inside: &crate::grid::Inside,
        op: &serde_json::Value,
    ) -> Edits<'a> {
        let mut k = 0u8;
        let mut random = || {
            k += 1;
            [k; 16]
        };
        crate::topology::apply(files, tree, inside, op, &mut random)
            .unwrap()
            .edits
    }

    #[test]
    fn a_grid_is_rebuilt_as_built() {
        // In Anvers: a breaker added, then switched, renamed and deleted; a load deleted.
        let texts = micro_grid();
        let datasets = [decode_all(&texts)];
        let m = Model::new(&datasets);
        let (g, t) = (grid::build(&m), tree::build(&m));
        fn anvers(g: &grid::Grid) -> &crate::grid::Inside {
            let id = &g.nodes.iter().find(|n| n.label == "Anvers").unwrap().id;
            g.inside_of(id).unwrap()
        }
        let inside = anvers(&g);
        let level = inside.groups[0].id.clone();
        let add = serde_json::json!({ "op": "add", "class": "Breaker", "level": level });
        assert!(rebuilt_as_built(&texts, |f| operated(f, &t, inside, &add)));
        let load = inside
            .items
            .iter()
            .find(|it| it.class == "ConformLoad")
            .unwrap()
            .id
            .clone();
        let delete = serde_json::json!({ "op": "delete", "ids": [load] });
        assert!(rebuilt_as_built(&texts, |f| operated(
            f, &t, inside, &delete
        )));

        let edits = edits_of(&texts, |f| operated(f, &t, inside, &add));
        let added: Vec<(String, String)> = texts
            .iter()
            .map(|(n, text)| match edits.iter().find(|(m, _)| m == n) {
                Some((_, e)) => (n.clone(), apply(text, e)),
                None => (n.clone(), text.clone()),
            })
            .collect();
        let datasets = [decode_all(&added)];
        let m = Model::new(&datasets);
        let (g, t) = (grid::build(&m), tree::build(&m));
        let inside = anvers(&g);
        let breaker = inside
            .items
            .iter()
            .find(|it| it.class == "Breaker")
            .unwrap()
            .id
            .clone();
        let open = serde_json::json!({ "op": "switch", "id": breaker, "open": true });
        assert!(rebuilt_as_built(&added, |f| operated(f, &t, inside, &open)));
        assert!(rebuilt_as_built(&added, |f| {
            edit::set_field(f, "", &breaker, "IdentifiedObject.name", "renamed").unwrap()
        }));
        let delete = serde_json::json!({ "op": "delete", "ids": [breaker] });
        assert!(rebuilt_as_built(&added, |f| operated(
            f, &t, inside, &delete
        )));
        // Nothing edited: as it was, its findings gone.
        assert!(rebuilt_as_built(&texts, |_| Vec::new()));

        // A line, or a substation: built anew.
        let line = datasets[0].by_type["ACLineSegment"][0].clone();
        assert!(!rebuilt_as_built(&texts, |f| {
            edit::set_field(f, "", &line, "IdentifiedObject.name", "renamed").unwrap()
        }));
        assert!(!rebuilt_as_built(&texts, |f| {
            edit::delete(f, &HashSet::from([line.as_str()])).edits
        }));
        let sub = datasets[0].by_type["Substation"][0].clone();
        assert!(!rebuilt_as_built(&texts, |f| {
            edit::set_field(f, "", &sub, "IdentifiedObject.name", "renamed").unwrap()
        }));
    }

    #[test]
    fn an_edit_of_the_root_is_refused() {
        let texts = micro_grid();
        let (name, text) = &texts[1];
        let after = text.replacen("xmlns:cim=", "xmlns:x=\"urn:x\" xmlns:cim=", 1);
        let (lines, index) = (LineIndex::new(&after), Index::build(&after));
        let files = [File {
            name,
            text: &after,
            lines: &lines,
            index: &index,
        }];
        let (old_lines, old_index) = (LineIndex::new(text), Index::build(text));
        let before = [File {
            name,
            text,
            lines: &old_lines,
            index: &old_index,
        }];
        let mut model = decode_all(&texts);
        assert!(refresh(&mut model, &before, &files).is_err());
    }
}