Manuscript Offprint
arXiv:2609.21495Scentree: a framework for generating scenario trees for multistage stochastic programming
Open access. PaperVantage converted this article to text, so layout and figures may differ from the original. This text is shared under the same licence.
Abstract
We present scentree, an open-source Python package for constructing scenario trees for multistage stochastic programming models using either historical data or samples drawn from a probability distribution. It combines machine learning and multivariate time series models to obtain a scenario fan that captures dependencies in the stochastic processes. This scenario fan is subsequently reduced into a scenario tree that preserves representativeness of the stochastic process, providing a flexible and extensible framework for uncertainty modeling in stochastic programming problems. The framework can also be naturally applied to two-stage stochastic programming problems. Key contributions are the joint modeling of the stochastic process, preserving correlations between all random variables, and the automation of the complete workflow, including forecasting model selection, parameter estimation, scenario fan generation, and scenario tree construction. In addition, scentree does not assume any underlying data distribution, reducing the statistical expertise required to produce a scenario tree, and is modular by design, allowing external forecasts and other partial executions of the workflow.
Keywords: scenario tree, multistage stochastic programming, uncertainty estimation, machine learning, multivariate time series models.
1 Introduction
Uncertainty arises naturally in many situations where decision must be made before all relevant information is available. For instance, in finance, investment decisions are made under uncertainty about future market conditions (Dixit and Pindyck, 2012). Similarly, in energy system operation, decisions regarding electricity generation must be made before future demand is known (Roald et al., 2023). In these and other applications, uncertain quantities evolve over time, and new information becomes available as the decision-making process progresses.
Multistage stochastic programming (Birge and Louveaux, 2011; Pflug and Pichler, 2014) provides a mathematical framework for addressing these decision problems by explicitly incorporating the evolution of uncertain parameters across multiple stages. At each stage, decisions can be adjusted according to the information available up to that point, allowing the model to account for the sequential revelation of uncertainty.
A key component of a multistage stochastic program is the representation of the underlying uncertainty. In its most general form, uncertain quantities can be described by a stochastic process. Usually, these stochastic processes admit infinitely many possible realizations, making their direct incorporation into a mathematical optimization model impractical. Consequently, a discrete approximation of the stochastic process is required. Such an approximation can be represented by a finite collection of scenarios (Dupačová et al., 2000), where each scenario corresponds to one possible realization of the stochastic process over the planning horizon.
In multistage problems, scenarios must capture the structure of the underlying uncertain process, which is typically defined over an index set representing time or other relevant dimensions. A scenario fan consists of a collection of possible trajectories of the uncertain process, with each scenario representing one possible evolution across the stages. A scenario tree provides the structured representation of these scenarios following the multistage decision-taking process defined in the associated stochastic programming problem, where scenarios can share nodes at a given stage and branch into different possible subsequent evolutions. Probabilities are assigned to the nodes to quantify the likelihood of the corresponding realizations, allowing the resulting discrete representation to be incorporated into a multistage stochastic programming model.
The construction of representative scenarios and, subsequently, a suitable scenario tree is therefore an essential step in the practical application of multistage stochastic programming. A scenario representation should capture the main characteristics of the underlying stochastic process. When historical observations of the uncertain process are available, scenario generation can be approached directly from data rather than by assuming a predefined probability distribution. This approach is particularly relevant when the underlying process is multivariate or exhibits complex temporal dependencies.
Building on these considerations, we present scentree, an open-source Python (Python Software Foundation, 2026) framework for generating scenario fans and scenario trees for multistage stochastic programming problems from historical data. The package is equally applicable to both two-stage and multistage stochastic problems. However, this work focuses on the multistage setting, as it is more general, complex, interesting and challenging from a methodological perspective, than two-stage problems, and fewer software tools are available for it.
In this context, the main contributions are (i) a data-driven approach based on historical data for developing predictive models; (ii) the integration of statistical and machine learning models; (iii) the ability to account for dependencies, such as correlations, among variables; (iv) a modular design supporting external forecasting tools; and (v) a fully automated workflow that reduces the expertise required from users to develop and apply forecasting algorithms.
To establish the mathematical framework used throughout the paper, we introduce the notation for the decision process, the optimization problem, the underlying stochastic process, and the scenario tree. Multistage stochastic programming models sequential decision-making under uncertainty, in which decisions are made as random information is revealed across stages. Following Pflug and Pichler (2014, Section 1.2), we represent this sequential structure as
possibly followed by a terminal decision . The initial decision, , is deterministic, and each subsequent decision , , depends only on the observed random variables , ensuring nonanticipativity.
A multistage stochastic programming problem optimizes this decision process; in the risk-neutral case, its general formulation is
where denotes the sequence of decisions, the sequence of random variables, the total cost, and the feasible set. We model the uncertainty through a multivariate stochastic process
where is the index set and is the sample space. Each stage is associated with a stochastic process
with
Our objective is to obtain a discrete approximation of the underlying stochastic process , represented by a scenario tree. We define
where is a finite sample space whose elements correspond to the scenarios of the tree. A discrete probability distribution is defined over , assigning a probability to each scenario.
In practice, the stochastic process is inferred from historical data, represented by a matrix of size , where denotes the number of observed realizations of the stochastic process and is the dimension of each realization.
To the best of our knowledge, scentree is the first Python framework specifically designed for scenario fan and tree generation using statistical and machine learning algorithms. The framework is also well suited to two-stage stochastic programming problems, as it provides a systematic approach for generating data-driven representations of uncertainty from historical observations.
The remainder of this paper is organized as follows. Section 2 presents and discusses the state of the art in scenario generation software. Section 3 provides a detailed description of the scentree package, followed by an illustrative example in Section 4. Finally, Section 5 presents the conclusions and discusses potential directions for future research.
Recent advances in scientific computing have established Julia (Bezanson et al., 2017) as a promising programming language for data science, particularly for computationally intensive statistical and numerical methods. In this context, Kirui et al. (2020) present the first Julia package dedicated to scenario generation for multistage stochastic programming, ScenTrees.jl. Scenario generation can be based either on a user-defined stochastic process or, when historical data are available, on kernel density estimation (KDE for short; Silverman, 1986), which is implemented in the package.
With regard to KDE, a limitation of the current implementation is that kernel_scenarios, which is the functionality that generates trajectories, only supports univariate kernel density estimation. Its interface accepts only two-dimensional arrays (i.e. matrices), where rows represent sample paths and columns represent stages, so each observation is assumed to be scalar. As a result, dependencies among the components of multivariate random vectors cannot be modeled, preventing the direct generation of multivariate scenario trees from data.
StochOptim (Keutchayan et al., 2020) is a Python package for generating scenarios. It is a framework for solving two-stage and multistage stochastic problems. It includes algorithms for scenario tree construction. It supports both scenario generation from user-specified probability distributions and scenario clustering based on historical data. The official GitHub repository (https://github.com/julienkeutchayan/StochOptim) and the PyPI release (https://pypi.org/project/stochoptim/) have not been updated since 2021, suggesting that it is no longer actively maintained.
We next consider stochastic programming software primarily designed for modeling and solving stochastic programs that also provides some limited scenario generation capabilities. The work of Knueven et al. (2023) presents mpi-sppy, a Python package whose main feature is its efficient parallelization capabilities when solving multistage stochastic optimization problems. This framework incorporates a functionality for defining and managing scenario trees, including scenario topology and probabilities, non-anticipativity information, and parallel scenario processing, but does not provide dedicated methods for scenario generation.
Biel and Johansson (2022) present StochasticPrograms.jl, an open-source framework for modeling and solving stochastic programming problems in Julia. The package provides an expressive modeling language, parallel implementations of structure-exploiting algorithms, such as variants of the L-shaped method, and distributed-memory support for large-scale instances. Regarding scenario generation, the framework does not provide methods for generating scenarios from historical data. Instead, it relies on user-supplied scenarios or on user-defined sampling mechanisms representing the underlying stochastic process.
SDDP.jl (Dowson and Kapelevich, 2021) is an open-source Julia package for solving large multistage stochastic optimization problems using the Stochastic Dual Dynamic Programming (SDDP) algorithm (Philpott et al., 2013). Built on top of JuMP (Dunning et al., 2017), it provides a high-level modeling interface while maintaining performance comparable to low-level implementations. Its main contribution is the development of a flexible, solver-independent, and extensible implementation of SDDP. The package assumes that the uncertainty has already been discretized into a finite set of outcomes (or represented through a user-defined stochastic process). Consequently, SDDP.jl focuses on solving the resulting multistage stochastic program and does not provide methods for generating scenarios from historical data.
3 Scentree package
The framework is inspired by Heredia et al. (2018); Cuadrado-Guevara (2020); Solà Vilalta et al. (2025), who propose constructing scenario trees using time series factor analysis (TSFA; Gilber and Meijer, 2005).
These works focus on modeling electricity price and variable renewable energy uncertainty within a multistage stochastic programming framework. The authors use TSFA to (i) obtain a low-dimensional representation of the data, (ii) estimate the underlying stochastic process, and (iii) predict future values to generate a scenario fan. Subsequently, tree reduction algorithms are applied to obtain a scenario tree, with the ultimate goal of supporting participation in the electricity market.
From an implementation perspective, scentree is designed to provide flexibility by allowing scenario fan generation to be performed independently of scenario tree construction. Thus, users can construct a scenario tree from a scenario fan generated with an external tool. The scenario fan generation methodology is presented in Section 3.1, while the tree reduction procedure is described in Section 3.2. Section 3.3 provides a detailed description of the package output.
Finally, note that the code is open-source, publicly available on GitHub at https://github.com/mmobec/scentree. It can be downloaded from PyPI at https://pypi.org/project/scentree and the documentation is on readthedocs at https://scentree.readthedocs.io.
3.1 Scenario fan generation
As the dimension of the stochastic process, , could be so large as to incur the curse of dimensionality (Bellman, 1957), the first step is to obtain a low-dimensional representation by means of Principal Component Analysis (PCA; Pearson, 1901). The number of principal components is automatically selected to explain at least 80% of the total variance, following a commonly used variance-retention criterion (Dunteman, 1989). After applying PCA to the data, the resulting matrix is of size , where denotes the dimension of the resulting space. Note that before applying PCA, the data are scaled so that the mean and variance of each column are 0 and 1, respectively. Let be the resulting matrix after applying PCA.
Once the data are preprocessed, a set of predictive model families, denoted by , is considered to identify the best-performing model. The families in include multivariate time series models, such as vector autoregressive models (Sims, 1980), and machine learning models, including support vector machines (Cortes and Vapnik, 1995).
In order to select the best predictive model for each family in , the first step consists of hyperparameter tuning. Since the data are indexed by , we use time series cross-validation (Bergmeir and Benítez, 2012). As a result, a set of predictive models, , is obtained. Each model in is the best-performing one within its respective family.
Afterwards, the final predictive algorithm, , is selected using the root mean squared error:
where denotes the number of lags, which is a hyperparameter selected in the first step, the norm and the th row of .
Now, let denote the number of scenario fans (each associated with a distinct instance of the problem formulated in Equation 1) and the number of scenarios in each fan required by the user. We derive predicted values using the predictive model . Note that the user may be interested in obtaining in-sample predictions, that is, estimating the last steps of the data. The package has a parameter, build_in_sample_fans, that allows the user to choose whether the estimated values correspond to the last steps, i.e. from to , or to the next steps, i.e. from to . Let be the set of predicted values.
Scenario fans are constructed by combining predicted values with estimated residuals. The latter are computed from historical data as
where
denotes the predicted value for . To obtain scenario fans, we follow the iterative process described in Algorithm 1. Note that the output is a tensor of size or, equivalently, a vector of length whose entries are matrices of size . Essentially, to obtain a scenario fan, we apply a Monte Carlo method (Hammersley and Handscomb, 1964).
Algorithm 1 Scenario fan generation
Set of predicted values
Set of residuals
Number of scenarios
Define a tensor of size and initialize it as empty
for do
Sample, at random and without replacement, residuals,
Define a matrix of size and initialize it as empty
for do
end for
end for
Output: Scenario fans in the low-dimensional space, i.e., tensor
Due to the nature of PCA, any point in the low-dimensional space, whether or not it belongs to the historical data, can be mapped back to the original -dimensional space. In brief, let denote the matrix containing the principal directions selected during PCA. The original-space representation is then obtained by multiplying the low-dimensional representation by . Accordingly, we define as the tensor of size containing the -dimensional scenario fans obtained from by (i) mapping them back to the original space and (ii) rescaling them to recover the initial data scale.
The first implementation includes a penalized linear regression model, a support vector machine, and a vector autoregressive model. We use scikit-learn (Pedregosa et al., 2011) and statsmodels (Seabold and Perktold, 2019) to incorporate these predictive models. The framework also allows additional models from these libraries, as well as models from other libraries or custom implementations, to be integrated straightforwardly, as its design is agnostic to any particular package or implementation.
Finally, from a theoretical point of view, applying a dimensionality reduction transformation to a stochastic process results in another stochastic process, now taking values in a low-dimensional space. In particular, if denotes the dimensionality reduction transformation (PCA in our case), the resulting process is defined as
Note that the index set remains unchanged. This approach is also exploited by Hyndman and Shang (2009), who forecast the principal component scores of functional observations as time series.
A scenario fan consists of complete trajectories but does not explicitly represent the information available at each stage. A scenario tree organizes these trajectories according to their shared history, providing a representation of the evolving uncertainty required in multistage stochastic programming (Shapiro et al., 2009). In addition, the total number of nodes in the scenario tree is significantly smaller than in the scenario fan, reducing the size of the multistage stochastic programming problem to be solved while preserving representativeness of the underlying stochastic process. In Section 3.2, we describe how to construct the scenario tree from the scenario fan.
3.2 Scenario tree reduction
Heitsch and Römisch (2009) propose the forward tree construction (FTC) algorithm to construct a scenario tree from an initial scenario fan. The objective is to represent the scenario fan as a tree whose nodes represent possible realizations of the stochastic process and whose edges connect realizations across consecutive stages. Figure 1 illustrates an example of a scenario tree for a three-stage multistage stochastic problem.
The procedure starts with a single root node to which all scenarios are associated. The tree is then constructed sequentially over the stages. Given a node at stage , the scenarios associated with that node are used to construct its successor nodes at stage . This is done by selecting representative scenarios according to a prescribed distance criterion and subsequently redistributing the scenarios among the selected representatives.
The forward selection procedure iteratively selects representative scenarios from the set of scenarios associated with a node. Once the representatives have been selected, an optimal redistribution assigns each scenario to the representative that minimizes the corresponding distance. Each representative and its associated scenarios then define a successor node at the next stage. This procedure is applied recursively to the resulting nodes until the final stage is reached, yielding the scenario tree .
RootStage 1Stage 2Stage 3
Figure 1: Example of a scenario tree.
It is important to note that each node results from clustering a set of scenarios and therefore contains all the scenarios assigned to the corresponding cluster. In terms of data, the resulting scenario tree can be represented by a matrix of size . At each stage, scenarios assigned to the same node share the same data values for the columns corresponding to that stage. These values are given by the scenario selected as the representative of that node.
The FTC algorithm also computes the probability of each node at each stage throughout the scenarios. Initially, the scenarios are assigned their fan probability (by default, a uniform distribution over the set of scenarios is assumed). Once the nodes are obtained, the probability of each node is computed by adding the probabilities of the scenarios assigned to it. At the implementation level, since each node contains a unique scenario representative, the node’s probability is assigned to its representative scenario, while the other scenarios belonging to the same node are assigned a probability of zero.
Our framework implements the FTC algorithm to construct the scenario trees. For each of the scenario fans, a corresponding scenario tree is obtained. To run the algorithm, the tensor obtained in Section 3.1 is considered. In terms of data, after constructing all the trees, a tensor of size is obtained.
Although FTC is one of the earliest algorithms proposed, considerable research has been devoted to this topic. Examples include Hewitt et al. (2022); Medina-González et al. (2020); Li and Gao (2019). Consequently, the tree reduction component in scentree is agnostic to the underlying algorithm, allowing alternative tree reduction methods to be implemented without affecting the existing ones. The choice of method is therefore left to the user.
3.3 Output structure
The construction of the scenario fan and the scenario tree generates several relevant data. In particular, two parts of the process produce data that require further explanation: the generation of the scenario fan and the construction of the scenario tree.
Regarding scenario fan generation, the output is a dictionary with the following structure:
- observed_values: when build_in_sample_fans is set to True, this is an array containing arrays, each storing the observed values. Otherwise, this variable contains no data.
- predicted_values: an array containing arrays, each storing the values predicted by the predictive model.
- scenarios: an array containing matrices, each representing the trajectories of the stochastic process.
A multistage stochastic programming problem can be formulated in two different ways. The first, which we refer to as the nodal formulation, associates decision variables with the nodes of the scenario tree, thereby enforcing nonanticipativity implicitly. The second, which we refer to as the nonanticipativity formulation, explicitly imposes nonanticipativity constraints to ensure the consistency of decisions across scenarios sharing the same history.
To support both formulations, the tree output provides the information required to construct either representation of the optimization problem. Accordingly, the output consists of a Python dictionary with two keys: nodal_formulation and nac_formulation, corresponding to the nodal and nonanticipativity formulations, respectively.
The output of the nodal formulation consists of an array of length , with each element containing the following information:
- nodes: the nodes belonging to each stage, represented by a dictionary whose keys are stage identifiers and whose values are lists of node identifiers.
- node_scenarios: the scenarios associated with each node, represented by a dictionary whose keys are node identifiers and whose values are lists of scenario identifiers.
- parent: the parent node associated with each node, represented by a dictionary whose keys are node identifiers and whose values identify their respective parent nodes.
- probability: the probability associated with each node, represented by a dictionary whose keys are node identifiers and whose values specify the corresponding probabilities.
- random_variable_value: the scenario data values associated with each node, represented by a dictionary whose keys are node identifiers and whose values are NumPy arrays (Harris et al., 2020) containing the corresponding values from matrix (see Section 3.2).
- stage: the stage associated with each node, represented by a dictionary whose keys are node identifiers and whose values indicate the corresponding stage.
Note that the example provided in Section 4 uses the nodal formulation. By directly supporting this formulation, the scenario tree can be easily and seamlessly integrated into optimization modeling frameworks, as demonstrated throughout the example.
On the other hand, the output of the nonanticipativity formulation consists of an array of length , where each element is a dictionary following the same structure:
- scenario_probabilities: an array of length containing the final probability of each scenario. All scenarios belonging to the same node have a probability of zero, except for the representative scenario, whose probability is equal to that of the node it represents.
- scenario_tree_data: a matrix of size containing the scenario tree data. As explained in Section 3.2, all scenarios belonging to the same node share exactly the same data values, thereby ensuring nonanticipativity.
- tree: an array representing the tree, in which each element corresponds to a node and consists of a dictionary organized as follows: – key: a unique identifier for the node. It is a Python tuple whose first element indicates the stage and whose second element identifies the node within that stage. – scenario_ids: an array containing the identifiers of the scenarios belonging to this node. – parent_key: a tuple containing the identifier of the parent node. – description: a human-readable string providing a textual representation of the key field.
4 Illustrative example: the Flowergirl problem
We consider the Flowergirl inventory problem of Pflug and Pichler (2014, Example 1.4): a retailer orders before uncertain demand, carries surviving stock forward, and covers shortages through more expensive emergency purchases. The multistage decision process is
where are the orders and the demand, The tree has a deterministic root and three observation stages, ending in settlement rather than another regular order. At every stage the selling price is 1, the purchase cost is , the emergency cost is and the survival fraction is .
Let be the scenario tree, with root node , where at every node the random variable is observed with probability . is the set of nodes at stage , is the parent of node , and is the stage of node (thus ). denotes the nodes from the root to the stage included, and the nodes from stage to final stage, included.
At every node, after observing the demand , a regular order will be placed, generating a stock , . is the inventory available at the next stage, while is the shortage that must be supplied at the emergency cost . As in Pflug and Pichler (2014) we assume that the final stock , , if some, is sold at at price . The corresponding MSP is
Throughout this section, we provide a set of code listings illustrating the different steps of the proposed workflow and enabling readers to reproduce the results presented. These listings cover the main functionalities of the scentree package, from scenario fan generation to scenario tree construction and its subsequent use in the optimization problem. For completeness, the complete implementation, including all the code required to reproduce the results, is available at https://github.com/mmobec/scentree/blob/main/scentree/examples/flowergirl.ipynb.
4.1 Data loader
Our package includes demand data for 401 consecutive days, represented by a matrix. Each row represents a three-period campaign, with consecutive rows corresponding to campaigns on consecutive days rather than demand periods. We solve the optimization problem for the final day, corresponding to row 401, which we refer to as the target day.
Accordingly, we partition the data into two sets: the historical data, consisting of the first 400 days and denoted by throughout this work, and the data corresponding to the target day. The historical data are used to generate the scenario fan for the target day (Section 4.2), from which a reduced scenario tree is constructed (Section 4.3) and subsequently used to solve the multistage stochastic programming problem (Section 4.4).
Listing 1 illustrates how the data are imported, loaded and partitioned. The DatasetLoader class provides methods for organizing and manipulating data. It is particularly useful when working with multiple datasets, as it facilitates their management. As shown in Listing 1 the data corresponding to the target day are stored in target_day variable.
⬇
import numpy as np
from scentree.io.data import load_flowergirl
from scentree.io.loader import Dataset, DatasetsLoader
Load the data and convert it into a scentree dataset
flowergirl_ds = load_flowergirl()
Y, target_day = flowergirl_ds[:-1],flowergirl_ds[-1]
datasets = [Dataset(
name="demand",
values=Y,
stage_ids=[1, 2, 3],
bounds=(0., np.inf),
)]
dsl = DatasetsLoader(datasets=datasets)
full_values = dsl.get_full_values()
stage_ids = dsl.get_sorted_stage_ids()
num_vars = dsl.get_num_variables_per_stage()
stage_cols_map = dsl.create_stage_columns_mapping()
Listing 1: Data import and loading.
Figure 2(a) shows the historical demand data for 400 consecutive days, with three demand periods per day. The black dashed line represents the demand observations for the target day. This representation highlights the variability in demand across both days and periods within each campaign.
4.2 Fan generation
The scenario fan can be generated as illustrated in Listing 2. StageManager class is responsible of fan generation. The user must specify the number of fans and scenarios; in our case, these are set to 1 and 80, respectively.
⬇
from scentree.fan_generator import StageManager
num_fans = 1
num_scenarios = 80
stage_manager = StageManager()
scenario_fans = stage_manager.generate_scenario_fans(
X=full_values,
num_fans=num_fans,
num_scenarios=num_scenarios,
build_in_sample_fans=False,
seed=204
)
fan = scenario_fans["scenarios"][0]
Listing 2: Fan generator.
Furthermore, the framework can generate scenario fans for both observed and unobserved days, i.e., future days. This behavior is controlled by the boolean variable build_in_sample_fans. For observed days, the scenario fans correspond to the last num_fans days, whereas for future days, they correspond to the subsequent num_fans days. In both cases, the scenario fans are generated in increasing chronological order. In our case, build_in_sample_fans is set to false.
Figure 2(b) shows the scenario fan generated for the target day, consisting of 80 demand trajectories. Each trajectory represents a possible realization of demand across the three periods of the campaign. The black dashed line represents the actual demand for the target day.
4.3 Tree reduction
We next employ the package to construct a reduced tree. Listing 3 illustrates how to use the package for this purpose. The output is stored in tree_instance, a list of dictionaries, each representing a scenario tree for a different day. In this example, the list contains a single dictionary because only one day is requested. The tree reduction algorithm reduces the 80-trajectory fan to nine terminal tree scenarios, producing a 1–4–7–9 tree.
⬇
from scentree.tree_construction.ftc import FTC
tree_instance = FTC(
scenarios=scenario_fans["scenarios"],
num_variables_per_stage=num_vars,
stage_ids=stage_ids
)
tree_structure = tree_instance.generate_scenario_trees(
r=1.,
stage_columns_mapping=stage_cols_map,
initial_stage_id_to_cluster=1,
seed=15,
)
tree_nac = tree_structure["nac_formulation"][0]
tree_data = tree_nac["scenario_tree_data"]
tree_data_matrix = np.unique(tree_data, axis=0)
Listing 3: Tree reduction.
(a) Historical data composed by 400 trajectories.
(b) Generated scenario fan with 80 scenarios
(c) Reduced scenario tree containing nine scenarios.
Figure 2: Historical demand data, scenario fan, and reduced scenario tree for the Flowergirl problem. The black dashed line indicates the target day for which the scenario fan and reduced scenario tree are constructed.
Figure 2(c) shows the scenario tree obtained by reducing the scenario fan to nine scenarios for the target day. The black dashed line indicates the actual demand observations for the target day.
4.4 Solution of the problem
Finally, we illustrate how the resulting stochastic programming problem is solved. We use Pyomo (Hart et al., 2011) as the optimization modeling framework. Before formulating the problem, we extract the data required from the reduced scenario tree, as shown in Listing 4.
⬇
ndl_formulation = tree_structure[’nodal_formulation’][0]
parent = ndl_formulation["parent"]
stage = ndl_formulation["stage"]
xi = ndl_formulation["random_variable_value"]
pi = ndl_formulation["probability"]
members = ndl_formulation["node_scenarios"]
nodes = ndl_formulation[’nodes’]
Listing 4: Data preprocessing for Pyomo compatibility defining the data structure of the Flowergirl formulation.
The model incorporates the reduced scenario tree and its associated probabilities to account for demand uncertainty across the three periods. The implementation is provided in Listing 5. The values of the optimal initial order and the optimal expected profit are and , respectively. Figure 3 illustrates the scenario tree in graph form and the optimal solution and .
This completes the workflow, from scenario fan generation and scenario tree reduction using scentree to the formulation and solution of the optimization problem using Pyomo. By integrating these steps into a single process, the package provides a systematic approach to incorporating demand uncertainty into the optimization model.
⬇
import pyomo.environ as pyo
def flowergirl_model(parent, stage, xi, pi):
root = next(n for n in stage if parent[n] is None)
N = list(stage)
B = [n for n in N if n != root]
O = [n for n in N if stage[n] < 3]
F = [n for n in N if stage[n] == 3]
m = pyo.ConcreteModel()
m.b, m.u, m.ell = 0.85, 1.25, 0.5
m.x = pyo.Var(O, domain=pyo.NonNegativeReals)
m.zeta_plus = pyo.Var(
N, domain=pyo.NonNegativeReals
)
m.zeta_minus = pyo.Var(
B, domain=pyo.NonNegativeReals
)
m.zeta_plus[root].fix(0.)
m.zeta = pyo.Expression(
B,
rule=lambda m, n:m.zeta_plus[n] - m.zeta_minus[n]
)
def balance(m, n):
a = parent[n]
prod = m.x[a] + m.ell * m.zeta_plus[a]
return prod - xi[n] == m.zeta[n]
m.balance = pyo.Constraint(B, rule=balance)
m.profit = pyo.Objective(
sense=pyo.maximize,
expr=sum(pi[n] * xi[n] for n in B)
-
m.b * sum(pi[n] * m.x[n] for n in O)
-
m.u * sum(pi[n] * m.zeta_minus[n] for n in B)
- m.ell * sum(pi[n] * m.zeta_plus[n] for n in F)
)
return m
model = flowergirl_model(parent, stage, xi, pi)
solver = pyo.SolverFactory("appsi_highs")
solution = solver.solve(model)
Listing 5: Pyomo implementation of the Flowergirl optimization problem.
Figure 3: Flowergirl tree represented as a directed graph. Every node includes: node number , demand , , and and the scenarios traversing the node.
5 Conclusions and future research
This work presents scentree, an open-source Python package for generating scenario fans and scenario trees for multistage stochastic programming using historical data. To the best of our knowledge, scentree is the first Python package specifically designed to generate scenario fans and scenario trees using machine learning and multivariate time series models for multivariate stochastic processes. The framework automates the main steps of generation process, from dimensionality reduction and model selection to scenario fan generation and scenario tree construction.
Scentree has three main features that highlight the value of its contribution. First, it does not require the user to specify a probability distribution for the underlying stochastic process, and the selection of predictive models is performed automatically. Consequently, only limited knowledge of statistics and machine learning is required to generate scenarios from historical data. Second, the framework is flexible by design. It is agnostic to the particular predictive model or tree construction method, allowing new models and scenario tree construction or clustering methods to be incorporated without affecting the existing implementations. In addition, its modular design allows partial executions of the framework. Third, the joint modeling of the multivariate stochastic process naturally captures the correlation between random variables.
Several extensions are planned for future research. First, we intend to incorporate additional machine learning, with particular attention to diffusion models and other recent techniques for time series modeling. These models may provide alternative approaches for capturing complex temporal dependencies and generating scenario fans. Second, recent methodologies for scenario tree construction will be investigated and incorporated into the framework. Finally, we plan to establish a connection with functional data analysis, which could provide a natural framework for modeling high-dimensional stochastic processes and their temporal evolution.
Overall, scentree is intended to provide a flexible and accessible framework for scenario generation, while maintaining sufficient extensibility to accommodate future developments in predictive modeling and scenario tree construction.
Acknowledgments
This work has been supported with grants PID2022-139219OB-I00 and Cetp-FP-2023-00185 from the Spanish Ministerio de Ciencia, Innovación y Universidades. This research has been funded by CETPartnership, the Clean Energy Transition Partnership under the 2023 joint call for research proposals, co-funded by the European Commission (GA N°101069750) and with the funding organisations FFG (Austria), AEI (Spain) and MUR (Italy).
References
R. E. Bellman Dynamic Programming. Princeton University Press. External Links: ISBN ISBN 978-0-691-07951-6 Cited by: §3.1.
C. Bergmeir and J. M. Benítez On the use of cross-validation for time series predictor evaluation. 191, pp. 192–213. External Links: Document Cited by: §3.1.
J. Bezanson, A. Edelman, S. Karpinski, and V. B. Shah Julia. 59 (1), pp. 65–98. External Links: Document Cited by: §2.
M. Biel and M. Johansson Efficient Stochastic Programming in Julia. 34 (4), pp. 1885–1902. External Links: Document Cited by: §2.
J. R. Birge and F. Louveaux Introduction to Stochastic Programming. Springer Nature. External Links: Document, ISBN 978-1-4614-0236-7 Cited by: §1.
C. Cortes and V. Vapnik Support-Vector Networks. 20, pp. 273–297. External Links: Document Cited by: §3.1.
M. D. Cuadrado-Guevara Multistage scenario trees generation for renewable energy systems optimization. PhD’s thesis, Universitat Politècnica de Catalunya. External Links: Document, Link Cited by: §3.
R. K. Dixit and R. S. Pindyck Investment under Uncertainty. Princeton University Press. External Links: Document, ISBN 9781400830176 Cited by: §1.
O. Dowson and L. Kapelevich SDDP.jl. 33 (1), pp. 27–33. External Links: Document Cited by: §2.
I. Dunning, J. Huchette, and M. Lubin JuMP. 59 (2), pp. 295–320. External Links: Document Cited by: §2.
G. H. Dunteman Principal Components Analysis. SAGE Publications. External Links: ISBN 9780803931046 Cited by: §3.1.
J. Dupačová, G. Consigli, and S. W. Wallace Scenarios for Multistage Stochastic Programs. 100, pp. 25–53. External Links: Document Cited by: §1.
P. D. Gilber and E. Meijer Time Series Factor Analysis with an Application to Measuring Money. Technical report University of Groningen, Research Institute SOM (Systems, Organisations and Management). Cited by: §3.
J. M. Hammersley and D. C. Handscomb Monte Carlo Methods. Springer Nature. External Links: Document, ISBN 9780416523409 Cited by: §3.1.
C. R. Harris, K. J. Millman, S. J. van der Walt, R. Gommers, P. Virtanen, D. Cournapeau, E. Wieser, J. Taylor, S. Berg, N. J. Smith, R. Kern, M. Picus, S. Hoyer, M. H. van Kerkwijk, M. Brett, A. Haldane, J. F. del Río, M. Wiebe, P. Peterson, P. Gérard-Marchant, K. Sheppard, T. Reddy, W. Weckesser, H. Abbasi, C. Gohlke, and T. E. Oliphant Array programming with NumPy. 585 (7825), pp. 357–362. External Links: Document Cited by: 5th item.
W. E. Hart, J. Watson, and D. L. Woodruff Pyomo. 3, pp. 219–260. External Links: Document Cited by: §4.4.
H. Heitsch and W. Römisch Scenario tree modeling for multistage stochastic programs. 118, pp. 71–406. External Links: Document Cited by: §3.2.
F. Heredia, M. D. Cuadrado, and C. Corchero On optimal participation in the electricity markets of wind power plants with battery energy storage systems. 96, pp. 316–329. External Links: Document Cited by: §3.
M. Hewitt, J. Ortmann, and W. Rei Decision-based scenario clustering for decision-making under uncertainty. 315, pp. 747–771. External Links: Document Cited by: §3.2.
R. J. Hyndman and H. L. Shang Forecasting functional time series. 38 (3), pp. 199–211. External Links: Document Cited by: §3.1.
J. Keutchayan, D. Munger, and M. Gendreau On the Scenario-Tree Optimal-Value Error for Stochastic Programming Problems. 45 (4), pp. 1572–1595. External Links: Document Cited by: §2.
K. B. Kirui, A. Pichler, and G. Ch. Pflug ScenTrees.jl. 5 (46). External Links: Document Cited by: §2.
B. Knueven, D. Mildebrath, C. Muir, J. D. Siirola, J. Watson, and D. L. Woodruff A parallel hub-and-spoke system for large-scale scenario-based optimization under uncertainty. 15, pp. 591–619. External Links: Document Cited by: §2.
Q. Li and D. W. Gao Fast Scenario Reduction for Power Systems by Deep Learning. External Links: 1908.11486 Cited by: §3.2.
S. Medina-González, I. Gkioulekas, V. Dua, and L. G. Papageorgiou A graph theory approach for scenario aggregation for stochastic optimisation. 137. External Links: Document Cited by: §3.2.
K. Pearson On lines and planes of closest fit to systems of points in space. 2 (11), pp. 559–572. External Links: Document Cited by: §3.1.
F. Pedregosa, G. Varoquaux, A. Gramfort, V. Michel, B. Thirion, O. Grisel, M. Blondel, P. Prettenhofer, R. Weiss, V. Dubourg, J. Vanderplas, A. Passos, D. Cournapeau, M. Brucher, M. Perrot, and É. Duchesnay Scikit-learn. 12 (85), pp. 2825–2830. Cited by: §3.1.
G. Ch. Pflug and A. Pichler Multistage Stochastic Optimization. Springer Cham. External Links: Document, ISBN 978-3-319-08842-6 Cited by: §1, §1, §4, §4.
A. Philpott, V. de Matos, and E. Finardi On Solving Multistage Stochastic Programs with Coherent Risk Measures. 61 (4), pp. 957–970. External Links: Document Cited by: §2.
Python Software Foundation Python Programming Language. External Links: Link Cited by: §1.
L. A. Roald, D. Pozo, A. Papavasiliou, D. K. Molzahn, J. Kazempour, and A. Conejo Power systems optimization under uncertainty. 214. External Links: Document Cited by: §1.
S. Seabold and J. Perktold statsmodels. In 9th Python in Science Conference, pp. 92–96. External Links: Document Cited by: §3.1.
A. Shapiro, D. Dentcheva, and A. Ruszczyński Lectures on Stochastic Programming. SIAM. External Links: ISBN 978-0-89871-687-0 Cited by: §3.1.
B. W. Silverman Density estimation for statistics and data analysis. Chapman & Hall/CRC. External Links: ISBN 978-0-412-24620-3 Cited by: §2.
C. A. Sims Macroeconomics and Reality. 48 (1), pp. 1–48. External Links: Document Cited by: §3.1.
A. Solà Vilalta, I. M. Bosch, and F. Heredia Optimal Participation of Energy Communities in Electricity Markets under Uncertainty. External Links: Link Cited by: §3.