gugen 0.7.0

Explainable materials synthesis and process planning
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
//! Multi-source candidate generation (Phase 30). `CandidateGenerator`
//! (`src/provider.rs`) is the per-source contract; this module holds every
//! type built on top of it: the provenance-carrying output shape
//! (`GeneratedCandidate`), three real generators (`CatalogExactGenerator`,
//! `FrequencyPriorGenerator`, `ThermodynamicStabilityGenerator`), and the
//! ensemble that combines them (`CandidateGeneratorEnsemble`). PR 1 shipped
//! the first two; PR 2 adds `ThermodynamicStabilityGenerator`.
//! `prior-experiment` and `literature-analog` are each their own future PR;
//! `chemical-substitution` has no backing data anywhere in this crate and
//! is deferred indefinitely pending a separate owner decision on
//! caller-supplied similarity data.

use crate::composition::{Composition, Element};
use crate::error::{ProviderError, require_finite};
use crate::precursor::{InMemoryPrecursorCatalog, PrecursorCandidate, PrecursorId};
use crate::provider::{CandidateGenerator, PrecursorCatalog};
use crate::target::PlanningConstraints;
use std::collections::{BTreeMap, BTreeSet};

/// A generator's stable identity, stamped onto every [`GeneratedCandidate`]
/// it produces and used to label a failed `generate()` call in
/// [`EnsembleOutput::generator_errors`]. A string newtype rather than an
/// enum: PR 1 only populates 2 of the eventual 6 named generators, and an
/// enum with unbuilt variants would force a premature `#[non_exhaustive]`
/// decision the crate's own API stability policy reserves for types whose
/// doc comment already states a growth expectation. Adding generator #3
/// later never forces a semver decision this way.
///
/// `Serialize` only, deliberately no `Deserialize`: the inner `&'static
/// str` cannot deserialize into a non-`'static` borrow from an arbitrary
/// input buffer -- matches this crate's existing precedent for
/// `&'static str`-bearing output-only types (`CommercialOfferSelection`,
/// `src/commercial_catalog/model.rs`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct GeneratorId(pub &'static str);

impl std::fmt::Display for GeneratorId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.0)
    }
}

/// One precursor candidate as proposed by exactly one generator. This is
/// where "full provenance" actually lives -- deliberately a wrapper type,
/// not a field added to `PrecursorCandidate` (not `#[non_exhaustive]`,
/// adding a field there would be a breaking change). `rank` is a plain
/// ordinal (0 = the generator's own top pick), never a float/confidence:
/// a generator's internal priority can never be read as a success
/// probability, because the type has no score field to misuse (mirrors
/// `SearchPriority`'s own score/priority separation, `src/precursor.rs`).
///
/// `Serialize` only -- see [`GeneratorId`]'s doc comment (`generator`
/// transitively carries its `&'static str` field).
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct GeneratedCandidate {
    pub candidate: PrecursorCandidate,
    pub generator: GeneratorId,
    pub rank: usize,
}

/// Wraps an existing [`InMemoryPrecursorCatalog`] as a `CandidateGenerator`
/// -- "exact" means literally whatever the catalog returns, in its own
/// element-overlap-filtered order, stamped with rank = output position.
/// Near-zero new logic: reuses `InMemoryPrecursorCatalog`'s existing
/// filter/sort/dedup verbatim rather than reimplementing it.
pub struct CatalogExactGenerator {
    catalog: InMemoryPrecursorCatalog,
}

impl CatalogExactGenerator {
    pub fn new(catalog: InMemoryPrecursorCatalog) -> Self {
        Self { catalog }
    }
}

impl CandidateGenerator for CatalogExactGenerator {
    fn id(&self) -> GeneratorId {
        GeneratorId("catalog-exact")
    }

    fn generate(
        &self,
        target: &Composition,
        constraints: &PlanningConstraints,
    ) -> std::result::Result<Vec<GeneratedCandidate>, ProviderError> {
        let candidates = self.catalog.candidates_for(target, constraints)?;
        Ok(candidates
            .into_iter()
            .enumerate()
            .map(|(rank, candidate)| GeneratedCandidate {
                candidate,
                generator: self.id(),
                rank,
            })
            .collect())
    }
}

/// Proposes precursors ranked by a caller-supplied frequency table --
/// never computed or bundled by this crate itself, matching the
/// established "caller supplies the data, core never fetches/bundles it"
/// convention (`ThermodynamicProvider`/`MaterialsProjectSnapshotProvider`'s
/// own precedent). A caller can build the table from anything: their own
/// literature database, `LiteratureObservationCorpus`, or a benchmark's
/// own precursor-formula counts.
pub struct FrequencyPriorGenerator {
    /// Sorted once at construction (descending frequency, ascending
    /// `PrecursorId` as a deterministic tie-break) -- mirrors
    /// `InMemoryPrecursorCatalog::new`'s own "sort once, not per-query"
    /// convention.
    entries: Vec<(PrecursorCandidate, u64)>,
}

impl FrequencyPriorGenerator {
    pub fn new(mut entries: Vec<(PrecursorCandidate, u64)>) -> Self {
        entries.sort_by(|(a, a_freq), (b, b_freq)| {
            b_freq.cmp(a_freq).then_with(|| a.id.0.cmp(&b.id.0))
        });
        Self { entries }
    }
}

impl CandidateGenerator for FrequencyPriorGenerator {
    fn id(&self) -> GeneratorId {
        GeneratorId("frequency-prior")
    }

    fn generate(
        &self,
        target: &Composition,
        _constraints: &PlanningConstraints,
    ) -> std::result::Result<Vec<GeneratedCandidate>, ProviderError> {
        let target_elements: BTreeSet<Element> = target.elements().collect();
        Ok(self
            .entries
            .iter()
            .filter(|(candidate, _frequency)| {
                candidate
                    .composition
                    .elements()
                    .any(|e| target_elements.contains(&e))
            })
            .enumerate()
            .map(|(rank, (candidate, _frequency))| GeneratedCandidate {
                candidate: candidate.clone(),
                generator: self.id(),
                rank,
            })
            .collect())
    }
}

/// Ranks caller-supplied precursor candidates by absolute thermodynamic
/// stability -- most-negative 0 K formation enthalpy per atom first, the
/// standard materials-informatics cross-compound stability proxy (a
/// convex-hull y-axis value). Never computed or fetched by this crate
/// itself, matching the established "caller supplies real data, core
/// never bundles it" convention (`ThermodynamicProvider`/
/// `MaterialsProjectSnapshotProvider`'s own precedent, and
/// [`FrequencyPriorGenerator`]'s own shape).
///
/// **This ranks each candidate's own absolute stability, not predicted
/// favorability of any specific reaction toward the search target.** A
/// true target-fit signal would need to know the other precursors chosen
/// and the eventual balanced reaction -- information
/// `CandidateGenerator::generate`'s signature (target + constraints only)
/// structurally cannot express, not merely something this generator
/// doesn't yet compute. `decomposition_margin_ev_per_atom`/
/// `balanced_reaction_delta_ev_per_atom` (`src/thermodynamics.rs`) are the
/// reaction-level alternatives; neither is reachable from a
/// `CandidateGenerator`. `ThermodynamicProvider::competing_phases` was
/// deliberately not repurposed into a ranking margin here either -- its
/// own doc comment states it is "context only, never converted into a
/// selectivity score," and reusing it that way here would violate that
/// stated contract.
pub struct ThermodynamicStabilityGenerator {
    /// Sorted once at construction (ascending by formation energy -- most
    /// negative/most stable first -- ascending `PrecursorId` as a
    /// deterministic tie-break) -- mirrors
    /// `InMemoryPrecursorCatalog::new`/`FrequencyPriorGenerator::new`'s own
    /// "sort once, not per-query" convention.
    entries: Vec<(PrecursorCandidate, f64)>,
}

impl ThermodynamicStabilityGenerator {
    /// Validates every formation-energy value is finite, matching every
    /// other f64-formation-energy constructor in this crate
    /// (`CompetingPhase::new`, `SolidThermodynamicEntry::new`,
    /// `ReactionEnergy::new` all call `require_finite`) -- prioritized
    /// over infallibly mirroring `FrequencyPriorGenerator`'s shape (owner's
    /// explicit choice). `f64::total_cmp`, not `partial_cmp`, for the sort
    /// -- no silent NaN-ordering surprise (`require_finite` above already
    /// rules NaN out, but `total_cmp` keeps the ordering total and
    /// panic-free regardless).
    pub fn new(mut entries: Vec<(PrecursorCandidate, f64)>) -> crate::error::Result<Self> {
        for (_candidate, formation_energy) in &entries {
            require_finite("formation_enthalpy_ev_per_atom", *formation_energy)?;
        }
        entries.sort_by(|(a, a_energy), (b, b_energy)| {
            a_energy
                .total_cmp(b_energy)
                .then_with(|| a.id.0.cmp(&b.id.0))
        });
        Ok(Self { entries })
    }
}

impl CandidateGenerator for ThermodynamicStabilityGenerator {
    fn id(&self) -> GeneratorId {
        GeneratorId("thermodynamic-stability")
    }

    fn generate(
        &self,
        target: &Composition,
        _constraints: &PlanningConstraints,
    ) -> std::result::Result<Vec<GeneratedCandidate>, ProviderError> {
        let target_elements: BTreeSet<Element> = target.elements().collect();
        Ok(self
            .entries
            .iter()
            .filter(|(candidate, _formation_energy)| {
                candidate
                    .composition
                    .elements()
                    .any(|e| target_elements.contains(&e))
            })
            .enumerate()
            .map(
                |(rank, (candidate, _formation_energy))| GeneratedCandidate {
                    candidate: candidate.clone(),
                    generator: self.id(),
                    rank,
                },
            )
            .collect())
    }
}

/// Combined output of every generator in a [`CandidateGeneratorEnsemble`]
/// run, per design principle 5 (every branch/provider outcome stays
/// distinguishable, never silently dropped): `candidates` is what a
/// `PrecursorCatalog` caller (e.g. `search_precursor_sets`) actually
/// consumes, `provenance` keeps every generator that proposed each id, and
/// `generator_errors` keeps every generator that failed outright, labeled
/// by which one.
#[derive(Debug, Clone, PartialEq)]
pub struct EnsembleOutput {
    pub candidates: Vec<PrecursorCandidate>,
    pub provenance: BTreeMap<PrecursorId, Vec<GeneratedCandidate>>,
    pub generator_errors: Vec<(GeneratorId, ProviderError)>,
}

/// Combines multiple [`CandidateGenerator`]s into one candidate list via
/// min-rank fusion, and implements [`PrecursorCatalog`] itself -- so an
/// ensemble is a drop-in `Planner::builder` catalog argument, requiring
/// zero changes to `Planner`/`PlannerBuilder`. PR 1 does not wire this
/// into `Planner`; every measurement in this PR calls the ensemble
/// directly, the same way every existing exploration-recall benchmark
/// already bypasses `Planner` and calls `search_precursor_sets` directly.
pub struct CandidateGeneratorEnsemble {
    generators: Vec<Box<dyn CandidateGenerator>>,
}

impl CandidateGeneratorEnsemble {
    pub fn new(generators: Vec<Box<dyn CandidateGenerator>>) -> Self {
        Self { generators }
    }

    /// Runs every generator, catching each one's failure individually
    /// (mirrors the existing `route_suitability_provider` catch-and-
    /// continue loop already in `Planner::plan`, `src/planner.rs`) so one
    /// generator's failure never prevents the others' candidates from
    /// being used.
    ///
    /// **Combination rule -- min-rank fusion**: a candidate's ensemble
    /// rank is the smallest rank any generator gave it, ties broken
    /// alphabetically by `PrecursorId` (matches this crate's existing
    /// determinism discipline, e.g. `search_precursor_sets`'s own
    /// tiebreaks). **Duplicate-id conflicts** (two generators proposing
    /// the same id with different composition/availability data):
    /// first-generator-in-list wins for the payload, matching
    /// `InMemoryPrecursorCatalog::new`'s own stated precedent -- but
    /// every generator that proposed it still appears in `provenance`,
    /// so nothing is silently collapsed.
    pub fn generate_with_provenance(
        &self,
        target: &Composition,
        constraints: &PlanningConstraints,
    ) -> EnsembleOutput {
        let mut best: BTreeMap<PrecursorId, (usize, PrecursorCandidate)> = BTreeMap::new();
        let mut provenance: BTreeMap<PrecursorId, Vec<GeneratedCandidate>> = BTreeMap::new();
        let mut generator_errors = Vec::new();

        for generator in &self.generators {
            match generator.generate(target, constraints) {
                Ok(generated) => {
                    for gc in generated {
                        let id = gc.candidate.id.clone();
                        best.entry(id.clone())
                            .and_modify(|(rank, _payload)| {
                                if gc.rank < *rank {
                                    *rank = gc.rank;
                                }
                            })
                            .or_insert_with(|| (gc.rank, gc.candidate.clone()));
                        provenance.entry(id).or_default().push(gc);
                    }
                }
                Err(err) => generator_errors.push((generator.id(), err)),
            }
        }

        let mut fused: Vec<(usize, PrecursorCandidate)> = best.into_values().collect();
        fused.sort_by(|(rank_a, candidate_a), (rank_b, candidate_b)| {
            rank_a
                .cmp(rank_b)
                .then_with(|| candidate_a.id.0.cmp(&candidate_b.id.0))
        });

        EnsembleOutput {
            candidates: fused
                .into_iter()
                .map(|(_rank, candidate)| candidate)
                .collect(),
            provenance,
            generator_errors,
        }
    }
}

impl PrecursorCatalog for CandidateGeneratorEnsemble {
    fn candidates_for(
        &self,
        target: &Composition,
        constraints: &PlanningConstraints,
    ) -> std::result::Result<Vec<PrecursorCandidate>, ProviderError> {
        Ok(self
            .generate_with_provenance(target, constraints)
            .candidates)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn element(symbol: &str) -> Element {
        Element::new(symbol).unwrap()
    }

    fn composition(pairs: &[(&str, f64)]) -> Composition {
        Composition::new(pairs.iter().map(|&(sym, amt)| (element(sym), amt))).unwrap()
    }

    fn candidate(id: &str, pairs: &[(&str, f64)]) -> PrecursorCandidate {
        PrecursorCandidate {
            id: PrecursorId(id.to_string()),
            composition: composition(pairs),
            availability: None,
        }
    }

    fn no_constraints() -> PlanningConstraints {
        PlanningConstraints::default()
    }

    fn barium_titanate_target() -> Composition {
        composition(&[("Ba", 1.0), ("Ti", 1.0), ("O", 3.0)])
    }

    /// Always fails, to exercise `CandidateGeneratorEnsemble`'s per-
    /// generator error handling without needing a second real generator.
    struct AlwaysFailsGenerator;

    impl CandidateGenerator for AlwaysFailsGenerator {
        fn id(&self) -> GeneratorId {
            GeneratorId("always-fails")
        }

        fn generate(
            &self,
            _target: &Composition,
            _constraints: &PlanningConstraints,
        ) -> std::result::Result<Vec<GeneratedCandidate>, ProviderError> {
            Err(ProviderError::Unavailable("test failure".to_string()))
        }
    }

    #[test]
    fn catalog_exact_generator_delegates_and_stamps_rank_by_output_position() {
        let catalog = InMemoryPrecursorCatalog::new(vec![
            candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]),
            candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
            candidate("NaCl", &[("Na", 1.0), ("Cl", 1.0)]),
        ]);
        let generator = CatalogExactGenerator::new(catalog);

        let generated = generator
            .generate(&barium_titanate_target(), &no_constraints())
            .unwrap();

        // NaCl shares no element with Ba-Ti-O, so InMemoryPrecursorCatalog's
        // own element-overlap filter drops it; BaCO3/TiO2 survive, sorted
        // by id (InMemoryPrecursorCatalog::new's own sort).
        let ids: Vec<&str> = generated
            .iter()
            .map(|gc| gc.candidate.id.0.as_str())
            .collect();
        assert_eq!(ids, vec!["BaCO3", "TiO2"]);
        assert!(
            generated
                .iter()
                .all(|gc| gc.generator == GeneratorId("catalog-exact"))
        );
        assert_eq!(generated[0].rank, 0);
        assert_eq!(generated[1].rank, 1);
    }

    #[test]
    fn frequency_prior_generator_filters_by_element_overlap_and_preserves_frequency_order() {
        let generator = FrequencyPriorGenerator::new(vec![
            (candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]), 5),
            (
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                50,
            ),
            // Irrelevant to the Ba-Ti-O target -- must be filtered out
            // regardless of its (highest) frequency.
            (candidate("NaCl", &[("Na", 1.0), ("Cl", 1.0)]), 1000),
        ]);

        let generated = generator
            .generate(&barium_titanate_target(), &no_constraints())
            .unwrap();

        let ids: Vec<&str> = generated
            .iter()
            .map(|gc| gc.candidate.id.0.as_str())
            .collect();
        assert_eq!(
            ids,
            vec!["BaCO3", "TiO2"],
            "higher frequency (50) must rank first"
        );
        assert!(
            generated
                .iter()
                .all(|gc| gc.generator == GeneratorId("frequency-prior"))
        );
        assert_eq!(generated[0].rank, 0);
        assert_eq!(generated[1].rank, 1);
    }

    #[test]
    fn thermodynamic_stability_generator_rejects_a_non_finite_formation_energy() {
        assert!(
            ThermodynamicStabilityGenerator::new(vec![(
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                f64::NAN,
            )])
            .is_err()
        );
        assert!(
            ThermodynamicStabilityGenerator::new(vec![(
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                f64::INFINITY,
            )])
            .is_err()
        );
        assert!(
            ThermodynamicStabilityGenerator::new(vec![(
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                -3.5,
            )])
            .is_ok()
        );
    }

    #[test]
    fn thermodynamic_stability_generator_filters_by_element_overlap_and_ranks_most_stable_first() {
        let generator = ThermodynamicStabilityGenerator::new(vec![
            (candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]), -3.0),
            (
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                -3.5,
            ),
            // Irrelevant to the Ba-Ti-O target -- must be filtered out
            // regardless of how stable it is.
            (candidate("NaCl", &[("Na", 1.0), ("Cl", 1.0)]), -10.0),
        ])
        .unwrap();

        let generated = generator
            .generate(&barium_titanate_target(), &no_constraints())
            .unwrap();

        let ids: Vec<&str> = generated
            .iter()
            .map(|gc| gc.candidate.id.0.as_str())
            .collect();
        assert_eq!(
            ids,
            vec!["BaCO3", "TiO2"],
            "more negative formation energy (-3.5) must rank first"
        );
        assert!(
            generated
                .iter()
                .all(|gc| gc.generator == GeneratorId("thermodynamic-stability"))
        );
        assert_eq!(generated[0].rank, 0);
        assert_eq!(generated[1].rank, 1);
    }

    #[test]
    fn ensemble_min_rank_fuses_candidates_proposed_by_either_generator() {
        // catalog-exact ranks BaCO3 (0), TiO2 (1) -- both sorted by id.
        let catalog_exact = CatalogExactGenerator::new(InMemoryPrecursorCatalog::new(vec![
            candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]),
            candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
        ]));
        // frequency-prior ranks TiO2 (0), BaCO3 (1) -- opposite order.
        let frequency_prior = FrequencyPriorGenerator::new(vec![
            (candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]), 100),
            (
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                1,
            ),
        ]);

        let ensemble = CandidateGeneratorEnsemble::new(vec![
            Box::new(catalog_exact),
            Box::new(frequency_prior),
        ]);
        let output =
            ensemble.generate_with_provenance(&barium_titanate_target(), &no_constraints());

        // Min-rank fusion: BaCO3's best rank is 0 (from catalog-exact),
        // TiO2's best rank is also 0 (from frequency-prior) -- tie broken
        // alphabetically by id.
        let ids: Vec<&str> = output.candidates.iter().map(|c| c.id.0.as_str()).collect();
        assert_eq!(ids, vec!["BaCO3", "TiO2"]);
        assert!(output.generator_errors.is_empty());

        // Both generators proposed both candidates -- provenance keeps
        // every one, nothing silently collapsed.
        assert_eq!(
            output.provenance[&PrecursorId("BaCO3".to_string())].len(),
            2
        );
        assert_eq!(output.provenance[&PrecursorId("TiO2".to_string())].len(), 2);
    }

    #[test]
    fn ensemble_fuses_a_third_generator_including_a_candidate_only_it_proposed() {
        let catalog_exact = CatalogExactGenerator::new(InMemoryPrecursorCatalog::new(vec![
            candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]),
            candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
        ]));
        let frequency_prior = FrequencyPriorGenerator::new(vec![
            (candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]), 100),
            (
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                1,
            ),
        ]);
        // Proposes BaCO3/TiO2 too, plus BaO -- a candidate neither of the
        // other two generators knows about at all.
        let thermodynamic_stability = ThermodynamicStabilityGenerator::new(vec![
            (candidate("TiO2", &[("Ti", 1.0), ("O", 2.0)]), -3.0),
            (
                candidate("BaCO3", &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)]),
                -3.5,
            ),
            (candidate("BaO", &[("Ba", 1.0), ("O", 1.0)]), -2.0),
        ])
        .unwrap();

        let ensemble = CandidateGeneratorEnsemble::new(vec![
            Box::new(catalog_exact),
            Box::new(frequency_prior),
            Box::new(thermodynamic_stability),
        ]);
        let output =
            ensemble.generate_with_provenance(&barium_titanate_target(), &no_constraints());

        let ids: std::collections::BTreeSet<&str> =
            output.candidates.iter().map(|c| c.id.0.as_str()).collect();
        assert_eq!(
            ids,
            std::collections::BTreeSet::from(["BaCO3", "TiO2", "BaO"]),
            "the union of all three generators' candidates, including the one only \
            thermodynamic-stability proposed"
        );
        assert!(output.generator_errors.is_empty());

        assert_eq!(
            output.provenance[&PrecursorId("BaCO3".to_string())].len(),
            3,
            "all three generators proposed BaCO3"
        );
        assert_eq!(
            output.provenance[&PrecursorId("TiO2".to_string())].len(),
            3,
            "all three generators proposed TiO2"
        );
        assert_eq!(
            output.provenance[&PrecursorId("BaO".to_string())].len(),
            1,
            "only thermodynamic-stability proposed BaO"
        );
    }

    #[test]
    fn ensemble_duplicate_id_conflict_keeps_first_generators_payload_but_records_every_proposer() {
        // Two generators proposing the same id with *different*
        // composition data (a malformed-input scenario, deliberately
        // constructed to test the conflict rule).
        let first = CatalogExactGenerator::new(InMemoryPrecursorCatalog::new(vec![candidate(
            "BaCO3",
            &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)],
        )]));
        let second = FrequencyPriorGenerator::new(vec![(
            candidate("BaCO3", &[("Ba", 2.0), ("C", 1.0), ("O", 3.0)]),
            10,
        )]);

        let ensemble = CandidateGeneratorEnsemble::new(vec![Box::new(first), Box::new(second)]);
        let output =
            ensemble.generate_with_provenance(&barium_titanate_target(), &no_constraints());

        assert_eq!(output.candidates.len(), 1);
        // First-generator-in-list (catalog-exact) wins the payload.
        assert_eq!(
            output.candidates[0].composition,
            composition(&[("Ba", 1.0), ("C", 1.0), ("O", 3.0)])
        );
        // But both proposals are still visible in provenance.
        assert_eq!(
            output.provenance[&PrecursorId("BaCO3".to_string())].len(),
            2
        );
    }

    #[test]
    fn ensemble_records_a_failed_generators_error_and_still_returns_the_others_candidates() {
        let catalog_exact =
            CatalogExactGenerator::new(InMemoryPrecursorCatalog::new(vec![candidate(
                "BaCO3",
                &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)],
            )]));

        let ensemble = CandidateGeneratorEnsemble::new(vec![
            Box::new(catalog_exact),
            Box::new(AlwaysFailsGenerator),
        ]);
        let output =
            ensemble.generate_with_provenance(&barium_titanate_target(), &no_constraints());

        assert_eq!(output.candidates.len(), 1);
        assert_eq!(output.candidates[0].id, PrecursorId("BaCO3".to_string()));
        assert_eq!(output.generator_errors.len(), 1);
        assert_eq!(output.generator_errors[0].0, GeneratorId("always-fails"));
    }

    #[test]
    fn ensemble_as_precursor_catalog_returns_the_same_candidates_as_generate_with_provenance() {
        let catalog_exact =
            CatalogExactGenerator::new(InMemoryPrecursorCatalog::new(vec![candidate(
                "BaCO3",
                &[("Ba", 1.0), ("C", 1.0), ("O", 3.0)],
            )]));
        let ensemble = CandidateGeneratorEnsemble::new(vec![Box::new(catalog_exact)]);

        let via_trait = PrecursorCatalog::candidates_for(
            &ensemble,
            &barium_titanate_target(),
            &no_constraints(),
        )
        .unwrap();
        let via_inherent =
            ensemble.generate_with_provenance(&barium_titanate_target(), &no_constraints());

        assert_eq!(via_trait, via_inherent.candidates);
    }
}