use alloc::collections::{BTreeMap, BTreeSet};
use alloc::vec::Vec;
use crate::geom::{DirSet, Direction};
use crate::graph::{RoutingGraph, VertexId};
use crate::search::Weights;
pub(crate) type Edges = BTreeSet<(VertexId, VertexId)>;
fn edge(graph: &RoutingGraph, a: VertexId, b: VertexId) -> (VertexId, VertexId) {
if graph.point(a) < graph.point(b) {
(a, b)
} else {
(b, a)
}
}
pub(crate) fn arms(graph: &RoutingGraph, edges: &Edges) -> BTreeMap<VertexId, DirSet> {
let mut arms: BTreeMap<VertexId, DirSet> = BTreeMap::new();
for &(a, b) in edges {
let d = Direction::between(graph.point(a), graph.point(b)).expect("aligned edge");
*arms.entry(a).or_default() |= DirSet::only(d);
*arms.entry(b).or_default() |= DirSet::only(d.reverse());
}
arms
}
pub(crate) fn cost(graph: &RoutingGraph, edges: &Edges, weights: Weights) -> u64 {
let length: u64 = edges
.iter()
.map(|&(a, b)| graph.point(a).manhattan(graph.point(b)))
.sum();
let bends = arms(graph, edges)
.values()
.filter(|a| {
a.iter().any(|d| d.axis() == crate::geom::Axis::X)
&& a.iter().any(|d| d.axis() == crate::geom::Axis::Y)
})
.count();
weights.length.saturating_mul(length).saturating_add(
weights
.bend
.saturating_mul(u64::try_from(bends).unwrap_or(u64::MAX)),
)
}
fn runs(graph: &RoutingGraph, edges: &Edges, forward: Direction) -> Vec<Vec<VertexId>> {
let arms = arms(graph, edges);
let mut out = Vec::new();
for (&v, set) in &arms {
if set.contains(forward) && !set.contains(forward.reverse()) {
let mut run = alloc::vec![v];
let mut at = v;
while arms.get(&at).is_some_and(|a| a.contains(forward)) {
at = graph
.neighbor(at, forward)
.expect("tree edges are graph edges");
run.push(at);
}
out.push(run);
}
}
out
}
fn chain(
graph: &RoutingGraph,
from: VertexId,
dir: Direction,
target: i32,
) -> Option<(VertexId, Vec<(VertexId, VertexId)>)> {
let axis = dir.axis();
let mut at = from;
let mut out = Vec::new();
loop {
let c = graph.point(at).coordinate(axis);
if c == target {
return Some((at, out));
}
if (dir.is_positive() && c > target) || (!dir.is_positive() && c < target) {
return None;
}
let next = graph.neighbor(at, dir)?;
out.push(edge(graph, at, next));
at = next;
}
}
fn is_tree(graph: &RoutingGraph, edges: &Edges, terminals: &[VertexId]) -> bool {
let arms = arms(graph, edges);
if arms.len() != edges.len() + 1 && !(edges.is_empty() && terminals.len() <= 1) {
return false;
}
let Some(&start) = arms.keys().next() else {
return terminals.len() <= 1;
};
let mut seen = BTreeSet::from([start]);
let mut stack = alloc::vec![start];
while let Some(v) = stack.pop() {
for d in arms[&v].iter() {
let w = graph.neighbor(v, d).expect("tree edges are graph edges");
if seen.insert(w) {
stack.push(w);
}
}
}
seen.len() == arms.len() && terminals.iter().all(|t| seen.contains(t))
}
fn shift(
graph: &RoutingGraph,
edges: &Edges,
run: &[VertexId],
forward: Direction,
side: Direction,
) -> Option<Edges> {
let arms = arms(graph, edges);
let across = side.axis();
let mut target: Option<i32> = None;
for &u in run {
if !arms[&u].contains(side) {
continue;
}
let mut at = u;
while arms.get(&at).is_some_and(|a| a.contains(side)) {
at = graph.neighbor(at, side)?;
}
let c = graph.point(at).coordinate(across);
target = Some(match target {
None => c,
Some(t) if side.is_positive() => t.min(c),
Some(t) => t.max(c),
});
}
let target = target?;
let mut next = edges.clone();
for pair in run.windows(2) {
next.remove(&edge(graph, pair[0], pair[1]));
}
let mut moved = Vec::with_capacity(run.len());
for &u in run {
let (w, path) = chain(graph, u, side, target)?;
if arms[&u].contains(side) {
for e in &path {
next.remove(e);
}
}
if arms[&u].contains(side.reverse()) {
next.extend(path);
}
moved.push(w);
}
for pair in moved.windows(2) {
let (w, path) = chain(
graph,
pair[0],
forward,
graph.point(pair[1]).coordinate(forward.axis()),
)?;
if w != pair[1] {
return None;
}
next.extend(path);
}
Some(next)
}
fn prune(graph: &RoutingGraph, edges: &mut Edges, terminals: &[VertexId]) {
loop {
let arms = arms(graph, edges);
let before = edges.len();
edges.retain(|&(a, b)| {
let leaf = |v: VertexId| arms[&v].iter().count() == 1 && !terminals.contains(&v);
!(leaf(a) || leaf(b))
});
if edges.len() == before {
return;
}
}
}
pub(crate) fn improve(
graph: &RoutingGraph,
edges: &mut Edges,
terminals: &[VertexId],
weights: Weights,
max_rounds: u32,
) {
for _ in 0..max_rounds {
if !improve_once(graph, edges, terminals, weights) {
return;
}
}
}
fn improve_once(
graph: &RoutingGraph,
edges: &mut Edges,
terminals: &[VertexId],
weights: Weights,
) -> bool {
let current = cost(graph, edges, weights);
for forward in [Direction::Right, Direction::Up] {
for run in runs(graph, edges, forward) {
if run.iter().any(|v| terminals.contains(v)) {
continue;
}
let arms = arms(graph, edges);
let count = |d: Direction| run.iter().filter(|u| arms[u].contains(d)).count();
for side in [forward.left(), forward.right()] {
if count(side) <= count(side.reverse()) {
continue;
}
let Some(mut next) = shift(graph, edges, &run, forward, side) else {
continue;
};
prune(graph, &mut next, terminals);
if is_tree(graph, &next, terminals) && cost(graph, &next, weights) < current {
*edges = next;
return true;
}
}
}
}
false
}