Debugging a Model

Several kinds of errors can occur when developing an optimization model:

  1. your program may not compile
  2. you may see error messages when building the model
  3. you may suspect a design error in your model

This page covers the third kind of problem. That is to say that your program compiles without problem, the model is successfully created and the search starts, but the results obtained look abnormal either because no solution is found, or on the contrary because the objective function is too good to be correct, or because some variables remain stuck to 0 while much larger values would be expected.

In this case, the following points are good modeling practices for debugging your Hexaly model:

  • Introduce the constraint families and objectives one by one, and be mindful of implicit constraints
  • Enable warnings to identify modeling errors
  • Inject a feasible solution as an initial solution
  • Name the expressions to better understand the log messages
  • Display the values of the expressions
  • Compute the inconsistency core

Be mindful of implicit constraints

If your model contains many constraints or a complex objective function, a good starting point for understanding its behavior is to simplify it as much as possible, then gradually reintroduce its components one by one.

For example, if your model fails to find feasible solutions even though trivial feasible solutions should be easy to obtain, reintroducing constraints one by one can help you identify which family of constraints is causing the infeasibility.

Similarly, if satisfying all the constraints is not an issue, but the model becomes infeasible when you add a particular component of the objective function, you are likely dealing with an implicit constraint. An implicit constraint is a constraint induced by an expression used in the objective function. Indeed, a solution is feasible if and only if two conditions are met:

  • all constraints are satisfied (that is to say that no constraint takes value 0 or Not A Number)
  • the values of all objective functions are valid

For example, if the objective function contains a term sqrt(x+y), then it implicitly requires that x+y is positive. Similarly, a term a[x] can be undefined if x is out of the bounds of the array a. Such implicit requirements can make the problem infeasible or can dramatically restrict the set of feasible solutions.

For instance, in our Capacitated Vehicle Routing Problem (CVRP) code template, we need to compute the distance traveled by each truck to write the objective function (total traveled distance). Each truck is modeled using a list decision variable representing the sequence of customers it visits. If we write sequence the list decision variable representing the customers visited by truck k, and c the number of customers visited by truck k (count(sequence)), then the distance traveled by truck k is the sum of

  • the sum of distances from one customer to the next
  • if the truck is used, the distance from the depot to the first customer and from the last customer back to the depot
distRoutes[k] <- sum(1...c, i => distMatrix[sequence[i - 1]][sequence[i]])
        + (c > 0 ? (distDepot[sequence[0]] + distDepot[sequence[c - 1]]) : 0);
dist_lambda = model.lambda_function(lambda i: \
        model.at(dist_matrix, sequence[i - 1], sequence[i]))
dist_routes[k] = model.sum(model.range(1, c), dist_lambda) \
        + model.iif(c > 0, dist_depot[sequence[0]] + dist_depot[sequence[c - 1]], 0)
HxExpression distLambda = model.createLambdaFunction(
        [&](HxExpression i) { return model.at(distMatrix, sequence[i - 1], sequence[i]); });
distRoutes[k] = model.sum(model.range(1, c), distLambda)
        + model.iif(c > 0, distDepot[sequence[0]] + distDepot[sequence[c - 1]], 0);
HxExpression distLambda = model.LambdaFunction(
        i => distMatrix[sequence[i - 1], sequence[i]]);
distRoutes[k] = model.Sum(model.Range(1, c), distLambda)
        + model.If(c > 0, distDepot[sequence[0]] + distDepot[sequence[c - 1]], 0);
HxExpression distLambda = model.lambdaFunction(i ->
        model.at(distMatrix, model.at(sequence, model.sub(i, 1)), model.at(sequence, i)));
distRoutes[k] = model.sum(model.sum(model.range(1, c), distLambda),
        model.iif(model.gt(c, 0), model.sum(model.at(distDepot, model.at(sequence, 0)),
        model.at(distDepot, model.at(sequence, model.sub(c, 1)))), 0));

If the c > 0 test (checking whether the truck visits at least one customer) is missing in the computation of the route distance, then we will access distDepot[sequence[0]] for each route, which implicitly requires that each list of the model is non-empty. Indeed, this expression would otherwise be undefined (out of bounds). Consequently, the model will find feasible solutions, but it will have to use all trucks to do so, which can lead to unexpected behavior.

Take warnings into account

Warnings are a feature of Hexaly aiming at assisting users in the detection of modeling errors, including errors induced by implicit constraints. Modeling warnings are disabled by default but can be enabled by setting the parameter WarningLevel to 2:

hxWarningLevel = 2;
optimizer.param.warning_level = 2
optimizer.getParam().setWarningLevel(2);
optimizer.GetParam().SetWarningLevel(2);
optimizer.getParam().setWarningLevel(2);

The key concept is that, for a solution to be valid, all objectives and all constraints must take a well-defined value. For example, if an objective is the square root of a negative number, then the solution is invalid. It is also the case if this objective is a sum including such an undefined value. However, if this undefined square root has no impact on constraints and objectives, then the model remains perfectly valid. For instance, the following objective is perfectly legitimate:

minimize x >= 0 ? sqrt(x) : sqrt(-x);
model.minimize(model.iif(x >= 0, model.sqrt(x), model.sqrt(-x)))
model.minimize(model.iif(x >= 0, model.sqrt(x), model.sqrt(0 - x)));
model.Minimize(model.If(x >= 0, model.Sqrt(x), model.Sqrt(0 - x)));
model.minimize(model.iif(model.geq(x, 0), model.sqrt(x), model.sqrt(model.sub(0, x))));

Indeed, in this case, the objective value is always well-defined, even when one branch of the conditional statement is undefined.

When the computation of warnings is enabled, Hexaly performs an in-depth analysis of the model to determine whether all objectives and constraints are guaranteed to be well-defined. Note that in order to keep this analysis as fast as possible, it is not exhaustive and false positive and false negative results are possible. However, checking the part of the model mentioned in the warning is highly recommended.

As mentioned above, the main possible causes of undefined values are forbidden arithmetic operations (0/0, sqrt(-1), log(0), etc.), and array overflows. It is important to understand that these mistakes will not throw errors during the resolution of the model. They will only lead to discarding a (possibly large) part of the solution space.

Let us consider our Capacitated Vehicle Routing Problem (CVRP) code template, again. In this model, we count the distances to the depot only when a tour is non-empty:

(c > 0 ? (distDepot[sequence[0]] + distDepot[sequence[c - 1]]) : 0)
model.iif(c > 0, dist_depot[sequence[0]] + dist_depot[sequence[c - 1]], 0)
model.iif(c > 0, distDepot[sequence[0]] + distDepot[sequence[c - 1]], 0)
model.If(c > 0, distDepot[sequence[0]] + distDepot[sequence[c - 1]], 0)
model.iif(model.gt(c, 0), model.sum(model.at(distDepot, model.at(sequence, 0)),
        model.at(distDepot, model.at(sequence, model.sub(c, 1)))), 0)

Without this safeguard, the only valid solutions would be solutions where all lists are non-empty. This would lead to unexpected behavior: the solver would only produce solutions using all the trucks, even though much better solutions using only a fraction of the trucks may exist for certain low-demand instances.

When this model analysis feature is enabled, the following warning is issued and the user can easily identify the problem:

Warning: A risk of "Not a Number" error on objective (expression #13522): sum#13522
was identified. Please make sure that this expression will always be well-defined.
The probable cause is expression #2271: at(list#0(512), 0).

This warning clearly identifies that at least one list is accessed at index 0 with a risk of overflow (with no guarantee that the list is non-empty).

Inject a feasible solution as initial solution

A good way to identify what is leading to infeasible or poor solutions is to inject a simple feasible solution in your model. In our above vehicle routing example, any solution with at least one unused truck would be suitable.

Having set this initial solution, you can solve the problem with a time limit of 0 second. Typically, you may observe that the solution you injected is considered infeasible by your model. You will then see the main violated constraints displayed at the end of the trace:

0 iterations performed in 0 seconds

Infeasible solution:
No feasible solution found (infeas = 4)

Main violated expressions:
    objective sum(sum(range(1, sum#21 + 1),......) is NaN
    ... because of at(array(35, 78, 76, 98, 55), at(list#3(5), count(list#3(5)) + -1))

In this output, NaN codes for “Not a Number”, that is to say that the given objective is undefined. The “because of” line gives the origin of this NaN.

Naming the variables

To make the display clearer, you can name some of your expressions (decision variables, intermediate expressions, or even constant numbers) using the name attribute (or function setName in C++ and Java, or SetName in C#). For example, you can name the objective function totalDistance:

totalDistance.name = "totalDistance";
total_distance.name = "totalDistance"
totalDistance.setName("totalDistance");
totalDistance.SetName("totalDistance");
totalDistance.setName("totalDistance");

After naming some of the expressions, the previous console message becomes:

Main violated expressions:
    objective totalDistance is NaN
... because of at(distanceToWarehouse, at(tour3, count(tour3) + -1))

We can now see clearly that the problem is due to the distanceToWarehouse array being accessed at position count(tour3)-1. You can then deduce that the array is accessed at position -1 since tour3 is empty.

Displaying the expression values

To get an even better understanding of this solution, you can also display the value of any expression in the model using the value attribute (or functions getValue, getCollectionValue, getIntervalValue in C++ and Java, or GetValue, GetCollectionValue, GetIntervalValue in C#). You can also check whether an expression is undefined using the isUndefined method (or is_undefined in Python, or IsUndefined in C#).

If no constraint is violated, but the objective value is not what you expected, you can then retrieve the values of intermediate expressions to track mistakes in the definition of this objective function, underlying intermediate expressions, or in input data reading.

For example, after solving the Capacitated Vehicle Routing Problem (CVRP), you can print the value of the list customersSequences[0] and the objective function totalDistance:

function output() {
    println("sequence = ", customersSequences[0].value);
    println("totalDistance = ", totalDistance.value);
}
print("sequence =", customers_sequences[0].value)
print("totalDistance =", total_distance.value)
std::cout << "sequence = " << customersSequences[0].getCollectionValue().toString() << std::endl;
std::cout << "totalDistance = " << totalDistance.getValue() << std::endl;
Console.WriteLine("sequence = " + customersSequences[0].GetCollectionValue());
Console.WriteLine("totalDistance = " + totalDistance.GetValue());
System.out.println("sequence = " + customersSequences[0].getCollectionValue());
System.out.println("totalDistance = " + totalDistance.getValue());

For a solution where customersSequences[0] visits customers 4, 8, 7, and 2, and totalDistance is 1234, the output is:

sequence = { 4, 8, 7, 2 }
totalDistance = 1234

Compute the inconsistency core

Infeasibility vs. inconsistency

At the end of the resolution, the solver displays the solution status, which can be:

  • Optimal (the solver has found a feasible solution and a bound with the same value: optimality has been proven)
  • Feasible (the solver has found a feasible solution but has not proven that this solution is optimal)
  • Infeasible (no solution was found within the time limit, but it doesn’t mean that there exists no feasible solution. Given more time, the solver might have found one)
  • Inconsistent (the solver was able to prove that no feasible solution exists for this model)

Inconsistency Core

When the model has been proven inconsistent, it is possible to display some information explaining the inconsistency. Indeed, Hexaly offers the possibility to analyze the causes of this inconsistency by computing an irreducible inconsistency core: a minimal set of constraints that cannot all be verified together.

For example, consider an integer decision variable x between 0 and 10, constrained to be both at least 8 and at most 3. These two constraints cannot be satisfied together, so the model is inconsistent. The following code builds and solves this model, then computes and displays its inconsistency core:

function main() {
    with(optimizer = hexaly.create()) {
        x <- int(0, 10);
        x.name = "x";
        constraint x >= 8;
        constraint x <= 3;
        minimize x;

        optimizer.model.close();
        optimizer.solve();

        iis = optimizer.computeInconsistency();
        println(iis);
    }
}
with hexaly.optimizer.HexalyOptimizer() as optimizer:
    model = optimizer.model
    x = model.int(0, 10)
    x.name = "x"
    model.constraint(x >= 8)
    model.constraint(x <= 3)
    model.minimize(x)

    model.close()
    optimizer.solve()

    iis = optimizer.compute_inconsistency()
    print(iis)
HexalyOptimizer optimizer;
HxModel model = optimizer.getModel();
HxExpression x = model.intVar(0, 10);
x.setName("x");
model.constraint(x >= 8);
model.constraint(x <= 3);
model.minimize(x);

model.close();
optimizer.solve();

HxInconsistency iis = optimizer.computeInconsistency();
std::cout << iis.toString() << std::endl;
using (HexalyOptimizer optimizer = new HexalyOptimizer()) {
    HxModel model = optimizer.GetModel();
    HxExpression x = model.Int(0, 10);
    x.SetName("x");
    model.Constraint(x >= 8);
    model.Constraint(x <= 3);
    model.Minimize(x);

    model.Close();
    optimizer.Solve();

    HxInconsistency iis = optimizer.ComputeInconsistency();
    Console.WriteLine(iis);
}
try (HexalyOptimizer optimizer = new HexalyOptimizer()) {
    HxModel model = optimizer.getModel();
    HxExpression x = model.intVar(0, 10);
    x.setName("x");
    model.constraint(model.geq(x, 8));
    model.constraint(model.leq(x, 3));
    model.minimize(x);

    model.close();
    optimizer.solve();

    HxInconsistency iis = optimizer.computeInconsistency();
    System.out.println(iis);
}

The result of this function is an object of type HxInconsistency, which can be printed in a readable format. For this model, the inconsistency core log is:

Computing inconsistency core...
Irreducible inconsistency core found with 2 causes.
2 causes in inconsistency core:
  expression #0: constraint x >= 8
  expression #1: constraint x <= 3

Both constraints appear in the core: removing either one makes the model feasible.