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