use std::collections::{BTreeMap, HashMap, HashSet};
const STEP: f64 = 0.5;
const THROUGH_NODE: u32 = 40;
const SHARED: u32 = 12;
const CROSSING: u32 = 3;
const BEND: u32 = 1;
type Point = (i64, i64);
#[derive(Debug, PartialEq)]
pub struct Schematic {
pub nodes: Vec<(f64, f64)>,
pub routes: Vec<Vec<(f64, f64)>>,
pub tracks: Vec<i32>,
}
pub fn octilinear(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Schematic {
let at = snap(pos, edges);
let unit = |p: Point| (p.0 as f64 * STEP, p.1 as f64 * STEP);
let taken: HashSet<Point> = at.iter().copied().collect();
let mut pairs: BTreeMap<(usize, usize), Vec<usize>> = BTreeMap::new();
for (k, &(a, b)) in edges.iter().enumerate() {
if a != b {
pairs.entry((a.min(b), a.max(b))).or_default().push(k);
}
}
let mut order: Vec<(usize, usize)> = pairs.keys().copied().collect();
let span = |&(a, b): &(usize, usize)| {
let (d0, d1) = ((at[b].0 - at[a].0).abs(), (at[b].1 - at[a].1).abs());
(d0.max(d1), d0.min(d1))
};
order.sort_by_key(|p| (span(p), *p));
let mut drawn = Drawn::default();
let mut paths: Vec<Vec<Point>> = vec![Vec::new(); edges.len()];
let mut walked = Vec::new();
for pair in order {
let (a, b) = pair;
let path = shapes(at[a], at[b])
.into_iter()
.map(|path| (drawn.cost(&path, &taken), path))
.min_by_key(|(cost, _)| *cost)
.map(|(_, path)| path)
.expect("a shape at least");
drawn.add(&path);
for &k in &pairs[&pair] {
paths[k] = if edges[k].0 == a {
path.clone()
} else {
path.iter().rev().copied().collect()
};
walked.push(k);
}
}
let mut sides: HashMap<(Point, Point), HashSet<i32>> = HashMap::new();
let mut tracks = vec![0; edges.len()];
for k in walked {
let pieces: Vec<((Point, Point), i32)> = steps(&paths[k])
.map(|(p, d)| {
let q = (p.0 + d.0, p.1 + d.1);
(piece(p, q), if p <= q { 1 } else { -1 })
})
.collect();
let free = |t: i32| {
pieces
.iter()
.all(|(key, sign)| !sides.get(key).is_some_and(|s| s.contains(&(t * sign))))
};
let track = (0..)
.flat_map(|i: i32| if i == 0 { vec![0] } else { vec![i, -i] })
.find(|&t| free(t))
.expect("a free track");
for (key, sign) in pieces {
sides.entry(key).or_default().insert(track * sign);
}
tracks[k] = track;
}
Schematic {
nodes: at.into_iter().map(unit).collect(),
routes: paths
.into_iter()
.map(|p| p.into_iter().map(unit).collect())
.collect(),
tracks,
}
}
fn snap(pos: &[(f64, f64)], edges: &[(usize, usize)]) -> Vec<Point> {
let mut degree = vec![0usize; pos.len()];
for &(a, b) in edges {
degree[a] += 1;
degree[b] += 1;
}
let mut order: Vec<usize> = (0..pos.len()).collect();
order.sort_by_key(|&i| (std::cmp::Reverse(degree[i]), i));
let mut taken: HashSet<Point> = HashSet::new();
let mut at = vec![(0, 0); pos.len()];
for i in order {
let (x, y) = (pos[i].0 / STEP, pos[i].1 / STEP);
let home = (x.round() as i64, y.round() as i64);
let mut best = home;
if taken.contains(&home) {
'rings: for r in 1i64.. {
let mut ring: Vec<Point> = (-r..=r)
.flat_map(|i| {
[
(home.0 + i, home.1 - r),
(home.0 + i, home.1 + r),
(home.0 - r, home.1 + i),
(home.0 + r, home.1 + i),
]
})
.filter(|p| !taken.contains(p))
.collect();
if ring.is_empty() {
continue;
}
ring.sort_by(|p, q| {
let d = |p: &Point| (p.0 as f64 - x).powi(2) + (p.1 as f64 - y).powi(2);
d(p).total_cmp(&d(q)).then(p.cmp(q))
});
best = ring[0];
break 'rings;
}
}
taken.insert(best);
at[i] = best;
}
at
}
fn shapes(a: Point, b: Point) -> Vec<Vec<Point>> {
let (dx, dy) = (b.0 - a.0, b.1 - a.1);
let (ax, ay) = (dx.abs(), dy.abs());
if ax == 0 || ay == 0 || ax == ay {
return vec![vec![a, b]];
}
let m = ax.min(ay);
let r = ax.max(ay) - m;
let diagonal = (dx.signum(), dy.signum());
let straight = if ax > ay {
(dx.signum(), 0)
} else {
(0, dy.signum())
};
let go = |p: Point, d: Point, n: i64| (p.0 + d.0 * n, p.1 + d.1 * n);
let mut out = vec![
vec![a, go(a, diagonal, m), b],
vec![a, go(a, straight, r), b],
];
if r >= 2 {
let h = go(a, straight, r / 2);
out.push(vec![a, h, go(h, diagonal, m), b]);
}
out
}
#[derive(Default)]
struct Drawn {
pieces: HashSet<(Point, Point)>,
}
fn piece(p: Point, q: Point) -> (Point, Point) {
if p <= q { (p, q) } else { (q, p) }
}
fn steps(path: &[Point]) -> impl Iterator<Item = (Point, Point)> + '_ {
path.windows(2).flat_map(|w| {
let (p, q) = (w[0], w[1]);
let d = ((q.0 - p.0).signum(), (q.1 - p.1).signum());
let n = (q.0 - p.0).abs().max((q.1 - p.1).abs());
(0..n).map(move |i| ((p.0 + d.0 * i, p.1 + d.1 * i), d))
})
}
impl Drawn {
fn cost(&self, path: &[Point], nodes: &HashSet<Point>) -> u32 {
let (a, b) = (path[0], path[path.len() - 1]);
let mut cost = BEND * (path.len() as u32 - 2);
for (p, d) in steps(path) {
let q = (p.0 + d.0, p.1 + d.1);
if q != b && q != a && nodes.contains(&q) {
cost += THROUGH_NODE;
}
if self.pieces.contains(&piece(p, q)) {
cost += SHARED;
}
if d.0 != 0
&& d.1 != 0
&& self
.pieces
.contains(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1)))
{
cost += CROSSING;
}
}
cost
}
fn add(&mut self, path: &[Point]) {
for (p, d) in steps(path) {
self.pieces.insert(piece(p, (p.0 + d.0, p.1 + d.1)));
}
}
}
#[cfg(test)]
fn crossings(routes: &[Vec<(f64, f64)>]) -> usize {
let mut drawn: HashMap<(Point, Point), usize> = HashMap::new();
let lattice = |p: (f64, f64)| ((p.0 / STEP).round() as i64, (p.1 / STEP).round() as i64);
let mut count = 0;
for (k, r) in routes.iter().enumerate() {
let path: Vec<Point> = r.iter().map(|&p| lattice(p)).collect();
let mut path = path;
path.dedup();
for (p, d) in steps(&path) {
if d.0 != 0
&& d.1 != 0
&& drawn
.get(&piece((p.0 + d.0, p.1), (p.0, p.1 + d.1)))
.is_some_and(|&o| o != k)
{
count += 1;
}
}
for (p, d) in steps(&path) {
drawn.insert(piece(p, (p.0 + d.0, p.1 + d.1)), k);
}
}
count
}
#[cfg(test)]
mod tests {
use super::*;
fn octilinear_pieces(routes: &[Vec<(f64, f64)>]) -> bool {
routes.iter().all(|r| {
r.windows(2).all(|w| {
let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
dx < 1e-9 || dy < 1e-9 || (dx - dy).abs() < 1e-9
})
})
}
#[test]
fn lines_run_along_axes_and_diagonals() {
let pos = [(0.0, 0.0), (1.7, 0.6), (0.4, 1.9), (2.2, 2.4), (-1.3, 0.8)];
let edges = [(0, 1), (0, 2), (1, 3), (2, 3), (0, 4), (4, 2)];
let Schematic { nodes, routes, .. } = octilinear(&pos, &edges);
assert!(octilinear_pieces(&routes), "{routes:?}");
for (k, &(a, b)) in edges.iter().enumerate() {
assert_eq!(
routes[k].first(),
Some(&nodes[a]),
"edge {k} from its source"
);
assert_eq!(routes[k].last(), Some(&nodes[b]), "edge {k} to its target");
assert!(routes[k].len() <= 4, "at most two bends: {:?}", routes[k]);
}
}
#[test]
fn nodes_keep_apart_and_near_where_they_were() {
let pos = [(0.0, 0.0), (0.01, 0.0), (0.0, 0.02), (3.0, 3.0)];
let Schematic { nodes, .. } = octilinear(&pos, &[(0, 3), (1, 3), (2, 3)]);
let distinct: HashSet<(i64, i64)> = nodes
.iter()
.map(|p| ((p.0 * 100.0).round() as i64, (p.1 * 100.0).round() as i64))
.collect();
assert_eq!(distinct.len(), 4);
assert!(
nodes
.iter()
.zip(&pos)
.all(|(p, q)| (p.0 - q.0).abs() <= 2.0 * STEP && (p.1 - q.1).abs() <= 2.0 * STEP)
);
}
#[test]
fn a_line_goes_round_a_node_in_its_way() {
let pos = [(0.0, 0.0), (1.0, 0.0), (2.0, 0.5)];
let Schematic { nodes, routes, .. } = octilinear(&pos, &[(0, 2), (0, 1)]);
let through = |r: &Vec<(f64, f64)>, p: (f64, f64)| {
r.windows(2).any(|w| {
let (a, b) = (w[0], w[1]);
let cross = (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0);
let within = (p.0 - a.0) * (p.0 - b.0) <= 1e-9 && (p.1 - a.1) * (p.1 - b.1) <= 1e-9;
cross.abs() < 1e-9 && within && p != a && p != b
})
};
assert!(
!through(&routes[0], nodes[1]),
"{:?} through {:?}",
routes[0],
nodes[1]
);
}
#[test]
fn double_circuits_run_side_by_side() {
let pos = [(0.0, 0.0), (2.0, 1.0)];
let Schematic {
nodes,
routes,
tracks,
} = octilinear(&pos, &[(0, 1), (1, 0), (0, 1)]);
assert!(octilinear_pieces(&routes), "{routes:?}");
assert_eq!(routes[0], routes[2]);
assert_eq!(
routes[1],
routes[0].iter().rev().copied().collect::<Vec<_>>()
);
assert_eq!(
routes[1][0], nodes[1],
"the one written the other way round, from its own source"
);
assert_eq!(tracks, vec![0, 1, 1]);
}
#[test]
fn lines_sharing_a_stretch_take_tracks_of_their_own() {
let pos = [(0.0, 0.0), (-1.0, 0.0), (1.5, 1.5)];
let Schematic { routes, tracks, .. } = octilinear(&pos, &[(0, 2), (1, 2)]);
let shared = routes[0]
.windows(2)
.any(|w| routes[1].windows(2).any(|v| v == w));
if shared {
assert_ne!(tracks[0], tracks[1], "{routes:?} {tracks:?}");
}
assert!(tracks.contains(&0));
}
#[test]
fn the_same_grid_the_same_schematic() {
let pos: Vec<(f64, f64)> = (0..60)
.map(|i| (((i * 37) % 23) as f64 * 0.7, ((i * 53) % 19) as f64 * 0.6))
.collect();
let edges: Vec<(usize, usize)> = (0..59).map(|i| (i, (i * 7 + 3) % 60)).collect();
assert_eq!(octilinear(&pos, &edges), octilinear(&pos, &edges));
let Schematic { routes, .. } = octilinear(&pos, &edges);
assert!(octilinear_pieces(&routes));
assert!(crossings(&routes) < edges.len());
}
}
#[cfg(test)]
mod timing {
#[test]
#[ignore]
fn realgrid_sized() {
let n = 4875;
let mut edges: Vec<(usize, usize)> = (1..n).map(|i| (i, (i * 7919) % i)).collect();
edges.extend((0..2878).map(|i| ((i * 31) % n, (i * 31 + 17) % n)));
let pos = crate::layout::force(n, &edges);
let t = std::time::Instant::now();
let super::Schematic { routes, .. } = super::octilinear(&pos, &edges);
eprintln!("octilinear: {:?} for {} routes", t.elapsed(), routes.len());
}
}
#[cfg(test)]
mod shared_count {
#[test]
#[ignore]
fn shared_pieces() {
for dir in ["SmallGrid/SmallGrid-Merged", "RealGrid/RealGrid-Merged"] {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("../CGMES-Test-Configurations/v3.0")
.join(dir);
let read = crate::testing::collect(&path);
let datasets: Vec<cimmodel::CimDataset> = read
.iter()
.map(|(_, t)| cimmodel::CimDataset::decode_str(t).unwrap())
.collect();
let m = crate::grid::Model::new(&datasets);
let g = crate::grid::build(&m);
let auto = g.auto.as_ref().unwrap();
let mut seen: std::collections::HashMap<((i64, i64), (i64, i64)), (usize, usize)> =
std::collections::HashMap::new();
let (mut shared, mut total) = (0, 0);
let mut high = 0;
for (&k, r) in &auto.edges {
let e = &g.edges[k];
let pair = (e.source.min(e.target), e.source.max(e.target));
let lattice: Vec<(i64, i64)> = r
.iter()
.map(|p| {
(
(p.0 / super::STEP).round() as i64,
(p.1 / super::STEP).round() as i64,
)
})
.collect();
for (p, d) in super::steps(&lattice) {
let q = (p.0 + d.0, p.1 + d.1);
let key = if p <= q { (p, q) } else { (q, p) };
total += 1;
if let Some(o) = seen.get(&key) {
if *o != pair {
shared += 1;
if e.kv.is_some_and(|v| v >= 300.0) {
high += 1;
}
}
} else {
seen.insert(key, pair);
}
}
}
eprintln!(
"{dir}: {shared} of {total} unit pieces shared between different pairs, {high} on ≥300 kV lines"
);
}
}
}