muse2 2.1.0

A tool for running simulations of energy systems
Documentation
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
//! The module responsible for writing output data to disk.
use crate::agent::AgentID;
use crate::asset::{Asset, AssetGroupID, AssetID, AssetRef};
use crate::commodity::CommodityID;
use crate::process::ProcessID;
use crate::region::RegionID;
use crate::simulation::CommodityPrices;
use crate::simulation::investment::appraisal::AppraisalOutput;
use crate::simulation::optimisation::{FlowMap, Solution};
use crate::time_slice::TimeSliceID;
use crate::units::{
    Activity, Capacity, Flow, Money, MoneyPerActivity, MoneyPerCapacity, MoneyPerFlow,
};
use anyhow::{Context, Result, ensure};
use csv;
use indexmap::IndexMap;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
use std::fs;
use std::fs::File;
use std::path::{Path, PathBuf};

pub mod metadata;
use metadata::write_metadata;

/// The output file name for commodity flows
const COMMODITY_FLOWS_FILE_NAME: &str = "commodity_flows.csv";

/// The output file name for commodity prices
const COMMODITY_PRICES_FILE_NAME: &str = "commodity_prices.csv";

/// The output file name for assets
const ASSETS_FILE_NAME: &str = "assets.csv";

/// Debug output file for asset dispatch
const ACTIVITY_ASSET_DISPATCH: &str = "debug_dispatch_assets.csv";

/// The output file name for commodity balance duals
const COMMODITY_BALANCE_DUALS_FILE_NAME: &str = "debug_commodity_balance_duals.csv";

/// The output file name for unmet demand values
const UNMET_DEMAND_FILE_NAME: &str = "debug_unmet_demand.csv";

/// The output file name for extra solver output values
const SOLVER_VALUES_FILE_NAME: &str = "debug_solver.csv";

/// The output file name for appraisal results
const APPRAISAL_RESULTS_FILE_NAME: &str = "debug_appraisal_results.csv";

/// The output file name for appraisal time slice results
const APPRAISAL_RESULTS_TIME_SLICE_FILE_NAME: &str = "debug_appraisal_results_time_slices.csv";

/// Get the default output directory for the model
pub fn get_output_dir(model_dir: &Path, results_root: PathBuf) -> Result<PathBuf> {
    // Get the model name from the dir path. This ends up being convoluted because we need to check
    // for all possible errors. Ugh.
    let model_dir = model_dir
        .canonicalize() // canonicalise in case the user has specified "."
        .context("Could not resolve path to model")?;

    let model_name = model_dir
        .file_name()
        .context("Model cannot be in root folder")?
        .to_str()
        .context("Invalid chars in model dir name")?;

    // Construct path
    Ok([results_root, model_name.into()].iter().collect())
}

/// Get the default output directory for commodity flow graphs for the model
pub fn get_graphs_dir(model_dir: &Path, graph_results_root: PathBuf) -> Result<PathBuf> {
    let model_dir = model_dir
        .canonicalize() // canonicalise in case the user has specified "."
        .context("Could not resolve path to model")?;
    let model_name = model_dir
        .file_name()
        .context("Model cannot be in root folder")?
        .to_str()
        .context("Invalid chars in model dir name")?;
    Ok([graph_results_root, model_name.into()].iter().collect())
}

/// Create a new output directory for the model, optionally overwriting existing data
///
/// # Arguments
///
/// * `output_dir` - The output directory to create/overwrite
/// * `allow_overwrite` - Whether to delete and recreate the folder if it is non-empty
///
/// # Returns
///
/// True if the output dir contained existing data that was deleted, false if not, or an error.
pub fn create_output_directory(output_dir: &Path, allow_overwrite: bool) -> Result<bool> {
    // If the folder already exists, then delete it
    let overwrite = if let Ok(mut it) = fs::read_dir(output_dir) {
        if it.next().is_none() {
            // Folder exists and is empty: nothing to do
            return Ok(false);
        }

        ensure!(
            allow_overwrite,
            "Output folder already exists and is not empty. \
            Please delete the folder or pass the --overwrite command-line option."
        );

        fs::remove_dir_all(output_dir).context("Could not delete folder")?;
        true
    } else {
        false
    };

    // Try to create the directory, with parents
    fs::create_dir_all(output_dir)?;

    Ok(overwrite)
}

/// Represents a row in the assets output CSV file.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct AssetRow {
    asset_id: AssetID,
    process_id: ProcessID,
    region_id: RegionID,
    agent_id: AgentID,
    group_id: Option<AssetGroupID>,
    commission_year: u32,
    decommission_year: Option<u32>,
    capacity: Capacity,
}

impl AssetRow {
    /// Create a new [`AssetRow`]
    fn new(asset: &Asset) -> Self {
        Self {
            asset_id: asset.id().unwrap(),
            process_id: asset.process_id().clone(),
            region_id: asset.region_id().clone(),
            agent_id: asset.agent_id().unwrap().clone(),
            group_id: asset.group_id(),
            commission_year: asset.commission_year(),
            decommission_year: asset.decommission_year(),
            capacity: asset.total_capacity(),
        }
    }
}

/// Represents the flow-related data in a row of the commodity flows CSV file.
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct CommodityFlowRow {
    milestone_year: u32,
    asset_id: AssetID,
    commodity_id: CommodityID,
    time_slice: TimeSliceID,
    flow: Flow,
}

/// Represents a row in the commodity prices CSV file
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct CommodityPriceRow {
    milestone_year: u32,
    commodity_id: CommodityID,
    region_id: RegionID,
    time_slice: TimeSliceID,
    price: MoneyPerFlow,
}

/// Represents the activity in a row of the activity CSV file
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct ActivityRow {
    milestone_year: u32,
    run_description: String,
    asset_id: Option<AssetID>,
    process_id: ProcessID,
    region_id: RegionID,
    time_slice: TimeSliceID,
    activity: Option<Activity>,
    activity_dual: Option<MoneyPerActivity>,
    column_dual: Option<MoneyPerActivity>,
}

/// Represents the commodity balance duals data in a row of the commodity balance duals CSV file
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct CommodityBalanceDualsRow {
    milestone_year: u32,
    run_description: String,
    commodity_id: CommodityID,
    region_id: RegionID,
    time_slice: TimeSliceID,
    value: MoneyPerFlow,
}

/// Represents the unmet demand data in a row of the unmet demand CSV file
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct UnmetDemandRow {
    milestone_year: u32,
    run_description: String,
    commodity_id: CommodityID,
    region_id: RegionID,
    time_slice: TimeSliceID,
    value: Flow,
}

/// Represents solver output values
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct SolverValuesRow {
    milestone_year: u32,
    run_description: String,
    objective_value: Money,
}

/// Represents the appraisal results in a row of the appraisal results CSV file
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct AppraisalResultsRow {
    milestone_year: u32,
    run_description: String,
    asset_id: Option<AssetID>,
    process_id: ProcessID,
    region_id: RegionID,
    capacity: Capacity,
    capacity_coefficient: MoneyPerCapacity,
    metric: Option<f64>,
}

/// Represents the appraisal results in a row of the appraisal results CSV file
#[derive(Serialize, Deserialize, Debug, PartialEq)]
struct AppraisalResultsTimeSliceRow {
    milestone_year: u32,
    run_description: String,
    asset_id: Option<AssetID>,
    process_id: ProcessID,
    region_id: RegionID,
    time_slice: TimeSliceID,
    activity: Activity,
    activity_coefficient: MoneyPerActivity,
    demand: Flow,
    unmet_demand: Flow,
}

/// For writing extra debug information about the model
struct DebugDataWriter {
    context: Option<String>,
    commodity_balance_duals_writer: csv::Writer<File>,
    unmet_demand_writer: csv::Writer<File>,
    solver_values_writer: csv::Writer<File>,
    appraisal_results_writer: csv::Writer<File>,
    appraisal_results_time_slice_writer: csv::Writer<File>,
    dispatch_asset_writer: csv::Writer<File>,
}

impl DebugDataWriter {
    /// Open CSV files to write debug info to
    ///
    /// # Arguments
    ///
    /// * `output_path` - Folder where files will be saved
    fn create(output_path: &Path) -> Result<Self> {
        let new_writer = |file_name| {
            let file_path = output_path.join(file_name);
            csv::Writer::from_path(file_path)
        };

        Ok(Self {
            context: None,
            commodity_balance_duals_writer: new_writer(COMMODITY_BALANCE_DUALS_FILE_NAME)?,
            unmet_demand_writer: new_writer(UNMET_DEMAND_FILE_NAME)?,
            solver_values_writer: new_writer(SOLVER_VALUES_FILE_NAME)?,
            appraisal_results_writer: new_writer(APPRAISAL_RESULTS_FILE_NAME)?,
            appraisal_results_time_slice_writer: new_writer(
                APPRAISAL_RESULTS_TIME_SLICE_FILE_NAME,
            )?,
            dispatch_asset_writer: new_writer(ACTIVITY_ASSET_DISPATCH)?,
        })
    }

    /// Prepend the current context to the run description
    fn with_context(&self, run_description: &str) -> String {
        if let Some(context) = &self.context {
            format!("{context}; {run_description}")
        } else {
            run_description.to_string()
        }
    }

    /// Write debug info about the dispatch optimisation
    fn write_dispatch_debug_info(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        solution: &Solution,
    ) -> Result<()> {
        self.write_activity(
            milestone_year,
            run_description,
            solution.iter_activity(),
            solution.iter_activity_duals(),
            solution.iter_column_duals(),
        )?;
        self.write_commodity_balance_duals(
            milestone_year,
            run_description,
            solution.iter_commodity_balance_duals(),
        )?;
        self.write_unmet_demand(
            milestone_year,
            run_description,
            solution.iter_unmet_demand(),
        )?;
        self.write_solver_values(milestone_year, run_description, solution.objective_value)?;
        Ok(())
    }

    // Write activity to file
    fn write_activity<'a, I, J, K>(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        iter_activity: I,
        iter_activity_duals: J,
        iter_column_duals: K,
    ) -> Result<()>
    where
        I: Iterator<Item = (&'a AssetRef, &'a TimeSliceID, Activity)>,
        J: Iterator<Item = (&'a AssetRef, &'a TimeSliceID, MoneyPerActivity)>,
        K: Iterator<Item = (&'a AssetRef, &'a TimeSliceID, MoneyPerActivity)>,
    {
        // To account for different order of entries or missing ones, we first compile data in hash map
        type CompiledActivityData = (
            Option<Activity>,
            Option<MoneyPerActivity>,
            Option<MoneyPerActivity>,
        );
        let mut map: IndexMap<(&AssetRef, &TimeSliceID), CompiledActivityData> = IndexMap::new();

        // For the activities
        for (asset, time_slice, activity) in iter_activity {
            map.entry((asset, time_slice)).or_default().0 = Some(activity);
        }
        // The activity duals
        for (asset, time_slice, activity_dual) in iter_activity_duals {
            map.entry((asset, time_slice)).or_default().1 = Some(activity_dual);
        }
        // And the column duals
        for (asset, time_slice, column_dual) in iter_column_duals {
            map.entry((asset, time_slice)).or_default().2 = Some(column_dual);
        }

        for (asset, time_slice, activity, activity_dual, column_dual) in
            map.iter()
                .map(|(&(agent, ts), &(activity, activity_dual, column_dual))| {
                    (agent, ts, activity, activity_dual, column_dual)
                })
        {
            let row = ActivityRow {
                milestone_year,
                run_description: self.with_context(run_description),
                asset_id: asset.id(),
                process_id: asset.process_id().clone(),
                region_id: asset.region_id().clone(),
                time_slice: time_slice.clone(),
                activity,
                activity_dual,
                column_dual,
            };
            self.dispatch_asset_writer.serialize(row)?;
        }

        Ok(())
    }

    /// Write commodity balance duals to file
    fn write_commodity_balance_duals<'a, I>(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        iter: I,
    ) -> Result<()>
    where
        I: Iterator<Item = (&'a CommodityID, &'a RegionID, &'a TimeSliceID, MoneyPerFlow)>,
    {
        for (commodity_id, region_id, time_slice, value) in iter {
            let row = CommodityBalanceDualsRow {
                milestone_year,
                run_description: self.with_context(run_description),
                commodity_id: commodity_id.clone(),
                region_id: region_id.clone(),
                time_slice: time_slice.clone(),
                value,
            };
            self.commodity_balance_duals_writer.serialize(row)?;
        }

        Ok(())
    }

    /// Write unmet demand values to file
    fn write_unmet_demand<'a, I>(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        iter: I,
    ) -> Result<()>
    where
        I: Iterator<Item = (&'a CommodityID, &'a RegionID, &'a TimeSliceID, Flow)>,
    {
        for (commodity_id, region_id, time_slice, value) in iter {
            let row = UnmetDemandRow {
                milestone_year,
                run_description: self.with_context(run_description),
                commodity_id: commodity_id.clone(),
                region_id: region_id.clone(),
                time_slice: time_slice.clone(),
                value,
            };
            self.unmet_demand_writer.serialize(row)?;
        }

        Ok(())
    }

    /// Write additional solver output values to file
    fn write_solver_values(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        objective_value: Money,
    ) -> Result<()> {
        let row = SolverValuesRow {
            milestone_year,
            run_description: self.with_context(run_description),
            objective_value,
        };
        self.solver_values_writer.serialize(row)?;
        self.solver_values_writer.flush()?;

        Ok(())
    }

    /// Write appraisal results to file
    fn write_appraisal_results(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        appraisal_results: &[AppraisalOutput],
    ) -> Result<()> {
        for result in appraisal_results {
            let row = AppraisalResultsRow {
                milestone_year,
                run_description: self.with_context(run_description),
                asset_id: result.asset.id(),
                process_id: result.asset.process_id().clone(),
                region_id: result.asset.region_id().clone(),
                capacity: result.capacity.total_capacity(),
                capacity_coefficient: result.coefficients.capacity_coefficient,
                metric: result.metric.as_ref().map(|m| m.value()),
            };
            self.appraisal_results_writer.serialize(row)?;
        }

        Ok(())
    }

    /// Write appraisal results to file
    fn write_appraisal_time_slice_results(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        appraisal_results: &[AppraisalOutput],
        demand: &IndexMap<TimeSliceID, Flow>,
    ) -> Result<()> {
        for result in appraisal_results {
            for (time_slice, activity) in &result.activity {
                let activity_coefficient = result.coefficients.activity_coefficients[time_slice];
                let demand = demand[time_slice];
                let unmet_demand = result.unmet_demand[time_slice];
                let row = AppraisalResultsTimeSliceRow {
                    milestone_year,
                    run_description: self.with_context(run_description),
                    asset_id: result.asset.id(),
                    process_id: result.asset.process_id().clone(),
                    region_id: result.asset.region_id().clone(),
                    time_slice: time_slice.clone(),
                    activity: *activity,
                    activity_coefficient,
                    demand,
                    unmet_demand,
                };
                self.appraisal_results_time_slice_writer.serialize(row)?;
            }
        }

        Ok(())
    }

    /// Flush the underlying streams
    fn flush(&mut self) -> Result<()> {
        self.commodity_balance_duals_writer.flush()?;
        self.unmet_demand_writer.flush()?;
        self.solver_values_writer.flush()?;
        self.appraisal_results_writer.flush()?;
        self.appraisal_results_time_slice_writer.flush()?;
        self.dispatch_asset_writer.flush()?;

        Ok(())
    }
}

/// An object for writing commodity prices to file
pub struct DataWriter {
    assets_path: PathBuf,
    flows_writer: csv::Writer<File>,
    prices_writer: csv::Writer<File>,
    debug_writer: Option<DebugDataWriter>,
}

impl DataWriter {
    /// Open CSV files to write output data to
    ///
    /// # Arguments
    ///
    /// * `output_path` - Folder where files will be saved
    /// * `model_path` - Path to input model
    /// * `save_debug_info` - Whether to include extra CSV files for debugging model
    pub fn create(output_path: &Path, model_path: &Path, save_debug_info: bool) -> Result<Self> {
        write_metadata(output_path, model_path).context("Failed to save metadata")?;

        let new_writer = |file_name| {
            let file_path = output_path.join(file_name);
            csv::Writer::from_path(file_path)
        };

        let debug_writer = if save_debug_info {
            // Create debug CSV files
            Some(DebugDataWriter::create(output_path)?)
        } else {
            None
        };

        Ok(Self {
            assets_path: output_path.join(ASSETS_FILE_NAME),
            flows_writer: new_writer(COMMODITY_FLOWS_FILE_NAME)?,
            prices_writer: new_writer(COMMODITY_PRICES_FILE_NAME)?,
            debug_writer,
        })
    }

    /// Write debug info about the dispatch optimisation
    pub fn write_dispatch_debug_info(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        solution: &Solution,
    ) -> Result<()> {
        if let Some(wtr) = &mut self.debug_writer {
            wtr.write_dispatch_debug_info(milestone_year, run_description, solution)?;
        }

        Ok(())
    }

    /// Write debug info about the investment appraisal
    pub fn write_appraisal_debug_info(
        &mut self,
        milestone_year: u32,
        run_description: &str,
        appraisal_results: &[AppraisalOutput],
        demand: &IndexMap<TimeSliceID, Flow>,
    ) -> Result<()> {
        if let Some(wtr) = &mut self.debug_writer {
            wtr.write_appraisal_results(milestone_year, run_description, appraisal_results)?;
            wtr.write_appraisal_time_slice_results(
                milestone_year,
                run_description,
                appraisal_results,
                demand,
            )?;
        }

        Ok(())
    }

    /// Write assets to a CSV file.
    ///
    /// The whole file is written at once and is overwritten with subsequent invocations. This is
    /// done so that partial results will be written in the case of errors and so that the user can
    /// see the results while the simulation is still running.
    ///
    /// The file is sorted by asset ID.
    ///
    /// # Panics
    ///
    /// Panics if any of the assets has not yet been commissioned (decommissioned assets are fine).
    pub fn write_assets<'a, I>(&mut self, assets: I) -> Result<()>
    where
        I: Iterator<Item = &'a AssetRef>,
    {
        let mut writer = csv::Writer::from_path(&self.assets_path)?;
        for asset in assets.sorted() {
            let row = AssetRow::new(asset);
            writer.serialize(row)?;
        }
        writer.flush()?;

        Ok(())
    }

    /// Write commodity flows to a CSV file
    pub fn write_flows(&mut self, milestone_year: u32, flow_map: &FlowMap) -> Result<()> {
        for ((asset, commodity_id, time_slice), flow) in flow_map {
            let row = CommodityFlowRow {
                milestone_year,
                asset_id: asset.id().unwrap(),
                commodity_id: commodity_id.clone(),
                time_slice: time_slice.clone(),
                flow: *flow,
            };
            self.flows_writer.serialize(row)?;
        }

        Ok(())
    }

    /// Write commodity prices to a CSV file
    pub fn write_prices(&mut self, milestone_year: u32, prices: &CommodityPrices) -> Result<()> {
        for (commodity_id, region_id, time_slice, price) in prices.iter() {
            let row = CommodityPriceRow {
                milestone_year,
                commodity_id: commodity_id.clone(),
                region_id: region_id.clone(),
                time_slice: time_slice.clone(),
                price,
            };
            self.prices_writer.serialize(row)?;
        }

        Ok(())
    }

    /// Flush the underlying streams
    pub fn flush(&mut self) -> Result<()> {
        self.flows_writer.flush()?;
        self.prices_writer.flush()?;
        if let Some(wtr) = &mut self.debug_writer {
            wtr.flush()?;
        }

        Ok(())
    }

    /// Add context to the debug writer
    pub fn set_debug_context(&mut self, context: String) {
        if let Some(wtr) = &mut self.debug_writer {
            wtr.context = Some(context);
        }
    }

    /// Clear context from the debug writer
    pub fn clear_debug_context(&mut self) {
        if let Some(wtr) = &mut self.debug_writer {
            wtr.context = None;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::asset::AssetPool;
    use crate::fixture::{appraisal_output, asset, assets, commodity_id, region_id, time_slice};
    use crate::simulation::investment::appraisal::AppraisalOutput;
    use crate::time_slice::TimeSliceID;
    use indexmap::indexmap;
    use itertools::{Itertools, assert_equal};
    use rstest::rstest;
    use std::iter;
    use tempfile::tempdir;

    #[rstest]
    fn write_assets(assets: AssetPool) {
        let dir = tempdir().unwrap();

        // Write an asset
        {
            let mut writer = DataWriter::create(dir.path(), dir.path(), false).unwrap();
            writer.write_assets(assets.iter()).unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let asset = assets.iter().next().unwrap();
        let expected = AssetRow::new(asset);
        let records: Vec<AssetRow> = csv::Reader::from_path(dir.path().join(ASSETS_FILE_NAME))
            .unwrap()
            .into_deserialize()
            .try_collect()
            .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_flows(assets: AssetPool, commodity_id: CommodityID, time_slice: TimeSliceID) {
        let milestone_year = 2020;
        let asset = assets.iter().next().unwrap();
        let flow_map = indexmap! {
            (asset.clone(), commodity_id.clone(), time_slice.clone()) => Flow(42.0)
        };

        // Write a flow
        let dir = tempdir().unwrap();
        {
            let mut writer = DataWriter::create(dir.path(), dir.path(), false).unwrap();
            writer.write_flows(milestone_year, &flow_map).unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = CommodityFlowRow {
            milestone_year,
            asset_id: asset.id().unwrap(),
            commodity_id,
            time_slice,
            flow: Flow(42.0),
        };
        let records: Vec<CommodityFlowRow> =
            csv::Reader::from_path(dir.path().join(COMMODITY_FLOWS_FILE_NAME))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_prices(commodity_id: CommodityID, region_id: RegionID, time_slice: TimeSliceID) {
        let milestone_year = 2020;
        let price = MoneyPerFlow(42.0);
        let mut prices = CommodityPrices::default();
        prices.insert(&commodity_id, &region_id, &time_slice, price);

        let dir = tempdir().unwrap();

        // Write a price
        {
            let mut writer = DataWriter::create(dir.path(), dir.path(), false).unwrap();
            writer.write_prices(milestone_year, &prices).unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = CommodityPriceRow {
            milestone_year,
            commodity_id,
            region_id,
            time_slice,
            price,
        };
        let records: Vec<CommodityPriceRow> =
            csv::Reader::from_path(dir.path().join(COMMODITY_PRICES_FILE_NAME))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_commodity_balance_duals(
        commodity_id: CommodityID,
        region_id: RegionID,
        time_slice: TimeSliceID,
    ) {
        let milestone_year = 2020;
        let run_description = "test_run".to_string();
        let value = MoneyPerFlow(0.5);
        let dir = tempdir().unwrap();

        // Write commodity balance dual
        {
            let mut writer = DebugDataWriter::create(dir.path()).unwrap();
            writer
                .write_commodity_balance_duals(
                    milestone_year,
                    &run_description,
                    iter::once((&commodity_id, &region_id, &time_slice, value)),
                )
                .unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = CommodityBalanceDualsRow {
            milestone_year,
            run_description,
            commodity_id,
            region_id,
            time_slice,
            value,
        };
        let records: Vec<CommodityBalanceDualsRow> =
            csv::Reader::from_path(dir.path().join(COMMODITY_BALANCE_DUALS_FILE_NAME))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_unmet_demand(commodity_id: CommodityID, region_id: RegionID, time_slice: TimeSliceID) {
        let milestone_year = 2020;
        let run_description = "test_run".to_string();
        let value = Flow(0.5);
        let dir = tempdir().unwrap();

        // Write unmet demand
        {
            let mut writer = DebugDataWriter::create(dir.path()).unwrap();
            writer
                .write_unmet_demand(
                    milestone_year,
                    &run_description,
                    iter::once((&commodity_id, &region_id, &time_slice, value)),
                )
                .unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = UnmetDemandRow {
            milestone_year,
            run_description,
            commodity_id,
            region_id,
            time_slice,
            value,
        };
        let records: Vec<UnmetDemandRow> =
            csv::Reader::from_path(dir.path().join(UNMET_DEMAND_FILE_NAME))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_activity(assets: AssetPool, time_slice: TimeSliceID) {
        let milestone_year = 2020;
        let run_description = "test_run".to_string();
        let activity = Activity(100.5);
        let activity_dual = MoneyPerActivity(-1.5);
        let column_dual = MoneyPerActivity(5.0);
        let dir = tempdir().unwrap();
        let asset = assets.iter().next().unwrap();

        // Write activity
        {
            let mut writer = DebugDataWriter::create(dir.path()).unwrap();
            writer
                .write_activity(
                    milestone_year,
                    &run_description,
                    iter::once((asset, &time_slice, activity)),
                    iter::once((asset, &time_slice, activity_dual)),
                    iter::once((asset, &time_slice, column_dual)),
                )
                .unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = ActivityRow {
            milestone_year,
            run_description,
            asset_id: asset.id(),
            process_id: asset.process_id().clone(),
            region_id: asset.region_id().clone(),
            time_slice,
            activity: Some(activity),
            activity_dual: Some(activity_dual),
            column_dual: Some(column_dual),
        };
        let records: Vec<ActivityRow> =
            csv::Reader::from_path(dir.path().join(ACTIVITY_ASSET_DISPATCH))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_activity_with_missing_keys(assets: AssetPool, time_slice: TimeSliceID) {
        let milestone_year = 2020;
        let run_description = "test_run".to_string();
        let activity = Activity(100.5);
        let dir = tempdir().unwrap();
        let asset = assets.iter().next().unwrap();

        // Write activity
        {
            let mut writer = DebugDataWriter::create(dir.path()).unwrap();
            writer
                .write_activity(
                    milestone_year,
                    &run_description,
                    iter::once((asset, &time_slice, activity)),
                    iter::empty::<(&AssetRef, &TimeSliceID, MoneyPerActivity)>(),
                    iter::empty::<(&AssetRef, &TimeSliceID, MoneyPerActivity)>(),
                )
                .unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = ActivityRow {
            milestone_year,
            run_description,
            asset_id: asset.id(),
            process_id: asset.process_id().clone(),
            region_id: asset.region_id().clone(),
            time_slice,
            activity: Some(activity),
            activity_dual: None,
            column_dual: None,
        };
        let records: Vec<ActivityRow> =
            csv::Reader::from_path(dir.path().join(ACTIVITY_ASSET_DISPATCH))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_solver_values() {
        let milestone_year = 2020;
        let run_description = "test_run".to_string();
        let objective_value = Money(1234.56);
        let dir = tempdir().unwrap();

        // Write solver values
        {
            let mut writer = DebugDataWriter::create(dir.path()).unwrap();
            writer
                .write_solver_values(milestone_year, &run_description, objective_value)
                .unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = SolverValuesRow {
            milestone_year,
            run_description,
            objective_value,
        };
        let records: Vec<SolverValuesRow> =
            csv::Reader::from_path(dir.path().join(SOLVER_VALUES_FILE_NAME))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_appraisal_results(asset: Asset, appraisal_output: AppraisalOutput) {
        let milestone_year = 2020;
        let run_description = "test_run".to_string();
        let dir = tempdir().unwrap();

        // Write appraisal results
        {
            let mut writer = DebugDataWriter::create(dir.path()).unwrap();
            writer
                .write_appraisal_results(milestone_year, &run_description, &[appraisal_output])
                .unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = AppraisalResultsRow {
            milestone_year,
            run_description,
            asset_id: None,
            process_id: asset.process_id().clone(),
            region_id: asset.region_id().clone(),
            capacity: Capacity(42.0),
            capacity_coefficient: MoneyPerCapacity(2.14),
            metric: Some(4.14),
        };
        let records: Vec<AppraisalResultsRow> =
            csv::Reader::from_path(dir.path().join(APPRAISAL_RESULTS_FILE_NAME))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[rstest]
    fn write_appraisal_time_slice_results(
        asset: Asset,
        appraisal_output: AppraisalOutput,
        time_slice: TimeSliceID,
    ) {
        let milestone_year = 2020;
        let run_description = "test_run".to_string();
        let dir = tempdir().unwrap();
        let demand = indexmap! {time_slice.clone() => Flow(100.0) };

        // Write appraisal time slice results
        {
            let mut writer = DebugDataWriter::create(dir.path()).unwrap();
            writer
                .write_appraisal_time_slice_results(
                    milestone_year,
                    &run_description,
                    &[appraisal_output],
                    &demand,
                )
                .unwrap();
            writer.flush().unwrap();
        }

        // Read back and compare
        let expected = AppraisalResultsTimeSliceRow {
            milestone_year,
            run_description,
            asset_id: None,
            process_id: asset.process_id().clone(),
            region_id: asset.region_id().clone(),
            time_slice: time_slice.clone(),
            activity: Activity(10.0),
            activity_coefficient: MoneyPerActivity(0.5),
            demand: Flow(100.0),
            unmet_demand: Flow(5.0),
        };
        let records: Vec<AppraisalResultsTimeSliceRow> =
            csv::Reader::from_path(dir.path().join(APPRAISAL_RESULTS_TIME_SLICE_FILE_NAME))
                .unwrap()
                .into_deserialize()
                .try_collect()
                .unwrap();
        assert_equal(records, iter::once(expected));
    }

    #[test]
    fn create_output_directory_new_directory() {
        let temp_dir = tempdir().unwrap();
        let output_dir = temp_dir.path().join("new_output");

        // Create a new directory should succeed and return false (no overwrite)
        let result = create_output_directory(&output_dir, false).unwrap();
        assert!(!result);
        assert!(output_dir.exists());
        assert!(output_dir.is_dir());
    }

    #[test]
    fn create_output_directory_existing_empty_directory() {
        let temp_dir = tempdir().unwrap();
        let output_dir = temp_dir.path().join("empty_output");

        // Create the directory first
        fs::create_dir(&output_dir).unwrap();

        // Creating again should succeed and return false (no overwrite needed)
        let result = create_output_directory(&output_dir, false).unwrap();
        assert!(!result);
        assert!(output_dir.exists());
        assert!(output_dir.is_dir());
    }

    #[test]
    fn create_output_directory_existing_with_files_no_overwrite() {
        let temp_dir = tempdir().unwrap();
        let output_dir = temp_dir.path().join("output_with_files");

        // Create directory with a file
        fs::create_dir(&output_dir).unwrap();
        fs::write(output_dir.join("existing_file.txt"), "some content").unwrap();

        // Should fail when allow_overwrite is false
        let result = create_output_directory(&output_dir, false);
        assert!(result.is_err());
        assert!(
            result
                .unwrap_err()
                .to_string()
                .contains("Output folder already exists")
        );
    }

    #[test]
    fn create_output_directory_existing_with_files_allow_overwrite() {
        let temp_dir = tempdir().unwrap();
        let output_dir = temp_dir.path().join("output_with_files");

        // Create directory with a file
        fs::create_dir(&output_dir).unwrap();
        let file_path = output_dir.join("existing_file.txt");
        fs::write(&file_path, "some content").unwrap();

        // Should succeed when allow_overwrite is true and return true (overwrite occurred)
        let result = create_output_directory(&output_dir, true).unwrap();
        assert!(result);
        assert!(output_dir.exists());
        assert!(output_dir.is_dir());
        assert!(!file_path.exists()); // File should be gone
    }

    #[test]
    fn create_output_directory_nested_path() {
        let temp_dir = tempdir().unwrap();
        let output_dir = temp_dir.path().join("nested").join("path").join("output");

        // Should create nested directories and return false (no overwrite)
        let result = create_output_directory(&output_dir, false).unwrap();
        assert!(!result);
        assert!(output_dir.exists());
        assert!(output_dir.is_dir());
    }

    #[test]
    fn create_output_directory_existing_subdirs_with_files_allow_overwrite() {
        let temp_dir = tempdir().unwrap();
        let output_dir = temp_dir.path().join("output_with_subdirs");

        // Create directory structure with files
        fs::create_dir_all(output_dir.join("subdir")).unwrap();
        fs::write(output_dir.join("file1.txt"), "content1").unwrap();
        fs::write(output_dir.join("subdir").join("file2.txt"), "content2").unwrap();

        // Should succeed when allow_overwrite is true and return true (overwrite occurred)
        let result = create_output_directory(&output_dir, true).unwrap();
        assert!(result);
        assert!(output_dir.exists());
        assert!(output_dir.is_dir());
        // All previous content should be gone
        assert!(!output_dir.join("file1.txt").exists());
        assert!(!output_dir.join("subdir").exists());
    }
}