muse2/input/commodity/
demand.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
//! Code for working with demand for a given commodity. Demand can vary by region, year and time
//! slice.
use super::demand_slicing::{read_demand_slices, DemandSliceMap, DemandSliceMapKey};
use crate::commodity::DemandMap;
use crate::input::*;
use crate::time_slice::TimeSliceInfo;
use anyhow::{ensure, Result};
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::rc::Rc;

const DEMAND_FILE_NAME: &str = "demand.csv";

/// Represents a single demand entry in the dataset.
#[derive(Debug, Clone, Deserialize, PartialEq)]
struct Demand {
    /// The commodity this demand entry refers to
    commodity_id: String,
    /// The region of the demand entry
    region_id: String,
    /// The year of the demand entry
    year: u32,
    /// Annual demand quantity
    demand: f64,
}

/// A map relating commodity, region and year to annual demand
pub type AnnualDemandMap = HashMap<AnnualDemandMapKey, f64>;

/// A key for an [`AnnualDemandMap`]
#[derive(PartialEq, Eq, Hash, Debug)]
pub struct AnnualDemandMapKey {
    /// The commodity to which this demand applies
    commodity_id: Rc<str>,
    /// The region to which this demand applies
    region_id: Rc<str>,
    /// The simulation year to which this demand applies
    year: u32,
}

/// A set of commodity + region pairs
pub type CommodityRegionPairs = HashSet<(Rc<str>, Rc<str>)>;

/// Reads demand data from CSV files.
///
/// # Arguments
///
/// * `model_dir` - Folder containing model configuration files
/// * `commodity_ids` - All possible IDs of commodities
/// * `region_ids` - All possible IDs for regions
/// * `time_slice_info` - Information about seasons and times of day
/// * `milestone_years` - All milestone years
///
/// # Returns
///
/// This function returns [`DemandMap`]s grouped by commodity ID.
pub fn read_demand(
    model_dir: &Path,
    commodity_ids: &HashSet<Rc<str>>,
    region_ids: &HashSet<Rc<str>>,
    time_slice_info: &TimeSliceInfo,
    milestone_years: &[u32],
) -> Result<HashMap<Rc<str>, DemandMap>> {
    let (demand, commodity_regions) =
        read_demand_file(model_dir, commodity_ids, region_ids, milestone_years)?;
    let slices = read_demand_slices(
        model_dir,
        commodity_ids,
        region_ids,
        &commodity_regions,
        time_slice_info,
    )?;

    Ok(compute_demand_maps(&demand, &slices, time_slice_info))
}

/// Read the demand.csv file.
///
/// # Arguments
///
/// * `model_dir` - Folder containing model configuration files
/// * `commodity_ids` - All possible IDs of commodities
/// * `region_ids` - All possible IDs for regions
/// * `milestone_years` - All milestone years
///
/// # Returns
///
/// Annual demand data, grouped by commodity, region and milestone year.
fn read_demand_file(
    model_dir: &Path,
    commodity_ids: &HashSet<Rc<str>>,
    region_ids: &HashSet<Rc<str>>,
    milestone_years: &[u32],
) -> Result<(AnnualDemandMap, CommodityRegionPairs)> {
    let file_path = model_dir.join(DEMAND_FILE_NAME);
    let iter = read_csv(&file_path)?;
    read_demand_from_iter(iter, commodity_ids, region_ids, milestone_years)
}

/// Read the demand data from an iterator.
///
/// # Arguments
///
/// * `iter` - An iterator of [`Demand`]s
/// * `commodity_ids` - All possible IDs of commodities
/// * `region_ids` - All possible IDs for regions
/// * `milestone_years` - All milestone years
///
/// # Returns
///
/// The demand for each combination of commodity, region and year along with a [`HashSet`] of all
/// commodity + region pairs included in the file.
fn read_demand_from_iter<I>(
    iter: I,
    commodity_ids: &HashSet<Rc<str>>,
    region_ids: &HashSet<Rc<str>>,
    milestone_years: &[u32],
) -> Result<(AnnualDemandMap, CommodityRegionPairs)>
where
    I: Iterator<Item = Demand>,
{
    let mut map = AnnualDemandMap::new();

    // Keep track of all commodity + region pairs so we can check that every milestone year is
    // covered
    let mut commodity_regions = HashSet::new();

    for demand in iter {
        let commodity_id = commodity_ids.get_id(&demand.commodity_id)?;
        let region_id = region_ids.get_id(&demand.region_id)?;

        ensure!(
            milestone_years.binary_search(&demand.year).is_ok(),
            "Year {} is not a milestone year. \
            Input of non-milestone years is currently not supported.",
            demand.year
        );

        ensure!(
            demand.demand.is_normal() && demand.demand > 0.0,
            "Demand must be a valid number greater than zero"
        );

        let key = AnnualDemandMapKey {
            commodity_id: Rc::clone(&commodity_id),
            region_id: Rc::clone(&region_id),
            year: demand.year,
        };
        ensure!(
            map.insert(key, demand.demand).is_none(),
            "Duplicate demand entries (commodity: {}, region: {}, year: {})",
            commodity_id,
            region_id,
            demand.year
        );

        commodity_regions.insert((commodity_id, region_id));
    }

    // If a commodity + region combination is represented, it must include entries for every
    // milestone year
    for (commodity_id, region_id) in commodity_regions.iter() {
        for year in milestone_years.iter().copied() {
            let key = AnnualDemandMapKey {
                commodity_id: Rc::clone(commodity_id),
                region_id: Rc::clone(region_id),
                year,
            };
            ensure!(
                map.contains_key(&key),
                "Missing milestone year {year} for commodity {commodity_id} in region {region_id}"
            );
        }
    }

    Ok((map, commodity_regions))
}

/// Calculate the demand for each combination of commodity, region, year and time slice.
///
/// # Arguments
///
/// * `demand` - Total annual demand for combinations of commodity, region and year
/// * `slices` - How annual demand is shared between time slices
/// * `time_slice_info` - Information about time slices
///
/// # Returns
///
/// [`DemandMap`]s for combinations of region, year and time slice, grouped by the commodity to
/// which the demand applies.
fn compute_demand_maps(
    demand: &AnnualDemandMap,
    slices: &DemandSliceMap,
    time_slice_info: &TimeSliceInfo,
) -> HashMap<Rc<str>, DemandMap> {
    let mut map = HashMap::new();
    for (demand_key, annual_demand) in demand.iter() {
        let commodity_id = &demand_key.commodity_id;
        let region_id = &demand_key.region_id;
        for time_slice in time_slice_info.iter_ids() {
            let slice_key = DemandSliceMapKey {
                commodity_id: Rc::clone(commodity_id),
                region_id: Rc::clone(region_id),
                time_slice: time_slice.clone(),
            };

            // NB: This has already been checked, so shouldn't fail
            let demand_fraction = slices.get(&slice_key).unwrap();

            // Get or create entry
            let map = map
                .entry(Rc::clone(commodity_id))
                .or_insert_with(DemandMap::new);

            // Add a new demand entry
            map.insert(
                Rc::clone(region_id),
                demand_key.year,
                time_slice.clone(),
                annual_demand * demand_fraction,
            );
        }
    }

    map
}

#[cfg(test)]
mod tests {
    use super::*;
    use itertools::iproduct;
    use std::fs::File;
    use std::io::Write;
    use std::iter;
    use std::path::Path;
    use tempfile::tempdir;

    /// Create an example demand file in dir_path
    fn create_demand_file(dir_path: &Path) {
        let file_path = dir_path.join(DEMAND_FILE_NAME);
        let mut file = File::create(file_path).unwrap();
        writeln!(
            file,
            "commodity_id,region_id,year,demand
COM1,North,2020,10
COM1,South,2020,11
COM1,East,2020,12
COM1,West,2020,13"
        )
        .unwrap();
    }

    #[test]
    fn test_read_demand_from_iter() {
        let commodity_ids = ["COM1".into()].into_iter().collect();
        let region_ids = ["North".into(), "South".into()].into_iter().collect();
        let milestone_years = [2020];

        // Valid
        let demand = [
            Demand {
                year: 2020,
                region_id: "North".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 10.0,
            },
            Demand {
                year: 2020,
                region_id: "South".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 11.0,
            },
        ];
        assert!(read_demand_from_iter(
            demand.into_iter(),
            &commodity_ids,
            &region_ids,
            &milestone_years
        )
        .is_ok());

        // Bad commodity ID
        let demand = [
            Demand {
                year: 2020,
                region_id: "North".to_string(),
                commodity_id: "COM2".to_string(),
                demand: 10.0,
            },
            Demand {
                year: 2020,
                region_id: "South".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 11.0,
            },
        ];
        assert!(read_demand_from_iter(
            demand.into_iter(),
            &commodity_ids,
            &region_ids,
            &milestone_years
        )
        .is_err());

        // Bad region ID
        let demand = [
            Demand {
                year: 2020,
                region_id: "East".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 10.0,
            },
            Demand {
                year: 2020,
                region_id: "South".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 11.0,
            },
        ];
        assert!(read_demand_from_iter(
            demand.into_iter(),
            &commodity_ids,
            &region_ids,
            &milestone_years
        )
        .is_err());

        // Bad year
        let demand = [
            Demand {
                year: 2010,
                region_id: "North".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 10.0,
            },
            Demand {
                year: 2020,
                region_id: "South".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 11.0,
            },
        ];
        assert!(read_demand_from_iter(
            demand.into_iter(),
            &commodity_ids,
            &region_ids,
            &milestone_years
        )
        .is_err());

        // Bad demand quantity
        macro_rules! test_quantity {
            ($quantity: expr) => {
                let demand = [Demand {
                    year: 2020,
                    region_id: "North".to_string(),
                    commodity_id: "COM1".to_string(),
                    demand: $quantity,
                }];
                assert!(read_demand_from_iter(
                    demand.into_iter(),
                    &commodity_ids,
                    &region_ids,
                    &milestone_years,
                )
                .is_err());
            };
        }
        test_quantity!(-1.0);
        test_quantity!(0.0);
        test_quantity!(f64::NAN);
        test_quantity!(f64::NEG_INFINITY);
        test_quantity!(f64::INFINITY);

        // Multiple entries for same commodity and region
        let demand = [
            Demand {
                year: 2020,
                region_id: "North".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 10.0,
            },
            Demand {
                year: 2020,
                region_id: "North".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 10.0,
            },
            Demand {
                year: 2020,
                region_id: "South".to_string(),
                commodity_id: "COM1".to_string(),
                demand: 11.0,
            },
        ];
        assert!(read_demand_from_iter(
            demand.into_iter(),
            &commodity_ids,
            &region_ids,
            &milestone_years
        )
        .is_err());

        // Missing entry for a milestone year
        let demand = Demand {
            year: 2020,
            region_id: "North".to_string(),
            commodity_id: "COM1".to_string(),
            demand: 10.0,
        };
        assert!(read_demand_from_iter(
            iter::once(demand),
            &commodity_ids,
            &region_ids,
            &[2020, 2030]
        )
        .is_err());
    }

    #[test]
    fn test_read_demand_file() {
        let dir = tempdir().unwrap();
        create_demand_file(dir.path());
        let commodity_ids = HashSet::from_iter(iter::once("COM1".into()));
        let region_ids =
            HashSet::from_iter(["North".into(), "South".into(), "East".into(), "West".into()]);
        let milestone_years = [2020];
        let expected = AnnualDemandMap::from_iter([
            (
                AnnualDemandMapKey {
                    commodity_id: "COM1".into(),
                    region_id: "North".into(),
                    year: 2020,
                },
                10.0,
            ),
            (
                AnnualDemandMapKey {
                    commodity_id: "COM1".into(),
                    region_id: "South".into(),
                    year: 2020,
                },
                11.0,
            ),
            (
                AnnualDemandMapKey {
                    commodity_id: "COM1".into(),
                    region_id: "East".into(),
                    year: 2020,
                },
                12.0,
            ),
            (
                AnnualDemandMapKey {
                    commodity_id: "COM1".into(),
                    region_id: "West".into(),
                    year: 2020,
                },
                13.0,
            ),
        ]);
        let (demand, commodity_regions) =
            read_demand_file(dir.path(), &commodity_ids, &region_ids, &milestone_years).unwrap();
        let commodity_regions_expected =
            iproduct!(commodity_ids.iter().cloned(), region_ids.iter().cloned()).collect();
        assert_eq!(demand, expected);
        assert_eq!(commodity_regions, commodity_regions_expected);
    }
}