diff --git a/src/output.rs b/src/output.rs index 9479e942e..c15146635 100644 --- a/src/output.rs +++ b/src/output.rs @@ -280,8 +280,9 @@ struct AppraisalResultsTimeSliceRow { /// For writing extra debug information about the model struct DebugDataWriter { context: Option, + unmet_demand_file_path: PathBuf, commodity_balance_duals_writer: csv::Writer, - unmet_demand_writer: csv::Writer, + unmet_demand_writer: Option>, solver_values_writer: csv::Writer, appraisal_results_writer: csv::Writer, appraisal_results_time_slice_writer: csv::Writer, @@ -302,8 +303,9 @@ impl DebugDataWriter { Ok(Self { context: None, + unmet_demand_file_path: output_path.join(UNMET_DEMAND_FILE_NAME), commodity_balance_duals_writer: new_writer(COMMODITY_BALANCE_DUALS_FILE_NAME)?, - unmet_demand_writer: new_writer(UNMET_DEMAND_FILE_NAME)?, + unmet_demand_writer: None, 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( @@ -439,16 +441,32 @@ impl DebugDataWriter { where I: Iterator, { - for (commodity_id, region_id, time_slice, value) in iter { + let mut rows = iter.peekable(); + + if rows.peek().is_none() { + return Ok(()); + } + + // If the unmet demand writer already exist, we panic, as it should not happen + assert!( + self.unmet_demand_writer.is_none(), + "Unmet demand file already exists!" + ); + + let run_description = self.with_context(run_description); + let writer = self + .unmet_demand_writer + .insert(csv::Writer::from_path(&self.unmet_demand_file_path)?); + for (commodity_id, region_id, time_slice, value) in rows { let row = UnmetDemandRow { milestone_year, - run_description: self.with_context(run_description), + run_description: run_description.clone(), commodity_id: commodity_id.clone(), region_id: region_id.clone(), time_slice: time_slice.clone(), value, }; - self.unmet_demand_writer.serialize(row)?; + writer.serialize(row)?; } Ok(()) @@ -529,8 +547,10 @@ impl DebugDataWriter { /// Flush the underlying streams fn flush(&mut self) -> Result<()> { + if let Some(wrt) = &mut self.unmet_demand_writer { + wrt.flush()?; + } 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()?; diff --git a/tests/data/simple/debug_unmet_demand.csv b/tests/data/simple/debug_unmet_demand.csv deleted file mode 100644 index e69de29bb..000000000