1use std::{
2 collections::{BTreeMap, BTreeSet},
3 fmt::Display,
4};
5
6use crate::cff::Esurface;
7use bincode_trait_derive::{Decode, Encode};
8use eyre::{Result, ensure};
9use linnet::half_edge::involution::EdgeVec;
10use schemars::JsonSchema;
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12use spenso::algebra::{algebraic_traits::IsZero, complex::Complex};
13use tracing::warn;
14use typed_index_collections::TiVec;
15
16use crate::{
17 DependentMomentaConstructor, GammaLoopContext,
18 graph::LoopMomentumBasis,
19 integrands::process::SamplingMapDefinition,
20 integrands::process::evaluators::EvaluatorMethod,
21 momentum::{Helicity, RotationMethod, sample::ExternalIndex, signature::SignatureLike},
22 observables::ObservableFileFormat,
23 settings::runtime::kinematic::{Externals, improvement::generate_default_momenta},
24 utils::{
25 ApproxEq, DEFAULT_ESURFACE_EXISTENCE_THRESHOLD, F, FloatLike, format_uncertainty,
26 serde_utils::{
27 _default_rotation_axis, _default_stability_levels, IsDefault,
28 deserialize_nonnegative_finite_f64, is_default_esurface_existence_threshold,
29 is_default_rotation_axis, is_default_stability_levels, is_false, is_float, is_true,
30 is_u64, is_usize, show_defaults_helper,
31 },
32 },
33};
34use symbolica::domains::{float::Real, integer::Integer, rational::Rational};
35
36use super::{
37 RuntimeSettings,
38 global::{OrientationPattern, RepresentationMode},
39};
40
41#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, Encode, Decode, JsonSchema)]
43#[serde(default)]
44pub struct RuntimeModelSettings {
45 #[serde(flatten, skip_serializing_if = "IsDefault::is_default")]
46 pub external_parameters: BTreeMap<String, (F<f64>, F<f64>)>,
47}
48
49#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
51#[serde(default, deny_unknown_fields)]
52pub struct SubtractionSettings {
53 #[serde(skip_serializing_if = "IsDefault::is_default")]
55 pub local_ct_settings: LocalCounterTermSettings,
56 #[serde(skip_serializing_if = "IsDefault::is_default")]
58 pub integrated_ct_settings: IntegratedCounterTermSettings,
59 #[serde(skip_serializing_if = "IsDefault::is_default")]
61 pub overlap_settings: OverlapSettings,
62 #[serde(
65 deserialize_with = "deserialize_nonnegative_finite_f64",
66 skip_serializing_if = "is_default_esurface_existence_threshold"
67 )]
68 #[schemars(range(min = 0.0))]
69 pub esurface_existence_threshold: f64,
70 #[serde(
75 deserialize_with = "deserialize_nonnegative_finite_f64",
76 skip_serializing_if = "is_float::<64>"
77 )]
78 #[schemars(range(min = 0.0))]
79 pub radial_root_residual_tolerance: f64,
80 #[serde(skip_serializing_if = "is_false")]
82 pub disable_threshold_subtraction: bool,
83}
84
85impl Default for SubtractionSettings {
86 fn default() -> Self {
87 Self {
88 local_ct_settings: LocalCounterTermSettings::default(),
89 integrated_ct_settings: IntegratedCounterTermSettings::default(),
90 overlap_settings: OverlapSettings::default(),
91 esurface_existence_threshold: DEFAULT_ESURFACE_EXISTENCE_THRESHOLD,
92 radial_root_residual_tolerance: 64.0,
93 disable_threshold_subtraction: false,
94 }
95 }
96}
97
98#[derive(Copy, Clone)]
99pub struct LockedRuntimeSettings<'a>(&'a RuntimeSettings);
100impl<'a> From<&'a RuntimeSettings> for LockedRuntimeSettings<'a> {
101 fn from(value: &'a RuntimeSettings) -> Self {
102 LockedRuntimeSettings(value)
103 }
104}
105
106impl<'a> From<LockedRuntimeSettings<'a>> for RuntimeSettings {
107 fn from(value: LockedRuntimeSettings) -> Self {
108 value.0.clone()
109 }
110}
111
112impl<'a> LockedRuntimeSettings<'a> {
113 pub(crate) fn helicities(&self) -> &[Helicity] {
114 self.0.kinematics.externals.get_helicities()
115 }
116
117 pub(crate) fn into_with_modified_kinematics(
119 self,
120 external_signature: &SignatureLike<ExternalIndex>,
121 external_masses: &TiVec<ExternalIndex, F<f64>>,
122 ) -> Result<RuntimeSettings> {
123 if external_signature.is_empty() {
124 Ok(self.into())
125 } else {
126 match &self.0.kinematics.externals {
127 Externals::Constant {
128 momenta,
129 helicities,
130 ..
131 } => {
132 if momenta.is_empty() && helicities.is_empty() {
133 warn!(
134 "No external kinematics were provided; using default-generated external momenta and helicities."
135 );
136 let new_externals = generate_default_momenta(
137 external_masses,
138 external_signature,
139 &F(self.0.kinematics.e_cm),
140 )?;
141
142 let mut new_settigns = self.0.clone();
143 new_settigns.kinematics.externals = new_externals;
144 Ok(new_settigns)
145 } else {
146 Ok(self.into())
147 }
148 }
149 }
150 }
151 }
152
153 pub(crate) fn existence_check(
154 &self,
155 esurface: &Esurface,
156 masses: &EdgeVec<F<f64>>,
157 external_signature: &SignatureLike<ExternalIndex>,
158 lmb: &LoopMomentumBasis,
159 esurface_existence_threshold: f64,
160 ) -> bool {
161 let dependent_momenta_constructor =
162 DependentMomentaConstructor::Amplitude(external_signature);
163
164 esurface
165 .classify_existence(
166 &self
167 .0
168 .kinematics
169 .externals
170 .get_dependent_externals(dependent_momenta_constructor)
171 .unwrap(),
172 lmb,
173 masses,
174 &F(self.0.kinematics.e_cm),
175 &F(esurface_existence_threshold),
176 )
177 .is_existing()
178 }
179}
180
181#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
182#[derive(
183 Debug, Copy, Clone, Deserialize, Serialize, Encode, Decode, PartialEq, Eq, JsonSchema, Default,
184)]
185#[serde(rename_all = "snake_case")]
186pub enum IntegralUnit {
187 #[default]
188 Auto,
189 Picobarn,
190 Femtobarn,
191 Attobarn,
192 Millibarn,
193 None,
194}
195
196impl IntegralUnit {
197 pub(crate) fn resolve_for_cross_section(self, n_initial_state_particles: usize) -> Self {
198 match self {
199 Self::Auto if n_initial_state_particles > 1 => Self::Picobarn,
200 Self::Auto => Self::None,
201 explicit => explicit,
202 }
203 }
204
205 pub(crate) fn relative_to_picobarn_factor<T: FloatLike>(self, one: &F<T>) -> Option<F<T>> {
206 match self {
207 Self::Picobarn => Some(one.one()),
208 Self::Femtobarn => Some(one.from_i64(1_000)),
209 Self::Attobarn => Some(one.from_i64(1_000_000)),
210 Self::Millibarn => Some(one.one() / one.from_i64(1_000_000_000)),
211 Self::None => None,
212 Self::Auto => unreachable!("integral unit must be resolved before conversion"),
213 }
214 }
215}
216
217#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
218#[derive(Debug, Clone, Deserialize, Serialize, Encode, Decode, PartialEq, JsonSchema)]
219#[trait_decode(trait= GammaLoopContext)]
220#[serde(default, deny_unknown_fields)]
221pub struct GeneralSettings {
222 #[serde(skip_serializing_if = "IsDefault::is_default")]
224 pub evaluator_method: EvaluatorMethod,
225 #[serde(skip_serializing_if = "IsDefault::is_default")]
227 pub orientation_pat: OrientationPattern,
228 #[serde(skip_serializing_if = "is_false")]
230 pub load_compiled_cff: bool,
231 #[serde(skip_serializing_if = "is_false")]
233 pub enable_cache: bool,
234 #[serde(skip_serializing_if = "is_false")]
236 pub debug_cache: bool,
237 #[serde(skip_serializing_if = "is_float::<1000>")]
239 pub m_uv: f64,
240 #[serde(skip_serializing_if = "is_float::<1000>")]
242 pub renormalization_localization_scale: f64,
243 #[serde(skip_serializing_if = "is_float::<1000>")]
245 pub mu_r: f64,
246 #[serde(skip_serializing_if = "is_float::<1>")]
248 pub numerator_sampling_scale: f64,
249 #[serde(skip_serializing_if = "is_float::<1>")]
251 pub inverse_temperature: f64,
252 #[serde(skip_serializing_if = "IsDefault::is_default")]
254 pub additional_param_values: Vec<f64>,
255 #[serde(skip_serializing_if = "IsDefault::is_default")]
257 pub integral_unit: IntegralUnit,
258 #[serde(skip_serializing_if = "is_false")]
260 pub disable_flux_factor: bool,
261 #[serde(skip_serializing_if = "is_false")]
264 pub generate_events: bool,
265 #[serde(skip_serializing_if = "is_false")]
267 pub store_additional_weights_in_event: bool,
268}
269
270impl Default for GeneralSettings {
271 fn default() -> Self {
272 Self {
273 evaluator_method: EvaluatorMethod::default(),
274 load_compiled_cff: false,
275 enable_cache: false,
276 debug_cache: false,
277 orientation_pat: OrientationPattern::default(),
278 m_uv: 1000.0,
279 renormalization_localization_scale: 1000.0,
280 mu_r: 1000.0,
281 numerator_sampling_scale: 1.0,
282 inverse_temperature: 1.0,
283 additional_param_values: vec![],
284 integral_unit: IntegralUnit::Auto,
285 disable_flux_factor: false,
286 generate_events: false,
287 store_additional_weights_in_event: false,
288 }
289 }
290}
291
292impl GeneralSettings {
293 pub(crate) fn mu_r_sq(&self) -> f64 {
294 self.mu_r * self.mu_r
295 }
296}
297
298#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
299#[derive(
300 Debug, Copy, Clone, PartialEq, Deserialize, Default, Serialize, Encode, Decode, JsonSchema,
301)]
302#[serde(deny_unknown_fields)]
304pub enum IntegratedPhase {
305 #[serde(rename = "real")]
306 #[default]
307 Real,
308 #[serde(rename = "imag")]
309 Imag,
310 #[serde(rename = "both")]
311 Both,
312}
313
314pub mod kinematic;
315
316#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
317#[derive(Debug, Clone, Deserialize, Serialize, Encode, Decode, PartialEq, JsonSchema)]
318#[serde(default, deny_unknown_fields)]
319pub struct ObservablesOutputSettings {
320 #[serde(
322 default = "default_observable_output_formats",
323 skip_serializing_if = "is_default_observable_output_formats"
324 )]
325 pub format: Vec<ObservableFileFormat>,
326}
327
328fn default_observable_output_formats() -> Vec<ObservableFileFormat> {
329 vec![ObservableFileFormat::Json]
330}
331
332fn is_default_observable_output_formats(formats: &Vec<ObservableFileFormat>) -> bool {
333 show_defaults_helper(formats.as_slice() == default_observable_output_formats().as_slice())
334}
335
336impl Default for ObservablesOutputSettings {
337 fn default() -> Self {
338 Self {
339 format: default_observable_output_formats(),
340 }
341 }
342}
343
344impl ObservablesOutputSettings {
345 pub(crate) fn resolved_formats(&self) -> Vec<ObservableFileFormat> {
346 let mut resolved_formats = Vec::new();
347 for format in &self.format {
348 if *format == ObservableFileFormat::None || resolved_formats.contains(format) {
349 continue;
350 }
351 resolved_formats.push(*format);
352 }
353 resolved_formats
354 }
355}
356
357#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
358#[derive(Debug, Clone, Deserialize, Serialize, Encode, Decode, PartialEq, JsonSchema)]
359#[serde(default, deny_unknown_fields)]
360pub struct IntegratorSettings {
361 #[serde(skip_serializing_if = "is_usize::<64>")]
363 pub n_bins: usize,
364 #[serde(skip_serializing_if = "IsDefault::is_default")]
366 pub bin_number_evolution: Option<Vec<usize>>,
367 #[serde(skip_serializing_if = "is_usize::<1000>")]
369 pub min_samples_for_update: usize,
370 #[serde(skip_serializing_if = "is_usize::<100000>")]
372 pub n_start: usize,
373 #[serde(skip_serializing_if = "is_usize::<10000>")]
375 pub n_increase: usize,
376 #[serde(skip_serializing_if = "is_usize::<10000000000>")]
378 pub n_max: usize,
379 #[serde(skip_serializing_if = "IsDefault::is_default")]
381 pub target_relative_accuracy: Option<f64>,
382 #[serde(skip_serializing_if = "IsDefault::is_default")]
384 pub target_absolute_accuracy: Option<f64>,
385 #[serde(skip_serializing_if = "IsDefault::is_default")]
387 pub integrated_phase: IntegratedPhase,
388 #[serde(skip_serializing_if = "is_float::<1>")]
390 pub discrete_dim_learning_rate: f64,
391 #[serde(skip_serializing_if = "is_float::<1>")]
393 pub continuous_dim_learning_rate: f64,
394 #[serde(skip_serializing_if = "is_false")]
396 pub train_on_avg: bool,
397 #[serde(skip_serializing_if = "is_true")]
399 pub show_max_wgt_info: bool,
400 #[serde(skip_serializing_if = "is_float::<30>")]
402 pub max_prob_ratio: f64,
403 #[serde(skip_serializing_if = "is_u64::<69>")]
405 pub seed: u64,
406 #[serde(skip_serializing_if = "IsDefault::is_default")]
408 pub observables_output: ObservablesOutputSettings,
409}
410
411impl Default for IntegratorSettings {
412 fn default() -> Self {
413 Self {
414 n_bins: 64,
415 bin_number_evolution: None,
416 min_samples_for_update: 1000,
417 n_start: 100000,
418 n_increase: 10000,
419 n_max: 10000000000,
420 target_relative_accuracy: None,
421 target_absolute_accuracy: None,
422 integrated_phase: IntegratedPhase::default(),
423 discrete_dim_learning_rate: 1.0,
424 continuous_dim_learning_rate: 1.0,
425 train_on_avg: false,
426 show_max_wgt_info: true,
427 max_prob_ratio: 30.0,
428 seed: 69,
429 observables_output: ObservablesOutputSettings::default(),
430 }
431 }
432}
433
434#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
435#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Encode, Decode, JsonSchema)]
436#[serde(default, deny_unknown_fields)]
437pub struct ParameterizationSettings {
438 #[serde(skip_serializing_if = "IsDefault::is_default")]
439 pub mode: ParameterizationMode,
440 #[serde(skip_serializing_if = "IsDefault::is_default")]
441 pub mapping: ParameterizationMapping,
442 #[serde(skip_serializing_if = "is_float::<1>")]
443 pub b: f64,
444 #[serde(skip_serializing_if = "is_float::<1>")]
445 pub power: f64,
446 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
447 pub lmb_basis_ids: BTreeMap<String, Vec<usize>>,
448 #[serde(skip_serializing_if = "IsDefault::is_default")]
452 pub sampling_channels: SamplingChannelSelection,
453}
454
455impl Default for ParameterizationSettings {
456 fn default() -> Self {
457 Self {
458 b: 1.0,
459 power: 1.0,
460 mode: ParameterizationMode::default(),
461 mapping: ParameterizationMapping::default(),
462 lmb_basis_ids: BTreeMap::new(),
463 sampling_channels: SamplingChannelSelection::default(),
464 }
465 }
466}
467
468#[derive(Serialize, Deserialize, Default, Debug, Clone)]
469#[serde(default, deny_unknown_fields)]
470pub struct IntegralEstimate {
471 pub neval: usize,
472 pub real_zero: usize,
473 pub im_zero: usize,
474 pub result: Complex<F<f64>>,
475 pub error: Complex<F<f64>>,
476 pub real_chisq: F<f64>,
477 pub im_chisq: F<f64>,
478}
479
480impl Display for IntegralEstimate {
481 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
482 let real_formatted = if self.error.re.0.abs() > 0.0 && f.alternate() {
484 format_uncertainty(self.result.re, self.error.re)
485 } else {
486 match f.precision() {
488 Some(p) => format!("{:.prec$e}", self.result.re.0, prec = p),
489 None => format!("{:e}", self.result.re.0),
490 }
491 };
492
493 let im_formatted = if self.error.im.0.abs() > 0.0 && f.alternate() {
494 format_uncertainty(self.result.im, self.error.im)
495 } else {
496 match f.precision() {
498 Some(p) => format!("{:.prec$e}", self.result.im.0, prec = p),
499 None => format!("{:e}", self.result.im.0),
500 }
501 };
502
503 if self.result.im.0.abs() > 0.0 {
505 if f.alternate() {
506 write!(
507 f,
508 "{} + {}i (neval: {}, real_chisq: {:.3}, im_chisq: {:.3})",
509 real_formatted, im_formatted, self.neval, self.real_chisq.0, self.im_chisq.0
510 )
511 } else {
512 write!(f, "{} + {}i", real_formatted, im_formatted,)
513 }
514 } else if f.alternate() {
515 write!(
516 f,
517 "{} (neval: {}, real_chisq: {:.3})",
518 real_formatted, self.neval, self.real_chisq.0
519 )
520 } else {
521 write!(f, "{}", real_formatted)
522 }
523 }
524}
525
526impl IntegralEstimate {
527 pub fn is_compatible_with_target(&self, target: Complex<F<f64>>, sigma: i8) -> bool {
528 let res_norm = self.result.norm().re;
529 let tolerance = if res_norm.is_zero() {
530 self.error.norm().re
531 } else {
532 (self.error).norm().re * F(sigma as f64) / res_norm
533 };
534
535 if tolerance.0 > 0.1 {
536 warn!("Tolerance larger than 10%! {}", tolerance)
537 }
538 self.result.approx_eq(&target, &tolerance)
540 }
541
542 pub fn is_compatible_with_result(&self, other: &Self, sigma: i8) -> bool {
543 let combined_error = Complex::new(
544 (self.error.re * self.error.re + other.error.re * other.error.re).sqrt(),
545 (self.error.im * self.error.im + other.error.im * other.error.im).sqrt(),
546 );
547 let delta = self.result - other.result;
548 let delta_norm = delta.norm().re;
549 let tolerance = if delta_norm.is_zero() {
550 combined_error.norm().re
551 } else {
552 combined_error.norm().re * F(sigma as f64) / delta_norm
553 };
554
555 if tolerance.0 > 0.1 {
556 warn!("Tolerance larger than 10%! {}", tolerance)
557 }
558
559 self.result.approx_eq(&other.result, &tolerance)
560 }
561}
562
563#[derive(Serialize, Deserialize, Default, Debug, Clone)]
564#[serde(default, deny_unknown_fields)]
565pub struct IntegrationTableComponentResult {
566 pub component: String,
567 pub value: F<f64>,
568 pub error: F<f64>,
569 pub relative_error_percent: Option<f64>,
570 pub chi_sq_per_dof: f64,
571 pub target_delta_sigma: Option<f64>,
572 pub target_delta_percent: Option<f64>,
573 pub max_weight_impact: f64,
574}
575
576#[derive(Serialize, Deserialize, Default, Debug, Clone)]
577#[serde(default, deny_unknown_fields)]
578pub struct IntegrationStatisticsSnapshot {
579 pub num_evals: usize,
580 pub average_total_time_seconds: f64,
581 pub average_parameterization_time_seconds: f64,
582 pub average_integrand_time_seconds: f64,
583 pub average_evaluator_time_seconds: f64,
584 pub average_observable_time_seconds: f64,
585 pub average_integrator_time_seconds: f64,
586 pub f64_percentage: f64,
587 pub f128_percentage: f64,
588 pub arb_percentage: f64,
589 pub nan_percentage: f64,
590 pub nan_or_unstable_percentage: f64,
591 pub generated_event_count: usize,
592 pub accepted_event_count: usize,
593 pub selection_efficiency_percentage: Option<f64>,
594}
595
596#[derive(Serialize, Deserialize, Default, Debug, Clone)]
597#[serde(default, deny_unknown_fields)]
598pub struct MaxWeightInfoEntry {
599 pub component: String,
600 pub sign: String,
601 pub max_eval: F<f64>,
602 pub coordinates: Option<String>,
603}
604
605#[derive(Serialize, Deserialize, Default, Debug, Clone)]
606#[serde(default, deny_unknown_fields)]
607pub struct DiscreteCoordinate {
608 pub axis_label: String,
609 pub bin_index: usize,
610 pub bin_label: Option<String>,
611}
612
613#[derive(Serialize, Deserialize, Default, Debug, Clone)]
614#[serde(default, deny_unknown_fields)]
615pub struct DiscreteBreakdownEntry {
616 pub bin_index: usize,
617 pub bin_label: Option<String>,
618 pub pdf: F<f64>,
619 pub value: F<f64>,
620 pub error: F<f64>,
621 pub chi_sq: F<f64>,
622 pub processed_samples: usize,
623}
624
625#[derive(Serialize, Deserialize, Default, Debug, Clone)]
626#[serde(default, deny_unknown_fields)]
627pub struct DiscreteBreakdown {
628 pub axis_label: String,
629 pub fixed_coordinates: Vec<DiscreteCoordinate>,
630 pub entries: Vec<DiscreteBreakdownEntry>,
631}
632
633#[derive(Serialize, Deserialize, Default, Debug, Clone)]
634#[serde(default, deny_unknown_fields)]
635pub struct ComponentDiscreteBreakdown {
636 pub re: Option<DiscreteBreakdown>,
637 pub im: Option<DiscreteBreakdown>,
638}
639
640#[derive(Serialize, Deserialize, Default, Debug, Clone)]
641#[serde(default, deny_unknown_fields)]
642pub struct AbsoluteIntegrationResult {
643 pub integral: IntegralEstimate,
644 pub table_results: Vec<IntegrationTableComponentResult>,
645 pub max_weight_info: Vec<MaxWeightInfoEntry>,
646 pub grid_breakdown: ComponentDiscreteBreakdown,
647}
648
649#[derive(Serialize, Deserialize, Default, Debug, Clone)]
650#[serde(default, deny_unknown_fields)]
651pub struct SlotIntegrationResult {
652 pub key: String,
653 pub process: String,
654 pub integrand: String,
655 pub target: Option<Complex<F<f64>>>,
656 pub integral: IntegralEstimate,
657 pub table_results: Vec<IntegrationTableComponentResult>,
658 pub integration_statistics: IntegrationStatisticsSnapshot,
659 pub max_weight_info: Vec<MaxWeightInfoEntry>,
660 pub grid_breakdown: ComponentDiscreteBreakdown,
661 pub absolute: AbsoluteIntegrationResult,
662}
663
664#[derive(Serialize, Deserialize, Default, Debug, Clone)]
665#[serde(default, deny_unknown_fields)]
666pub struct IntegrationResult {
667 pub slots: Vec<SlotIntegrationResult>,
668}
669
670impl IntegrationResult {
671 pub fn slot(&self, key: &str) -> Option<&SlotIntegrationResult> {
672 self.slots.iter().find(|slot| slot.key == key)
673 }
674
675 pub fn single_slot(&self) -> Option<&SlotIntegrationResult> {
676 (self.slots.len() == 1).then(|| &self.slots[0])
677 }
678
679 pub fn single_slot_integral(&self) -> Option<&IntegralEstimate> {
680 self.single_slot().map(|slot| &slot.integral)
681 }
682
683 pub fn is_compatible_with_target(&self, target: Complex<F<f64>>, n_sigma: i8) -> bool {
684 self.single_slot_integral()
685 .is_some_and(|integral| integral.is_compatible_with_target(target, n_sigma))
686 }
687}
688
689impl Display for IntegrationResult {
690 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
691 if let Some(slot) = self.single_slot() {
692 return slot.integral.fmt(f);
693 }
694
695 for (index, slot) in self.slots.iter().enumerate() {
696 if index > 0 {
697 writeln!(f)?;
698 }
699 write!(f, "{}: {}", slot.key, slot.integral)?;
700 }
701 Ok(())
702 }
703}
704
705#[cfg(test)]
706mod tests {
707 use super::*;
708 use crate::utils::serde_utils::ShowDefaultsGuard;
709 use spenso::algebra::complex::Complex;
710
711 #[test]
712 fn axis_angle_rotation_settings_roundtrip_and_reject_invalid_parameters() {
713 let setting: RotationSetting =
714 toml::from_str("type='axis_angle'\naxis=[1.0,2.0,2.0]\ncos_theta=0.0").unwrap();
715 setting.validate().unwrap();
716 assert_eq!(
717 toml::from_str::<RotationSetting>(&toml::to_string(&setting).unwrap()).unwrap(),
718 setting
719 );
720 assert_eq!(
721 serde_json::from_str::<RotationSetting>(&serde_json::to_string(&setting).unwrap())
722 .unwrap(),
723 setting
724 );
725 for axis in [[0.0; 3], [f64::NAN, 1.0, 0.0], [1.0, f64::INFINITY, 0.0]] {
726 assert!(
727 RotationSetting::AxisAngle {
728 axis,
729 cos_theta: 0.0
730 }
731 .validate()
732 .is_err()
733 );
734 }
735 for cos_theta in [f64::NAN, f64::INFINITY, -1.1, 1.1] {
736 assert!(
737 RotationSetting::AxisAngle {
738 axis: [1.0, 2.0, 2.0],
739 cos_theta
740 }
741 .validate()
742 .is_err()
743 );
744 }
745 for cos_theta in [-1.0, 0.0, 1.0] {
746 RotationSetting::AxisAngle {
747 axis: [1.0, 2.0, 2.0],
748 cos_theta,
749 }
750 .validate()
751 .unwrap();
752 }
753 assert!(
754 toml::from_str::<RotationSetting>("type='axis_angle'\naxis=[1.0,2.0]\ncos_theta=0.0")
755 .is_err()
756 );
757 assert!(
758 toml::from_str::<RotationSetting>(
759 "type='axis_angle'\naxis=[1.0,2.0,2.0]\ncos_theta=0.0\nangle=1.0"
760 )
761 .is_err()
762 );
763 }
764
765 #[test]
766 fn sampling_lu_h_profile_shorthand_and_table_share_one_definition() {
767 let shorthand: SamplingChannelDefinition =
768 toml::from_str("around='phase_space(cut(2,3))'\nradial_profile='lu_h'").unwrap();
769 let table: SamplingChannelDefinition = toml::from_str("around='phase_space(cut(2,3))'\nradial_profile={kind='lu_h',approximation='log_logistic',broad_fraction=0.02}").unwrap();
770 assert_eq!(shorthand, table);
771 assert_eq!(
772 shorthand.radial_profile,
773 Some(SamplingRadialProfile::default())
774 );
775 let exported = toml::to_string(&shorthand).unwrap();
776 assert_eq!(
777 toml::from_str::<SamplingChannelDefinition>(&exported).unwrap(),
778 shorthand
779 );
780 for invalid in [
781 "{kind='lu_h',broad_faction=0.1}",
782 "'unknown'",
783 "{kind='lu_h',approximation='exact'}",
784 ] {
785 assert!(
786 toml::from_str::<SamplingChannelDefinition>(&format!("radial_profile={invalid}"))
787 .is_err()
788 );
789 }
790 let _guard = ShowDefaultsGuard::new(true);
791 let json = serde_json::to_value(SamplingRadialProfile::default()).unwrap();
792 assert!(json.get("scale").is_some());
793 assert!(json.get("shape").is_some());
794 }
795
796 #[test]
797 fn h_function_normalizations_match_bessel_integrals_in_native_precision() {
798 use symbolica::{
799 atom::{Atom, AtomView},
800 coefficient::CoefficientView,
801 domains::float::{Float, RealLike},
802 function,
803 transcendental::bessel_k,
804 };
805
806 use crate::utils::{ArbPrec, SamplingFloat, f128};
807
808 const ORACLE_PRECISION: u32 = 1200;
809 let scaled_bessel_k = |twice_order: usize| {
811 let value = function!(
812 bessel_k(),
813 Atom::num((twice_order as i64, 2)),
814 Atom::num(Float::with_val(ORACLE_PRECISION, 2))
815 );
816 let AtomView::Num(number) = value.as_view() else {
817 panic!("bessel_k did not evaluate: {value}");
818 };
819 let CoefficientView::Float(real, _) = number.get_coeff_view() else {
820 panic!("bessel_k did not evaluate to a float: {value}");
821 };
822 real.to_float() * Float::with_val(ORACLE_PRECISION, 2).exp()
823 };
824 let sqrt_pi_half = std::f64::consts::PI.sqrt() / 2.0;
826 let poly = [
827 (None, sqrt_pi_half),
828 (Some(1), 0.841_568_215_070_771_4),
829 (Some(3), 1.033_476_847_068_688_6),
830 (Some(4), 1.329_340_388_179_137),
831 (Some(6), 2.880_237_507_721_463_7),
832 (Some(7), 4.783_566_971_347_609),
833 (Some(9), 16.225_745_976_182_285),
834 (Some(10), 32.735_007_058_911_25),
835 (Some(12), 155.837_465_922_583_42),
836 (Some(13), 364.658_500_356_566_04),
837 (Some(15), 2_257.637_553_015_473),
838 (Some(16), 5_939.804_418_537_864),
839 ];
840 let left_right = [
841 (Some(0), 2.066_953_694_137_377),
842 (Some(1), 1.683_136_430_141_542_8),
843 (Some(3), 3.750_090_124_278_92),
844 (Some(4), 9.567_133_942_695_218),
845 (Some(6), 139.373_101_752_153_5),
846 (Some(7), 729.317_000_713_132_1),
847 (Some(9), 32_336.242_742_929_753),
848 (Some(10), 263_205.217_049_469),
849 (Some(12), 2.427_503_717_893_097_5e7),
850 (Some(13), 2.694_265_921_644_289e8),
851 (Some(15), 4.261_555_045_314_143e10),
852 (Some(16), 5.998_751_004_871_322e11),
853 ];
854 let tabulated = std::iter::once((HFunction::Exponential, None, sqrt_pi_half))
855 .chain(poly.map(|(power, value)| (HFunction::PolyExponential, power, value)))
856 .chain(
857 left_right
858 .map(|(power, value)| (HFunction::PolyLeftRightExponential, power, value)),
859 );
860 fn check<T: FloatLike>(sigma: F<T>, settings: &HFunctionSettings, expected: &Float) {
861 for multiplier in [1, 2, 3] {
863 let scaled_sigma = &sigma * sigma.from_usize(multiplier);
864 let expected =
865 expected.clone() * Float::with_val(ORACLE_PRECISION, multiplier as u32);
866 let actual: Float = settings.normalization(&scaled_sigma).0.into();
867 let relative = ((actual - &expected) / &expected).norm();
868 let epsilon: Float = sigma.epsilon().0.into();
870 assert!(
871 relative <= epsilon * 64,
872 "{settings:?} in {}: relative error {relative}",
873 std::any::type_name::<T>()
874 );
875 }
876 }
877 for (function, power, binary64) in tabulated {
878 let settings = HFunctionSettings {
879 function: function.clone(),
880 power,
881 ..Default::default()
882 };
883 let p = power.unwrap_or(0);
884 let expected = match function {
885 HFunction::Exponential => scaled_bessel_k(1),
886 HFunction::PolyExponential => scaled_bessel_k(p.abs_diff(1)),
887 _ => scaled_bessel_k(2 * p.abs_diff(1)) * 2,
888 };
889 assert!(
890 ((expected.to_f64() - binary64) / binary64).abs() < 4.0 * f64::EPSILON,
891 "{settings:?}: {expected} != tabulated {binary64}"
892 );
893 let expected = expected * Float::with_val(ORACLE_PRECISION, 1.25);
895 check(F(1.25_f64), &settings, &expected);
896 check(F(f128::from_f64(1.25)), &settings, &expected);
897 check(F(SamplingFloat::from_f64(1.25)), &settings, &expected);
898 check(F(ArbPrec::from_f64(1.25)), &settings, &expected);
899 }
900 let sigma = F(ArbPrec::from_f64(1.25));
902 assert_eq!(
903 HFunctionSettings::default().normalization(&sigma),
904 sigma.PI().sqrt() * &sigma / sigma.from_usize(2)
905 );
906 }
907
908 #[test]
909 fn integration_target_compatibility_preserves_tiny_phase_differences() {
910 let mut estimate = IntegralEstimate {
911 result: Complex::new(F(2.0), F(-1e-16)),
912 error: Complex::new(F(2e-18), F(0.0)),
913 ..IntegralEstimate::default()
914 };
915 let target = Complex::new(F(2.0), F(0.0));
916 assert!(!estimate.is_compatible_with_target(target, 1));
917 estimate.error = Complex::new(F(2e-15), F(0.0));
918 assert!(estimate.is_compatible_with_target(target, 1));
919 }
920
921 #[test]
922 fn test_integration_result_display() {
923 let result = IntegralEstimate {
924 neval: 1000000,
925 real_zero: 0,
926 im_zero: 0,
927 result: Complex::new(F(1.23456789e-3), F(4.56789e-5)),
928 error: Complex::new(F(1.2e-5), F(3.4e-7)),
929 real_chisq: F(1.05),
930 im_chisq: F(0.98),
931 };
932
933 let display_str = format!("{}", result);
934 println!("Integration result display: {}", display_str);
935
936 let real_only_result = IntegralEstimate {
938 neval: 500000,
939 real_zero: 0,
940 im_zero: 0,
941 result: Complex::new(F(2.345e-2), F(0.0)),
942 error: Complex::new(F(1.5e-4), F(0.0)),
943 real_chisq: F(1.12),
944 im_chisq: F(0.0),
945 };
946
947 let real_display_str = format!("{}", real_only_result);
948 println!("Real-only result display: {}", real_display_str);
949
950 let precision_str = format!("{:.2}", result);
952 println!("With precision 2: {}", precision_str);
953 }
954
955 #[test]
956 fn integrator_settings_target_accuracy_defaults_stay_optional() {
957 let settings = IntegratorSettings::default();
958
959 let hidden_defaults = toml::to_string(&settings).expect("serialize integrator defaults");
960 assert!(!hidden_defaults.contains("target_relative_accuracy"));
961 assert!(!hidden_defaults.contains("target_absolute_accuracy"));
962
963 let _guard = ShowDefaultsGuard::new(true);
964 let shown_defaults = toml::to_string(&settings).expect("serialize integrator defaults");
965 assert!(shown_defaults.contains("n_bins"));
966 assert!(!shown_defaults.contains("target_relative_accuracy"));
967 assert!(!shown_defaults.contains("target_absolute_accuracy"));
968 }
969
970 #[test]
971 fn integrator_settings_target_accuracy_serializes_when_configured() {
972 let settings = IntegratorSettings {
973 target_relative_accuracy: Some(0.05),
974 target_absolute_accuracy: Some(1.0e-6),
975 ..IntegratorSettings::default()
976 };
977
978 let serialized = toml::to_string(&settings).expect("serialize configured integrator");
979 assert!(serialized.contains("target_relative_accuracy = 0.05"));
980 assert!(serialized.contains("target_absolute_accuracy = "));
981
982 let deserialized: IntegratorSettings =
983 toml::from_str(&serialized).expect("deserialize configured integrator");
984 assert_eq!(settings, deserialized);
985 }
986
987 #[test]
988 fn stability_representation_defaults_to_first_generated_and_roundtrips() {
989 let _guard = ShowDefaultsGuard::new(false);
990 let mut level = StabilityLevelSetting::default_double();
991 assert_eq!(
992 level
993 .resolved_representation(&[RepresentationMode::Ltd, RepresentationMode::Cff])
994 .unwrap(),
995 RepresentationMode::Ltd
996 );
997 assert_eq!(
998 level
999 .resolved_representation(&[RepresentationMode::Cff, RepresentationMode::Ltd])
1000 .unwrap(),
1001 RepresentationMode::Cff
1002 );
1003 assert!(level.resolved_representation(&[]).is_err());
1004 assert!(
1005 !toml::to_string(&level)
1006 .unwrap()
1007 .contains("three_dimensional_representation")
1008 );
1009
1010 level.three_dimensional_representation = Some(RepresentationMode::Cff);
1011 assert!(
1012 level
1013 .resolved_representation(&[RepresentationMode::Ltd])
1014 .is_err()
1015 );
1016 let serialized = toml::to_string(&level).unwrap();
1017 assert!(serialized.contains(r#"three_dimensional_representation = "cff""#));
1018 assert_eq!(
1019 toml::from_str::<StabilityLevelSetting>(&serialized).unwrap(),
1020 level
1021 );
1022 assert!(
1023 toml::from_str::<StabilityLevelSetting>(&serialized.replace("cff", "unknown")).is_err()
1024 );
1025 let schema = serde_json::to_value(schemars::schema_for!(StabilityLevelSetting)).unwrap();
1026 assert!(schema["properties"]["three_dimensional_representation"].is_object());
1027 assert!(schema["properties"].get("3drep").is_none());
1028 let error = toml::from_str::<StabilityLevelSetting>(
1029 &serialized.replace("three_dimensional_representation", "3drep"),
1030 )
1031 .unwrap_err();
1032 assert!(error.to_string().contains("unknown field `3drep`"));
1033 drop(_guard);
1034 let _guard = ShowDefaultsGuard::new(true);
1035 let defaults = serde_json::to_value(StabilityLevelSetting::default_double()).unwrap();
1036 assert!(defaults["three_dimensional_representation"].is_null());
1037 assert!(defaults.get("three_dimensional_representation").is_some());
1038 assert_eq!(
1039 serde_json::from_value::<StabilityLevelSetting>(defaults).unwrap(),
1040 StabilityLevelSetting::default_double()
1041 );
1042 }
1043
1044 #[test]
1045 fn stability_ecm_relative_tolerances_default_and_roundtrip() {
1046 let _guard = ShowDefaultsGuard::new(false);
1047 for settings in [
1048 StabilityLevelSetting::default_double(),
1049 StabilityLevelSetting::default_quad(),
1050 StabilityLevelSetting::default_arb(),
1051 ] {
1052 let serialized = toml::to_string(&settings).unwrap();
1053 assert!(!serialized.contains("ecm_relative_tolerance"));
1054 assert_eq!(
1055 toml::from_str::<StabilityLevelSetting>(&serialized).unwrap(),
1056 settings
1057 );
1058 }
1059
1060 let settings = StabilityLevelSetting {
1061 ecm_relative_tolerance_for_re: 1e-100,
1062 ecm_relative_tolerance_for_im: 2e-90,
1063 ..StabilityLevelSetting::default_arb()
1064 };
1065 let serialized = toml::to_string(&settings).unwrap();
1066 assert_eq!(
1067 toml::from_str::<StabilityLevelSetting>(&serialized).unwrap(),
1068 settings
1069 );
1070 let schema = serde_json::to_value(schemars::schema_for!(StabilityLevelSetting)).unwrap();
1071 for field in [
1072 "ecm_relative_tolerance_for_re",
1073 "ecm_relative_tolerance_for_im",
1074 ] {
1075 assert_eq!(schema["properties"][field]["minimum"], 0.0);
1076 }
1077
1078 let defaults: StabilitySettings = toml::from_str("").unwrap();
1079 assert_eq!(defaults.integrated_energy_dimension, None);
1080 assert!(
1081 !toml::to_string(&defaults)
1082 .unwrap()
1083 .contains("integrated_energy_dimension")
1084 );
1085 let declared = StabilitySettings {
1086 integrated_energy_dimension: Some(-6),
1087 levels: vec![settings],
1088 ..defaults
1089 };
1090 assert_eq!(
1091 toml::from_str::<StabilitySettings>(&toml::to_string(&declared).unwrap()).unwrap(),
1092 declared
1093 );
1094 drop(_guard);
1095 let _guard = ShowDefaultsGuard::new(true);
1096 for settings in [
1097 StabilityLevelSetting::default_double(),
1098 StabilityLevelSetting::default_quad(),
1099 StabilityLevelSetting::default_arb(),
1100 ] {
1101 let shown = serde_json::to_value(settings).unwrap();
1102 assert_eq!(shown["ecm_relative_tolerance_for_re"], 0.0);
1103 assert_eq!(shown["ecm_relative_tolerance_for_im"], 0.0);
1104 }
1105 assert_eq!(
1106 serde_json::to_value(&declared).unwrap()["integrated_energy_dimension"],
1107 -6
1108 );
1109 }
1110
1111 #[test]
1112 fn stability_ecm_relative_tolerances_reject_invalid_values() {
1113 let _guard = ShowDefaultsGuard::new(false);
1114 let defaults = toml::to_string(&StabilityLevelSetting::default_arb()).unwrap();
1115 for field in [
1116 "ecm_relative_tolerance_for_re",
1117 "ecm_relative_tolerance_for_im",
1118 ] {
1119 for invalid in ["-1.0", "nan", "inf", "-inf"] {
1120 let text = format!("{defaults}\n{field} = {invalid}\n");
1121 assert!(
1122 toml::from_str::<StabilityLevelSetting>(&text).is_err(),
1123 "{field} = {invalid}"
1124 );
1125 }
1126 }
1127 }
1128
1129 #[test]
1130 fn sampling_ose_and_named_weight_roundtrip() {
1131 let _guard = ShowDefaultsGuard::new(false);
1132 for (graphs, channels) in [
1133 ("summed", "summed"),
1134 ("monte_carlo", "summed"),
1135 ("monte_carlo", "monte_carlo"),
1136 ] {
1137 for (global, local) in [("ose", "map_density"), ("map_density", "ose")] {
1138 let text = format!(
1139 r#"graphs = "{graphs}"
1140sampling_multichanneling = true
1141sampling_channels = "{channels}"
1142sampling_channel_weight = "{global}"
1143alpha = 2.5
1144default_channel_selection = ["auto:optimized_lmb"]
1145[channel_definitions.G.soft]
1146around = "lmb(1,2)"
1147parent_lmb = [1,2]
1148channel_weight = "{local}"
1149"#
1150 );
1151 let settings: SamplingSettings = toml::from_str(&text).unwrap();
1152 let selection = settings
1153 .get_parameterization_settings()
1154 .unwrap()
1155 .sampling_channels;
1156 assert_eq!(selection.alpha, 2.5);
1157 assert_eq!(
1158 selection.weight == SamplingChannelWeight::Ose,
1159 global == "ose"
1160 );
1161 assert_eq!(
1162 selection.channel_definitions["G"]["soft"].channel_weight
1163 == Some(SamplingChannelWeight::Ose),
1164 local == "ose"
1165 );
1166 let serialized = toml::to_string(&settings).unwrap();
1167 assert_eq!(
1168 toml::from_str::<SamplingSettings>(&serialized).unwrap(),
1169 settings
1170 );
1171 }
1172 }
1173 let settings: SamplingSettings =
1174 toml::from_str("sampling_multichanneling=true\nsampling_channel_weight='ose'").unwrap();
1175 let selection = settings
1176 .get_parameterization_settings()
1177 .unwrap()
1178 .sampling_channels;
1179 assert_eq!(selection.weight, SamplingChannelWeight::Ose);
1180 assert_eq!(selection.alpha, 3.0);
1181 assert_eq!(
1182 selection.default_channel_selection,
1183 vec!["auto:optimized_lmb"]
1184 );
1185 assert!(!toml::to_string(&settings).unwrap().contains("alpha"));
1186 drop(_guard);
1187 let _guard = ShowDefaultsGuard::new(true);
1188 assert_eq!(serde_json::to_value(settings).unwrap()["alpha"], 3.0);
1189 }
1190
1191 #[test]
1192 fn sampling_ose_alpha_validation_and_zero_control() {
1193 for invalid in ["-1.0", "nan", "inf", "-inf"] {
1194 let text = format!("alpha={invalid}");
1195 assert!(toml::from_str::<SamplingSettings>(&text).is_err());
1196 assert!(toml::from_str::<SamplingChannelSelection>(&text).is_err());
1197 }
1198 for alpha in [-1.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
1199 assert!(
1200 SamplingSettings::from_parser(SamplingSettingsParser {
1201 alpha,
1202 ..Default::default()
1203 })
1204 .is_err()
1205 );
1206 }
1207 let settings: SamplingSettings = toml::from_str(
1208 "sampling_multichanneling=true\nsampling_channel_weight='ose'\nalpha=0.0",
1209 )
1210 .unwrap();
1211 assert_eq!(
1212 settings
1213 .get_parameterization_settings()
1214 .unwrap()
1215 .sampling_channels
1216 .alpha,
1217 0.0
1218 );
1219 assert_eq!(
1220 toml::from_str::<SamplingSettings>(&toml::to_string(&settings).unwrap()).unwrap(),
1221 settings
1222 );
1223 }
1224
1225 #[test]
1226 fn uv_localisation_smooth_sliver_defaults_and_roundtrips() {
1227 let defaults: UVLocalisationSettings = toml::from_str("").unwrap();
1228 assert!(!defaults.smooth_sliver);
1229 assert_eq!(defaults, UVLocalisationSettings::default());
1230 {
1231 let _guard = ShowDefaultsGuard::new(false);
1232 assert!(
1233 !toml::to_string(&defaults)
1234 .unwrap()
1235 .contains("smooth_sliver")
1236 );
1237 let settings = UVLocalisationSettings {
1238 smooth_sliver: true,
1239 ..defaults.clone()
1240 };
1241 let serialized = toml::to_string(&settings).unwrap();
1242 assert!(serialized.contains("smooth_sliver = true"));
1243 assert_eq!(
1244 toml::from_str::<UVLocalisationSettings>(&serialized).unwrap(),
1245 settings
1246 );
1247 }
1248 let _guard = ShowDefaultsGuard::new(true);
1249 assert!(
1250 toml::to_string(&defaults)
1251 .unwrap()
1252 .contains("smooth_sliver = false")
1253 );
1254 }
1255
1256 #[test]
1257 fn integral_unit_auto_resolves_by_initial_state_count() {
1258 assert_eq!(
1259 IntegralUnit::Auto.resolve_for_cross_section(1),
1260 IntegralUnit::None
1261 );
1262 assert_eq!(
1263 IntegralUnit::Auto.resolve_for_cross_section(2),
1264 IntegralUnit::Picobarn
1265 );
1266 }
1267
1268 #[test]
1269 fn integral_unit_relative_scalings_match_requested_barn_unit() {
1270 let one = F(1.0f64);
1271 assert_eq!(
1272 IntegralUnit::Picobarn.relative_to_picobarn_factor(&one),
1273 Some(F(1.0))
1274 );
1275 assert_eq!(
1276 IntegralUnit::Femtobarn.relative_to_picobarn_factor(&one),
1277 Some(F(1_000.0))
1278 );
1279 assert_eq!(
1280 IntegralUnit::Attobarn.relative_to_picobarn_factor(&one),
1281 Some(F(1_000_000.0))
1282 );
1283 assert_eq!(
1284 IntegralUnit::Millibarn.relative_to_picobarn_factor(&one),
1285 Some(F(1.0e-9))
1286 );
1287 assert_eq!(IntegralUnit::None.relative_to_picobarn_factor(&one), None);
1288 }
1289
1290 #[test]
1291 fn general_settings_store_mu_r_and_compute_mu_r_sq_internally() {
1292 let settings = GeneralSettings {
1293 mu_r: 91.188,
1294 ..GeneralSettings::default()
1295 };
1296
1297 assert_eq!(settings.mu_r, 91.188);
1298 assert!((settings.mu_r_sq() - 8315.251344).abs() < 1.0e-12);
1299
1300 let serialized = toml::to_string(&settings).expect("serialize general settings");
1301 assert!(serialized.contains("mu_r = 91.188"));
1302 assert!(!serialized.contains("mu_r_sq"));
1303 }
1304}
1305
1306#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1307#[derive(Serialize, Deserialize, Debug, Clone, Encode, Decode, PartialEq, JsonSchema)]
1308#[serde(default, deny_unknown_fields)]
1309pub struct StabilitySettings {
1310 #[serde(skip_serializing_if = "IsDefault::is_default")]
1316 pub integrated_energy_dimension: Option<i32>,
1317 #[serde(skip_serializing_if = "is_default_rotation_axis")]
1319 pub rotation_axis: Vec<RotationSetting>,
1320 #[serde(skip_serializing_if = "is_default_stability_levels")]
1322 pub levels: Vec<StabilityLevelSetting>,
1323 #[serde(skip_serializing_if = "is_true")]
1325 pub check_on_norm: bool,
1326 #[serde(skip_serializing_if = "is_false")]
1328 pub escalate_if_exact_zero: bool,
1329 #[serde(
1335 default,
1336 deserialize_with = "deserialize_nonnegative_finite_f64",
1337 skip_serializing_if = "is_float::<0>"
1338 )]
1339 #[schemars(range(min = 0.0))]
1340 pub min_abs_wgt_for_escalation: f64,
1341 #[serde(skip_serializing_if = "is_float::<-1>")]
1343 pub loop_momenta_norm_escalation_factor: f64,
1344 #[serde(skip_serializing_if = "IsDefault::is_default")]
1346 pub recording: Option<StabilityRecordingSettings>,
1347}
1348
1349impl Default for StabilitySettings {
1350 fn default() -> Self {
1351 Self {
1352 integrated_energy_dimension: None,
1353 rotation_axis: _default_rotation_axis(),
1354 levels: _default_stability_levels(),
1355 check_on_norm: true,
1356 escalate_if_exact_zero: false,
1357 min_abs_wgt_for_escalation: 0.0,
1358 loop_momenta_norm_escalation_factor: -1.0,
1359 recording: None,
1360 }
1361 }
1362}
1363
1364#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1365#[derive(Serialize, Deserialize, Debug, Clone, Copy, Encode, Decode, PartialEq, JsonSchema)]
1366#[serde(default, deny_unknown_fields)]
1367pub struct StabilityRecordingSettings {
1368 #[serde(skip_serializing_if = "is_false")]
1370 pub record_rotated_results: bool,
1371 #[serde(skip_serializing_if = "is_false")]
1373 pub record_all_stability_levels: bool,
1374 #[serde(skip_serializing_if = "is_false")]
1376 pub record_loop_momenta_escalation: bool,
1377}
1378
1379#[allow(clippy::derivable_impls)]
1380impl Default for StabilityRecordingSettings {
1381 fn default() -> Self {
1382 Self {
1383 record_rotated_results: false,
1384 record_all_stability_levels: false,
1385 record_loop_momenta_escalation: false,
1386 }
1387 }
1388}
1389
1390#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1391#[derive(Serialize, Deserialize, Debug, Clone, Copy, Encode, Decode, PartialEq, JsonSchema)]
1392#[serde(deny_unknown_fields)]
1393pub struct StabilityLevelSetting {
1394 pub precision: Precision,
1396 #[serde(default, skip_serializing_if = "IsDefault::is_default")]
1398 pub three_dimensional_representation: Option<RepresentationMode>,
1399 pub required_precision_for_re: f64,
1401 pub required_precision_for_im: f64,
1403 #[serde(
1410 default,
1411 deserialize_with = "deserialize_nonnegative_finite_f64",
1412 skip_serializing_if = "is_float::<0>"
1413 )]
1414 #[schemars(range(min = 0.0))]
1415 pub ecm_relative_tolerance_for_re: f64,
1416 #[serde(
1419 default,
1420 deserialize_with = "deserialize_nonnegative_finite_f64",
1421 skip_serializing_if = "is_float::<0>"
1422 )]
1423 #[schemars(range(min = 0.0))]
1424 pub ecm_relative_tolerance_for_im: f64,
1425 pub escalate_for_large_weight_threshold: f64,
1427}
1428
1429impl StabilityLevelSetting {
1430 pub fn resolved_representation(
1431 &self,
1432 generated: &[RepresentationMode],
1433 ) -> Result<RepresentationMode> {
1434 let first = generated
1435 .first()
1436 .ok_or_else(|| eyre::eyre!("integrand has no generated 3D representations"))?;
1437 let selected = self.three_dimensional_representation.unwrap_or(*first);
1438 if !generated.contains(&selected) {
1439 return Err(eyre::eyre!(
1440 "Requested 3D representation `{selected}` was not generated; available representations: {}",
1441 generated
1442 .iter()
1443 .map(ToString::to_string)
1444 .collect::<Vec<_>>()
1445 .join(", ")
1446 ));
1447 }
1448 Ok(selected)
1449 }
1450
1451 pub fn default_double() -> Self {
1452 Self {
1453 precision: Precision::Double,
1454 three_dimensional_representation: None,
1455 required_precision_for_re: 1e-5,
1456 required_precision_for_im: 1e-5,
1457 ecm_relative_tolerance_for_re: 0.0,
1458 ecm_relative_tolerance_for_im: 0.0,
1459 escalate_for_large_weight_threshold: 0.9,
1460 }
1461 }
1462
1463 pub fn default_quad() -> Self {
1464 Self {
1465 precision: Precision::Quad,
1466 three_dimensional_representation: None,
1467 required_precision_for_re: 1e-5,
1468 required_precision_for_im: 1e-5,
1469 ecm_relative_tolerance_for_re: 0.0,
1470 ecm_relative_tolerance_for_im: 0.0,
1471 escalate_for_large_weight_threshold: -1.0,
1472 }
1473 }
1474
1475 pub fn default_arb() -> Self {
1476 Self {
1477 precision: Precision::Arb,
1478 three_dimensional_representation: None,
1479 required_precision_for_re: 1e-5,
1480 required_precision_for_im: 1e-5,
1481 ecm_relative_tolerance_for_re: 0.0,
1482 ecm_relative_tolerance_for_im: 0.0,
1483 escalate_for_large_weight_threshold: -1.0,
1484 }
1485 }
1486}
1487
1488#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1489#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Encode, Decode, JsonSchema)]
1490#[serde(tag = "type")]
1491#[serde(deny_unknown_fields)]
1492pub enum RotationSetting {
1493 #[serde(rename = "x")]
1494 Pi2X {},
1495 #[serde(rename = "y")]
1496 Pi2Y {},
1497 #[serde(rename = "z")]
1498 Pi2Z {},
1499 #[serde(rename = "none")]
1500 None {},
1501 #[serde(rename = "euler_angles")]
1502 EulerAngles {
1503 alpha: f64,
1505 beta: f64,
1507 gamma: f64,
1509 },
1510 #[serde(rename = "axis_angle")]
1511 AxisAngle {
1512 axis: [f64; 3],
1514 cos_theta: f64,
1517 },
1518}
1519
1520impl Default for RotationSetting {
1521 fn default() -> Self {
1522 Self::Pi2Z {}
1523 }
1524}
1525
1526impl RotationSetting {
1527 pub(crate) fn validate(&self) -> Result<()> {
1528 if let Self::AxisAngle { axis, cos_theta } = self {
1529 ensure!(
1530 axis.iter().all(|component| component.is_finite())
1531 && axis.iter().any(|component| *component != 0.0),
1532 "axis-angle rotation requires a finite nonzero axis"
1533 );
1534 ensure!(
1535 cos_theta.is_finite() && (-1.0..=1.0).contains(cos_theta),
1536 "axis-angle rotation cosine must be finite and lie in [-1, 1]"
1537 );
1538 }
1539 Ok(())
1540 }
1541
1542 pub(crate) fn rotation_method(&self) -> RotationMethod {
1543 match self {
1544 Self::Pi2X {} => RotationMethod::Pi2X,
1545 Self::Pi2Y {} => RotationMethod::Pi2Y,
1546 Self::Pi2Z {} => RotationMethod::Pi2Z,
1547 Self::None {} => RotationMethod::Identity,
1548 Self::EulerAngles { alpha, beta, gamma } => {
1549 RotationMethod::EulerAngles(*alpha, *beta, *gamma)
1550 }
1551 Self::AxisAngle { axis, cos_theta } => RotationMethod::AxisAngle {
1552 axis: *axis,
1553 cos_theta: *cos_theta,
1554 },
1555 }
1556 }
1557
1558 pub(crate) fn _as_str(&self) -> String {
1559 match self {
1560 Self::Pi2X {} => "x".to_owned(),
1561 Self::Pi2Y {} => "y".to_owned(),
1562 Self::Pi2Z {} => "z".to_owned(),
1563 Self::None {} => "none".to_owned(),
1564 Self::EulerAngles { alpha, beta, gamma } => {
1565 format!("euler {} {} {}", alpha, beta, gamma)
1566 }
1567 Self::AxisAngle { axis, cos_theta } => format!("axis {:?}, cosine {}", axis, cos_theta),
1568 }
1569 }
1570}
1571
1572#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
1573#[derive(
1574 Serialize, Deserialize, Debug, Clone, PartialEq, Copy, Hash, Eq, Encode, Decode, JsonSchema,
1575)]
1576#[serde(deny_unknown_fields)]
1577pub enum Precision {
1578 Double,
1579 Quad,
1580 Arb,
1581}
1582
1583impl Display for Precision {
1584 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1585 match self {
1586 Self::Double => write!(f, "f64"),
1587 Self::Quad => write!(f, "f128"),
1588 Self::Arb => write!(f, "arb"),
1589 }
1590 }
1591}
1592
1593#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1594#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default, Encode, Decode, JsonSchema)]
1595#[serde(deny_unknown_fields)]
1596pub enum ParameterizationMode {
1597 #[serde(rename = "cartesian")]
1598 Cartesian,
1599 #[serde(rename = "spherical")]
1600 #[default]
1601 Spherical,
1602 #[serde(rename = "hyperspherical")]
1603 HyperSpherical,
1604 #[serde(rename = "hyperspherical_flat")]
1605 HyperSphericalFlat,
1606 #[serde(rename = "momentum_space")]
1607 MomentumSpace,
1608 #[serde(rename = "relative_spherical")]
1609 RelativeSpherical,
1610 #[serde(rename = "spherical_common_radial")]
1611 SphericalCommonRadial,
1612 #[serde(rename = "spherical_product_common_radial")]
1613 SphericalProductCommonRadial,
1614}
1615
1616#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1617#[derive(Debug, Clone, Serialize, Deserialize, Default)]
1618#[serde(default, deny_unknown_fields)]
1619pub struct OutputMetadata {
1620 #[serde(skip_serializing_if = "IsDefault::is_default")]
1621 pub model_name: String,
1622 #[serde(skip_serializing_if = "IsDefault::is_default")]
1623 pub output_type: String,
1624 #[serde(skip_serializing_if = "IsDefault::is_default")]
1625 pub contents: Vec<String>,
1626}
1627
1628impl Display for ParameterizationMode {
1629 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1630 match self {
1631 ParameterizationMode::Cartesian => write!(f, "cartesian"),
1632 ParameterizationMode::Spherical => write!(f, "spherical"),
1633 ParameterizationMode::RelativeSpherical => write!(f, "relative spherical"),
1634 ParameterizationMode::SphericalCommonRadial => {
1635 write!(f, "common-radial spherical")
1636 }
1637 ParameterizationMode::SphericalProductCommonRadial => {
1638 write!(f, "product/common-radial spherical")
1639 }
1640 ParameterizationMode::HyperSpherical => write!(f, "hyperspherical"),
1641 ParameterizationMode::HyperSphericalFlat => write!(f, "flat hyperspherical"),
1642 ParameterizationMode::MomentumSpace => write!(f, "momentum space"),
1643 }
1644 }
1645}
1646
1647#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
1648#[derive(Debug, Clone, Deserialize, PartialEq, Default, Serialize, Encode, Decode, JsonSchema)]
1649#[serde(deny_unknown_fields)]
1650pub enum ParameterizationMapping {
1651 #[serde(rename = "log")]
1652 Log,
1653 #[serde(rename = "power")]
1654 Power,
1655 #[serde(rename = "linear")]
1656 #[default]
1657 Linear,
1658}
1659
1660#[derive(Debug, Clone, PartialEq, Encode, Decode)]
1661#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1662pub enum SamplingSettings {
1663 Default(ParameterizationSettings),
1664 MultiChanneling(MultiChannelingSettings),
1665 DiscreteGraphs(DiscreteGraphSamplingSettings),
1666}
1667
1668#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
1669#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1670#[serde(default, deny_unknown_fields)]
1671pub struct SamplingSettingsParser {
1672 #[serde(skip_serializing_if = "IsDefault::is_default")]
1674 pub graphs: SumMode,
1675 #[serde(skip_serializing_if = "IsDefault::is_default")]
1677 pub graph_names: Vec<String>,
1678 #[serde(skip_serializing_if = "IsDefault::is_default")]
1680 pub orientations: SumMode,
1681 #[serde(skip_serializing_if = "is_false")]
1683 #[serde(rename = "sampling_multichanneling", alias = "lmb_multichanneling")]
1684 pub sampling_multichanneling: bool,
1685 #[serde(skip_serializing_if = "IsDefault::is_default")]
1687 #[serde(rename = "sampling_channels", alias = "lmb_channels")]
1688 pub sampling_channels: SumMode,
1689 #[serde(
1691 deserialize_with = "deserialize_nonnegative_finite_f64",
1692 skip_serializing_if = "is_float::<3>"
1693 )]
1694 #[schemars(range(min = 0.0))]
1695 pub alpha: f64,
1696 #[serde(skip_serializing_if = "IsDefault::is_default")]
1698 #[serde(rename = "sampling_channel_weight", alias = "lmb_channel_weight")]
1699 pub sampling_channel_weight: SamplingChannelWeight,
1700 #[serde(skip_serializing_if = "IsDefault::is_default")]
1702 pub coordinate_system: CoordinateSystem,
1703 #[serde(skip_serializing_if = "IsDefault::is_default")]
1705 pub mapping: ParameterizationMapping,
1706 #[serde(skip_serializing_if = "is_float::<1>")]
1708 pub b: f64,
1709 #[serde(skip_serializing_if = "is_float::<1>")]
1711 pub power: f64,
1712 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1714 pub lmb_basis_ids: BTreeMap<String, Vec<usize>>,
1715 #[serde(skip_serializing_if = "Vec::is_empty")]
1717 pub default_channel_selection: Vec<String>,
1718 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1720 pub channel_selection: BTreeMap<String, Vec<String>>,
1721 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
1723 pub channel_definitions: BTreeMap<String, BTreeMap<String, SamplingChannelDefinition>>,
1724}
1725
1726#[cfg(feature = "python")]
1731#[pyo3::pymethods]
1732impl SamplingSettingsParser {
1733 #[getter(lmb_multichanneling)]
1734 fn legacy_lmb_multichanneling(&self) -> bool {
1735 self.sampling_multichanneling
1736 }
1737
1738 #[setter(lmb_multichanneling)]
1739 fn set_legacy_lmb_multichanneling(&mut self, value: bool) {
1740 self.sampling_multichanneling = value;
1741 }
1742
1743 #[getter(lmb_channels)]
1744 fn legacy_lmb_channels(&self) -> SumMode {
1745 self.sampling_channels.clone()
1746 }
1747
1748 #[setter(lmb_channels)]
1749 fn set_legacy_lmb_channels(&mut self, value: SumMode) {
1750 self.sampling_channels = value;
1751 }
1752
1753 #[getter(lmb_channel_weight)]
1754 fn legacy_lmb_channel_weight(&self) -> SamplingChannelWeight {
1755 self.sampling_channel_weight
1756 }
1757
1758 #[setter(lmb_channel_weight)]
1759 fn set_legacy_lmb_channel_weight(&mut self, value: SamplingChannelWeight) {
1760 self.sampling_channel_weight = value;
1761 }
1762}
1763
1764impl Default for SamplingSettingsParser {
1765 fn default() -> Self {
1766 Self {
1767 graphs: SumMode::Summed,
1768 graph_names: Vec::new(),
1769 orientations: SumMode::Summed,
1770 sampling_multichanneling: false,
1771 sampling_channels: SumMode::Summed,
1772 alpha: 3.0,
1773 sampling_channel_weight: SamplingChannelWeight::default(),
1774 coordinate_system: CoordinateSystem::Spherical,
1775 mapping: ParameterizationMapping::Linear,
1776 b: 1.0,
1777 power: 1.0,
1778 lmb_basis_ids: BTreeMap::new(),
1779 default_channel_selection: Vec::new(),
1780 channel_selection: BTreeMap::new(),
1781 channel_definitions: BTreeMap::new(),
1782 }
1783 }
1784}
1785
1786#[derive(
1792 Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Encode, Decode, JsonSchema,
1793)]
1794#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1795pub enum SamplingChannelWeight {
1796 #[serde(rename = "map_density")]
1797 #[default]
1798 MapDensity,
1799 #[serde(rename = "ose")]
1800 Ose,
1801 #[serde(rename = "singularity_proxy")]
1802 SingularityProxy,
1803 #[serde(rename = "inverse_jacobian")]
1804 InverseJacobian,
1805}
1806
1807#[derive(
1809 Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Encode, Decode, JsonSchema,
1810)]
1811#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1812#[serde(rename_all = "snake_case")]
1813pub enum SamplingRadialProfileKind {
1814 #[default]
1815 LuH,
1816}
1817
1818#[derive(
1819 Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Encode, Decode, JsonSchema,
1820)]
1821#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1822#[serde(rename_all = "snake_case")]
1823pub enum SamplingRadialApproximation {
1824 #[default]
1825 LogLogistic,
1826}
1827
1828#[derive(Debug, Clone, Serialize, PartialEq, Encode, Decode, JsonSchema)]
1831#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1832#[schemars(with = "SamplingRadialProfileInput")]
1833pub struct SamplingRadialProfile {
1834 pub kind: SamplingRadialProfileKind,
1835 #[serde(skip_serializing_if = "IsDefault::is_default")]
1836 pub approximation: SamplingRadialApproximation,
1837 pub broad_fraction: f64,
1838 #[serde(skip_serializing_if = "IsDefault::is_default")]
1839 pub scale: Option<f64>,
1840 #[serde(skip_serializing_if = "IsDefault::is_default")]
1841 pub shape: Option<f64>,
1842}
1843
1844impl Default for SamplingRadialProfile {
1845 fn default() -> Self {
1846 Self {
1847 kind: SamplingRadialProfileKind::LuH,
1848 approximation: SamplingRadialApproximation::LogLogistic,
1849 broad_fraction: 0.02,
1850 scale: None,
1851 shape: None,
1852 }
1853 }
1854}
1855
1856#[derive(Deserialize, JsonSchema)]
1859#[serde(untagged, deny_unknown_fields)]
1860enum SamplingRadialProfileInput {
1861 Name(SamplingRadialProfileKind),
1862 Settings {
1863 kind: SamplingRadialProfileKind,
1864 #[serde(default)]
1865 approximation: SamplingRadialApproximation,
1866 #[serde(default = "SamplingRadialProfile::default_broad_fraction")]
1867 broad_fraction: f64,
1868 #[serde(default)]
1869 scale: Option<f64>,
1870 #[serde(default)]
1871 shape: Option<f64>,
1872 },
1873}
1874
1875impl SamplingRadialProfile {
1876 fn default_broad_fraction() -> f64 {
1877 Self::default().broad_fraction
1878 }
1879}
1880
1881impl<'de> Deserialize<'de> for SamplingRadialProfile {
1882 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
1883 Ok(
1884 match SamplingRadialProfileInput::deserialize(deserializer)? {
1885 SamplingRadialProfileInput::Name(kind) => Self {
1886 kind,
1887 ..Self::default()
1888 },
1889 SamplingRadialProfileInput::Settings {
1890 kind,
1891 approximation,
1892 broad_fraction,
1893 scale,
1894 shape,
1895 } => Self {
1896 kind,
1897 approximation,
1898 broad_fraction,
1899 scale,
1900 shape,
1901 },
1902 },
1903 )
1904 }
1905}
1906
1907#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
1911#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1912#[serde(default, deny_unknown_fields)]
1913pub struct SamplingChannelDefinition {
1914 pub around: String,
1915 #[serde(skip_serializing_if = "IsDefault::is_default")]
1919 pub channel_weight: Option<SamplingChannelWeight>,
1920 #[serde(skip_serializing_if = "IsDefault::is_default")]
1921 pub radial_profile: Option<SamplingRadialProfile>,
1922 pub subspace_lmb: Vec<usize>,
1926 pub parent_lmb: Vec<usize>,
1927 pub on_cut: Vec<usize>,
1928 #[serde(skip_serializing_if = "Option::is_none")]
1935 pub singularity_proxy: Option<String>,
1936}
1937
1938#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
1940#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1941#[serde(default, deny_unknown_fields)]
1942pub struct SamplingChannelSelection {
1943 #[serde(skip_serializing_if = "IsDefault::is_default")]
1944 pub weight: SamplingChannelWeight,
1945 #[serde(
1948 deserialize_with = "deserialize_nonnegative_finite_f64",
1949 skip_serializing_if = "is_float::<3>"
1950 )]
1951 #[schemars(range(min = 0.0))]
1952 pub alpha: f64,
1953 pub default_channel_selection: Vec<String>,
1954 pub channel_selection: BTreeMap<String, Vec<String>>,
1955 pub channel_definitions: BTreeMap<String, BTreeMap<String, SamplingChannelDefinition>>,
1956}
1957
1958impl Default for SamplingChannelSelection {
1959 fn default() -> Self {
1960 Self {
1961 weight: SamplingChannelWeight::default(),
1962 alpha: 3.0,
1963 default_channel_selection: Vec::new(),
1964 channel_selection: BTreeMap::new(),
1965 channel_definitions: BTreeMap::new(),
1966 }
1967 }
1968}
1969
1970#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
1971#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1972pub enum SumMode {
1973 #[serde(rename = "summed")]
1974 #[default]
1975 Summed,
1976 #[serde(rename = "monte_carlo")]
1977 MonteCarlo,
1978}
1979
1980#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema, Default)]
1981#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
1982pub enum CoordinateSystem {
1983 #[serde(rename = "cartesian")]
1984 Cartesian,
1985 #[serde(rename = "spherical")]
1986 #[default]
1987 Spherical,
1988 #[serde(rename = "hyperspherical")]
1989 HyperSpherical,
1990 #[serde(rename = "hyperspherical_flat")]
1991 HyperSphericalFlat,
1992 #[serde(rename = "momentum_space")]
1993 MomentumSpace,
1994 #[serde(rename = "tropical")]
1995 MomTrop,
1996 #[serde(rename = "relative_spherical")]
1997 RelativeSpherical,
1998 #[serde(rename = "spherical_common_radial")]
1999 SphericalCommonRadial,
2000 #[serde(rename = "spherical_product_common_radial")]
2001 SphericalProductCommonRadial,
2002}
2003
2004impl Default for SamplingSettings {
2005 fn default() -> Self {
2006 Self::Default(ParameterizationSettings::default())
2007 }
2008}
2009
2010fn validate_lmb_basis_ids(lmb_basis_ids: &BTreeMap<String, Vec<usize>>) -> Result<(), String> {
2011 for (graph_name, basis_ids) in lmb_basis_ids {
2012 if basis_ids.is_empty() {
2013 return Err(format!(
2014 "Invalid sampling settings: lmb_basis_ids entry for graph '{graph_name}' cannot be empty."
2015 ));
2016 }
2017
2018 let mut seen = BTreeSet::new();
2019 for basis_id in basis_ids {
2020 if !seen.insert(*basis_id) {
2021 return Err(format!(
2022 "Invalid sampling settings: lmb_basis_ids entry for graph '{graph_name}' contains duplicate basis id {basis_id}."
2023 ));
2024 }
2025 }
2026 }
2027
2028 Ok(())
2029}
2030
2031fn validate_sampling_channel_selection(
2032 default_selection: &[String],
2033 selection: &BTreeMap<String, Vec<String>>,
2034 definitions: &BTreeMap<String, BTreeMap<String, SamplingChannelDefinition>>,
2035) -> Result<(), String> {
2036 for (label, entries) in [("default_channel_selection", default_selection)] {
2037 if entries.iter().any(|entry| entry.trim().is_empty()) {
2038 return Err(format!(
2039 "Invalid sampling settings: {label} contains an empty channel selector."
2040 ));
2041 }
2042 }
2043 for (graph, entries) in selection {
2044 if graph.trim().is_empty() {
2045 return Err(
2046 "Invalid sampling settings: channel_selection contains an empty graph name."
2047 .to_string(),
2048 );
2049 }
2050 if entries.iter().any(|entry| entry.trim().is_empty()) {
2051 return Err(format!(
2052 "Invalid sampling settings: channel_selection entry for graph '{graph}' contains an empty selector."
2053 ));
2054 }
2055 }
2056 for (graph, graph_definitions) in definitions {
2057 if graph.trim().is_empty() {
2058 return Err(
2059 "Invalid sampling settings: channel_definitions contains an empty graph name."
2060 .to_string(),
2061 );
2062 }
2063 for (name, definition) in graph_definitions {
2064 if name.trim().is_empty() || definition.around.trim().is_empty() {
2065 return Err(format!(
2066 "Invalid sampling settings: channel definition '{graph}.{name}' requires a non-empty around expression."
2067 ));
2068 }
2069 if definition.parent_lmb.is_empty() {
2070 return Err(format!(
2071 "Invalid sampling settings: channel definition '{graph}.{name}' requires a non-empty parent_lmb."
2072 ));
2073 }
2074 let mut seen = BTreeSet::new();
2075 if definition.parent_lmb.iter().any(|edge| !seen.insert(edge)) {
2076 return Err(format!(
2077 "Invalid sampling settings: channel definition '{graph}.{name}' contains duplicate parent_lmb edge ids."
2078 ));
2079 }
2080 let mut seen_subspace = BTreeSet::new();
2081 if definition
2082 .subspace_lmb
2083 .iter()
2084 .any(|edge| !seen_subspace.insert(edge))
2085 {
2086 return Err(format!(
2087 "Invalid sampling settings: channel definition '{graph}.{name}' contains duplicate subspace_lmb edge ids."
2088 ));
2089 }
2090 let mut seen_on_cut = BTreeSet::new();
2091 if definition
2092 .on_cut
2093 .iter()
2094 .any(|edge| !seen_on_cut.insert(edge))
2095 {
2096 return Err(format!(
2097 "Invalid sampling settings: channel definition '{graph}.{name}' contains duplicate on_cut edge ids."
2098 ));
2099 }
2100 SamplingMapDefinition::parse(&definition.around).map_err(|error| {
2101 format!(
2102 "Invalid sampling settings: channel definition '{graph}.{name}' has an invalid around expression: {error}"
2103 )
2104 })?;
2105 }
2106 }
2107 Ok(())
2108}
2109
2110impl SamplingSettings {
2111 pub fn as_parser(&self) -> SamplingSettingsParser {
2112 let mut parser = SamplingSettingsParser::default();
2113 match self {
2114 Self::Default(_) => {}
2115 Self::MultiChanneling(_) => parser.sampling_multichanneling = true,
2116 Self::DiscreteGraphs(settings) => {
2117 parser.graphs = SumMode::MonteCarlo;
2118 parser.graph_names = settings.graph_names.clone();
2119 parser.orientations = if settings.sample_orientations {
2120 SumMode::MonteCarlo
2121 } else {
2122 SumMode::Summed
2123 };
2124 parser.sampling_multichanneling = matches!(
2125 settings.sampling_type,
2126 DiscreteGraphSamplingType::MultiChanneling(_)
2127 | DiscreteGraphSamplingType::SamplingMultiChanneling(_)
2128 );
2129 if matches!(
2130 settings.sampling_type,
2131 DiscreteGraphSamplingType::SamplingMultiChanneling(_)
2132 ) {
2133 parser.sampling_channels = SumMode::MonteCarlo;
2134 }
2135 }
2136 }
2137 match self.get_parameterization_settings() {
2138 Some(settings) => SamplingSettingsParser {
2139 alpha: settings.sampling_channels.alpha,
2140 sampling_channel_weight: settings.sampling_channels.weight,
2141 coordinate_system: CoordinateSystem::from_mode(settings.mode),
2142 mapping: settings.mapping,
2143 b: settings.b,
2144 power: settings.power,
2145 lmb_basis_ids: settings.lmb_basis_ids,
2146 default_channel_selection: settings.sampling_channels.default_channel_selection,
2147 channel_selection: settings.sampling_channels.channel_selection,
2148 channel_definitions: settings.sampling_channels.channel_definitions,
2149 ..parser
2150 },
2151 None => SamplingSettingsParser {
2152 coordinate_system: CoordinateSystem::MomTrop,
2153 ..parser
2154 },
2155 }
2156 }
2157
2158 fn from_parser(parser: SamplingSettingsParser) -> Result<Self, String> {
2159 let SamplingSettingsParser {
2160 graphs,
2161 graph_names,
2162 orientations,
2163 sampling_multichanneling,
2164 sampling_channels,
2165 alpha,
2166 sampling_channel_weight,
2167 coordinate_system,
2168 mapping,
2169 b,
2170 power,
2171 lmb_basis_ids,
2172 default_channel_selection,
2173 channel_selection,
2174 channel_definitions,
2175 } = parser;
2176
2177 validate_lmb_basis_ids(&lmb_basis_ids)?;
2178 let default_channel_selection =
2179 if sampling_multichanneling && default_channel_selection.is_empty() {
2180 vec!["auto:optimized_lmb".to_string()]
2181 } else {
2182 default_channel_selection
2183 };
2184 validate_sampling_channel_selection(
2185 &default_channel_selection,
2186 &channel_selection,
2187 &channel_definitions,
2188 )?;
2189 if !alpha.is_finite() || alpha < 0.0 {
2190 return Err(
2191 "Invalid sampling settings: alpha must be finite and nonnegative.".to_string(),
2192 );
2193 }
2194
2195 let mut seen_graph_names = BTreeSet::new();
2196 for graph_name in &graph_names {
2197 if !seen_graph_names.insert(graph_name) {
2198 return Err(format!(
2199 "Invalid sampling settings: graph_names contains duplicate graph name '{graph_name}'."
2200 ));
2201 }
2202 }
2203 if !graph_names.is_empty() && matches!(graphs, SumMode::Summed) {
2204 return Err(
2205 "Invalid sampling settings: graph_names requires graphs = 'monte_carlo'."
2206 .to_string(),
2207 );
2208 }
2209
2210 let sample_orientations = match (graphs.clone(), orientations) {
2211 (SumMode::Summed, SumMode::Summed) => false,
2212 (SumMode::Summed, SumMode::MonteCarlo) => {
2213 return Err(
2214 "Invalid sampling settings: orientations can only be set to 'monte_carlo' when graphs is 'monte_carlo'.".to_string(),
2215 )
2216 }
2217 (SumMode::MonteCarlo, SumMode::Summed) => false,
2218 (SumMode::MonteCarlo, SumMode::MonteCarlo) => true,
2219 };
2220
2221 if matches!(coordinate_system, CoordinateSystem::MomTrop) {
2222 if sampling_channel_weight != SamplingChannelWeight::MapDensity
2223 || !default_channel_selection.is_empty()
2224 || !channel_selection.is_empty()
2225 || !channel_definitions.is_empty()
2226 {
2227 return Err(
2228 "Invalid sampling settings: advanced sampling channels are incompatible with tropical coordinates."
2229 .to_string(),
2230 );
2231 }
2232 if !lmb_basis_ids.is_empty() {
2233 return Err(
2234 "Invalid sampling settings: coordinate_system = 'tropical' is incompatible with lmb_basis_ids."
2235 .to_string(),
2236 );
2237 }
2238 if !matches!(graphs, SumMode::MonteCarlo) {
2239 return Err(
2240 "Invalid sampling settings: coordinate_system = 'tropical' requires graphs = 'monte_carlo'."
2241 .to_string(),
2242 );
2243 }
2244
2245 if sampling_multichanneling {
2246 return Err(
2247 "Invalid sampling settings: coordinate_system = 'tropical' is incompatible with sampling_multichanneling = true."
2248 .to_string(),
2249 );
2250 }
2251
2252 return Ok(SamplingSettings::DiscreteGraphs(
2253 DiscreteGraphSamplingSettings {
2254 graph_names,
2255 sample_orientations,
2256 sampling_type: DiscreteGraphSamplingType::TropicalSampling(
2257 GammaloopTropicalSamplingSettings::default(),
2258 ),
2259 },
2260 ));
2261 }
2262
2263 let mode = coordinate_system.into_mode();
2264 if matches!(mode, ParameterizationMode::SphericalProductCommonRadial)
2265 && (!sampling_multichanneling
2266 || sampling_channel_weight != SamplingChannelWeight::InverseJacobian)
2267 {
2268 return Err(
2269 "Invalid sampling settings: coordinate_system = 'spherical_product_common_radial' requires sampling_multichanneling = true and sampling_channel_weight = 'inverse_jacobian'."
2270 .to_string(),
2271 );
2272 }
2273 if sampling_channel_weight == SamplingChannelWeight::InverseJacobian
2274 && matches!(mode, ParameterizationMode::HyperSphericalFlat)
2275 {
2276 return Err(
2277 "Invalid sampling settings: sampling_channel_weight = 'inverse_jacobian' is incompatible with coordinate_system = 'hyperspherical_flat' because the inverse map is not available."
2278 .to_string(),
2279 );
2280 }
2281 if matches!(mapping, ParameterizationMapping::Power) {
2282 if !matches!(
2283 mode,
2284 ParameterizationMode::Spherical
2285 | ParameterizationMode::RelativeSpherical
2286 | ParameterizationMode::SphericalCommonRadial
2287 | ParameterizationMode::SphericalProductCommonRadial
2288 | ParameterizationMode::HyperSpherical
2289 | ParameterizationMode::HyperSphericalFlat
2290 ) {
2291 return Err(
2292 "Invalid sampling settings: mapping = 'power' requires a spherical coordinate system."
2293 .to_string(),
2294 );
2295 }
2296 if !power.is_finite() || power < 1.0 {
2297 return Err(
2298 "Invalid sampling settings: mapping = 'power' requires power >= 1.".to_string(),
2299 );
2300 }
2301 }
2302 let parameterization_settings = ParameterizationSettings {
2303 mode,
2304 mapping,
2305 b,
2306 power,
2307 lmb_basis_ids,
2308 sampling_channels: SamplingChannelSelection {
2309 weight: sampling_channel_weight,
2310 alpha,
2311 default_channel_selection,
2312 channel_selection,
2313 channel_definitions,
2314 },
2315 };
2316
2317 match graphs {
2318 SumMode::Summed => {
2319 if !matches!(sampling_channels, SumMode::Summed) {
2320 return Err(
2321 "Invalid sampling settings: sampling_channels = 'monte_carlo' requires graphs = 'monte_carlo'."
2322 .to_string(),
2323 );
2324 }
2325
2326 if sample_orientations {
2327 return Err(
2328 "Invalid sampling settings: orientations can only be Monte Carlo sampled when graphs are Monte Carlo sampled."
2329 .to_string(),
2330 );
2331 }
2332
2333 if sampling_multichanneling {
2334 Ok(SamplingSettings::MultiChanneling(MultiChannelingSettings {
2335 parameterization_settings,
2336 }))
2337 } else {
2338 Ok(SamplingSettings::Default(parameterization_settings))
2339 }
2340 }
2341 SumMode::MonteCarlo => {
2342 let sampling_type = if sampling_multichanneling {
2343 let settings = MultiChannelingSettings {
2344 parameterization_settings,
2345 };
2346
2347 match sampling_channels {
2348 SumMode::Summed => DiscreteGraphSamplingType::MultiChanneling(settings),
2349 SumMode::MonteCarlo => {
2350 DiscreteGraphSamplingType::SamplingMultiChanneling(settings)
2351 }
2352 }
2353 } else {
2354 DiscreteGraphSamplingType::Default(parameterization_settings)
2355 };
2356
2357 Ok(SamplingSettings::DiscreteGraphs(
2358 DiscreteGraphSamplingSettings {
2359 graph_names,
2360 sample_orientations,
2361 sampling_type,
2362 },
2363 ))
2364 }
2365 }
2366 }
2367}
2368
2369impl Serialize for SamplingSettings {
2370 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
2371 where
2372 S: Serializer,
2373 {
2374 self.as_parser().serialize(serializer)
2375 }
2376}
2377
2378impl<'de> Deserialize<'de> for SamplingSettings {
2379 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2380 where
2381 D: Deserializer<'de>,
2382 {
2383 let parser = SamplingSettingsParser::deserialize(deserializer)?;
2384 SamplingSettings::from_parser(parser).map_err(serde::de::Error::custom)
2385 }
2386}
2387
2388impl JsonSchema for SamplingSettings {
2389 fn schema_name() -> std::borrow::Cow<'static, str> {
2390 "SamplingSettings".into()
2391 }
2392
2393 fn json_schema(generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
2394 SamplingSettingsParser::json_schema(generator)
2395 }
2396}
2397
2398impl CoordinateSystem {
2399 fn from_mode(mode: ParameterizationMode) -> Self {
2400 match mode {
2401 ParameterizationMode::Cartesian => Self::Cartesian,
2402 ParameterizationMode::Spherical => Self::Spherical,
2403 ParameterizationMode::RelativeSpherical => Self::RelativeSpherical,
2404 ParameterizationMode::SphericalCommonRadial => Self::SphericalCommonRadial,
2405 ParameterizationMode::SphericalProductCommonRadial => {
2406 Self::SphericalProductCommonRadial
2407 }
2408 ParameterizationMode::HyperSpherical => Self::HyperSpherical,
2409 ParameterizationMode::HyperSphericalFlat => Self::HyperSphericalFlat,
2410 ParameterizationMode::MomentumSpace => Self::MomentumSpace,
2411 }
2412 }
2413
2414 fn into_mode(self) -> ParameterizationMode {
2415 match self {
2416 CoordinateSystem::Cartesian => ParameterizationMode::Cartesian,
2417 CoordinateSystem::Spherical => ParameterizationMode::Spherical,
2418 CoordinateSystem::RelativeSpherical => ParameterizationMode::RelativeSpherical,
2419 CoordinateSystem::SphericalCommonRadial => ParameterizationMode::SphericalCommonRadial,
2420 CoordinateSystem::SphericalProductCommonRadial => {
2421 ParameterizationMode::SphericalProductCommonRadial
2422 }
2423 CoordinateSystem::HyperSpherical => ParameterizationMode::HyperSpherical,
2424 CoordinateSystem::HyperSphericalFlat => ParameterizationMode::HyperSphericalFlat,
2425 CoordinateSystem::MomentumSpace => ParameterizationMode::MomentumSpace,
2426 CoordinateSystem::MomTrop => {
2427 unreachable!("tropical coordinate system has no ParameterizationMode equivalent")
2428 }
2429 }
2430 }
2431}
2432
2433impl SamplingSettings {
2434 pub(crate) fn uses_sampling_channels(&self) -> bool {
2438 match self {
2439 Self::MultiChanneling(_) => true,
2440 Self::DiscreteGraphs(settings) => matches!(
2441 &settings.sampling_type,
2442 DiscreteGraphSamplingType::MultiChanneling(_)
2443 | DiscreteGraphSamplingType::SamplingMultiChanneling(_)
2444 ),
2445 Self::Default(_) => false,
2446 }
2447 }
2448
2449 pub fn selected_graph_names(&self) -> &[String] {
2450 match self {
2451 SamplingSettings::DiscreteGraphs(settings) => &settings.graph_names,
2452 SamplingSettings::Default(_) | SamplingSettings::MultiChanneling(_) => &[],
2453 }
2454 }
2455
2456 pub fn get_parameterization_settings(&self) -> Option<ParameterizationSettings> {
2457 match self {
2458 SamplingSettings::Default(settings) => Some(settings.clone()),
2459 SamplingSettings::MultiChanneling(settings) => {
2460 Some(settings.parameterization_settings.clone())
2461 }
2462 SamplingSettings::DiscreteGraphs(settings) => match &settings.sampling_type {
2463 DiscreteGraphSamplingType::Default(settings) => Some(settings.clone()),
2464 DiscreteGraphSamplingType::MultiChanneling(settings) => {
2465 Some(settings.parameterization_settings.clone())
2466 }
2467 DiscreteGraphSamplingType::SamplingMultiChanneling(settings) => {
2468 Some(settings.parameterization_settings.clone())
2469 }
2470 DiscreteGraphSamplingType::TropicalSampling(_) => None,
2471 },
2472 }
2473 }
2474
2475 pub(crate) fn discrete_depth(&self) -> usize {
2476 match self {
2477 SamplingSettings::Default(_) => 0,
2478 SamplingSettings::MultiChanneling(_) => 0,
2479 SamplingSettings::DiscreteGraphs(settings) => {
2480 let depth_from_orientations = settings.sample_orientations as usize;
2481
2482 match &settings.sampling_type {
2483 DiscreteGraphSamplingType::Default(_) => 1 + depth_from_orientations,
2484 DiscreteGraphSamplingType::MultiChanneling(_) => 1 + depth_from_orientations,
2485 DiscreteGraphSamplingType::SamplingMultiChanneling(_) => {
2486 2 + depth_from_orientations
2487 }
2488 DiscreteGraphSamplingType::TropicalSampling(_) => 1 + depth_from_orientations,
2489 }
2490 }
2491 }
2492 }
2493
2494 pub(crate) fn describe_settings(&self) -> String {
2495 match self {
2496 SamplingSettings::Default(settings) => {
2497 format!("{} coordinates", settings.mode)
2498 }
2499 SamplingSettings::MultiChanneling(settings) => {
2500 format!(
2501 "lmb multichanneling in {} coordinates",
2502 settings.parameterization_settings.mode
2503 )
2504 }
2505 SamplingSettings::DiscreteGraphs(settings) => {
2506 let discrete_graph_string = if settings.graph_names.is_empty() {
2507 "Monte Carlo over graphs".to_string()
2508 } else {
2509 format!(
2510 "Monte Carlo over selected graph groups [{}]",
2511 settings.graph_names.join(", ")
2512 )
2513 };
2514 let orientation_sampling_string = if settings.sample_orientations {
2515 "and Monte Carlo over orientations"
2516 } else {
2517 ""
2518 };
2519
2520 match &settings.sampling_type {
2521 DiscreteGraphSamplingType::Default(settings) => {
2522 format!(
2523 "{} {} in {} coordinates",
2524 discrete_graph_string, orientation_sampling_string, settings.mode
2525 )
2526 }
2527 DiscreteGraphSamplingType::MultiChanneling(settings) => {
2528 format!(
2529 "{}, lmb multichanneling in {} coordinates {}",
2530 discrete_graph_string,
2531 settings.parameterization_settings.mode,
2532 orientation_sampling_string,
2533 )
2534 }
2535 DiscreteGraphSamplingType::SamplingMultiChanneling(settings) => {
2536 format!(
2537 "{}, {} and monte carlo over lmbs in {} coordinates",
2538 discrete_graph_string,
2539 orientation_sampling_string,
2540 settings.parameterization_settings.mode
2541 )
2542 }
2543 DiscreteGraphSamplingType::TropicalSampling(_) => {
2544 format!(
2545 "{} {} using 🌴🥥 tropical sampling 🥥🌴",
2546 discrete_graph_string, orientation_sampling_string,
2547 )
2548 }
2549 }
2550 }
2551 }
2552 }
2553}
2554
2555#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2556#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2557#[serde(deny_unknown_fields, default)]
2558pub struct MultiChannelingSettings {
2559 #[serde(skip_serializing_if = "IsDefault::is_default")]
2561 pub parameterization_settings: ParameterizationSettings,
2562}
2563
2564#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2565#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2566#[serde(deny_unknown_fields, default)]
2567pub struct GammaloopTropicalSamplingSettings {
2568 #[serde(skip_serializing_if = "is_true")]
2570 pub upcast_on_failure: bool,
2571 #[serde(skip_serializing_if = "IsDefault::is_default")]
2573 pub matrix_stability_test: Option<f64>,
2574}
2575
2576impl Default for GammaloopTropicalSamplingSettings {
2577 fn default() -> Self {
2578 Self {
2579 upcast_on_failure: true,
2580 matrix_stability_test: None,
2581 }
2582 }
2583}
2584
2585impl GammaloopTropicalSamplingSettings {
2586 pub fn into_tropical_sampling_settings(&self) -> momtrop::TropicalSamplingSettings {
2587 momtrop::TropicalSamplingSettings {
2588 matrix_stability_test: self.matrix_stability_test,
2589 print_debug_info: false,
2590 return_metadata: false,
2591 }
2592 }
2593}
2594
2595#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2596#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2597#[serde(tag = "subtype", deny_unknown_fields)]
2598pub enum DiscreteGraphSamplingType {
2599 #[serde(rename = "default")]
2600 Default(ParameterizationSettings),
2601 #[serde(rename = "multi_channeling")]
2602 MultiChanneling(MultiChannelingSettings),
2603 #[serde(rename = "discrete_multi_channeling")]
2604 SamplingMultiChanneling(MultiChannelingSettings),
2605 #[serde(rename = "tropical")]
2606 TropicalSampling(GammaloopTropicalSamplingSettings),
2607}
2608
2609impl Default for DiscreteGraphSamplingType {
2610 fn default() -> Self {
2611 DiscreteGraphSamplingType::Default(ParameterizationSettings::default())
2612 }
2613}
2614
2615#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2616#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema, Default)]
2617#[serde(deny_unknown_fields, default)]
2618pub struct DiscreteGraphSamplingSettings {
2619 #[serde(skip_serializing_if = "IsDefault::is_default")]
2621 pub graph_names: Vec<String>,
2622 #[serde(skip_serializing_if = "is_false")]
2624 pub sample_orientations: bool,
2625 #[serde(skip_serializing_if = "IsDefault::is_default")]
2627 pub sampling_type: DiscreteGraphSamplingType,
2628}
2629
2630#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2631#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2632#[serde(deny_unknown_fields, default)]
2633pub struct LocalCounterTermSettings {
2634 #[serde(skip_serializing_if = "IsDefault::is_default")]
2636 pub uv_localisation: UVLocalisationSettings,
2637}
2638
2639#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2640#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2641#[serde(default, deny_unknown_fields)]
2642pub struct UVLocalisationSettings {
2643 #[serde(skip_serializing_if = "is_float::<10>")]
2645 pub sliver_width: f64,
2646 #[serde(skip_serializing_if = "is_false")]
2648 pub smooth_sliver: bool,
2649 #[serde(skip_serializing_if = "is_false")]
2651 pub dynamic_width: bool,
2652 #[serde(skip_serializing_if = "is_float::<1>")]
2654 pub gaussian_width: f64,
2655 #[serde(skip_serializing_if = "is_false")]
2657 pub force_uv_dampers_to_one: bool,
2658}
2659
2660impl Default for UVLocalisationSettings {
2661 fn default() -> Self {
2662 Self {
2663 sliver_width: 10.0,
2664 smooth_sliver: false,
2665 dynamic_width: false,
2666 gaussian_width: 1.0,
2667 force_uv_dampers_to_one: false,
2668 }
2669 }
2670}
2671
2672#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2673#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2674#[serde(deny_unknown_fields, default)]
2675pub struct IntegratedCounterTermSettings {
2676 #[serde(skip_serializing_if = "IsDefault::is_default")]
2678 pub range: IntegratedCounterTermRange,
2679}
2680
2681#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2682#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2683#[serde(tag = "type")]
2684#[serde(deny_unknown_fields)]
2685pub enum IntegratedCounterTermRange {
2686 #[serde(rename = "infinite")]
2688 Infinite {
2689 h_function_settings: HFunctionSettings,
2691 },
2692 #[serde(rename = "compact")]
2694 Compact {},
2695}
2696
2697impl Default for IntegratedCounterTermRange {
2698 fn default() -> Self {
2699 Self::Infinite {
2700 h_function_settings: HFunctionSettings::default(),
2701 }
2702 }
2703}
2704
2705#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object, get_all, set_all))]
2706#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2707#[serde(deny_unknown_fields)]
2708#[serde(default)]
2709pub struct OverlapSettings {
2710 #[serde(skip_serializing_if = "IsDefault::is_default")]
2713 pub force_global_center: Option<Vec<[f64; 3]>>,
2714 #[serde(skip_serializing_if = "is_true")]
2716 pub check_global_center: bool,
2717 #[serde(skip_serializing_if = "is_true")]
2719 pub try_origin: bool,
2720 #[serde(skip_serializing_if = "is_false")]
2722 pub try_origin_all_lmbs: bool,
2723}
2724
2725impl Default for OverlapSettings {
2726 fn default() -> Self {
2727 Self {
2728 force_global_center: None,
2729 check_global_center: true,
2730 try_origin: true,
2731 try_origin_all_lmbs: false,
2732 }
2733 }
2734}
2735
2736#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
2737#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2738#[serde(deny_unknown_fields)]
2739pub enum HFunction {
2741 #[default]
2742 #[serde(rename = "poly_exponential")]
2743 PolyExponential,
2744 #[serde(rename = "exponential")]
2745 Exponential,
2746 #[serde(rename = "poly_left_right_exponential")]
2747 PolyLeftRightExponential,
2748 #[serde(rename = "exponential_ct")]
2749 ExponentialCT,
2750}
2751
2752#[cfg_attr(feature = "python", pyo3::pyclass(from_py_object))]
2753#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Encode, Decode, JsonSchema)]
2754#[serde(deny_unknown_fields)]
2755#[serde(default)]
2756pub struct HFunctionSettings {
2757 #[serde(skip_serializing_if = "IsDefault::is_default")]
2759 pub function: HFunction,
2760 #[serde(skip_serializing_if = "is_float::<1>")]
2762 pub sigma: f64,
2763 #[serde(skip_serializing_if = "is_true")]
2765 pub enabled_dampening: bool,
2766 #[serde(skip_serializing_if = "IsDefault::is_default")]
2768 pub power: Option<usize>,
2769}
2770
2771impl Default for HFunctionSettings {
2772 fn default() -> Self {
2773 Self {
2774 sigma: 1.0,
2775 function: HFunction::default(),
2776 enabled_dampening: true,
2777 power: None,
2778 }
2779 }
2780}
2781
2782impl HFunctionSettings {
2783 const NORMALIZED_POWERS: [usize; 12] = [0, 1, 3, 4, 6, 7, 9, 10, 12, 13, 15, 16];
2785
2786 pub(crate) fn normalization<T: FloatLike>(&self, sigma: &F<T>) -> F<T> {
2792 let one = sigma.one();
2793 let power = self.power.unwrap_or(0);
2794 if self.function != HFunction::Exponential && !Self::NORMALIZED_POWERS.contains(&power) {
2795 panic!("Value {power} of power in poly exponential h function not supported");
2796 }
2797 let unit = match self.function {
2798 HFunction::Exponential => Self::scaled_bessel_k_at_two(1, &one),
2799 HFunction::PolyExponential => Self::scaled_bessel_k_at_two(power.abs_diff(1), &one),
2800 HFunction::PolyLeftRightExponential => {
2801 one.from_usize(2) * Self::scaled_bessel_k_at_two(2 * power.abs_diff(1), &one)
2802 }
2803 HFunction::ExponentialCT => {
2804 unreachable!("exponential_ct is a threshold localization without a normalization")
2805 }
2806 };
2807 unit * sigma
2808 }
2809
2810 fn scaled_bessel_k_at_two<T: FloatLike>(twice_order: usize, one: &F<T>) -> F<T> {
2819 use std::{
2820 any::{Any, TypeId},
2821 cell::RefCell,
2822 collections::HashMap,
2823 };
2824 use symbolica::domains::float::SingleFloat;
2825
2826 if twice_order % 2 == 1 {
2827 let n = twice_order / 2;
2828 let sum = (0..=n).fold(Rational::zero(), |sum, k| {
2829 sum + Rational::from((
2830 Integer::factorial((n + k) as u32),
2831 Integer::factorial(k as u32)
2832 * Integer::factorial((n - k) as u32)
2833 * Integer::from(4).pow(k as u64),
2834 ))
2835 });
2836 return one.PI().sqrt() * one.from_rational(&(sum / Rational::from(2)));
2837 }
2838 type NativeValues = HashMap<(TypeId, u32, usize), Box<dyn Any>>;
2842 thread_local! {
2843 static CACHE: RefCell<NativeValues> = RefCell::default();
2844 }
2845 let key = (TypeId::of::<T>(), one.0.get_precision(), twice_order);
2846 if let Some(value) = CACHE.with_borrow(|cache| {
2847 cache.get(&key).map(|value| {
2848 value
2849 .downcast_ref::<F<T>>()
2850 .expect("cache key includes the numeric type")
2851 .clone()
2852 })
2853 }) {
2854 return value;
2855 }
2856
2857 let (mut i0, mut i1, mut harmonic_sum) = (one.zero(), one.zero(), one.zero());
2859 let (mut inverse_square, mut harmonic) = (one.clone(), one.zero());
2860 for k in 1.. {
2861 i0 += &inverse_square;
2862 i1 += &inverse_square / one.from_usize(k);
2863 inverse_square = &inverse_square / one.from_usize(k * k);
2864 harmonic += one.from_usize(k).inv();
2865 let term = &harmonic * &inverse_square;
2867 harmonic_sum += &term;
2868 if term <= &harmonic_sum * one.epsilon() {
2869 break;
2870 }
2871 }
2872 let k0 = harmonic_sum - one.euler() * &i0;
2873 let k1 = (one.from_usize(2).inv() - &i1 * &k0) / &i0;
2874 let order = twice_order / 2;
2875 let (mut lower, mut upper) = (k0, k1);
2876 for n in 1..order {
2877 (lower, upper) = (upper.clone(), lower + one.from_usize(n) * &upper);
2878 }
2879 let value = one.from_usize(2).exp() * if order == 0 { lower } else { upper };
2880 CACHE.with_borrow_mut(|cache| {
2881 if cache.len() == 1024 {
2883 cache.clear();
2884 }
2885 cache.insert(key, Box::new(value.clone()));
2886 });
2887 value
2888 }
2889
2890 pub(crate) fn validate_normalized_profile(&self) -> Result<()> {
2893 if !self.sigma.is_finite() || self.sigma <= 0.0 {
2894 return Err(eyre::eyre!(
2895 "A normalized h_function profile requires a positive finite h_function.sigma; got {}",
2896 self.sigma
2897 ));
2898 }
2899 match self.function {
2900 HFunction::Exponential => Ok(()),
2901 HFunction::PolyExponential | HFunction::PolyLeftRightExponential => {
2902 let power = self.power.unwrap_or(0);
2903 if Self::NORMALIZED_POWERS.contains(&power) {
2904 Ok(())
2905 } else {
2906 Err(eyre::eyre!(
2907 "Unsupported h_function.power {power}; supported powers are {:?}",
2908 Self::NORMALIZED_POWERS
2909 ))
2910 }
2911 }
2912 HFunction::ExponentialCT => Err(eyre::eyre!(
2913 "exponential_ct is a local threshold localization, not a normalized h_function profile"
2914 )),
2915 }
2916 }
2917}