muse2/
input.rs

1//! Common routines for handling input data.
2use crate::asset::AssetPool;
3use crate::graph::investment::solve_investment_order_for_model;
4use crate::graph::validate::validate_commodity_graphs_for_model;
5use crate::graph::{CommoditiesGraph, build_commodity_graphs_for_model};
6use crate::id::{HasID, IDLike};
7use crate::model::{Model, ModelParameters};
8use crate::region::RegionID;
9use crate::units::UnitType;
10use anyhow::{Context, Result, bail, ensure};
11use float_cmp::approx_eq;
12use indexmap::IndexMap;
13use itertools::Itertools;
14use serde::de::{Deserialize, DeserializeOwned, Deserializer};
15use std::collections::HashMap;
16use std::fmt::{self, Write};
17use std::fs;
18use std::hash::Hash;
19use std::path::Path;
20
21mod agent;
22use agent::read_agents;
23mod asset;
24use asset::read_assets;
25mod commodity;
26use commodity::read_commodities;
27mod process;
28use process::read_processes;
29mod region;
30use region::read_regions;
31mod time_slice;
32use time_slice::read_time_slice_info;
33
34/// A trait which provides a method to insert a key and value into a map
35pub trait Insert<K, V> {
36    /// Insert a key and value into the map
37    fn insert(&mut self, key: K, value: V) -> Option<V>;
38}
39
40impl<K: Eq + Hash, V> Insert<K, V> for HashMap<K, V> {
41    fn insert(&mut self, key: K, value: V) -> Option<V> {
42        HashMap::insert(self, key, value)
43    }
44}
45
46impl<K: Eq + Hash, V> Insert<K, V> for IndexMap<K, V> {
47    fn insert(&mut self, key: K, value: V) -> Option<V> {
48        IndexMap::insert(self, key, value)
49    }
50}
51
52/// Read a series of type `T`s from a CSV file.
53///
54/// Returns an error if the file is empty.
55///
56/// # Arguments
57///
58/// * `file_path` - Path to the CSV file
59pub fn read_csv<'a, T: DeserializeOwned + 'a>(
60    file_path: &'a Path,
61) -> Result<impl Iterator<Item = T> + 'a> {
62    let vec = read_csv_internal(file_path)?;
63    if vec.is_empty() {
64        bail!("CSV file {} cannot be empty", file_path.display());
65    }
66    Ok(vec.into_iter())
67}
68
69/// Read a series of type `T`s from a CSV file.
70///
71/// # Arguments
72///
73/// * `file_path` - Path to the CSV file
74pub fn read_csv_optional<'a, T: DeserializeOwned + 'a>(
75    file_path: &'a Path,
76) -> Result<impl Iterator<Item = T> + 'a> {
77    if !file_path.exists() {
78        return Ok(Vec::new().into_iter());
79    }
80
81    let vec = read_csv_internal(file_path)?;
82    Ok(vec.into_iter())
83}
84
85fn read_csv_internal<'a, T: DeserializeOwned + 'a>(file_path: &'a Path) -> Result<Vec<T>> {
86    let vec = csv::ReaderBuilder::new()
87        .trim(csv::Trim::All)
88        .from_path(file_path)
89        .with_context(|| input_err_msg(file_path))?
90        .into_deserialize()
91        .process_results(|iter| iter.collect_vec())
92        .with_context(|| input_err_msg(file_path))?;
93
94    Ok(vec)
95}
96
97/// Parse a TOML file at the specified path.
98///
99/// # Arguments
100///
101/// * `file_path` - Path to the TOML file
102///
103/// # Returns
104///
105/// * The deserialised TOML data or an error if the file could not be read or parsed.
106pub fn read_toml<T: DeserializeOwned>(file_path: &Path) -> Result<T> {
107    let toml_str = fs::read_to_string(file_path).with_context(|| input_err_msg(file_path))?;
108    let toml_data = toml::from_str(&toml_str).with_context(|| input_err_msg(file_path))?;
109    Ok(toml_data)
110}
111
112/// Read a Dimensionless float, checking that it is between 0 and 1
113pub fn deserialise_proportion_nonzero<'de, D, T>(deserialiser: D) -> Result<T, D::Error>
114where
115    T: UnitType,
116    D: Deserializer<'de>,
117{
118    let value = f64::deserialize(deserialiser)?;
119    if !(value > 0.0 && value <= 1.0) {
120        Err(serde::de::Error::custom("Value must be > 0 and <= 1"))?;
121    }
122
123    Ok(T::new(value))
124}
125
126/// Format an error message to include the file path. To be used with `anyhow::Context`.
127pub fn input_err_msg<P: AsRef<Path>>(file_path: P) -> String {
128    format!("Error reading {}", file_path.as_ref().display())
129}
130
131/// Read a CSV file of items with IDs.
132///
133/// As this function is only ever used for top-level CSV files (i.e. the ones which actually define
134/// the IDs for a given type), we use an ordered map to maintain the order in the input files.
135fn read_csv_id_file<T, ID: IDLike>(file_path: &Path) -> Result<IndexMap<ID, T>>
136where
137    T: HasID<ID> + DeserializeOwned,
138{
139    fn fill_and_validate_map<T, ID: IDLike>(file_path: &Path) -> Result<IndexMap<ID, T>>
140    where
141        T: HasID<ID> + DeserializeOwned,
142    {
143        let mut map = IndexMap::new();
144        for record in read_csv::<T>(file_path)? {
145            let id = record.get_id().clone();
146            let existing = map.insert(id.clone(), record).is_some();
147            ensure!(!existing, "Duplicate ID found: {id}");
148        }
149        ensure!(!map.is_empty(), "CSV file is empty");
150
151        Ok(map)
152    }
153
154    fill_and_validate_map(file_path).with_context(|| input_err_msg(file_path))
155}
156
157/// Check that fractions sum to (approximately) one
158fn check_values_sum_to_one_approx<I, T>(fractions: I) -> Result<()>
159where
160    T: UnitType,
161    I: Iterator<Item = T>,
162{
163    let sum = fractions.sum();
164    ensure!(
165        approx_eq!(T, sum, T::new(1.0), epsilon = 1e-5),
166        "Sum of fractions does not equal one (actual: {sum})"
167    );
168
169    Ok(())
170}
171
172/// Check whether an iterator contains values that are sorted and unique
173pub fn is_sorted_and_unique<T, I>(iter: I) -> bool
174where
175    T: PartialOrd + Clone,
176    I: IntoIterator<Item = T>,
177{
178    iter.into_iter().tuple_windows().all(|(a, b)| a < b)
179}
180
181/// Insert a key-value pair into a map implementing the `Insert` trait if the key does not
182/// already exist.
183///
184/// If the key already exists, this returns an error with a message indicating the key's
185/// existence.
186pub fn try_insert<M, K, V>(map: &mut M, key: &K, value: V) -> Result<()>
187where
188    M: Insert<K, V>,
189    K: Eq + Hash + Clone + std::fmt::Debug,
190{
191    let existing = map.insert(key.clone(), value).is_some();
192    ensure!(!existing, "Key {key:?} already exists in the map");
193    Ok(())
194}
195
196/// Format a list of items with a cap on display count for error messages
197pub fn format_items_with_cap<I, J, T>(items: I) -> String
198where
199    I: IntoIterator<Item = T, IntoIter = J>,
200    J: ExactSizeIterator<Item = T>,
201    T: fmt::Debug,
202{
203    const MAX_DISPLAY: usize = 10;
204
205    let items = items.into_iter();
206    let total_count = items.len();
207
208    // Format items with fmt::Debug::fmt() and separate with commas
209    let formatted_items = items
210        .take(MAX_DISPLAY)
211        .format_with(", ", |items, f| f(&format_args!("{items:?}")));
212    let mut out = format!("[{formatted_items}]");
213
214    // If there are remaining items, include the count
215    if total_count > MAX_DISPLAY {
216        write!(&mut out, " and {} more", total_count - MAX_DISPLAY).unwrap();
217    }
218
219    out
220}
221
222/// Read a model from the specified directory.
223///
224/// # Arguments
225///
226/// * `model_dir` - Folder containing model configuration files
227///
228/// # Returns
229///
230/// The static model data ([`Model`]) and an [`AssetPool`] struct or an error.
231pub fn load_model<P: AsRef<Path>>(model_dir: P) -> Result<(Model, AssetPool)> {
232    let model_params = ModelParameters::from_path(&model_dir)?;
233
234    let time_slice_info = read_time_slice_info(model_dir.as_ref())?;
235    let regions = read_regions(model_dir.as_ref())?;
236    let region_ids = regions.keys().cloned().collect();
237    let years = &model_params.milestone_years;
238
239    let commodities = read_commodities(model_dir.as_ref(), &region_ids, &time_slice_info, years)?;
240    let processes = read_processes(
241        model_dir.as_ref(),
242        &commodities,
243        &region_ids,
244        &time_slice_info,
245        years,
246    )?;
247    let agents = read_agents(
248        model_dir.as_ref(),
249        &commodities,
250        &processes,
251        &region_ids,
252        years,
253    )?;
254    let agent_ids = agents.keys().cloned().collect();
255    let assets = read_assets(model_dir.as_ref(), &agent_ids, &processes, &region_ids)?;
256
257    // Build and validate commodity graphs for all regions and years
258    let commodity_graphs = build_commodity_graphs_for_model(&processes, &region_ids, years);
259    validate_commodity_graphs_for_model(
260        &commodity_graphs,
261        &processes,
262        &commodities,
263        &time_slice_info,
264    )?;
265
266    // Solve investment order for each region/year
267    let investment_order = solve_investment_order_for_model(&commodity_graphs, &commodities, years);
268
269    let model_path = model_dir
270        .as_ref()
271        .canonicalize()
272        .context("Could not parse path to model")?;
273    let model = Model {
274        model_path,
275        parameters: model_params,
276        agents,
277        commodities,
278        processes,
279        time_slice_info,
280        regions,
281        investment_order,
282    };
283    Ok((model, AssetPool::new(assets)))
284}
285
286/// Load commodity flow graphs for a model.
287///
288/// Loads necessary input data and creates a graph of commodity flows for each region and year,
289/// where nodes are commodities and edges are processes.
290///
291/// Graphs validation is NOT performed. This ensures that graphs can be generated even when
292/// validation would fail, which may be helpful for debugging.
293pub fn load_commodity_graphs<P: AsRef<Path>>(
294    model_dir: P,
295) -> Result<IndexMap<(RegionID, u32), CommoditiesGraph>> {
296    let model_params = ModelParameters::from_path(&model_dir)?;
297
298    let time_slice_info = read_time_slice_info(model_dir.as_ref())?;
299    let regions = read_regions(model_dir.as_ref())?;
300    let region_ids = regions.keys().cloned().collect();
301    let years = &model_params.milestone_years;
302
303    let commodities = read_commodities(model_dir.as_ref(), &region_ids, &time_slice_info, years)?;
304    let processes = read_processes(
305        model_dir.as_ref(),
306        &commodities,
307        &region_ids,
308        &time_slice_info,
309        years,
310    )?;
311
312    let commodity_graphs = build_commodity_graphs_for_model(&processes, &region_ids, years);
313    Ok(commodity_graphs)
314}
315
316#[cfg(test)]
317mod tests {
318    use super::*;
319    use crate::id::GenericID;
320    use crate::units::Dimensionless;
321    use rstest::rstest;
322    use serde::Deserialize;
323    use serde::de::IntoDeserializer;
324    use serde::de::value::{Error as ValueError, F64Deserializer};
325    use std::fs::File;
326    use std::io::Write;
327    use std::path::PathBuf;
328    use tempfile::tempdir;
329
330    #[derive(Debug, PartialEq, Deserialize)]
331    struct Record {
332        id: GenericID,
333        value: u32,
334    }
335
336    impl HasID<GenericID> for Record {
337        fn get_id(&self) -> &GenericID {
338            &self.id
339        }
340    }
341
342    /// Create an example CSV file in `dir_path`
343    fn create_csv_file(dir_path: &Path, contents: &str) -> PathBuf {
344        let file_path = dir_path.join("test.csv");
345        let mut file = File::create(&file_path).unwrap();
346        writeln!(file, "{contents}").unwrap();
347        file_path
348    }
349
350    /// Test a normal read
351    #[test]
352    fn read_csv_works() {
353        let dir = tempdir().unwrap();
354        let file_path = create_csv_file(dir.path(), "id,value\nhello,1\nworld,2\n");
355        let records: Vec<Record> = read_csv(&file_path).unwrap().collect();
356        assert_eq!(
357            records,
358            &[
359                Record {
360                    id: "hello".into(),
361                    value: 1,
362                },
363                Record {
364                    id: "world".into(),
365                    value: 2,
366                }
367            ]
368        );
369
370        // File with leading/trailing whitespace
371        let dir = tempdir().unwrap();
372        let file_path = create_csv_file(dir.path(), "id  , value\t\n  hello\t ,1\n world ,2\n");
373        let records: Vec<Record> = read_csv(&file_path).unwrap().collect();
374        assert_eq!(
375            records,
376            &[
377                Record {
378                    id: "hello".into(),
379                    value: 1,
380                },
381                Record {
382                    id: "world".into(),
383                    value: 2,
384                }
385            ]
386        );
387
388        // File with no data (only column headers)
389        let file_path = create_csv_file(dir.path(), "id,value\n");
390        assert!(read_csv::<Record>(&file_path).is_err());
391        assert!(
392            read_csv_optional::<Record>(&file_path)
393                .unwrap()
394                .next()
395                .is_none()
396        );
397
398        // Missing file
399        let dir = tempdir().unwrap();
400        let file_path = dir.path().join("a_missing_file.csv");
401        assert!(!file_path.exists());
402        assert!(read_csv::<Record>(&file_path).is_err());
403        // optional csv's should return empty iterator
404        assert!(
405            read_csv_optional::<Record>(&file_path)
406                .unwrap()
407                .next()
408                .is_none()
409        );
410    }
411
412    #[test]
413    fn read_toml_works() {
414        let dir = tempdir().unwrap();
415        let file_path = dir.path().join("test.toml");
416        {
417            let mut file = File::create(&file_path).unwrap();
418            writeln!(file, "id = \"hello\"\nvalue = 1").unwrap();
419        }
420
421        assert_eq!(
422            read_toml::<Record>(&file_path).unwrap(),
423            Record {
424                id: "hello".into(),
425                value: 1,
426            }
427        );
428
429        {
430            let mut file = File::create(&file_path).unwrap();
431            writeln!(file, "bad toml syntax").unwrap();
432        }
433
434        read_toml::<Record>(&file_path).unwrap_err();
435    }
436
437    /// Deserialise value with `deserialise_proportion_nonzero()`
438    fn deserialise_f64(value: f64) -> Result<Dimensionless, ValueError> {
439        let deserialiser: F64Deserializer<ValueError> = value.into_deserializer();
440        deserialise_proportion_nonzero(deserialiser)
441    }
442
443    #[test]
444    fn deserialise_proportion_nonzero_works() {
445        // Valid inputs
446        assert_eq!(deserialise_f64(0.01), Ok(Dimensionless(0.01)));
447        assert_eq!(deserialise_f64(0.5), Ok(Dimensionless(0.5)));
448        assert_eq!(deserialise_f64(1.0), Ok(Dimensionless(1.0)));
449
450        // Invalid inputs
451        deserialise_f64(0.0).unwrap_err();
452        deserialise_f64(-1.0).unwrap_err();
453        deserialise_f64(2.0).unwrap_err();
454        deserialise_f64(f64::NAN).unwrap_err();
455        deserialise_f64(f64::INFINITY).unwrap_err();
456    }
457
458    #[test]
459    fn check_values_sum_to_one_approx_works() {
460        // Single input, valid
461        check_values_sum_to_one_approx([Dimensionless(1.0)].into_iter()).unwrap();
462
463        // Multiple inputs, valid
464        check_values_sum_to_one_approx([Dimensionless(0.4), Dimensionless(0.6)].into_iter())
465            .unwrap();
466
467        // Single input, invalid
468        assert!(check_values_sum_to_one_approx([Dimensionless(0.5)].into_iter()).is_err());
469
470        // Multiple inputs, invalid
471        assert!(
472            check_values_sum_to_one_approx([Dimensionless(0.4), Dimensionless(0.3)].into_iter())
473                .is_err()
474        );
475
476        // Edge cases
477        assert!(
478            check_values_sum_to_one_approx([Dimensionless(f64::INFINITY)].into_iter()).is_err()
479        );
480        assert!(check_values_sum_to_one_approx([Dimensionless(f64::NAN)].into_iter()).is_err());
481    }
482
483    #[rstest]
484    #[case(&[], true)]
485    #[case(&[1], true)]
486    #[case(&[1,2], true)]
487    #[case(&[1,2,3,4], true)]
488    #[case(&[2,1],false)]
489    #[case(&[1,1],false)]
490    #[case(&[1,3,2,4], false)]
491    fn is_sorted_and_unique_works(#[case] values: &[u32], #[case] expected: bool) {
492        assert_eq!(is_sorted_and_unique(values), expected);
493    }
494
495    #[test]
496    fn format_items_with_cap_works() {
497        let items = vec!["a", "b", "c"];
498        assert_eq!(format_items_with_cap(&items), r#"["a", "b", "c"]"#);
499
500        // Test with more than 10 items to trigger the cap
501        let many_items = vec!["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"];
502        assert_eq!(
503            format_items_with_cap(&many_items),
504            r#"["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"] and 2 more"#
505        );
506    }
507}