muse2/
simulation.rs

1//! Functionality for running the MUSE2 simulation across milestone years.
2use crate::asset::{Asset, AssetPool, AssetRef};
3use crate::model::Model;
4use crate::output::DataWriter;
5use crate::process::ProcessMap;
6use crate::simulation::prices::calculate_prices;
7use crate::units::Capacity;
8use anyhow::{Context, Result};
9use log::info;
10use std::path::Path;
11use std::rc::Rc;
12
13pub mod optimisation;
14use optimisation::{DispatchRun, FlowMap};
15pub mod investment;
16use investment::perform_agent_investment;
17pub mod prices;
18pub use prices::CommodityPrices;
19
20/// Run the simulation.
21///
22/// # Arguments:
23///
24/// * `model` - The model to run
25/// * `output_path` - The folder to which output files will be written
26/// * `debug_model` - Whether to write additional information (e.g. duals) to output files
27pub fn run(model: &Model, output_path: &Path, debug_model: bool) -> Result<()> {
28    let mut writer = DataWriter::create(output_path, &model.model_path, debug_model)?;
29    let mut user_assets = model.user_assets.clone();
30    let mut asset_pool = AssetPool::new(); // active assets
31    let mut decommissioned = Vec::new();
32
33    // Iterate over milestone years
34    let mut year_iter = model.iter_years().peekable();
35    let year = year_iter.next().unwrap(); // Unwrap is safe: model must contain at least one milestone year
36
37    info!("Milestone year: {year}");
38
39    // Commission assets for base year
40    asset_pool.commission_new(year, &mut user_assets);
41
42    // Write assets to file
43    writer.write_assets(asset_pool.iter())?;
44
45    // Gather candidates for the next year, if any
46    let next_year = year_iter.peek().copied();
47    let mut candidates = candidate_assets_for_next_year(
48        &model.processes,
49        next_year,
50        model.parameters.candidate_asset_capacity,
51    );
52
53    // Run dispatch optimisation
54    info!("Running dispatch optimisation...");
55    let (flow_map, mut prices) =
56        run_dispatch_for_year(model, asset_pool.as_slice(), &candidates, year, &mut writer)?;
57
58    // Write results of dispatch optimisation to file
59    writer.write_flows(year, &flow_map)?;
60    writer.write_prices(year, &prices)?;
61
62    while let Some(year) = year_iter.next() {
63        info!("Milestone year: {year}");
64
65        // Decommission assets whose lifetime has passed
66        asset_pool.decommission_old(year, &mut decommissioned);
67
68        // Commission user-defined assets for this year
69        asset_pool.commission_new(year, &mut user_assets);
70
71        // Take all the active assets as a list of existing assets
72        let existing_assets = asset_pool.take();
73
74        // Iterative loop to "iron out" prices via repeated investment and dispatch
75        let mut ironing_out_iter = 0;
76        let selected_assets: Vec<AssetRef> = loop {
77            // Add context to the writer
78            writer.set_debug_context(format!("ironing out iteration {ironing_out_iter}"));
79
80            // Perform agent investment
81            info!("Running agent investment...");
82            let selected_assets =
83                perform_agent_investment(model, year, &existing_assets, &prices, &mut writer)
84                    .context("Agent investment failed")?;
85
86            // Run dispatch optimisation to get updated prices for the next iteration
87            info!("Running dispatch optimisation...");
88            let (_flow_map, new_prices) =
89                run_dispatch_for_year(model, &selected_assets, &candidates, year, &mut writer)?;
90
91            // Check if prices have converged using time slice-weighted averages
92            let prices_stable = prices.within_tolerance_weighted(
93                &new_prices,
94                model.parameters.price_tolerance,
95                &model.time_slice_info,
96            );
97
98            // Update prices for the next iteration
99            prices = new_prices;
100
101            // Clear writer context
102            writer.clear_debug_context();
103
104            // Break early if prices have converged
105            if prices_stable {
106                info!("Prices converged after {} iterations", ironing_out_iter + 1);
107                break selected_assets;
108            }
109
110            // Break if max iterations reached
111            ironing_out_iter += 1;
112            if ironing_out_iter == model.parameters.max_ironing_out_iterations {
113                info!(
114                    "Max ironing out iterations ({}) reached",
115                    model.parameters.max_ironing_out_iterations
116                );
117                break selected_assets;
118            }
119        };
120
121        // Add selected_assets to the active pool
122        asset_pool.extend(selected_assets);
123
124        // Decommission unused assets
125        asset_pool.mothball_unretained(existing_assets, year);
126        asset_pool.decommission_mothballed(
127            year,
128            model.parameters.mothball_years,
129            &mut decommissioned,
130        );
131
132        // Write assets
133        writer.write_assets(decommissioned.iter().chain(asset_pool.iter()))?;
134
135        // Gather candidates for the next year, if any
136        let next_year = year_iter.peek().copied();
137        candidates = candidate_assets_for_next_year(
138            &model.processes,
139            next_year,
140            model.parameters.candidate_asset_capacity,
141        );
142
143        // Run dispatch optimisation
144        info!("Running final dispatch optimisation for year {year}...");
145        let (flow_map, new_prices) =
146            run_dispatch_for_year(model, asset_pool.as_slice(), &candidates, year, &mut writer)?;
147
148        // Write results of dispatch optimisation to file
149        writer.write_flows(year, &flow_map)?;
150        writer.write_prices(year, &new_prices)?;
151
152        // Prices for the next year
153        prices = new_prices;
154    }
155
156    writer.flush()?;
157
158    Ok(())
159}
160
161// Run dispatch to get flows and prices for a milestone year
162fn run_dispatch_for_year(
163    model: &Model,
164    assets: &[AssetRef],
165    candidates: &[AssetRef],
166    year: u32,
167    writer: &mut DataWriter,
168) -> Result<(FlowMap, CommodityPrices)> {
169    // Run dispatch optimisation with existing assets only, if there are any. If not, then assume no
170    // flows (i.e. all are zero)
171    let (solution_existing, flow_map) = (!assets.is_empty())
172        .then(|| -> Result<_> {
173            let solution =
174                DispatchRun::new(model, assets, year).run("final without candidates", writer)?;
175            let flow_map = solution.create_flow_map();
176
177            Ok((Some(solution), flow_map))
178        })
179        .transpose()?
180        .unwrap_or_default();
181
182    // Perform a separate dispatch run with both existing assets and candidates, if there are any,
183    // to get prices. If not, use the previous solution.
184    let solution_for_prices = (!candidates.is_empty())
185        .then(|| {
186            DispatchRun::new(model, assets, year)
187                .with_candidates(candidates)
188                .run("final with candidates", writer)
189        })
190        .transpose()?
191        .or(solution_existing);
192
193    // If there were either existing or candidate assets, we can calculate prices.
194    // If not, return empty maps.
195    let prices = solution_for_prices
196        .map(|solution| calculate_prices(model, &solution, year))
197        .transpose()?
198        .unwrap_or_default();
199
200    Ok((flow_map, prices))
201}
202
203/// Create candidate assets for all potential processes in a specified year
204fn candidate_assets_for_next_year(
205    processes: &ProcessMap,
206    next_year: Option<u32>,
207    candidate_asset_capacity: Capacity,
208) -> Vec<AssetRef> {
209    let mut candidates = Vec::new();
210    let Some(next_year) = next_year else {
211        return candidates;
212    };
213
214    for process in processes
215        .values()
216        .filter(move |process| process.active_for_year(next_year))
217    {
218        for region_id in &process.regions {
219            candidates.push(
220                Asset::new_candidate_for_dispatch(
221                    Rc::clone(process),
222                    region_id.clone(),
223                    candidate_asset_capacity,
224                    next_year,
225                )
226                .unwrap()
227                .into(),
228            );
229        }
230    }
231
232    candidates
233}