Extensions
In order to allow for extension or modification of code behavior, many of
the components (hubs and spokes) support callout points. The objects
that provide the methods that are called are referred to as extensions.
Instead of using an extension, you could just hack in a function call,
but then every time mpi-sppy is updated, you would have to remember
to hack it back in. By using an extension object, the addition
or modification will remain available. Perhaps more important, the
extension can be included in some applications, but not others.
There are a number of extensions, particularly for PH, that are provided
with mpi-sppy and they provide examples that can be used for the
creation of more. Extensions can be found in mpisppy.extensions.
Note that some things (e.g. some xhatters) can be used as a cylinder
or as an extension. A few other things (e.g., cross scenario cuts) need
both an extension and a cylinder.
Many extensions are supported in generic_cylinders.py via command-line flags:
--fixer– activates the fixer extension--slamming-directives-file <file>– activates the slammer extension--detect-W-oscillations <file>– activates W-oscillation detection (see W-vector oscillation: detection and interruption)--interrupt-W-oscillations <file>– activates W-oscillation interruption (slamming; implies detection; see W-vector oscillation: detection and interruption)--mipgaps-json <file>– activates the legacy mipgapper schedule mode--starting-mipgap <float>(required;--mipgap-ratiodefaults to0.1) – activates the mipgapper’s auto-gap mode for cylinders--timed-mipgap <curve>– activates the timed MIP gap extension and sets the timed MIP gap curve asgap:timepairs (e.g.,"0.02:100 0.05:200")--user-defined-extensions <module>– attaches the extension classes defined in a module (see User-defined extensions)--grad-rho– activates gradient-based rho (see Rho Setting)--use-norm-rho-updater– activates the norm rho updater--use-primal-dual-rho-updater– activates the primal-dual rho updater--xhat-feasibility-cuts-count <N>– feasibility cuts from the xhatter when its candidate is infeasible; binary first-stage only (see Xhat Feasibility Cuts)
The rest of this help file describes extensions released with mpisppy along with some hints for including them in your own cylinders driver program.
User-defined extensions
--user-defined-extensions myext imports the module myext and attaches
to the hub every non-abstract subclass of Extension that the module
defines. Classes the module imports are not attached, so a concrete helper
base class you do not want attached belongs in another module. For several
modules, quote a space-separated list: --user-defined-extensions "myext1
myext2". No two extensions in a run may share a class name, shipped ones
included; the run stops with an error if they do.
The module is found the way --module-name finds a model: give a module
name (myext or mypkg.myext), which is looked for in the current
directory as well as on sys.path, or a path (some/dir/myext) to a
.py file or a package directory. A module of the same name that is
already imported, or that comes earlier on sys.path, is used instead
of yours; which comes first depends on how the run is launched. With a
path, that case is an error, so rename your module. For a class in a
package, name the module that defines it, not a package that re-exports
it.
If myext.json is in the same directory as myext.py (for classes
defined in a package’s __init__.py, __init__.json), its contents are
put in the hub options under the module’s name, without any directory part
(myext or mypkg.myext). The file is optional, so read it with
self.opt.options.get("myext").
Multiple Extensions
To employ multiple PH extensions, use mpisppy.extensions.extension import MultiExtension
that allows you to give a list of extensions that will fire in order
at each callout point. See, e.g. examples.sizes.sizes_demo.py or
examples.farmer.CI.farmer_rho_demo.py for an
example of use.
Note
The MultiExtension constructor in mpisppy.extensions.extensions.py
takes a list of extensions classes in addition to the optimization object
(e.g. inherited from PHBase). However, cfg_vanilla.py wants
to see the class MultiExtension in the hub or cylinder dict entry
for ["opt_kwargs"]["extensions"] and then wants to see a list of
extension classes in ["opt_kwargs"]["extension_kwargs"]["ext_classes"].
Some examples do both, which can be little confusing.
Replacing subproblem solves
An Extension may override solve_subproblem to customize how a scenario
or bundle subproblem is solved. A common reason is to provide a custom solution
algorithm for the subproblem. The override may replace mpi-sppy’s configured
solve entirely or wrap it with additional work. For example, constraint
generation can solve, inspect the loaded candidate, add violated rows, and
solve again. This all remains one logical subproblem solve from the perspective
of PH and the other mpi-sppy algorithms.
The hook has this signature:
def solve_subproblem(
self, subproblem, subproblem_solve, *, outer_bound_only=False):
...
subproblem_solve is a zero-argument callable supplied by mpi-sppy. Each
call performs one complete, configured solve attempt: it invokes the solver
with the current options and logging setup, classifies the results, loads an
available solution using the appropriate persistent or nonpersistent solver
path, and returns a SubproblemSolveOutcome. Calling it does not advance
PH, start another MPI operation, or invoke pre_solve and post_solve.
Those hooks surround the entire logical subproblem solve.
An extension may call subproblem_solve zero, one, or multiple times, but it
must return exactly one final SubproblemSolveOutcome. The ordinary wrapper
pattern is:
from mpisppy.extensions.extension import Extension
class ConstraintGeneration(Extension):
def solve_subproblem(
self, subproblem, subproblem_solve, *, outer_bound_only=False):
outcome = subproblem_solve()
# A bound-only solve deliberately does not load variable values.
if outer_bound_only or not outcome.solution_available:
return outcome
while add_violated_rows(subproblem):
# Persistent solvers must also receive the new rows; that step
# belongs in add_violated_rows.
outcome = subproblem_solve()
if not outcome.solution_available:
break
return outcome
The callback exists so an extension does not have to duplicate mpi-sppy’s solver invocation, result classification, solution loading, logging, and failure bookkeeping. Only the outcome returned by the extension is committed to the subproblem’s final availability and bound state.
SubproblemSolveOutcome contains:
resultsThe Pyomo solver results associated with the outcome, or
Nonefor a complete replacement that did not use the Pyomo solver.solution_availableA promise that the corresponding variable values are already loaded into
subproblem. Setting this toTruewithout loading the values violates the hook contract.outer_boundandinner_boundA numeric value reports that value directly.
INFER_BOUNDasksSPOptto read it fromresults; this can recover a usable bound from a non-optimal solve.Noneexplicitly reports that no bound is available.
A normal subproblem_solve attempt whose results mpi-sppy classifies as
failed reports None bounds, preserving native solve behavior. A wrapping
extension may instead return a new outcome with INFER_BOUND when those
non-optimal results contain a bound it intentionally wants to retain.
When outer_bound_only=True, subproblem_solve obtains a bound without
loading a candidate solution. An extension must not inspect variable values on
that path. It may replace the solve completely, but then it assumes the same
solution-loading and outcome-reporting responsibilities as the callback.
Replacing the callback completely
An extension does not have to call subproblem_solve. This is useful when an
external service, a specialized decomposition method, or a cached calculation
replaces the Pyomo solver entirely. In that case the extension owns the full
contract: it must solve the current subproblem objective and constraints,
load any reported solution into the Pyomo variables, and report trustworthy
bounds and availability.
For example:
from mpisppy.extensions.extension import (
Extension,
SubproblemSolveOutcome,
)
from pyomo.environ import Var
class ExternalSubproblemSolver(Extension):
def solve_subproblem(
self, subproblem, subproblem_solve, *, outer_bound_only=False):
answer = external_service.solve(
subproblem,
need_solution=not outer_bound_only,
)
solution_available = False
if not outer_bound_only and answer.has_solution:
for variable in subproblem.component_data_objects(Var):
variable.set_value(answer.primal_values[variable.name])
solution_available = True
return SubproblemSolveOutcome(
results=None,
solution_available=solution_available,
outer_bound=answer.outer_bound,
inner_bound=answer.inner_bound,
)
Here the bounds are supplied numerically because there is no Pyomo results
object from which INFER_BOUND could read them. A replacement may instead
return a suitable Pyomo results object and use INFER_BOUND. It must not
claim solution_available=True unless it has loaded every value required by
the calling algorithm. It must also avoid reusing a result computed for stale
PH weights, fixed variables, objective coefficients, or generated constraints.
Only one member of a MultiExtension may override solve_subproblem.
Other extensions still receive the observational solve hooks. In particular,
post_solve runs after final solution availability and bounds have been
recorded, and its return value is ignored. Extensions that previously returned
a replacement results object from post_solve must move that behavior into
solve_subproblem.
solve_subproblem cannot be combined with the Agnostic interface. Agnostic
dispatch is already a replacement for the native subproblem solve, so
SPOpt raises RuntimeError when both mechanisms are requested. Ordinary
extensions that do not override solve_subproblem remain compatible with
Agnostic solves.
Checkpointing your extension
A run with --checkpoint-dir (see Checkpointing and Resuming a Run) saves the scenario
models, so anything your extension keeps on a model comes back on a resume
by itself. Anything it keeps on itself does not. If that state decides what
the extension does next – a history, a counter, a record of what it already
fixed – implement two methods:
from mpisppy.extensions.extension import Extension
class MoveCounter(Extension):
"""Counts, for each nonant, the iterations in which it moved."""
def __init__(self, ph):
super().__init__(ph)
self.moves = {} # (scenario name, variable name) -> count
self.last = {} # (scenario name, variable name) -> value
def enditer(self):
for sname, s in self.opt.local_scenarios.items():
for xvar in s._mpisppy_data.nonant_indices.values():
key = (sname, xvar.name)
if key in self.last and xvar.value != self.last[key]:
self.moves[key] = self.moves.get(key, 0) + 1
self.last[key] = xvar.value
def checkpoint_state(self):
return {"moves": dict(self.moves), "last": dict(self.last)}
def restore_state(self, state):
self.moves = dict(state["moves"])
self.last = dict(state["last"])
The rules:
Return plain data – dicts, lists, numbers, strings, tuples. Key by variable name or by
(node name, index), never by a Pyomo object or itsid(): a resume replaces every model, so a saved reference points at an object that no longer exists.restore_stateruns once, near the end of iteration 0, afterpre_iter0andpost_iter0. Rebuild whatever you derive from the models in those hooks as usual;restore_statethen puts back what the models cannot tell you.Make no MPI calls in either method. On a cylinder with several ranks each rank saves and restores its own scenarios’ state, and a collective call reached by some ranks and not others hangs the run.
State is matched to extensions by class name, so renaming the class between the stop and the resume drops its state; the resume says so.
restore_statemay return a sentence saying what it could not put back exactly; the resume prints it with its other warnings.
If your extension keeps no such state, say so instead:
class MyExtension(Extension):
def checkpoint_state(self):
return None
def restore_state(self, state):
pass
Do one or the other. The base methods raise NotImplementedError, and a run
with --checkpoint-dir or --resume-from refuses to start, before any
solve, if an attached extension does not override both – because it cannot
tell “keeps nothing” from “nobody decided”. A run without checkpointing never
calls either method.
PH extensions
Some of these can be used with other hubs. An extension object can be
passed to the PH constructor and it is assumed to have methods defined
for all the callout points in PH (so all of the examples do). To see
the callout points look at phbase.py. Extensions can also specify
callout points in the Hub SPCommunicator object: these callout points
are especially useful for writing custom Spoke objects which can then
interact with the hub PH object. To see the callout points look at
cylinders/hub.py; an example of such an extension is the
“cross-scenario cut” extension defined in extensions/cross_scen_extension.py
and associated spoke object defined in cylinders/cross_scen_spoke.py.
If you want to use more than one extension, define a main extension that has
a reference to the other extensions and can call their methods in the
appropriate order. Extensions typically access low level elements of
mpi-sppy so writing your extensions is an advanced topic. We will
now describe a few of the extensions in the release.
mipgapper.py
This is a good extension to look at as a first example. It can either take a
dictionary with iteration numbers and mipgaps as input, or it can run in
auto-gap mode when used from generic_cylinders.
The dictionary form is provided in the options dictionary in
["gapperoptions"]["mipgapdict"]. There is an example of its use in
examples.sizes.sizes_demo.py.
When run with cylinders, the options ["gapperoptions"]["starting_mipgap"]
and ["gapperoptions"]["mipgap_ratio"] can be set instead. The
starting_mipgap is the initial value used, and as the cylinders close the
relative optimality gap the extension sets the subproblem mipgaps as
min(starting_mipgap, mipgap_ratio * problem_ratio), where
problem_ratio is the relative optimality gap on the overall problem as
computed by the cylinders.
This extension can also be used with the Lagrangian and subgradient spokes.
timed_mipgap.py
This extension installs a solver termination callback that stops a persistent
MIP solve once a user-specified run time has been reached and the current
relative gap is already below a target threshold. The option is given as a
string of ordered gap:time pairs in
options["timed_mipgap"]["timecurve"]. For example,
"0.02:100 0.05:200" means: after 100 seconds, stop if the relative gap is
below 2%; after 200 seconds, stop if it is below 5%.
This is a soft, time-dependent stopping rule: it does not force termination at the specified times unless the incumbent and bound are already close enough. It is useful when early PH iterations do not need tight subproblem solves, but later iterations may still benefit from stronger solves when the solver is making progress.
When using generic_cylinders.py, enable it with:
--timed-mipgap "0.02:100 0.05:200"
The extension currently requires a persistent solver with supported termination
callbacks; at present this includes CPLEX, Gurobi, and Xpress persistent
interfaces. The gap:time pairs are validated in the order provided and
must be strictly increasing in both gap and time; duplicate gap entries are
rejected.
fixer.py
This extension provides methods for fixing nonanticipative variables (usually integers) for
which all scenarios have agreed for some number of iterations. There
is an example of its use in examples.sizes.sizes_demo.py also
in examples.uc.uc_ama.py. The uc_ama example illustrates
that when amalgamator is used "id_fix_list_fct" needs
to be on the Config object so the amalgamator can find it.
Note
For the iteration zero fixer tuples, the iteration counts are just
compared with None. If you provide a count for iteration zero, the
variable will be fixed if it is within the tolerance of being converged.
So if you don’t want to fix a variable at iteration zero, provide a
tolerance, but set all count values to None.
reduced_cost_fixer
This extension provides methods for fixing nonanticipative variables based on their expected
reduced cost as calculated by the ReducedCostSpoke. The aggressiveness of the
fixing can be controled through the zero_rc_tol parameter (reduced costs
with magnitude below this value will be considered 0 and not eligible for fixing)
and the fix_fraction_target paramemters, which set a maximum fraction of
nonanticipative variables to be fixed based on expected reduced costs. These two
parameters iteract with each other – the expected reduced costs are sorted by
magnitude, and if the fix_fraction_target` percental is below zero_rc_tol,
then fewer than fix_fraction_target variables will be fixed. Further, to
have a defined expected reduced cost, all nonant variable values must be at
the same bound in the ReducedCostSpoke.
Variables will be unfixed if they no longer meet the expected reduced cost criterion for fixing, e.g., the variable’s expected reduced cost became too low or the variable was not at its bound in every subproblem in the ReducedCostSpoke.
relaxed_ph_fixer
This extension will fix nonanticipative variables at their bound if they are at their bound in the RelaxedPHSpoke for that subproblem. It will similarly unfix nonanticipative variables which are not at their bounds in the RelaxedPHSpoke. Because different nonanticipative variables are fixed in different subproblems, it will also unfix nonanticipative variables if their value is not at the current consensus solution xbar (because the variable was not fixed in a different subproblem and therefore came off its bound).
xhat
Most of the xhat methods can be used as an extension instead of being used as a spoke, when that is desired (e.g. for serial applications).
integer_relax_then_enforce
This extension is for problems with integer variables. The scenario subproblems
have the integrality restrictions initially relaxed, and then at a later point
the subproblem integrality restrictions are re-enabled. The parameter ratio
(default = 0.5) controls how much of the progressive hedging algorithm, either
in the iteration or time limit, is used for relaxed progressive hedging iterations.
The extension will also re-enforce the integrality restrictions if the convergence
threshold is within 10% of the convergence tolerance.
The iteration fraction is of --stop-at-iteration-number when that is set,
counted from the start of the study, and otherwise of this run’s own
--max-iterations. The time fraction is always of this run’s
--time-limit. So a study stopped and resumed with checkpointing (see
Checkpointing and Resuming a Run) enforces at the same iteration as an uninterrupted run
only if every run of it is given --stop-at-iteration-number; without it,
each resumed run applies the ratio to its own budget. A run that ends before
the study reaches its fraction ends with integrality still relaxed, unless
the time or convergence condition enforced it first; the run that continues
the study enforces it. APH does not honour --stop-at-iteration-number, so
under APH the fraction is always of --max-iterations.
This extension can be especially effective if (1) solving the relaxation is much easier than solving the problem with integrality constraints or (2) the relaxation is reasonably “tight”.
It cannot be used with an FWPH hub, which manages integrality on the same models itself, and refuses one at startup.
slammer
This extension does preference-driven slamming: it forces (fixes) a
nonanticipative variable according to pre-specified user preferences while the
hub is running, to break a stall or cycle. Unlike the other fixers above –
which fix on agreement and so can infer a direction automatically – slamming
is meant for variables that are not settling, where there is no agreement to
read a direction from, so the directions are supplied by the user in a
directives file. This is the intended use rather than an enforced precondition:
slamming does not test convergence per variable; any variable matched by a
can_slam rule is eligible (see the eligibility rules below). (Slamming is
distinct from the SlamMin / SlamMax spokes, which are non-destructive
incumbent finders that never perturb the hub.)
From generic_cylinders.py the extension is activated only when a
directives file is supplied, so a run with no slamming options behaves exactly
as it does today:
--slamming-directives-file <file>– the directives file (its presence activates the extension)--slam-start-iter <K>– first hub iteration at which slamming may occur (default 1)--iters-between-slams <M>– once started, slam at most once everyMiterations (default 1)
Supplying --slam-start-iter or --iters-between-slams without the file is
an error.
The directives file is a CSV keyed by nonant name with shell-style wildcards
(*/?; the index brackets [ ] are matched literally). Each row
gives a name pattern, an optional can_slam flag (1/0; 0 carves
out an exception), an ordered |-separated list of directions from
{lb, ub, nearest, anywhere, min, max} (the first applicable one is used),
and a priority (the eligible nonant with the largest priority is slammed
first). Matching is last-match-wins, so write broad defaults first and
exceptions after; only variables matched by a can_slam rule are ever
slammed. A multi-index name contains a comma and so must be quoted. A pattern
that matches no variable in the model is a hard error (it is almost always a
typo) and the message names the file. A worked example translated from PySP
ships at examples/sizes/config/slamming_directives.csv.
The available directions, and the value each fixes the variable to, are:
Direction |
Value the variable is fixed to |
|---|---|
|
the variable’s lower bound |
|
the variable’s upper bound |
|
whichever bound ( |
|
|
|
the minimum of the variable’s value across all scenarios that share its scenario-tree node |
|
the maximum of the variable’s value across all scenarios that share its scenario-tree node |
A direction is applicable only when it produces a finite value (for example,
lb is skipped for a variable that has no lower bound). The directions in a
row are tried in order and the first applicable one is used; if none applies,
that variable is not slammed at this event.
Slamming is triggered by iteration count: no variable is slammed before
--slam-start-iter, and from then on at most one variable is slammed every
--iters-between-slams iterations. At each such event the single eligible
variable with the largest priority is slammed (ties are broken by name, so
the choice is the same on every rank). A variable is eligible only if it is
matched by a can_slam rule, is not already fixed (by the modeler or another
fixer), and is not a surrogate variable. Once a variable is slammed it stays
fixed for the remainder of the run.
The directions lb, ub, nearest, and anywhere use only data that
is already identical on every rank, so they need no communication; min and
max perform a single small reduction across scenarios, and only when such a
slam actually occurs. See doc/designs/slamming_design.md for design details
and rationale.
WXBarWriter and WXBarReader
There is an extension to write xbar and W values and another to read them.
An example of their use is shown in examples.sizes.sizes_demo.py
When the reader loads W (--init-W-fname) or xbar
(--init-Xbar-fname), the W and prox terms are put in the objective
before the iteration-0 solve, so iteration 0 uses the values read.
Without the reader, PH adds those terms after iteration 0.
When only W is read, the iteration-0 bound is a Lagrangian bound for that W, not the trivial bound. The reader refuses W whose probability-weighted sum over the scenarios of any tree node is not zero, because the bound would not be valid.
When xbar is read, the prox term is on in iteration 0, so that solve gives no bound and PH reports no trivial bound. That prox term uses
--default-rho: a rho setter, SepRho, GradRho and the other rho extensions set rho after the iteration-0 solve. Reading xbar cannot be combined with smoothing, and cannot be used with APH, whose prox term is centered on its own z rather than on xbar. W alone can be read with APH.With
--iter0-from-picklethere is no iteration-0 solve: iteration 0 comes from the pickle, which was solved without W or xbar. The values read take effect from iteration 1.
norm_rho_updater
This extension adjust rho dynamically. The code is in mpisppy.extensions.norm_rho_updater.py
and there is an accompanying converger in mpisppy.convergers.norm_rho_converger. From
generic_cylinders.py, enable it with --use-norm-rho-updater; a
hand-wired example using the underlying classes directly is preserved in
examples.farmer.archive.farmer_cylinders.py. This is the original
Gabe H. dynamic rho.
rho_setter
Per variable rho values (mainly for PH) can be set using a function
that takes a scenario (a Pyomo ConcreteModel) as its only
argument. The function returns a list of (id(vardata), rho)
tuples. The function name can be given to the vanilla.ph_hub
constructor or in the hub dictionary under opt_kwargs as the
rho_setter entry. (The function name is ultimately passed to the
phabase constructor.)
The function is called once per scenario, and must return the same rho for a variable in every scenario through that variable’s tree node (see Rho Setting).
There is an example of the function in the sizes example (_rho_setter).
SepRho
Set per variable rho values using the “SEP” algorithm from
Progressive hedging innovations for a class of stochastic mixed-integer resource allocation problems Jean-Paul Watson, David L. Woodruff, Compu Management Science, 2011 DOI 10.1007/s10287-010-0125-4
One can additional specify a multiplier on the computed value (default = 1.0). If the cost coefficient on a non-anticipative variable is 0, the default rho value is used instead.
CoeffRho
Set per variable rho values proportional to the cost coefficient on each non-anticipative variable, with an optional multiplier (default = 1.0) that is applied to the computed value. If the coefficient is 0, the default rho value is used instead.
primal_dual_rho
Increase or decrease rho for every variable to keep primal and dual convergence balance. If
the primal residual is greater than update_threshold times the dual residual, then all
rhos are increased by the update_threshold, and conversely all rhos are decreased if
the dual residual is greater than update_threshold time the primal residual. The user
can also specify a primal_bias (default 1.0) which will emphasize primal convergence
when greater than 1 and emphasize dual convergence if less than 1.
This extension is especially useful if the rhos provided by the user (or some other extension) are believed to be “in balance”, such that per-variable updates are not needed (and can sometimes hinder algorithmic progress when different nonanticipative variables play similar roles in the subproblem optimization problems).
wtracker_extension
The wtracker_extension outputs a report about the convergence (or really, lack thereof) of
W values.
An example of programmatic use is shown in examples.sizes.sizes_demo.py.
From generic_cylinders.py, enable it with --wtracker. Related options:
--wtracker– enable the extension (default off)--wtracker-file-prefix <str>– prefix for the rank-by-rank output files (default: empty)--wtracker-wlen <int>– moving-window length, in iterations, used by the convergence statistics (default 20)--wtracker-reportlen <int>– maximum number of rows in each ranked report (default 100)--wtracker-stdevthresh <float>– ignore moving standard deviations below this value when counting “converged” traces (default: useE1_tolerance)
At the end of the run, each rank writes three files using its prefix:
<prefix>_summary_iter<N>_rank<r>.txt– text summary with counts and totals<prefix>_stdev_iter<N>_rank<r>.csv– top entries sorted by moving standard deviation<prefix>_cv_iter<N>_rank<r>.csv– top entries sorted by moving absolute coefficient of variation
Each CSV row is indexed by (varname, scenario_name) and gives the
windowed mean and stdev of W for that nonant/scenario pair. This is a
diagnostic tool intended for tuning rho and convergence behavior; it
adds time and memory and is not recommended for production runs.
w_oscillation
The w_oscillation extension (mpisppy.extensions.w_oscillation)
detects oscillation / cycling in the PH dual weight (W) vector and can
optionally interrupt it (by slamming). Because both
detection and interruption have a fair amount of configuration, they have
their own page: W-vector oscillation: detection and interruption. It is activated with
--detect-W-oscillations and/or --interrupt-W-oscillations.
gradient_extension
The gradient_extension sets gradient-based rho for PH. From
generic_cylinders.py, enable it with --grad-rho; a standalone
demo is in examples.farmer.CI.farmer_rho_demo.py. There are options
in cfg to control dynamic updates.
mult_rho_updater
This extension does a simple multiplicative update of rho; consequently, the update is cumulative.
cross-scenario cuts
Two-stage models only. This extension adds cross scenario cuts as calculated
by the cross-scenario cut spoke. See the implementation paper for details.
A hand-wired example using the underlying classes is preserved in
examples/farmer/archive/cs_farmer.py.
Distributed Subproblem Presolve
This functionality is available for all Hub and Spoke algorithms which inherit from
SPBase. It can be enabled by passing presolve=True into the constructor.
Leveraging the existing feasibility-based bounds tightening (FBBT) available in Pyomo, this presolver will tighten the bounds on all variables, including the non-anticipative variables. If the non-anticipative variables have different bounds, the bounds among the non-anticipative variables will be synchronized to utilize the tightest available bound.
In its current state, the user might opt-in to presolve for two reasons:
For problems without relatively complete recourse, utilizing the tighter bounds on the non-anticipative variables and speed convergence and improve primal and dual bounds. In rare cases it might also detect infeasibility.
For problems where a “fixer” extension or spoke is used, determining tight bounds on the non-anticipative variables may improve the fixer’s performance.
Note
Like many solvers, the presolver will convert infinite bounds to 1e+100.
Note
This capability requires the auto-persistent pyomo solver interface (APPSI) extensions
for Pyomo to be built on your system. This can be achieved by running pyomo build-extensions
at the command line.
Note
The APPSI capability in Pyomo is under active development. As a result, the presolver may not work for all Pyomo models.
variable_probability
This is experimental as of February 2021; use with caution. The main use-case is to allow zero-probability variables.
A function similar to rho_setter can be passed to the SPBase
constructor via the PHBase construtor as the
variable_probability argument to allow for per variable
probability specification. So it can be passed through by vanilla
via ph_hub. The function should return (vid, probability) pairs.
If the function needs arguments, pass them via
the SPBase option variable_probability_kwargs
The variable probabilities impact the computation of
xbars and W.
Note
The only xhatter that is likely to work with variable probabilities is xhatxbar. The others are likely to execute without error messages but will not find good solutions.
Objective function considerations
If variables with by-variable probability are in the objective function, it is up to the scenario creator code to deal with it. This is not so difficult for zero-probability variables.
zero-probability variables
When you
create the scenario, you probably want to fix zero probability variables and perhaps give
them a zero coefficient if they appear in the objective. Fixed
variables will not get a nonanticipativity constraint in bundles. If you
create the EF directly, you probably want to set
nonant_for_fixed_vars to False in the call to create_EF. If
you are not calling create_EF directly, but rather using the
mpisppy.opt.ef.ExtensiveForm object, add nonant_for_fixed_vars
to the dict passed as its options argument with the value
False.
Note
The W value for a zero-probability variable will be stay at zero.
Fixed variables may cause trouble if you are relying on the internal PH convergence metric.
Note
You must declare variables to be in the nonant list even for those scenarios where they have zero probability if they are in other scenarios that share a scenario tree node at the variable’s stage.
If some variables have zero probability in all scenarios, then you will need to set the option
do_not_check_variable_probabilities to True in the options for spbase. This will result in skipping the checks for
all variable probabilities! So you might want to set this to False to verify that the probabilities sum to one
only for the Vars you expect before setting it to True.
Scenario_lp_mps_writer_dir
This extension writes an lp file and an mps file with the model, a
json file with (a) list(s) of scenario tree node names and
nonanticaptive variables, and a {scenario}_rho.csv file with the
per-nonant rho values, for each scenario before the iteration zero
solve of PH or APH. Note that for two-stage problems, all json files
(and all rho files) will be the same. See mpisppy.generic_cylinders.py
for an example of use. In that program it is activated with the
--scenario-lp-mps-writerdir option that specifies a directory that
does not exist. The extension
writes the files to this directory and for each scenario
the base name of the four files written is the scenario name.
Unless you know exactly why you need this, you probably don’t.