logicaffeine_compile/codegen_sva/
signal_design.rs1use logicaffeine_proof::sat::{prove_unsat, UnsatOutcome};
15use logicaffeine_proof::ProofExpr;
16use std::collections::HashMap;
17
18#[derive(Clone, Debug, PartialEq)]
20pub struct Intersection {
21 pub movements: Vec<String>,
23 pub conflicts: Vec<(usize, usize)>,
25}
26
27impl Intersection {
28 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#[derive(Clone, Debug, PartialEq)]
38pub struct PhasePlan {
39 pub num_phases: usize,
41 pub assignment: Vec<usize>,
43 pub minimal_certified: bool,
46}
47
48impl PhasePlan {
49 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
61pub 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
77pub 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 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 let lb = clique.len().max(3);
124 let (greedy_colors, ub) = greedy_coloring(&adj, n);
125
126 if lb >= ub {
129 return Some(PhasePlan {
130 num_phases: ub,
131 assignment: greedy_colors,
132 minimal_certified: true,
133 });
134 }
135
136 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 Some(PhasePlan {
156 num_phases: ub,
157 assignment: greedy_colors,
158 minimal_certified: prev_infeasible_certified,
159 })
160}
161
162pub 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
169enum ColoringResult {
172 Feasible(Vec<usize>),
173 Infeasible,
174 Unknown,
175}
176
177#[cfg(test)]
180thread_local! {
181 static SAT_SOLVE_COUNT: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
182}
183
184#[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
210fn 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
240fn 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 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 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 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 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
286fn 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
301fn 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(°(a)).then(a.cmp(&b)));
307 order
308}
309
310fn 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
333fn 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
357fn 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
388fn 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); let mut up_u = to_root(u); up_u.reverse(); walk.extend(up_u.into_iter().skip(1)); walk
404}
405
406fn 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
429pub 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;