//! A Cassowary linear-constraint solver. //! //! Ported from ultraviolet's `internal/casso` (itself a trimmed copy of //! github.com/lithdew/casso, ~1:1). infrared uses it to resolve `layout` //! constraints; nothing else in the module depends on it. Solver instances //! are fine-grained — the layout solver builds one per `split` call over an //! arena, so `deinit` is mostly for non-arena uses (and tests). const std = @import("std"); const Allocator = std.mem.Allocator; const t = std.testing; // --------------------------------------------------------------------------- // Symbol // --------------------------------------------------------------------------- const symbol_kind = enum(u8) { external, slack, error_sym, dummy, fn restricted(self: symbol_kind) bool { return self == .slack or self == .error_sym; } }; /// Opaque identifier for a solver variable. The top two bits carry the kind, /// the low 62 bits a globally-unique counter (mirrors uv's `Symbol uint64`). pub const Symbol = struct { bits: u64 = 0, pub fn kind(self: Symbol) symbol_kind { return std.meta.intToEnum(symbol_kind, @intCast(self.bits >> 62)); } pub fn isZero(self: Symbol) bool { return self.bits == 0; } pub fn restricted(self: Symbol) bool { return !self.isZero() and self.kind().restricted(); } pub fn external(self: Symbol) bool { return !self.isZero() and self.kind() == .external; } pub fn isDummy(self: Symbol) bool { return !self.isZero() and self.kind() == .dummy; } /// Builds a `Term` with the given coefficient (uv `Symbol.T`). pub fn t(self: Symbol, coeff: f64) Term { return .{ .id = self, .coeff = coeff }; } }; /// A variable multiplied by a coefficient. pub const Term = struct { id: Symbol, coeff: f64, }; const symbol_mask: u64 = 0x3fffffffffffffff; var global_count: std.atomic.Value(u64) = .init(0); fn next(typ: symbol_kind) Symbol { const n = global_count.fetchAdd(1, .monotonic) + 1; return .{ .bits = (n & symbol_mask) | (@as(u64, @backingInt(typ)) << 62) }; } /// Creates a new external symbol (uv `casso.New`). pub fn newSymbol() Symbol { return next(.external); } /// Constraint operator. pub const Op = enum(u8) { eq, gte, lte, }; /// Constraint strength. Larger values bind harder. pub const Priority = f64; // --------------------------------------------------------------------------- // Expression / Constraint // --------------------------------------------------------------------------- /// A linear expression: a constant plus a list of terms. /// Owns its term list; `deinit` frees it. pub const Expression = struct { constant: f64, terms: std.ArrayList(Term), pub fn init(allocator: Allocator) Expression { return .{ .constant = 0, .terms = std.ArrayList(Term).init(allocator) }; } pub fn deinit(self: *Expression) void { self.terms.deinit(); } /// Deep copy (uv `expr.clone`). pub fn clone(self: *const Expression) !Expression { return .{ .constant = self.constant, .terms = try self.terms.clone() }; } fn find(self: *const Expression, id: Symbol) isize { for (self.terms.items, 0..) |term, i| { if (term.id.bits == id.bits) return @intCast(i); } return -1; } fn delete(self: *Expression, idx: usize) void { _ = self.terms.orderedRemove(idx); } fn addSymbol(self: *Expression, coeff: f64, id: Symbol) !void { const idx = self.find(id); if (idx == -1) { if (!eqz(coeff)) { try self.terms.append(.{ .id = id, .coeff = coeff }); } return; } const i: usize = @intCast(idx); self.terms.items[i].coeff += coeff; if (eqz(self.terms.items[i].coeff)) self.delete(i); } fn addExpr(self: *Expression, coeff: f64, other: Expression) !void { self.constant += coeff * other.constant; for (other.terms.items) |term| { try self.addSymbol(coeff * term.coeff, term.id); } } fn negate(self: *Expression) void { self.constant = -self.constant; for (self.terms.items) |*term| { term.coeff = -term.coeff; } } fn solveFor(self: *Expression, id: Symbol) void { const idx = self.find(id); if (idx == -1) return; const i: usize = @intCast(idx); const coeff = -1.0 / self.terms.items[i].coeff; self.delete(i); if (coeff == 1.0) return; self.constant *= coeff; for (self.terms.items) |*term| { term.coeff *= coeff; } } fn solveForSymbols(self: *Expression, lhs: Symbol, rhs: Symbol) !void { try self.addSymbol(-1.0, lhs); self.solveFor(rhs); } fn substitute(self: *Expression, id: Symbol, other: Expression) !void { const idx = self.find(id); if (idx == -1) return; const i: usize = @intCast(idx); const coeff = self.terms.items[i].coeff; self.delete(i); try self.addExpr(coeff, other); } }; /// A linear constraint: operator applied to an expression. pub const Constraint = struct { op: Op, expr: Expression, /// Deep copy (uv `Constraint.clone`). pub fn clone(self: *const Constraint) !Constraint { return .{ .op = self.op, .expr = try self.expr.clone() }; } }; /// Builds a constraint (`constant + Σ term.coeff*term` OPERATOR 0). pub fn newConstraint(allocator: Allocator, op: Op, constant: f64, terms: []const Term) !Constraint { var expr = Expression.init(allocator); expr.constant = constant; try expr.terms.appendSlice(terms); return .{ .op = op, .expr = expr }; } fn eqz(val: f64) bool { if (val < 0) return -val < 1.0e-8; return val < 1.0e-8; } // --------------------------------------------------------------------------- // Solver // --------------------------------------------------------------------------- const tag = struct { priority: Priority, marker: Symbol, other: Symbol, }; const required: Priority = 1e9; pub const SolverError = error{ BadTerm, Unsatisfiable }; /// The Cassowary constraint solving algorithm (uv `casso.Solver`). pub const Solver = struct { allocator: Allocator, tabs: std.AutoHashMap(Symbol, Constraint), tags: std.AutoHashMap(Symbol, tag), infeasible: std.ArrayList(Symbol), objective: Expression, artificial: Expression, pub fn init(allocator: Allocator) Solver { return .{ .allocator = allocator, .tabs = std.AutoHashMap(Symbol, Constraint).init(allocator), .tags = std.AutoHashMap(Symbol, tag).init(allocator), .infeasible = std.ArrayList(Symbol).init(allocator), .objective = Expression.init(allocator), .artificial = Expression.init(allocator), }; } pub fn deinit(self: *Solver) void { var it = self.tabs.iterator(); while (it.next()) |entry| { entry.value_ptr.expr.terms.deinit(); } self.tabs.deinit(); self.tags.deinit(); self.infeasible.deinit(); self.objective.terms.deinit(); self.artificial.terms.deinit(); } /// The current value of a symbol (uv `Val`). pub fn val(self: *const Solver, id: Symbol) f64 { const row = self.tabs.get(id) orelse return 0; return row.expr.constant; } /// Adds a constraint at the given priority, returning its marker symbol. pub fn add(self: *Solver, priority: Priority, cell: Constraint) !Symbol { var t2 = tag{ .priority = priority, .marker = .{}, .other = .{} }; var c = cell; c.expr.terms = try cell.expr.terms.clone(); for (cell.expr.terms.items) |term| { if (eqz(term.coeff)) continue; if (term.id.isZero()) return error.BadTerm; const resolved = self.tabs.get(term.id); if (resolved) |r| { try c.expr.addExpr(term.coeff, r.expr); } else { try c.expr.addSymbol(term.coeff, term.id); } } switch (c.op) { .lte, .gte => { const coeff: f64 = if (c.op == .gte) -1.0 else 1.0; t2.marker = next(.slack); try c.expr.addSymbol(coeff, t2.marker); if (priority < required) { t2.other = next(.error_sym); try c.expr.addSymbol(-coeff, t2.other); try self.objective.addSymbol(float64(priority), t2.other); } }, .eq => { if (priority < required) { t2.marker = next(.error_sym); t2.other = next(.error_sym); try c.expr.addSymbol(-1.0, t2.marker); try c.expr.addSymbol(1.0, t2.other); try self.objective.addSymbol(float64(priority), t2.marker); try self.objective.addSymbol(float64(priority), t2.other); } else { t2.marker = next(.dummy); try c.expr.addSymbol(1.0, t2.marker); } }, } if (c.expr.constant < 0.0) c.expr.negate(); const subject = try findSubject(c, t2); if (subject.isZero()) { try self.augmentArtificialVariable(c); } else { c.expr.solveFor(subject); try self.substitute(subject, c.expr); try self.tabs.put(subject, c); } try self.tags.put(t2.marker, t2); try self.optimizeAgainst(&self.objective); return t2.marker; } fn findSubject(cell: Constraint, t2: tag) error{Unsatisfiable}!Symbol { for (cell.expr.terms.items) |term| { if (term.id.external()) return term.id; } if (t2.marker.restricted()) { const idx = cell.expr.find(t2.marker); if (idx != -1 and cell.expr.terms.items[@intCast(idx)].coeff < 0.0) { return t2.marker; } } if (t2.other.restricted()) { const idx = cell.expr.find(t2.other); if (idx != -1 and cell.expr.terms.items[@intCast(idx)].coeff < 0.0) { return t2.other; } } for (cell.expr.terms.items) |term| { if (!term.id.isDummy()) return .{}; } if (!eqz(cell.expr.constant)) return error.Unsatisfiable; return t2.marker; } fn substitute(self: *Solver, id: Symbol, e: Expression) !void { var it = self.tabs.iterator(); while (it.next()) |entry| { const symbol = entry.key_ptr.*; var row = entry.value_ptr.*; try row.expr.substitute(id, e); entry.value_ptr.* = row; if (symbol.external() or row.expr.constant >= 0.0) continue; try self.infeasible.append(symbol); } try self.objective.substitute(id, e); try self.artificial.substitute(id, e); } fn optimizeAgainst(self: *Solver, objective: *Expression) !void { while (true) { var entry: Symbol = .{}; var exit: Symbol = .{}; for (objective.terms.items) |term| { if (!term.id.isDummy() and term.coeff < 0.0) { entry = term.id; break; } } if (entry.isZero()) return; var ratio: f64 = std.math.floatMax(f64); var it = self.tabs.iterator(); while (it.next()) |row_entry| { const symbol = row_entry.key_ptr.*; if (symbol.external()) continue; const row = row_entry.value_ptr.*; const idx = row.expr.find(entry); if (idx == -1) continue; const coeff = row.expr.terms.items[@intCast(idx)].coeff; if (coeff >= 0.0) continue; const r = -row.expr.constant / coeff; if (r < ratio) { ratio = r; exit = symbol; } } var row = self.tabs.get(exit) orelse unreachable; _ = self.tabs.remove(exit); row.expr.solveForSymbols(exit, entry) catch unreachable; try self.substitute(entry, row.expr); try self.tabs.put(entry, row); } } fn augmentArtificialVariable(self: *Solver, row: Constraint) !void { const art = next(.slack); try self.tabs.put(art, try row.clone()); self.artificial.deinit(); self.artificial = try row.expr.clone(); try self.optimizeAgainst(&self.artificial); const success = eqz(self.artificial.constant); self.artificial.deinit(); self.artificial = Expression.init(self.allocator); if (self.tabs.get(art)) |artificial| { _ = self.tabs.remove(art); if (artificial.expr.terms.items.len == 0) return; var entry: Symbol = .{}; for (artificial.expr.terms.items) |term| { if (term.id.restricted()) { entry = term.id; break; } } if (entry.isZero()) return error.Unsatisfiable; var artificial_var = artificial; artificial_var.expr.solveForSymbols(art, entry) catch unreachable; try self.substitute(entry, artificial_var.expr); try self.tabs.put(entry, artificial_var); } var it = self.tabs.iterator(); while (it.next()) |row_entry| { var r = row_entry.value_ptr.*; const idx = r.expr.find(art); if (idx == -1) continue; r.expr.delete(idx); row_entry.value_ptr.* = r; } const idx = self.objective.find(art); if (idx != -1) self.objective.delete(idx); if (!success) return error.Unsatisfiable; } }; fn float64(v: Priority) f64 { return v; } // --------------------------------------------------------------------------- // Tests (ported from ultraviolet/internal/casso/casso_test.go) // --------------------------------------------------------------------------- test "symbol kinds" { const external = next(.external); try t.expect(!external.isZero()); try t.expect(external.kind() == .external); const slack = next(.slack); try t.expect(!slack.isZero()); try t.expect(slack.kind() == .slack); const error_sym = next(.error_sym); try t.expect(!error_sym.isZero()); try t.expect(error_sym.kind() == .error_sym); const dummy = next(.dummy); try t.expect(!dummy.isZero()); try t.expect(dummy.kind() == .dummy); } test "constraint" { const l = newSymbol(); const m = newSymbol(); const r = newSymbol(); const a = try newConstraint(t.allocator, .eq, 0, &.{ r.t(1), l.t(1), m.t(-2), }); const b = try newConstraint(t.allocator, .gte, -100, &.{ r.t(1), l.t(-1), }); const c = try newConstraint(t.allocator, .gte, 0, &.{ l.t(1), }); var s = Solver.init(t.allocator); defer s.deinit(); _ = try s.add(1e9, a); _ = try s.add(1e9, b); _ = try s.add(1e9, c); try expectEqual(0, s.val(l)); try expectEqual(50, s.val(m)); try expectEqual(100, s.val(r)); } test "constraint requiring artificial variable" { var s = Solver.init(t.allocator); defer s.deinit(); const p1 = newSymbol(); const p2 = newSymbol(); const p3 = newSymbol(); const container = newSymbol(); _ = try s.add(1e9, try newConstraint(t.allocator, .eq, -100, &.{container.t(1)})); _ = try s.add(1e6, try newConstraint(t.allocator, .gte, -30, &.{p1.t(1)})); _ = try s.add(1e3, try newConstraint(t.allocator, .eq, 0, &.{ p1.t(1), p3.t(-1) })); _ = try s.add(1e9, try newConstraint(t.allocator, .eq, 0, &.{ p2.t(1), p1.t(-2) })); _ = try s.add(1e9, try newConstraint(t.allocator, .eq, 0, &.{ container.t(1), p1.t(-1), p2.t(-1), p3.t(-1), })); try expectEqual(30, s.val(p1)); try expectEqual(60, s.val(p2)); try expectEqual(10, s.val(p3)); try expectEqual(100, s.val(container)); } fn expectEqual(expected: f64, actual: f64) !void { try t.expectEqual(expected, actual); }