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
//! Calculation for investment tools such as Levelised Cost of X (LCOX) and Net Present Value (NPV).
use super::DemandMap;
use crate::agent::ObjectiveType;
use crate::asset::{Asset, AssetCapacity, AssetRef};
use crate::commodity::Commodity;
use crate::finance::{ProfitabilityIndex, lcox, profitability_index};
use crate::model::Model;
use crate::time_slice::TimeSliceID;
use crate::units::{Activity, Capacity, Money, MoneyPerActivity, MoneyPerCapacity};
use anyhow::Result;
use costs::annual_fixed_cost;
use erased_serde::Serialize as ErasedSerialize;
use indexmap::IndexMap;
use optimisation::ResultsMap;
use serde::Serialize;
use std::any::Any;
use std::cmp::Ordering;
use std::rc::Rc;

pub mod coefficients;
mod constraints;
mod costs;
mod optimisation;
use coefficients::ObjectiveCoefficients;
use float_cmp::approx_eq;
use float_cmp::{ApproxEq, F64Margin};
use optimisation::perform_optimisation;

/// Compares two values with approximate equality checking.
///
/// Returns `Ordering::Equal` if the values are approximately equal
/// according to the default floating-point margin, otherwise returns
/// their relative ordering based on `a.partial_cmp(&b)`.
///
/// This is useful when comparing floating-point-based types where exact
/// equality may not be appropriate due to numerical precision limitations.
///
/// # Panics
///
/// Panics if `partial_cmp` returns `None` (i.e., if either value is NaN).
fn compare_approx<T>(a: T, b: T) -> Ordering
where
    T: Copy + PartialOrd + ApproxEq<Margin = F64Margin>,
{
    if a.approx_eq(b, F64Margin::default()) {
        Ordering::Equal
    } else {
        a.partial_cmp(&b).expect("Cannot compare NaN values")
    }
}

/// The output of investment appraisal required to compare potential investment decisions
pub struct AppraisalOutput {
    /// The asset being appraised
    pub asset: AssetRef,
    /// The hypothetical capacity to install
    pub capacity: AssetCapacity,
    /// Time slice level activity of the asset
    pub activity: IndexMap<TimeSliceID, Activity>,
    /// The hypothetical unmet demand following investment in this asset
    pub unmet_demand: DemandMap,
    /// The comparison metric to compare investment decisions
    pub metric: Option<Box<dyn MetricTrait>>,
    /// Capacity and activity coefficients used in the appraisal
    pub coefficients: Rc<ObjectiveCoefficients>,
}

impl AppraisalOutput {
    /// Create a new `AppraisalOutput`
    fn new<T: MetricTrait>(
        asset: AssetRef,
        results: ResultsMap,
        metric: Option<T>,
        coefficients: Rc<ObjectiveCoefficients>,
    ) -> Self {
        Self {
            asset,
            capacity: results.capacity,
            activity: results.activity,
            unmet_demand: results.unmet_demand,
            metric: metric.map(|m| Box::new(m) as Box<dyn MetricTrait>),
            coefficients,
        }
    }
    /// Compare this appraisal to another on the basis of the comparison metric.
    ///
    /// Note that if the metrics are approximately equal (as determined by the [`approx_eq!`] macro)
    /// then [`Ordering::Equal`] is returned. The reason for this is because different CPU
    /// architectures may lead to subtly different values for the comparison metrics and if the
    /// value is very similar to another, then it can lead to different decisions being made,
    /// depending on the user's platform (e.g. macOS ARM vs. Windows). We want to avoid this, if
    /// possible, which is why we use a more approximate comparison.
    pub fn compare_metric(&self, other: &Self) -> Ordering {
        assert!(
            self.is_valid() && other.is_valid(),
            "Cannot compare non-valid outputs"
        );

        // We've already checked the metrics aren't `None` in `is_valid`
        self.metric
            .as_ref()
            .unwrap()
            .compare(other.metric.as_ref().unwrap().as_ref())
    }

    /// Whether this [`AppraisalOutput`] is a valid output.
    ///
    /// Specifically, it checks whether the metric is a valid value (not `None`) and that the
    /// calculated capacity is greater than zero.
    pub fn is_valid(&self) -> bool {
        self.metric.is_some() && self.capacity.total_capacity() > Capacity(0.0)
    }
}

/// Supertrait for appraisal metrics that can be serialised and compared.
pub trait MetricTrait: ComparableMetric + ErasedSerialize {}
erased_serde::serialize_trait_object!(MetricTrait);

/// Trait for appraisal metrics that can be compared.
///
/// Implementers define how their values should be compared to determine
/// which investment option is preferable through the `compare` method.
pub trait ComparableMetric: Any + Send + Sync {
    /// Returns the numeric value of this metric.
    fn value(&self) -> f64;

    /// Compares this metric with another of the same type.
    ///
    /// Returns `Ordering::Less` if `self` is better than `other`,
    /// `Ordering::Greater` if `other` is better, or `Ordering::Equal`
    /// if they are approximately equal.
    ///
    /// # Panics
    ///
    /// Panics if `other` is not the same concrete type as `self`.
    fn compare(&self, other: &dyn ComparableMetric) -> Ordering;

    /// Helper for downcasting to enable type-safe comparison.
    fn as_any(&self) -> &dyn Any;
}

/// Levelised Cost of X (LCOX) metric.
///
/// Represents the average cost per unit of output. Lower values indicate
/// more cost-effective investments.
#[derive(Debug, Clone, Serialize)]
pub struct LCOXMetric {
    /// The calculated cost value for this LCOX metric
    pub cost: MoneyPerActivity,
}

impl LCOXMetric {
    /// Creates a new `LCOXMetric` with the given cost.
    pub fn new(cost: MoneyPerActivity) -> Self {
        Self { cost }
    }
}

impl ComparableMetric for LCOXMetric {
    fn value(&self) -> f64 {
        self.cost.value()
    }

    fn compare(&self, other: &dyn ComparableMetric) -> Ordering {
        let other = other
            .as_any()
            .downcast_ref::<Self>()
            .expect("Cannot compare metrics of different types");

        compare_approx(self.cost, other.cost)
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// `LCOXMetric` implements the `MetricTrait` supertrait.
impl MetricTrait for LCOXMetric {}

/// Net Present Value (NPV) metric
#[derive(Debug, Clone, Serialize)]
pub struct NPVMetric(ProfitabilityIndex);

impl NPVMetric {
    /// Creates a new `NPVMetric` with the given profitability index.
    pub fn new(profitability_index: ProfitabilityIndex) -> Self {
        Self(profitability_index)
    }

    /// Returns true if this metric represents a zero fixed cost case.
    fn is_zero_fixed_cost(&self) -> bool {
        approx_eq!(Money, self.0.annualised_fixed_cost, Money(0.0))
    }
}

impl ComparableMetric for NPVMetric {
    fn value(&self) -> f64 {
        if self.is_zero_fixed_cost() {
            self.0.total_annualised_surplus.value()
        } else {
            self.0.value().value()
        }
    }

    /// Higher profitability index values indicate more profitable investments.
    /// When annual fixed cost is zero, the profitability index is infinite and
    /// total surplus is used for comparison instead.
    fn compare(&self, other: &dyn ComparableMetric) -> Ordering {
        let other = other
            .as_any()
            .downcast_ref::<Self>()
            .expect("Cannot compare metrics of different types");

        // Handle comparison based on fixed cost status
        match (self.is_zero_fixed_cost(), other.is_zero_fixed_cost()) {
            // Both have zero fixed cost: compare total surplus (higher is better)
            (true, true) => {
                let self_surplus = self.0.total_annualised_surplus;
                let other_surplus = other.0.total_annualised_surplus;
                compare_approx(other_surplus, self_surplus)
            }
            // Both have non-zero fixed cost: compare profitability index (higher is better)
            (false, false) => {
                let self_pi = self.0.value();
                let other_pi = other.0.value();
                compare_approx(other_pi, self_pi)
            }
            // Zero fixed cost is always better than non-zero fixed cost
            (true, false) => Ordering::Less,
            (false, true) => Ordering::Greater,
        }
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// `NPVMetric` implements the `MetricTrait` supertrait.
impl MetricTrait for NPVMetric {}

/// Calculate LCOX for a hypothetical investment in the given asset.
///
/// This is more commonly referred to as Levelised Cost of *Electricity*, but as the model can
/// include other flows, we use the term LCOX.
///
/// # Returns
///
/// An `AppraisalOutput` containing the hypothetical capacity, activity profile and unmet demand.
/// The returned `metric` is the LCOX value (lower is better).
fn calculate_lcox(
    model: &Model,
    asset: &AssetRef,
    max_capacity: Option<AssetCapacity>,
    commodity: &Commodity,
    coefficients: &Rc<ObjectiveCoefficients>,
    demand: &DemandMap,
) -> Result<AppraisalOutput> {
    let results = perform_optimisation(
        asset,
        max_capacity,
        commodity,
        coefficients,
        demand,
        &model.time_slice_info,
        highs::Sense::Minimise,
    )?;

    let cost_index = lcox(
        results.capacity.total_capacity(),
        coefficients.capacity_coefficient,
        &results.activity,
        &coefficients.activity_coefficients,
    );

    Ok(AppraisalOutput::new(
        asset.clone(),
        results,
        cost_index.map(LCOXMetric::new),
        coefficients.clone(),
    ))
}

/// Calculate NPV for a hypothetical investment in the given asset.
///
/// # Returns
///
/// An `AppraisalOutput` containing the hypothetical capacity, activity profile and unmet demand.
fn calculate_npv(
    model: &Model,
    asset: &AssetRef,
    max_capacity: Option<AssetCapacity>,
    commodity: &Commodity,
    coefficients: &Rc<ObjectiveCoefficients>,
    demand: &DemandMap,
) -> Result<AppraisalOutput> {
    let results = perform_optimisation(
        asset,
        max_capacity,
        commodity,
        coefficients,
        demand,
        &model.time_slice_info,
        highs::Sense::Maximise,
    )?;

    let annual_fixed_cost = annual_fixed_cost(asset);
    assert!(
        annual_fixed_cost >= MoneyPerCapacity(0.0),
        "The current NPV calculation does not support negative annual fixed costs"
    );

    let profitability_index = profitability_index(
        results.capacity.total_capacity(),
        annual_fixed_cost,
        &results.activity,
        &coefficients.activity_coefficients,
    );

    Ok(AppraisalOutput::new(
        asset.clone(),
        results,
        Some(NPVMetric::new(profitability_index)),
        coefficients.clone(),
    ))
}

/// Appraise the given investment with the specified objective type
///
/// # Returns
///
/// The `AppraisalOutput` produced by the selected appraisal method. The `metric` field is
/// comparable with other appraisals of the same type (npv/lcox).
pub fn appraise_investment(
    model: &Model,
    asset: &AssetRef,
    max_capacity: Option<AssetCapacity>,
    commodity: &Commodity,
    objective_type: &ObjectiveType,
    coefficients: &Rc<ObjectiveCoefficients>,
    demand: &DemandMap,
) -> Result<AppraisalOutput> {
    let appraisal_method = match objective_type {
        ObjectiveType::LevelisedCostOfX => calculate_lcox,
        ObjectiveType::NetPresentValue => calculate_npv,
    };
    appraisal_method(model, asset, max_capacity, commodity, coefficients, demand)
}

/// Compare assets as a fallback if metrics are equal.
///
/// Commissioned assets are ordered before uncommissioned and newer before older.
///
/// Used as a fallback to sort assets when they have equal appraisal tool outputs.
fn compare_asset_fallback(asset1: &Asset, asset2: &Asset) -> Ordering {
    (asset2.is_commissioned(), asset2.commission_year())
        .cmp(&(asset1.is_commissioned(), asset1.commission_year()))
}

/// Sort appraisal outputs by their investment priority and exclude non-feasible options.
///
/// Investment priority is primarily decided by appraisal metric. When appraisal metrics are equal,
/// a tie-breaker fallback is used. Commissioned assets are preferred over uncommissioned assets,
/// and newer assets are preferred over older ones. The function does not guarantee that all ties
/// will be resolved.
///
/// Before sorting, outputs are filtered using [`AppraisalOutput::is_valid`], which excludes entries
/// with invalid metrics (e.g. `None`) as well as zero capacity. This avoids meaningless or `NaN`
/// appraisal metrics that could cause the program to panic, so the length of the returned vector
/// may be less than the input.
pub fn sort_and_filter_appraisal_outputs(outputs_for_opts: &mut Vec<AppraisalOutput>) {
    outputs_for_opts.retain(AppraisalOutput::is_valid);
    outputs_for_opts.sort_by(|output1, output2| match output1.compare_metric(output2) {
        // If equal, we fall back on comparing asset properties
        Ordering::Equal => compare_asset_fallback(&output1.asset, &output2.asset),
        cmp => cmp,
    });
}

/// Counts the number of top appraisal outputs in a sorted slice that are indistinguishable
/// by both metric and fallback ordering. Excludes the first element from the count.
pub fn count_equal_and_best_appraisal_outputs(outputs: &[AppraisalOutput]) -> usize {
    if outputs.is_empty() {
        return 0;
    }
    outputs[1..]
        .iter()
        .take_while(|output| {
            output.compare_metric(&outputs[0]).is_eq()
                && compare_asset_fallback(&output.asset, &outputs[0].asset).is_eq()
        })
        .count()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agent::AgentID;
    use crate::finance::ProfitabilityIndex;
    use crate::fixture::{agent_id, asset, process, region_id};
    use crate::process::Process;
    use crate::region::RegionID;
    use crate::units::{Money, MoneyPerActivity, MoneyPerFlow};
    use float_cmp::assert_approx_eq;
    use rstest::rstest;
    use std::rc::Rc;

    /// Parametrised tests for LCOX metric comparison.
    #[rstest]
    #[case(10.0, 10.0, Ordering::Equal, "equal_costs")]
    #[case(5.0, 10.0, Ordering::Less, "first_lower_cost_is_better")]
    #[case(10.0, 5.0, Ordering::Greater, "second_lower_cost_is_better")]
    fn lcox_metric_comparison(
        #[case] cost1: f64,
        #[case] cost2: f64,
        #[case] expected: Ordering,
        #[case] description: &str,
    ) {
        let metric1 = LCOXMetric::new(MoneyPerActivity(cost1));
        let metric2 = LCOXMetric::new(MoneyPerActivity(cost2));

        assert_eq!(
            metric1.compare(&metric2),
            expected,
            "Failed comparison for case: {description}"
        );
    }

    /// Parametrised tests for NPV metric comparison.
    #[rstest]
    // Both zero AFC: compare by total surplus (higher is better)
    #[case(100.0, 0.0, 50.0, 0.0, Ordering::Less, "both_zero_afc_first_better")]
    #[case(
        50.0,
        0.0,
        100.0,
        0.0,
        Ordering::Greater,
        "both_zero_afc_second_better"
    )]
    #[case(100.0, 0.0, 100.0, 0.0, Ordering::Equal, "both_zero_afc_equal")]
    // Both approximately zero AFC (same as both zero): compare by total surplus (higher is better)
    #[case(
        100.0,
        1e-10,
        50.0,
        1e-10,
        Ordering::Less,
        "both_approx_zero_afc_first_better"
    )]
    #[case(
        100.0,
        1e-10,
        200.0,
        50.0,
        Ordering::Less,
        "approx_zero_afc_beats_nonzero"
    )]
    #[case(
        200.0,
        50.0,
        100.0,
        1e-10,
        Ordering::Greater,
        "nonzero_afc_loses_to_approx_zero"
    )]
    // Both non-zero AFC: compare by profitability index (higher is better)
    #[case(
        200.0,
        100.0,
        150.0,
        100.0,
        Ordering::Less,
        "both_nonzero_afc_first_better"
    )]
    #[case(
        150.0,
        100.0,
        200.0,
        100.0,
        Ordering::Greater,
        "both_nonzero_afc_second_better"
    )]
    #[case(200.0, 100.0, 200.0, 100.0, Ordering::Equal, "both_nonzero_afc_equal")]
    // Zero vs non-zero AFC: zero or approximately zero is always better
    #[case(
        10.0,
        0.0,
        1000.0,
        100.0,
        Ordering::Less,
        "first_zero_afc_beats_second_nonzero_afc"
    )]
    #[case(
        10.0,
        1e-10,
        1000.0,
        100.0,
        Ordering::Less,
        "first_approx_zero_afc_beats_second_nonzero_afc"
    )]
    #[case(
        1000.0,
        100.0,
        10.0,
        0.0,
        Ordering::Greater,
        "second_zero_afc_beats_first_nonzero_afc"
    )]
    #[case(
        1000.0,
        100.0,
        10.0,
        1e-10,
        Ordering::Greater,
        "second_nonzero_afc_beats_first_approx_zero_afc"
    )]
    fn npv_metric_comparison(
        #[case] surplus1: f64,
        #[case] fixed_cost1: f64,
        #[case] surplus2: f64,
        #[case] fixed_cost2: f64,
        #[case] expected: Ordering,
        #[case] description: &str,
    ) {
        let metric1 = NPVMetric::new(ProfitabilityIndex {
            total_annualised_surplus: Money(surplus1),
            annualised_fixed_cost: Money(fixed_cost1),
        });
        let metric2 = NPVMetric::new(ProfitabilityIndex {
            total_annualised_surplus: Money(surplus2),
            annualised_fixed_cost: Money(fixed_cost2),
        });

        assert_eq!(
            metric1.compare(&metric2),
            expected,
            "Failed comparison for case: {description}"
        );
    }

    #[rstest]
    fn compare_assets_fallback(process: Process, region_id: RegionID, agent_id: AgentID) {
        let process = Rc::new(process);
        let capacity = Capacity(2.0);
        let asset1 = Asset::new_commissioned(
            agent_id.clone(),
            process.clone(),
            region_id.clone(),
            capacity,
            2015,
        )
        .unwrap();
        let asset2 =
            Asset::new_candidate(process.clone(), region_id.clone(), capacity, 2015).unwrap();
        let asset3 =
            Asset::new_commissioned(agent_id, process, region_id.clone(), capacity, 2010).unwrap();

        assert!(compare_asset_fallback(&asset1, &asset1).is_eq());
        assert!(compare_asset_fallback(&asset2, &asset2).is_eq());
        assert!(compare_asset_fallback(&asset3, &asset3).is_eq());
        assert!(compare_asset_fallback(&asset1, &asset2).is_lt());
        assert!(compare_asset_fallback(&asset2, &asset1).is_gt());
        assert!(compare_asset_fallback(&asset1, &asset3).is_lt());
        assert!(compare_asset_fallback(&asset3, &asset1).is_gt());
        assert!(compare_asset_fallback(&asset3, &asset2).is_lt());
        assert!(compare_asset_fallback(&asset2, &asset3).is_gt());
    }

    fn objective_coeffs() -> Rc<ObjectiveCoefficients> {
        Rc::new(ObjectiveCoefficients {
            capacity_coefficient: MoneyPerCapacity(0.0),
            activity_coefficients: IndexMap::new(),
            unmet_demand_coefficient: MoneyPerFlow(0.0),
        })
    }

    /// Creates appraisal from corresponding assets and metrics
    ///
    /// # Panics
    ///
    /// Panics if `assets` and `metrics` have different lengths
    fn appraisal_outputs(
        assets: Vec<Asset>,
        metrics: Vec<Box<dyn MetricTrait>>,
    ) -> Vec<AppraisalOutput> {
        assert_eq!(
            assets.len(),
            metrics.len(),
            "assets and metrics must have the same length"
        );

        assets
            .into_iter()
            .zip(metrics)
            .map(|(asset, metric)| AppraisalOutput {
                asset: AssetRef::from(asset),
                capacity: AssetCapacity::Continuous(Capacity(10.0)),
                coefficients: objective_coeffs(),
                activity: IndexMap::new(),
                unmet_demand: IndexMap::new(),
                metric: Some(metric),
            })
            .collect()
    }

    /// Creates appraisal outputs with given metrics.
    /// Copies the provided default asset for each metric.
    fn appraisal_outputs_with_investment_priority_invariant_to_assets(
        metrics: Vec<Box<dyn MetricTrait>>,
        asset: &Asset,
    ) -> Vec<AppraisalOutput> {
        let assets = vec![asset.clone(); metrics.len()];
        appraisal_outputs(assets, metrics)
    }

    /// Test sorting by LCOX metric when invariant to asset properties
    #[rstest]
    fn appraisal_sort_by_lcox_metric(asset: Asset) {
        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(3.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(7.0))),
        ];

        let mut outputs =
            appraisal_outputs_with_investment_priority_invariant_to_assets(metrics, &asset);
        sort_and_filter_appraisal_outputs(&mut outputs);

        assert_approx_eq!(f64, outputs[0].metric.as_ref().unwrap().value(), 3.0); // Best (lowest)
        assert_approx_eq!(f64, outputs[1].metric.as_ref().unwrap().value(), 5.0);
        assert_approx_eq!(f64, outputs[2].metric.as_ref().unwrap().value(), 7.0); // Worst (highest)
    }

    /// Test sorting by NPV profitability index when invariant to asset properties
    #[rstest]
    fn appraisal_sort_by_npv_metric(asset: Asset) {
        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(200.0),
                annualised_fixed_cost: Money(100.0),
            })),
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(300.0),
                annualised_fixed_cost: Money(100.0),
            })),
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(150.0),
                annualised_fixed_cost: Money(100.0),
            })),
        ];

        let mut outputs =
            appraisal_outputs_with_investment_priority_invariant_to_assets(metrics, &asset);
        sort_and_filter_appraisal_outputs(&mut outputs);

        // Higher profitability index is better, so should be sorted: 3.0, 2.0, 1.5
        assert_approx_eq!(f64, outputs[0].metric.as_ref().unwrap().value(), 3.0); // Best (highest PI)
        assert_approx_eq!(f64, outputs[1].metric.as_ref().unwrap().value(), 2.0);
        assert_approx_eq!(f64, outputs[2].metric.as_ref().unwrap().value(), 1.5); // Worst (lowest PI)
    }

    /// Test that NPV metrics with zero annual fixed cost are prioritised above all others
    /// when invariant to asset properties
    #[rstest]
    fn appraisal_sort_by_npv_metric_zero_afc_prioritised(asset: Asset) {
        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            // Very high profitability index but non-zero AFC
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(1000.0),
                annualised_fixed_cost: Money(100.0),
            })),
            // Zero AFC with modest surplus - should be prioritised first
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(50.0),
                annualised_fixed_cost: Money(0.0),
            })),
            // Another high profitability index but non-zero AFC
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(500.0),
                annualised_fixed_cost: Money(50.0),
            })),
        ];

        let mut outputs =
            appraisal_outputs_with_investment_priority_invariant_to_assets(metrics, &asset);
        sort_and_filter_appraisal_outputs(&mut outputs);

        // Zero AFC should be first despite lower absolute surplus value
        assert_approx_eq!(f64, outputs[0].metric.as_ref().unwrap().value(), 50.0); // Zero AFC (uses surplus)
        assert_approx_eq!(f64, outputs[1].metric.as_ref().unwrap().value(), 10.0); // PI = 1000/100
        assert_approx_eq!(f64, outputs[2].metric.as_ref().unwrap().value(), 10.0); // PI = 500/50
    }

    /// Test that mixing LCOX and NPV metrics causes a runtime panic during comparison
    #[rstest]
    #[should_panic(expected = "Cannot compare metrics of different types")]
    fn appraisal_sort_by_mixed_metrics_panics(asset: Asset) {
        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(200.0),
                annualised_fixed_cost: Money(100.0),
            })),
            Box::new(LCOXMetric::new(MoneyPerActivity(3.0))),
        ];

        let mut outputs =
            appraisal_outputs_with_investment_priority_invariant_to_assets(metrics, &asset);
        // This should panic when trying to compare different metric types
        sort_and_filter_appraisal_outputs(&mut outputs);
    }

    /// Test that when metrics are equal, commissioned assets are sorted by commission year (newer first)
    #[rstest]
    fn appraisal_sort_by_commission_year_when_metrics_equal(
        process: Process,
        region_id: RegionID,
        agent_id: AgentID,
    ) {
        let process_rc = Rc::new(process);
        let capacity = Capacity(10.0);
        let commission_years = [2015, 2020, 2010];

        let assets: Vec<_> = commission_years
            .iter()
            .map(|&year| {
                Asset::new_commissioned(
                    agent_id.clone(),
                    process_rc.clone(),
                    region_id.clone(),
                    capacity,
                    year,
                )
                .unwrap()
            })
            .collect();

        // All metrics have the same value
        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
        ];

        let mut outputs = appraisal_outputs(assets, metrics);
        sort_and_filter_appraisal_outputs(&mut outputs);

        // Should be sorted by commission year, newest first: 2020, 2015, 2010
        assert_eq!(outputs[0].asset.commission_year(), 2020);
        assert_eq!(outputs[1].asset.commission_year(), 2015);
        assert_eq!(outputs[2].asset.commission_year(), 2010);
    }

    /// Test that when metrics and commission years are equal, the original order is preserved
    #[rstest]
    fn appraisal_sort_maintains_order_when_all_equal(process: Process, region_id: RegionID) {
        let process_rc = Rc::new(process);
        let capacity = Capacity(10.0);
        let commission_year = 2015;
        let agent_ids = ["agent1", "agent2", "agent3"];

        let assets: Vec<_> = agent_ids
            .iter()
            .map(|&id| {
                Asset::new_commissioned(
                    AgentID(id.into()),
                    process_rc.clone(),
                    region_id.clone(),
                    capacity,
                    commission_year,
                )
                .unwrap()
            })
            .collect();

        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
        ];

        let mut outputs = appraisal_outputs(assets.clone(), metrics);
        sort_and_filter_appraisal_outputs(&mut outputs);

        // Verify order is preserved - should match the original agent_ids array
        for (&expected_id, output) in agent_ids.iter().zip(outputs) {
            assert_eq!(output.asset.agent_id(), Some(&AgentID(expected_id.into())));
        }
    }

    /// Test that commissioned assets are prioritised over non-commissioned assets when metrics are equal
    #[rstest]
    fn appraisal_sort_commissioned_before_uncommissioned_when_metrics_equal(
        process: Process,
        region_id: RegionID,
        agent_id: AgentID,
    ) {
        let process_rc = Rc::new(process);
        let capacity = Capacity(10.0);

        // Create a mix of commissioned and candidate (non-commissioned) assets
        let commissioned_asset_newer = Asset::new_commissioned(
            agent_id.clone(),
            process_rc.clone(),
            region_id.clone(),
            capacity,
            2020,
        )
        .unwrap();

        let commissioned_asset_older = Asset::new_commissioned(
            agent_id.clone(),
            process_rc.clone(),
            region_id.clone(),
            capacity,
            2015,
        )
        .unwrap();

        let candidate_asset =
            Asset::new_candidate(process_rc.clone(), region_id.clone(), capacity, 2020).unwrap();

        let assets = vec![
            candidate_asset.clone(),
            commissioned_asset_older.clone(),
            candidate_asset.clone(),
            commissioned_asset_newer.clone(),
        ];

        // All metrics have identical values to test fallback ordering
        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
            Box::new(LCOXMetric::new(MoneyPerActivity(5.0))),
        ];

        let mut outputs = appraisal_outputs(assets, metrics);
        sort_and_filter_appraisal_outputs(&mut outputs);

        // Commissioned assets should be prioritised first
        assert!(outputs[0].asset.is_commissioned());
        assert!(outputs[0].asset.commission_year() == 2020);
        assert!(outputs[1].asset.is_commissioned());
        assert!(outputs[1].asset.commission_year() == 2015);

        // Non-commissioned assets should come after
        assert!(!outputs[2].asset.is_commissioned());
        assert!(!outputs[3].asset.is_commissioned());
    }

    /// Test that appraisal metric is prioritised over asset properties when sorting
    #[rstest]
    fn appraisal_metric_is_prioritised_over_asset_properties(
        process: Process,
        region_id: RegionID,
        agent_id: AgentID,
    ) {
        let process_rc = Rc::new(process);
        let capacity = Capacity(10.0);

        // Create a mix of commissioned and candidate (non-commissioned) assets
        let commissioned_asset_newer = Asset::new_commissioned(
            agent_id.clone(),
            process_rc.clone(),
            region_id.clone(),
            capacity,
            2020,
        )
        .unwrap();

        let commissioned_asset_older = Asset::new_commissioned(
            agent_id.clone(),
            process_rc.clone(),
            region_id.clone(),
            capacity,
            2015,
        )
        .unwrap();

        let candidate_asset =
            Asset::new_candidate(process_rc.clone(), region_id.clone(), capacity, 2020).unwrap();

        let assets = vec![
            candidate_asset.clone(),
            commissioned_asset_older.clone(),
            candidate_asset.clone(),
            commissioned_asset_newer.clone(),
        ];

        // Make one metric slightly better than all others
        let baseline_metric_value = 5.0;
        let best_metric_value = baseline_metric_value - 1e-5;
        let metrics: Vec<Box<dyn MetricTrait>> = vec![
            Box::new(LCOXMetric::new(MoneyPerActivity(best_metric_value))),
            Box::new(LCOXMetric::new(MoneyPerActivity(baseline_metric_value))),
            Box::new(LCOXMetric::new(MoneyPerActivity(baseline_metric_value))),
            Box::new(LCOXMetric::new(MoneyPerActivity(baseline_metric_value))),
        ];

        let mut outputs = appraisal_outputs(assets, metrics);
        sort_and_filter_appraisal_outputs(&mut outputs);

        // non-commissioned asset prioritised because it has a slightly better metric
        assert_approx_eq!(
            f64,
            outputs[0].metric.as_ref().unwrap().value(),
            best_metric_value
        );
    }

    /// Test that appraisal outputs with zero capacity are filtered out during sorting.
    #[rstest]
    fn appraisal_sort_filters_zero_capacity_outputs(asset: Asset) {
        let metric = LCOXMetric::new(MoneyPerActivity(1.0));
        let metrics = [
            Box::new(metric.clone()),
            Box::new(metric.clone()),
            Box::new(metric),
        ];

        // Create outputs with zero capacity
        let mut outputs: Vec<AppraisalOutput> = metrics
            .into_iter()
            .map(|metric| AppraisalOutput {
                asset: AssetRef::from(asset.clone()),
                capacity: AssetCapacity::Continuous(Capacity(0.0)),
                coefficients: objective_coeffs(),
                activity: IndexMap::new(),
                unmet_demand: IndexMap::new(),
                metric: Some(metric),
            })
            .collect();

        sort_and_filter_appraisal_outputs(&mut outputs);

        // All zero capacity outputs should be filtered out
        assert_eq!(outputs.len(), 0);
    }

    /// Test that appraisal outputs with an invalid metric are filtered out
    #[rstest]
    fn appraisal_sort_filters_invalid_metric(asset: Asset) {
        let output = AppraisalOutput {
            asset: AssetRef::from(asset),
            capacity: AssetCapacity::Continuous(Capacity(1.0)), // non-zero capacity
            coefficients: objective_coeffs(),
            activity: IndexMap::new(),
            unmet_demand: IndexMap::new(),
            metric: None,
        };
        let mut outputs = vec![output];

        sort_and_filter_appraisal_outputs(&mut outputs);

        // The invalid output should have been filtered out
        assert_eq!(outputs.len(), 0);
    }

    /// Tests for counting number of equal metrics using identical assets so only metric values
    /// affect the count.
    #[rstest]
    #[case(vec![5.0], 0, "single_element")]
    #[case(vec![5.0, 5.0, 5.0], 2, "all_equal_returns_len_minus_one")]
    #[case(vec![1.0, 2.0, 3.0], 0, "none_equal_to_best")]
    #[case(vec![5.0, 5.0, 9.0], 1, "partial_equality_stops_at_first_difference")]
    #[case(vec![5.0, 5.0, 9.0, 5.0], 1, "equality_does_not_resume_after_gap")]
    fn count_equal_best_lcox_metric(
        asset: Asset,
        #[case] metric_values: Vec<f64>,
        #[case] expected_count: usize,
        #[case] description: &str,
    ) {
        let metrics: Vec<Box<dyn MetricTrait>> = metric_values
            .into_iter()
            .map(|v| Box::new(LCOXMetric::new(MoneyPerActivity(v))) as Box<dyn MetricTrait>)
            .collect();

        let outputs =
            appraisal_outputs_with_investment_priority_invariant_to_assets(metrics, &asset);

        assert_eq!(
            count_equal_and_best_appraisal_outputs(&outputs),
            expected_count,
            "Failed for case: {description}"
        );
    }

    /// Empty slice count should return 0.
    #[test]
    fn count_equal_best_empty_slice_returns_zero() {
        let outputs: Vec<AppraisalOutput> = vec![];
        assert_eq!(count_equal_and_best_appraisal_outputs(&outputs), 0);
    }

    /// Equal metrics but differing asset fallback (commissioned vs. candidate) →
    /// outputs are distinguishable, so count should be 0.
    #[rstest]
    fn count_equal_best_equal_metric_different_fallback_returns_zero(
        process: Process,
        region_id: RegionID,
        agent_id: AgentID,
    ) {
        let process_rc = Rc::new(process);
        let capacity = Capacity(10.0);

        let commissioned = Asset::new_commissioned(
            agent_id.clone(),
            process_rc.clone(),
            region_id.clone(),
            capacity,
            2020,
        )
        .unwrap();
        let candidate =
            Asset::new_candidate(process_rc.clone(), region_id.clone(), capacity, 2020).unwrap();

        let metric_value = MoneyPerActivity(5.0);
        let outputs = appraisal_outputs(
            vec![commissioned, candidate],
            vec![
                Box::new(LCOXMetric::new(metric_value)),
                Box::new(LCOXMetric::new(metric_value)),
            ],
        );

        assert_eq!(count_equal_and_best_appraisal_outputs(&outputs), 0);
    }

    /// Equal metrics and equal asset fallback (same commissioned status and commission year) →
    /// the second element is indistinguishable, so count should be 1.
    #[rstest]
    fn count_equal_best_equal_metric_and_equal_fallback_returns_one(
        process: Process,
        region_id: RegionID,
        agent_id: AgentID,
    ) {
        let process_rc = Rc::new(process);
        let capacity = Capacity(10.0);
        let year = 2020;

        let asset1 = Asset::new_commissioned(
            agent_id.clone(),
            process_rc.clone(),
            region_id.clone(),
            capacity,
            year,
        )
        .unwrap();
        let asset2 = Asset::new_commissioned(
            agent_id.clone(),
            process_rc.clone(),
            region_id.clone(),
            capacity,
            year,
        )
        .unwrap();

        let metric_value = MoneyPerActivity(5.0);
        let outputs = appraisal_outputs(
            vec![asset1, asset2],
            vec![
                Box::new(LCOXMetric::new(metric_value)),
                Box::new(LCOXMetric::new(metric_value)),
            ],
        );

        assert_eq!(count_equal_and_best_appraisal_outputs(&outputs), 1);
    }

    /// Equal NPV metrics and identical assets → second element should be counted.
    #[rstest]
    fn count_equal_best_equal_npv_metrics(asset: Asset) {
        let make_npv = |surplus: f64, fixed_cost: f64| {
            Box::new(NPVMetric::new(ProfitabilityIndex {
                total_annualised_surplus: Money(surplus),
                annualised_fixed_cost: Money(fixed_cost),
            })) as Box<dyn MetricTrait>
        };

        let metrics = vec![
            make_npv(200.0, 100.0),
            make_npv(200.0, 100.0), // Equal to best
            make_npv(100.0, 100.0), // Worse
        ];

        let outputs =
            appraisal_outputs_with_investment_priority_invariant_to_assets(metrics, &asset);

        assert_eq!(count_equal_and_best_appraisal_outputs(&outputs), 1);
    }
}