Skip to main content

logicaffeine_compile/codegen_sva/
signal_design.rs

1//! Conflict-free traffic-signal PHASE DESIGNER (certified SAT synthesis).
2//!
3//! Grouping intersection movements into green phases so no two *conflicting* movements ever share
4//! a phase is exactly graph k-colouring — a SAT problem. We encode it as a boolean [`ProofExpr`]
5//! and discharge it with the project's own certified solver (`logicaffeine_proof::sat`), never Z3:
6//!
7//! * a feasible plan is a SAT **model** (a witness that is trivially re-checkable), and
8//! * the claim "fewer phases is impossible" is a `prove_unsat` **`Refuted`** result, which is
9//!   RUP-certified — so the *minimality* of the plan is certified, not merely asserted.
10//!
11//! The English frontend is a focused grammar ("X conflicts with Y, Z and …") rather than the
12//! general FOL pipeline, so the designer is robust independent of that surface.
13
14use logicaffeine_proof::sat::{prove_unsat, UnsatOutcome};
15use logicaffeine_proof::ProofExpr;
16use std::collections::HashMap;
17
18/// An intersection: a set of movements and the pairs that may not be green together.
19#[derive(Clone, Debug, PartialEq)]
20pub struct Intersection {
21    /// Movement display names, in first-seen order.
22    pub movements: Vec<String>,
23    /// Conflicting movement pairs, as `(min, max)` indices into [`movements`](Self::movements).
24    pub conflicts: Vec<(usize, usize)>,
25}
26
27impl Intersection {
28    /// Resolve a slice of movement indices to their display names.
29    pub fn names(&self, idxs: &[usize]) -> Vec<String> {
30        idxs.iter()
31            .filter_map(|&i| self.movements.get(i).cloned())
32            .collect()
33    }
34}
35
36/// A synthesized signal plan: each movement assigned to a green phase.
37#[derive(Clone, Debug, PartialEq)]
38pub struct PhasePlan {
39    /// Number of green phases used (the chromatic number when `minimal_certified`).
40    pub num_phases: usize,
41    /// `assignment[m]` = the phase index movement `m` is served in.
42    pub assignment: Vec<usize>,
43    /// `true` when `num_phases - 1` was proven infeasible (RUP-certified) — i.e. this is provably
44    /// the *fewest* phases possible. (Trivially `true` for a single phase.)
45    pub minimal_certified: bool,
46}
47
48impl PhasePlan {
49    /// Movement indices grouped by phase, in phase order.
50    pub fn groups(&self) -> Vec<Vec<usize>> {
51        let mut groups = vec![Vec::new(); self.num_phases];
52        for (m, &p) in self.assignment.iter().enumerate() {
53            if p < self.num_phases {
54                groups[p].push(m);
55            }
56        }
57        groups
58    }
59}
60
61/// Re-check that a plan is a genuine conflict-free colouring (used by tests and as a guard).
62pub fn is_valid_coloring(it: &Intersection, plan: &PhasePlan) -> bool {
63    if plan.assignment.len() != it.movements.len() {
64        return false;
65    }
66    if plan.assignment.iter().any(|&p| p >= plan.num_phases.max(1)) {
67        return false;
68    }
69    it.conflicts.iter().all(|&(a, b)| {
70        a == b
71            || a >= it.movements.len()
72            || b >= it.movements.len()
73            || plan.assignment.get(a) != plan.assignment.get(b)
74    })
75}
76
77/// Design the minimal-phase conflict-free plan for an intersection, or `None` if it has no
78/// movements.
79///
80/// The chromatic number `χ` is pinned between two **checkable combinatorial certificates** before
81/// the SAT solver is ever consulted:
82///
83/// * a maximal **clique** of mutually-conflicting movements proves `χ ≥ |clique|` (you can verify
84///   it by eye — every pair really is in conflict), and
85/// * a **greedy proper colouring** is a self-checking witness that `χ ≤ greedy`.
86///
87/// When those meet (`|clique| == greedy`) the greedy colouring is provably optimal and we return it
88/// with **zero SAT calls** — the common case for the perfect-ish conflict graphs real intersections
89/// produce. Otherwise we close the gap `[lb, ub)` with the certified solver, pinning the clique to
90/// phases `0..lb-1` to break colour-permutation symmetry; the first feasible `k` is `χ`, its witness
91/// is a SAT model, and minimality is certified either by the clique (`k == lb`) or by the RUP-
92/// `Refuted` solve at `k-1`. Either route is certified end-to-end.
93pub fn design_phase_plan(it: &Intersection) -> Option<PhasePlan> {
94    let n = it.movements.len();
95    if n == 0 {
96        return None;
97    }
98    let adj = build_adjacency(it, n);
99
100    // Sharpest cheap lever first — bipartiteness. A 2-colouring (BFS, O(V+E)) either *is* the
101    // certified-minimal plan (the graph is 1- or 2-chromatic; any edge rules out a single phase),
102    // or it fails and hands back an **odd closed walk**: a checkable certificate that χ ≥ 3, since
103    // colours must alternate along any walk and a 2-colourable graph therefore has none.
104    match two_color(&adj, n) {
105        Ok(coloring) => {
106            let num_phases = coloring.iter().copied().max().map(|c| c + 1).unwrap_or(1);
107            return Some(PhasePlan {
108                num_phases,
109                assignment: coloring,
110                minimal_certified: true,
111            });
112        }
113        Err(odd_walk) => {
114            debug_assert!(
115                is_odd_closed_walk(&adj, &odd_walk),
116                "two_color must return a genuine odd closed walk: {odd_walk:?}"
117            );
118        }
119    }
120
121    let clique = greedy_clique(&adj, n);
122    // χ ≥ 3 (the odd walk just proved non-bipartiteness) and χ ≥ |clique|.
123    let lb = clique.len().max(3);
124    let (greedy_colors, ub) = greedy_coloring(&adj, n);
125
126    // Fast path: lower bound meets the greedy upper bound, so the greedy colouring is optimal and
127    // fewer phases is impossible — certified by the clique (when it sets the bound) or the odd walk.
128    if lb >= ub {
129        return Some(PhasePlan {
130            num_phases: ub,
131            assignment: greedy_colors,
132            minimal_certified: true,
133        });
134    }
135
136    // Close the gap. `k = lb-1 ≥ 2` is already infeasible by a certificate (the clique when
137    // `lb = |clique|`, otherwise the odd walk, which forbids any 2-colouring), so entering the scan
138    // at `lb` is sound and `lb` is certified-minimal the moment it proves feasible.
139    let mut prev_infeasible_certified = true;
140    for k in lb..ub {
141        match solve_coloring(it, &adj, &clique, k) {
142            ColoringResult::Feasible(assignment) => {
143                return Some(PhasePlan {
144                    num_phases: k,
145                    assignment,
146                    minimal_certified: prev_infeasible_certified,
147                });
148            }
149            ColoringResult::Infeasible => prev_infeasible_certified = true,
150            ColoringResult::Unknown => prev_infeasible_certified = false,
151        }
152    }
153    // Every `k` in `[lb, ub)` was infeasible, so `χ = ub`, witnessed by the greedy colouring we
154    // already hold — no need to re-solve at `ub`.
155    Some(PhasePlan {
156        num_phases: ub,
157        assignment: greedy_colors,
158        minimal_certified: prev_infeasible_certified,
159    })
160}
161
162/// Parse an English spec into an [`Intersection`], then design its minimal plan.
163pub fn design_from_spec(spec: &str) -> Result<(Intersection, PhasePlan), String> {
164    let it = parse_intersection(spec)?;
165    let plan = design_phase_plan(&it).ok_or_else(|| "no movements to schedule".to_string())?;
166    Ok((it, plan))
167}
168
169// ── SAT encoding ────────────────────────────────────────────────────────────
170
171enum ColoringResult {
172    Feasible(Vec<usize>),
173    Infeasible,
174    Unknown,
175}
176
177/// Counts every actual SAT query, so tests can prove the bounds short-circuit (zero solves for a
178/// perfect graph, one for an odd cycle, etc.) — the whole point of the speedup.
179#[cfg(test)]
180thread_local! {
181    static SAT_SOLVE_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
182}
183
184/// Read and reset the per-thread SAT-solve counter (test instrumentation).
185#[cfg(test)]
186fn take_solve_count() -> usize {
187    SAT_SOLVE_COUNT.with(|c| {
188        let v = c.get();
189        c.set(0);
190        v
191    })
192}
193
194fn solve_coloring(
195    it: &Intersection,
196    adj: &[Vec<bool>],
197    clique: &[usize],
198    k: usize,
199) -> ColoringResult {
200    #[cfg(test)]
201    SAT_SOLVE_COUNT.with(|c| c.set(c.get() + 1));
202    let formula = coloring_formula(it, adj, clique, k);
203    match prove_unsat(&formula) {
204        UnsatOutcome::Sat(model) => ColoringResult::Feasible(decode(it.movements.len(), k, &model)),
205        UnsatOutcome::Refuted => ColoringResult::Infeasible,
206        UnsatOutcome::Unsupported => ColoringResult::Unknown,
207    }
208}
209
210/// `a_m_p` ≙ "movement `m` is served in phase `p`".
211fn assign_atom(m: usize, p: usize) -> ProofExpr {
212    ProofExpr::Atom(format!("a_{m}_{p}"))
213}
214
215fn and(a: ProofExpr, b: ProofExpr) -> ProofExpr {
216    ProofExpr::And(Box::new(a), Box::new(b))
217}
218
219fn not(a: ProofExpr) -> ProofExpr {
220    ProofExpr::Not(Box::new(a))
221}
222
223fn conj(mut parts: Vec<ProofExpr>) -> ProofExpr {
224    match parts.len() {
225        0 => {
226            let t = ProofExpr::Atom("__true".to_string());
227            ProofExpr::Or(Box::new(t.clone()), Box::new(ProofExpr::Not(Box::new(t))))
228        }
229        1 => parts.pop().unwrap(),
230        _ => {
231            let mut acc = parts.pop().unwrap();
232            while let Some(p) = parts.pop() {
233                acc = and(p, acc);
234            }
235            acc
236        }
237    }
238}
239
240/// Build the boolean k-colouring obligation: every movement gets exactly one phase, and no
241/// conflicting pair shares a phase. The `clique` is pinned to phases `0..|clique|` as a
242/// **symmetry-breaking** constraint — colours are interchangeable, so a clique of distinct colours
243/// can WLOG take `0, 1, 2, …` in order; this is satisfiability-preserving (so a SAT model is a real
244/// witness and a RUP refutation still certifies the original UNSAT) while collapsing the otherwise
245/// factorial colour-permutation search.
246fn coloring_formula(it: &Intersection, adj: &[Vec<bool>], clique: &[usize], k: usize) -> ProofExpr {
247    let n = it.movements.len();
248    let mut clauses: Vec<ProofExpr> = Vec::new();
249
250    // Every movement is served in at least one phase.
251    for m in 0..n {
252        let mut disj = assign_atom(m, 0);
253        for p in 1..k {
254            disj = ProofExpr::Or(Box::new(disj), Box::new(assign_atom(m, p)));
255        }
256        clauses.push(disj);
257    }
258    // …and at most one phase (no movement runs in two phases at once).
259    for m in 0..n {
260        for p in 0..k {
261            for q in (p + 1)..k {
262                clauses.push(not(and(assign_atom(m, p), assign_atom(m, q))));
263            }
264        }
265    }
266    // Conflicting movements never share a phase. (Adjacency already dropped self-loops and
267    // out-of-range pairs, so no nonsensical conflict can make the problem unsatisfiable.)
268    for x in 0..n {
269        for y in (x + 1)..n {
270            if adj[x][y] {
271                for p in 0..k {
272                    clauses.push(not(and(assign_atom(x, p), assign_atom(y, p))));
273                }
274            }
275        }
276    }
277    // Symmetry break: pin clique member `i` to phase `i` (sound because k ≥ |clique| here).
278    for (i, &m) in clique.iter().enumerate() {
279        if i < k {
280            clauses.push(assign_atom(m, i));
281        }
282    }
283    conj(clauses)
284}
285
286// ── combinatorial bounds (checkable certificates that often avoid the solver) ──
287
288/// `n × n` symmetric adjacency from the conflict pairs, with self-loops and out-of-range indices
289/// dropped — the single normalised view shared by the bounds and the SAT encoding.
290fn build_adjacency(it: &Intersection, n: usize) -> Vec<Vec<bool>> {
291    let mut adj = vec![vec![false; n]; n];
292    for &(x, y) in &it.conflicts {
293        if x != y && x < n && y < n {
294            adj[x][y] = true;
295            adj[y][x] = true;
296        }
297    }
298    adj
299}
300
301/// Degree of each vertex, then a descending-degree order (ties by index) — the ordering both the
302/// clique and the colouring heuristics use.
303fn degree_order(adj: &[Vec<bool>], n: usize) -> Vec<usize> {
304    let deg = |v: usize| adj[v].iter().filter(|&&b| b).count();
305    let mut order: Vec<usize> = (0..n).collect();
306    order.sort_by(|&a, &b| deg(b).cmp(&deg(a)).then(a.cmp(&b)));
307    order
308}
309
310/// A large clique of mutually-conflicting movements: try growing greedily from each vertex (in
311/// degree order) and keep the biggest. Any clique is a sound lower bound on the chromatic number;
312/// a larger one just makes it tighter, so heuristic maximality is enough.
313fn greedy_clique(adj: &[Vec<bool>], n: usize) -> Vec<usize> {
314    if n == 0 {
315        return Vec::new();
316    }
317    let order = degree_order(adj, n);
318    let mut best = vec![order[0]];
319    for &start in &order {
320        let mut clique = vec![start];
321        for &v in &order {
322            if v != start && clique.iter().all(|&u| adj[v][u]) {
323                clique.push(v);
324            }
325        }
326        if clique.len() > best.len() {
327            best = clique;
328        }
329    }
330    best
331}
332
333/// A greedy proper colouring (Welsh–Powell: descending degree, smallest non-conflicting colour).
334/// Returns the assignment and the number of colours used — a self-checking upper bound on `χ`.
335fn greedy_coloring(adj: &[Vec<bool>], n: usize) -> (Vec<usize>, usize) {
336    let mut color = vec![usize::MAX; n];
337    let mut num_colors = 0usize;
338    for v in degree_order(adj, n) {
339        let mut used = vec![false; num_colors + 1];
340        for (u, &is_adj) in adj[v].iter().enumerate() {
341            if is_adj && color[u] != usize::MAX && color[u] < used.len() {
342                used[color[u]] = true;
343            }
344        }
345        let c = used.iter().position(|&b| !b).unwrap_or(num_colors);
346        color[v] = c;
347        num_colors = num_colors.max(c + 1);
348    }
349    for c in color.iter_mut() {
350        if *c == usize::MAX {
351            *c = 0;
352        }
353    }
354    (color, num_colors.max(1))
355}
356
357/// BFS 2-colouring. `Ok(colouring)` when the graph is bipartite (χ ≤ 2, the colouring uses 1 colour
358/// if edgeless else 2); `Err(odd_walk)` otherwise, where `odd_walk` is an odd closed walk witnessing
359/// χ ≥ 3. The walk is `v … root … u` (closed by the conflicting edge `u–v`); since `v` and `u` were
360/// found at the same colour their BFS depths share parity, so the walk has odd length.
361fn two_color(adj: &[Vec<bool>], n: usize) -> Result<Vec<usize>, Vec<usize>> {
362    let mut color = vec![usize::MAX; n];
363    let mut parent = vec![usize::MAX; n];
364    for start in 0..n {
365        if color[start] != usize::MAX {
366            continue;
367        }
368        color[start] = 0;
369        let mut stack = vec![start];
370        while let Some(v) = stack.pop() {
371            for u in 0..n {
372                if !adj[v][u] {
373                    continue;
374                }
375                if color[u] == usize::MAX {
376                    color[u] = 1 - color[v];
377                    parent[u] = v;
378                    stack.push(u);
379                } else if color[u] == color[v] {
380                    return Err(odd_walk(&parent, v, u));
381                }
382            }
383        }
384    }
385    Ok(color)
386}
387
388/// Reconstruct the odd closed walk `v → … → root → … → u` from the BFS parent forest (the edge
389/// `u–v` then closes it).
390fn odd_walk(parent: &[usize], v: usize, u: usize) -> Vec<usize> {
391    let to_root = |mut x: usize| {
392        let mut path = vec![x];
393        while parent[x] != usize::MAX {
394            x = parent[x];
395            path.push(x);
396        }
397        path
398    };
399    let mut walk = to_root(v); // v … root
400    let mut up_u = to_root(u); // u … root
401    up_u.reverse(); // root … u
402    walk.extend(up_u.into_iter().skip(1)); // … u (drop the duplicated root)
403    walk
404}
405
406/// Verify a vertex sequence is a genuine odd closed walk: every consecutive pair (including the
407/// wrap-around) is an edge, and the number of edges is odd — the property that makes it a checkable
408/// certificate of `χ ≥ 3`.
409fn is_odd_closed_walk(adj: &[Vec<bool>], walk: &[usize]) -> bool {
410    let m = walk.len();
411    m >= 3 && m % 2 == 1 && (0..m).all(|i| adj[walk[i]][walk[(i + 1) % m]])
412}
413
414fn decode(n: usize, k: usize, model: &[(String, bool)]) -> Vec<usize> {
415    let truth: HashMap<&str, bool> = model.iter().map(|(s, b)| (s.as_str(), *b)).collect();
416    let mut assignment = vec![0usize; n];
417    for m in 0..n {
418        for p in 0..k {
419            let key = format!("a_{m}_{p}");
420            if *truth.get(key.as_str()).unwrap_or(&false) {
421                assignment[m] = p;
422                break;
423            }
424        }
425    }
426    assignment
427}
428
429// ── English frontend (focused grammar) ──────────────────────────────────────
430
431/// Parse a focused English spec into an [`Intersection`].
432///
433/// Recognised:
434/// * `Movements: a, b, c.` — an optional explicit movement set (so isolated movements appear).
435/// * `<A> conflicts with <B>, <C> and <D>.` — `A` may not share a phase with any of `B`, `C`, `D`.
436///
437/// Movement names are everything else (articles `the`/`a`/`an` are dropped). Names are matched
438/// case-insensitively; the first spelling seen is the display name.
439pub fn parse_intersection(spec: &str) -> Result<Intersection, String> {
440    let mut names: Vec<String> = Vec::new();
441    let mut index: HashMap<String, usize> = HashMap::new();
442    let mut conflicts: Vec<(usize, usize)> = Vec::new();
443
444    for raw in spec.split(['.', '\n']) {
445        let sentence = raw.trim();
446        if sentence.is_empty() {
447            continue;
448        }
449        let lower = sentence.to_lowercase();
450
451        if let Some(mpos) = lower.find("movements:") {
452            let list = &lower[mpos + "movements:".len()..];
453            for m in split_list(list) {
454                intern_movement(&mut names, &mut index, &m);
455            }
456            continue;
457        }
458
459        if let Some(cpos) = lower.find("conflict") {
460            if let Some(wrel) = lower[cpos..].find("with") {
461                let subject = &lower[..cpos];
462                let objects = &lower[cpos + wrel + "with".len()..];
463                if let Some(si) = intern_movement(&mut names, &mut index, subject) {
464                    for obj in split_list(objects) {
465                        if let Some(oi) = intern_movement(&mut names, &mut index, &obj) {
466                            if si != oi {
467                                push_conflict(&mut conflicts, si, oi);
468                            }
469                        }
470                    }
471                }
472            }
473        }
474    }
475
476    if names.is_empty() {
477        return Err("no movements found — describe conflicts like \
478            \"northbound-left conflicts with southbound-through\""
479            .to_string());
480    }
481    Ok(Intersection {
482        movements: names,
483        conflicts,
484    })
485}
486
487fn intern_movement(
488    names: &mut Vec<String>,
489    index: &mut HashMap<String, usize>,
490    raw: &str,
491) -> Option<usize> {
492    let name = clean_name(raw);
493    if name.is_empty() {
494        return None;
495    }
496    let key = name.to_lowercase();
497    if let Some(&i) = index.get(&key) {
498        return Some(i);
499    }
500    let i = names.len();
501    names.push(name);
502    index.insert(key, i);
503    Some(i)
504}
505
506fn clean_name(raw: &str) -> String {
507    let mut s = raw
508        .trim()
509        .trim_matches(|c: char| c == '.' || c == ',' || c == ';' || c == ':')
510        .trim()
511        .to_string();
512    for article in ["the ", "a ", "an "] {
513        if s.to_lowercase().starts_with(article) {
514            s = s[article.len()..].trim().to_string();
515        }
516    }
517    s.split_whitespace().collect::<Vec<_>>().join(" ")
518}
519
520fn split_list(s: &str) -> Vec<String> {
521    s.replace(" and ", ",")
522        .replace('&', ",")
523        .split(',')
524        .map(|x| x.trim().to_string())
525        .filter(|x| !x.is_empty())
526        .collect()
527}
528
529fn push_conflict(conflicts: &mut Vec<(usize, usize)>, a: usize, b: usize) {
530    let pair = (a.min(b), a.max(b));
531    if !conflicts.contains(&pair) {
532        conflicts.push(pair);
533    }
534}
535
536#[cfg(test)]
537#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen_sva/signal_design/tests.rs"]
538mod tests;