Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
147 changes: 147 additions & 0 deletions solutions/Z3.Linq.Tests/AssertSoftMaxSatTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
namespace Z3.Linq.Tests;

/// <summary>
/// The soft constraints of <see cref="Theorem{T}.SoftWhere"/>: weighted MaxSAT.
/// </summary>
/// <remarks>
/// A soft constraint is not required to hold. When it conflicts with the hard constraints or with a
/// heavier soft constraint, the optimizer leaves it unsatisfied and pays its weight, minimising the
/// total weight it leaves unsatisfied. Without it the DSL had only hard constraints, so "satisfy
/// this if you can, but prefer that one" could not be written at all: a violated constraint simply
/// made the theorem unsatisfiable.
/// </remarks>
[TestClass]
public class AssertSoftMaxSatTests
{
/// <summary>Two flags, which a hard XOR forces apart.</summary>
public class Flags
{
/// <summary>Gets or sets the first flag.</summary>
public bool A { get; set; }

/// <summary>Gets or sets the second flag.</summary>
public bool B { get; set; }
}

/// <summary>One integer, for the numeric form.</summary>
public class Cell
{
/// <summary>Gets or sets the value.</summary>
public int X { get; set; }
}

[TestMethod]
public void HigherWeightSoftConstraint_WinsConflict()
{
// The hard XOR admits exactly one of A and B, so the two soft constraints cannot both hold
// and the weights decide which one is sacrificed.
using var ctx = new Z3Context();

var result = ctx.NewTheorem<Flags>()
.Where(f => f.A ^ f.B)
.SoftWhere(f => f.A, weight: 10)
.SoftWhere(f => f.B, weight: 1)
.Solve();

result.ShouldNotBeNull();
result!.A.ShouldBeTrue();
result.B.ShouldBeFalse();
}

[TestMethod]
public void FlippingWeights_FlipsOutcome()
{
// The same theorem with the weights swapped: the outcome follows the weight, not the order
// the soft constraints were declared in.
using var ctx = new Z3Context();

var result = ctx.NewTheorem<Flags>()
.Where(f => f.A ^ f.B)
.SoftWhere(f => f.A, weight: 1)
.SoftWhere(f => f.B, weight: 10)
.Solve();

result.ShouldNotBeNull();
result!.A.ShouldBeFalse();
result.B.ShouldBeTrue();
}

[TestMethod]
public void CompatibleSoftConstraint_IsSatisfied()
{
// Nothing competes with it, so sacrificing it would buy nothing.
using var ctx = new Z3Context();

var result = ctx.NewTheorem<Flags>()
.Where(f => f.A ^ f.B)
.SoftWhere(f => f.A, weight: 5)
.Solve();

result.ShouldNotBeNull();
result!.A.ShouldBeTrue();
}

[TestMethod]
public void ImpossibleSoftConstraint_DoesNotMakeProblemUnsat()
{
// A soft constraint that contradicts a hard fact is paid for, and a model is still
// returned: this is the property that makes the constraint soft.
using var ctx = new Z3Context();

var result = ctx.NewTheorem<Flags>()
.Where(f => f.A)
.SoftWhere(f => !f.A, weight: 100)
.Solve();

result.ShouldNotBeNull();
result!.A.ShouldBeTrue();
}

[TestMethod]
[DataRow(0)]
[DataRow(-3)]
public void NonPositiveWeight_Throws(int weight)
{
// Z3 takes an unsigned weight, and a weight of zero would mean "free to violate" - a
// programming error rather than a trade-off, so it fails at the call rather than on solve.
using var ctx = new Z3Context();

Should.Throw<ArgumentOutOfRangeException>(
() => ctx.NewTheorem<Flags>().SoftWhere(f => f.A, weight));
}

[TestMethod]
public void NumericSoftConstraints_HigherWeightTargetWins()
{
// Two values wanted by constraints of different weight, over the same symbol.
using var ctx = new Z3Context();

var result = ctx.NewTheorem<Cell>()
.Where(c => c.X >= 0 && c.X <= 9)
.SoftWhere(c => c.X == 3, weight: 2)
.SoftWhere(c => c.X == 7, weight: 5)
.Solve();

result.ShouldNotBeNull();
result!.X.ShouldBe(7);
}

[TestMethod]
public void SoftWhereThenWhere_KeepsTheSoftConstraint()
{
// A hard constraint added after a soft one must not drop it: the two lists travel separately
// through the Where chain, and losing one there would silently turn a trade-off into a
// requirement.
using var ctx = new Z3Context();

var result = ctx.NewTheorem<Flags>()
.SoftWhere(f => f.A, weight: 10)
.SoftWhere(f => f.B, weight: 1)
.Where(f => f.A ^ f.B)
.Solve();

result.ShouldNotBeNull();
result!.A.ShouldBeTrue();
result.B.ShouldBeFalse();
}
}
71 changes: 66 additions & 5 deletions solutions/Z3.Linq/Theorem.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,24 @@ public class Theorem
/// </summary>
private readonly object? template;

/// <summary>
/// The soft (weighted MaxSAT) constraints, which a solve may leave violated at a cost.
/// </summary>
private readonly IEnumerable<SoftConstraint> softConstraints;

/// <summary>
/// Z3 context under which the theorem is solved.
/// </summary>
private readonly Z3Context context;

/// <summary>
/// A soft constraint: a Boolean the solve may leave violated, at the cost of its weight.
/// </summary>
/// <param name="Constraint">The constraint expression.</param>
/// <param name="Weight">The cost of leaving the constraint violated; strictly positive.</param>
/// <param name="Group">The MaxSAT group the constraint belongs to.</param>
protected internal readonly record struct SoftConstraint(LambdaExpression Constraint, int Weight, string Group);

/// <summary>
/// Creates a new theorem for the given Z3 context.
/// </summary>
Expand Down Expand Up @@ -61,17 +74,39 @@ protected Theorem(Z3Context context, IEnumerable<LambdaExpression> constraints)
/// or <see langword="null"/>. See #78.
/// </param>
protected Theorem(Z3Context context, IEnumerable<LambdaExpression> constraints, object? template)
: this(context, constraints, template, [])
{
}

/// <summary>
/// Creates a new pre-constrained theorem for the given Z3 context, with a template instance and
/// soft constraints.
/// </summary>
/// <param name="context">Z3 context.</param>
/// <param name="constraints">Constraints to apply to the created theorem.</param>
/// <param name="template">
/// An instance of the environment type whose collections supply a length to the solution's,
/// or <see langword="null"/>. See #78.
/// </param>
/// <param name="softConstraints">Weighted soft constraints to apply to the created theorem.</param>
protected Theorem(Z3Context context, IEnumerable<LambdaExpression> constraints, object? template, IEnumerable<SoftConstraint> softConstraints)
{
this.context = context;
this.constraints = constraints;
this.template = template;
this.softConstraints = softConstraints;
}

/// <summary>
/// Gets the constraints of the theorem.
/// </summary>
protected IEnumerable<LambdaExpression> Constraints => constraints;

/// <summary>
/// Gets the soft constraints of the theorem.
/// </summary>
protected IEnumerable<SoftConstraint> SoftConstraints => softConstraints;

/// <summary>
/// Gets the template instance the theorem was created from, if any.
/// </summary>
Expand Down Expand Up @@ -121,20 +156,31 @@ protected bool TrySolve<T>([MaybeNullWhen(false)] out T result, CancellationToke
using Context ctx = this.context.CreateContext();
var environment = GetEnvironment(ctx, typeof(T));

// Solver solver = context.MkSimpleSolver();
Solver solver = ctx.MkSolver();
// A soft constraint needs an optimizer: AssertSoft defines an implicit objective - minimise
// the total weight left unsatisfied - that a solver has nowhere to put. A theorem without
// any soft constraint takes the plain solver, as before.
Z3Object approach = this.softConstraints.Any()
? ctx.MkOptimize()
: ctx.MkSolver();

AssertConstraints<T>(ctx, solver, environment);
AssertConstraints<T>(ctx, approach, environment);

Status status = this.Check(ctx, solver, cancellationToken);
Status status = this.Check(ctx, approach, cancellationToken);

if (status != Status.SATISFIABLE)
{
result = default;
return false;
}

result = GetSolution<T>(ctx, solver.Model, environment, this.template);
Model model = approach switch
{
Solver solver => solver.Model,
Optimize optimizer => optimizer.Model,
_ => throw new ArgumentException("Expected a Solver or an Optimize.", nameof(approach)),
};

result = GetSolution<T>(ctx, model, environment, this.template);
return true;
}

Expand Down Expand Up @@ -325,6 +371,21 @@ private void AssertConstraints<T>(Context context, Z3Object approach, Environmen
}

AssertBounds(context, approach, environment);

// Soft constraints: only an optimizer can carry them, each with its weight and group, so
// that Z3 minimises the total weight of the ones it leaves unsatisfied. The solve path
// routes through an optimizer whenever a soft constraint exists, which is the only way this
// branch is ever reached.
if (approach is Optimize softOptimizer)
{
foreach (var soft in this.softConstraints)
{
BoolExpr softExpression = (BoolExpr)ExpressionVisitor.Translate(context, environment, soft.Constraint.Body, soft.Constraint.Parameters[0]);

softOptimizer.AssertSoft(softExpression, (uint)soft.Weight, soft.Group);
this.context.LogWriteLine($"[soft w={soft.Weight} g={soft.Group}] {softExpression}");
}
}
}

/// <summary>
Expand Down
55 changes: 55 additions & 0 deletions solutions/Z3.Linq/Theorem{T}.cs
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ internal Theorem(Z3Context context, IEnumerable<LambdaExpression> constraints, o
{
}

/// <summary>
/// Creates a new pre-constrained theorem for the given Z3 context, with soft constraints.
/// </summary>
/// <param name="context">Z3 context.</param>
/// <param name="constraints">Constraints to apply to the created theorem.</param>
/// <param name="template">The template instance of the theorem being extended, or null.</param>
/// <param name="softConstraints">Weighted soft constraints to apply to the created theorem.</param>
internal Theorem(Z3Context context, IEnumerable<LambdaExpression> constraints, object? template, IEnumerable<Theorem.SoftConstraint> softConstraints)
: base(context, constraints, template, softConstraints)
{
}

/// <summary>
/// Solves the theorem.
/// </summary>
Expand Down Expand Up @@ -180,6 +192,49 @@ public Theorem<T> Where(Expression<Func<T, bool>> constraint)
return new Theorem<T>(base.Context, base.Constraints.Concat([constraint]), base.Template);
}

/// <summary>
/// Soft where query operator: a constraint the solve may leave violated, at the cost of
/// <paramref name="weight"/>.
/// </summary>
/// <param name="constraint">Theorem constraint expression.</param>
/// <param name="weight">
/// The cost of leaving the constraint violated. When two soft constraints cannot both hold,
/// the solve sacrifices the one with the lower weight, minimising the total weight left
/// unsatisfied.
/// </param>
/// <param name="group">The MaxSAT group the constraint belongs to.</param>
/// <returns>Theorem with the new soft constraint applied.</returns>
/// <remarks>
/// <para>
/// Unlike <see cref="Where(Expression{Func{T, bool}})"/>, a soft constraint is not required to
/// hold. When it conflicts with the hard constraints or with a heavier soft constraint, the
/// solve leaves it unsatisfied and pays <paramref name="weight"/>, minimising the total weight
/// of what it leaves unsatisfied. A heavier constraint is therefore honoured in preference to a
/// lighter one, which is what makes a weight a statement of priority rather than of importance.
/// </para>
/// <para>
/// A theorem carrying at least one soft constraint is checked through an optimizer, since an
/// implicit objective has nowhere to live on a plain solver.
/// </para>
/// </remarks>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="weight"/> is zero or negative: a sacrifice that costs nothing cannot be
/// traded against one that does.
/// </exception>
public Theorem<T> SoftWhere(Expression<Func<T, bool>> constraint, int weight, string group = "default")
{
if (weight <= 0)
{
throw new ArgumentOutOfRangeException(nameof(weight), weight, "Soft-constraint weight must be strictly positive.");
}

return new Theorem<T>(
base.Context,
base.Constraints,
base.Template,
base.SoftConstraints.Concat([new SoftConstraint(constraint, weight, group)]));
}

/// <summary>
/// OrderBy query operator, used to optimize a solution using query expression syntax.
/// </summary>
Expand Down