Diverse alternatives: beyond the solution pool#
Description: Generate near-optimal alternatives that really differ: a solution pool against max-min Modelling to Generate Alternatives (MGA) on a unit commitment model, with the budget as a constraint or as an objective hierarchy
Tags: mp, mga, alternative-solutions, solution-pool, multi-objective, suffixes, unit-commitment, energy, milp, amplpy, highs, gurobi
Notebook author: Gleb Belov <gleb@ampl.com>
References:
Brill, E.D., Chang, S.-Y., Hopkins, L.D. (1982). Modeling to generate alternatives: the HSJ approach and an illustration using a problem in land use planning. Management Science 28(3), 221-235.
Trapp, A.C., Konrad, R.A. (2015). Finding diverse optima and near-optima to binary integer programs. IIE Transactions 47(11), 1300-1312.
DeCarolis, J.F. (2011). Using modeling to generate alternatives (MGA) to expand our thinking on energy futures. Energy Economics 33(2), 145-152.
MP solver features, solution pool and multiple objectives: https://mp.ampl.com/features-guide.html
# Install dependencies
%pip install -q amplpy pandas
# Google Colab & Kaggle integration
from amplpy import AMPL, ampl_notebook
ampl = ampl_notebook(
modules=["highs", "gurobi"], # modules to install
license_uuid="default", # license to use
) # instantiate AMPL object and register magics
The point#
One optimal plan is rarely the end of the story: a planner wants alternatives that are nearly as cheap but really different, to keep options open when something the model does not know changes. Two ways to get them:
a solution pool: the feasible plans the solver met during its search, within a gap of the best one. Cheap to ask for, but its members are often near-duplicates, because they come from the same neighbourhood of the search;
diversity on purpose, Modelling to Generate Alternatives (MGA): within a cost budget, ask for the plan that is as far as possible from the nearest plan found so far, and repeat. This is the max-min variant of MGA.
This notebook builds both for a small unit commitment model and measures how different the plans really are.
SOLVER = "highs" # the MGA rounds: any MP-based MILP solver
SOLVER_POOL = (
"gurobi" # a solver with a solution pool: gurobi, xpress, cplex, copt, scip, ...
)
The model#
The same unit commitment model as in the IIS notebook of this series: units on or off (On), output P, starts and
stops with minimum up and down times, demand, spinning reserve and inertia in every period. The cost is a defined
variable Cost, so the cost budget below can reuse it in a constraint.
MODEL = r"""
set UNITS;
param T integer > 0;
set HOURS := 1..T;
param dt > 0; # hours per period
param demand {HOURS} >= 0; # MW
param reserve {HOURS} >= 0; # spinning reserve required, MW
param min_online integer >= 0; # units online, for system inertia
param pmin {UNITS} >= 0;
param pmax {g in UNITS} >= pmin[g];
param ramp {UNITS} > 0; # MW per period
param minup {UNITS} integer >= 1;
param mindn {UNITS} integer >= 1;
param fuel {UNITS} >= 0; # $/MWh
param noload {UNITS} >= 0; # $/h while on
param startcost {UNITS} >= 0; # $ per start
param emis {UNITS} >= 0; # t CO2 per MWh
param on0 {UNITS} binary; # on before the horizon
param p0 {UNITS} >= 0; # output before the horizon
var On {UNITS, HOURS} binary;
var Start {UNITS, HOURS} >= 0, <= 1;
var Stop {UNITS, HOURS} >= 0, <= 1;
var P {g in UNITS, HOURS} >= 0, <= pmax[g];
var Cost = sum {g in UNITS, t in HOURS}
(dt * (fuel[g] * P[g,t] + noload[g] * On[g,t]) + startcost[g] * Start[g,t]);
minimize Total_Cost: Cost;
subject to Output_Lo {g in UNITS, t in HOURS}: P[g,t] >= pmin[g] * On[g,t];
subject to Output_Up {g in UNITS, t in HOURS}: P[g,t] <= pmax[g] * On[g,t];
subject to Balance {t in HOURS}: sum {g in UNITS} P[g,t] = demand[t];
subject to Spinning_Reserve {t in HOURS}:
sum {g in UNITS} (pmax[g] * On[g,t] - P[g,t]) >= reserve[t];
subject to Inertia {t in HOURS}: sum {g in UNITS} On[g,t] >= min_online;
subject to Switch {g in UNITS, t in HOURS}:
Start[g,t] - Stop[g,t] = On[g,t] - (if t = 1 then on0[g] else On[g,t-1]);
subject to Ramp_Up {g in UNITS, t in HOURS}:
P[g,t] - (if t = 1 then p0[g] else P[g,t-1]) <= ramp[g] + pmax[g] * Start[g,t];
subject to Ramp_Down {g in UNITS, t in HOURS}:
(if t = 1 then p0[g] else P[g,t-1]) - P[g,t] <= ramp[g] + pmax[g] * Stop[g,t];
subject to Min_Up {g in UNITS, t in HOURS}:
sum {s in max(1, t - minup[g] + 1) .. t} Start[g,s] <= On[g,t];
subject to Min_Down {g in UNITS, t in HOURS}:
sum {s in max(1, t - mindn[g] + 1) .. t} Stop[g,s] <= 1 - On[g,t];
"""
import pandas as pd
# A small thermal fleet: seven units of four types, twelve 2-hour periods
units = pd.DataFrame(
{
"pmin": [300, 120, 80, 20, 300, 120, 80], # MW
"pmax": [500, 350, 250, 100, 500, 350, 250], # MW
"ramp": [60, 80, 120, 100, 60, 80, 120], # MW per period
"minup": [12, 6, 2, 1, 12, 6, 2], # periods
"mindn": [12, 5, 2, 1, 12, 5, 2], # periods
"fuel": [9, 24, 38, 75, 9, 25, 39], # $/MWh
"noload": [800, 500, 300, 100, 800, 500, 300], # $/h while on
"startcost": [9000, 6000, 2000, 400, 9000, 6000, 2000], # $ per start
"emis": [0, 0.95, 0.37, 0.55, 0, 0.969, 0.3774], # t CO2 per MWh
"on0": [1, 1, 0, 0, 1, 1, 0], # on before the horizon
"p0": [400, 200, 0, 0, 400, 200, 0], # MW before the horizon
},
index=["NUKE1", "COAL1", "CCGT1", "GT1", "NUKE2", "COAL2", "CCGT2"],
)
demand = [1027, 960, 1093, 1325, 1557, 1490, 1027, 960, 1557, 1656, 1457, 1093] # MW
def load(units, reserve_frac, demand=demand, model=MODEL):
"""Reset the AMPL session, read the model and feed the data."""
ampl.reset()
ampl.eval(model)
ampl.set_data(units, "UNITS")
ampl.param["T"] = len(demand)
ampl.param["dt"] = 2
ampl.param["min_online"] = 2
ampl.param["demand"] = {t + 1: d for t, d in enumerate(demand)}
ampl.param["reserve"] = {
t + 1: round(reserve_frac * d) for t, d in enumerate(demand)
}
units
| pmin | pmax | ramp | minup | mindn | fuel | noload | startcost | emis | on0 | p0 | |
|---|---|---|---|---|---|---|---|---|---|---|---|
| NUKE1 | 300 | 500 | 60 | 12 | 12 | 9 | 800 | 9000 | 0.0000 | 1 | 400 |
| COAL1 | 120 | 350 | 80 | 6 | 5 | 24 | 500 | 6000 | 0.9500 | 1 | 200 |
| CCGT1 | 80 | 250 | 120 | 2 | 2 | 38 | 300 | 2000 | 0.3700 | 0 | 0 |
| GT1 | 20 | 100 | 100 | 1 | 1 | 75 | 100 | 400 | 0.5500 | 0 | 0 |
| NUKE2 | 300 | 500 | 60 | 12 | 12 | 9 | 800 | 9000 | 0.0000 | 1 | 400 |
| COAL2 | 120 | 350 | 80 | 6 | 5 | 25 | 500 | 6000 | 0.9690 | 1 | 200 |
| CCGT2 | 80 | 250 | 120 | 2 | 2 | 39 | 300 | 2000 | 0.3774 | 0 | 0 |
load(units, reserve_frac=0.08)
ampl.solve(solver=SOLVER, verbose=False)
c_star = ampl.get_value("Cost")
print(ampl.solve_result, " optimal cost", round(c_star))
solved optimal cost 483106
Which variables count: primary and secondary#
Distance should count the decisions a planner reads off the plan, not the variables that follow from them. Here the
primary decisions are the on/off states On[g,t]; Start and Stop are secondary, determined by On, and
counting them would reward differences that are only consequences. The output P is primary too, but this notebook
counts the commitment only; the last section adds output levels.
For binaries, the distance between a plan \(x\) and a reference \(r\) is linear:
A helper shows a plan as one string per unit, 1 for on:
def commitment():
on = ampl.get_variable("On").get_values().to_dict()
return {
g: "".join(str(round(on[g, t])) for t in range(1, len(demand) + 1))
for g in units.index
}
def distance(a, b):
return sum(x != y for g in a for x, y in zip(a[g], b[g]))
best = commitment()
best
{'NUKE1': '111111111111',
'COAL1': '111111111110',
'CCGT1': '000111001100',
'GT1': '000000000000',
'NUKE2': '111111111111',
'COAL2': '000000001111',
'CCGT2': '000011000000'}
The solution pool#
Ask the pool solver for up to six plans within 1 % of the best. Each plan is written to a .sol file and read back
into the session with AMPL’s solution command (amplpy’s get_output runs it and keeps its messages out of the
notebook):
import os, tempfile
stub = os.path.join(tempfile.mkdtemp(), "pool")
load(units, reserve_frac=0.08)
ampl.solve(
solver=SOLVER_POOL,
**{
f"{SOLVER_POOL}_options": f"sol:stub={stub} sol:poollimit=6 sol:poolmode=2 sol:poolgap=0.01"
},
verbose=False,
)
pool = []
for k in range(1, int(ampl.get_value("Initial.nsol")) + 1):
ampl.get_output(f'solution "{stub}{k}.sol";') # load plan k
pool.append((ampl.get_value("Cost"), commitment()))
print(
len(pool),
"plans; cost above the best, %:",
[round(100 * (c / c_star - 1), 2) for c, _ in pool],
)
6 plans; cost above the best, %: [0.0, 0.04, 0.07, 0.11, 0.19, 0.27]
def pairwise(plans):
# closest pair and the distance matrix of a list of commitments
m = [[distance(a, b) for b in plans] for a in plans]
closest = min(m[i][j] for i in range(len(plans)) for j in range(i + 1, len(plans)))
return closest, pd.DataFrame(m)
closest_pool, m_pool = pairwise([p for _, p in pool])
print("pool: closest pair differs in", closest_pool, "on/off decisions")
m_pool
pool: closest pair differs in 2 on/off decisions
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| 0 | 0 | 2 | 4 | 6 | 4 | 8 |
| 1 | 2 | 0 | 6 | 4 | 6 | 10 |
| 2 | 4 | 6 | 0 | 2 | 8 | 4 |
| 3 | 6 | 4 | 2 | 0 | 10 | 6 |
| 4 | 4 | 6 | 8 | 10 | 0 | 4 |
| 5 | 8 | 10 | 4 | 6 | 4 | 0 |
The pool members are cheap, but several differ in only a handful of on/off decisions: they are variations of the same plan. (Pools differ between solvers: SCIP, for one, returns only the incumbents its search found, here two copies of the optimum.)
Diversity on purpose: max-min MGA#
Add to the model, as AMPL declarations:
REFS, the plans found so far, andref[k,g,t], their on/off states;z, the distance to the nearest earlier plan: one rowz <= D(x, ref_k)per earlier plan;the budget, a row on the defined variable
Cost: at most 1 % above the optimum;the objective
maximize Diversity: z.
Each round solves the model with this objective, stores the new plan as one more reference and repeats. (Max-min diversity: Trapp and Konrad, 2015; MGA: Brill, Chang and Hopkins, 1982.)
MGA = r"""
set REFS ordered default {};
param ref {REFS, UNITS, HOURS} default 0;
param cap; # the cost budget
var z >= 0;
subject to Budget: Cost <= cap; # reuses the defined variable Cost
subject to Distance {k in REFS}:
z <= sum {g in UNITS, t in HOURS}
(if ref[k,g,t] = 1 then 1 - On[g,t] else On[g,t]);
maximize Diversity: z;
"""
def store(k):
# the current plan becomes reference k
ampl.eval(f"let REFS := REFS union {{{k}}};")
ampl.eval(f"let {{g in UNITS, t in HOURS}} ref[{k},g,t] := round(On[g,t]);")
def mga(rounds=6, eps=0.01, solver_options=""):
load(units, reserve_frac=0.08, model=MODEL + MGA)
ampl.param["cap"] = 1e30
ampl.eval("objective Total_Cost;")
ampl.solve(solver=SOLVER, verbose=False) # round 1: the optimum
c0 = ampl.get_value("Cost")
ampl.param["cap"] = c0 * (1 + eps)
store(1)
plans, zs = [commitment()], []
ampl.eval("objective Diversity;")
for k in range(2, rounds + 1):
ampl.solve(
solver=SOLVER, **{f"{SOLVER}_options": solver_options}, verbose=False
)
z = ampl.get_value("z")
if ampl.solve_result not in ("solved", "limit") or z < 0.5:
break # nothing farther within the budget (or the round found no new plan)
zs.append(round(z))
plans.append(commitment())
store(k)
return plans, zs
plans, zs = mga()
print("z per round (distance to the nearest earlier plan):", zs)
print(
"costs, % above the optimum:",
round(100 * (ampl.get_value("Cost") / c_star - 1), 2),
"(last plan)",
)
z per round (distance to the nearest earlier plan): [26, 11, 9, 8, 7]
costs, % above the optimum: 1.0 (last plan)
closest_mga, m_mga = pairwise(plans)
print(
"MGA: closest pair differs in", closest_mga, "on/off decisions; pool:", closest_pool
)
m_mga
MGA: closest pair differs in 7 on/off decisions; pool: 2
| 0 | 1 | 2 | 3 | 4 | 5 | |
|---|---|---|---|---|---|---|
| 0 | 0 | 26 | 11 | 19 | 9 | 8 |
| 1 | 26 | 0 | 23 | 9 | 23 | 22 |
| 2 | 11 | 23 | 0 | 28 | 8 | 7 |
| 3 | 19 | 9 | 28 | 0 | 26 | 27 |
| 4 | 9 | 23 | 8 | 26 | 0 | 7 |
| 5 | 8 | 22 | 7 | 27 | 7 | 0 |
Every MGA plan stays within the same 1 % budget as the pool, and the closest two now differ in many more on/off
decisions. Note the order: the first alternative is the farthest from the optimum, and each later round is limited
by the nearest of the plans already found, so z does not increase.
Here are the optimum and the first alternative, unit by unit (1: on):
pd.DataFrame({"optimum": plans[0], "first alternative": plans[1]})
| optimum | first alternative | |
|---|---|---|
| NUKE1 | 111111111111 | 111111111111 |
| COAL1 | 111111111110 | 000000001111 |
| CCGT1 | 000111001100 | 000011000000 |
| GT1 | 000000000000 | 000001000000 |
| NUKE2 | 111111111111 | 111111111111 |
| COAL2 | 000000001111 | 111111111110 |
| CCGT2 | 000011000000 | 000110001100 |
The first alternative swaps the roles of the two coal units. They are nearly identical (the same limits and start cost, fuel 24 against 25 $/MWh), so to an operator the two plans may be one plan with the units renamed. The distance counts such a swap in full, and MGA, which maximises that distance, gladly uses it.
Twins: distance by unit type#
Count instead how many units of each type (NUKE, COAL, CCGT, GT) are on in each period. A swap of two
twins then counts 0, and one more unit of a type counts 1:
def kind(g):
return g.rstrip("0123456789") # COAL1 -> COAL
def counts(plan):
# units on per type and period
c = {}
for g, bits in plan.items():
for t, b in enumerate(bits):
c[kind(g), t] = c.get((kind(g), t), 0) + int(b)
return c
def by_type(a, b):
ca, cb = counts(a), counts(b)
return sum(abs(ca[k] - cb[k]) for k in ca)
def closest_by_type(plans):
return min(
by_type(plans[i], plans[j])
for i in range(len(plans))
for j in range(i + 1, len(plans))
)
print("optimum and first alternative:", distance(plans[0], plans[1]), "decisions,",
by_type(plans[0], plans[1]), "by type")
print("closest pair by type: pool", closest_by_type([p for _, p in pool]),
" MGA", closest_by_type(plans))
optimum and first alternative: 26 decisions, 2 by type
closest pair by type: pool 0 MGA 1
The optimum and the first alternative differ in 26 on/off decisions but, by type, in only 2: almost all of the distance is the coal swap. By type, the pool’s closest pair is 0, a pure swap, and the MGA set’s is 1.
To ask for diversity in the fleet’s mix, maximise the distance on the type counts instead: one abs() term per
type and period, which MP linearizes:
MGA_TYPE = MGA.replace(
"maximize Diversity: z;",
"""set KINDS;
param kind_of {UNITS} symbolic in KINDS;
param refN {REFS, KINDS, HOURS} default 0;
subject to Distance_N {k in REFS}:
z <= sum {c in KINDS, t in HOURS}
abs(sum {g in UNITS: kind_of[g] = c} On[g,t] - refN[k,c,t]);
maximize Diversity: z;""",
).replace("subject to Distance {k in REFS}:", "subject to Distance {k in REFS: 0}:")
def store_n(k):
store(k)
ampl.eval(
f"let {{c in KINDS, t in HOURS}} refN[{k},c,t] := "
"sum {g in UNITS: kind_of[g] = c} round(On[g,t]);"
)
def mga_by_type(rounds=6, eps=0.01):
load(units, reserve_frac=0.08, model=MODEL + MGA_TYPE)
ampl.set["KINDS"] = sorted({kind(g) for g in units.index})
ampl.param["kind_of"] = {g: kind(g) for g in units.index}
ampl.param["cap"] = 1e30
ampl.eval("objective Total_Cost;")
ampl.solve(solver=SOLVER, verbose=False)
ampl.param["cap"] = ampl.get_value("Cost") * (1 + eps)
store_n(1)
found, zs = [commitment()], []
ampl.eval("objective Diversity;")
for k in range(2, rounds + 1):
ampl.solve(solver=SOLVER, verbose=False)
z = ampl.get_value("z")
if ampl.solve_result not in ("solved", "limit") or z < 0.5:
break
zs.append(round(z))
found.append(commitment())
store_n(k)
return found, zs
plans_t, zs_t = mga_by_type()
print("z per round, distance by type:", zs_t)
print("closest pair: by type", closest_by_type(plans_t), " in decisions", pairwise(plans_t)[0])
z per round, distance by type: [8, 6, 4, 3, 3]
closest pair: by type 3 in decisions 3
Now each round changes the mix: the closest pair differs by 3 in the type counts, against 1 for the unit-by-unit MGA, and no plan gains distance by renaming twins. Which distance fits is a modelling choice: by unit when units of one type differ in ways the model does not capture (site, crew, maintenance), by type when they are interchangeable.
The budget as a hierarchy instead of a constraint#
The budget can also be stated with the multi-objective feature: optimise cost first (priority 2) and let it give up
1 % (.objreltol), then maximise diversity (priority 1). These are IN suffixes on the objectives; obj:multi=2
lets MP emulate the two passes on any solver (obj:multi=1 uses the solver’s native hierarchy where there is one).
The next notebook of this series looks at tolerances more closely.
def mga_hierarchy(rounds=6, eps=0.01):
load(units, reserve_frac=0.08, model=MODEL + MGA)
ampl.eval("drop Budget;") # the tolerance replaces the budget row
ampl.eval("suffix objpriority IN, integer; suffix objreltol IN;")
ampl.eval("drop Diversity;")
ampl.solve(solver=SOLVER, verbose=False)
store(1)
ampl.eval("restore Diversity;")
cost = ampl.get_objective("Total_Cost")
cost.set_suffix("objpriority", 2)
cost.set_suffix("objreltol", eps) # may give up eps of its optimum
ampl.get_objective("Diversity").set_suffix("objpriority", 1)
zs = []
for k in range(2, rounds + 1):
ampl.solve(solver=SOLVER, **{f"{SOLVER}_options": "obj:multi=2"}, verbose=False)
zs.append(round(ampl.get_value("z")))
store(k)
return zs
print("z per round, budget as a hierarchy:", mga_hierarchy())
print("z per round, budget as a row: ", zs)
z per round, budget as a hierarchy: [26, 11, 9, 8, 7]
z per round, budget as a row: [26, 11, 9, 8, 7]
The two routes agree. The hierarchy needs no budget row and no second solve to compute the optimum first, and a solver with a native hierarchy applies the tolerance itself (possibly to its own pass bound rather than the exact optimum).
Counting output levels too: |x - r| for a continuous variable#
To make plans that differ in how much each unit produces count as different, add the output to the distance,
scaled by each unit’s range so that one unit-period contributes at most 1:
\(|P_{gt} - r_{gt}| / p^{\max}_g\). Maximising an absolute value is not convex, so it needs a binary per term. Write
abs() and let MP linearize it:
MGA_P = MGA.replace(
"maximize Diversity: z;",
"""param refP {REFS, UNITS, HOURS} default 0;
subject to Distance_P {k in REFS}:
z <= sum {g in UNITS, t in HOURS}
((if ref[k,g,t] = 1 then 1 - On[g,t] else On[g,t])
+ abs(P[g,t] - refP[k,g,t]) / pmax[g]);
maximize Diversity: z;""",
).replace("subject to Distance {k in REFS}:", "subject to Distance {k in REFS: 0}:")
def store_p(k):
store(k)
ampl.eval(f"let {{g in UNITS, t in HOURS}} refP[{k},g,t] := P[g,t];")
load(units, reserve_frac=0.08, model=MODEL + MGA_P)
ampl.param["cap"] = 1e30
ampl.eval("objective Total_Cost;")
ampl.solve(solver=SOLVER, verbose=False)
ampl.param["cap"] = ampl.get_value("Cost") * 1.01
store_p(1)
ampl.eval("objective Diversity;")
ampl.solve(solver=SOLVER, verbose=False)
print(
"first alternative, on/off and output counted: z =", round(ampl.get_value("z"), 2)
)
first alternative, on/off and output counted: z = 40.25
If you linearize \(d \le |x - r|\) by hand (for example in a model that must stay a pure MIP), use a binary \(b\) and two times the range \(W\) as the constant:
Since \(x - r\) ranges over \([-W, W]\), a constant of only \(W\) does not switch the second row off: it caps \(d\) at \(W - |x - r|\) whenever \(|x - r| > W/2\), and the rounds quietly return less diverse plans than they report. The pairwise distances computed after the fact, as above, are the check.
Takeaways#
A solution pool returns what the search met near the optimum; its members can be near-duplicates.
Max-min MGA asks for diversity directly: within a cost budget, each new plan is as far as possible from the nearest earlier one.
Count primary decisions only; derived variables (starts, stops) would reward consequences.
State the budget on a defined variable for the cost, or as an objective tolerance in a hierarchy (
.objpriority,.objreltol,obj:multi).For continuous decisions,
abs()with MP, or a hand linearization with a 2W constant; check the reported distances against the plans.A max-min round that stops at a time limit may return a repeat (
z = 0): stop there, or give the round more time.Near-identical units make a unit-by-unit distance overstate diversity: count by type to check, or maximise the distance on the type counts.