The model as an evaluator: fix the decisions, solve the rest#

model_as_evaluator.ipynb Open In Colab Open In Deepnote Open In Kaggle Open In Gradient Open In SageMaker Studio Lab Powered by AMPL

Description: A local-search heuristic around an AMPL model: fixing the discrete decisions and solving the continuous rest with an NLP solver, checking every solve, ranking infeasible candidates with an elastic model, and comparing against the status-quo baseline

Tags: heuristics, fix-and-solve, modeling-tips, amplpy, nonlinear, local-optimization, facility-location, minlp

Notebook author: Gleb Belov <gleb@ampl.com>

References:

  1. Duran, M.A., Grossmann, I.E. (1986). An outer-approximation algorithm for a class of mixed-integer nonlinear programs. Mathematical Programming 36, 307-339 (the fixed-integer NLP subproblem).

  2. Fletcher, R. (1987). Practical Methods of Optimization, 2nd ed., ch. 12 (exact L1 penalty functions). Wiley.

  3. Fischetti, M., Lodi, A. (2003). Local branching. Mathematical Programming 98, 23-47.

# Install dependencies
%pip install -q amplpy numpy pandas
# Google Colab & Kaggle integration
from amplpy import AMPL, ampl_notebook

ampl = ampl_notebook(
    modules=["ipopt"],  # modules to install
    license_uuid="default",  # license to use
)  # instantiate AMPL object and register magics
SOLVER_NLP = "ipopt"  # local NLP solver for the evaluations: ipopt, knitro, conopt, ...
SOLVER_MINLP = (
    None  # optional reference: an MINLP solver for the full model, e.g. "couenne"
)

The idea#

When a mixed-integer model is too hard to solve as a whole, a common design keeps the model and uses it as an evaluator: a heuristic proposes values for the discrete decisions, they are fixed with fix, and a solver optimizes the continuous rest. What remains is the fixed-integer subproblem of outer approximation (Duran & Grossmann 1986): here a smooth convex NLP that a local solver handles well.

The model: facilities \(i\) with capacity \(\text{cap}_i\) and opening cost \(f_i\) serve customers \(j\) with demand \(d_j\). Shipping costs \(c_{ij}\) per unit, and an open facility has a congestion cost that grows as its load approaches capacity,

\[\alpha_i \frac{L_i}{\text{cap}_i - L_i}, \qquad L_i = \sum_j x_{ij} \le 0.9\,\text{cap}_i \,\text{Open}_i.\]

A parameter elastic switches on slack variables for unmet demand, priced high. This is used to rank candidates that would otherwise be infeasible.

import time

import numpy as np
import pandas as pd

MODEL = r"""
set I; set J;
param cap {I}; param dem {J}; param f {I}; param alpha {I}; param c {I, J};
param util_max := 0.9;
param elastic binary default 0;
param pen := 1000;
var Open {I} binary;
var X {I, J} >= 0;
var Unmet {j in J} >= 0, <= dem[j];
var Load {i in I} = sum {j in J} X[i,j];
minimize Total:
   sum {i in I} f[i] * Open[i] + sum {i in I, j in J} c[i,j] * X[i,j]
 + sum {i in I} alpha[i] * Load[i] / (cap[i] - Load[i])
 + (if elastic then pen * sum {j in J} Unmet[j]);
subject to Serve {j in J}: sum {i in I} X[i,j] + (if elastic then Unmet[j]) = dem[j];
subject to Capacity {i in I}: Load[i] <= util_max * cap[i] * Open[i];
"""

rng = np.random.default_rng(11)
nI, nJ = 15, 60
cap = rng.integers(80, 160, nI).astype(float)
dem = rng.integers(5, 20, nJ).astype(float)
f = rng.integers(400, 900, nI).astype(float)
alpha = rng.uniform(20, 60, nI).round(1)
xi, yi, xj, yj = rng.random(nI), rng.random(nI), rng.random(nJ), rng.random(nJ)
c = {
    (i, j): round(60 * float(np.hypot(xi[i] - xj[j], yi[i] - yj[j])), 2)
    for i in range(nI)
    for j in range(nJ)
}
current_open = set(rng.choice(nI, 8, replace=False).tolist())  # today's network

ampl = AMPL()
ampl.eval(MODEL)
ampl.set["I"] = range(nI)
ampl.set["J"] = range(nJ)
for name, values in [("cap", cap), ("dem", dem), ("f", f), ("alpha", alpha)]:
    ampl.param[name] = dict(enumerate(values.tolist()))
ampl.param["c"] = c
print(
    "total demand",
    dem.sum(),
    " capacity of today's network",
    0.9 * cap[list(current_open)].sum(),
)
total demand 787.0  capacity of today's network 826.2

One evaluator, checked every time#

evaluate fixes Open, solves, and returns a record. Three checks are built in, because a heuristic that trusts every solve ranks noise:

  1. The status. An infeasible solve still leaves values in the variables, and AMPL still reports an objective. That number means nothing.

  2. The point moved. A solver stopped by a limit can return the starting point unchanged.

  3. The objective is recomputed from the returned flows with independent code, and must match the solver’s value. This catches dropped terms, penalty slacks counted as cost, and sign errors.

def total_cost(open_set, X):
    """Independent recomputation of the true objective from a flow dictionary."""
    load = {i: sum(X.get((i, j), 0.0) for j in range(nJ)) for i in range(nI)}
    cost = sum(f[i] for i in open_set)
    cost += sum(c[i, j] * v for (i, j), v in X.items())
    cost += sum(
        alpha[i] * load[i] / (cap[i] - load[i]) for i in range(nI) if load[i] > 0
    )
    return cost


def evaluate(open_set, elastic=False):
    ampl.param["elastic"] = int(elastic)
    for i in range(nI):
        ampl.var["Open"][i].fix(1 if i in open_set else 0)
    before = ampl.var["X"].to_dict()
    start = time.time()
    ampl.solve(solver=SOLVER_NLP, verbose=False)
    record = dict(
        open=sorted(open_set),
        status=ampl.solve_result,
        seconds=round(time.time() - start, 2),
        objective=ampl.obj["Total"].value(),
    )
    X = ampl.var["X"].to_dict()
    record["moved"] = any(abs(X[k] - before.get(k, 0.0)) > 1e-9 for k in X)
    record["unmet"] = sum(ampl.var["Unmet"].to_dict().values()) if elastic else 0.0
    if record["status"] == "solved" and record["unmet"] < 1e-6:
        record["recomputed"] = total_cost(open_set, X)
        assert abs(record["recomputed"] - record["objective"]) <= 1e-6 * abs(
            record["objective"]
        ), "solver objective and recomputation disagree"
    record["ok"] = record["status"] == "solved" and record["moved"]
    return record

Closing three of today’s facilities leaves too little capacity. The plain evaluation is infeasible but still prints an objective; the elastic one gives a value with a meaning, mostly penalty, which a search can rank:

closing = set(sorted(current_open)[3:])
plain = evaluate(closing)
elastic = evaluate(closing, elastic=True)
pd.DataFrame([plain, elastic], index=["plain", "elastic"])[
    ["status", "objective", "unmet", "ok"]
]
status objective unmet ok
plain infeasible 17267.761530 0.000000 False
elastic solved 289639.816792 278.499994 True

Three baselines, not one#

  • Entering state: today’s network with today’s flows. Here each customer is served by the nearest open facility with spare capacity.

  • Status-quo optimum: today’s network, every discrete decision held, flows optimized. This is the baseline a heuristic must beat: it costs one solve and is often much better than the entering state.

  • The heuristic: below.

def entering_flows(open_set):
    X, room = {}, {i: 0.9 * cap[i] for i in open_set}
    for j in range(nJ):
        left = dem[j]
        for i in sorted(open_set, key=lambda i: c[i, j]):
            take = min(left, room[i])
            if take > 0:
                X[i, j] = take
                room[i] -= take
                left -= take
        assert left < 1e-9, "today's network cannot serve customer %d" % j
    return X


entering = total_cost(current_open, entering_flows(current_open))
status_quo = evaluate(current_open)
print(f"entering state      {entering:12.2f}")
print(f"status-quo optimum  {status_quo['objective']:12.2f}  ({status_quo['status']})")
entering state          20873.31
status-quo optimum      18273.19  (solved)

A local search with the evaluator#

First-improvement search over single changes: open one closed facility, or close one open facility. Candidates are compared by unmet demand first, then by objective, using the elastic model for every candidate so that all of them get a comparable value. The incumbent is the best feasible candidate. Every evaluation goes through the same function, the “one evaluator” rule: values from different procedures cannot be ranked against each other.

def better(a, b, tol=1e-6):
    """Less unmet demand first, then lower objective."""
    if abs(a["unmet"] - b["unmet"]) > tol:
        return a["unmet"] < b["unmet"]
    return a["objective"] < b["objective"] - tol * abs(b["objective"])


incumbent = evaluate(current_open, elastic=True)
history = [("status quo", incumbent["objective"])]
improved, n_eval = True, 1
while improved:
    improved = False
    for i in range(nI):
        candidate = set(incumbent["open"]) ^ {i}
        record = evaluate(candidate, elastic=True)
        n_eval += 1
        if record["ok"] and better(record, incumbent):
            incumbent = record
            history.append(
                (
                    "%s facility %d" % ("open" if i in candidate else "close", i),
                    record["objective"],
                )
            )
            improved = True
            break
final = evaluate(set(incumbent["open"]))  # report in the exact (non-elastic) model
print(f"{n_eval} evaluations; open facilities {final['open']}")
print(
    f"heuristic           {final['objective']:12.2f}  ({final['status']}, "
    f"recomputed {final['recomputed']:.2f})"
)
pd.DataFrame(history, columns=["move", "objective"])
55 evaluations; open facilities [1, 2, 4, 5, 7, 9, 10, 11, 13]
heuristic               14660.96  (solved, recomputed 14660.96)
move objective
0 status quo 18273.191743
1 open facility 0 17933.251940
2 open facility 2 15917.910632
3 close facility 0 15850.338005
4 open facility 5 15607.977459
5 close facility 6 15526.175625
6 open facility 7 15111.379408
7 close facility 12 14660.957336

Report the three numbers together. The improvement worth claiming is the heuristic’s over the status-quo optimum, not over the entering state.

pd.DataFrame(
    {"objective": [entering, status_quo["objective"], final["objective"]]},
    index=["entering state", "status-quo optimum", "heuristic"],
).round(2)
objective
entering state 20873.31
status-quo optimum 18273.19
heuristic 14660.96

Optional: a reference from an MINLP solver#

Set SOLVER_MINLP above to an MINLP solver available to you to see how far the heuristic is from the solver’s answer on this small instance. Remember that a local MINLP solver’s “optimal” is not a proof on a nonconvex model.

if SOLVER_MINLP:
    ampl.param["elastic"] = 0
    ampl.var["Open"].unfix()
    ampl.solve(solver=SOLVER_MINLP, verbose=False)
    print(
        SOLVER_MINLP,
        ampl.solve_result,
        round(ampl.obj["Total"].value(), 2),
        "open:",
        [i for i, v in ampl.var["Open"].to_dict().items() if v > 0.5],
    )
    if ampl.solve_result != "solved":
        print(ampl.get_value("solve_message"))
else:
    print("SOLVER_MINLP not set: skipped")
SOLVER_MINLP not set: skipped

Takeaways#

  • Fixing the discrete decisions and solving the continuous rest turns one hard model into many easy ones; AMPL’s fix/unfix (and drop/restore for rows) do it on one loaded model.

  • Check every solve: status, that the point moved, and an independently recomputed objective.

  • Rank infeasible candidates with an elastic version of the same model (slacks with an exact L1 penalty); report only exact-model values.

  • Compare against the status-quo optimum, not only the entering state.

More: https://colab.ampl.com/tags/heuristics.html, and the MP modeling guide section on reading solver results, https://mp.ampl.com/modeling-troublesh.html.