APIs

High-level

For most developers, understanding the API for the high level classes is not necessary except perhaps when they want to bypass the examples shared services.

EF class

This class forms the extensive form and makes it available to send to a solver. It also provides some methods to look at the solution.

class mpisppy.opt.ef.ExtensiveForm(options, all_scenario_names, scenario_creator, scenario_creator_kwargs=None, all_nodenames=None, model_name=None, suppress_warnings=False, extensions=None, extension_kwargs=None, mutable_probability=None)[source]

Bases: SPBase

Create and solve an extensive form.

ef

Pyomo model of the extensive form.

Type:

pyomo.environ.ConcreteModel

solver

Solver produced by the Pyomo solver factory.

Parameters:
  • options (dict) – Dictionary of options. May include a solver key to specify which solver name to use on the EF.

  • all_scenario_names (list) – List of the names of each scenario in the EF (strings).

  • scenario_creator (callable) – Scenario creator function, which takes as input a scenario name, and returns a Pyomo model of that scenario.

  • scenario_creator_kwargs (dict, optional) – Keyword arguments passed to scenario_creator.

  • all_nodenames (list, optional) – List of all node names, incl. leaves. Can be None for two-stage problem.

  • model_name (str, optional) – Name of the resulting EF model object.

  • suppress_warnings (bool, optional) – Boolean to suppress warnings when building the EF. Default is False.

Note: allowing use of the “solver” option key is for backward compatibility

get_objective_value()[source]

Retrieve the objective value.

Returns:

Objective value.

Return type:

float

Raises:

ValueError – If optimal objective value could not be retrieved.

get_root_solution()[source]

Get the value of the variables at the root node.

Returns:

Dictionary mapping variable name (str) to variable value (float) for all variables at the root node, or None if no solution is currently loaded (no successful solve yet, or the model was changed since the last one – see set_scenario_probabilities).

Return type:

dict

nonants()[source]

An iterator to give representative Vars subject to non-anticipitivity Args: None

Yields:

tree node name, full EF Var name, Var value

nonants_to_csv(filename)[source]

Dump the nonant vars from an ef to a csv file; truly a dump… :param filename: the full name of the csv output file :type filename: str

scenarios()[source]

An iterator to give the scenario sub-models in an ef Args: None

Yields:

scenario name, scenario instance (str, ConcreteModel)

set_scenario_probabilities(prob_map)[source]

Update scenario probabilities on a mutable-probability EF in place.

Requires the EF to have been created with mutable_probability=True. The supplied probabilities replace the current values; the full set of scenario probabilities must sum to 1 after the update (this is a full EF). If a persistent solver has already been loaded, the objective is re-pushed so a subsequent solve_extensive_form(reuse_instance=True) re-solves with the new probabilities without rebuilding the model.

Parameters:

prob_map (dict) – Maps scenario name to its new probability. Names not present are left unchanged.

Raises:
  • RuntimeError – If the EF was not built with mutable_probability=True.

  • KeyError – If prob_map contains an unknown scenario name.

  • ValueError – If a supplied probability is not a finite, nonnegative number, or if the resulting probabilities do not sum to 1.

Note

Two-stage only, and enforced at construction: building an EF with mutable_probability=True from a multistage tree raises ValueError there, so no object reaching this method can be multistage. There is no multistage support and none is planned; to re-weight a multistage model, rebuild it with the new probabilities.

solve_extensive_form(solver_options=None, tee=False, reuse_instance=False)[source]

Solve the extensive form.

Parameters:
  • solver_options (dict, optional) – Dictionary of solver-specific options (e.g. Gurobi options, CPLEX options, etc.).

  • tee (bool, optional) – If True, displays solver output. Default False.

  • reuse_instance (bool, optional) – If True and this EF has already been loaded into a persistent solver, skip re-loading the instance (set_instance) and re-solve the already-loaded model. Use this to re-solve cheaply after set_scenario_probabilities, which re-pushes the objective so the change reaches the solver. It is not a general “re-solve after editing the model”: a legacy persistent solver does not re-read other mutable Param values on solve(), so editing one and re-solving with reuse_instance=True silently returns the pre-edit answer. Ignored for non-persistent solvers. Default False.

Returns:

Result returned by the Pyomo solve method.

Return type:

pyomo.opt.results.results_.SolverResults

PH class

This is the class for PH hub.

class mpisppy.opt.ph.PH(options, all_scenario_names, scenario_creator, scenario_denouement=None, all_nodenames=None, mpicomm=None, scenario_creator_kwargs=None, extensions=None, extension_kwargs=None, ph_converger=None, rho_setter=None, variable_probability=None)[source]

Bases: PHBase

PH. See PHBase for list of args.

ph_main(finalize=True, attach_prox=True)[source]

Execute the PH algorithm.

Parameters:
  • finalize (bool, optional, default=True) – If True, call PH.post_loops(), if False, do not, and return None for Eobj

  • attach_prox (bool, optional, default=True) – If True, use a proximal term, if False, no proximal term is added to the objective function

Returns:

Tuple containing

conv (float):

The convergence value (not easily interpretable).

Eobj (float or None):

If finalize=True, this is the expected, weighted objective value with the proximal term included. This value is not directly useful. If finalize=False, this value is None.

trivial_bound (float):

The “trivial bound”, computed by solving the model with no nonanticipativity constraints (immediately after iter 0).

Return type:

tuple

Note

You need an xhat finder either in denouement or in an extension.

mpisppy.opt.ph.profile(filename=None, comm=<mpisppy.MPI._MockMPIComm object>)[source]

lshaped class

This is the class for L-shaped hub.

class mpisppy.opt.lshaped.LShapedMethod(options, all_scenario_names, scenario_creator, scenario_denouement=None, all_nodenames=None, mpicomm=None, scenario_creator_kwargs=None)[source]

Bases: SPBase

Base class for the L-shaped method for two-stage stochastic programs.

Note

Maximization is supported. The objective is negated internally so the root (master) and subproblems are always solved as minimizations, and the reported bound is negated back to the model’s natural sense.

Parameters:
  • options (dict) –

    Dictionary of options. Possible (optional) options include

    • root_scenarios (list) - List of scenario names to include as part of the root problem (default [])

    • store_subproblems (boolean) - If True, the BendersDecomp object will maintain a dictionary containing the subproblems created by the BendersCutGenerator.

    • relax_root (boolean) - If True, the LP relaxation of the root problem is solved (i.e. integer variables in the root problem are relaxed).

    • scenario_creator_kwargs (dict) - Keyword args to pass to the scenario_creator.

    • valid_eta_lb (dict) - Dictionary mapping scenario names to valid lower bounds for the eta variables–i.e., a valid lower (outer) bound on the optimal objective value for each scenario. If none are provided, the lower bound is set to -sys.maxsize * scenario_prob, which may cause numerical errors.

    • lshaped_cut_generator (string) - “pyomo_feasibility” keeps the existing Pyomo Benders cut generator; “standard_l1” solves the ordinary recourse problem for optimality cuts and an L1-normalized feasibility problem if recourse is infeasible.

    • indx_to_stage (dict) - Dictionary mapping the index of every variable in the model to the stage they belong to.

  • all_scenario_names (list) – List of all scenarios names present in the model (strings).

  • scenario_creator (callable) – Function which take a scenario name (string) and returns a Pyomo Concrete model with some things attached.

  • scenario_denouement (callable, optional) – Function which does post-processing and reporting.

  • all_nodenames (list, optional) – List of all node name (strings). Can be None for two-stage problems.

  • mpicomm (MPI comm, optional) – MPI communicator to use between all scenarios. Default is MPI.COMM_WORLD.

  • scenario_creator_kwargs (dict, optional) – Keyword arguments to pass to scenario_creator.

attach_nonant_var_map(scenario_name)[source]
create_root()[source]

creates a ConcreteModel from one of the problem scenarios then modifies the model to serve as the root problem

create_subproblem(scenario_name)[source]

the subproblem creation function passed into the BendersCutsGenerator

lshaped_algorithm(converger=None)[source]

function that runs the lshaped.py algorithm

options_check()[source]

Check to ensure that the user-specified options are valid. Requried options are:

  • root_solver (string) - Solver to use for the root problem.

  • sp_solver (string) - Solver to use for the subproblems.

set_eta_bounds()[source]
mpisppy.opt.lshaped.main()[source]

Mid-level

Most developers will not want to interact directly with mid-level classes; however, they are important to code contributors and to developers who want to create their own extensions.

phbase.py

This is the base class for PH and PH-like algorithms.

class mpisppy.phbase.PHBase(options, all_scenario_names, scenario_creator, scenario_denouement=None, all_nodenames=None, mpicomm=None, scenario_creator_kwargs=None, extensions=None, extension_kwargs=None, ph_converger=None, rho_setter=None, variable_probability=None)[source]

Bases: SPOpt

Base class for all PH-based algorithms.

Based on mpi4py (but should run with, or without, mpi) EVERY INDEX IS ZERO-BASED! (Except stages, which are one based).

Node names other than ROOT, although strings, must be a number or end in a number because mpi4py comms need a number. PH using a smart referencemodel that knows how to make its own tree nodes and just wants a trailing number in the scenario name. Assume we have only non-leaf nodes.

To check for rank 0 use self.cylinder_rank == 0.

local_scenarios

Dictionary mapping scenario names (strings) to scenarios (Pyomo conrete model objects). These are only the scenarios managed by the current rank (not all scenarios in the entire model).

Type:

dict

comms

Dictionary mapping node names (strings) to MPI communicator objects.

Type:

dict

local_scenario_names

List of local scenario names (strings). Should match the keys of the local_scenarios dict.

Type:

list

current_solver_options

from options, but callbacks might Dictionary of solver options provided in options. Note that callbacks could change these options.

Type:

dict

Parameters:
  • options (dict) – Options for the PH algorithm.

  • all_scenario_names (list) – List of all scenario names in the model (strings).

  • scenario_creator (callable) – Function which take a scenario name (string) and returns a Pyomo Concrete model with some things attached.

  • scenario_denouement (callable, optional) – Function which does post-processing and reporting.

  • all_nodenames (list, optional) – List of all node name (strings). Can be None for two-stage problems.

  • mpicomm (MPI comm, optional) – MPI communicator to use between all scenarios. Default is MPI.COMM_WORLD.

  • scenario_creator_kwargs (dict, optional) – Keyword arguments passed to scenario_creator.

  • extensions (object, optional) – PH extension object.

  • extension_kwargs (dict, optional) – Keyword arguments to pass to the extensions.

  • ph_converger (object, optional) – PH converger object.

  • rho_setter (callable, optional) – Function to set rho values throughout the PH algorithm.

  • variable_probability (callable, optional) – Function to set variable specific probabilities.

Compute_Xbar(verbose=False)[source]

Gather xbar and x squared bar for each node in the list and distribute the values back to the scenarios.

Parameters:

verbose (boolean) – If True, prints verbose output.

Iter0()[source]

Create solvers and perform the initial PH solve (with no dual weights or prox terms, unless an extension called request_PH_attach_before_iter0_solve).

This function quits() if the scenario probabilities do not sum to one, or if any of the scenario subproblems are infeasible. It also calls the post_iter0 method of any extensions, and uses the rho setter (if present) after the initial solve.

Returns:

The so-called “trivial bound”, i.e., the objective value of the stochastic program with the nonanticipativity constraints removed.

Return type:

float

PH_Prep(attach_duals=True, attach_prox=True, attach_smooth=0, defer_attach=True)[source]

Set up PH objectives (duals and prox terms), and prepare extensions, if available.

Parameters:
  • attach_duals (boolean, optional) – If True, adds dual weight (Ws) to the objective. Default True.

  • attach_prox (boolean, optional) – If True, adds prox terms to the objective. Default True.

  • attach_smooth (int, optional) – If 0, no smoothing; if 1, p_value is used; if 2, p_ratio is used.

  • defer_attach (boolean, optional) – If True (default), the W and prox terms are not spliced into the subproblem objectives here; instead they are attached at the end of Iter0 (see _attach_PH_to_objective_after_iter0) so that the iteration-0 solve uses exactly the user’s objective – no PH machinery in the expression tree. If False, the terms are attached immediately (legacy behavior, needed by FWPH, which snarfs the subproblem objective between PH_Prep and Iter0). Agnostic (AML guest) runs are always attached immediately regardless of this flag (the guest builds its xbars Param in the attach callout, which solve_one needs from iteration 0).

Note

This function constructs an Extension object if one was specified at the time the PH object was created.

Note

PH_Prep may be run only once on an object, so a PH object solves one problem. Running PH_Prep twice used to look like it worked and quietly solve something else: attach_Ws_and_prox re-declared W and rho as fresh Params, discarding the duals the first run produced, and attach_PH_to_objective appended a second PH term to the same objective, leaving the first live and anchored to the previous run’s xbar. Measured on farmer, W went from [8.374, 33.574, -41.948] to [0.0, 0.0, 0.0] and the objective’s W_on count from 1 to 2, with no error and no warning.

Making it genuinely re-entrant is possible but is not free – see issue #848 – and no caller wants it: every one that runs PH more than once builds a new object.

Update_W(verbose)[source]

Update the dual weights during the PH algorithm.

Parameters:

verbose (bool) – If True, displays verbose output during update.

Update_z(verbose)[source]

Update the smoothing variable z during the PH algorithm.

Parameters:

verbose (bool) – If True, displays verbose output during update.

property W_disabled
W_from_flat_list(flat_list)[source]

Set the dual weight values (Ws) for all local scenarios from a flat list.

Parameters:

flat_list (list) – One-dimensional list of dual weights.

Warning

We are counting on Pyomo indices not to change order between list creation and use.

attach_PH_to_objective(add_duals, add_prox, add_smooth=0)[source]

Attach dual weight and prox terms to the objective function of the models in local_scenarios.

Parameters:
  • add_duals (boolean) – If True, adds dual weight (Ws) to the objective.

  • add_prox (boolean) – If True, adds the prox term to the objective.

attach_Ws_and_prox()[source]

Attach the dual and prox terms to the models in local_scenarios.

attach_smoothing()[source]

Attach the smoothing terms to the models in local_scenarios.

attach_xbars()[source]

Attach xbar and xbar^2 Pyomo parameters to each model in local_scenarios.

convergence_diff()[source]

Compute the convergence metric ||x_s - bar{x}||_1 / num_scenarios.

Returns:

The convergence metric ||x_s - bar{x}||_1 / num_scenarios.

Return type:

float

disable_W_and_prox()[source]
property iter0_solver_options

Read-only fold of solver_options_layers for iteration 0.

Deprecated; reads emit a DeprecationWarning. Use _effective_solver_options(0) for the iter-0 fold, which is the same value but doesn’t go through the deprecation path.

iterk_loop()[source]

Perform all PH iterations after iteration 0.

This function terminates if any of the following occur:

  1. The maximum number of iterations is reached.

  2. The user specifies a converger, and the is_converged() method of that converger returns True.

  3. The hub tells it to terminate.

  4. The user does not specify a converger, and the default convergence criteria are met (i.e. the convergence value falls below the user-specified threshold).

Args: None

property iterk_solver_options

Read-only fold of solver_options_layers for iteration k>=1.

Deprecated; reads emit a DeprecationWarning. Use _effective_solver_options(k) for an exact per-iteration fold (which can differ from k=1 when starting_at_iter layers are present).

keep_supplied_xbar_through_iter0()[source]

Tell Iter0 that an extension set xbar in pre_iter0 (WXBarReader reading –init-Xbar-fname, for example), so Iter0 must not replace it with the mean of the iteration-0 solutions. The rho setters that run in post_iter0 (SepRho, SensiRho, GradRho) then measure the iteration-0 solutions against the supplied xbar. Iteration 1 computes xbar from the solutions as usual.

options_check()[source]

Check whether the options in the options attribute are acceptable.

Required options are

  • solver_name (string): The name of the solver to use.

  • PHIterLimit (int): The maximum number of PH iterations to execute.

  • defaultPHrho (float): The default value of rho (penalty parameter) to use for PH.

  • convthresh (float): The convergence tolerance of the PH algorithm.

  • verbose (boolean): Flag indicating whether to display verbose output.

  • display_progress (boolean): Flag indicating whether to display information about the progression of the algorithm.

  • iter0_solver_options (dict): Dictionary of solver options to use on the first solve loop.

  • iterk_solver_options (dict): Dictionary of solver options to use on subsequent solve loops (after iteration 0).

post_loops(extensions=None)[source]

Call scenario denouement methods, and report the expected objective value.

Parameters:

extensions (object, optional) – PH extension object.

Returns:

Pretty useless weighted, proxed objective value.

Return type:

float

post_solve_bound(solver_options=None, verbose=False)[source]

Compute a bound Lagrangian bound using the existing weights.

Parameters:
  • solver_options (dict, optional) – Options for these solves.

  • verbose (boolean, optional) – If True, displays verbose output. Default False.

Returns:

An outer bound on the optimal objective function value, or None if any subproblem solve produced no bound (the expectation cannot be formed if a scenario is missing one).

Return type:

float or None

Note

This function overwrites current variable values. This is only suitable for use at the end of the solves, or if you really know what you are doing. It is not suitable as a general, per-iteration Lagrangian bound solver.

property prox_disabled
reenable_W_and_prox()[source]
request_PH_attach_before_iter0_solve()[source]

Ask Iter0 to splice the W and prox terms into the objectives before the iteration-0 solve rather than after it, so that solve uses whatever W (and xbar) an extension set in pre_iter0 – WXBarReader, for example. Iter0 does the splice once every pre_iter0 hook has run and before it creates the solvers.

With the terms attached, the iteration-0 objective values give a Lagrangian bound for the supplied W rather than the trivial bound. Has no effect when the terms were attached in PH_Prep (defer_attach=False) or the run resumed from a checkpoint.

solve_loop(solver_options=None, dtiming=False, dis_W=False, dis_prox=False, gripe=False, disable_pyomo_signal_handling=False, tee=False, verbose=False, need_solution=True, warmstart=WarmstartStatus.FALSE, *, outer_bound_only=False)[source]

Loop over local_scenarios and solve them in a manner dictated by the arguments.

In addition to changing the Var values in the scenarios, this function also updates the _PySP_feas_indictor to indicate which scenarios were feasible/infeasible.

Parameters:
  • solver_options (dict, optional) – The scenario solver options.

  • dtiming (boolean, optional) – If True, reports solve timing information. Default is False.

  • dis_W (boolean, optional) – If True, duals weights (Ws) are disabled before solve, then re-enabled after solve. Default is False.

  • dis_prox (boolean, optional) – If True, prox terms are disabled before solve, then re-enabled after solve. Default is False.

  • gripe (boolean, optional) – If True, output a message when a solve fails. Default is False.

  • disable_pyomo_signal_handling (boolean, optional) – True for asynchronous PH; ignored for persistent solvers. Default False.

  • tee (boolean, optional) – If True, displays solver output. Default False.

  • verbose (boolean, optional) – If True, displays verbose output. Default False.

  • need_solution (boolean, optional) – If True, raises an exception if a solution is not available. Default True

  • warmstart (bool, optional) – If True, warmstart the subproblem solves. Default False.

  • outer_bound_only (boolean, optional) – If True, populate outer_bound only; no solution is loaded, so need_solution must be False. If the solve reports no bound, outer_bound is cleared to None rather than left at its previous value: a stale bound cannot be mixed with fresh ones in the expectation that Ebound forms. Keyword-only. Default False.

mpisppy.phbase.W_magnitude_by_node(opt)[source]

E[|W|] per tree node: how big the numbers behind E[W] are.

The companion to Wbar_by_node, for judging one of its entries. Whether a given E[W] is “zero” is a question about the size of the terms that were summed to get it: a sum of 1e-6 is float dust beside weights of 1e6 and a real violation beside weights of 1e-3. Same collective shape.

Parameters:

opt (phbase or xhat_eval object) – object with the local scenarios

mpisppy.phbase.Wbar_by_node(opt)[source]

E[W] per tree node: the probability-weighted sum of W over scenarios.

sum_s p_s W_s = 0 is the dual feasibility a Lagrangian bound built from W relies on, and is what makes W a point in the orthogonal complement of the nonanticipativity subspace. PH’s Update_W keeps it when rho is the same in every scenario: it adds rho * (x_s - xbar), and xbar is the probability weighted mean, so the additions sum to zero when rho factors out. Then every entry of what comes back is zero up to the drift of accumulating it in floating point, which is a fraction of the size of the weights themselves (see W_magnitude_by_node).

It is not guaranteed. The rho setter is called once per scenario and may return a different rho for each, and then E[W] moves away from zero. project_W_to_zero_sum repairs every local scenario copy and is used by W-receiving outer-bound spokes for mixed-generation APH snapshots. The older diagnostic _Compute_Wbar is called by APH when display_convergence_detail is set; it subtracts only on cylinder rank 0’s scenarios, so on more than one rank it does not bring E[W] to zero.

Collective: the scenarios of a node are spread over the ranks, so the sum is an Allreduce over that node’s comm and every rank gets the same answer. Returns {node name: numpy array over the node’s nonants}.

Parameters:

opt (phbase or xhat_eval object) – object with the local scenarios

mpisppy.phbase.profile(filename=None, comm=<mpisppy.MPI._MockMPIComm object>)[source]
mpisppy.phbase.project_W_to_zero_sum(opt)[source]

Project scenario weights onto the dual-feasible nonanticipativity space.

For every scenario-tree node and nonanticipative position, subtract the probability-weighted node mean from every active local scenario copy. Variable-probability copies with zero probability remain masked to zero. This is a collective operation over the node communicators. It is useful when an asynchronous publisher supplies pieces of W from different generations: the mixed snapshot is not necessarily dual feasible, but its projection is and can therefore be used for a valid Lagrangian bound.

Returns the node-wise means that were removed.

spbase.py

SPBase is the base class for many algorithms.

class mpisppy.spbase.SPBase(options, all_scenario_names, scenario_creator, scenario_denouement=None, all_nodenames=None, mpicomm=None, scenario_creator_kwargs=None, variable_probability=None, E1_tolerance=1e-05)[source]

Bases: object

Defines an interface to all strata (hubs and spokes)

Parameters:
  • options (dict) – options

  • all_scenario_names (list) – all scenario names

  • scenario_creator (fct) – returns a concrete model with special things

  • scenario_denouement (fct) – for post processing and reporting

  • all_nodenames (list) – all node names (including leaves); can be None for 2 Stage

  • mpicomm (MPI comm) – if not given, use the global fullcomm

  • scenario_creator_kwargs (dict) – kwargs passed directly to scenario_creator.

  • variable_probability (fct) – returns a list of tuples of (id(var), prob) to set variable-specific probability (similar to PHBase.rho_setter).

local_scenarios

concrete models with extra data, key is name

Type:

dict of scenario objects

comms

keys are node names values are comm objects.

Type:

dict

local_scenario_names

names of locals

Type:

list

allreduce_or(val)[source]
gather_nonant_tree_to_rank0(get_zero_prob_values=True)[source]

Gather the whole nonant tree to the root of the cylinder’s mpicomm, keyed by node name.

Node-keyed analog of gather_var_values_to_rank0: builds, per node, the list of (node-local variable name, value) pairs – one entry per node, deduped across local scenarios that share it – gathers to rank 0 and merges.

Returns:

On rank 0, {node_name: [(local_var_name, value), ...]}. On other ranks, None.

Return type:

dict or None

Raises:

RuntimeError – if two ranks report different values for a shared node beyond tolerance (the incumbent is then not nonanticipative and the tree would be ill-defined).

gather_var_values_to_rank0(get_zero_prob_values=False, fixed_vars=True)[source]

Gather the values of the nonanticipative variables to the root of the mpicomm for the cylinder

Returns:

On the root (rank0), returns a dictionary mapping (scenario_name, variable_name) pairs to their values. On other ranks, returns None.

Return type:

dict or None

is_zero_prob(scenario_model, var)[source]
Parameters:
  • scenario_model – a value in SPBase.local_scenarios

  • var – a Pyomo Var on the scenario_model

Returns:

True if the variable has 0 probability, False otherwise

load_best_solution()[source]
report_var_values_at_rank0(header='', print_zero_prob_values=False, fixed_vars=True)[source]

Pretty-print the values and associated statistics for non-anticipative variables across all scenarios.

property spcomm
update_best_solution_if_improving(obj_val)[source]

Call if the variable values have a nonanticipative solution with associated obj_val. Will update the best_solution_cache if the solution is better than the existing cached solution

write_first_stage_solution(file_name, first_stage_solution_writer=<function first_stage_nonant_writer>)[source]

Writes the first-stage solution, if this object reports one available.

Parameters:
  • file_name – path of file to write first stage solution to

  • first_stage_solution_writer (optional) – custom first stage solution writer function

write_tree_nonants(file_name)[source]

Write the whole nonant tree (the xhat) to one by-name CSV.

Single-file, node-local-name companion to write_tree_solution (which writes a directory of per-scenario, all-variable files). Only rank 0 of the cylinder writes; the tree is assembled there by gather_nonant_tree_to_rank0.

Args:

file_name: path of the CSV file to write the xhat tree to

write_tree_solution(directory_name, scenario_tree_solution_writer=<function scenario_tree_solution_writer>)[source]

Writes the tree solution, if this object reports one available. Raises a RuntimeError if it is not.

Parameters:
  • directory_name – directory to write tree solution to

  • scenario_tree_solution_writer (optional) – custom scenario solution writer function

scenario_tree.py

This provides services for the scenario tree.

class mpisppy.scenario_tree.ScenarioNode(name, cond_prob, stage, cost_expression, nonant_list, scen_model, nonant_ef_suppl_list=None, surrogate_nonant_list=None, parent_name=None, linear_surrogate_definitions=None)[source]

Bases: object

Store a node in the scenario tree.

Note

This can only be created programmatically from a scenario creation function. (maybe that function reads data)

Parameters:
  • name (str) – name of the node; one node must be named “ROOT”

  • cond_prob (float) – conditional probability

  • stage (int) – stage number (root is 1)

  • cost_expression (pyo Expression or Var) – stage cost

  • nonant_list (list of pyo Var, VarData or slices) – the Vars that require nonanticipativity at the node (might not be a list)

  • scen_model (pyo concrete model) – the (probably not ‘a’) concrete model

  • nonant_ef_suppl_list (list of pyo Var, Vardata or slices) –

    Vars for which nonanticipativity constraints will only be added to the extensive form (important for bundling), but for which mpi-sppy will not enforce them as nonanticipative elsewhere.

    Note

    These types of variables are often indicator variables that are already present in the deterministic model.

  • surrogate_nonant_list (list of pyo Var, VarData or slices) –

    Vars for which nonanticipativity constraints are enforced implicitly by the vars in varlist, but which may speed PH convergence and/or aid in cut generation when considered explicitly. These vars will be ignored for fixers, incumbent finders which fix nonants to calculate solutions, and the EF creator.

    Note

    These types of variables are typically artificially added to the model to capture hierarchical model features.

  • linear_surrogate_definitions (list of LinearSurrogateDefinition) – Linear expressions of ordinary nonants for which mpi-sppy creates and registers auxiliary surrogate nonants.

  • parent_name (str) – name of the parent node

Lists:

nonant_vardata(list of vardata objects): vardatas to blend x_bar_list(list of floats): bound by index to nonant_vardata

Low Level

Most developers will not need to understand the low-level classes.

spcommunicator

This class handles communication between ranks.

spoke

hub