Skip to main content

gammalooprs/observables/
mod.rs

1use crate::model::{Model, ParticleGammaLoopExt};
2use crate::momentum::FourMomentum;
3use crate::settings::RuntimeSettings;
4use crate::utils::serde_utils::{
5    IsDefault, is_false, is_float, is_true, is_usize, show_defaults_helper,
6};
7use crate::utils::{F, FloatLike};
8use bincode_trait_derive::{Decode, Encode};
9use eyre::{Result, eyre};
10use schemars::JsonSchema;
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12use smallvec::{SmallVec, smallvec};
13use spenso::algebra::complex::Complex;
14use std::cmp::Ordering;
15use std::collections::{BTreeMap, BTreeSet};
16use std::fmt;
17use std::fs::File;
18use std::io::{BufReader, BufWriter, Write};
19use std::path::Path;
20use std::result::Result as StdResult;
21
22pub mod clustering;
23mod estimates;
24pub mod events;
25mod sample;
26pub use estimates::{
27    HistogramEstimates, IndependentEstimate, ObservableEstimateError, ObservableEstimates,
28};
29
30pub use sample::ObservableAccumulationError;
31
32pub use clustering::{ClusteringResult, Jet, JetAlgorithm, JetClustering};
33pub use events::{
34    AdditionalWeightKey, CutInfo, Event, EventGroup, EventGroupList, GenericAdditionalWeightInfo,
35    GenericEvent, GenericEventGroup, GenericEventGroupList,
36    GenericThresholdCountertermComponentWeight, GenericThresholdCountertermEventInfo,
37    ThresholdCountertermComponentOccurrence,
38};
39
40pub type QuantitiesSettings = BTreeMap<String, QuantitySettings>;
41pub type ObservablesSettings = BTreeMap<String, ObservableSettings>;
42pub type SelectorsSettings = BTreeMap<String, SelectorSettings>;
43
44#[derive(Debug, Clone, Default)]
45pub struct HistogramProcessInfo {
46    pub graph_names: Vec<String>,
47    pub graph_to_group_id: Vec<usize>,
48    pub graph_group_master_names: Vec<String>,
49    pub orientation_labels_by_group: Vec<Vec<String>>,
50    pub sampling_channel_labels_by_group: Vec<Vec<String>>,
51}
52
53#[derive(
54    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
55)]
56#[serde(rename_all = "snake_case")]
57pub enum EntrySelection {
58    #[default]
59    All,
60    LeadingOnly,
61    NthOnly,
62}
63
64#[derive(
65    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
66)]
67#[serde(rename_all = "snake_case")]
68pub enum SelectorReduction {
69    #[default]
70    AnyInRange,
71    AllInRange,
72}
73
74#[derive(
75    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
76)]
77#[serde(rename_all = "snake_case")]
78pub enum ObservableValueTransform {
79    #[default]
80    Identity,
81    Log10,
82}
83
84#[derive(
85    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
86)]
87#[serde(rename_all = "snake_case")]
88pub enum ObservablePhase {
89    #[default]
90    Real,
91    Imag,
92}
93
94#[derive(
95    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
96)]
97#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
98pub enum ObservableFileFormat {
99    #[serde(rename = "none")]
100    None,
101    #[serde(rename = "hwu", alias = "HwU")]
102    Hwu,
103    #[default]
104    #[serde(rename = "json")]
105    Json,
106}
107
108#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
109pub enum FilterQuantity {
110    #[serde(rename = "E")]
111    Energy,
112    #[serde(rename = "CosTheta")]
113    CosThetaP,
114    #[serde(rename = "PT")]
115    PT,
116    #[serde(rename = "y")]
117    Rapidity,
118    #[serde(rename = "eta")]
119    PseudoRapidity,
120    #[serde(rename = "Px")]
121    Px,
122    #[serde(rename = "Py")]
123    Py,
124    #[serde(rename = "Pz")]
125    Pz,
126    #[serde(rename = "Mass")]
127    Mass,
128}
129
130impl FilterQuantity {
131    pub(crate) fn setting_name(&self) -> &'static str {
132        match self {
133            FilterQuantity::Energy => "E",
134            FilterQuantity::CosThetaP => "CosTheta",
135            FilterQuantity::PT => "PT",
136            FilterQuantity::Rapidity => "y",
137            FilterQuantity::PseudoRapidity => "eta",
138            FilterQuantity::Px => "Px",
139            FilterQuantity::Py => "Py",
140            FilterQuantity::Pz => "Pz",
141            FilterQuantity::Mass => "Mass",
142        }
143    }
144
145    fn project_momentum<T: FloatLike>(
146        &self,
147        momentum: &FourMomentum<F<T>>,
148        incoming_beam: Option<&FourMomentum<F<T>>>,
149    ) -> Option<F<T>> {
150        match self {
151            FilterQuantity::Energy => Some(momentum.temporal.value.clone()),
152            FilterQuantity::CosThetaP => incoming_beam.map(|beam| {
153                let beam_spatial = beam.spatial.clone();
154                let momentum_spatial = momentum.spatial.clone();
155                beam_spatial.clone() * momentum_spatial.clone()
156                    / (beam_spatial.norm() * momentum_spatial.norm())
157            }),
158            FilterQuantity::PT => Some(momentum.pt()),
159            FilterQuantity::Rapidity => Some(momentum.rapidity()),
160            FilterQuantity::PseudoRapidity => Some(momentum.spatial.pseudo_rap()),
161            FilterQuantity::Px => Some(momentum.spatial.px.clone()),
162            FilterQuantity::Py => Some(momentum.spatial.py.clone()),
163            FilterQuantity::Pz => Some(momentum.spatial.pz.clone()),
164            FilterQuantity::Mass => Some(momentum.square().abs().sqrt()),
165        }
166    }
167}
168
169impl fmt::Display for FilterQuantity {
170    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
171        write!(f, "{}", self.setting_name())
172    }
173}
174
175#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
176pub enum QuantityOrdering {
177    #[serde(rename = "PT")]
178    PT,
179    #[serde(rename = "Energy")]
180    Energy,
181    #[serde(rename = "AbsRapidity")]
182    AbsRapidity,
183    #[serde(rename = "Quantity")]
184    Quantity,
185}
186
187impl QuantityOrdering {
188    pub(crate) fn setting_name(&self) -> &'static str {
189        match self {
190            QuantityOrdering::PT => "PT",
191            QuantityOrdering::Energy => "Energy",
192            QuantityOrdering::AbsRapidity => "AbsRapidity",
193            QuantityOrdering::Quantity => "Quantity",
194        }
195    }
196
197    fn scalar_sort_key<T: FloatLike>(
198        &self,
199        momentum: &FourMomentum<F<T>>,
200        quantity_value: &F<T>,
201    ) -> F<T> {
202        match self {
203            QuantityOrdering::PT => momentum.pt(),
204            QuantityOrdering::Energy => momentum.temporal.value.clone(),
205            QuantityOrdering::AbsRapidity => momentum.rapidity().abs(),
206            QuantityOrdering::Quantity => quantity_value.clone(),
207        }
208    }
209}
210
211impl fmt::Display for QuantityOrdering {
212    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
213        write!(f, "{}", self.setting_name())
214    }
215}
216
217#[derive(
218    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
219)]
220pub enum QuantityOrder {
221    #[serde(rename = "Ascending")]
222    Ascending,
223    #[default]
224    #[serde(rename = "Descending")]
225    Descending,
226}
227
228impl QuantityOrder {
229    pub(crate) fn setting_name(&self) -> &'static str {
230        match self {
231            QuantityOrder::Ascending => "Ascending",
232            QuantityOrder::Descending => "Descending",
233        }
234    }
235}
236
237impl fmt::Display for QuantityOrder {
238    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239        write!(f, "{}", self.setting_name())
240    }
241}
242
243#[derive(
244    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
245)]
246#[serde(rename_all = "snake_case")]
247pub enum QuantityComputation {
248    #[default]
249    Scalar,
250    Count,
251    Pair,
252}
253
254#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
255pub enum PairQuantity {
256    #[serde(rename = "DeltaR")]
257    DeltaR,
258}
259
260impl PairQuantity {
261    pub(crate) fn setting_name(&self) -> &'static str {
262        match self {
263            PairQuantity::DeltaR => "DeltaR",
264        }
265    }
266
267    fn project_momenta<T: FloatLike>(
268        &self,
269        left: &FourMomentum<F<T>>,
270        right: &FourMomentum<F<T>>,
271    ) -> F<T> {
272        match self {
273            PairQuantity::DeltaR => left.delta_r(right),
274        }
275    }
276}
277
278impl fmt::Display for PairQuantity {
279    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
280        write!(f, "{}", self.setting_name())
281    }
282}
283
284#[derive(
285    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
286)]
287#[serde(rename_all = "snake_case")]
288pub enum PairingMode {
289    #[default]
290    AllPairs,
291}
292
293impl PairingMode {
294    pub(crate) fn setting_name(&self) -> &'static str {
295        match self {
296            PairingMode::AllPairs => "all_pairs",
297        }
298    }
299}
300
301impl fmt::Display for PairingMode {
302    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
303        write!(f, "{}", self.setting_name())
304    }
305}
306
307fn filter_quantity_completion_example() -> FilterQuantity {
308    FilterQuantity::PT
309}
310
311fn pair_quantity_completion_example() -> PairQuantity {
312    PairQuantity::DeltaR
313}
314
315fn pairing_mode_completion_example() -> PairingMode {
316    PairingMode::AllPairs
317}
318
319fn quantity_ordering_completion_example() -> QuantityOrdering {
320    QuantityOrdering::Quantity
321}
322
323fn quantity_order_completion_example() -> QuantityOrder {
324    QuantityOrder::Descending
325}
326
327#[derive(Debug, Clone, Copy)]
328enum QuantitySourceKind {
329    Particle,
330    Jet,
331}
332
333impl QuantitySourceKind {
334    fn default_scalar_ordering(self) -> QuantityOrdering {
335        match self {
336            QuantitySourceKind::Particle => QuantityOrdering::Quantity,
337            QuantitySourceKind::Jet => QuantityOrdering::PT,
338        }
339    }
340}
341
342#[derive(Debug, Clone, Default, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
343#[allow(non_snake_case)]
344#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
345#[serde(default, deny_unknown_fields)]
346pub struct QuantityComputationSettings {
347    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
348    #[schemars(
349        description = "Quantity computation mode: scalar projection per object, exact object count, or pairwise quantity."
350    )]
351    pub computation: QuantityComputation,
352    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
353    #[schemars(
354        description = "Per-object scalar quantity used when computation = \"scalar\".",
355        example = filter_quantity_completion_example()
356    )]
357    pub quantity: Option<FilterQuantity>,
358    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
359    #[schemars(
360        description = "Pairwise quantity used when computation = \"pair\".",
361        example = pair_quantity_completion_example()
362    )]
363    pub pair_quantity: Option<PairQuantity>,
364    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
365    #[schemars(
366        description = "Pairing strategy used when computation = \"pair\".",
367        example = pairing_mode_completion_example()
368    )]
369    pub pairing: Option<PairingMode>,
370    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
371    #[schemars(
372        description = "Ordering key used before entry_selection. Particle scalar quantities default to Quantity, jet scalar quantities default to PT, and pair quantities default to Quantity.",
373        example = quantity_ordering_completion_example()
374    )]
375    pub ordering: Option<QuantityOrdering>,
376    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
377    #[schemars(
378        description = "Sorting direction applied together with ordering.",
379        example = quantity_order_completion_example()
380    )]
381    pub order: QuantityOrder,
382}
383
384impl QuantityComputationSettings {
385    pub fn scalar(quantity: FilterQuantity) -> Self {
386        Self {
387            computation: QuantityComputation::Scalar,
388            quantity: Some(quantity),
389            pair_quantity: None,
390            pairing: None,
391            ordering: None,
392            order: QuantityOrder::Descending,
393        }
394    }
395
396    fn try_normalized_for_source(&self, source: QuantitySourceKind) -> Result<Self> {
397        match self.computation {
398            QuantityComputation::Scalar => Ok(Self {
399                computation: QuantityComputation::Scalar,
400                quantity: Some(self.quantity.unwrap_or(FilterQuantity::PT)),
401                pair_quantity: None,
402                pairing: None,
403                ordering: Some(self.ordering.unwrap_or(source.default_scalar_ordering())),
404                order: self.order,
405            }),
406            QuantityComputation::Count => Ok(Self {
407                computation: QuantityComputation::Count,
408                quantity: None,
409                pair_quantity: None,
410                pairing: None,
411                ordering: None,
412                order: QuantityOrder::Descending,
413            }),
414            QuantityComputation::Pair => {
415                let ordering = self.ordering.unwrap_or(QuantityOrdering::Quantity);
416                if ordering != QuantityOrdering::Quantity {
417                    return Err(eyre!(
418                        "Pair quantities only support ordering=Quantity, got ordering={ordering}"
419                    ));
420                }
421
422                Ok(Self {
423                    computation: QuantityComputation::Pair,
424                    quantity: None,
425                    pair_quantity: Some(self.pair_quantity.unwrap_or(PairQuantity::DeltaR)),
426                    pairing: Some(self.pairing.unwrap_or_default()),
427                    ordering: Some(QuantityOrdering::Quantity),
428                    order: self.order,
429                })
430            }
431        }
432    }
433
434    fn resolve_for_source(
435        &self,
436        source: QuantitySourceKind,
437    ) -> Result<ResolvedQuantityComputation> {
438        let normalized = self.try_normalized_for_source(source)?;
439        match normalized.computation {
440            QuantityComputation::Scalar => Ok(ResolvedQuantityComputation::Scalar {
441                quantity: normalized.quantity.unwrap(),
442                ordering: normalized.ordering.unwrap(),
443                order: normalized.order,
444            }),
445            QuantityComputation::Count => Ok(ResolvedQuantityComputation::Count),
446            QuantityComputation::Pair => Ok(ResolvedQuantityComputation::Pair {
447                quantity: normalized.pair_quantity.unwrap(),
448                pairing: normalized.pairing.unwrap(),
449                order: normalized.order,
450            }),
451        }
452    }
453}
454
455#[derive(Debug, Clone, Default, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
456#[allow(non_snake_case)]
457#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
458#[serde(default, deny_unknown_fields)]
459pub struct JetClusteringSettings {
460    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
461    pub algorithm: JetAlgorithm,
462    #[serde(skip_serializing_if = "is_float::<0>")]
463    pub dR: f64,
464    #[serde(skip_serializing_if = "is_float::<0>")]
465    pub min_jpt: f64,
466    #[serde(skip_serializing_if = "IsDefault::is_default")]
467    #[schemars(
468        description = "Optional list of PDG IDs allowed to be clustered. Use null to derive the default from the model, or a compact list like [-1,1,21,82] in CLI key-value assignments.",
469        example = clustered_pdgs_completion_example()
470    )]
471    pub clustered_pdgs: Option<Vec<isize>>,
472}
473
474fn clustered_pdgs_completion_example() -> Option<Vec<isize>> {
475    Some(vec![-1, 1, 21, 82])
476}
477
478#[derive(Debug, Clone, PartialEq)]
479struct ResolvedJetClusteringSettings {
480    algorithm: JetAlgorithm,
481    d_r: f64,
482    min_jpt: f64,
483    clustered_pdgs: Vec<isize>,
484}
485
486impl JetClusteringSettings {
487    fn resolve(&self, model: Option<&Model>) -> Result<ResolvedJetClusteringSettings> {
488        if !self.min_jpt.is_finite() || self.min_jpt < 0.0 {
489            return Err(eyre!(
490                "minimum jet transverse momentum must be finite and nonnegative"
491            ));
492        }
493        Ok(ResolvedJetClusteringSettings {
494            algorithm: self.algorithm,
495            d_r: self.dR,
496            min_jpt: self.min_jpt,
497            clustered_pdgs: self.resolve_clustered_pdgs(model)?,
498        })
499    }
500
501    fn resolve_clustered_pdgs(&self, model: Option<&Model>) -> Result<Vec<isize>> {
502        let clustered_pdgs = match &self.clustered_pdgs {
503            Some(clustered_pdgs) => clustered_pdgs.clone(),
504            None => Self::default_clustered_pdgs(model.ok_or_else(|| {
505                eyre!(
506                    "Cannot resolve default clustered_pdgs without a model. Provide a model-aware event-processing runtime or set clustered_pdgs explicitly."
507                )
508            })?)?,
509        };
510        Ok(Self::normalize_clustered_pdgs(clustered_pdgs))
511    }
512
513    fn default_clustered_pdgs(model: &Model) -> Result<Vec<isize>> {
514        Ok(model
515            .particles()
516            .iter()
517            .filter(|particle| particle.is_qcd_charged())
518            .map(|particle| {
519                particle.has_zero_resolved_mass(model).map(|has_zero_mass| {
520                    has_zero_mass.then(|| {
521                        particle
522                            .pdg_code
523                            .try_into()
524                            .expect("PDG code must fit in an isize")
525                    })
526                })
527            })
528            .collect::<Result<Vec<_>>>()?
529            .into_iter()
530            .flatten()
531            .collect())
532    }
533
534    fn normalize_clustered_pdgs(mut clustered_pdgs: Vec<isize>) -> Vec<isize> {
535        clustered_pdgs.sort_unstable();
536        clustered_pdgs.dedup();
537        clustered_pdgs
538    }
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
542#[allow(non_snake_case)]
543#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
544#[serde(deny_unknown_fields)]
545pub struct ParticleQuantitySettings {
546    #[serde(skip_serializing_if = "IsDefault::is_default")]
547    pub pdgs: Vec<isize>,
548    #[serde(flatten)]
549    pub computation: QuantityComputationSettings,
550}
551
552impl ParticleQuantitySettings {
553    fn try_normalized(&self) -> Result<Self> {
554        Ok(Self {
555            pdgs: self.pdgs.clone(),
556            computation: self
557                .computation
558                .try_normalized_for_source(QuantitySourceKind::Particle)?,
559        })
560    }
561}
562
563#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
564#[allow(non_snake_case)]
565#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
566#[serde(deny_unknown_fields)]
567pub struct JetQuantitySettings {
568    #[serde(flatten)]
569    pub clustering: JetClusteringSettings,
570    #[serde(flatten)]
571    pub computation: QuantityComputationSettings,
572}
573
574impl JetQuantitySettings {
575    fn try_normalized(&self) -> Result<Self> {
576        Ok(Self {
577            clustering: self.clustering.clone(),
578            computation: self
579                .computation
580                .try_normalized_for_source(QuantitySourceKind::Jet)?,
581        })
582    }
583}
584
585#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
586#[allow(non_snake_case)]
587#[serde(tag = "type", rename_all = "snake_case")]
588#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
589pub enum QuantitySettings {
590    Particle(ParticleQuantitySettings),
591    Jet(JetQuantitySettings),
592    AFB {},
593    Integral {},
594    GraphId {},
595    GraphGroupId {},
596    OrientationId {},
597    SamplingChannelId {},
598}
599
600impl QuantitySettings {
601    pub fn try_normalized(&self) -> Result<Self> {
602        match self {
603            QuantitySettings::Particle(settings) => {
604                Ok(QuantitySettings::Particle(settings.try_normalized()?))
605            }
606            QuantitySettings::Jet(settings) => {
607                Ok(QuantitySettings::Jet(settings.try_normalized()?))
608            }
609            QuantitySettings::AFB {} => Ok(QuantitySettings::AFB {}),
610            QuantitySettings::Integral {} => Ok(QuantitySettings::Integral {}),
611            QuantitySettings::GraphId {} => Ok(QuantitySettings::GraphId {}),
612            QuantitySettings::GraphGroupId {} => Ok(QuantitySettings::GraphGroupId {}),
613            QuantitySettings::OrientationId {} => Ok(QuantitySettings::OrientationId {}),
614            QuantitySettings::SamplingChannelId {} => Ok(QuantitySettings::SamplingChannelId {}),
615        }
616    }
617
618    pub fn normalized(&self) -> Self {
619        self.try_normalized()
620            .expect("quantity settings should normalize successfully")
621    }
622}
623
624#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
625#[allow(non_snake_case)]
626#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
627#[serde(deny_unknown_fields)]
628pub struct ValueRangeSelectorSettings {
629    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
630    #[schemars(description = "Optional lower bound. Use null to disable the lower cut.")]
631    pub min: Option<f64>,
632    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
633    #[schemars(description = "Optional upper bound. Use null to disable the upper cut.")]
634    pub max: Option<f64>,
635    #[serde(default, skip_serializing_if = "is_default_selector_reduction")]
636    pub reduction: SelectorReduction,
637}
638
639#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
640#[allow(non_snake_case)]
641#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
642#[serde(deny_unknown_fields)]
643pub struct DiscreteRangeSelectorSettings {
644    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
645    #[schemars(description = "Optional inclusive lower bound. Use null to disable.")]
646    pub min: Option<isize>,
647    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
648    #[schemars(description = "Optional inclusive upper bound. Use null to disable.")]
649    pub max: Option<isize>,
650}
651
652#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
653#[allow(non_snake_case)]
654#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
655#[serde(deny_unknown_fields)]
656pub struct CountRangeSelectorSettings {
657    pub min_count: usize,
658    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
659    pub max_count: Option<usize>,
660}
661
662#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
663#[allow(non_snake_case)]
664#[serde(tag = "selector", rename_all = "snake_case")]
665#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
666pub enum SelectorDefinitionSettings {
667    ValueRange(ValueRangeSelectorSettings),
668    DiscreteRange(DiscreteRangeSelectorSettings),
669    CountRange(CountRangeSelectorSettings),
670}
671
672#[derive(Debug, Clone, Encode, Decode, PartialEq)]
673#[allow(non_snake_case)]
674#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
675pub struct SelectorSettings {
676    pub quantity: String,
677    pub active: bool,
678    pub entry_selection: EntrySelection,
679    pub entry_index: usize,
680    pub selector: SelectorDefinitionSettings,
681}
682
683#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
684#[serde(rename_all = "snake_case")]
685enum ValueRangeSelectorSerdeTag {
686    ValueRange,
687}
688
689#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
690#[serde(rename_all = "snake_case")]
691enum DiscreteRangeSelectorSerdeTag {
692    DiscreteRange,
693}
694
695#[derive(Debug, Clone, Copy, Serialize, Deserialize, JsonSchema)]
696#[serde(rename_all = "snake_case")]
697enum CountRangeSelectorSerdeTag {
698    CountRange,
699}
700
701#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
702#[serde(deny_unknown_fields)]
703struct ValueRangeSelectorSettingsSerde {
704    quantity: String,
705    #[serde(default = "default_true", skip_serializing_if = "is_true")]
706    active: bool,
707    #[serde(default, skip_serializing_if = "is_default_entry_selection")]
708    entry_selection: EntrySelection,
709    #[serde(default, skip_serializing_if = "is_default_entry_index")]
710    entry_index: usize,
711    selector: ValueRangeSelectorSerdeTag,
712    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
713    min: Option<f64>,
714    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
715    max: Option<f64>,
716    #[serde(default, skip_serializing_if = "is_default_selector_reduction")]
717    reduction: SelectorReduction,
718}
719
720#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
721#[serde(deny_unknown_fields)]
722struct DiscreteRangeSelectorSettingsSerde {
723    quantity: String,
724    #[serde(default = "default_true", skip_serializing_if = "is_true")]
725    active: bool,
726    #[serde(default, skip_serializing_if = "is_default_entry_selection")]
727    entry_selection: EntrySelection,
728    #[serde(default, skip_serializing_if = "is_default_entry_index")]
729    entry_index: usize,
730    selector: DiscreteRangeSelectorSerdeTag,
731    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
732    min: Option<isize>,
733    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
734    max: Option<isize>,
735}
736
737#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
738#[serde(deny_unknown_fields)]
739struct CountRangeSelectorSettingsSerde {
740    quantity: String,
741    #[serde(default = "default_true", skip_serializing_if = "is_true")]
742    active: bool,
743    #[serde(default, skip_serializing_if = "is_default_entry_selection")]
744    entry_selection: EntrySelection,
745    #[serde(default, skip_serializing_if = "is_default_entry_index")]
746    entry_index: usize,
747    selector: CountRangeSelectorSerdeTag,
748    min_count: usize,
749    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
750    max_count: Option<usize>,
751}
752
753#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
754#[allow(clippy::enum_variant_names)]
755#[serde(untagged)]
756enum SelectorSettingsSerde {
757    ValueRange(ValueRangeSelectorSettingsSerde),
758    DiscreteRange(DiscreteRangeSelectorSettingsSerde),
759    CountRange(CountRangeSelectorSettingsSerde),
760}
761
762impl JsonSchema for SelectorSettings {
763    fn schema_name() -> std::borrow::Cow<'static, str> {
764        "SelectorSettings".into()
765    }
766
767    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
768        <SelectorSettingsSerde as JsonSchema>::json_schema(generator)
769    }
770}
771
772impl Serialize for SelectorSettings {
773    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
774    where
775        S: Serializer,
776    {
777        match &self.selector {
778            SelectorDefinitionSettings::ValueRange(selector) => ValueRangeSelectorSettingsSerde {
779                quantity: self.quantity.clone(),
780                active: self.active,
781                entry_selection: self.entry_selection,
782                entry_index: self.entry_index,
783                selector: ValueRangeSelectorSerdeTag::ValueRange,
784                min: selector.min,
785                max: selector.max,
786                reduction: selector.reduction,
787            }
788            .serialize(serializer),
789            SelectorDefinitionSettings::DiscreteRange(selector) => {
790                DiscreteRangeSelectorSettingsSerde {
791                    quantity: self.quantity.clone(),
792                    active: self.active,
793                    entry_selection: self.entry_selection,
794                    entry_index: self.entry_index,
795                    selector: DiscreteRangeSelectorSerdeTag::DiscreteRange,
796                    min: selector.min,
797                    max: selector.max,
798                }
799                .serialize(serializer)
800            }
801            SelectorDefinitionSettings::CountRange(selector) => CountRangeSelectorSettingsSerde {
802                quantity: self.quantity.clone(),
803                active: self.active,
804                entry_selection: self.entry_selection,
805                entry_index: self.entry_index,
806                selector: CountRangeSelectorSerdeTag::CountRange,
807                min_count: selector.min_count,
808                max_count: selector.max_count,
809            }
810            .serialize(serializer),
811        }
812    }
813}
814
815impl<'de> Deserialize<'de> for SelectorSettings {
816    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
817    where
818        D: Deserializer<'de>,
819    {
820        let settings = SelectorSettingsSerde::deserialize(deserializer)?;
821        Ok(match settings {
822            SelectorSettingsSerde::ValueRange(settings) => SelectorSettings {
823                quantity: settings.quantity,
824                active: settings.active,
825                entry_selection: settings.entry_selection,
826                entry_index: settings.entry_index,
827                selector: SelectorDefinitionSettings::ValueRange(ValueRangeSelectorSettings {
828                    min: settings.min,
829                    max: settings.max,
830                    reduction: settings.reduction,
831                }),
832            },
833            SelectorSettingsSerde::DiscreteRange(settings) => SelectorSettings {
834                quantity: settings.quantity,
835                active: settings.active,
836                entry_selection: settings.entry_selection,
837                entry_index: settings.entry_index,
838                selector: SelectorDefinitionSettings::DiscreteRange(
839                    DiscreteRangeSelectorSettings {
840                        min: settings.min,
841                        max: settings.max,
842                    },
843                ),
844            },
845            SelectorSettingsSerde::CountRange(settings) => SelectorSettings {
846                quantity: settings.quantity,
847                active: settings.active,
848                entry_selection: settings.entry_selection,
849                entry_index: settings.entry_index,
850                selector: SelectorDefinitionSettings::CountRange(CountRangeSelectorSettings {
851                    min_count: settings.min_count,
852                    max_count: settings.max_count,
853                }),
854            },
855        })
856    }
857}
858
859#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
860#[allow(non_snake_case)]
861#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
862#[serde(default, deny_unknown_fields)]
863pub struct ContinuousHistogramSettings {
864    #[serde(skip_serializing_if = "is_float::<0>")]
865    pub x_min: f64,
866    #[serde(skip_serializing_if = "is_float::<0>")]
867    pub x_max: f64,
868    #[serde(skip_serializing_if = "is_usize::<0>")]
869    pub n_bins: usize,
870    #[serde(skip_serializing_if = "is_false")]
871    pub log_x_axis: bool,
872    #[serde(default = "default_true", skip_serializing_if = "is_true")]
873    pub log_y_axis: bool,
874    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
875    #[schemars(
876        description = "Optional histogram title. Defaults to the observable name when omitted."
877    )]
878    pub title: Option<String>,
879    #[serde(
880        default = "default_histogram_type_description",
881        skip_serializing_if = "is_default_histogram_type_description"
882    )]
883    #[schemars(description = "HwU TYPE description written after TYPE@ in the histogram header.")]
884    pub type_description: String,
885}
886
887impl Default for ContinuousHistogramSettings {
888    fn default() -> Self {
889        Self {
890            x_min: 0.0,
891            x_max: 0.0,
892            n_bins: 0,
893            log_x_axis: false,
894            log_y_axis: true,
895            title: None,
896            type_description: default_histogram_type_description(),
897        }
898    }
899}
900
901#[derive(
902    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
903)]
904#[serde(rename_all = "snake_case")]
905#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
906pub enum DiscreteBinOrdering {
907    #[default]
908    AscendingBinId,
909    ValueDescending,
910    AbsValueDescending,
911}
912
913impl DiscreteBinOrdering {
914    pub fn as_str(self) -> &'static str {
915        match self {
916            Self::AscendingBinId => "ascending_bin_id",
917            Self::ValueDescending => "value_descending",
918            Self::AbsValueDescending => "abs_value_descending",
919        }
920    }
921}
922
923#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
924#[allow(non_snake_case)]
925#[serde(tag = "type", rename_all = "snake_case")]
926pub enum DiscreteBinDomainSettings {
927    ExplicitRange { min: isize, max: isize },
928    SingleBin,
929    GraphIds,
930    GraphGroupIds,
931    OrientationIds,
932    SamplingChannelIds,
933}
934
935#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
936#[allow(non_snake_case)]
937#[serde(tag = "type", rename_all = "snake_case")]
938pub enum DiscreteBinLabelsSettings {
939    Custom { labels: Vec<String> },
940    BinId,
941    GraphName,
942    GraphGroupMasterName,
943    Orientation,
944    SamplingChannelEdgeIds,
945}
946
947#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
948#[allow(non_snake_case)]
949#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
950#[serde(default, deny_unknown_fields)]
951pub struct DiscreteHistogramSettings {
952    pub domain: DiscreteBinDomainSettings,
953    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
954    pub ordering: DiscreteBinOrdering,
955    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
956    pub labels: Option<DiscreteBinLabelsSettings>,
957    #[serde(default = "default_true", skip_serializing_if = "is_true")]
958    pub log_y_axis: bool,
959    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
960    #[schemars(
961        description = "Optional histogram title. Defaults to the observable name when omitted."
962    )]
963    pub title: Option<String>,
964    #[serde(
965        default = "default_histogram_type_description",
966        skip_serializing_if = "is_default_histogram_type_description"
967    )]
968    #[schemars(description = "HwU TYPE description written after TYPE@ in the histogram header.")]
969    pub type_description: String,
970}
971
972impl Default for DiscreteHistogramSettings {
973    fn default() -> Self {
974        Self {
975            domain: DiscreteBinDomainSettings::SingleBin,
976            ordering: DiscreteBinOrdering::AscendingBinId,
977            labels: None,
978            log_y_axis: true,
979            title: None,
980            type_description: default_histogram_type_description(),
981        }
982    }
983}
984
985#[derive(Debug, Clone, Serialize, Deserialize, Encode, Decode, PartialEq, JsonSchema)]
986#[allow(non_snake_case)]
987#[serde(tag = "kind", rename_all = "snake_case")]
988#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
989pub enum HistogramSettings {
990    Continuous(ContinuousHistogramSettings),
991    Discrete(DiscreteHistogramSettings),
992}
993
994impl Default for HistogramSettings {
995    fn default() -> Self {
996        Self::Continuous(ContinuousHistogramSettings::default())
997    }
998}
999
1000#[derive(Debug, Clone, Encode, Decode, PartialEq)]
1001#[allow(non_snake_case)]
1002#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
1003pub struct ObservableSettings {
1004    pub quantity: String,
1005    pub selections: Vec<String>,
1006    pub entry_selection: EntrySelection,
1007    pub entry_index: usize,
1008    pub value_transform: ObservableValueTransform,
1009    pub phase: ObservablePhase,
1010    pub misbinning_max_normalized_distance: Option<f64>,
1011    pub histogram: HistogramSettings,
1012}
1013
1014#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
1015#[serde(rename_all = "snake_case")]
1016enum HistogramKindSerde {
1017    #[default]
1018    Continuous,
1019    Discrete,
1020}
1021
1022#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
1023#[serde(deny_unknown_fields)]
1024struct ObservableSettingsSerde {
1025    quantity: String,
1026    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1027    selections: Vec<String>,
1028    #[serde(default, skip_serializing_if = "is_default_entry_selection")]
1029    entry_selection: EntrySelection,
1030    #[serde(default, skip_serializing_if = "is_default_entry_index")]
1031    entry_index: usize,
1032    #[serde(default, skip_serializing_if = "is_default_value_transform")]
1033    value_transform: ObservableValueTransform,
1034    #[serde(default, skip_serializing_if = "is_default_observable_phase")]
1035    phase: ObservablePhase,
1036    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1037    misbinning_max_normalized_distance: Option<f64>,
1038    #[serde(default)]
1039    kind: Option<HistogramKindSerde>,
1040    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1041    x_min: Option<f64>,
1042    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1043    x_max: Option<f64>,
1044    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1045    n_bins: Option<usize>,
1046    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1047    log_x_axis: Option<bool>,
1048    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1049    log_y_axis: Option<bool>,
1050    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1051    title: Option<String>,
1052    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1053    type_description: Option<String>,
1054    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1055    domain: Option<DiscreteBinDomainSettings>,
1056    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1057    ordering: Option<DiscreteBinOrdering>,
1058    #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1059    labels: Option<DiscreteBinLabelsSettings>,
1060}
1061
1062impl JsonSchema for ObservableSettings {
1063    fn schema_name() -> std::borrow::Cow<'static, str> {
1064        "ObservableSettings".into()
1065    }
1066
1067    fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
1068        <ObservableSettingsSerde as JsonSchema>::json_schema(generator)
1069    }
1070}
1071
1072impl Serialize for ObservableSettings {
1073    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1074    where
1075        S: Serializer,
1076    {
1077        let mut raw = ObservableSettingsSerde {
1078            quantity: self.quantity.clone(),
1079            selections: self.selections.clone(),
1080            entry_selection: self.entry_selection,
1081            entry_index: self.entry_index,
1082            value_transform: self.value_transform,
1083            phase: self.phase,
1084            misbinning_max_normalized_distance: self.misbinning_max_normalized_distance,
1085            kind: None,
1086            x_min: None,
1087            x_max: None,
1088            n_bins: None,
1089            log_x_axis: None,
1090            log_y_axis: None,
1091            title: None,
1092            type_description: None,
1093            domain: None,
1094            ordering: None,
1095            labels: None,
1096        };
1097        match &self.histogram {
1098            HistogramSettings::Continuous(histogram) => {
1099                raw.kind = Some(HistogramKindSerde::Continuous);
1100                raw.x_min = Some(histogram.x_min);
1101                raw.x_max = Some(histogram.x_max);
1102                raw.n_bins = Some(histogram.n_bins);
1103                raw.log_x_axis = Some(histogram.log_x_axis);
1104                raw.log_y_axis = Some(histogram.log_y_axis);
1105                raw.title = histogram.title.clone();
1106                raw.type_description = Some(histogram.type_description.clone());
1107            }
1108            HistogramSettings::Discrete(histogram) => {
1109                raw.kind = Some(HistogramKindSerde::Discrete);
1110                raw.log_y_axis = Some(histogram.log_y_axis);
1111                raw.title = histogram.title.clone();
1112                raw.type_description = Some(histogram.type_description.clone());
1113                raw.domain = Some(histogram.domain.clone());
1114                raw.ordering = Some(histogram.ordering);
1115                raw.labels = histogram.labels.clone();
1116            }
1117        }
1118        raw.serialize(serializer)
1119    }
1120}
1121
1122impl<'de> Deserialize<'de> for ObservableSettings {
1123    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1124    where
1125        D: Deserializer<'de>,
1126    {
1127        let raw = ObservableSettingsSerde::deserialize(deserializer)?;
1128        let inferred_kind = raw.kind.unwrap_or_else(|| {
1129            if raw.domain.is_some() || raw.ordering.is_some() || raw.labels.is_some() {
1130                HistogramKindSerde::Discrete
1131            } else {
1132                HistogramKindSerde::Continuous
1133            }
1134        });
1135        let histogram = match inferred_kind {
1136            HistogramKindSerde::Continuous => {
1137                if raw.domain.is_some() || raw.ordering.is_some() || raw.labels.is_some() {
1138                    return Err(serde::de::Error::custom(
1139                        "continuous observables cannot specify discrete histogram fields",
1140                    ));
1141                }
1142                HistogramSettings::Continuous(ContinuousHistogramSettings {
1143                    x_min: raw.x_min.unwrap_or_default(),
1144                    x_max: raw.x_max.unwrap_or_default(),
1145                    n_bins: raw.n_bins.unwrap_or_default(),
1146                    log_x_axis: raw.log_x_axis.unwrap_or(false),
1147                    log_y_axis: raw.log_y_axis.unwrap_or(true),
1148                    title: raw.title,
1149                    type_description: raw
1150                        .type_description
1151                        .unwrap_or_else(default_histogram_type_description),
1152                })
1153            }
1154            HistogramKindSerde::Discrete => {
1155                if raw.x_min.is_some()
1156                    || raw.x_max.is_some()
1157                    || raw.n_bins.is_some()
1158                    || raw.log_x_axis.is_some()
1159                {
1160                    return Err(serde::de::Error::custom(
1161                        "discrete observables cannot specify continuous histogram fields",
1162                    ));
1163                }
1164                HistogramSettings::Discrete(DiscreteHistogramSettings {
1165                    domain: raw.domain.unwrap_or(DiscreteBinDomainSettings::SingleBin),
1166                    ordering: raw.ordering.unwrap_or_default(),
1167                    labels: raw.labels,
1168                    log_y_axis: raw.log_y_axis.unwrap_or(true),
1169                    title: raw.title,
1170                    type_description: raw
1171                        .type_description
1172                        .unwrap_or_else(default_histogram_type_description),
1173                })
1174            }
1175        };
1176        Ok(ObservableSettings {
1177            quantity: raw.quantity,
1178            selections: raw.selections,
1179            entry_selection: raw.entry_selection,
1180            entry_index: raw.entry_index,
1181            value_transform: raw.value_transform,
1182            phase: raw.phase,
1183            misbinning_max_normalized_distance: raw.misbinning_max_normalized_distance,
1184            histogram,
1185        })
1186    }
1187}
1188
1189fn default_true() -> bool {
1190    true
1191}
1192
1193fn default_histogram_type_description() -> String {
1194    "AL".to_string()
1195}
1196
1197fn is_default_histogram_type_description(value: &String) -> bool {
1198    show_defaults_helper(value == &default_histogram_type_description())
1199}
1200
1201fn is_default_entry_selection(selection: &EntrySelection) -> bool {
1202    show_defaults_helper(selection == &EntrySelection::All)
1203}
1204
1205fn is_default_entry_index(index: &usize) -> bool {
1206    show_defaults_helper(*index == 0)
1207}
1208
1209fn is_default_selector_reduction(reduction: &SelectorReduction) -> bool {
1210    show_defaults_helper(reduction == &SelectorReduction::AnyInRange)
1211}
1212
1213fn is_default_value_transform(transform: &ObservableValueTransform) -> bool {
1214    show_defaults_helper(transform == &ObservableValueTransform::Identity)
1215}
1216
1217fn is_default_observable_phase(phase: &ObservablePhase) -> bool {
1218    show_defaults_helper(phase == &ObservablePhase::Real)
1219}
1220
1221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1222enum ObservableCoordinateKind {
1223    Continuous,
1224    Discrete,
1225}
1226
1227#[derive(Debug, Clone)]
1228pub enum ObservableCoordinate<T: FloatLike> {
1229    Continuous(F<T>),
1230    Discrete(isize),
1231}
1232
1233#[derive(Debug, Clone)]
1234pub struct ObservableEntry<T: FloatLike> {
1235    pub coordinate: ObservableCoordinate<T>,
1236    pub weight_modifier: Complex<F<T>>,
1237}
1238
1239impl<T: FloatLike> ObservableEntry<T> {
1240    fn unit_continuous(value: F<T>) -> Self {
1241        Self {
1242            weight_modifier: unit_complex(&value),
1243            coordinate: ObservableCoordinate::Continuous(value),
1244        }
1245    }
1246
1247    fn unit_discrete(bin_id: isize, reference: &F<T>) -> Self {
1248        Self {
1249            weight_modifier: unit_complex(reference),
1250            coordinate: ObservableCoordinate::Discrete(bin_id),
1251        }
1252    }
1253}
1254
1255type ObservableEntries<T> = SmallVec<[ObservableEntry<T>; 8]>;
1256
1257type ClusteringHandle = usize;
1258
1259#[derive(Debug, Clone)]
1260struct CompiledClustering {
1261    settings: ResolvedJetClusteringSettings,
1262    clustering: JetClustering,
1263}
1264
1265#[derive(Debug, Clone, Default)]
1266pub(crate) struct CompiledClusteringRegistry {
1267    entries: Vec<CompiledClustering>,
1268}
1269
1270impl CompiledClusteringRegistry {
1271    fn register(
1272        &mut self,
1273        settings: &JetClusteringSettings,
1274        model: Option<&Model>,
1275    ) -> Result<ClusteringHandle> {
1276        let resolved_settings = settings.resolve(model)?;
1277        if let Some(index) = self
1278            .entries
1279            .iter()
1280            .position(|entry| entry.settings == resolved_settings)
1281        {
1282            Ok(index)
1283        } else {
1284            let index = self.entries.len();
1285            self.entries.push(CompiledClustering {
1286                clustering: JetClustering::new(
1287                    resolved_settings.algorithm,
1288                    resolved_settings.d_r,
1289                    resolved_settings.min_jpt,
1290                    resolved_settings.clustered_pdgs.clone(),
1291                ),
1292                settings: resolved_settings,
1293            });
1294            Ok(index)
1295        }
1296    }
1297
1298    fn get(&self, handle: ClusteringHandle) -> &JetClustering {
1299        &self.entries[handle].clustering
1300    }
1301
1302    fn len(&self) -> usize {
1303        self.entries.len()
1304    }
1305}
1306
1307#[derive(Debug, Clone)]
1308#[allow(clippy::enum_variant_names)]
1309enum SelectorCriterion {
1310    ValueRange {
1311        selection: EntrySelection,
1312        entry_index: usize,
1313        reduction: SelectorReduction,
1314        min: Option<f64>,
1315        max: Option<f64>,
1316    },
1317    DiscreteRange {
1318        selection: EntrySelection,
1319        entry_index: usize,
1320        min: Option<isize>,
1321        max: Option<isize>,
1322    },
1323    CountRange {
1324        selection: EntrySelection,
1325        entry_index: usize,
1326        min: usize,
1327        max: Option<usize>,
1328    },
1329}
1330
1331impl SelectorCriterion {
1332    fn passes<T: FloatLike>(&self, entries: &[ObservableEntry<T>]) -> bool {
1333        match self {
1334            SelectorCriterion::ValueRange {
1335                selection,
1336                entry_index,
1337                reduction,
1338                min,
1339                max,
1340            } => {
1341                let selected = apply_entry_selection(entries, *selection, *entry_index);
1342                if selected.is_empty() {
1343                    return false;
1344                }
1345                match reduction {
1346                    SelectorReduction::AnyInRange => selected.iter().any(|entry| {
1347                        matches!(
1348                            &entry.coordinate,
1349                            ObservableCoordinate::Continuous(value)
1350                                if value_in_range(value.into_ff64().0, *min, *max)
1351                        )
1352                    }),
1353                    SelectorReduction::AllInRange => selected.iter().all(|entry| {
1354                        matches!(
1355                            &entry.coordinate,
1356                            ObservableCoordinate::Continuous(value)
1357                                if value_in_range(value.into_ff64().0, *min, *max)
1358                        )
1359                    }),
1360                }
1361            }
1362            SelectorCriterion::DiscreteRange {
1363                selection,
1364                entry_index,
1365                min,
1366                max,
1367            } => {
1368                let selected = apply_entry_selection(entries, *selection, *entry_index);
1369                if selected.is_empty() {
1370                    return false;
1371                }
1372                selected.iter().all(|entry| {
1373                    matches!(
1374                        &entry.coordinate,
1375                        ObservableCoordinate::Discrete(value)
1376                            if discrete_value_in_range(*value, *min, *max)
1377                    )
1378                })
1379            }
1380            SelectorCriterion::CountRange {
1381                selection,
1382                entry_index,
1383                min,
1384                max,
1385            } => {
1386                let count = apply_entry_selection(entries, *selection, *entry_index).len();
1387                count >= *min && max.is_none_or(|max| count <= max)
1388            }
1389        }
1390    }
1391}
1392
1393#[derive(Debug, Clone, Default)]
1394struct IntegralDefinition;
1395
1396impl IntegralDefinition {
1397    fn process_event<T: FloatLike>(&self, event: &GenericEvent<T>) -> ObservableEntries<T> {
1398        let reference = event.weight.re.clone();
1399        smallvec![ObservableEntry::unit_discrete(0, &reference)]
1400    }
1401}
1402
1403#[derive(Debug, Clone)]
1404enum ResolvedQuantityComputation {
1405    Scalar {
1406        quantity: FilterQuantity,
1407        ordering: QuantityOrdering,
1408        order: QuantityOrder,
1409    },
1410    Count,
1411    Pair {
1412        quantity: PairQuantity,
1413        pairing: PairingMode,
1414        order: QuantityOrder,
1415    },
1416}
1417
1418impl ResolvedQuantityComputation {
1419    fn coordinate_kind(&self) -> ObservableCoordinateKind {
1420        match self {
1421            ResolvedQuantityComputation::Scalar { .. }
1422            | ResolvedQuantityComputation::Pair { .. } => ObservableCoordinateKind::Continuous,
1423            ResolvedQuantityComputation::Count => ObservableCoordinateKind::Discrete,
1424        }
1425    }
1426
1427    fn process_momenta<T: FloatLike>(
1428        &self,
1429        momenta: &[&FourMomentum<F<T>>],
1430        incoming_beam: Option<&FourMomentum<F<T>>>,
1431        event: &GenericEvent<T>,
1432    ) -> ObservableEntries<T> {
1433        match self {
1434            ResolvedQuantityComputation::Scalar {
1435                quantity,
1436                ordering,
1437                order,
1438            } => {
1439                let mut entries = momenta
1440                    .iter()
1441                    .filter_map(|momentum| {
1442                        quantity
1443                            .project_momentum(momentum, incoming_beam)
1444                            .map(|value| SortableObservableEntry {
1445                                sort_key: ordering.scalar_sort_key(momentum, &value),
1446                                entry: ObservableEntry::unit_continuous(value),
1447                            })
1448                    })
1449                    .collect::<SmallVec<[SortableObservableEntry<T>; 8]>>();
1450                sort_observable_entries(&mut entries, *order);
1451                entries.into_iter().map(|entry| entry.entry).collect()
1452            }
1453            ResolvedQuantityComputation::Count => {
1454                let reference = event_representative_one(event);
1455                smallvec![ObservableEntry::unit_discrete(
1456                    momenta.len() as isize,
1457                    &reference,
1458                )]
1459            }
1460            ResolvedQuantityComputation::Pair {
1461                quantity,
1462                pairing,
1463                order,
1464            } => match pairing {
1465                PairingMode::AllPairs => {
1466                    let mut entries = SmallVec::<[SortableObservableEntry<T>; 8]>::new();
1467                    for left_index in 0..momenta.len() {
1468                        for right_index in left_index + 1..momenta.len() {
1469                            let value =
1470                                quantity.project_momenta(momenta[left_index], momenta[right_index]);
1471                            entries.push(SortableObservableEntry {
1472                                sort_key: value.clone(),
1473                                entry: ObservableEntry::unit_continuous(value),
1474                            });
1475                        }
1476                    }
1477                    sort_observable_entries(&mut entries, *order);
1478                    entries.into_iter().map(|entry| entry.entry).collect()
1479                }
1480            },
1481        }
1482    }
1483
1484    fn supports_misbinning_mitigation(&self) -> bool {
1485        !matches!(self, ResolvedQuantityComputation::Count)
1486    }
1487}
1488
1489#[derive(Debug, Clone)]
1490enum QuantitySourceDefinition {
1491    Particle { pdgs: Vec<isize> },
1492    Jet { clustering_handle: ClusteringHandle },
1493}
1494
1495impl QuantitySourceDefinition {
1496    fn required_clustering_handle(&self) -> Option<ClusteringHandle> {
1497        match self {
1498            QuantitySourceDefinition::Particle { .. } => None,
1499            QuantitySourceDefinition::Jet { clustering_handle } => Some(*clustering_handle),
1500        }
1501    }
1502
1503    fn collect_momenta<'a, T: FloatLike>(
1504        &self,
1505        event: &'a GenericEvent<T>,
1506    ) -> SmallVec<[&'a FourMomentum<F<T>>; 8]> {
1507        match self {
1508            QuantitySourceDefinition::Particle { pdgs } => event
1509                .cut_info
1510                .particle_pdgs
1511                .1
1512                .iter()
1513                .copied()
1514                .zip(event.kinematic_configuration.1.iter())
1515                .filter(|(pdg, _)| pdgs.contains(pdg))
1516                .map(|(_, momentum)| momentum)
1517                .collect(),
1518            QuantitySourceDefinition::Jet { clustering_handle } => event
1519                .cached_clustering(*clustering_handle)
1520                .expect("jet quantity requires precomputed clustering")
1521                .jets
1522                .iter()
1523                .map(|jet| &jet.momentum)
1524                .collect(),
1525        }
1526    }
1527}
1528
1529#[derive(Debug, Clone)]
1530struct ObjectQuantityDefinition {
1531    source: QuantitySourceDefinition,
1532    computation: ResolvedQuantityComputation,
1533}
1534
1535impl ObjectQuantityDefinition {
1536    fn particle(settings: &ParticleQuantitySettings) -> Result<Self> {
1537        Ok(Self {
1538            source: QuantitySourceDefinition::Particle {
1539                pdgs: settings.pdgs.clone(),
1540            },
1541            computation: settings
1542                .computation
1543                .resolve_for_source(QuantitySourceKind::Particle)?,
1544        })
1545    }
1546
1547    fn jet(
1548        settings: &JetQuantitySettings,
1549        clustering_registry: &mut CompiledClusteringRegistry,
1550        model: Option<&Model>,
1551    ) -> Result<Self> {
1552        Ok(Self {
1553            source: QuantitySourceDefinition::Jet {
1554                clustering_handle: clustering_registry.register(&settings.clustering, model)?,
1555            },
1556            computation: settings
1557                .computation
1558                .resolve_for_source(QuantitySourceKind::Jet)?,
1559        })
1560    }
1561
1562    fn process_event<T: FloatLike>(&self, event: &GenericEvent<T>) -> ObservableEntries<T> {
1563        let incoming_beam = event.kinematic_configuration.0.get(1);
1564        let momenta = self.source.collect_momenta(event);
1565        self.computation
1566            .process_momenta(&momenta, incoming_beam, event)
1567    }
1568
1569    fn required_clustering_handle(&self) -> Option<ClusteringHandle> {
1570        self.source.required_clustering_handle()
1571    }
1572
1573    fn supports_misbinning_mitigation(&self) -> bool {
1574        self.computation.supports_misbinning_mitigation()
1575    }
1576
1577    fn coordinate_kind(&self) -> ObservableCoordinateKind {
1578        self.computation.coordinate_kind()
1579    }
1580}
1581
1582#[derive(Debug, Clone, Copy)]
1583#[allow(clippy::enum_variant_names)]
1584enum MetadataQuantityKind {
1585    GraphId,
1586    GraphGroupId,
1587    OrientationID,
1588    SamplingChannelId,
1589}
1590
1591#[derive(Debug, Clone, Copy)]
1592struct MetadataQuantityDefinition {
1593    kind: MetadataQuantityKind,
1594}
1595
1596impl MetadataQuantityDefinition {
1597    fn process_event<T: FloatLike>(&self, event: &GenericEvent<T>) -> ObservableEntries<T> {
1598        let value = match self.kind {
1599            MetadataQuantityKind::GraphId => Some(event.cut_info.graph_id as isize),
1600            MetadataQuantityKind::GraphGroupId => {
1601                event.cut_info.graph_group_id.map(|id| id as isize)
1602            }
1603            MetadataQuantityKind::OrientationID => {
1604                event.cut_info.orientation_id.map(|id| id as isize)
1605            }
1606            MetadataQuantityKind::SamplingChannelId => {
1607                event.cut_info.sampling_channel_id.map(|id| id as isize)
1608            }
1609        };
1610        let Some(bin_id) = value else {
1611            return ObservableEntries::new();
1612        };
1613        let reference = event_representative_one(event);
1614        smallvec![ObservableEntry::unit_discrete(bin_id, &reference)]
1615    }
1616}
1617
1618#[derive(Debug, Clone, Default)]
1619struct ForwardBackwardDefinition;
1620
1621impl ForwardBackwardDefinition {
1622    fn process_event<T: FloatLike>(&self, event: &GenericEvent<T>) -> ObservableEntries<T> {
1623        let Some(beam) = event.kinematic_configuration.0.get(1).cloned() else {
1624            return ObservableEntries::new();
1625        };
1626
1627        let Some(outgoing) = event
1628            .cut_info
1629            .particle_pdgs
1630            .1
1631            .iter()
1632            .copied()
1633            .zip(event.kinematic_configuration.1.iter().cloned())
1634            .find(|(pdg, _)| (1..=6).contains(pdg))
1635            .map(|(_, momentum)| momentum)
1636        else {
1637            return ObservableEntries::new();
1638        };
1639
1640        let beam_spatial = beam.spatial.clone();
1641        let outgoing_spatial = outgoing.spatial.clone();
1642        smallvec![ObservableEntry::unit_continuous(
1643            beam_spatial.clone() * outgoing_spatial.clone()
1644                / (beam_spatial.norm() * outgoing_spatial.norm()),
1645        )]
1646    }
1647}
1648
1649#[derive(Debug, Clone)]
1650enum ObservableDefinition {
1651    Integral(IntegralDefinition),
1652    ObjectQuantity(ObjectQuantityDefinition),
1653    Metadata(MetadataQuantityDefinition),
1654    ForwardBackward(ForwardBackwardDefinition),
1655}
1656
1657impl ObservableDefinition {
1658    fn from_settings(
1659        settings: &QuantitySettings,
1660        clustering_registry: &mut CompiledClusteringRegistry,
1661        model: Option<&Model>,
1662    ) -> Result<Self> {
1663        Ok(match settings {
1664            QuantitySettings::Particle(settings) => {
1665                ObservableDefinition::ObjectQuantity(ObjectQuantityDefinition::particle(settings)?)
1666            }
1667            QuantitySettings::Jet(settings) => ObservableDefinition::ObjectQuantity(
1668                ObjectQuantityDefinition::jet(settings, clustering_registry, model)?,
1669            ),
1670            QuantitySettings::AFB {} => {
1671                ObservableDefinition::ForwardBackward(ForwardBackwardDefinition)
1672            }
1673            QuantitySettings::Integral {} => ObservableDefinition::Integral(IntegralDefinition),
1674            QuantitySettings::GraphId {} => {
1675                ObservableDefinition::Metadata(MetadataQuantityDefinition {
1676                    kind: MetadataQuantityKind::GraphId,
1677                })
1678            }
1679            QuantitySettings::GraphGroupId {} => {
1680                ObservableDefinition::Metadata(MetadataQuantityDefinition {
1681                    kind: MetadataQuantityKind::GraphGroupId,
1682                })
1683            }
1684            QuantitySettings::OrientationId {} => {
1685                ObservableDefinition::Metadata(MetadataQuantityDefinition {
1686                    kind: MetadataQuantityKind::OrientationID,
1687                })
1688            }
1689            QuantitySettings::SamplingChannelId {} => {
1690                ObservableDefinition::Metadata(MetadataQuantityDefinition {
1691                    kind: MetadataQuantityKind::SamplingChannelId,
1692                })
1693            }
1694        })
1695    }
1696
1697    fn process_event<T: FloatLike>(&self, event: &GenericEvent<T>) -> ObservableEntries<T> {
1698        match self {
1699            ObservableDefinition::Integral(definition) => definition.process_event(event),
1700            ObservableDefinition::ObjectQuantity(definition) => definition.process_event(event),
1701            ObservableDefinition::Metadata(definition) => definition.process_event(event),
1702            ObservableDefinition::ForwardBackward(definition) => definition.process_event(event),
1703        }
1704    }
1705
1706    fn required_clustering_handle(&self) -> Option<ClusteringHandle> {
1707        match self {
1708            ObservableDefinition::ObjectQuantity(definition) => {
1709                definition.required_clustering_handle()
1710            }
1711            _ => None,
1712        }
1713    }
1714
1715    fn supports_misbinning_mitigation(&self) -> bool {
1716        match self {
1717            ObservableDefinition::ObjectQuantity(definition) => {
1718                definition.supports_misbinning_mitigation()
1719            }
1720            ObservableDefinition::Integral(_) | ObservableDefinition::Metadata(_) => false,
1721            ObservableDefinition::ForwardBackward(_) => true,
1722        }
1723    }
1724
1725    fn coordinate_kind(&self) -> ObservableCoordinateKind {
1726        match self {
1727            ObservableDefinition::Integral(_) | ObservableDefinition::Metadata(_) => {
1728                ObservableCoordinateKind::Discrete
1729            }
1730            ObservableDefinition::ObjectQuantity(definition) => definition.coordinate_kind(),
1731            ObservableDefinition::ForwardBackward(_) => ObservableCoordinateKind::Continuous,
1732        }
1733    }
1734}
1735
1736fn event_representative_one<T: FloatLike>(event: &GenericEvent<T>) -> F<T> {
1737    event
1738        .kinematic_configuration
1739        .0
1740        .first()
1741        .map(|momentum| momentum.temporal.value.one())
1742        .or_else(|| {
1743            event
1744                .kinematic_configuration
1745                .1
1746                .first()
1747                .map(|momentum| momentum.temporal.value.one())
1748        })
1749        .unwrap_or_else(|| event.weight.re.one())
1750}
1751
1752#[derive(Debug, Clone)]
1753struct SortableObservableEntry<T: FloatLike> {
1754    sort_key: F<T>,
1755    entry: ObservableEntry<T>,
1756}
1757
1758fn sort_observable_entries<T: FloatLike>(
1759    entries: &mut SmallVec<[SortableObservableEntry<T>; 8]>,
1760    order: QuantityOrder,
1761) {
1762    entries.sort_by(|lhs, rhs| compare_sort_keys(&lhs.sort_key, &rhs.sort_key, order));
1763}
1764
1765fn compare_sort_keys<T: FloatLike>(lhs: &F<T>, rhs: &F<T>, order: QuantityOrder) -> Ordering {
1766    let base = lhs.partial_cmp(rhs).unwrap_or(Ordering::Equal);
1767    match order {
1768        QuantityOrder::Ascending => base,
1769        QuantityOrder::Descending => base.reverse(),
1770    }
1771}
1772
1773fn ensure_event_clustering<T: FloatLike>(
1774    event: &mut GenericEvent<T>,
1775    clustering_handle: ClusteringHandle,
1776    clustering_registry: &CompiledClusteringRegistry,
1777) {
1778    event.ensure_clustering_slots(clustering_registry.len());
1779    if event.cached_clustering(clustering_handle).is_some() {
1780        return;
1781    }
1782
1783    let clustering = clustering_registry.get(clustering_handle).clone();
1784    let clustering_result = clustering.process_event(&*event);
1785    event.derived_observable_data.clustered_jets[clustering_handle] = Some(clustering_result);
1786}
1787
1788#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
1789pub struct ObservableBinAccumulator {
1790    pub sum_weights: f64,
1791    new_sum_weights: f64,
1792    pub sum_weights_squared: f64,
1793    new_sum_weights_squared: f64,
1794    pub entry_count: usize,
1795    new_entry_count: usize,
1796    pub mitigated_fill_count: usize,
1797    new_mitigated_fill_count: usize,
1798}
1799
1800impl ObservableBinAccumulator {
1801    fn add_sample(&mut self, sample: f64, entry_count: usize, mitigated_fill_count: usize) {
1802        self.new_sum_weights += sample;
1803        self.new_sum_weights_squared += sample * sample;
1804        self.new_entry_count += entry_count;
1805        self.new_mitigated_fill_count += mitigated_fill_count;
1806    }
1807
1808    fn merge_samples(&mut self, other: &mut ObservableBinAccumulator) {
1809        self.new_sum_weights += other.new_sum_weights;
1810        self.new_sum_weights_squared += other.new_sum_weights_squared;
1811        self.new_entry_count += other.new_entry_count;
1812        self.new_mitigated_fill_count += other.new_mitigated_fill_count;
1813
1814        other.new_sum_weights = 0.0;
1815        other.new_sum_weights_squared = 0.0;
1816        other.new_entry_count = 0;
1817        other.new_mitigated_fill_count = 0;
1818    }
1819
1820    fn total_sum_weights(&self) -> f64 {
1821        self.sum_weights + self.new_sum_weights
1822    }
1823
1824    fn total_sum_weights_squared(&self) -> f64 {
1825        self.sum_weights_squared + self.new_sum_weights_squared
1826    }
1827
1828    fn total_entry_count(&self) -> usize {
1829        self.entry_count + self.new_entry_count
1830    }
1831
1832    fn total_mitigated_fill_count(&self) -> usize {
1833        self.mitigated_fill_count + self.new_mitigated_fill_count
1834    }
1835
1836    fn average(&self, sample_count: usize) -> f64 {
1837        if sample_count == 0 {
1838            0.0
1839        } else {
1840            self.total_sum_weights() / sample_count as f64
1841        }
1842    }
1843
1844    fn error(&self, sample_count: usize) -> f64 {
1845        if sample_count <= 1 {
1846            return 0.0;
1847        }
1848
1849        let n = sample_count as f64;
1850        let sum = self.total_sum_weights();
1851        let sum_sq = self.total_sum_weights_squared();
1852        let variance_numerator = sum_sq - (sum * sum) / n;
1853        if !variance_numerator.is_finite() || variance_numerator <= 0.0 {
1854            0.0
1855        } else {
1856            (variance_numerator / (n * (n - 1.0))).sqrt()
1857        }
1858    }
1859
1860    fn update_iter(&mut self) {
1861        self.sum_weights += self.new_sum_weights;
1862        self.sum_weights_squared += self.new_sum_weights_squared;
1863        self.entry_count += self.new_entry_count;
1864        self.mitigated_fill_count += self.new_mitigated_fill_count;
1865
1866        self.new_sum_weights = 0.0;
1867        self.new_sum_weights_squared = 0.0;
1868        self.new_entry_count = 0;
1869        self.new_mitigated_fill_count = 0;
1870    }
1871
1872    fn rescale(&mut self, factor: f64) {
1873        self.sum_weights *= factor;
1874        self.new_sum_weights *= factor;
1875        self.sum_weights_squared *= factor * factor;
1876        self.new_sum_weights_squared *= factor * factor;
1877    }
1878
1879    fn from_snapshot(snapshot: &HistogramBinSnapshot) -> Self {
1880        Self {
1881            sum_weights: snapshot.sum_weights,
1882            new_sum_weights: 0.0,
1883            sum_weights_squared: snapshot.sum_weights_squared,
1884            new_sum_weights_squared: 0.0,
1885            entry_count: snapshot.entry_count,
1886            new_entry_count: 0,
1887            mitigated_fill_count: snapshot.mitigated_fill_count,
1888            new_mitigated_fill_count: 0,
1889        }
1890    }
1891}
1892
1893#[derive(Debug, Clone, Default, Serialize, Deserialize)]
1894pub struct ObservableHistogramStatistics {
1895    pub in_range_entry_count: usize,
1896    pub nan_value_count: usize,
1897    pub mitigated_pair_count: usize,
1898    new_in_range_entry_count: usize,
1899    new_nan_value_count: usize,
1900    new_mitigated_pair_count: usize,
1901}
1902
1903impl ObservableHistogramStatistics {
1904    fn register_in_range_entry(&mut self) {
1905        self.new_in_range_entry_count += 1;
1906    }
1907
1908    fn register_nan(&mut self) {
1909        self.new_nan_value_count += 1;
1910    }
1911
1912    fn register_mitigated_pair(&mut self) {
1913        self.new_mitigated_pair_count += 1;
1914    }
1915
1916    fn merge_samples(&mut self, other: &mut ObservableHistogramStatistics) {
1917        self.new_in_range_entry_count += other.new_in_range_entry_count;
1918        self.new_nan_value_count += other.new_nan_value_count;
1919        self.new_mitigated_pair_count += other.new_mitigated_pair_count;
1920
1921        other.new_in_range_entry_count = 0;
1922        other.new_nan_value_count = 0;
1923        other.new_mitigated_pair_count = 0;
1924    }
1925
1926    fn update_iter(&mut self) {
1927        self.in_range_entry_count += self.new_in_range_entry_count;
1928        self.nan_value_count += self.new_nan_value_count;
1929        self.mitigated_pair_count += self.new_mitigated_pair_count;
1930
1931        self.new_in_range_entry_count = 0;
1932        self.new_nan_value_count = 0;
1933        self.new_mitigated_pair_count = 0;
1934    }
1935}
1936
1937#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1938pub struct HistogramBinSnapshot {
1939    pub x_min: Option<f64>,
1940    pub x_max: Option<f64>,
1941    pub bin_id: Option<isize>,
1942    pub label: Option<String>,
1943    pub entry_count: usize,
1944    pub sum_weights: f64,
1945    pub sum_weights_squared: f64,
1946    pub mitigated_fill_count: usize,
1947}
1948
1949impl HistogramBinSnapshot {
1950    pub fn average(&self, sample_count: usize) -> f64 {
1951        if sample_count == 0 {
1952            0.0
1953        } else {
1954            self.sum_weights / sample_count as f64
1955        }
1956    }
1957
1958    pub fn error(&self, sample_count: usize) -> f64 {
1959        if sample_count <= 1 {
1960            return 0.0;
1961        }
1962
1963        let n = sample_count as f64;
1964        let variance_numerator =
1965            self.sum_weights_squared - (self.sum_weights * self.sum_weights) / n;
1966        if !variance_numerator.is_finite() || variance_numerator <= 0.0 {
1967            0.0
1968        } else {
1969            (variance_numerator / (n * (n - 1.0))).sqrt()
1970        }
1971    }
1972
1973    fn merge_in_place(&mut self, other: &HistogramBinSnapshot) {
1974        self.entry_count += other.entry_count;
1975        self.sum_weights += other.sum_weights;
1976        self.sum_weights_squared += other.sum_weights_squared;
1977        self.mitigated_fill_count += other.mitigated_fill_count;
1978    }
1979
1980    fn rescale_in_place(&mut self, factor: f64) {
1981        self.sum_weights *= factor;
1982        self.sum_weights_squared *= factor * factor;
1983    }
1984}
1985
1986#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
1987pub struct HistogramStatisticsSnapshot {
1988    pub in_range_entry_count: usize,
1989    pub nan_value_count: usize,
1990    pub mitigated_pair_count: usize,
1991}
1992
1993#[derive(
1994    Debug, Clone, Copy, Default, Serialize, Deserialize, Encode, Decode, PartialEq, Eq, JsonSchema,
1995)]
1996#[serde(rename_all = "snake_case")]
1997pub enum HistogramSnapshotKind {
1998    #[default]
1999    Continuous,
2000    Discrete,
2001}
2002
2003#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
2004pub struct HistogramSnapshot {
2005    /// Determines whether bins represent continuous ranges or discrete identifiers.
2006    pub kind: HistogramSnapshotKind,
2007    /// Human-readable histogram title used by JSON and HwU output.
2008    pub title: String,
2009    /// HwU `TYPE@` description retained with the histogram metadata.
2010    pub type_description: String,
2011    /// Real or imaginary component of the complex event weight accumulated in this histogram.
2012    pub phase: ObservablePhase,
2013    /// Transformation applied to observable coordinates before continuous binning.
2014    pub value_transform: ObservableValueTransform,
2015    /// Whether the observable supports paired fills that mitigate boundary misbinning.
2016    pub supports_misbinning_mitigation: bool,
2017    /// Lower bound of a continuous histogram, or `None` for a discrete histogram.
2018    pub x_min: Option<f64>,
2019    /// Upper bound of a continuous histogram, or `None` for a discrete histogram.
2020    pub x_max: Option<f64>,
2021    /// Number of statistically independent Monte Carlo samples represented by the snapshot.
2022    pub sample_count: usize,
2023    /// Whether compatible renderers should display the horizontal axis logarithmically.
2024    pub log_x_axis: bool,
2025    /// Whether compatible renderers should display the vertical axis logarithmically.
2026    pub log_y_axis: bool,
2027    /// Smallest discrete bin identifier, or `None` for a continuous histogram.
2028    pub discrete_min_bin_id: Option<isize>,
2029    /// Display ordering for discrete bins, or `None` for a continuous histogram.
2030    pub discrete_ordering: Option<DiscreteBinOrdering>,
2031    /// Raw statistics for every in-range bin.
2032    pub bins: Vec<HistogramBinSnapshot>,
2033    /// Raw statistics for entries below the configured histogram range.
2034    pub underflow_bin: HistogramBinSnapshot,
2035    /// Raw statistics for entries above the configured histogram range.
2036    pub overflow_bin: HistogramBinSnapshot,
2037    /// Histogram-wide entry, non-finite-value, and mitigation counters.
2038    pub statistics: HistogramStatisticsSnapshot,
2039}
2040
2041#[derive(Clone, Copy, Debug, PartialEq)]
2042pub enum HistogramMedianPosition {
2043    Underflow,
2044    InRange(f64),
2045    Overflow,
2046}
2047
2048impl HistogramSnapshot {
2049    pub fn to_json_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
2050        let writer = BufWriter::new(File::create(path.as_ref())?);
2051        serde_json::to_writer_pretty(writer, self)?;
2052        Ok(())
2053    }
2054
2055    pub fn from_json_file<P: AsRef<Path>>(path: P) -> Result<Self> {
2056        let reader = BufReader::new(File::open(path.as_ref())?);
2057        Ok(serde_json::from_reader(reader)?)
2058    }
2059
2060    fn write_hwu_block<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
2061        let x_axis_mode = if self.log_x_axis { "LOG" } else { "LIN" };
2062        let y_axis_mode = if self.log_y_axis { "LOG" } else { "LIN" };
2063
2064        writeln!(writer, "##& xmin & xmax & central value & dy &\n")?;
2065        writeln!(
2066            writer,
2067            "<histogram> {} \"{} |X_AXIS@{} |Y_AXIS@{} |TYPE@{}\"",
2068            self.bins.len(),
2069            self.title,
2070            x_axis_mode,
2071            y_axis_mode,
2072            self.type_description,
2073        )?;
2074
2075        for bin in &self.bins {
2076            let (x_min, x_max) = match self.kind {
2077                HistogramSnapshotKind::Continuous => (
2078                    bin.x_min.unwrap_or(self.x_min.unwrap_or_default()),
2079                    bin.x_max.unwrap_or(self.x_max.unwrap_or_default()),
2080                ),
2081                HistogramSnapshotKind::Discrete => {
2082                    let bin_id = bin.bin_id.expect("discrete histogram bin missing bin id");
2083                    (bin_id as f64, (bin_id + 1) as f64)
2084                }
2085            };
2086            writeln!(
2087                writer,
2088                "  {:.8e}   {:.8e}   {:.8e}   {:.8e}",
2089                x_min,
2090                x_max,
2091                bin.average(self.sample_count),
2092                bin.error(self.sample_count),
2093            )?;
2094        }
2095
2096        writeln!(writer, "<\\histogram>")?;
2097        Ok(())
2098    }
2099
2100    pub fn merge(&self, other: &HistogramSnapshot) -> Result<Self> {
2101        let mut merged = self.clone();
2102        merged.merge_in_place(other)?;
2103        Ok(merged)
2104    }
2105
2106    pub fn merged(&self, other: &HistogramSnapshot) -> Result<Self> {
2107        self.merge(other)
2108    }
2109
2110    fn has_compatible_layout(&self, other: &Self) -> bool {
2111        if self.title != other.title
2112            || self.type_description != other.type_description
2113            || self.phase != other.phase
2114            || self.value_transform != other.value_transform
2115            || self.supports_misbinning_mitigation != other.supports_misbinning_mitigation
2116            || self.kind != other.kind
2117            || self.x_min != other.x_min
2118            || self.x_max != other.x_max
2119            || self.log_x_axis != other.log_x_axis
2120            || self.log_y_axis != other.log_y_axis
2121            || self.discrete_min_bin_id != other.discrete_min_bin_id
2122            || self.bins.len() != other.bins.len()
2123        {
2124            return false;
2125        }
2126        match self.kind {
2127            HistogramSnapshotKind::Continuous => self
2128                .bins
2129                .iter()
2130                .zip(&other.bins)
2131                .all(|(left, right)| left.x_min == right.x_min && left.x_max == right.x_max),
2132            HistogramSnapshotKind::Discrete => {
2133                let left = self
2134                    .bins
2135                    .iter()
2136                    .filter_map(|bin| bin.bin_id)
2137                    .collect::<BTreeSet<_>>();
2138                let right = other
2139                    .bins
2140                    .iter()
2141                    .filter_map(|bin| bin.bin_id)
2142                    .collect::<BTreeSet<_>>();
2143                left.len() == self.bins.len() && right.len() == other.bins.len() && left == right
2144            }
2145        }
2146    }
2147
2148    pub fn merge_in_place(&mut self, other: &HistogramSnapshot) -> Result<()> {
2149        if !self.has_compatible_layout(other) {
2150            return Err(eyre!(
2151                "Cannot merge incompatible histogram snapshots '{}'",
2152                self.title
2153            ));
2154        }
2155
2156        self.sample_count += other.sample_count;
2157        if self.kind == HistogramSnapshotKind::Continuous {
2158            for (bin, other_bin) in self.bins.iter_mut().zip(other.bins.iter()) {
2159                bin.merge_in_place(other_bin);
2160            }
2161        } else {
2162            let other_by_id = other
2163                .bins
2164                .iter()
2165                .filter_map(|bin| bin.bin_id.map(|bin_id| (bin_id, bin)))
2166                .collect::<BTreeMap<_, _>>();
2167            for bin in &mut self.bins {
2168                let bin_id = bin.bin_id.ok_or_else(|| {
2169                    eyre!(
2170                        "Discrete histogram snapshot '{}' contains a bin without bin_id",
2171                        self.title
2172                    )
2173                })?;
2174                let other_bin = other_by_id.get(&bin_id).ok_or_else(|| {
2175                    eyre!(
2176                        "Cannot merge discrete histogram snapshot '{}' because bin_id {} is missing",
2177                        self.title,
2178                        bin_id
2179                    )
2180                })?;
2181                bin.merge_in_place(other_bin);
2182            }
2183        }
2184        self.underflow_bin.merge_in_place(&other.underflow_bin);
2185        self.overflow_bin.merge_in_place(&other.overflow_bin);
2186        self.statistics.in_range_entry_count += other.statistics.in_range_entry_count;
2187        self.statistics.nan_value_count += other.statistics.nan_value_count;
2188        self.statistics.mitigated_pair_count += other.statistics.mitigated_pair_count;
2189        Ok(())
2190    }
2191
2192    pub fn rescale(&mut self, factor: f64) {
2193        for bin in &mut self.bins {
2194            bin.rescale_in_place(factor);
2195        }
2196        self.underflow_bin.rescale_in_place(factor);
2197        self.overflow_bin.rescale_in_place(factor);
2198    }
2199
2200    pub fn rescaled(&self, factor: f64) -> Self {
2201        let mut scaled = self.clone();
2202        scaled.rescale(factor);
2203        scaled
2204    }
2205
2206    pub fn approximate_weighted_median_position(&self) -> Option<HistogramMedianPosition> {
2207        if self.kind != HistogramSnapshotKind::Continuous {
2208            return None;
2209        }
2210
2211        let positive_weight = |bin: &HistogramBinSnapshot| bin.sum_weights.max(0.0);
2212        let total_weight = positive_weight(&self.underflow_bin)
2213            + self.bins.iter().map(positive_weight).sum::<f64>()
2214            + positive_weight(&self.overflow_bin);
2215        if total_weight <= 0.0 {
2216            return None;
2217        }
2218
2219        let target = 0.5 * total_weight;
2220        let mut cumulative = positive_weight(&self.underflow_bin);
2221        if cumulative >= target {
2222            return Some(HistogramMedianPosition::Underflow);
2223        }
2224
2225        for bin in &self.bins {
2226            cumulative += positive_weight(bin);
2227            if cumulative >= target {
2228                let x_min = bin.x_min.or(self.x_min)?;
2229                let x_max = bin.x_max.or(self.x_max)?;
2230                return Some(HistogramMedianPosition::InRange(0.5 * (x_min + x_max)));
2231            }
2232        }
2233
2234        Some(HistogramMedianPosition::Overflow)
2235    }
2236
2237    pub fn change_bin_ordering(&mut self, ordering: DiscreteBinOrdering) -> Result<()> {
2238        if self.kind != HistogramSnapshotKind::Discrete {
2239            return Err(eyre!(
2240                "Cannot change bin ordering on continuous histogram '{}'",
2241                self.title
2242            ));
2243        }
2244        self.discrete_ordering = Some(ordering);
2245        sort_discrete_snapshot_bins(&mut self.bins, ordering, self.sample_count);
2246        Ok(())
2247    }
2248
2249    pub fn changed_bin_ordering(&self, ordering: DiscreteBinOrdering) -> Result<Self> {
2250        let mut reordered = self.clone();
2251        reordered.change_bin_ordering(ordering)?;
2252        Ok(reordered)
2253    }
2254
2255    pub fn rebin(&self, contiguous_bins: usize) -> Result<Self> {
2256        if self.kind == HistogramSnapshotKind::Discrete {
2257            return Ok(self.clone());
2258        }
2259        if contiguous_bins == 0 {
2260            return Err(eyre!("Rebinning factor must be strictly positive."));
2261        }
2262        if self.bins.is_empty() || !self.bins.len().is_multiple_of(contiguous_bins) {
2263            return Err(eyre!(
2264                "Rebinning factor {} does not divide the {} histogram bins exactly.",
2265                contiguous_bins,
2266                self.bins.len()
2267            ));
2268        }
2269
2270        let bins = self
2271            .bins
2272            .chunks(contiguous_bins)
2273            .map(|chunk| {
2274                let mut rebinned = chunk[0].clone();
2275                rebinned.x_min = chunk.first().and_then(|bin| bin.x_min);
2276                rebinned.x_max = chunk.last().and_then(|bin| bin.x_max);
2277                for bin in &chunk[1..] {
2278                    rebinned.merge_in_place(bin);
2279                }
2280                rebinned
2281            })
2282            .collect();
2283
2284        Ok(Self {
2285            title: self.title.clone(),
2286            type_description: self.type_description.clone(),
2287            phase: self.phase,
2288            value_transform: self.value_transform,
2289            supports_misbinning_mitigation: self.supports_misbinning_mitigation,
2290            kind: self.kind,
2291            x_min: self.x_min,
2292            x_max: self.x_max,
2293            sample_count: self.sample_count,
2294            log_x_axis: self.log_x_axis,
2295            log_y_axis: self.log_y_axis,
2296            discrete_min_bin_id: self.discrete_min_bin_id,
2297            discrete_ordering: self.discrete_ordering,
2298            bins,
2299            underflow_bin: self.underflow_bin.clone(),
2300            overflow_bin: self.overflow_bin.clone(),
2301            statistics: self.statistics.clone(),
2302        })
2303    }
2304
2305    pub fn rebinned(&self, contiguous_bins: usize) -> Result<Self> {
2306        self.rebin(contiguous_bins)
2307    }
2308
2309    pub fn into_accumulator_state(self) -> HistogramAccumulatorState {
2310        HistogramAccumulatorState::from_snapshot(&self)
2311    }
2312}
2313
2314#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2315pub struct HistogramAccumulatorState {
2316    /// Determines whether bins represent continuous ranges or discrete identifiers.
2317    pub kind: HistogramSnapshotKind,
2318    /// Human-readable histogram title used by snapshots and exported output.
2319    pub title: String,
2320    /// HwU `TYPE@` description retained in generated snapshots.
2321    pub type_description: String,
2322    /// Real or imaginary component of the complex event weight accumulated in this histogram.
2323    pub phase: ObservablePhase,
2324    /// Transformation applied to observable coordinates before continuous binning.
2325    pub value_transform: ObservableValueTransform,
2326    /// Whether the observable supports paired fills that mitigate boundary misbinning.
2327    pub supports_misbinning_mitigation: bool,
2328    /// Lower continuous bound, or the smallest discrete bin identifier as an `f64`.
2329    pub x_min: f64,
2330    /// Upper continuous bound, or one past the largest discrete bin identifier as an `f64`.
2331    pub x_max: f64,
2332    /// Number of committed statistically independent Monte Carlo samples.
2333    pub sample_count: usize,
2334    new_sample_count: usize,
2335    /// Whether compatible renderers should display the horizontal axis logarithmically.
2336    pub log_x_axis: bool,
2337    /// Whether compatible renderers should display the vertical axis logarithmically.
2338    pub log_y_axis: bool,
2339    /// Smallest discrete bin identifier, or `None` for a continuous histogram.
2340    pub discrete_min_bin_id: Option<isize>,
2341    /// Display ordering for discrete bins, or `None` for a continuous histogram.
2342    pub discrete_ordering: Option<DiscreteBinOrdering>,
2343    /// Optional labels indexed by bin offset, primarily used by discrete histograms.
2344    pub bin_labels: Vec<Option<String>>,
2345    /// Per-bin raw-stat accumulators in continuous or ascending discrete-bin order.
2346    pub bins: Vec<ObservableBinAccumulator>,
2347    /// Raw-stat accumulator for entries below the configured histogram range.
2348    pub underflow_bin: ObservableBinAccumulator,
2349    /// Raw-stat accumulator for entries above the configured histogram range.
2350    pub overflow_bin: ObservableBinAccumulator,
2351    /// Histogram-wide entry, non-finite-value, and mitigation counters.
2352    pub statistics: ObservableHistogramStatistics,
2353}
2354
2355impl HistogramAccumulatorState {
2356    #[allow(clippy::too_many_arguments)]
2357    pub fn continuous(
2358        title: String,
2359        type_description: String,
2360        phase: ObservablePhase,
2361        value_transform: ObservableValueTransform,
2362        x_min: f64,
2363        x_max: f64,
2364        log_x_axis: bool,
2365        log_y_axis: bool,
2366        n_bins: usize,
2367    ) -> Self {
2368        Self::new_continuous(
2369            title,
2370            type_description,
2371            phase,
2372            value_transform,
2373            true,
2374            x_min,
2375            x_max,
2376            log_x_axis,
2377            log_y_axis,
2378            n_bins,
2379        )
2380    }
2381
2382    #[allow(clippy::too_many_arguments)]
2383    pub fn discrete(
2384        title: String,
2385        type_description: String,
2386        phase: ObservablePhase,
2387        min_bin_id: isize,
2388        max_bin_id: isize,
2389        ordering: DiscreteBinOrdering,
2390        log_y_axis: bool,
2391        bin_labels: Vec<Option<String>>,
2392    ) -> Result<Self> {
2393        Self::new_discrete(
2394            title,
2395            type_description,
2396            phase,
2397            ObservableValueTransform::Identity,
2398            min_bin_id,
2399            max_bin_id,
2400            ordering,
2401            log_y_axis,
2402            bin_labels,
2403        )
2404    }
2405
2406    #[allow(clippy::too_many_arguments)]
2407    fn new_continuous(
2408        title: String,
2409        type_description: String,
2410        phase: ObservablePhase,
2411        value_transform: ObservableValueTransform,
2412        supports_misbinning_mitigation: bool,
2413        x_min: f64,
2414        x_max: f64,
2415        log_x_axis: bool,
2416        log_y_axis: bool,
2417        n_bins: usize,
2418    ) -> Self {
2419        Self {
2420            kind: HistogramSnapshotKind::Continuous,
2421            title,
2422            type_description,
2423            phase,
2424            value_transform,
2425            supports_misbinning_mitigation,
2426            x_min,
2427            x_max,
2428            sample_count: 0,
2429            new_sample_count: 0,
2430            log_x_axis,
2431            log_y_axis,
2432            discrete_min_bin_id: None,
2433            discrete_ordering: None,
2434            bin_labels: Vec::new(),
2435            bins: vec![ObservableBinAccumulator::default(); n_bins],
2436            underflow_bin: ObservableBinAccumulator::default(),
2437            overflow_bin: ObservableBinAccumulator::default(),
2438            statistics: ObservableHistogramStatistics::default(),
2439        }
2440    }
2441
2442    #[allow(clippy::too_many_arguments)]
2443    fn new_discrete(
2444        title: String,
2445        type_description: String,
2446        phase: ObservablePhase,
2447        value_transform: ObservableValueTransform,
2448        min_bin_id: isize,
2449        max_bin_id: isize,
2450        ordering: DiscreteBinOrdering,
2451        log_y_axis: bool,
2452        bin_labels: Vec<Option<String>>,
2453    ) -> Result<Self> {
2454        if max_bin_id < min_bin_id {
2455            return Err(eyre!(
2456                "invalid discrete histogram range: max_bin_id ({max_bin_id}) must be >= min_bin_id ({min_bin_id})"
2457            ));
2458        }
2459        let n_bins = max_bin_id.saturating_sub(min_bin_id) as usize + 1;
2460        Ok(Self {
2461            kind: HistogramSnapshotKind::Discrete,
2462            title,
2463            type_description,
2464            phase,
2465            value_transform,
2466            supports_misbinning_mitigation: false,
2467            x_min: min_bin_id as f64,
2468            x_max: (max_bin_id + 1) as f64,
2469            sample_count: 0,
2470            new_sample_count: 0,
2471            log_x_axis: false,
2472            log_y_axis,
2473            discrete_min_bin_id: Some(min_bin_id),
2474            discrete_ordering: Some(ordering),
2475            bin_labels,
2476            bins: vec![ObservableBinAccumulator::default(); n_bins],
2477            underflow_bin: ObservableBinAccumulator::default(),
2478            overflow_bin: ObservableBinAccumulator::default(),
2479            statistics: ObservableHistogramStatistics::default(),
2480        })
2481    }
2482
2483    fn cleared_clone(&self) -> Self {
2484        match self.kind {
2485            HistogramSnapshotKind::Continuous => Self::new_continuous(
2486                self.title.clone(),
2487                self.type_description.clone(),
2488                self.phase,
2489                self.value_transform,
2490                self.supports_misbinning_mitigation,
2491                self.x_min,
2492                self.x_max,
2493                self.log_x_axis,
2494                self.log_y_axis,
2495                self.bins.len(),
2496            ),
2497            HistogramSnapshotKind::Discrete => Self::new_discrete(
2498                self.title.clone(),
2499                self.type_description.clone(),
2500                self.phase,
2501                self.value_transform,
2502                self.discrete_min_bin_id
2503                    .expect("discrete histogram missing min bin id"),
2504                self.discrete_min_bin_id
2505                    .expect("discrete histogram missing min bin id")
2506                    + self.bins.len() as isize
2507                    - 1,
2508                self.discrete_ordering
2509                    .expect("discrete histogram missing ordering"),
2510                self.log_y_axis,
2511                self.bin_labels.clone(),
2512            )
2513            .expect("cleared_clone should preserve a valid discrete histogram range"),
2514        }
2515    }
2516
2517    fn discrete_bin_id(&self, index: usize) -> isize {
2518        self.discrete_min_bin_id
2519            .expect("discrete histogram missing min bin id")
2520            + index as isize
2521    }
2522
2523    fn discrete_display_indices(&self) -> Vec<usize> {
2524        let mut indices: Vec<_> = (0..self.bins.len()).collect();
2525        let ordering = self
2526            .discrete_ordering
2527            .expect("discrete histogram missing ordering");
2528        let sample_count = self.sample_count + self.new_sample_count;
2529        indices.sort_by(|lhs, rhs| {
2530            let lhs_bin = &self.bins[*lhs];
2531            let rhs_bin = &self.bins[*rhs];
2532            let base = match ordering {
2533                DiscreteBinOrdering::AscendingBinId => Ordering::Equal,
2534                DiscreteBinOrdering::ValueDescending => rhs_bin
2535                    .average(sample_count)
2536                    .partial_cmp(&lhs_bin.average(sample_count))
2537                    .unwrap_or(Ordering::Equal),
2538                DiscreteBinOrdering::AbsValueDescending => rhs_bin
2539                    .average(sample_count)
2540                    .abs()
2541                    .partial_cmp(&lhs_bin.average(sample_count).abs())
2542                    .unwrap_or(Ordering::Equal),
2543            };
2544            if base == Ordering::Equal {
2545                self.discrete_bin_id(*lhs).cmp(&self.discrete_bin_id(*rhs))
2546            } else {
2547                base
2548            }
2549        });
2550        indices
2551    }
2552
2553    pub fn snapshot(&self) -> HistogramSnapshot {
2554        let bins = match self.kind {
2555            HistogramSnapshotKind::Continuous => self
2556                .bins
2557                .iter()
2558                .enumerate()
2559                .map(|(index, bin)| {
2560                    let x_min = (self.x_max - self.x_min) * index as f64 / self.bins.len() as f64
2561                        + self.x_min;
2562                    let x_max = (self.x_max - self.x_min) * (index + 1) as f64
2563                        / self.bins.len() as f64
2564                        + self.x_min;
2565                    HistogramBinSnapshot {
2566                        x_min: Some(x_min),
2567                        x_max: Some(x_max),
2568                        bin_id: None,
2569                        label: None,
2570                        entry_count: bin.total_entry_count(),
2571                        sum_weights: bin.total_sum_weights(),
2572                        sum_weights_squared: bin.total_sum_weights_squared(),
2573                        mitigated_fill_count: bin.total_mitigated_fill_count(),
2574                    }
2575                })
2576                .collect(),
2577            HistogramSnapshotKind::Discrete => self
2578                .discrete_display_indices()
2579                .into_iter()
2580                .map(|index| {
2581                    let bin = &self.bins[index];
2582                    HistogramBinSnapshot {
2583                        x_min: None,
2584                        x_max: None,
2585                        bin_id: Some(self.discrete_bin_id(index)),
2586                        label: self.bin_labels.get(index).cloned().flatten(),
2587                        entry_count: bin.total_entry_count(),
2588                        sum_weights: bin.total_sum_weights(),
2589                        sum_weights_squared: bin.total_sum_weights_squared(),
2590                        mitigated_fill_count: bin.total_mitigated_fill_count(),
2591                    }
2592                })
2593                .collect(),
2594        };
2595
2596        HistogramSnapshot {
2597            kind: self.kind,
2598            title: self.title.clone(),
2599            type_description: self.type_description.clone(),
2600            phase: self.phase,
2601            value_transform: self.value_transform,
2602            supports_misbinning_mitigation: self.supports_misbinning_mitigation,
2603            x_min: (self.kind == HistogramSnapshotKind::Continuous).then_some(self.x_min),
2604            x_max: (self.kind == HistogramSnapshotKind::Continuous).then_some(self.x_max),
2605            sample_count: self.sample_count + self.new_sample_count,
2606            log_x_axis: self.log_x_axis,
2607            log_y_axis: self.log_y_axis,
2608            discrete_min_bin_id: self.discrete_min_bin_id,
2609            discrete_ordering: self.discrete_ordering,
2610            bins,
2611            underflow_bin: HistogramBinSnapshot {
2612                x_min: None,
2613                x_max: (self.kind == HistogramSnapshotKind::Continuous).then_some(self.x_min),
2614                bin_id: None,
2615                label: None,
2616                entry_count: self.underflow_bin.total_entry_count(),
2617                sum_weights: self.underflow_bin.total_sum_weights(),
2618                sum_weights_squared: self.underflow_bin.total_sum_weights_squared(),
2619                mitigated_fill_count: self.underflow_bin.total_mitigated_fill_count(),
2620            },
2621            overflow_bin: HistogramBinSnapshot {
2622                x_min: (self.kind == HistogramSnapshotKind::Continuous).then_some(self.x_max),
2623                x_max: None,
2624                bin_id: None,
2625                label: None,
2626                entry_count: self.overflow_bin.total_entry_count(),
2627                sum_weights: self.overflow_bin.total_sum_weights(),
2628                sum_weights_squared: self.overflow_bin.total_sum_weights_squared(),
2629                mitigated_fill_count: self.overflow_bin.total_mitigated_fill_count(),
2630            },
2631            statistics: HistogramStatisticsSnapshot {
2632                in_range_entry_count: self.statistics.in_range_entry_count
2633                    + self.statistics.new_in_range_entry_count,
2634                nan_value_count: self.statistics.nan_value_count
2635                    + self.statistics.new_nan_value_count,
2636                mitigated_pair_count: self.statistics.mitigated_pair_count
2637                    + self.statistics.new_mitigated_pair_count,
2638            },
2639        }
2640    }
2641
2642    fn merge_samples(&mut self, other: &mut HistogramAccumulatorState) -> Result<()> {
2643        self.ensure_compatible(other)?;
2644        self.new_sample_count += other.new_sample_count;
2645        other.new_sample_count = 0;
2646        for (bin, other_bin) in self.bins.iter_mut().zip(other.bins.iter_mut()) {
2647            bin.merge_samples(other_bin);
2648        }
2649        self.underflow_bin.merge_samples(&mut other.underflow_bin);
2650        self.overflow_bin.merge_samples(&mut other.overflow_bin);
2651        self.statistics.merge_samples(&mut other.statistics);
2652        Ok(())
2653    }
2654
2655    pub fn merge_in_place(
2656        &mut self,
2657        other: &mut HistogramAccumulatorState,
2658    ) -> StdResult<(), ObservableAccumulationError> {
2659        self.ensure_compatible(other)?;
2660        let mut merged = self.snapshot();
2661        merged.merge_in_place(&other.snapshot())?;
2662        *self = merged.into_accumulator_state();
2663        *other = other.cleared_clone();
2664        Ok(())
2665    }
2666
2667    pub fn merged_with(&self, other: &HistogramAccumulatorState) -> Result<Self> {
2668        let mut merged = self.clone();
2669        let mut other_clone = other.clone();
2670        merged.merge_in_place(&mut other_clone)?;
2671        Ok(merged)
2672    }
2673
2674    fn update_result(&mut self) {
2675        self.sample_count += self.new_sample_count;
2676        self.new_sample_count = 0;
2677        for bin in &mut self.bins {
2678            bin.update_iter();
2679        }
2680        self.underflow_bin.update_iter();
2681        self.overflow_bin.update_iter();
2682        self.statistics.update_iter();
2683    }
2684
2685    pub fn update_results(&mut self) {
2686        self.update_result();
2687    }
2688
2689    fn write_hwu_block<W: Write>(&self, writer: &mut W) -> std::io::Result<()> {
2690        let x_axis_mode = if self.log_x_axis { "LOG" } else { "LIN" };
2691        let y_axis_mode = if self.log_y_axis { "LOG" } else { "LIN" };
2692
2693        writeln!(writer, "##& xmin & xmax & central value & dy &\n")?;
2694        writeln!(
2695            writer,
2696            "<histogram> {} \"{} |X_AXIS@{} |Y_AXIS@{} |TYPE@{}\"",
2697            self.bins.len(),
2698            self.title,
2699            x_axis_mode,
2700            y_axis_mode,
2701            self.type_description,
2702        )?;
2703
2704        let display_indices = if self.kind == HistogramSnapshotKind::Discrete {
2705            self.discrete_display_indices()
2706        } else {
2707            (0..self.bins.len()).collect()
2708        };
2709
2710        for index in display_indices {
2711            let bin = &self.bins[index];
2712            let (c1, c2) = if self.kind == HistogramSnapshotKind::Discrete {
2713                let bin_id = self.discrete_bin_id(index);
2714                (bin_id as f64, (bin_id + 1) as f64)
2715            } else {
2716                let c1 =
2717                    (self.x_max - self.x_min) * index as f64 / self.bins.len() as f64 + self.x_min;
2718                let c2 = (self.x_max - self.x_min) * (index + 1) as f64 / self.bins.len() as f64
2719                    + self.x_min;
2720                (c1, c2)
2721            };
2722            writeln!(
2723                writer,
2724                "  {:.8e}   {:.8e}   {:.8e}   {:.8e}",
2725                c1,
2726                c2,
2727                bin.average(self.sample_count + self.new_sample_count),
2728                bin.error(self.sample_count + self.new_sample_count),
2729            )?;
2730        }
2731
2732        writeln!(writer, "<\\histogram>")?;
2733        Ok(())
2734    }
2735
2736    fn from_snapshot(snapshot: &HistogramSnapshot) -> Self {
2737        let mut bins = snapshot.bins.clone();
2738        if snapshot.kind == HistogramSnapshotKind::Discrete {
2739            bins.sort_by_key(|bin| bin.bin_id.unwrap_or_default());
2740        }
2741        let discrete_min_bin_id = if snapshot.kind == HistogramSnapshotKind::Discrete {
2742            Some(
2743                bins.first()
2744                    .and_then(|bin| bin.bin_id)
2745                    .or(snapshot.discrete_min_bin_id)
2746                    .unwrap_or(0),
2747            )
2748        } else {
2749            None
2750        };
2751        let x_min = snapshot
2752            .x_min
2753            .unwrap_or_else(|| discrete_min_bin_id.unwrap_or_default() as f64);
2754        let x_max = snapshot.x_max.unwrap_or_else(|| {
2755            let min = discrete_min_bin_id.unwrap_or_default();
2756            (min + bins.len() as isize) as f64
2757        });
2758        Self {
2759            kind: snapshot.kind,
2760            title: snapshot.title.clone(),
2761            type_description: snapshot.type_description.clone(),
2762            phase: snapshot.phase,
2763            value_transform: snapshot.value_transform,
2764            supports_misbinning_mitigation: snapshot.supports_misbinning_mitigation,
2765            x_min,
2766            x_max,
2767            sample_count: snapshot.sample_count,
2768            new_sample_count: 0,
2769            log_x_axis: snapshot.log_x_axis,
2770            log_y_axis: snapshot.log_y_axis,
2771            discrete_min_bin_id,
2772            discrete_ordering: snapshot.discrete_ordering,
2773            bin_labels: if snapshot.kind == HistogramSnapshotKind::Discrete
2774                || bins.iter().any(|bin| bin.label.is_some())
2775            {
2776                bins.iter().map(|bin| bin.label.clone()).collect()
2777            } else {
2778                Vec::new()
2779            },
2780            bins: bins
2781                .iter()
2782                .map(ObservableBinAccumulator::from_snapshot)
2783                .collect(),
2784            underflow_bin: ObservableBinAccumulator::from_snapshot(&snapshot.underflow_bin),
2785            overflow_bin: ObservableBinAccumulator::from_snapshot(&snapshot.overflow_bin),
2786            statistics: ObservableHistogramStatistics {
2787                in_range_entry_count: snapshot.statistics.in_range_entry_count,
2788                nan_value_count: snapshot.statistics.nan_value_count,
2789                mitigated_pair_count: snapshot.statistics.mitigated_pair_count,
2790                new_in_range_entry_count: 0,
2791                new_nan_value_count: 0,
2792                new_mitigated_pair_count: 0,
2793            },
2794        }
2795    }
2796
2797    pub fn rebin(&self, contiguous_bins: usize) -> Result<Self> {
2798        self.snapshot()
2799            .rebin(contiguous_bins)
2800            .map(|s| s.into_accumulator_state())
2801    }
2802
2803    pub fn rescale(&mut self, factor: f64) {
2804        for bin in &mut self.bins {
2805            bin.rescale(factor);
2806        }
2807        self.underflow_bin.rescale(factor);
2808        self.overflow_bin.rescale(factor);
2809    }
2810
2811    pub fn rescaled(&self, factor: f64) -> Self {
2812        let mut scaled = self.clone();
2813        scaled.rescale(factor);
2814        scaled
2815    }
2816
2817    pub fn change_bin_ordering(&mut self, ordering: DiscreteBinOrdering) -> Result<()> {
2818        if self.kind != HistogramSnapshotKind::Discrete {
2819            return Err(eyre!(
2820                "Cannot change bin ordering on continuous histogram '{}'",
2821                self.title
2822            ));
2823        }
2824        self.discrete_ordering = Some(ordering);
2825        Ok(())
2826    }
2827
2828    pub fn changed_bin_ordering(&self, ordering: DiscreteBinOrdering) -> Result<Self> {
2829        let mut reordered = self.clone();
2830        reordered.change_bin_ordering(ordering)?;
2831        Ok(reordered)
2832    }
2833
2834    fn ensure_compatible(&self, other: &HistogramAccumulatorState) -> Result<()> {
2835        if self.title != other.title
2836            || self.type_description != other.type_description
2837            || self.phase != other.phase
2838            || self.value_transform != other.value_transform
2839            || self.supports_misbinning_mitigation != other.supports_misbinning_mitigation
2840            || self.kind != other.kind
2841            || self.x_min != other.x_min
2842            || self.x_max != other.x_max
2843            || self.log_x_axis != other.log_x_axis
2844            || self.log_y_axis != other.log_y_axis
2845            || self.discrete_min_bin_id != other.discrete_min_bin_id
2846            || self.bin_labels != other.bin_labels
2847            || self.bins.len() != other.bins.len()
2848        {
2849            return Err(eyre!(
2850                "Cannot merge incompatible histogram accumulators '{}'",
2851                self.title
2852            ));
2853        }
2854        Ok(())
2855    }
2856}
2857
2858#[derive(Debug, Clone, Default, Serialize, Deserialize)]
2859pub struct ObservableAccumulatorBundle {
2860    pub histograms: BTreeMap<String, HistogramAccumulatorState>,
2861}
2862
2863impl ObservableAccumulatorBundle {
2864    pub fn merge_samples(&mut self, other: &mut ObservableAccumulatorBundle) -> Result<()> {
2865        for (name, other_histogram) in other.histograms.iter_mut() {
2866            let histogram = self
2867                .histograms
2868                .get_mut(name)
2869                .ok_or_else(|| eyre!("Cannot merge unknown observable accumulator '{}'", name))?;
2870            histogram.merge_samples(other_histogram)?;
2871        }
2872        Ok(())
2873    }
2874
2875    pub fn update_results(&mut self) {
2876        for histogram in self.histograms.values_mut() {
2877            histogram.update_result();
2878        }
2879    }
2880
2881    pub fn snapshot_bundle(&self) -> ObservableSnapshotBundle {
2882        ObservableSnapshotBundle {
2883            histograms: self
2884                .histograms
2885                .iter()
2886                .map(|(name, histogram)| (name.clone(), histogram.snapshot()))
2887                .collect(),
2888        }
2889    }
2890}
2891
2892#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, JsonSchema)]
2893pub struct ObservableSnapshotBundle {
2894    pub histograms: BTreeMap<String, HistogramSnapshot>,
2895}
2896
2897impl ObservableSnapshotBundle {
2898    pub fn to_json_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
2899        let writer = BufWriter::new(File::create(path.as_ref())?);
2900        serde_json::to_writer_pretty(writer, self)?;
2901        Ok(())
2902    }
2903
2904    pub fn from_json_file<P: AsRef<Path>>(path: P) -> Result<Self> {
2905        let reader = BufReader::new(File::open(path.as_ref())?);
2906        Ok(serde_json::from_reader(reader)?)
2907    }
2908
2909    pub fn write_hwu_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
2910        let mut writer = BufWriter::new(File::create(path.as_ref())?);
2911        for histogram in self.histograms.values() {
2912            histogram.write_hwu_block(&mut writer)?;
2913        }
2914        Ok(())
2915    }
2916
2917    pub fn into_accumulator_bundle(self) -> ObservableAccumulatorBundle {
2918        ObservableAccumulatorBundle {
2919            histograms: self
2920                .histograms
2921                .into_iter()
2922                .map(|(name, histogram)| (name, histogram.into_accumulator_state()))
2923                .collect(),
2924        }
2925    }
2926
2927    pub fn merge_in_place(&mut self, other: &ObservableSnapshotBundle) -> Result<()> {
2928        if !self.histograms.keys().eq(other.histograms.keys()) {
2929            return Err(eyre!(
2930                "Cannot merge observable snapshots with different histogram names"
2931            ));
2932        }
2933        for (name, other_histogram) in other.histograms.iter() {
2934            let histogram = self
2935                .histograms
2936                .get_mut(name)
2937                .ok_or_else(|| eyre!("Cannot merge unknown histogram snapshot '{}'", name))?;
2938            histogram.merge_in_place(other_histogram)?;
2939        }
2940        Ok(())
2941    }
2942}
2943
2944trait EventSelector {
2945    fn process_event<T: FloatLike>(
2946        &mut self,
2947        event: &mut GenericEvent<T>,
2948        clustering_registry: &CompiledClusteringRegistry,
2949    ) -> bool;
2950}
2951
2952#[derive(Debug, Clone)]
2953struct ConfiguredSelector {
2954    definition: ObservableDefinition,
2955    criteria: Vec<SelectorCriterion>,
2956}
2957
2958impl ConfiguredSelector {
2959    pub(crate) fn new(
2960        settings: &SelectorSettings,
2961        quantities: &QuantitiesSettings,
2962        clustering_registry: &mut CompiledClusteringRegistry,
2963        model: Option<&Model>,
2964    ) -> Result<Self> {
2965        let quantity = quantities.get(&settings.quantity).ok_or_else(|| {
2966            eyre!(
2967                "Selector references unknown quantity '{}'",
2968                settings.quantity
2969            )
2970        })?;
2971
2972        let definition = ObservableDefinition::from_settings(quantity, clustering_registry, model)?;
2973        let coordinate_kind = definition.coordinate_kind();
2974
2975        let criterion = match &settings.selector {
2976            SelectorDefinitionSettings::ValueRange(selector) => {
2977                if coordinate_kind != ObservableCoordinateKind::Continuous {
2978                    return Err(eyre!(
2979                        "Selector '{}' uses value_range with a discrete quantity '{}'",
2980                        settings.quantity,
2981                        settings.quantity
2982                    ));
2983                }
2984                SelectorCriterion::ValueRange {
2985                    selection: settings.entry_selection,
2986                    entry_index: settings.entry_index,
2987                    reduction: selector.reduction,
2988                    min: selector.min,
2989                    max: selector.max,
2990                }
2991            }
2992            SelectorDefinitionSettings::DiscreteRange(selector) => {
2993                if coordinate_kind != ObservableCoordinateKind::Discrete {
2994                    return Err(eyre!(
2995                        "Selector '{}' uses discrete_range with a continuous quantity '{}'",
2996                        settings.quantity,
2997                        settings.quantity
2998                    ));
2999                }
3000                SelectorCriterion::DiscreteRange {
3001                    selection: settings.entry_selection,
3002                    entry_index: settings.entry_index,
3003                    min: selector.min,
3004                    max: selector.max,
3005                }
3006            }
3007            SelectorDefinitionSettings::CountRange(selector) => SelectorCriterion::CountRange {
3008                selection: settings.entry_selection,
3009                entry_index: settings.entry_index,
3010                min: selector.min_count,
3011                max: selector.max_count,
3012            },
3013        };
3014
3015        Ok(Self {
3016            definition,
3017            criteria: vec![criterion],
3018        })
3019    }
3020
3021    fn required_clustering_handle(&self) -> Option<ClusteringHandle> {
3022        self.definition.required_clustering_handle()
3023    }
3024
3025    fn passes_event<T: FloatLike>(
3026        &self,
3027        event: &mut GenericEvent<T>,
3028        clustering_registry: &CompiledClusteringRegistry,
3029    ) -> bool {
3030        if let Some(clustering_handle) = self.definition.required_clustering_handle() {
3031            ensure_event_clustering(event, clustering_handle, clustering_registry);
3032        }
3033        let entries = self.definition.process_event(event);
3034        self.criteria
3035            .iter()
3036            .all(|criterion| criterion.passes(&entries))
3037    }
3038
3039    fn passes_prepared_event<T: FloatLike>(&self, event: &GenericEvent<T>) -> bool {
3040        let entries = self.definition.process_event(event);
3041        self.criteria
3042            .iter()
3043            .all(|criterion| criterion.passes(&entries))
3044    }
3045}
3046
3047impl EventSelector for ConfiguredSelector {
3048    fn process_event<T: FloatLike>(
3049        &mut self,
3050        event: &mut GenericEvent<T>,
3051        clustering_registry: &CompiledClusteringRegistry,
3052    ) -> bool {
3053        self.passes_event(event, clustering_registry)
3054    }
3055}
3056
3057#[derive(Clone)]
3058enum Selectors {
3059    Configured(ConfiguredSelector),
3060}
3061
3062impl Selectors {
3063    fn process_event<T: FloatLike>(
3064        &mut self,
3065        event: &mut GenericEvent<T>,
3066        clustering_registry: &CompiledClusteringRegistry,
3067    ) -> bool {
3068        match self {
3069            Selectors::Configured(selector) => selector.process_event(event, clustering_registry),
3070        }
3071    }
3072}
3073
3074#[derive(Clone, Default)]
3075pub struct EventProcessingRuntime {
3076    clustering_registry: CompiledClusteringRegistry,
3077    observable_clustering_handles: Vec<ClusteringHandle>,
3078    selectors: Vec<Selectors>,
3079    observables: BTreeMap<String, Observables>,
3080}
3081
3082impl EventProcessingRuntime {
3083    pub fn from_settings(settings: &RuntimeSettings) -> Result<Self> {
3084        Self::from_settings_inner(settings, None, None)
3085    }
3086
3087    pub fn from_settings_with_model(settings: &RuntimeSettings, model: &Model) -> Result<Self> {
3088        Self::from_settings_inner(settings, Some(model), None)
3089    }
3090
3091    pub fn from_settings_with_model_and_process_info(
3092        settings: &RuntimeSettings,
3093        model: &Model,
3094        process_info: &HistogramProcessInfo,
3095    ) -> Result<Self> {
3096        Self::from_settings_inner(settings, Some(model), Some(process_info))
3097    }
3098
3099    fn from_settings_inner(
3100        settings: &RuntimeSettings,
3101        model: Option<&Model>,
3102        process_info: Option<&HistogramProcessInfo>,
3103    ) -> Result<Self> {
3104        let mut clustering_registry = CompiledClusteringRegistry::default();
3105        let selector_registry = settings
3106            .selectors
3107            .iter()
3108            .map(|(name, selector)| {
3109                ConfiguredSelector::new(
3110                    selector,
3111                    &settings.quantities,
3112                    &mut clustering_registry,
3113                    model,
3114                )
3115                .map(|configured| (name.clone(), configured))
3116            })
3117            .collect::<Result<BTreeMap<_, _>>>()?;
3118        let selectors = settings
3119            .selectors
3120            .iter()
3121            .filter(|(_, selector)| selector.active)
3122            .map(|(name, _selector)| Ok(Selectors::Configured(selector_registry[name].clone())))
3123            .collect::<Result<Vec<_>>>()?;
3124
3125        let mut observable_clustering_handles = Vec::new();
3126        let observables = settings
3127            .observables
3128            .iter()
3129            .map(|(name, observable)| {
3130                Observables::from_settings(
3131                    name,
3132                    observable,
3133                    &settings.quantities,
3134                    &settings.selectors,
3135                    &selector_registry,
3136                    process_info,
3137                    &mut clustering_registry,
3138                    model,
3139                )
3140                .map(|observable| {
3141                    for handle in observable.required_clustering_handles() {
3142                        if !observable_clustering_handles.contains(&handle) {
3143                            observable_clustering_handles.push(handle);
3144                        }
3145                    }
3146                    (name.clone(), observable)
3147                })
3148            })
3149            .collect::<Result<BTreeMap<_, _>>>()?;
3150
3151        Ok(Self {
3152            clustering_registry,
3153            observable_clustering_handles,
3154            selectors,
3155            observables,
3156        })
3157    }
3158
3159    pub fn has_selectors(&self) -> bool {
3160        !self.selectors.is_empty()
3161    }
3162
3163    pub fn has_observables(&self) -> bool {
3164        !self.observables.is_empty()
3165    }
3166
3167    fn process_event_internal<T: FloatLike>(
3168        &mut self,
3169        event: &mut GenericEvent<T>,
3170        prepare_observables: bool,
3171    ) -> bool {
3172        for selector in self.selectors.iter_mut() {
3173            if !selector.process_event(event, &self.clustering_registry) {
3174                return false;
3175            }
3176        }
3177
3178        if prepare_observables && self.has_observables() {
3179            for &handle in &self.observable_clustering_handles {
3180                ensure_event_clustering(event, handle, &self.clustering_registry);
3181            }
3182        }
3183        true
3184    }
3185
3186    pub fn process_event<T: FloatLike>(&mut self, event: &mut GenericEvent<T>) -> bool {
3187        self.process_event_internal(event, true)
3188    }
3189
3190    pub(crate) fn process_event_for_selectors<T: FloatLike>(
3191        &mut self,
3192        event: &mut GenericEvent<T>,
3193    ) -> bool {
3194        self.process_event_internal(event, false)
3195    }
3196
3197    /// Accumulate one independent draw, preserving correlations between all its groups.
3198    ///
3199    /// `coefficient` is the complete outer integration weight. A zero coefficient
3200    /// counts one attempt without histogram fills. Event weights are never mutated.
3201    ///
3202    /// # Errors
3203    /// Returns an error if the coefficient is nonfinite.
3204    ///
3205    /// # Examples
3206    /// ```
3207    /// use gammalooprs::observables::{EventGroupList, EventProcessingRuntime};
3208    /// use gammalooprs::utils::F;
3209    /// let mut accumulator = EventProcessingRuntime::default();
3210    /// accumulator.accumulate_sample(&EventGroupList::default(), &F(0.0))?;
3211    /// # Ok::<(), gammalooprs::observables::ObservableAccumulationError>(())
3212    /// ```
3213    pub fn accumulate_sample<T: FloatLike>(
3214        &mut self,
3215        event_groups: &GenericEventGroupList<T>,
3216        coefficient: &F<T>,
3217    ) -> StdResult<(), ObservableAccumulationError> {
3218        if !coefficient.0.is_finite() {
3219            return Err(ObservableAccumulationError::NonFiniteCoefficient);
3220        }
3221        for observable in self.observables.values_mut() {
3222            observable.process_event_groups(event_groups, coefficient, &self.clustering_registry);
3223        }
3224        Ok(())
3225    }
3226
3227    pub fn merge_samples(&mut self, other: &mut EventProcessingRuntime) -> Result<()> {
3228        for (name, other_observable) in other.observables.iter_mut() {
3229            let observable = self
3230                .observables
3231                .get_mut(name)
3232                .ok_or_else(|| eyre!("Cannot merge unknown observable '{}'", name))?;
3233            observable.merge_samples(other_observable)?;
3234        }
3235        Ok(())
3236    }
3237
3238    pub fn update_results(&mut self, iter: usize) {
3239        for observable in self.observables.values_mut() {
3240            observable.update_result(iter);
3241        }
3242    }
3243
3244    pub fn cleared_observable_clone(&self) -> Self {
3245        Self {
3246            clustering_registry: self.clustering_registry.clone(),
3247            observable_clustering_handles: self.observable_clustering_handles.clone(),
3248            selectors: self.selectors.clone(),
3249            observables: self
3250                .observables
3251                .iter()
3252                .map(|(name, observable)| (name.clone(), observable.cleared_clone()))
3253                .collect(),
3254        }
3255    }
3256
3257    pub fn snapshot_bundle(&self) -> ObservableSnapshotBundle {
3258        ObservableSnapshotBundle {
3259            histograms: self
3260                .observables
3261                .iter()
3262                .map(|(name, observable)| (name.clone(), observable.snapshot()))
3263                .collect(),
3264        }
3265    }
3266
3267    /// Merge an independent batch's complete statistics, including restored samples.
3268    ///
3269    /// Unlike the native integrator's iteration-local transfer, this consumes all
3270    /// samples represented by the snapshot. The source snapshot is unchanged.
3271    /// See [`Self::accumulate_sample`] for the per-sample boundary.
3272    ///
3273    /// # Errors
3274    /// Returns an error if histogram definitions or bin layouts are incompatible.
3275    pub fn merge_snapshot(
3276        &mut self,
3277        other: &ObservableSnapshotBundle,
3278    ) -> StdResult<(), ObservableAccumulationError> {
3279        let mut merged = self.snapshot_bundle();
3280        merged.merge_in_place(other)?;
3281        self.restore_snapshot_bundle(&merged)
3282            .map_err(ObservableAccumulationError::from)
3283    }
3284
3285    pub fn restore_snapshot_bundle(&mut self, bundle: &ObservableSnapshotBundle) -> Result<()> {
3286        if self.observables.len() != bundle.histograms.len() {
3287            return Err(eyre!(
3288                "Cannot restore observables from a snapshot with a different histogram count"
3289            ));
3290        }
3291
3292        for (name, observable) in self.observables.iter_mut() {
3293            let snapshot = bundle
3294                .histograms
3295                .get(name)
3296                .ok_or_else(|| eyre!("Cannot restore unknown histogram snapshot '{}'", name))?;
3297            observable.restore_snapshot(snapshot)?;
3298        }
3299
3300        Ok(())
3301    }
3302
3303    pub fn accumulator_bundle(&self) -> ObservableAccumulatorBundle {
3304        ObservableAccumulatorBundle {
3305            histograms: self
3306                .observables
3307                .iter()
3308                .map(|(name, observable)| (name.clone(), observable.accumulator_state()))
3309                .collect(),
3310        }
3311    }
3312
3313    pub fn merge_accumulator_bundle(
3314        &mut self,
3315        other: &mut ObservableAccumulatorBundle,
3316    ) -> Result<()> {
3317        for (name, other_histogram) in other.histograms.iter_mut() {
3318            let observable = self
3319                .observables
3320                .get_mut(name)
3321                .ok_or_else(|| eyre!("Cannot merge unknown observable '{}'", name))?;
3322            observable.merge_accumulator_state(other_histogram)?;
3323        }
3324        Ok(())
3325    }
3326}
3327
3328pub(crate) trait Observable {
3329    fn process_event_groups<T: FloatLike>(
3330        &mut self,
3331        event_groups: &GenericEventGroupList<T>,
3332        coefficient: &F<T>,
3333        clustering_registry: &CompiledClusteringRegistry,
3334    );
3335
3336    fn merge_samples(&mut self, other: &mut Self) -> Result<()>
3337    where
3338        Self: Sized;
3339
3340    fn update_result(&mut self, iter: usize);
3341}
3342
3343#[derive(Debug, Clone)]
3344struct PendingBinContribution {
3345    value: f64,
3346    bin_index: usize,
3347    projected_weight: f64,
3348    mitigated: bool,
3349}
3350
3351#[derive(Debug, Clone, Default)]
3352struct GroupBinContribution {
3353    projected_weight: f64,
3354    entry_count: usize,
3355    mitigated_fill_count: usize,
3356}
3357
3358#[derive(Debug, Clone)]
3359pub struct HistogramObservable {
3360    definition: ObservableDefinition,
3361    selections: Vec<ConfiguredSelector>,
3362    entry_selection: EntrySelection,
3363    entry_index: usize,
3364    misbinning_max_normalized_distance: Option<f64>,
3365    state: HistogramAccumulatorState,
3366    pending_contributions: Vec<PendingBinContribution>,
3367    candidate_pairs: Vec<(f64, usize, usize)>,
3368    used_contributions: Vec<bool>,
3369    grouped_contributions: Vec<GroupBinContribution>,
3370    grouped_underflow: GroupBinContribution,
3371    grouped_overflow: GroupBinContribution,
3372    touched_bins: Vec<usize>,
3373}
3374
3375impl HistogramObservable {
3376    fn new(config: HistogramObservableConfig<'_>) -> Result<Self> {
3377        let HistogramObservableConfig {
3378            definition,
3379            selections,
3380            quantities,
3381            quantity_settings,
3382            observable_name,
3383            settings,
3384            selector_settings,
3385            process_info,
3386        } = config;
3387        let state = match (&settings.histogram, definition.coordinate_kind()) {
3388            (HistogramSettings::Continuous(histogram), ObservableCoordinateKind::Continuous) => {
3389                let supports_misbinning_mitigation = definition.supports_misbinning_mitigation();
3390                if settings.misbinning_max_normalized_distance.is_some()
3391                    && !supports_misbinning_mitigation
3392                {
3393                    return Err(eyre!(
3394                        "Observable '{}' does not support misbinning mitigation.",
3395                        observable_name
3396                    ));
3397                }
3398                HistogramAccumulatorState::new_continuous(
3399                    histogram
3400                        .title
3401                        .clone()
3402                        .unwrap_or_else(|| observable_name.to_string()),
3403                    histogram.type_description.clone(),
3404                    settings.phase,
3405                    settings.value_transform,
3406                    supports_misbinning_mitigation,
3407                    histogram.x_min,
3408                    histogram.x_max,
3409                    histogram.log_x_axis,
3410                    histogram.log_y_axis,
3411                    histogram.n_bins,
3412                )
3413            }
3414            (HistogramSettings::Discrete(histogram), ObservableCoordinateKind::Discrete) => {
3415                if settings.misbinning_max_normalized_distance.is_some() {
3416                    return Err(eyre!(
3417                        "Observable '{}' uses a discrete histogram, so misbinning mitigation is not supported.",
3418                        observable_name
3419                    ));
3420                }
3421                if settings.value_transform != ObservableValueTransform::Identity {
3422                    return Err(eyre!(
3423                        "Observable '{}' uses a discrete histogram, so value_transform must stay identity.",
3424                        observable_name
3425                    ));
3426                }
3427                let (min_bin_id, max_bin_id, bin_labels) = resolve_discrete_histogram_layout(
3428                    quantities,
3429                    quantity_settings,
3430                    observable_name,
3431                    histogram,
3432                    &settings.selections,
3433                    selector_settings,
3434                    process_info,
3435                )?;
3436                HistogramAccumulatorState::new_discrete(
3437                    histogram
3438                        .title
3439                        .clone()
3440                        .unwrap_or_else(|| observable_name.to_string()),
3441                    histogram.type_description.clone(),
3442                    settings.phase,
3443                    settings.value_transform,
3444                    min_bin_id,
3445                    max_bin_id,
3446                    histogram.ordering,
3447                    histogram.log_y_axis,
3448                    bin_labels,
3449                )?
3450            }
3451            (HistogramSettings::Continuous(_), ObservableCoordinateKind::Discrete) => {
3452                return Err(eyre!(
3453                    "Observable '{}' uses a discrete quantity and therefore requires a discrete histogram definition.",
3454                    observable_name
3455                ));
3456            }
3457            (HistogramSettings::Discrete(_), ObservableCoordinateKind::Continuous) => {
3458                return Err(eyre!(
3459                    "Observable '{}' uses a continuous quantity and therefore requires a continuous histogram definition.",
3460                    observable_name
3461                ));
3462            }
3463        };
3464        let n_bins = state.bins.len();
3465
3466        Ok(Self {
3467            definition,
3468            selections,
3469            entry_selection: settings.entry_selection,
3470            entry_index: settings.entry_index,
3471            misbinning_max_normalized_distance: settings.misbinning_max_normalized_distance,
3472            state,
3473            pending_contributions: Vec::with_capacity(16),
3474            candidate_pairs: Vec::with_capacity(16),
3475            used_contributions: Vec::with_capacity(16),
3476            grouped_contributions: vec![GroupBinContribution::default(); n_bins],
3477            grouped_underflow: GroupBinContribution::default(),
3478            grouped_overflow: GroupBinContribution::default(),
3479            touched_bins: Vec::with_capacity(n_bins.min(16)),
3480        })
3481    }
3482
3483    fn build_group_contributions<T: FloatLike>(
3484        &mut self,
3485        event_group: &GenericEventGroup<T>,
3486        coefficient: &F<T>,
3487        _clustering_registry: &CompiledClusteringRegistry,
3488    ) {
3489        self.pending_contributions.clear();
3490        self.pending_contributions
3491            .reserve(event_group.len().saturating_mul(4));
3492
3493        for event in event_group.iter() {
3494            if self
3495                .selections
3496                .iter()
3497                .any(|selector| !selector.passes_prepared_event(event))
3498            {
3499                continue;
3500            }
3501            let entries = self.definition.process_event(event);
3502            for entry in apply_entry_selection(&entries, self.entry_selection, self.entry_index) {
3503                let (value, bin_position) = match &entry.coordinate {
3504                    ObservableCoordinate::Continuous(entry_value) => {
3505                        let transformed_value =
3506                            transform_value(entry_value, self.state.value_transform);
3507                        let value = transformed_value.into_ff64().0;
3508                        if !value.is_finite() {
3509                            self.state.statistics.register_nan();
3510                            continue;
3511                        }
3512
3513                        let Some(bin_position) = histogram_bin_position(
3514                            value,
3515                            self.state.x_min,
3516                            self.state.x_max,
3517                            self.state.bins.len(),
3518                        ) else {
3519                            self.state.statistics.register_nan();
3520                            continue;
3521                        };
3522                        (value, bin_position)
3523                    }
3524                    ObservableCoordinate::Discrete(bin_id) => (
3525                        *bin_id as f64,
3526                        histogram_bin_position_discrete(
3527                            *bin_id,
3528                            self.state
3529                                .discrete_min_bin_id
3530                                .expect("discrete histogram missing min bin id"),
3531                            self.state.bins.len(),
3532                        ),
3533                    ),
3534                };
3535
3536                let projected_weight = self
3537                    .state
3538                    .phase
3539                    .project(&(combined_entry_weight(event, &entry) * coefficient))
3540                    .into_ff64()
3541                    .0;
3542                if !projected_weight.is_finite() {
3543                    self.state.statistics.register_nan();
3544                    continue;
3545                }
3546
3547                match bin_position {
3548                    HistogramBinPosition::Underflow => {
3549                        self.grouped_underflow.projected_weight += projected_weight;
3550                        self.grouped_underflow.entry_count += 1;
3551                    }
3552                    HistogramBinPosition::Overflow => {
3553                        self.grouped_overflow.projected_weight += projected_weight;
3554                        self.grouped_overflow.entry_count += 1;
3555                    }
3556                    HistogramBinPosition::InRange(bin_index) => {
3557                        self.state.statistics.register_in_range_entry();
3558                        self.pending_contributions.push(PendingBinContribution {
3559                            value,
3560                            bin_index,
3561                            projected_weight,
3562                            mitigated: false,
3563                        });
3564                    }
3565                }
3566            }
3567        }
3568    }
3569
3570    fn mitigate_group_misbinning(&mut self) {
3571        if self.state.kind == HistogramSnapshotKind::Discrete {
3572            return;
3573        }
3574        let Some(max_distance) = self.misbinning_max_normalized_distance else {
3575            return;
3576        };
3577
3578        if self.pending_contributions.len() < 2 || self.state.bins.len() < 2 || max_distance <= 0.0
3579        {
3580            return;
3581        }
3582
3583        let bin_width = (self.state.x_max - self.state.x_min) / self.state.bins.len() as f64;
3584        if !bin_width.is_finite() || bin_width <= 0.0 {
3585            return;
3586        }
3587
3588        self.candidate_pairs.clear();
3589        for i in 0..self.pending_contributions.len() {
3590            for j in (i + 1)..self.pending_contributions.len() {
3591                if self.pending_contributions[i].projected_weight == 0.0
3592                    || self.pending_contributions[j].projected_weight == 0.0
3593                {
3594                    continue;
3595                }
3596                if self.pending_contributions[i].projected_weight.signum()
3597                    == self.pending_contributions[j].projected_weight.signum()
3598                {
3599                    continue;
3600                }
3601                if self.pending_contributions[i]
3602                    .bin_index
3603                    .abs_diff(self.pending_contributions[j].bin_index)
3604                    != 1
3605                {
3606                    continue;
3607                }
3608
3609                let normalized_distance = (self.pending_contributions[i].value
3610                    - self.pending_contributions[j].value)
3611                    .abs()
3612                    / bin_width;
3613                if normalized_distance <= max_distance {
3614                    self.candidate_pairs.push((normalized_distance, i, j));
3615                }
3616            }
3617        }
3618
3619        self.candidate_pairs
3620            .sort_by(|lhs, rhs| match lhs.0.partial_cmp(&rhs.0) {
3621                Some(ordering) => ordering,
3622                None => Ordering::Greater,
3623            });
3624
3625        self.used_contributions.clear();
3626        self.used_contributions
3627            .resize(self.pending_contributions.len(), false);
3628        for (_, i, j) in self.candidate_pairs.iter().copied() {
3629            if self.used_contributions[i] || self.used_contributions[j] {
3630                continue;
3631            }
3632
3633            let averaged_weight = 0.5
3634                * (self.pending_contributions[i].projected_weight
3635                    + self.pending_contributions[j].projected_weight);
3636            self.pending_contributions[i].projected_weight = averaged_weight;
3637            self.pending_contributions[j].projected_weight = averaged_weight;
3638            self.pending_contributions[i].mitigated = true;
3639            self.pending_contributions[j].mitigated = true;
3640            self.used_contributions[i] = true;
3641            self.used_contributions[j] = true;
3642            self.state.statistics.register_mitigated_pair();
3643        }
3644    }
3645
3646    pub fn snapshot(&self) -> HistogramSnapshot {
3647        self.state.snapshot()
3648    }
3649
3650    pub fn write_to_file<P: AsRef<Path>>(
3651        &self,
3652        path: P,
3653        format: ObservableFileFormat,
3654    ) -> Result<()> {
3655        match format {
3656            ObservableFileFormat::None => Ok(()),
3657            ObservableFileFormat::Hwu => {
3658                self.write_hwu_file(path)?;
3659                Ok(())
3660            }
3661            ObservableFileFormat::Json => self.snapshot().to_json_file(path),
3662        }
3663    }
3664
3665    fn write_hwu_file<P: AsRef<Path>>(&self, path: P) -> std::io::Result<()> {
3666        let mut writer = BufWriter::new(File::create(path.as_ref())?);
3667        self.state.write_hwu_block(&mut writer)
3668    }
3669
3670    fn flush_sample_contributions(&mut self) {
3671        if self.touched_bins.is_empty()
3672            && self.grouped_underflow.projected_weight == 0.0
3673            && self.grouped_underflow.entry_count == 0
3674            && self.grouped_underflow.mitigated_fill_count == 0
3675            && self.grouped_overflow.projected_weight == 0.0
3676            && self.grouped_overflow.entry_count == 0
3677            && self.grouped_overflow.mitigated_fill_count == 0
3678        {
3679            return;
3680        }
3681
3682        for &bin_index in &self.touched_bins {
3683            let grouped = &self.grouped_contributions[bin_index];
3684            let bin_accumulator = &mut self.state.bins[bin_index];
3685            bin_accumulator.add_sample(
3686                grouped.projected_weight,
3687                grouped.entry_count,
3688                grouped.mitigated_fill_count,
3689            );
3690        }
3691        if self.grouped_underflow.projected_weight != 0.0
3692            || self.grouped_underflow.entry_count != 0
3693            || self.grouped_underflow.mitigated_fill_count != 0
3694        {
3695            self.state.underflow_bin.add_sample(
3696                self.grouped_underflow.projected_weight,
3697                self.grouped_underflow.entry_count,
3698                self.grouped_underflow.mitigated_fill_count,
3699            );
3700        }
3701        if self.grouped_overflow.projected_weight != 0.0
3702            || self.grouped_overflow.entry_count != 0
3703            || self.grouped_overflow.mitigated_fill_count != 0
3704        {
3705            self.state.overflow_bin.add_sample(
3706                self.grouped_overflow.projected_weight,
3707                self.grouped_overflow.entry_count,
3708                self.grouped_overflow.mitigated_fill_count,
3709            );
3710        }
3711    }
3712
3713    fn clear_sample_contributions(&mut self) {
3714        self.grouped_underflow = GroupBinContribution::default();
3715        self.grouped_overflow = GroupBinContribution::default();
3716        for bin_index in self.touched_bins.drain(..) {
3717            self.grouped_contributions[bin_index] = GroupBinContribution::default();
3718        }
3719    }
3720
3721    fn required_clustering_handles(&self) -> Vec<ClusteringHandle> {
3722        let mut handles = Vec::new();
3723        if let Some(handle) = self.definition.required_clustering_handle() {
3724            handles.push(handle);
3725        }
3726        for selector in &self.selections {
3727            if let Some(handle) = selector.required_clustering_handle()
3728                && !handles.contains(&handle)
3729            {
3730                handles.push(handle);
3731            }
3732        }
3733        handles
3734    }
3735}
3736
3737struct HistogramObservableConfig<'a> {
3738    definition: ObservableDefinition,
3739    selections: Vec<ConfiguredSelector>,
3740    quantities: &'a QuantitiesSettings,
3741    quantity_settings: &'a QuantitySettings,
3742    observable_name: &'a str,
3743    settings: &'a ObservableSettings,
3744    selector_settings: &'a SelectorsSettings,
3745    process_info: Option<&'a HistogramProcessInfo>,
3746}
3747
3748fn resolve_discrete_histogram_layout(
3749    quantities: &QuantitiesSettings,
3750    quantity_settings: &QuantitySettings,
3751    observable_name: &str,
3752    histogram: &DiscreteHistogramSettings,
3753    selection_names: &[String],
3754    selector_settings: &SelectorsSettings,
3755    process_info: Option<&HistogramProcessInfo>,
3756) -> Result<(isize, isize, Vec<Option<String>>)> {
3757    let graph_group_context = resolve_graph_group_context(
3758        observable_name,
3759        selection_names,
3760        selector_settings,
3761        quantities,
3762        process_info,
3763    )?;
3764    let (min_bin_id, max_bin_id) = match histogram.domain {
3765        DiscreteBinDomainSettings::ExplicitRange { min, max } => (min, max),
3766        DiscreteBinDomainSettings::SingleBin => (0, 0),
3767        DiscreteBinDomainSettings::GraphIds => {
3768            let info = process_info.ok_or_else(|| {
3769                eyre!(
3770                    "Observable '{}' uses GraphIds but no process information is available.",
3771                    observable_name
3772                )
3773            })?;
3774            if info.graph_names.is_empty() {
3775                return Err(eyre!(
3776                    "Observable '{}' uses GraphIds but the process exposes no graphs.",
3777                    observable_name
3778                ));
3779            }
3780            (0, info.graph_names.len() as isize - 1)
3781        }
3782        DiscreteBinDomainSettings::GraphGroupIds => {
3783            let info = process_info.ok_or_else(|| {
3784                eyre!(
3785                    "Observable '{}' uses GraphGroupIds but no process information is available.",
3786                    observable_name
3787                )
3788            })?;
3789            if info.graph_group_master_names.is_empty() {
3790                return Err(eyre!(
3791                    "Observable '{}' uses GraphGroupIds but the process exposes no graph groups.",
3792                    observable_name
3793                ));
3794            }
3795            (0, info.graph_group_master_names.len() as isize - 1)
3796        }
3797        DiscreteBinDomainSettings::OrientationIds => {
3798            let info = process_info.ok_or_else(|| {
3799                eyre!(
3800                    "Observable '{}' uses OrientationIds but no process information is available.",
3801                    observable_name
3802                )
3803            })?;
3804            let group_id = graph_group_context.ok_or_else(|| {
3805                eyre!(
3806                    "Observable '{}' uses OrientationIds but no singleton graph-group context could be resolved from its selections.",
3807                    observable_name
3808                )
3809            })?;
3810            let labels = info.orientation_labels_by_group.get(group_id).ok_or_else(|| {
3811                eyre!(
3812                    "Observable '{}' resolved graph-group {} for OrientationIds, but no orientation metadata is available.",
3813                    observable_name,
3814                    group_id
3815                )
3816            })?;
3817            (0, labels.len() as isize - 1)
3818        }
3819        DiscreteBinDomainSettings::SamplingChannelIds => {
3820            let info = process_info.ok_or_else(|| {
3821                eyre!(
3822                    "Observable '{}' uses SamplingChannelIds but no process information is available.",
3823                    observable_name
3824                )
3825            })?;
3826            let group_id = graph_group_context.ok_or_else(|| {
3827                eyre!(
3828                    "Observable '{}' uses SamplingChannelIds but no singleton graph-group context could be resolved from its selections.",
3829                    observable_name
3830                )
3831            })?;
3832            let labels = info.sampling_channel_labels_by_group.get(group_id).ok_or_else(|| {
3833                eyre!(
3834                    "Observable '{}' resolved graph-group {} for SamplingChannelIds, but no sampling-channel metadata is available.",
3835                    observable_name,
3836                    group_id
3837                )
3838            })?;
3839            (0, labels.len() as isize - 1)
3840        }
3841    };
3842    if max_bin_id < min_bin_id {
3843        return Err(eyre!(
3844            "Observable '{}' has an invalid discrete histogram range [{}, {}].",
3845            observable_name,
3846            min_bin_id,
3847            max_bin_id
3848        ));
3849    }
3850    let n_bins = max_bin_id.saturating_sub(min_bin_id) as usize + 1;
3851    let bin_labels = match histogram.labels.as_ref() {
3852        None => {
3853            if matches!(quantity_settings, QuantitySettings::Integral {}) && n_bins == 1 {
3854                vec![Some("total integral".to_string())]
3855            } else {
3856                vec![None; n_bins]
3857            }
3858        }
3859        Some(DiscreteBinLabelsSettings::Custom { labels }) => {
3860            if labels.len() != n_bins {
3861                return Err(eyre!(
3862                    "Observable '{}' defines {} discrete labels for {} bins.",
3863                    observable_name,
3864                    labels.len(),
3865                    n_bins
3866                ));
3867            }
3868            labels.iter().cloned().map(Some).collect()
3869        }
3870        Some(DiscreteBinLabelsSettings::BinId) => (0..n_bins)
3871            .map(|offset| Some(format!("#{}", min_bin_id + offset as isize)))
3872            .collect(),
3873        Some(DiscreteBinLabelsSettings::GraphName) => {
3874            if !matches!(quantity_settings, QuantitySettings::GraphId {}) {
3875                return Err(eyre!(
3876                    "Observable '{}' uses GraphName labels, but its quantity is not graph_id.",
3877                    observable_name
3878                ));
3879            }
3880            let info = process_info.ok_or_else(|| {
3881                eyre!(
3882                    "Observable '{}' uses GraphName labels but no process information is available.",
3883                    observable_name
3884                )
3885            })?;
3886            info.graph_names.iter().cloned().map(Some).collect()
3887        }
3888        Some(DiscreteBinLabelsSettings::GraphGroupMasterName) => {
3889            if !matches!(quantity_settings, QuantitySettings::GraphGroupId {}) {
3890                return Err(eyre!(
3891                    "Observable '{}' uses GraphGroupMasterName labels, but its quantity is not graph_group_id.",
3892                    observable_name
3893                ));
3894            }
3895            let info = process_info.ok_or_else(|| {
3896                eyre!(
3897                    "Observable '{}' uses GraphGroupMasterName labels but no process information is available.",
3898                    observable_name
3899                )
3900            })?;
3901            info.graph_group_master_names
3902                .iter()
3903                .cloned()
3904                .map(Some)
3905                .collect()
3906        }
3907        Some(DiscreteBinLabelsSettings::Orientation) => {
3908            if !matches!(quantity_settings, QuantitySettings::OrientationId {}) {
3909                return Err(eyre!(
3910                    "Observable '{}' uses Orientation labels, but its quantity is not orientation_id.",
3911                    observable_name
3912                ));
3913            }
3914            let info = process_info.ok_or_else(|| {
3915                eyre!(
3916                    "Observable '{}' uses Orientation labels but no process information is available.",
3917                    observable_name
3918                )
3919            })?;
3920            let group_id = graph_group_context.ok_or_else(|| {
3921                eyre!(
3922                    "Observable '{}' uses Orientation labels but no singleton graph-group context could be resolved from its selections.",
3923                    observable_name
3924                )
3925            })?;
3926            info.orientation_labels_by_group
3927                .get(group_id)
3928                .ok_or_else(|| {
3929                    eyre!(
3930                        "Observable '{}' resolved graph group {} for Orientation labels, but the process only exposes {} graph groups.",
3931                        observable_name,
3932                        group_id,
3933                        info.orientation_labels_by_group.len()
3934                    )
3935                })?
3936                .iter()
3937                .cloned()
3938                .map(Some)
3939                .collect()
3940        }
3941        Some(DiscreteBinLabelsSettings::SamplingChannelEdgeIds) => {
3942            if !matches!(quantity_settings, QuantitySettings::SamplingChannelId {}) {
3943                return Err(eyre!(
3944                    "Observable '{}' uses SamplingChannelEdgeIds labels, but its quantity is not sampling_channel_id.",
3945                    observable_name
3946                ));
3947            }
3948            let info = process_info.ok_or_else(|| {
3949                eyre!(
3950                    "Observable '{}' uses SamplingChannelEdgeIds labels but no process information is available.",
3951                    observable_name
3952                )
3953            })?;
3954            let group_id = graph_group_context.ok_or_else(|| {
3955                eyre!(
3956                    "Observable '{}' uses SamplingChannelEdgeIds labels but no singleton graph-group context could be resolved from its selections.",
3957                    observable_name
3958                )
3959            })?;
3960            info.sampling_channel_labels_by_group
3961                .get(group_id)
3962                .ok_or_else(|| {
3963                    eyre!(
3964                        "Observable '{}' resolved graph group {} for SamplingChannelEdgeIds labels, but the process only exposes {} graph groups.",
3965                        observable_name,
3966                        group_id,
3967                        info.sampling_channel_labels_by_group.len()
3968                    )
3969                })?
3970                .iter()
3971                .cloned()
3972                .map(Some)
3973                .collect()
3974        }
3975    };
3976    if bin_labels.len() != n_bins {
3977        return Err(eyre!(
3978            "Observable '{}' resolved {} labels for {} discrete bins.",
3979            observable_name,
3980            bin_labels.len(),
3981            n_bins
3982        ));
3983    }
3984    Ok((min_bin_id, max_bin_id, bin_labels))
3985}
3986
3987fn resolve_graph_group_context(
3988    observable_name: &str,
3989    selection_names: &[String],
3990    selector_settings: &SelectorsSettings,
3991    quantities: &QuantitiesSettings,
3992    process_info: Option<&HistogramProcessInfo>,
3993) -> Result<Option<usize>> {
3994    let mut resolved = None;
3995    for selection_name in selection_names {
3996        let Some(selector) = selector_settings.get(selection_name) else {
3997            return Err(eyre!(
3998                "Observable '{}' references unknown selector '{}'",
3999                observable_name,
4000                selection_name
4001            ));
4002        };
4003        let quantity = quantities.get(&selector.quantity).ok_or_else(|| {
4004            eyre!(
4005                "Observable '{}' selection '{}' references unknown quantity '{}'",
4006                observable_name,
4007                selection_name,
4008                selector.quantity
4009            )
4010        })?;
4011        let candidate = graph_group_context_candidate(
4012            observable_name,
4013            selection_name,
4014            selector,
4015            quantity,
4016            process_info,
4017        )?;
4018        if let Some(candidate) = candidate {
4019            if let Some(existing) = resolved
4020                && existing != candidate
4021            {
4022                return Err(eyre!(
4023                    "Observable '{}' resolves conflicting graph-group contexts {} and {} from its selections.",
4024                    observable_name,
4025                    existing,
4026                    candidate
4027                ));
4028            }
4029            resolved = Some(candidate);
4030        }
4031    }
4032
4033    if resolved.is_none()
4034        && let Some(info) = process_info
4035        && info.graph_group_master_names.len() == 1
4036    {
4037        resolved = Some(0);
4038    }
4039
4040    Ok(resolved)
4041}
4042
4043fn graph_group_context_candidate(
4044    observable_name: &str,
4045    selection_name: &str,
4046    selector: &SelectorSettings,
4047    quantity: &QuantitySettings,
4048    process_info: Option<&HistogramProcessInfo>,
4049) -> Result<Option<usize>> {
4050    let SelectorDefinitionSettings::DiscreteRange(DiscreteRangeSelectorSettings {
4051        min: Some(min),
4052        max: Some(max),
4053    }) = &selector.selector
4054    else {
4055        return Ok(None);
4056    };
4057    if min != max {
4058        return Ok(None);
4059    }
4060
4061    match quantity {
4062        QuantitySettings::GraphGroupId {} => {
4063            let group_id = singleton_selector_index(
4064                observable_name,
4065                selection_name,
4066                "graph_group_id",
4067                *min,
4068                process_info.map(|info| info.graph_group_master_names.len()),
4069            )?;
4070            Ok(Some(group_id))
4071        }
4072        QuantitySettings::GraphId {} => {
4073            let info = process_info.ok_or_else(|| {
4074                eyre!(
4075                    "Observable '{}' needs process information to map selector '{}' graph_id={} to a graph group.",
4076                    observable_name,
4077                    selection_name,
4078                    min
4079                )
4080            })?;
4081            let graph_id = singleton_selector_index(
4082                observable_name,
4083                selection_name,
4084                "graph_id",
4085                *min,
4086                Some(info.graph_to_group_id.len()),
4087            )?;
4088            Ok(info.graph_to_group_id.get(graph_id).copied())
4089        }
4090        _ => Ok(None),
4091    }
4092}
4093
4094fn singleton_selector_index(
4095    observable_name: &str,
4096    selection_name: &str,
4097    quantity_label: &str,
4098    value: isize,
4099    upper_bound: Option<usize>,
4100) -> Result<usize> {
4101    let index = usize::try_from(value).map_err(|_| {
4102        eyre!(
4103            "Observable '{}' resolves selector '{}' {}={} as graph-group context, but the value must be non-negative.",
4104            observable_name,
4105            selection_name,
4106            quantity_label,
4107            value
4108        )
4109    })?;
4110    if let Some(upper_bound) = upper_bound
4111        && index >= upper_bound
4112    {
4113        return Err(eyre!(
4114            "Observable '{}' resolves selector '{}' {}={} as graph-group context, but the process only exposes {} valid values.",
4115            observable_name,
4116            selection_name,
4117            quantity_label,
4118            value,
4119            upper_bound
4120        ));
4121    }
4122    Ok(index)
4123}
4124
4125impl Observable for HistogramObservable {
4126    fn process_event_groups<T: FloatLike>(
4127        &mut self,
4128        event_groups: &GenericEventGroupList<T>,
4129        coefficient: &F<T>,
4130        clustering_registry: &CompiledClusteringRegistry,
4131    ) {
4132        self.state.new_sample_count += 1;
4133        if coefficient == &coefficient.zero() {
4134            return;
4135        }
4136        self.touched_bins.clear();
4137
4138        for event_group in event_groups.iter() {
4139            self.build_group_contributions(event_group, coefficient, clustering_registry);
4140            self.mitigate_group_misbinning();
4141
4142            for contribution in &self.pending_contributions {
4143                let grouped = &mut self.grouped_contributions[contribution.bin_index];
4144                if grouped.projected_weight == 0.0
4145                    && grouped.entry_count == 0
4146                    && grouped.mitigated_fill_count == 0
4147                {
4148                    self.touched_bins.push(contribution.bin_index);
4149                }
4150                grouped.projected_weight += contribution.projected_weight;
4151                grouped.entry_count += 1;
4152                if contribution.mitigated {
4153                    grouped.mitigated_fill_count += 1;
4154                }
4155            }
4156        }
4157
4158        self.flush_sample_contributions();
4159        self.clear_sample_contributions();
4160    }
4161
4162    fn merge_samples(&mut self, other: &mut HistogramObservable) -> Result<()> {
4163        self.state.merge_samples(&mut other.state)
4164    }
4165
4166    fn update_result(&mut self, _iter: usize) {
4167        self.state.update_result();
4168    }
4169}
4170
4171#[derive(Debug, Clone)]
4172pub enum Observables {
4173    Histogram(HistogramObservable),
4174}
4175
4176impl Observables {
4177    #[allow(clippy::too_many_arguments)]
4178    fn from_settings(
4179        name: &str,
4180        settings: &ObservableSettings,
4181        quantities: &QuantitiesSettings,
4182        selector_settings: &SelectorsSettings,
4183        selector_registry: &BTreeMap<String, ConfiguredSelector>,
4184        process_info: Option<&HistogramProcessInfo>,
4185        clustering_registry: &mut CompiledClusteringRegistry,
4186        model: Option<&Model>,
4187    ) -> Result<Self> {
4188        let quantity = quantities.get(&settings.quantity).ok_or_else(|| {
4189            eyre!(
4190                "Observable '{}' references unknown quantity '{}'",
4191                name,
4192                settings.quantity
4193            )
4194        })?;
4195        let selections = settings
4196            .selections
4197            .iter()
4198            .map(|selector_name| {
4199                selector_registry
4200                    .get(selector_name)
4201                    .cloned()
4202                    .ok_or_else(|| {
4203                        eyre!(
4204                            "Observable '{}' references unknown selector '{}'",
4205                            name,
4206                            selector_name
4207                        )
4208                    })
4209            })
4210            .collect::<Result<Vec<_>>>()?;
4211
4212        Ok(Observables::Histogram(HistogramObservable::new(
4213            HistogramObservableConfig {
4214                definition: ObservableDefinition::from_settings(
4215                    quantity,
4216                    clustering_registry,
4217                    model,
4218                )?,
4219                selections,
4220                quantities,
4221                quantity_settings: quantity,
4222                observable_name: name,
4223                settings,
4224                selector_settings,
4225                process_info,
4226            },
4227        )?))
4228    }
4229
4230    pub(crate) fn process_event_groups<T: FloatLike>(
4231        &mut self,
4232        event_groups: &GenericEventGroupList<T>,
4233        coefficient: &F<T>,
4234        clustering_registry: &CompiledClusteringRegistry,
4235    ) {
4236        match self {
4237            Observables::Histogram(observable) => {
4238                observable.process_event_groups(event_groups, coefficient, clustering_registry)
4239            }
4240        }
4241    }
4242
4243    pub(crate) fn merge_samples(&mut self, other: &mut Observables) -> Result<()> {
4244        match (self, other) {
4245            (Observables::Histogram(lhs), Observables::Histogram(rhs)) => lhs.merge_samples(rhs),
4246        }
4247    }
4248
4249    pub(crate) fn required_clustering_handles(&self) -> Vec<ClusteringHandle> {
4250        match self {
4251            Observables::Histogram(observable) => observable.required_clustering_handles(),
4252        }
4253    }
4254
4255    pub(crate) fn update_result(&mut self, iter: usize) {
4256        match self {
4257            Observables::Histogram(observable) => observable.update_result(iter),
4258        }
4259    }
4260
4261    pub(crate) fn restore_snapshot(&mut self, snapshot: &HistogramSnapshot) -> Result<()> {
4262        match self {
4263            Observables::Histogram(observable) => observable.restore_snapshot(snapshot),
4264        }
4265    }
4266
4267    pub(crate) fn cleared_clone(&self) -> Self {
4268        match self {
4269            Observables::Histogram(observable) => Observables::Histogram(HistogramObservable {
4270                definition: observable.definition.clone(),
4271                selections: observable.selections.clone(),
4272                entry_selection: observable.entry_selection,
4273                entry_index: observable.entry_index,
4274                misbinning_max_normalized_distance: observable.misbinning_max_normalized_distance,
4275                state: observable.state.cleared_clone(),
4276                pending_contributions: Vec::with_capacity(
4277                    observable.pending_contributions.capacity(),
4278                ),
4279                candidate_pairs: Vec::with_capacity(observable.candidate_pairs.capacity()),
4280                used_contributions: Vec::with_capacity(observable.used_contributions.capacity()),
4281                grouped_contributions: vec![
4282                    GroupBinContribution::default();
4283                    observable.grouped_contributions.len()
4284                ],
4285                grouped_underflow: GroupBinContribution::default(),
4286                grouped_overflow: GroupBinContribution::default(),
4287                touched_bins: Vec::with_capacity(observable.touched_bins.capacity()),
4288            }),
4289        }
4290    }
4291
4292    pub(crate) fn snapshot(&self) -> HistogramSnapshot {
4293        match self {
4294            Observables::Histogram(observable) => observable.snapshot(),
4295        }
4296    }
4297
4298    pub(crate) fn accumulator_state(&self) -> HistogramAccumulatorState {
4299        match self {
4300            Observables::Histogram(observable) => observable.state.clone(),
4301        }
4302    }
4303
4304    pub(crate) fn merge_accumulator_state(
4305        &mut self,
4306        other: &mut HistogramAccumulatorState,
4307    ) -> Result<()> {
4308        match self {
4309            Observables::Histogram(observable) => observable.state.merge_samples(other),
4310        }
4311    }
4312}
4313
4314impl HistogramObservable {
4315    fn restore_snapshot(&mut self, snapshot: &HistogramSnapshot) -> Result<()> {
4316        let restored_state = snapshot.clone().into_accumulator_state();
4317        self.state.ensure_compatible(&restored_state)?;
4318        self.state = restored_state;
4319        self.pending_contributions.clear();
4320        self.candidate_pairs.clear();
4321        self.used_contributions.clear();
4322        self.grouped_contributions
4323            .fill(GroupBinContribution::default());
4324        self.grouped_underflow = GroupBinContribution::default();
4325        self.grouped_overflow = GroupBinContribution::default();
4326        self.touched_bins.clear();
4327        Ok(())
4328    }
4329}
4330
4331#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
4332enum HistogramBinPosition {
4333    Underflow,
4334    Overflow,
4335    InRange(usize),
4336}
4337
4338fn histogram_bin_position(
4339    value: f64,
4340    x_min: f64,
4341    x_max: f64,
4342    num_bins: usize,
4343) -> Option<HistogramBinPosition> {
4344    if num_bins == 0 || x_max <= x_min || !value.is_finite() {
4345        return None;
4346    }
4347
4348    if value < x_min {
4349        return Some(HistogramBinPosition::Underflow);
4350    }
4351    if value >= x_max {
4352        return Some(HistogramBinPosition::Overflow);
4353    }
4354
4355    let index = ((value - x_min) / (x_max - x_min) * num_bins as f64) as usize;
4356    if index < num_bins {
4357        Some(HistogramBinPosition::InRange(index))
4358    } else {
4359        Some(HistogramBinPosition::Overflow)
4360    }
4361}
4362
4363fn histogram_bin_position_discrete(
4364    value: isize,
4365    min_bin_id: isize,
4366    num_bins: usize,
4367) -> HistogramBinPosition {
4368    let max_bin_id = min_bin_id + num_bins as isize - 1;
4369    if value < min_bin_id {
4370        HistogramBinPosition::Underflow
4371    } else if value > max_bin_id {
4372        HistogramBinPosition::Overflow
4373    } else {
4374        HistogramBinPosition::InRange((value - min_bin_id) as usize)
4375    }
4376}
4377
4378fn sort_discrete_snapshot_bins(
4379    bins: &mut [HistogramBinSnapshot],
4380    ordering: DiscreteBinOrdering,
4381    sample_count: usize,
4382) {
4383    bins.sort_by(|lhs, rhs| {
4384        let base = match ordering {
4385            DiscreteBinOrdering::AscendingBinId => Ordering::Equal,
4386            DiscreteBinOrdering::ValueDescending => rhs
4387                .average(sample_count)
4388                .partial_cmp(&lhs.average(sample_count))
4389                .unwrap_or(Ordering::Equal),
4390            DiscreteBinOrdering::AbsValueDescending => rhs
4391                .average(sample_count)
4392                .abs()
4393                .partial_cmp(&lhs.average(sample_count).abs())
4394                .unwrap_or(Ordering::Equal),
4395        };
4396        if base == Ordering::Equal {
4397            lhs.bin_id
4398                .unwrap_or_default()
4399                .cmp(&rhs.bin_id.unwrap_or_default())
4400        } else {
4401            base
4402        }
4403    });
4404}
4405
4406fn unit_complex<T: FloatLike>(reference: &F<T>) -> Complex<F<T>> {
4407    Complex::new(reference.one(), reference.zero())
4408}
4409
4410fn apply_entry_selection<T: FloatLike>(
4411    entries: &[ObservableEntry<T>],
4412    selection: EntrySelection,
4413    entry_index: usize,
4414) -> ObservableEntries<T> {
4415    match selection {
4416        EntrySelection::All => entries.iter().cloned().collect(),
4417        EntrySelection::LeadingOnly => entries.first().into_iter().cloned().collect(),
4418        EntrySelection::NthOnly => entries.get(entry_index).into_iter().cloned().collect(),
4419    }
4420}
4421
4422fn transform_value<T: FloatLike>(value: &F<T>, value_transform: ObservableValueTransform) -> F<T> {
4423    match value_transform {
4424        ObservableValueTransform::Identity => value.clone(),
4425        ObservableValueTransform::Log10 => value.log10(),
4426    }
4427}
4428
4429fn value_in_range(value: f64, min: Option<f64>, max: Option<f64>) -> bool {
4430    if let Some(min) = min
4431        && value < min
4432    {
4433        return false;
4434    }
4435
4436    if let Some(max) = max {
4437        value <= max
4438    } else {
4439        true
4440    }
4441}
4442
4443fn discrete_value_in_range(value: isize, min: Option<isize>, max: Option<isize>) -> bool {
4444    if let Some(min) = min
4445        && value < min
4446    {
4447        return false;
4448    }
4449
4450    if let Some(max) = max {
4451        value <= max
4452    } else {
4453        true
4454    }
4455}
4456
4457fn combined_entry_weight<T: FloatLike>(
4458    event: &GenericEvent<T>,
4459    entry: &ObservableEntry<T>,
4460) -> Complex<F<T>> {
4461    event.weight.clone() * entry.weight_modifier.clone()
4462}
4463
4464impl ObservablePhase {
4465    fn project<T: FloatLike>(&self, weight: &Complex<F<T>>) -> F<T> {
4466        match self {
4467            ObservablePhase::Real => weight.re.clone(),
4468            ObservablePhase::Imag => weight.im.clone(),
4469        }
4470    }
4471}
4472
4473#[cfg(test)]
4474mod tests {
4475    use super::{
4476        ContinuousHistogramSettings, DiscreteBinDomainSettings, DiscreteBinOrdering,
4477        DiscreteRangeSelectorSettings, EntrySelection, HistogramAccumulatorState,
4478        HistogramBinSnapshot, HistogramProcessInfo, HistogramSettings, HistogramSnapshot,
4479        HistogramSnapshotKind, HistogramStatisticsSnapshot, JetClusteringSettings, ObservablePhase,
4480        ObservableSettings, ObservableValueTransform, QuantitySettings, SelectorDefinitionSettings,
4481        SelectorSettings, resolve_graph_group_context,
4482    };
4483    use schemars::schema_for;
4484    use serde_json::Value as JsonValue;
4485    use std::collections::BTreeMap;
4486    use std::fs;
4487
4488    fn sample_histogram_snapshot() -> HistogramSnapshot {
4489        HistogramSnapshot {
4490            kind: HistogramSnapshotKind::Continuous,
4491            title: "top_pt".to_string(),
4492            type_description: "AL".to_string(),
4493            phase: ObservablePhase::Real,
4494            value_transform: ObservableValueTransform::Identity,
4495            supports_misbinning_mitigation: true,
4496            x_min: Some(0.0),
4497            x_max: Some(10.0),
4498            sample_count: 3,
4499            log_x_axis: false,
4500            log_y_axis: true,
4501            discrete_min_bin_id: None,
4502            discrete_ordering: None,
4503            bins: vec![HistogramBinSnapshot {
4504                x_min: Some(0.0),
4505                x_max: Some(10.0),
4506                bin_id: None,
4507                label: None,
4508                entry_count: 3,
4509                sum_weights: 3.75,
4510                sum_weights_squared: 5.625,
4511                mitigated_fill_count: 2,
4512            }],
4513            underflow_bin: HistogramBinSnapshot {
4514                x_min: None,
4515                x_max: Some(0.0),
4516                bin_id: None,
4517                label: None,
4518                entry_count: 1,
4519                sum_weights: 1.5,
4520                sum_weights_squared: 2.25,
4521                mitigated_fill_count: 0,
4522            },
4523            overflow_bin: HistogramBinSnapshot {
4524                x_min: Some(10.0),
4525                x_max: None,
4526                bin_id: None,
4527                label: None,
4528                entry_count: 2,
4529                sum_weights: 0.5,
4530                sum_weights_squared: 0.25,
4531                mitigated_fill_count: 1,
4532            },
4533            statistics: HistogramStatisticsSnapshot {
4534                in_range_entry_count: 3,
4535                nan_value_count: 3,
4536                mitigated_pair_count: 4,
4537            },
4538        }
4539    }
4540
4541    #[test]
4542    fn jet_clustering_settings_normalize_explicit_clustered_pdgs() {
4543        let settings = JetClusteringSettings {
4544            clustered_pdgs: Some(vec![21, -1, 21, 1, -1]),
4545            ..JetClusteringSettings::default()
4546        };
4547        let resolved = settings
4548            .resolve(None)
4549            .expect("explicit clustered_pdgs should not require a model");
4550        assert_eq!(resolved.clustered_pdgs, vec![-1, 1, 21]);
4551    }
4552
4553    #[test]
4554    fn jet_clustering_settings_require_model_for_default_clustered_pdgs() {
4555        let error = JetClusteringSettings::default()
4556            .resolve(None)
4557            .expect_err("default clustered_pdgs should require model context");
4558        assert!(
4559            error
4560                .to_string()
4561                .contains("Cannot resolve default clustered_pdgs without a model")
4562        );
4563    }
4564
4565    #[test]
4566    fn jet_clustering_settings_reject_invalid_minimum_pt() {
4567        for min_jpt in [-1.0, f64::NAN, f64::INFINITY] {
4568            let error = JetClusteringSettings {
4569                min_jpt,
4570                clustered_pdgs: Some(Vec::new()),
4571                ..JetClusteringSettings::default()
4572            }
4573            .resolve(None)
4574            .expect_err("invalid minimum jet transverse momentum must be rejected");
4575            assert!(error.to_string().contains("finite and nonnegative"));
4576        }
4577    }
4578
4579    #[test]
4580    fn histogram_snapshot_json_round_trip() {
4581        let snapshot = sample_histogram_snapshot();
4582
4583        let file_path = std::env::temp_dir().join(format!(
4584            "gammaloop_histogram_snapshot_{}_{}.json",
4585            std::process::id(),
4586            std::time::SystemTime::now()
4587                .duration_since(std::time::UNIX_EPOCH)
4588                .unwrap()
4589                .as_nanos()
4590        ));
4591
4592        snapshot.to_json_file(&file_path).unwrap();
4593        let loaded = HistogramSnapshot::from_json_file(&file_path).unwrap();
4594        let _ = fs::remove_file(&file_path);
4595
4596        assert_eq!(loaded, snapshot);
4597    }
4598
4599    #[test]
4600    fn continuous_histogram_checkpoint_resumes_worker_merges() {
4601        let mut uninterrupted = HistogramAccumulatorState::continuous(
4602            "leading_jet_pt_hist".to_string(),
4603            "AL".to_string(),
4604            ObservablePhase::Real,
4605            ObservableValueTransform::Identity,
4606            0.0,
4607            1000.0,
4608            false,
4609            true,
4610            8,
4611        );
4612        for sample in [
4613            &[
4614                (5.0, 1.5),
4615                (145.0, 0.5),
4616                (-1.0, -0.75),
4617                (1000.0, 2.0),
4618                (f64::NAN, 1.0),
4619            ][..],
4620            &[(5.0, -0.5), (145.0, 1.25)][..],
4621        ] {
4622            uninterrupted.fill_continuous_sample(sample).unwrap();
4623        }
4624        uninterrupted.update_results();
4625        let checkpoint = uninterrupted.snapshot();
4626        let loaded: HistogramSnapshot =
4627            serde_json::from_slice(&serde_json::to_vec(&checkpoint).unwrap()).unwrap();
4628        let mut resumed = loaded.into_accumulator_state();
4629        assert_eq!(resumed.snapshot(), checkpoint);
4630
4631        let mut worker = uninterrupted.cleared_clone();
4632        worker
4633            .fill_continuous_sample(&[(260.0, 2.0), (145.0, -0.5), (-2.0, 0.25)])
4634            .unwrap();
4635        uninterrupted = uninterrupted.merged_with(&worker).unwrap();
4636        resumed.merge_in_place(&mut worker).unwrap();
4637        uninterrupted.update_results();
4638        resumed.update_results();
4639        assert_eq!(resumed.snapshot(), uninterrupted.snapshot());
4640    }
4641
4642    #[test]
4643    fn continuous_histogram_checkpoint_preserves_explicit_label_guard() {
4644        let mut checkpoint = sample_histogram_snapshot();
4645        let mut unlabeled = checkpoint.clone().into_accumulator_state();
4646        checkpoint.bins[0].label = Some("region".to_string());
4647        let loaded: HistogramSnapshot =
4648            serde_json::from_slice(&serde_json::to_vec(&checkpoint).unwrap()).unwrap();
4649        let mut labeled = loaded.into_accumulator_state();
4650        assert_eq!(labeled.bin_labels, vec![Some("region".to_string())]);
4651        assert!(unlabeled.merge_in_place(&mut labeled).is_err());
4652    }
4653
4654    #[test]
4655    fn discrete_histogram_checkpoint_retains_ordering_and_labels() {
4656        let mut uninterrupted = HistogramAccumulatorState::discrete(
4657            "jet_count".to_string(),
4658            "AL".to_string(),
4659            ObservablePhase::Real,
4660            0,
4661            2,
4662            DiscreteBinOrdering::ValueDescending,
4663            true,
4664            vec![Some("zero".to_string()), None, Some("two".to_string())],
4665        )
4666        .unwrap();
4667        for sample in [
4668            &[(0, 1.0), (1, 3.0), (2, 2.0), (-1, -0.5), (3, 0.25)][..],
4669            &[(0, 0.5), (2, -1.0)][..],
4670        ] {
4671            uninterrupted.fill_discrete_sample(sample).unwrap();
4672        }
4673        uninterrupted.update_results();
4674        let checkpoint = uninterrupted.snapshot();
4675        assert_eq!(checkpoint.bins[0].bin_id, Some(1));
4676        let loaded: HistogramSnapshot =
4677            serde_json::from_slice(&serde_json::to_vec(&checkpoint).unwrap()).unwrap();
4678        let mut resumed = loaded.into_accumulator_state();
4679        assert_eq!(resumed.snapshot(), checkpoint);
4680        assert_eq!(resumed.bin_labels, uninterrupted.bin_labels);
4681        assert_eq!(resumed.discrete_ordering, uninterrupted.discrete_ordering);
4682
4683        let mut worker = uninterrupted.cleared_clone();
4684        worker.fill_discrete_sample(&[(2, 4.0), (0, -0.5)]).unwrap();
4685        uninterrupted = uninterrupted.merged_with(&worker).unwrap();
4686        resumed.merge_in_place(&mut worker).unwrap();
4687        uninterrupted.update_results();
4688        resumed.update_results();
4689        assert_eq!(resumed.snapshot(), uninterrupted.snapshot());
4690    }
4691
4692    #[test]
4693    fn histogram_snapshot_rescale_scales_weight_sums_only() {
4694        let snapshot = sample_histogram_snapshot();
4695        let scaled = snapshot.rescaled(2.0);
4696
4697        assert_eq!(scaled.sample_count, snapshot.sample_count);
4698        assert_eq!(scaled.statistics, snapshot.statistics);
4699        assert_eq!(scaled.bins[0].entry_count, snapshot.bins[0].entry_count);
4700        assert_eq!(
4701            scaled.bins[0].mitigated_fill_count,
4702            snapshot.bins[0].mitigated_fill_count
4703        );
4704        assert_eq!(scaled.bins[0].sum_weights, 7.5);
4705        assert_eq!(scaled.bins[0].sum_weights_squared, 22.5);
4706        assert_eq!(scaled.underflow_bin.sum_weights, 3.0);
4707        assert_eq!(scaled.underflow_bin.sum_weights_squared, 9.0);
4708        assert_eq!(scaled.overflow_bin.sum_weights, 1.0);
4709        assert_eq!(scaled.overflow_bin.sum_weights_squared, 1.0);
4710        assert_eq!(
4711            scaled.bins[0].average(scaled.sample_count),
4712            snapshot.bins[0].average(snapshot.sample_count) * 2.0
4713        );
4714        assert_eq!(
4715            scaled.bins[0].error(scaled.sample_count),
4716            snapshot.bins[0].error(snapshot.sample_count) * 2.0
4717        );
4718    }
4719
4720    #[test]
4721    fn histogram_snapshot_hwu_header_uses_type_description() {
4722        let mut snapshot = sample_histogram_snapshot();
4723        snapshot.type_description = "SB".to_string();
4724
4725        let mut output = Vec::new();
4726        snapshot.write_hwu_block(&mut output).unwrap();
4727        let output = String::from_utf8(output).unwrap();
4728
4729        assert!(output.contains("|TYPE@SB\""), "{output}");
4730    }
4731
4732    #[test]
4733    fn observable_settings_infer_discrete_histogram_from_domain() {
4734        let settings: ObservableSettings = toml::from_str(
4735            r#"
4736quantity = "integral"
4737domain = { type = "single_bin" }
4738"#,
4739        )
4740        .unwrap();
4741
4742        let HistogramSettings::Discrete(histogram) = settings.histogram else {
4743            panic!("expected discrete histogram");
4744        };
4745        assert_eq!(histogram.domain, DiscreteBinDomainSettings::SingleBin);
4746    }
4747
4748    #[test]
4749    fn observable_settings_serialize_flat_histogram_fields() {
4750        let settings = ObservableSettings {
4751            quantity: "integral".to_string(),
4752            selections: vec!["graph_cut".to_string()],
4753            entry_selection: super::EntrySelection::All,
4754            entry_index: 0,
4755            value_transform: ObservableValueTransform::Identity,
4756            phase: ObservablePhase::Real,
4757            misbinning_max_normalized_distance: None,
4758            histogram: HistogramSettings::Continuous(ContinuousHistogramSettings {
4759                x_min: 0.0,
4760                x_max: 1.0,
4761                n_bins: 1,
4762                log_x_axis: false,
4763                log_y_axis: true,
4764                title: Some("xs".to_string()),
4765                type_description: "AL".to_string(),
4766            }),
4767        };
4768
4769        let serialized = toml::to_string(&settings).unwrap();
4770        assert!(serialized.contains("kind = \"continuous\""));
4771        assert!(serialized.contains("quantity = \"integral\""));
4772        assert!(serialized.contains("n_bins = 1"));
4773        assert!(!serialized.contains("histogram"));
4774    }
4775
4776    #[test]
4777    fn observable_settings_schema_is_flat() {
4778        let schema = serde_json::to_value(schema_for!(ObservableSettings)).unwrap();
4779        let properties = schema
4780            .get("properties")
4781            .and_then(JsonValue::as_object)
4782            .expect("observable schema properties");
4783        assert!(properties.contains_key("kind"));
4784        assert!(properties.contains_key("quantity"));
4785        assert!(properties.contains_key("domain"));
4786        assert!(!properties.contains_key("histogram"));
4787    }
4788
4789    #[test]
4790    fn selector_settings_schema_is_flat() {
4791        let schema = serde_json::to_string(&schema_for!(SelectorSettings)).unwrap();
4792        assert!(schema.contains("\"selector\""));
4793        assert!(schema.contains("\"quantity\""));
4794        assert!(!schema.contains("\"histogram\""));
4795    }
4796
4797    #[test]
4798    fn selector_settings_serialize_flat_discrete_range() {
4799        let settings = SelectorSettings {
4800            quantity: "graph_id".to_string(),
4801            active: false,
4802            entry_selection: super::EntrySelection::All,
4803            entry_index: 0,
4804            selector: SelectorDefinitionSettings::DiscreteRange(DiscreteRangeSelectorSettings {
4805                min: Some(3),
4806                max: Some(3),
4807            }),
4808        };
4809
4810        let serialized = toml::to_string(&settings).unwrap();
4811        assert!(serialized.contains("selector = \"discrete_range\""));
4812        assert!(serialized.contains("active = false"));
4813        assert!(serialized.contains("min = 3"));
4814        assert!(!serialized.contains("selector = {"));
4815    }
4816
4817    #[test]
4818    fn selector_settings_deserialize_flat_discrete_range() {
4819        let settings: SelectorSettings = toml::from_str(
4820            r#"
4821quantity = "graph_id"
4822active = false
4823selector = "discrete_range"
4824min = 0
4825max = 0
4826"#,
4827        )
4828        .unwrap();
4829
4830        assert_eq!(settings.quantity, "graph_id");
4831        assert!(!settings.active);
4832        match settings.selector {
4833            SelectorDefinitionSettings::DiscreteRange(selector) => {
4834                assert_eq!(selector.min, Some(0));
4835                assert_eq!(selector.max, Some(0));
4836            }
4837            other => panic!("expected discrete-range selector, got {other:?}"),
4838        }
4839    }
4840
4841    #[test]
4842    fn discrete_histogram_ordering_changes_presentation_only() {
4843        let mut histogram = HistogramAccumulatorState::discrete(
4844            "jet_count".to_string(),
4845            "AL".to_string(),
4846            ObservablePhase::Real,
4847            0,
4848            1,
4849            DiscreteBinOrdering::AscendingBinId,
4850            true,
4851            vec![Some("zero".to_string()), Some("one".to_string())],
4852        )
4853        .unwrap();
4854        histogram
4855            .fill_discrete_sample(&[(0, 1.0), (1, 3.0)])
4856            .unwrap();
4857        histogram.update_results();
4858
4859        let ascending = histogram.snapshot();
4860        assert_eq!(ascending.bins[0].bin_id, Some(0));
4861        assert_eq!(ascending.bins[1].bin_id, Some(1));
4862        assert_eq!(ascending.discrete_min_bin_id, Some(0));
4863
4864        histogram
4865            .change_bin_ordering(DiscreteBinOrdering::ValueDescending)
4866            .unwrap();
4867        let reordered = histogram.snapshot();
4868        assert_eq!(reordered.bins[0].bin_id, Some(1));
4869        assert_eq!(reordered.bins[1].bin_id, Some(0));
4870        assert_eq!(reordered.bins[0].label.as_deref(), Some("one"));
4871        assert_eq!(reordered.bins[1].label.as_deref(), Some("zero"));
4872        assert_eq!(reordered.rebin(99).unwrap(), reordered);
4873    }
4874
4875    #[test]
4876    fn discrete_histogram_constructor_rejects_invalid_range() {
4877        let err = HistogramAccumulatorState::discrete(
4878            "bad_range".to_string(),
4879            "AL".to_string(),
4880            ObservablePhase::Real,
4881            3,
4882            1,
4883            DiscreteBinOrdering::AscendingBinId,
4884            true,
4885            Vec::new(),
4886        )
4887        .unwrap_err();
4888
4889        assert!(err.to_string().contains("invalid discrete histogram range"));
4890    }
4891
4892    #[test]
4893    fn resolve_graph_group_context_uses_selector_quantity_type() {
4894        let quantities = BTreeMap::from([("my_graph".to_string(), QuantitySettings::GraphId {})]);
4895        let selectors = BTreeMap::from([(
4896            "graph_only".to_string(),
4897            SelectorSettings {
4898                quantity: "my_graph".to_string(),
4899                active: false,
4900                entry_selection: EntrySelection::All,
4901                entry_index: 0,
4902                selector: SelectorDefinitionSettings::DiscreteRange(
4903                    DiscreteRangeSelectorSettings {
4904                        min: Some(1),
4905                        max: Some(1),
4906                    },
4907                ),
4908            },
4909        )]);
4910        let process_info = HistogramProcessInfo {
4911            graph_names: vec!["g0".to_string(), "g1".to_string()],
4912            graph_to_group_id: vec![0, 2],
4913            graph_group_master_names: vec![
4914                "group0".to_string(),
4915                "group1".to_string(),
4916                "group2".to_string(),
4917            ],
4918            orientation_labels_by_group: vec![Vec::new(), Vec::new(), Vec::new()],
4919            sampling_channel_labels_by_group: vec![Vec::new(), Vec::new(), Vec::new()],
4920        };
4921
4922        let resolved = resolve_graph_group_context(
4923            "obs",
4924            &["graph_only".to_string()],
4925            &selectors,
4926            &quantities,
4927            Some(&process_info),
4928        )
4929        .unwrap();
4930
4931        assert_eq!(resolved, Some(2));
4932    }
4933
4934    #[test]
4935    fn resolve_graph_group_context_rejects_negative_singleton_values() {
4936        let quantities =
4937            BTreeMap::from([("my_group".to_string(), QuantitySettings::GraphGroupId {})]);
4938        let selectors = BTreeMap::from([(
4939            "negative_group".to_string(),
4940            SelectorSettings {
4941                quantity: "my_group".to_string(),
4942                active: false,
4943                entry_selection: EntrySelection::All,
4944                entry_index: 0,
4945                selector: SelectorDefinitionSettings::DiscreteRange(
4946                    DiscreteRangeSelectorSettings {
4947                        min: Some(-1),
4948                        max: Some(-1),
4949                    },
4950                ),
4951            },
4952        )]);
4953        let process_info = HistogramProcessInfo {
4954            graph_names: Vec::new(),
4955            graph_to_group_id: Vec::new(),
4956            graph_group_master_names: vec!["group0".to_string()],
4957            orientation_labels_by_group: vec![Vec::new()],
4958            sampling_channel_labels_by_group: vec![Vec::new()],
4959        };
4960
4961        let err = resolve_graph_group_context(
4962            "obs",
4963            &["negative_group".to_string()],
4964            &selectors,
4965            &quantities,
4966            Some(&process_info),
4967        )
4968        .unwrap_err();
4969
4970        assert!(err.to_string().contains("must be non-negative"));
4971    }
4972}