Skip to main content

gammalooprs/utils/
mod.rs

1use crate::integrands::process::{
2    GenericEvaluatorFloat, LmbMultiChannelingSetup, SamplingChannelBridge,
3    sampling::maps::SamplingEvaluationError,
4};
5use crate::model::Model;
6use crate::momentum::sample::{
7    ExternalFourMomenta, ExternalIndex, ExternalThreeMomenta, LoopMomenta, SubspaceData,
8};
9use crate::momentum::signature::{ExternalSignature, LoopSignature};
10use crate::momentum::{FourMomentum, ThreeMomentum};
11use crate::numerator::aind::Aind;
12use crate::settings::runtime::ParameterizationSettings;
13use crate::settings::runtime::SamplingSettings;
14use crate::settings::runtime::kinematic::Externals;
15use crate::settings::runtime::{ParameterizationMapping, ParameterizationMode};
16use crate::utils::hyperdual_utils::new_constant;
17
18use bincode::{Decode, Encode};
19use colored::Colorize;
20use itertools::Itertools;
21use linnet::half_edge::involution::EdgeIndex;
22
23use rand::Rng;
24use ref_ops::{RefAdd, RefDiv, RefMul, RefNeg, RefRem, RefSub};
25use rug::float::{Constant, ParseFloatError, Round};
26use rug::ops::{CompleteRound, Pow};
27use rug::{Assign, Float};
28use schemars::JsonSchema;
29use serde::{Deserialize, Deserializer, Serialize};
30use smallvec::SmallVec;
31use spenso::algebra::algebraic_traits::RefOne;
32use spenso::algebra::algebraic_traits::RefZero;
33use spenso::algebra::complex::Complex;
34use spenso::algebra::complex::R;
35use spenso::algebra::complex::SymbolicaComplex;
36use spenso::algebra::complex::symbolica_traits::ToFloat;
37use spenso::algebra::upgrading_arithmetic::TrySmallestUpgrade;
38use spenso::network::library::TensorLibraryData;
39use spenso::network::library::function_lib::{INBUILTS, Panic, SymbolLib, Wrap};
40use spenso::network::library::symbolic::{ExplicitKey, TensorLibrary};
41use spenso::network::parsing::ShadowedStructure;
42use spenso::structure::concrete_index::ExpandedIndex;
43use spenso::tensors::data::StorageTensor;
44use spenso::tensors::parametric::ParamTensor;
45use spenso::tensors::parametric::to_param::ToAtom;
46use spenso_hep_lib::hep_lib_atom;
47use symbolica::domains::float::Magnitude;
48use symbolica::{
49    domains::{
50        dual::HyperDual,
51        float::{FixedPrecision, Float as SymbolicaFloat, FloatLike as SymFloatLike},
52    },
53    prelude::*,
54};
55
56use std::cell::RefCell;
57use std::cmp::{Ord, Ordering};
58use std::collections::HashMap;
59use std::fmt::{Debug, Display};
60use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Rem, Sub, SubAssign};
61use std::str::FromStr;
62use std::sync::{LazyLock, OnceLock, RwLock};
63use std::time::Duration;
64
65use vakint::Vakint;
66// use symbolica_community::physics::tensors::library::{
67//     gamma5_weyl_data, gamma_data_weyl, proj_m_data_weyl, proj_p_data_weyl, SpensorLibrary,
68//     TensorNamespace,
69// };
70// use symbolica_community::physics::tensors::structure::SpensoStucture;
71// use symbolica::domains::Field;
72use crate::MAX_LOOP;
73use ::tracing::debug;
74use typed_index_collections::TiVec;
75
76/// Transient runtime data which contributes no bytes to persisted state.
77/// Decoding always starts empty, so numerical bindings are rebuilt at warmup.
78#[derive(Clone, Debug, PartialEq)]
79pub struct RuntimeCache<T>(Option<T>);
80
81impl<T> Default for RuntimeCache<T> {
82    fn default() -> Self {
83        Self(None)
84    }
85}
86
87impl<T> RuntimeCache<T> {
88    pub(crate) fn invalidate(&mut self) {
89        self.0 = None;
90    }
91
92    pub(crate) fn set(&mut self, value: T) {
93        self.0 = Some(value);
94    }
95
96    pub(crate) fn take(&mut self) -> Option<T> {
97        self.0.take()
98    }
99
100    pub(crate) fn as_ref(&self) -> Option<&T> {
101        self.0.as_ref()
102    }
103
104    pub(crate) fn as_mut(&mut self) -> Option<&mut T> {
105        self.0.as_mut()
106    }
107}
108
109impl<T> bincode::Encode for RuntimeCache<T> {
110    fn encode<E: bincode::enc::Encoder>(
111        &self,
112        _encoder: &mut E,
113    ) -> std::result::Result<(), bincode::error::EncodeError> {
114        Ok(())
115    }
116}
117
118impl<C, T> bincode::Decode<C> for RuntimeCache<T> {
119    fn decode<D: bincode::de::Decoder<Context = C>>(
120        _decoder: &mut D,
121    ) -> std::result::Result<Self, bincode::error::DecodeError> {
122        Ok(Self::default())
123    }
124}
125
126pub const GIT_VERSION: &str = env!("CARGO_PKG_VERSION");
127pub const VERSION: &str = "0.0.1";
128pub mod fitting;
129pub mod hyperdual_utils;
130pub mod progress;
131pub mod representations;
132pub mod serde_utils;
133pub use progress::{long_running_progress_style, long_running_progress_style_with_eta_warmup};
134/// can be used instead of commenting out code
135#[macro_export]
136macro_rules! disable {
137    ($($tokens:tt)*) => {};
138}
139
140/// Shorthand for tagged debug events.
141///
142/// `#tag` expands to `tag = true` and the remaining tokens are forwarded to
143/// `tracing::debug!` unchanged.
144///
145/// GammaLoop's logging DSL treats tags as boolean event fields.
146///
147/// Emitting `#generation` makes directives such as `[{generation}]` eligible to
148/// match this event. A negated directive term such as `[{!inspect}]` matches
149/// events where the field is absent. If you need value-sensitive filtering, use
150/// an explicit field such as `inspect = false` or `mode = "summary"` at the
151/// callsite and a directive such as `[{inspect=false}]` or `[{mode=summary}]`.
152///
153/// Separately, the formatter supports sink-only field prefixes:
154/// - `file.<name>` is rendered only in the logfile/json sink
155/// - `display.<name>` is rendered only in the stderr/display sink
156///
157/// For example, `file.integrands = %expr` is useful for attaching large dumps
158/// to the logfile without printing them to stderr.
159///
160/// Pipeline-wide tag set:
161///
162/// Prefer a small stable vocabulary that cuts across the whole pipeline.
163///
164/// Primary phase tags:
165///
166/// | Tag | Meaning |
167/// | --- | --- |
168/// | `#generation` | Work that builds or prepares runtime objects before Monte Carlo integration starts |
169/// | `#integration` | Work performed while evaluating samples or managing the adaptive integration loop |
170/// | `#profile` | UV/IR/profile-style diagnostic scans and their analysis |
171/// | `#persistence` | Reading or writing saved state, manifests, checkpoints, and exported results |
172///
173/// Core domain tags:
174///
175/// | Tag | Meaning |
176/// | --- | --- |
177/// | `#uv` | Ultraviolet counterterms, UV forests, UV profiles, or UV-specific generation/evaluation logic |
178/// | `#ir` | Infrared subtraction, IR profiles, or IR-specific generation/evaluation logic |
179/// | `#subtraction` | Threshold, UV, or IR subtraction logic when the main concern is subtraction rather than the specific regime |
180/// | `#sampling` | Channel choice, discrete axes, parameterizations, or sample-generation choices |
181/// | `#stability` | Precision escalation, retries, instability diagnosis, and numerical safety checks |
182/// | `#observables` | Histogramming, event-to-observable projection, and observable snapshot production |
183/// | `#selectors` | Event-selection logic and selector decisions |
184/// | `#cache` | Cache lookup, reuse, invalidation, or cache-debug instrumentation |
185///
186/// Common work-unit tags:
187///
188/// | Tag | Meaning |
189/// | --- | --- |
190/// | `#graph` | The log is about one graph or graph-local data |
191/// | `#group` | The log is about a graph group or another explicitly grouped aggregate |
192/// | `#orientation` | The log is about orientation-dependent data or choosing/summing orientations |
193/// | `#channel` | The log is about multi-channeling or a particular channel |
194/// | `#cut` | The log is about a cut, raised cut, or cut-local computation |
195/// | `#event` | The log is about generated/retained event objects or event-group processing |
196/// | `#sample` | The log is about one evaluation sample, its coordinates, or per-sample intermediate values |
197/// | `#iteration` | The log is about one adaptive integration iteration or iteration-level summaries |
198/// | `#term` | The log is about one algebraic term, summand, or term-local contribution |
199///
200/// Common purpose tags:
201///
202/// | Tag | Meaning |
203/// | --- | --- |
204/// | `#solver` | The log is about root-finding, linear solves, fitting, or similar numerical solver state |
205/// | `#compile` | The log is about evaluator/code generation or compilation-oriented preparation |
206/// | `#inspect` | The log exposes detailed intermediate state for debugging, rather than a high-level milestone |
207/// | `#summary` | The log is a compact roll-up rather than a step-by-step trace |
208/// | `#dump` | The log emits large or structured payloads such as expressions, tables, or serialized views |
209///
210/// Tag boundaries:
211///
212/// - Prefer `#generation` over `#compile` when the message is a broad generation milestone.
213/// - Add `#compile` only when the message is specifically about evaluator construction or compilation-like work.
214/// - Prefer `#uv` or `#ir` when the regime matters to the user; use `#subtraction` when the subtraction mechanism is the real concern.
215/// - Prefer `#inspect` for verbose intermediate values that are mainly useful while debugging internals.
216/// - Add `#dump` when the payload is large enough that users may want to suppress it separately from lighter debug logs.
217/// - Do not use `#graph`, `#cut`, or `#sample` as substitutes for `#generation` or `#integration`; they refine phase tags rather than replace them.
218///
219/// Naming guidance:
220///
221/// - Use phase tags first. They answer "when in the pipeline did this happen?"
222/// - Use domain tags second. They answer "what subsystem is this about?"
223/// - Use work-unit tags third. They answer "what object is being worked on?"
224/// - Use purpose tags last for optional refinement.
225/// - Prefer tags that are meaningful across multiple modules.
226/// - Avoid tags that merely restate a function name.
227/// - Avoid tags tied to one internal representation unless that representation is a stable concept in user-facing debugging.
228///
229/// `parametric` is usually not a core pipeline tag. It is acceptable as a local refinement when needed, but should not be treated as part of the primary vocabulary unless it becomes a consistently useful cross-cutting concept.
230///
231/// Examples:
232/// - `debug_tags!(#generation, #uv, #graph, #dump; name = %graph.name, "generated graph payload");`
233/// - `debug_tags!(#integration, #summary; inspect = false, "iteration summary");`
234#[macro_export]
235macro_rules! debug_tags {
236    (@collect_tags [$($acc:tt)*] # $tag:ident, $($tail:tt)*) => {
237        $crate::debug_tags!(@collect_tags [$($acc)* $tag = true,] $($tail)*)
238    };
239    (@collect_tags [$($acc:tt)*] # $tag:ident; $($rest:tt)*) => {
240        $crate::debug_tags!(@collect_fields [$($acc)* $tag = true,] [] $($rest)*)
241    };
242    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] log.$name:ident = $value:expr, $($tail:tt)*) => {
243        $crate::debug_tags!(@collect_fields
244            [$($tags)*]
245            [$($fields)*
246                display.$name = %$crate::LogMessage::log_display(&$value),
247                file.$name = %$crate::LogMessage::log_file(&$value),
248            ]
249            $($tail)*
250        )
251    };
252    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $prefix:ident.$name:ident = %$value:expr, $($tail:tt)*) => {
253        $crate::debug_tags!(@collect_fields [$($tags)*] [$($fields)* $prefix.$name = %$value,] $($tail)*)
254    };
255    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $prefix:ident.$name:ident = ?$value:expr, $($tail:tt)*) => {
256        $crate::debug_tags!(@collect_fields [$($tags)*] [$($fields)* $prefix.$name = ?$value,] $($tail)*)
257    };
258    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $prefix:ident.$name:ident = $value:expr, $($tail:tt)*) => {
259        $crate::debug_tags!(@collect_fields [$($tags)*] [$($fields)* $prefix.$name = $value,] $($tail)*)
260    };
261    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $name:ident = %$value:expr, $($tail:tt)*) => {
262        $crate::debug_tags!(@collect_fields [$($tags)*] [$($fields)* $name = %$value,] $($tail)*)
263    };
264    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $name:ident = ?$value:expr, $($tail:tt)*) => {
265        $crate::debug_tags!(@collect_fields [$($tags)*] [$($fields)* $name = ?$value,] $($tail)*)
266    };
267    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $name:ident = $value:expr, $($tail:tt)*) => {
268        $crate::debug_tags!(@collect_fields [$($tags)*] [$($fields)* $name = $value,] $($tail)*)
269    };
270    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $name:ident, $($tail:tt)*) => {
271        $crate::debug_tags!(@collect_fields [$($tags)*] [$($fields)* $name,] $($tail)*)
272    };
273    (@collect_fields [$($tags:tt)*] [$($fields:tt)*] $($rest:tt)+) => {
274        tracing::debug!($($tags)* $($fields)* $($rest)+)
275    };
276    ($($input:tt)*) => {
277        $crate::debug_tags!(@collect_tags [] $($input)*)
278    };
279}
280
281#[allow(unused)]
282const MAX_DIMENSION: usize = MAX_LOOP * 3;
283
284pub(crate) const ESURFACE_SHIFT_THRESHOLD: f64 = 1.0e-13;
285/// Default dimensionless tolerance for E-surface invariant-mass-squared margins.
286pub const DEFAULT_ESURFACE_EXISTENCE_THRESHOLD: f64 = 1.0e-7;
287
288pub const LEFT: usize = 0;
289pub const RIGHT: usize = 1;
290
291#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
292pub enum Side {
293    LEFT = 0,
294    RIGHT = 1,
295}
296
297impl From<Side> for usize {
298    fn from(val: Side) -> Self {
299        val as usize
300    }
301}
302
303pub mod linnet_ext;
304pub mod symbolica_ext;
305pub mod tracing;
306
307#[cfg(test)]
308mod tests {
309    use super::{
310        ApproxEq, ArbPrec, Complex, F, FloatLike, QuadFloat, Real, SamplingFloat, SymbolicaComplex,
311    };
312    use rug::Float;
313    use symbolica::domains::float::DoubleFloat;
314
315    #[test]
316    fn complex_phases_compare_across_zero() {
317        let tolerance = F(1e-10);
318        let real = Complex::new(F(2.0), F(0.0));
319        let below = Complex::new(F(2.0), F(-1e-20));
320        assert!(below.approx_eq(&real, &tolerance));
321        assert!(real.approx_eq(&below, &tolerance));
322        assert!(below.approx_eq_res(&real, &tolerance).is_ok());
323
324        // The norms agree to 1.25e-13, so only the phase check (5e-7 apart) rejects this.
325        let off_phase = Complex::new(F(2.0), F(-1e-6));
326        assert!(!off_phase.approx_eq(&real, &tolerance));
327        assert!(!real.approx_eq(&off_phase, &tolerance));
328        assert!(off_phase.approx_eq_res(&real, &tolerance).is_err());
329    }
330
331    #[test]
332    fn complex_phases_preserve_tight_tolerances_across_zero() {
333        let tolerance = F(1e-18);
334        let real = Complex::new(F(2.0), F(0.0));
335        let below = Complex::new(F(2.0), F(-1e-16));
336        let phase_difference = (-1e-16_f64).atan2(2.0).abs();
337        assert!(phase_difference > tolerance.0);
338
339        let approx_equal = below.approx_eq(&real, &tolerance);
340        let diagnostic = below.approx_eq_res(&real, &tolerance);
341        assert!(
342            !approx_equal && diagnostic.is_err(),
343            "phase difference {phase_difference:e} exceeds tolerance {:e}: approx_eq={approx_equal}, approx_eq_res={diagnostic:?}",
344            tolerance.0
345        );
346    }
347
348    fn check_phase_comparison<T: FloatLike>(
349        lhs: &Complex<F<T>>,
350        rhs: &Complex<F<T>>,
351        tolerance: &F<T>,
352        expected: bool,
353    ) {
354        assert_eq!(
355            lhs.approx_eq(rhs, tolerance),
356            expected,
357            "lhs={lhs:+e}, rhs={rhs:+e}, tolerance={tolerance:+e}"
358        );
359        let diagnostic = lhs.approx_eq_res(rhs, tolerance);
360        assert_eq!(
361            diagnostic.is_ok(),
362            expected,
363            "lhs={lhs:+e}, rhs={rhs:+e}, tolerance={tolerance:+e}: {diagnostic:?}"
364        );
365        if !expected {
366            assert!(
367                diagnostic
368                    .unwrap_err()
369                    .to_string()
370                    .starts_with("Phases are not approximately equal:")
371            );
372        }
373    }
374
375    fn phase_boundary_controls<T: FloatLike>(prototype: &F<T>, exponent: i32, scales: &[i32]) {
376        let one = prototype.one();
377        let zero = prototype.zero();
378        let delta = prototype.from_usize(2).powi(-exponent);
379        let tight = &delta / prototype.from_usize(8);
380        let loose = &delta * prototype.from_usize(8);
381        let positive = Complex::new(one.clone(), zero.clone());
382        let below = Complex::new(one.clone(), -&delta);
383        let above = Complex::new(one.clone(), delta.clone());
384        // For these exact Cartesian sources, delta/2 < atan(delta) < delta.
385        // The factors of eight bound the decision independently of the kernel.
386        for (lhs, rhs) in [(&below, &positive), (&positive, &below)] {
387            check_phase_comparison(lhs, rhs, &tight, false);
388            check_phase_comparison(lhs, rhs, &loose, true);
389        }
390        // Preserve the directional RHS-relative policy: a zero reference uses
391        // absolute tolerance, a negative tiny phase wraps near TAU, and a
392        // positive tiny reference uses its own small phase as the divisor.
393        let asymmetric = &delta / prototype.from_usize(4);
394        check_phase_comparison(&below, &positive, &asymmetric, false);
395        check_phase_comparison(&positive, &below, &asymmetric, true);
396        check_phase_comparison(&above, &positive, &loose, true);
397        check_phase_comparison(&positive, &above, &loose, false);
398        check_phase_comparison(&below, &below, &tight, true);
399        let negative = Complex::new(-&one, zero);
400        let negative_above = Complex::new(-&one, delta.clone());
401        let negative_below = Complex::new(-&one, -&delta);
402        for (lhs, rhs) in [
403            (&negative_above, &negative_below),
404            (&negative_below, &negative_above),
405            (&negative, &negative_above),
406            (&negative_above, &negative),
407        ] {
408            check_phase_comparison(lhs, rhs, &tight, false);
409            check_phase_comparison(lhs, rhs, &loose, true);
410        }
411        for axis in [one.clone(), -&one] {
412            let reference = Complex::new(prototype.zero(), axis.clone());
413            for transverse in [delta.clone(), -&delta] {
414                let displaced = Complex::new(transverse, axis.clone());
415                for (lhs, rhs) in [(&displaced, &reference), (&reference, &displaced)] {
416                    check_phase_comparison(lhs, rhs, &tight, false);
417                    check_phase_comparison(lhs, rhs, &loose, true);
418                }
419            }
420        }
421        // Uniform magnitude changes must not change the phase decision. These
422        // scales keep the inherited (separately tested) norm check finite.
423        for &exponent in scales {
424            let scale = prototype.from_usize(2).powi(exponent);
425            let scaled_axis = Complex::new(scale.clone(), prototype.zero());
426            let scaled_below = Complex::new(scale.clone(), -(&delta * scale));
427            check_phase_comparison(&scaled_below, &scaled_axis, &tight, false);
428            check_phase_comparison(&scaled_below, &scaled_axis, &loose, true);
429        }
430    }
431
432    fn exact_phase_ratio_boundary<T: FloatLike>(prototype: &F<T>) {
433        let one = prototype.one();
434        let negative = Complex::new(-&one, prototype.zero());
435        // An exactly half-pi separation is half the negative-axis reference
436        // phase, but one full positive-y reference phase in the reverse order.
437        let positive_y = Complex::new(prototype.zero(), one.clone());
438        let half = &one / prototype.from_usize(2);
439        let three_quarters = prototype.from_usize(3) / prototype.from_usize(4);
440        check_phase_comparison(&positive_y, &negative, &half, false);
441        check_phase_comparison(&positive_y, &negative, &three_quarters, true);
442        check_phase_comparison(&negative, &positive_y, &three_quarters, false);
443    }
444
445    #[test]
446    fn complex_phase_boundaries_preserve_rhs_scaling_in_binary64() {
447        phase_boundary_controls(&F(0.0_f64), 60, &[-530, -200, 200]);
448        exact_phase_ratio_boundary(&F(0.0_f64));
449    }
450
451    #[test]
452    fn complex_phase_boundaries_preserve_double_double_sources() {
453        phase_boundary_controls(&F::<QuadFloat>::default(), 166, &[-200, 200]);
454    }
455
456    #[test]
457    fn complex_phase_boundaries_reconstruct_fresh_mpfr_sources() {
458        phase_boundary_controls(
459            &F(SamplingFloat::from(Float::with_val(256, 0))),
460            384,
461            &[-2000, 2000],
462        );
463        exact_phase_ratio_boundary(&F(SamplingFloat::from(Float::with_val(256, 0))));
464        // The source's tiny component is beyond binary64's exponent range.
465        phase_boundary_controls(
466            &F(ArbPrec::from(Float::with_val(1000, 0))),
467            1128,
468            &[-2000, 2000],
469        );
470        exact_phase_ratio_boundary(&F(ArbPrec::from(Float::with_val(1000, 0))));
471    }
472
473    #[test]
474    fn complex_phase_comparison_preserves_extreme_norm_controls() {
475        // Spenso's norm squares the components before taking the square root.
476        // These finite Cartesian inputs therefore leave the phase calculation
477        // through the inherited zero shortcut or norm rejection, respectively.
478        let tiny = Complex::new(F(2.0_f64.powi(-1000)), F(0.0));
479        assert_eq!(tiny.norm().re, F(0.0));
480        assert!(tiny.approx_eq(&tiny, &F(1e-10)));
481        assert!(tiny.approx_eq_res(&tiny, &F(1e-10)).is_ok());
482        let large = Complex::new(F(2.0_f64.powi(1000)), F(0.0));
483        assert!(large.norm().re.0.is_infinite());
484        assert!(!large.approx_eq(&large, &F(1e-10)));
485        assert!(
486            large
487                .approx_eq_res(&large, &F(1e-10))
488                .unwrap_err()
489                .to_string()
490                .starts_with("Norms are not approximately equal:")
491        );
492    }
493
494    #[test]
495    fn complex_phase_scaling_spans_admitted_fixed_precision_magnitudes() {
496        phase_boundary_controls(&F(0.0), 40, &[-500, 500]);
497        phase_boundary_controls(&F::<QuadFloat>::default(), 40, &[-500, 500]);
498    }
499
500    #[test]
501    fn complex_phase_scaling_preserves_tiny_references_at_large_magnitudes() {
502        for (real, imaginary) in [
503            (2.0_f64.powi(400), 2.0_f64.powi(-674)),
504            (2.0_f64.powi(500), 2.0_f64.powi(-574)),
505            // The magnitude bound rounds the real component's binade up.
506            // Without a guard binade the scaled imaginary source lands half
507            // an ulp below MIN_POSITIVE and rounds into its next-up neighbor.
508            (
509                2.0_f64.powi(500) * (1.0 - 2.0_f64.powi(-40)),
510                2.0_f64.powi(-575).next_down(),
511            ),
512        ] {
513            let rhs = Complex::new(F(real), F(imaginary));
514            let lhs = Complex::new(F(real), F(imaginary.next_up()));
515            assert!(rhs.norm().re.0.is_normal());
516            assert_eq!(lhs.norm().re, rhs.norm().re);
517            assert_eq!(rhs.arg().0, f64::from_bits(1));
518            // The Cartesian sources differ by one relative binary64 ulp in
519            // their imaginary component. Their angular gap is unrepresentable
520            // alone, but dividing by the nonzero RHS phase gives a value
521            // between 2^-55 and 2^-51 for these sources.
522            // Scaling the imaginary components into the subnormal range can
523            // erase that difference before the compensated determinant.
524            for (lhs, rhs) in [(&lhs, &rhs), (&rhs, &lhs)] {
525                check_phase_comparison(lhs, rhs, &F(2.0_f64.powi(-56)), false);
526                check_phase_comparison(lhs, rhs, &F(2.0_f64.powi(-50)), true);
527            }
528        }
529    }
530
531    #[test]
532    fn complex_phase_scaling_preserves_sparse_double_double_limbs() {
533        let scalar = |value: f64| F(QuadFloat::from(DoubleFloat::from(value)));
534        for exponent in [400, 500, 511] {
535            let real = scalar(2.0_f64.powi(exponent));
536            let imaginary = 2.0_f64.powi(exponent - 1074);
537            let low = f64::from_bits(1);
538            for perturbation in [-low, low] {
539                let rhs = Complex::new(real, scalar(imaginary));
540                let lhs = Complex::new(
541                    real,
542                    F(QuadFloat::from(DoubleFloat::from_compensated_sum(
543                        imaginary,
544                        perturbation,
545                    ))),
546                );
547                assert_eq!(lhs.im - rhs.im, scalar(perturbation));
548                assert_eq!(lhs.norm().re, real);
549                assert_eq!(rhs.norm().re, real);
550                assert_eq!(rhs.arg(), scalar(low));
551                for value in [&lhs, &rhs] {
552                    check_phase_comparison(
553                        value,
554                        value,
555                        &scalar(2.0_f64.powi(-exponent - 2)),
556                        true,
557                    );
558                }
559                // At exponent 500 the angular gap is near 2^-1574, below
560                // native range, but its RHS-relative value is near 2^-500.
561                for (lhs, rhs) in [(&lhs, &rhs), (&rhs, &lhs)] {
562                    check_phase_comparison(lhs, rhs, &scalar(2.0_f64.powi(-exponent - 2)), false);
563                    check_phase_comparison(lhs, rhs, &scalar(2.0_f64.powi(-exponent + 2)), true);
564                }
565            }
566        }
567    }
568
569    fn large_wrapped_reference_controls<T: FloatLike>(prototype: &F<T>) {
570        let two = prototype.from_usize(2);
571        let real = two.powi(511);
572        let unit = two.powi(-563);
573        let lhs = Complex::new(real.clone(), -(&unit * prototype.from_usize(16)));
574        let rhs = Complex::new(real.clone(), -(&unit * prototype.from_usize(8)));
575        let minimum = two.powi(-1022) / two.powi(52);
576        assert_eq!(lhs.norm().re, real);
577        assert_eq!(rhs.norm().re, real);
578        assert!(minimum > minimum.zero());
579        // The gap is eight minimum subnormals; dividing by the wrapped
580        // reference near TAU leaves one. An unscaled dot*TAU overflows.
581        for (lhs, rhs) in [(&lhs, &rhs), (&rhs, &lhs)] {
582            check_phase_comparison(lhs, rhs, &minimum, false);
583            check_phase_comparison(lhs, rhs, &(&minimum * prototype.from_usize(4)), true);
584        }
585    }
586
587    #[test]
588    fn complex_phase_normalization_bounds_large_wrapped_references() {
589        large_wrapped_reference_controls(&F(0.0_f64));
590        large_wrapped_reference_controls(&F::<QuadFloat>::default());
591    }
592
593    #[test]
594    fn complex_phase_products_stay_finite_at_the_norm_boundary() {
595        let x = F(f64::from_bits(0x5fef_ffff_ffff_fffc));
596        let y = F(f64::from_bits(0x5e5e_fbde_b14f_4ed9));
597        let next_y = F(y.0.next_down());
598        let lhs = Complex::new(x, y);
599        let rhs = Complex::new(x, next_y);
600        // Separately rounded squared norms equal MAX, while the fused dot
601        // overflows. The compensated determinant and relative gap are finite.
602        assert_eq!(lhs.norm().re, F(f64::MAX.sqrt()));
603        assert_eq!(rhs.norm().re, lhs.norm().re);
604        assert!(x.0.mul_add(x.0, y.0 * next_y.0).is_infinite());
605        for (lhs, rhs) in [(&lhs, &rhs), (&rhs, &lhs)] {
606            check_phase_comparison(lhs, rhs, &F(2.0_f64.powi(-55)), false);
607            check_phase_comparison(lhs, rhs, &F(2.0_f64.powi(-50)), true);
608        }
609        // Rotating one direction moves the overflowing sum to the cross
610        // product. Its circular gap is near PI/2, relative to a phase near PI/2.
611        let rotated = Complex::new(-next_y, x);
612        assert_eq!(rotated.norm().re, lhs.norm().re);
613        check_phase_comparison(&lhs, &rotated, &F(0.5), false);
614        check_phase_comparison(&lhs, &rotated, &F(1.5), true);
615    }
616
617    #[test]
618    fn complex_phase_large_double_double_products_preserve_precision() {
619        let one = F::<QuadFloat>::default().one();
620        let two = one.from_usize(2);
621        let lhs = Complex::new(one.from_usize(3), one.from_usize(4));
622        let rhs = Complex::new(one.from_usize(4), one.from_usize(3));
623        let (_, relative) = F::phase_differences(&lhs, &rhs);
624        // A huge unscaled dot product has a low-precision reciprocal in the
625        // double-double backend. The boolean decision must retain its precision
626        // when both Cartesian directions are scaled by an exact binary power.
627        let margin = two.powi(-95);
628        for exponent in [0, 500, 508] {
629            let scale = two.powi(exponent);
630            let lhs = Complex::new(lhs.re * scale, lhs.im * scale);
631            let rhs = Complex::new(rhs.re * scale, rhs.im * scale);
632            assert_eq!(lhs.norm().re, rhs.norm().re);
633            check_phase_comparison(&lhs, &rhs, &(relative - margin), false);
634            check_phase_comparison(&lhs, &rhs, &(relative + margin), true);
635        }
636    }
637
638    #[test]
639    fn complex_phase_scaling_spans_mpfr_magnitudes() {
640        phase_boundary_controls(
641            &F(SamplingFloat::from(Float::with_val(256, 0))),
642            384,
643            &[-1_000_000, 1_000_000],
644        );
645        phase_boundary_controls(
646            &F(ArbPrec::from(Float::with_val(1000, 0))),
647            1128,
648            &[-1_000_000, 1_000_000],
649        );
650    }
651
652    #[test]
653    fn complex_phase_scaling_retains_distinct_nearby_directions() {
654        let h = 2.0_f64.powi(-52);
655        let a = 1.5 + h;
656        let lhs = Complex::new(F(a), F(1.5));
657        let rhs = Complex::new(F(1.5 + 2.0 * h), F(a));
658        assert_eq!(lhs.norm().re, rhs.norm().re);
659        // These exact binary64 sources have cross=-h^2 and dot=2*a^2.
660        // The relative phase lies strictly between h^2/16 and h^2;
661        // independent max-component division would erase the distinction.
662        check_phase_comparison(&lhs, &rhs, &F(h * h / 16.0), false);
663        check_phase_comparison(&rhs, &lhs, &F(h * h / 16.0), false);
664        check_phase_comparison(&lhs, &rhs, &F(h * h), true);
665        check_phase_comparison(&rhs, &lhs, &F(h * h), true);
666        check_phase_comparison(&lhs, &lhs, &F(h * h / 16.0), true);
667    }
668
669    #[test]
670    fn complex_phase_scaling_preserves_subnormal_angular_gaps() {
671        let d = f64::from_bits(1);
672        for real in [1.0, 1.25, 1.5, 1.75, 2.0, 3.0] {
673            let reference = Complex::new(F(real), F(0.0));
674            for imaginary in [d, -d, 2.0 * d, -2.0 * d, 3.0 * d, -3.0 * d] {
675                let lhs = Complex::new(F(real), F(imaginary));
676                assert_eq!(lhs.norm().re, reference.norm().re);
677                // The independent native arg on the original source retains
678                // these subnormal gaps; direction-product scaling must too.
679                let phase = imaginary.atan2(real).abs();
680                for tolerance in [d, 2.0 * d, 3.0 * d] {
681                    check_phase_comparison(&lhs, &reference, &F(tolerance), phase < tolerance);
682                }
683            }
684        }
685        let lhs = Complex::new(F(1.0), F(-2.0 * d));
686        let rhs = Complex::new(F(1.0), F(0.0));
687        assert!(!lhs.approx_eq(&rhs, &F(d)));
688        assert!(lhs.approx_eq_res(&rhs, &F(d)).is_err());
689    }
690
691    #[test]
692    fn complex_phase_normalization_preserves_subnormal_nonzero_references() {
693        let d = f64::from_bits(1);
694        let lhs = Complex::new(F(2.0), F(3.0 * d));
695        let rhs = Complex::new(F(2.0), F(2.0 * d));
696        assert_eq!(lhs.norm().re, rhs.norm().re);
697        assert_eq!(lhs.im.0.atan2(lhs.re.0), 2.0 * d);
698        assert_eq!(rhs.im.0.atan2(rhs.re.0), d);
699        check_phase_comparison(&lhs, &rhs, &F(0.25), false);
700        check_phase_comparison(&rhs, &lhs, &F(0.25), false);
701        // atan(k*d/2)-atan(m*d/2) has leading value (k-m)*d/2;
702        // its cubic correction is far below one working ulp of the normalized
703        // result. Compute that ratio from integer coefficients, without first
704        // materializing a subnormal angular difference.
705        for k in 2..=6 {
706            for m in 2..=6 {
707                let lhs = Complex::new(F(2.0), F(f64::from(k) * d));
708                let rhs = Complex::new(F(2.0), F(f64::from(m) * d));
709                let reference_units = rhs.im.0.atan2(2.0) / d;
710                let relative = f64::from(k - m).abs() / (2.0 * reference_units);
711                for tolerance in [0.25, 0.5, 0.75] {
712                    check_phase_comparison(&lhs, &rhs, &F(tolerance), relative < tolerance);
713                }
714            }
715        }
716    }
717
718    #[test]
719    fn complex_phase_normalization_preserves_double_double_subnormal_differences() {
720        let scalar = |value: f64| F(QuadFloat::from(DoubleFloat::from(value)));
721        let d = f64::from_bits(1);
722        let n = f64::MIN_POSITIVE;
723        let lhs = Complex::new(scalar(2.0), scalar(n + 6.0 * d));
724        let rhs = Complex::new(scalar(2.0), scalar(n + d));
725        assert_eq!(lhs.norm().re, rhs.norm().re);
726        let one = F::<QuadFloat>::default().one();
727        let tolerance = one.from_usize(9) * one.from_usize(2).powi(-53);
728        // The circular gap is 2.5*d before native angular rounding. Its
729        // RHS-normalized value is near 10*2^-53, above the strict budget;
730        // rounding the angle first would incorrectly compare 8*2^-53.
731        check_phase_comparison(&lhs, &rhs, &tolerance, false);
732        check_phase_comparison(&rhs, &lhs, &tolerance, false);
733    }
734
735    #[test]
736    fn complex_phase_near_perpendicular_double_double_directions_stay_finite() {
737        // Build the native binary64 limbs directly: d=2^-1040 is retained as
738        // a separate double-double limb of 1±d, rather than added in binary64.
739        let d = f64::from_bits(1_u64 << 34);
740        let one = F::<QuadFloat>::default().one();
741        let tolerance = one.from_usize(3) / one.from_usize(4);
742        for sign in [-1.0, 1.0] {
743            for perturbation in [-d, d] {
744                let lhs = Complex::new(one, if sign < 0.0 { -&one } else { one });
745                let rhs = Complex::new(
746                    -&one,
747                    F(QuadFloat::from(DoubleFloat::from_compensated_sum(
748                        sign,
749                        sign * perturbation,
750                    ))),
751                );
752                assert_eq!(lhs.norm().re, rhs.norm().re);
753                // The circular gap is near pi/2. Its RHS-relative size is
754                // near 2/3 above the axis and 2/5 below it, both below 3/4.
755                check_phase_comparison(&lhs, &rhs, &tolerance, true);
756                check_phase_comparison(&rhs, &lhs, &tolerance, sign < 0.0);
757            }
758        }
759    }
760
761    #[test]
762    fn complex_phase_fix_preserves_norm_scaling_and_zero_controls() {
763        let one = Complex::new(F(1.0), F(0.0));
764        let two = Complex::new(F(2.0), F(0.0));
765        assert!(one.approx_eq(&two, &F(0.75)));
766        assert!(!two.approx_eq(&one, &F(0.75)));
767        assert!(
768            two.approx_eq_res(&one, &F(0.75))
769                .unwrap_err()
770                .to_string()
771                .starts_with("Norms are not approximately equal:")
772        );
773        let zero = Complex::new(F(0.0), F(0.0));
774        assert!(zero.approx_eq(&zero, &F(1e-18)));
775        assert!(zero.approx_eq_res(&zero, &F(1e-18)).is_ok());
776        assert!(!zero.approx_eq(&one, &F(1e-18)));
777        assert!(!one.approx_eq(&zero, &F(1e-18)));
778    }
779
780    #[test]
781    fn native_hypot_preserves_finite_range() {
782        use super::{ArbPrec, F};
783
784        for scale in [1e-200, 1.0, 1e200] {
785            for sign in [-1.0, 1.0] {
786                let norm = F(sign * 3.0 * scale).hypot(&F(4.0 * scale)).0;
787                assert!(norm.is_finite());
788                assert!((norm / scale - 5.0).abs() < 1e-14);
789            }
790        }
791        assert_eq!(F(0.0).hypot(&F(-0.0)), F(0.0));
792        assert!(F(f64::NAN).hypot(&F(1.0)).0.is_nan());
793        assert!(F(1.0).hypot(&F(f64::NAN)).0.is_nan());
794        assert!(F(f64::INFINITY).hypot(&F(1.0)).0.is_infinite());
795        assert!(F(f64::MAX).hypot(&F(f64::MAX)).0.is_infinite());
796
797        // Native precision must not pass through binary64 for scaling/order.
798        let one = F::<ArbPrec>::default().one();
799        for exponent in [-2000, 2000] {
800            let scale = one.from_i64(2).powi(exponent);
801            let norm = (&scale * one.from_i64(3)).hypot(&(&scale * one.from_i64(4)));
802            assert!((norm / scale - one.from_i64(5)).abs() < one.from_i64(10).powi(-50));
803        }
804    }
805
806    #[test]
807    fn canonical_arb_materialization_preserves_native_bits_and_checks_range() {
808        use super::{ArbPrec, F, FloatLike, QuadFloat, SamplingEvaluationError};
809        use rug::Float;
810
811        let low = Float::with_val(1000, 1) >> 400;
812        let source = ArbPrec {
813            float: Float::with_val(1000, 1) + &low,
814        };
815        let quad = F::<QuadFloat>::from_arb(&source).unwrap();
816        let (lower, upper) = quad.0.mpfr_enclosure(1000);
817        assert_eq!(lower, source.float);
818        assert_eq!(upper, source.float);
819        assert_eq!(
820            F::<ArbPrec>::from_arb(&source).unwrap().0.float,
821            source.float
822        );
823        assert_eq!(F::<f64>::from_arb(&source).unwrap().0, 1.0);
824
825        let one = F::<ArbPrec>::default().one();
826        let large = one.from_i64(2).powi(2000);
827        for value in [large.clone(), -large.clone(), large.inv(), -large.inv()] {
828            assert!(value.0.float.is_finite() && value != one.zero());
829            for error in [
830                F::<f64>::from_arb(&value.0).unwrap_err(),
831                F::<QuadFloat>::from_arb(&value.0).unwrap_err(),
832            ] {
833                assert!(matches!(
834                    error.downcast_ref::<SamplingEvaluationError>(),
835                    Some(SamplingEvaluationError::Unrepresentable { .. })
836                ));
837            }
838            assert_eq!(F::<ArbPrec>::from_arb(&value.0).unwrap(), value);
839        }
840        assert_eq!(F::<f64>::from_arb(&one.zero().0).unwrap().0, 0.0);
841        let invalid = ArbPrec {
842            float: Float::with_val(1000, f64::NAN),
843        };
844        assert!(matches!(
845            F::<ArbPrec>::from_arb(&invalid)
846                .unwrap_err()
847                .downcast_ref::<SamplingEvaluationError>(),
848            Some(SamplingEvaluationError::Unrepresentable { .. })
849        ));
850    }
851
852    #[test]
853    fn canonical_native_embedding_requires_finite_singleton_enclosures() {
854        use super::{F, QuadFloat, SamplingEvaluationError};
855        use rug::Float;
856        use symbolica::domains::float::DoubleFloat;
857        for sign in [-1.0, 1.0] {
858            let low = sign * 2.0_f64.powi(-400);
859            let native = F(QuadFloat::from(DoubleFloat::from_compensated_sum(
860                sign, low,
861            )));
862            let exact = Float::with_val(1000, sign) + Float::with_val(1000, low);
863            assert_eq!(native.to_arb_exact().unwrap().0.float, exact);
864            // The exact sum spans 1075 bits, although both binary64 limbs are
865            // finite. Rounding it to the container would change the source.
866            let separated = F(QuadFloat::from(DoubleFloat::from_compensated_sum(
867                sign,
868                sign * f64::from_bits(1),
869            )));
870            assert!(matches!(
871                separated
872                    .to_arb_exact()
873                    .unwrap_err()
874                    .downcast_ref::<SamplingEvaluationError>(),
875                Some(SamplingEvaluationError::Unrepresentable {
876                    operation: "canonical source embedding",
877                    ..
878                })
879            ));
880        }
881        for value in [0.0, -0.0, f64::from_bits(1), f64::MAX] {
882            assert_eq!(
883                F(value).to_arb_exact().unwrap().0.float,
884                Float::with_val(1000, value)
885            );
886        }
887        assert!(F(-0.0).to_arb_exact().unwrap().0.float.is_sign_negative());
888        for zero in [0.0, -0.0] {
889            let native = F(QuadFloat::from_f64_exact_binary(zero));
890            assert_eq!(
891                native.to_arb_exact().unwrap().0.float.is_sign_negative(),
892                native.0.as_f64().is_sign_negative()
893            );
894        }
895        for value in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
896            assert!(F(value).to_arb_exact().is_err());
897        }
898    }
899
900    #[test]
901    fn fixed256_source_scalar_embeds_exactly_without_binary64_range_limits() {
902        use super::{ArbPrec, F, FloatLike, SamplingFloat, SamplingPrecision};
903        use crate::settings::runtime::Precision;
904        use rug::Float;
905
906        assert_eq!(
907            SamplingFloat::sampling_precision(),
908            SamplingPrecision::Fixed256
909        );
910        for (physical, sampling) in [
911            (Precision::Double, SamplingPrecision::Double),
912            (Precision::Quad, SamplingPrecision::Quad),
913            (Precision::Arb, SamplingPrecision::Arb),
914        ] {
915            assert_eq!(SamplingPrecision::from(physical), sampling);
916        }
917        let one = F::<SamplingFloat>::default().one();
918        assert_eq!(one.epsilon(), one.from_i64(2).powi(-255));
919        for exponent in [-4096, -255, 0, 255, 4096] {
920            for sign in [-1, 1] {
921                let native = one.from_i64(sign)
922                    * one.from_i64(2).powi(exponent)
923                    * (&one + one.from_i64(2).powi(-254));
924                let promoted = native.to_arb_exact().unwrap();
925                assert_eq!(promoted.0.float, native.0.float);
926                assert_eq!(F::<SamplingFloat>::from_arb(&promoted.0).unwrap(), native);
927                assert_eq!(promoted.0.float.prec(), 1000);
928                assert_eq!(native.0.float.prec(), 256);
929            }
930        }
931        for zero in [0.0, -0.0] {
932            let native = F(SamplingFloat::from_f64_exact_binary(zero));
933            assert_eq!(
934                native.to_arb_exact().unwrap().0.float.is_sign_negative(),
935                zero.is_sign_negative()
936            );
937        }
938        for invalid in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
939            assert!(
940                F(SamplingFloat::from(Float::with_val(256, invalid)))
941                    .to_arb_exact()
942                    .is_err()
943            );
944        }
945        // Physical inputs remain Arb values; constructing proposal externals at
946        // 256 bits does not redefine the original higher-precision kinematics.
947        let physical =
948            F::<ArbPrec>::default().one() + F::<ArbPrec>::default().from_i64(2).powi(-300);
949        assert_eq!(F::<SamplingFloat>::from_arb(&physical.0).unwrap(), one);
950        assert_ne!(physical, one.to_arb_exact().unwrap());
951    }
952
953    #[test]
954    fn fixed_mpfr_rational_coefficients_are_rounded_once() {
955        use super::VarFloat;
956        use rug::{Float, Integer, Rational};
957        use symbolica::domains::rational::Rational as SymbolicaRational;
958
959        fn check<const N: u32>() {
960            for (numerator, denominator) in [(0, 7), (1, 7), (-7, 3), (7, -3), (-7, -3)] {
961                let exact = Rational::from((numerator, denominator));
962                let rational = SymbolicaRational::from(exact.clone());
963                let actual = VarFloat::<N>::from(&rational);
964                assert_eq!(actual.float, Float::with_val(N, exact));
965                assert_eq!(actual.float.prec(), N);
966            }
967            // Exercise Symbolica's Double and Large integer storage, with
968            // either sign. The N-bit boundary also has an analytic rounding
969            // result: (2^N+3)/(2^N+1) rounds to 1+2^(1-N), not 1+2^(2-N).
970            for bits in [80, N] {
971                let power = Integer::from(1) << bits;
972                for sign in [-1, 1] {
973                    let exact = Rational::from(((power.clone() + 3) * sign, power.clone() + 1));
974                    let rational = SymbolicaRational::from(exact.clone());
975                    let actual = VarFloat::<N>::from(&rational);
976                    assert_eq!(actual.float, Float::with_val(N, exact));
977                    if bits == N {
978                        let expected =
979                            (Float::with_val(N, 1) + (Float::with_val(N, 1) >> (N - 1))) * sign;
980                        assert_eq!(actual.float, expected);
981                    }
982                }
983            }
984        }
985        check::<256>();
986        check::<1000>();
987    }
988
989    #[test]
990    fn fixed_mpfr_symbolica_inputs_use_declared_precision_for_later_arithmetic() {
991        use super::{SymbolicaFloat, VarFloat};
992        use rug::Float;
993
994        fn check<const N: u32>() {
995            for input_precision in [53, N + 31] {
996                let input = Float::with_val(input_precision, 1);
997                let native = VarFloat::<N>::from(SymbolicaFloat::from(input.clone()));
998                assert_eq!(native.float.prec(), N);
999                assert_eq!(native.float, input);
1000                // Expanding a represented 53-bit input does not restore lost
1001                // information, but subsequent arithmetic must use all N bits.
1002                let small = VarFloat::<N>::from(Float::with_val(N, 1) >> 200_u32);
1003                let expected = Float::with_val(N, 1) + &small.float;
1004                assert_eq!((native + small).float, expected);
1005            }
1006            let precise = Float::with_val(N + 31, 1) + (Float::with_val(N + 31, 1) >> (N + 10));
1007            let native = VarFloat::<N>::from(SymbolicaFloat::from(precise.clone()));
1008            assert_eq!(native.float, Float::with_val(N, precise));
1009            assert_eq!(native.float.prec(), N);
1010            for value in [0.0, -0.0, f64::INFINITY, f64::NEG_INFINITY, f64::NAN] {
1011                let native = VarFloat::<N>::from(SymbolicaFloat::from(Float::with_val(53, value)));
1012                assert_eq!(native.float.prec(), N);
1013                if value.is_nan() {
1014                    assert!(native.float.is_nan());
1015                } else {
1016                    assert_eq!(native.float, value);
1017                    assert_eq!(native.float.is_sign_negative(), value.is_sign_negative());
1018                }
1019            }
1020        }
1021        check::<256>();
1022        check::<1000>();
1023    }
1024
1025    #[test]
1026    fn canonical_scalar_relative_budget_is_directed_and_signed() {
1027        use super::{ArbPrec, F, FloatLike, QuadFloat, SamplingEvaluationError};
1028        fn check<T: FloatLike>() {
1029            let one = F::<ArbPrec>::default().one();
1030            let source = &one - one.from_i64(2).powi(-54);
1031            let tolerance = 2.0_f64.powi(-54);
1032            let loose = f64::from_bits(tolerance.to_bits() + 1);
1033            for sign in [-1, 1] {
1034                let native = F::<T>::default().from_i64(sign);
1035                let source = &source * one.from_i64(sign);
1036                // |native-source|=2^-54, but tolerance*|source| is strictly
1037                // smaller by 2^-108. Nearest rounding must not erase that gap.
1038                let error = native
1039                    .verify_arb_materialization(&source.0, tolerance)
1040                    .unwrap_err();
1041                assert!(matches!(
1042                    error.downcast_ref::<SamplingEvaluationError>(),
1043                    Some(SamplingEvaluationError::UncertainGeometry { .. })
1044                ));
1045                native.verify_arb_materialization(&source.0, loose).unwrap();
1046            }
1047            let zero = F::<T>::default().zero();
1048            zero.verify_arb_materialization(&one.zero().0, tolerance)
1049                .unwrap();
1050            assert!(
1051                zero.one()
1052                    .verify_arb_materialization(&one.zero().0, tolerance)
1053                    .is_err()
1054            );
1055            for budget in [0.0, -1.0, f64::INFINITY, f64::NAN] {
1056                assert!(
1057                    zero.verify_arb_materialization(&one.zero().0, budget)
1058                        .is_err()
1059                );
1060            }
1061        }
1062        check::<f64>();
1063        check::<QuadFloat>();
1064        check::<ArbPrec>();
1065    }
1066
1067    #[test]
1068    fn native_mpfr_enclosures_preserve_separated_limbs_and_signs() {
1069        use super::{ArbPrec, FloatLike, QuadFloat};
1070        use rug::Float;
1071        use symbolica::domains::float::DoubleFloat;
1072
1073        for sign in [-1.0, 1.0] {
1074            let low = sign * 2.0_f64.powi(-400);
1075            let quad = QuadFloat(DoubleFloat::from_compensated_sum(sign, low));
1076            let exact = Float::with_val(512, sign) + Float::with_val(512, low);
1077            for precision in [24, 106, 512] {
1078                let (lower, upper) = quad.mpfr_enclosure(precision);
1079                assert!(lower <= exact && upper >= exact);
1080                if precision == 512 {
1081                    assert_eq!(lower, exact);
1082                    assert_eq!(upper, exact);
1083                } else {
1084                    assert!(
1085                        lower < upper,
1086                        "a separated limb cannot disappear from a certificate"
1087                    );
1088                }
1089                let arb = ArbPrec {
1090                    float: exact.clone(),
1091                };
1092                let (lower, upper) = arb.mpfr_enclosure(precision);
1093                assert!(lower <= exact && upper >= exact);
1094                let native = sign * 1.23456789012345;
1095                let (lower, upper) = native.mpfr_enclosure(precision);
1096                let exact_native = Float::with_val(53, native);
1097                assert!(lower <= exact_native && upper >= exact_native);
1098            }
1099        }
1100    }
1101
1102    #[test]
1103    fn normalized_h_functions_integrate_to_one() {
1104        use super::{F, h, h_dual, hyperdual_utils::new_constant};
1105        use crate::settings::runtime::{HFunction, HFunctionSettings};
1106        use symbolica::domains::dual::HyperDual;
1107
1108        let template = HyperDual::from_values(vec![vec![0], vec![1]], vec![F(1.0), F(0.0)]);
1109        // With t = sigma e^u, the trapezoidal rule converges exponentially for
1110        // these profiles, which decay doubly exponentially at both ends.
1111        let step = 0.01;
1112        for function in [
1113            HFunction::Exponential,
1114            HFunction::PolyExponential,
1115            HFunction::PolyLeftRightExponential,
1116        ] {
1117            // The exponential profile ignores the power.
1118            for power in [None, Some(1), Some(4), Some(16)] {
1119                let settings = HFunctionSettings {
1120                    function: function.clone(),
1121                    sigma: 1.5,
1122                    power,
1123                    ..Default::default()
1124                };
1125                let integral = (-4000..=4000)
1126                    .map(|n| {
1127                        let t = F(settings.sigma * (n as f64 * step).exp());
1128                        let value = h(&t, None, None, &settings);
1129                        let dual = h_dual(&new_constant(&template, &t), None, None, &settings);
1130                        // Far tails amplify argument rounding but are negligible.
1131                        let scale = value.0.abs().max(1.0);
1132                        assert!((dual.values[0].0 - value.0).abs() <= 1e-14 * scale);
1133                        value.0 * t.0 * step
1134                    })
1135                    .sum::<f64>();
1136                assert!(
1137                    (integral - 1.0).abs() < 1e-12,
1138                    "{settings:?} integrates to {integral}"
1139                );
1140            }
1141        }
1142    }
1143
1144    #[test]
1145    fn debug_tags_macro_supports_tags_and_regular_fields() {
1146        crate::debug_tags!(#integration, #summary;
1147            inspect = false,
1148            answer = 42,
1149            "macro compiles with tag shorthands and regular fields"
1150        );
1151    }
1152}
1153
1154pub trait FloatConvertFrom<U> {
1155    fn convert_from(x: &U) -> Self;
1156}
1157
1158//     fn convert_from(x: &f128::f128) -> f64 {
1159//         (*x).to_f64().unwrap()
1160//     }
1161// }
1162
1163// impl FloatConvertFrom<f128::f128> for f128::f128 {
1164//     fn convert_from(x: &f128::f128) -> f128::f128 {
1165//         *x
1166//     }
1167// }
1168
1169// impl FloatConvertFrom<f64> for f128::f128 {
1170//     fn convert_from(x: &f64) -> f128::f128 {
1171//         f128::f128::from_f64(*x).unwrap()
1172//     }
1173// }
1174
1175#[derive(Debug, Clone, PartialEq, PartialOrd, Encode, Decode)]
1176pub struct VarFloat<const N: u32> {
1177    #[bincode(with_serde)]
1178    float: rug::Float,
1179}
1180
1181impl<const N: u32> Serialize for VarFloat<N> {
1182    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1183    where
1184        S: serde::Serializer,
1185    {
1186        let string = self.float.to_string();
1187        string.serialize(serializer)
1188    }
1189}
1190
1191impl<'de, const N: u32> Deserialize<'de> for VarFloat<N> {
1192    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1193    where
1194        D: Deserializer<'de>,
1195    {
1196        let string: String = serde::Deserialize::deserialize(deserializer)?;
1197        let val: Self = string
1198            .parse()
1199            .unwrap_or_else(|_| panic!("failed to parse arb prec from string: {}", string));
1200
1201        Ok(val)
1202    }
1203}
1204
1205impl<const N: u32> FromStr for VarFloat<N> {
1206    type Err = ParseFloatError;
1207    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1208        let float = rug::Float::parse(s)?;
1209        Ok(Self {
1210            float: rug::Float::with_val(N, float),
1211        })
1212    }
1213}
1214
1215#[derive(
1216    Debug,
1217    Clone,
1218    Copy,
1219    Default,
1220    PartialEq,
1221    PartialOrd,
1222    Eq,
1223    Hash,
1224    Serialize,
1225    Deserialize,
1226    Encode,
1227    Decode,
1228)]
1229#[repr(transparent)]
1230pub struct QuadFloat(DoubleFloat);
1231
1232impl std::fmt::Display for QuadFloat {
1233    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1234        std::fmt::Display::fmt(&self.0, f)
1235    }
1236}
1237
1238impl std::fmt::LowerExp for QuadFloat {
1239    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1240        std::fmt::LowerExp::fmt(&self.0, f)
1241    }
1242}
1243
1244impl From<DoubleFloat> for QuadFloat {
1245    fn from(value: DoubleFloat) -> Self {
1246        Self(value)
1247    }
1248}
1249
1250impl From<QuadFloat> for DoubleFloat {
1251    fn from(value: QuadFloat) -> Self {
1252        value.0
1253    }
1254}
1255
1256impl From<&QuadFloat> for DoubleFloat {
1257    fn from(value: &QuadFloat) -> Self {
1258        value.0
1259    }
1260}
1261
1262impl From<SymbolicaFloat> for QuadFloat {
1263    fn from(value: SymbolicaFloat) -> Self {
1264        Self(value.to_double_float())
1265    }
1266}
1267
1268impl From<Float> for QuadFloat {
1269    fn from(value: Float) -> Self {
1270        Self(SymbolicaFloat::from(value).to_double_float())
1271    }
1272}
1273
1274impl From<&Rational> for QuadFloat {
1275    fn from(value: &Rational) -> Self {
1276        Self(value.into())
1277    }
1278}
1279
1280impl<const N: u32> Rem<&VarFloat<N>> for &VarFloat<N> {
1281    type Output = VarFloat<N>;
1282
1283    fn rem(self, rhs: &VarFloat<N>) -> Self::Output {
1284        (&self.float % &rhs.float).complete(N).into()
1285    }
1286}
1287
1288impl<const N: u32> From<Float> for VarFloat<N> {
1289    fn from(x: Float) -> Self {
1290        VarFloat {
1291            float: rug::Float::with_val(N, x),
1292        }
1293    }
1294}
1295
1296impl<const N: u32> From<&Rational> for VarFloat<N> {
1297    fn from(x: &Rational) -> Self {
1298        // Round the exact rational once; separately rounded numerator and
1299        // denominator can change the result by an ulp.
1300        Self::from(x.to_multi_prec_float(N))
1301    }
1302}
1303
1304macro_rules! impl_quad_binary_op {
1305    ($trait:ident, $fn:ident, $op:tt) => {
1306        impl std::ops::$trait for QuadFloat {
1307            type Output = Self;
1308
1309            fn $fn(self, rhs: Self) -> Self::Output {
1310                Self(self.0 $op rhs.0)
1311            }
1312        }
1313
1314        impl std::ops::$trait<&QuadFloat> for QuadFloat {
1315            type Output = Self;
1316
1317            fn $fn(self, rhs: &Self) -> Self::Output {
1318                Self(self.0 $op rhs.0)
1319            }
1320        }
1321
1322        impl std::ops::$trait<QuadFloat> for &QuadFloat {
1323            type Output = QuadFloat;
1324
1325            fn $fn(self, rhs: QuadFloat) -> Self::Output {
1326                QuadFloat(self.0 $op rhs.0)
1327            }
1328        }
1329
1330        impl std::ops::$trait<&QuadFloat> for &QuadFloat {
1331            type Output = QuadFloat;
1332
1333            fn $fn(self, rhs: &QuadFloat) -> Self::Output {
1334                QuadFloat(self.0 $op rhs.0)
1335            }
1336        }
1337    };
1338}
1339
1340macro_rules! impl_quad_assign_op {
1341    ($trait:ident, $fn:ident, $op:tt) => {
1342        impl std::ops::$trait for QuadFloat {
1343            fn $fn(&mut self, rhs: Self) {
1344                self.0 $op rhs.0;
1345            }
1346        }
1347
1348        impl std::ops::$trait<&QuadFloat> for QuadFloat {
1349            fn $fn(&mut self, rhs: &Self) {
1350                self.0 $op rhs.0;
1351            }
1352        }
1353    };
1354}
1355
1356impl_quad_binary_op!(Add, add, +);
1357impl_quad_binary_op!(Sub, sub, -);
1358impl_quad_binary_op!(Mul, mul, *);
1359impl_quad_binary_op!(Div, div, /);
1360
1361impl_quad_assign_op!(AddAssign, add_assign, +=);
1362impl_quad_assign_op!(SubAssign, sub_assign, -=);
1363impl_quad_assign_op!(MulAssign, mul_assign, *=);
1364impl_quad_assign_op!(DivAssign, div_assign, /=);
1365
1366impl Neg for QuadFloat {
1367    type Output = Self;
1368
1369    fn neg(self) -> Self::Output {
1370        Self(-self.0)
1371    }
1372}
1373
1374impl Neg for &QuadFloat {
1375    type Output = QuadFloat;
1376
1377    fn neg(self) -> Self::Output {
1378        QuadFloat(-self.0)
1379    }
1380}
1381
1382impl Rem<&QuadFloat> for &QuadFloat {
1383    type Output = QuadFloat;
1384
1385    fn rem(self, rhs: &QuadFloat) -> Self::Output {
1386        self.truncating_remainder(rhs)
1387    }
1388}
1389
1390impl<const N: u32> std::ops::Mul for VarFloat<N> {
1391    type Output = Self;
1392
1393    fn mul(self, rhs: Self) -> Self::Output {
1394        (self.float * rhs.float).into()
1395    }
1396}
1397
1398impl<const N: u32> std::ops::Mul<&VarFloat<N>> for VarFloat<N> {
1399    type Output = Self;
1400
1401    fn mul(self, rhs: &Self) -> Self::Output {
1402        (self.float * &rhs.float).into()
1403    }
1404}
1405
1406impl<const N: u32> std::ops::Mul<VarFloat<N>> for &VarFloat<N> {
1407    type Output = VarFloat<N>;
1408
1409    fn mul(self, rhs: VarFloat<N>) -> Self::Output {
1410        (&self.float * &rhs.float).complete(N).into()
1411    }
1412}
1413
1414impl<const N: u32> std::ops::Mul<&VarFloat<N>> for &VarFloat<N> {
1415    type Output = VarFloat<N>;
1416
1417    fn mul(self, rhs: &VarFloat<N>) -> Self::Output {
1418        (&self.float * &rhs.float).complete(N).into()
1419    }
1420}
1421
1422impl<const N: u32> std::ops::MulAssign for VarFloat<N> {
1423    fn mul_assign(&mut self, rhs: Self) {
1424        self.float *= rhs.float;
1425        self.float.set_prec(N);
1426    }
1427}
1428
1429impl<const N: u32> std::ops::MulAssign<&VarFloat<N>> for VarFloat<N> {
1430    fn mul_assign(&mut self, rhs: &Self) {
1431        self.float *= &rhs.float;
1432        self.float.set_prec(N);
1433    }
1434}
1435
1436impl<const N: u32> std::ops::Add for VarFloat<N> {
1437    type Output = Self;
1438
1439    fn add(self, rhs: Self) -> Self::Output {
1440        (self.float + rhs.float).into()
1441    }
1442}
1443
1444impl<const N: u32> std::ops::Add<&VarFloat<N>> for VarFloat<N> {
1445    type Output = Self;
1446
1447    fn add(self, rhs: &Self) -> Self::Output {
1448        (self.float + &rhs.float).into()
1449    }
1450}
1451
1452impl<const N: u32> std::ops::Add<VarFloat<N>> for &VarFloat<N> {
1453    type Output = VarFloat<N>;
1454
1455    fn add(self, rhs: VarFloat<N>) -> Self::Output {
1456        (&self.float + &rhs.float).complete(N).into()
1457    }
1458}
1459
1460impl<const N: u32> std::ops::Add<&VarFloat<N>> for &VarFloat<N> {
1461    type Output = VarFloat<N>;
1462
1463    fn add(self, rhs: &VarFloat<N>) -> Self::Output {
1464        (&self.float + &rhs.float).complete(N).into()
1465    }
1466}
1467
1468impl<const N: u32> std::ops::AddAssign for VarFloat<N> {
1469    fn add_assign(&mut self, rhs: Self) {
1470        self.float += rhs.float;
1471        self.float.set_prec(N);
1472    }
1473}
1474
1475impl<const N: u32> std::ops::AddAssign<&VarFloat<N>> for VarFloat<N> {
1476    fn add_assign(&mut self, rhs: &Self) {
1477        self.float += &rhs.float;
1478        self.float.set_prec(N);
1479    }
1480}
1481
1482impl<const N: u32> std::ops::Sub for VarFloat<N> {
1483    type Output = Self;
1484
1485    fn sub(self, rhs: Self) -> Self::Output {
1486        (self.float - rhs.float).into()
1487    }
1488}
1489
1490impl<const N: u32> std::ops::Sub<&VarFloat<N>> for VarFloat<N> {
1491    type Output = Self;
1492
1493    fn sub(self, rhs: &Self) -> Self::Output {
1494        (self.float - &rhs.float).into()
1495    }
1496}
1497
1498impl<const N: u32> std::ops::Sub<VarFloat<N>> for &VarFloat<N> {
1499    type Output = VarFloat<N>;
1500
1501    fn sub(self, rhs: VarFloat<N>) -> Self::Output {
1502        (&self.float - &rhs.float).complete(N).into()
1503    }
1504}
1505
1506impl<const N: u32> std::ops::Sub<&VarFloat<N>> for &VarFloat<N> {
1507    type Output = VarFloat<N>;
1508
1509    fn sub(self, rhs: &VarFloat<N>) -> Self::Output {
1510        (&self.float - &rhs.float).complete(N).into()
1511    }
1512}
1513
1514impl<const N: u32> std::ops::SubAssign for VarFloat<N> {
1515    fn sub_assign(&mut self, rhs: Self) {
1516        self.float -= rhs.float;
1517        self.float.set_prec(N);
1518    }
1519}
1520
1521impl<const N: u32> std::ops::SubAssign<&VarFloat<N>> for VarFloat<N> {
1522    fn sub_assign(&mut self, rhs: &Self) {
1523        self.float -= &rhs.float;
1524        self.float.set_prec(N);
1525    }
1526}
1527
1528impl<const N: u32> Div for VarFloat<N> {
1529    type Output = Self;
1530
1531    fn div(self, rhs: Self) -> Self::Output {
1532        (self.float / rhs.float).into()
1533    }
1534}
1535
1536impl<const N: u32> Div<&VarFloat<N>> for VarFloat<N> {
1537    type Output = Self;
1538
1539    fn div(self, rhs: &Self) -> Self::Output {
1540        (self.float / &rhs.float).into()
1541    }
1542}
1543
1544impl<const N: u32> Div<VarFloat<N>> for &VarFloat<N> {
1545    type Output = VarFloat<N>;
1546
1547    fn div(self, rhs: VarFloat<N>) -> Self::Output {
1548        (&self.float / &rhs.float).complete(N).into()
1549    }
1550}
1551
1552impl<const N: u32> Div<&VarFloat<N>> for &VarFloat<N> {
1553    type Output = VarFloat<N>;
1554
1555    fn div(self, rhs: &VarFloat<N>) -> Self::Output {
1556        (&self.float / &rhs.float).complete(N).into()
1557    }
1558}
1559
1560impl<const N: u32> std::ops::DivAssign for VarFloat<N> {
1561    fn div_assign(&mut self, rhs: Self) {
1562        self.float /= rhs.float;
1563        self.float.set_prec(N);
1564    }
1565}
1566
1567impl<const N: u32> std::ops::DivAssign<&VarFloat<N>> for VarFloat<N> {
1568    fn div_assign(&mut self, rhs: &Self) {
1569        self.float /= &rhs.float;
1570        self.float.set_prec(N);
1571    }
1572}
1573
1574impl<const N: u32> std::ops::Neg for VarFloat<N> {
1575    type Output = Self;
1576
1577    fn neg(self) -> Self::Output {
1578        (-self.float).into()
1579    }
1580}
1581
1582impl<const N: u32> std::ops::Neg for &VarFloat<N> {
1583    type Output = VarFloat<N>;
1584
1585    fn neg(self) -> Self::Output {
1586        (-&self.float).complete(N).into()
1587    }
1588}
1589
1590impl<const N: u32> std::fmt::Display for VarFloat<N> {
1591    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1592        write!(f, "{}", self.float)
1593    }
1594}
1595
1596impl<const N: u32> std::fmt::LowerExp for VarFloat<N> {
1597    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1598        write!(f, "{:e}", self.float)
1599    }
1600}
1601
1602impl<const N: u32> RefZero for VarFloat<N> {
1603    fn ref_zero(&self) -> Self {
1604        Self::new_zero()
1605    }
1606}
1607
1608impl<const N: u32> R for VarFloat<N> {}
1609
1610impl<const N: u32> RefOne for VarFloat<N> {
1611    fn ref_one(&self) -> Self {
1612        self.one()
1613    }
1614}
1615
1616impl<const N: u32> SymFloatLike for VarFloat<N> {
1617    // The type parameter fixes the working precision.
1618    #[inline]
1619    fn set_precision(&mut self, _precision: u32) {}
1620
1621    #[inline]
1622    fn set_from(&mut self, other: &Self) {
1623        self.float.assign(&other.float);
1624    }
1625
1626    fn mul_add(&self, a: &Self, b: &Self) -> Self {
1627        (&self.float * &a.float + &b.float).complete(N).into()
1628    }
1629
1630    fn is_fully_zero(&self) -> bool {
1631        self.float.is_zero()
1632    }
1633
1634    // fn norm(&self) -> Self {
1635    //     self.float.clone().abs().into()
1636    // }
1637
1638    fn from_i64(&self, a: i64) -> Self {
1639        VarFloat {
1640            float: Float::with_val(N, a),
1641        }
1642    }
1643
1644    fn from_usize(&self, a: usize) -> Self {
1645        VarFloat {
1646            float: Float::with_val(N, a),
1647        }
1648    }
1649
1650    fn get_precision(&self) -> u32 {
1651        N
1652    }
1653
1654    fn zero(&self) -> Self {
1655        Self::new_zero()
1656    }
1657
1658    fn one(&self) -> Self {
1659        self.from_i64(1)
1660    }
1661
1662    fn new_zero() -> Self {
1663        VarFloat {
1664            float: Float::new(N),
1665        }
1666    }
1667
1668    fn inv(&self) -> Self {
1669        self.float.clone().recip().into()
1670    }
1671
1672    fn pow(&self, e: u64) -> Self {
1673        rug::ops::Pow::pow(&self.float, e).complete(N).into()
1674    }
1675
1676    fn sample_unit<R: Rng + ?Sized>(&self, rng: &mut R) -> Self {
1677        let f: f64 = rng.random();
1678        Float::with_val(N, f).into()
1679    }
1680
1681    fn neg(&self) -> Self {
1682        (-self.float.clone()).into()
1683    }
1684
1685    fn get_epsilon(&self) -> f64 {
1686        2.0f64.powi(1 - (N as i32))
1687    }
1688
1689    fn fixed_precision(&self) -> bool {
1690        true
1691    }
1692}
1693
1694impl<const N: u32> SingleFloat for VarFloat<N> {
1695    fn is_finite(&self) -> bool {
1696        self.float.is_finite()
1697    }
1698
1699    fn is_one(&self) -> bool {
1700        self.float == 1.
1701    }
1702
1703    fn is_zero(&self) -> bool {
1704        self.float == 0.
1705    }
1706
1707    fn from_rational(&self, rat: &Rational) -> Self {
1708        rat.into()
1709    }
1710}
1711impl<const N: u32> RealLike for VarFloat<N> {
1712    fn absolute_magnitude(&self) -> Magnitude {
1713        // Preserve the MPFR exponent while rounding the magnitude away from
1714        // zero. This bound never replaces the full-precision source value.
1715        let rounding = if self.float.is_sign_negative() {
1716            Round::Down
1717        } else {
1718            Round::Up
1719        };
1720        let (mantissa, exponent) = self.float.to_f64_exp_round(rounding);
1721        Magnitude::from_f64_exp(mantissa, i64::from(exponent))
1722    }
1723
1724    fn to_f64(&self) -> f64 {
1725        self.float.to_f64()
1726    }
1727
1728    fn round_to_nearest_integer(&self) -> Integer {
1729        symbolica::domains::integer::MultiPrecisionInteger::from_raw(
1730            self.float.clone().round().to_integer().unwrap(),
1731        )
1732        .into()
1733    }
1734
1735    fn to_usize_clamped(&self) -> usize {
1736        self.float
1737            .to_integer()
1738            .unwrap()
1739            .to_usize()
1740            .unwrap_or(usize::MAX)
1741    }
1742}
1743
1744impl<const N: u32> Real for VarFloat<N> {
1745    fn i(&self) -> Option<Self> {
1746        None
1747    }
1748
1749    fn conj(&self) -> Self {
1750        self.clone()
1751    }
1752
1753    #[inline(always)]
1754    fn pi(&self) -> Self {
1755        Float::with_val(N, rug::float::Constant::Pi).into()
1756    }
1757
1758    #[inline(always)]
1759    fn e(&self) -> Self {
1760        self.one().exp()
1761    }
1762
1763    #[inline(always)]
1764    fn euler(&self) -> Self {
1765        Float::with_val(N, rug::float::Constant::Euler).into()
1766    }
1767
1768    #[inline(always)]
1769    fn phi(&self) -> Self {
1770        (self.one() + self.from_i64(5).sqrt()) / Self::from_f64(2.)
1771    }
1772    fn atan2(&self, x: &Self) -> Self {
1773        self.float.clone().atan2(&x.float).into()
1774    }
1775
1776    fn powf(&self, e: &Self) -> Self {
1777        self.float.clone().pow(e.float.clone()).into()
1778    }
1779
1780    fn log(&self) -> Self {
1781        self.float.ln_ref().complete(N).into()
1782    }
1783    fn norm(&self) -> Self {
1784        self.float.clone().abs().into()
1785    }
1786
1787    delegate! {
1788        #[into]
1789        to self.float.clone(){
1790            fn sqrt(&self) -> Self;
1791            fn exp(&self) -> Self;
1792            fn sin(&self) -> Self;
1793            fn cos(&self) -> Self;
1794            fn tan(&self) -> Self;
1795            fn asin(&self) -> Self;
1796            fn acos(&self) -> Self;
1797            fn sinh(&self) -> Self;
1798            fn cosh(&self) -> Self;
1799            fn tanh(&self) -> Self;
1800            fn asinh(&self) -> Self;
1801            fn acosh(&self) -> Self;
1802            fn atanh(&self) -> Self;
1803        }
1804    }
1805}
1806
1807impl<const N: u32> From<VarFloat<N>> for SymbolicaFloat {
1808    fn from(value: VarFloat<N>) -> Self {
1809        SymbolicaFloat::from(value.float)
1810    }
1811}
1812
1813impl<const N: u32> From<&VarFloat<N>> for SymbolicaFloat {
1814    fn from(value: &VarFloat<N>) -> Self {
1815        SymbolicaFloat::from(value.float.clone())
1816    }
1817}
1818
1819impl<const N: u32> From<SymbolicaFloat> for VarFloat<N> {
1820    fn from(value: SymbolicaFloat) -> Self {
1821        // Preserve the represented input at this lane's precision so later
1822        // owned arithmetic cannot silently retain the input's smaller precision.
1823        Self::from(value.into_raw())
1824    }
1825}
1826
1827impl From<QuadFloat> for SymbolicaFloat {
1828    fn from(value: QuadFloat) -> Self {
1829        value.0.into()
1830    }
1831}
1832
1833impl From<&QuadFloat> for SymbolicaFloat {
1834    fn from(value: &QuadFloat) -> Self {
1835        value.0.into()
1836    }
1837}
1838
1839impl RefZero for QuadFloat {
1840    fn ref_zero(&self) -> Self {
1841        Self::new_zero()
1842    }
1843}
1844
1845impl R for QuadFloat {}
1846
1847impl RefOne for QuadFloat {
1848    fn ref_one(&self) -> Self {
1849        self.one()
1850    }
1851}
1852
1853impl SymFloatLike for QuadFloat {
1854    #[inline]
1855    fn set_precision(&mut self, precision: u32) {
1856        self.0.set_precision(precision);
1857    }
1858
1859    // Preserve the backend's scalar range signal through the wrapper.
1860    fn needs_rescaling(&self) -> bool {
1861        self.0.needs_rescaling()
1862    }
1863
1864    #[inline]
1865    fn set_from(&mut self, other: &Self) {
1866        self.0.set_from(&other.0);
1867    }
1868
1869    fn mul_add(&self, a: &Self, b: &Self) -> Self {
1870        Self(self.0.mul_add(&a.0, &b.0))
1871    }
1872
1873    fn is_fully_zero(&self) -> bool {
1874        self.0.is_fully_zero()
1875    }
1876
1877    fn from_i64(&self, a: i64) -> Self {
1878        Self(self.0.from_i64(a))
1879    }
1880
1881    fn from_usize(&self, a: usize) -> Self {
1882        Self(self.0.from_usize(a))
1883    }
1884
1885    fn get_precision(&self) -> u32 {
1886        self.0.get_precision()
1887    }
1888
1889    fn zero(&self) -> Self {
1890        Self(self.0.zero())
1891    }
1892
1893    fn one(&self) -> Self {
1894        Self(self.0.one())
1895    }
1896
1897    fn new_zero() -> Self {
1898        Self(DoubleFloat::default().zero())
1899    }
1900
1901    fn inv(&self) -> Self {
1902        Self(self.0.inv())
1903    }
1904
1905    fn pow(&self, e: u64) -> Self {
1906        // Old direct wrapper around Symbolica's DoubleFloat::pow -> Df64::powi.
1907        // Keep this inactive until the upstream bug is fixed in Symbolica.
1908        // Self(self.0.pow(e))
1909
1910        // Temporary local workaround kept active in GammaLoop for now.
1911        // Equivalent explicit implementation:
1912        // let mut base = *self;
1913        // let mut acc = Self::one();
1914        // let mut exponent = e;
1915        // while exponent > 0 {
1916        //     if exponent & 1 == 1 {
1917        //         acc *= base;
1918        //     }
1919        //     exponent >>= 1;
1920        //     if exponent > 0 {
1921        //         base *= base;
1922        //     }
1923        // }
1924        // acc
1925        self.pow_u64_via_mul(e)
1926    }
1927
1928    fn sample_unit<R: Rng + ?Sized>(&self, rng: &mut R) -> Self {
1929        Self(self.0.sample_unit(rng))
1930    }
1931
1932    fn neg(&self) -> Self {
1933        Self(self.0.neg())
1934    }
1935
1936    fn get_epsilon(&self) -> f64 {
1937        self.0.get_epsilon()
1938    }
1939
1940    fn fixed_precision(&self) -> bool {
1941        self.0.fixed_precision()
1942    }
1943}
1944
1945impl SingleFloat for QuadFloat {
1946    fn is_finite(&self) -> bool {
1947        self.0.is_finite()
1948    }
1949
1950    fn is_one(&self) -> bool {
1951        self.0.is_one()
1952    }
1953
1954    fn is_zero(&self) -> bool {
1955        self.0.is_zero()
1956    }
1957
1958    fn from_rational(&self, rat: &Rational) -> Self {
1959        rat.into()
1960    }
1961}
1962
1963impl RealLike for QuadFloat {
1964    fn absolute_magnitude(&self) -> Magnitude {
1965        self.0.absolute_magnitude()
1966    }
1967
1968    fn to_f64(&self) -> f64 {
1969        self.0.to_f64()
1970    }
1971
1972    fn round_to_nearest_integer(&self) -> Integer {
1973        self.0.round_to_nearest_integer()
1974    }
1975
1976    fn to_usize_clamped(&self) -> usize {
1977        self.0.to_usize_clamped()
1978    }
1979}
1980
1981impl Real for QuadFloat {
1982    fn i(&self) -> Option<Self> {
1983        None
1984    }
1985
1986    fn conj(&self) -> Self {
1987        *self
1988    }
1989
1990    #[inline(always)]
1991    fn pi(&self) -> Self {
1992        Self(self.0.pi())
1993    }
1994
1995    #[inline(always)]
1996    fn e(&self) -> Self {
1997        Self(self.0.e())
1998    }
1999
2000    #[inline(always)]
2001    fn euler(&self) -> Self {
2002        Self(self.0.euler())
2003    }
2004
2005    #[inline(always)]
2006    fn phi(&self) -> Self {
2007        Self(self.0.phi())
2008    }
2009
2010    fn atan2(&self, x: &Self) -> Self {
2011        Self(self.0.atan2(&x.0))
2012    }
2013
2014    fn powf(&self, e: &Self) -> Self {
2015        Self(self.0.powf(&e.0))
2016    }
2017
2018    fn log(&self) -> Self {
2019        Self(self.0.log())
2020    }
2021
2022    fn norm(&self) -> Self {
2023        Self(self.0.norm())
2024    }
2025
2026    fn sqrt(&self) -> Self {
2027        Self(self.0.sqrt())
2028    }
2029
2030    fn exp(&self) -> Self {
2031        Self(self.0.exp())
2032    }
2033
2034    fn sin(&self) -> Self {
2035        Self(self.0.sin())
2036    }
2037
2038    fn cos(&self) -> Self {
2039        Self(self.0.cos())
2040    }
2041
2042    fn tan(&self) -> Self {
2043        Self(self.0.tan())
2044    }
2045
2046    fn asin(&self) -> Self {
2047        Self(self.0.asin())
2048    }
2049
2050    fn acos(&self) -> Self {
2051        Self(self.0.acos())
2052    }
2053
2054    fn sinh(&self) -> Self {
2055        Self(self.0.sinh())
2056    }
2057
2058    fn cosh(&self) -> Self {
2059        Self(self.0.cosh())
2060    }
2061
2062    fn tanh(&self) -> Self {
2063        Self(self.0.tanh())
2064    }
2065
2066    fn asinh(&self) -> Self {
2067        Self(self.0.asinh())
2068    }
2069
2070    fn acosh(&self) -> Self {
2071        Self(self.0.acosh())
2072    }
2073
2074    fn atanh(&self) -> Self {
2075        Self(self.0.atanh())
2076    }
2077}
2078
2079impl FloatLike for f128 {
2080    fn mpfr_enclosure(&self, precision: u32) -> (Float, Float) {
2081        let limbs = self.0.into_inner();
2082        let high = Float::with_val(53, limbs.hi());
2083        let low = Float::with_val(53, limbs.lo());
2084        (
2085            Float::with_val_round(precision, &high + &low, Round::Down).0,
2086            Float::with_val_round(precision, &high + &low, Round::Up).0,
2087        )
2088    }
2089
2090    fn E(&self) -> Self {
2091        Self::E()
2092    }
2093
2094    fn PIHALF(&self) -> Self {
2095        Self::PIHALF()
2096    }
2097
2098    fn SQRT_2(&self) -> Self {
2099        Self::from_f64(2.0).sqrt()
2100    }
2101
2102    fn SQRT_2_HALF(&self) -> Self {
2103        Self::from_f64(2.0).sqrt() / Self::from_f64(2.0)
2104    }
2105
2106    fn rem_euclid(&self, rhs: &Self) -> Self {
2107        let r = self.ref_rem(rhs);
2108        if r < r.zero() { r + rhs } else { r }
2109    }
2110
2111    fn FRAC_1_PI(&self) -> Self {
2112        Self::FRAC_1_PI()
2113    }
2114
2115    fn PI(&self) -> Self {
2116        Self::PI()
2117    }
2118
2119    fn TAU(&self) -> Self {
2120        Self::TAU()
2121    }
2122
2123    fn from_f64_exact_binary(x: f64) -> Self {
2124        Self::from_f64_exact_binary(x)
2125    }
2126
2127    fn from_arb(value: &ArbPrec) -> Self {
2128        Self::from(value.float.clone())
2129    }
2130
2131    fn sampling_precision() -> SamplingPrecision {
2132        SamplingPrecision::Quad
2133    }
2134
2135    fn sampling_bridge_cache(
2136        setup: &LmbMultiChannelingSetup,
2137    ) -> &RuntimeCache<std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>>
2138    {
2139        &setup.sampling_bridge_quad
2140    }
2141
2142    fn sampling_bridge_cache_mut(
2143        setup: &mut LmbMultiChannelingSetup,
2144    ) -> &mut RuntimeCache<std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>>
2145    {
2146        &mut setup.sampling_bridge_quad
2147    }
2148
2149    fn from_f64(x: f64) -> Self {
2150        // There are two reasonable f64 -> higher-precision policies:
2151        // preserve the exact binary64 value or reinterpret the visible decimal
2152        // spelling of the f64. GammaLoop currently chooses the decimal route here
2153        // because these upcasts are overwhelmingly user-authored settings, and
2154        // values like 0.1 are less surprising when they retain their decimal
2155        // semantics instead of exposing the hidden binary64 tail. The exact-binary
2156        // helper is kept alongside this for callers that need a faithful embedding
2157        // of an already-computed f64.
2158        Self::from_f64_decimal(x)
2159    }
2160
2161    fn into_f64(&self) -> f64 {
2162        self.as_f64()
2163    }
2164
2165    fn is_nan(&self) -> bool {
2166        self.is_nan_value()
2167    }
2168
2169    fn is_infinite(&self) -> bool {
2170        self.is_infinite_value()
2171    }
2172
2173    fn floor(&self) -> Self {
2174        self.floor_value()
2175    }
2176
2177    fn try_extract_externals_from_cache(
2178        externals: &Externals,
2179    ) -> Option<&TiVec<ExternalIndex, FourMomentum<F<Self>>>> {
2180        match externals {
2181            Externals::Constant { f_128_cache, .. } => f_128_cache.as_ref(),
2182        }
2183    }
2184
2185    fn epsilon(&self) -> Self {
2186        self.machine_epsilon()
2187    }
2188}
2189
2190// Only the runtime cache hooks differ between the two fixed MPFR lanes.
2191macro_rules! impl_mpfr_float_like {
2192    ($scalar:ty, $precision:ident, $bridge:ident, $externals:ident => $external_cache:expr) => {
2193        impl FloatLike for $scalar {
2194            fn mpfr_enclosure(&self, precision: u32) -> (Float, Float) {
2195                (
2196                    Float::with_val_round(precision, &self.float, Round::Down).0,
2197                    Float::with_val_round(precision, &self.float, Round::Up).0,
2198                )
2199            }
2200
2201            fn E(&self) -> Self {
2202                Self::E()
2203            }
2204
2205            fn PIHALF(&self) -> Self {
2206                Self::PIHALF()
2207            }
2208
2209            fn SQRT_2(&self) -> Self {
2210                self.from_i64(2).sqrt()
2211            }
2212
2213            fn SQRT_2_HALF(&self) -> Self {
2214                self.from_i64(2).sqrt() / self.from_i64(2)
2215            }
2216
2217            fn rem_euclid(&self, rhs: &Self) -> Self {
2218                let r = self.ref_rem(rhs);
2219                if r < r.zero() { r + rhs } else { r }
2220            }
2221
2222            fn FRAC_1_PI(&self) -> Self {
2223                Self::FRAC_1_PI()
2224            }
2225
2226            fn PI(&self) -> Self {
2227                Self::PI()
2228            }
2229
2230            fn TAU(&self) -> Self {
2231                Self::TAU()
2232            }
2233
2234            fn from_f64_exact_binary(x: f64) -> Self {
2235                Self::from_f64_exact_binary(x)
2236            }
2237
2238            fn from_arb(value: &ArbPrec) -> Self {
2239                Self::from(value.float.clone())
2240            }
2241
2242            fn sampling_precision() -> SamplingPrecision {
2243                SamplingPrecision::$precision
2244            }
2245
2246            fn sampling_bridge_cache(
2247                setup: &LmbMultiChannelingSetup,
2248            ) -> &RuntimeCache<
2249                std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>,
2250            > {
2251                &setup.$bridge
2252            }
2253
2254            fn sampling_bridge_cache_mut(
2255                setup: &mut LmbMultiChannelingSetup,
2256            ) -> &mut RuntimeCache<
2257                std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>,
2258            > {
2259                &mut setup.$bridge
2260            }
2261
2262            fn from_f64(x: f64) -> Self {
2263                // There are two reasonable f64 -> higher-precision policies:
2264                // preserve the exact binary64 value or reinterpret the visible decimal
2265                // spelling of the f64. GammaLoop currently chooses the decimal route here
2266                // because these upcasts are overwhelmingly user-authored settings, and
2267                // values like 0.1 are less surprising when they retain their decimal
2268                // semantics instead of exposing the hidden binary64 tail. The exact-binary
2269                // helper is kept alongside this for callers that need a faithful embedding
2270                // of an already-computed f64.
2271                VarFloat::from_f64(x)
2272            }
2273
2274            fn into_f64(&self) -> f64 {
2275                self.to_f64()
2276            }
2277
2278            fn is_nan(&self) -> bool {
2279                self.float.is_nan()
2280            }
2281
2282            fn is_infinite(&self) -> bool {
2283                self.float.is_infinite()
2284            }
2285
2286            fn floor(&self) -> Self {
2287                self.float.clone().floor().into()
2288            }
2289
2290            fn try_extract_externals_from_cache(
2291                $externals: &Externals,
2292            ) -> Option<&TiVec<ExternalIndex, FourMomentum<F<Self>>>> {
2293                $external_cache
2294            }
2295
2296            fn epsilon(&self) -> Self {
2297                self.machine_epsilon()
2298            }
2299        }
2300
2301        impl PrecisionUpgradable for $scalar {
2302            type Higher = ArbPrec;
2303            type Lower = f128;
2304
2305            fn higher(&self) -> Self::Higher {
2306                ArbPrec::from(self.float.clone())
2307            }
2308
2309            fn lower(&self) -> Self::Lower {
2310                f128::from(self.float.clone())
2311            }
2312        }
2313    };
2314}
2315
2316impl_mpfr_float_like!(ArbPrec, Arb, sampling_bridge_arb, externals => match externals {
2317    Externals::Constant { arb_cache, .. } => arb_cache.as_ref(),
2318});
2319impl_mpfr_float_like!(SamplingFloat, Fixed256, sampling_bridge_fixed256, _externals => None);
2320
2321impl<const N: u32> VarFloat<N> {
2322    fn machine_epsilon(&self) -> Self {
2323        self.from_i64(2).pow((N - 1) as u64).inv()
2324    }
2325
2326    fn one() -> Self {
2327        VarFloat {
2328            float: rug::Float::with_val(N, 1.0),
2329        }
2330    }
2331    #[allow(non_snake_case)]
2332    fn E() -> Self {
2333        Self::one().exp()
2334    }
2335
2336    #[allow(non_snake_case)]
2337    fn PIHALF() -> Self {
2338        Self::PI() / Self::from_f64(2.0)
2339    }
2340
2341    #[allow(non_snake_case)]
2342    fn PI() -> Self {
2343        VarFloat {
2344            float: rug::Float::with_val(N, Constant::Pi),
2345        }
2346    }
2347
2348    #[allow(non_snake_case)]
2349    fn TAU() -> Self {
2350        let mut tau = Self::PI() + Self::PI();
2351        tau.float.set_prec(N);
2352        tau
2353    }
2354
2355    #[allow(non_snake_case)]
2356    fn FRAC_1_PI() -> Self {
2357        Self::PI().inv()
2358    }
2359
2360    #[allow(dead_code)]
2361    pub(crate) fn from_f64_exact_binary(x: f64) -> Self {
2362        VarFloat {
2363            float: rug::Float::with_val(N, x),
2364        }
2365    }
2366
2367    pub(crate) fn from_f64_decimal(x: f64) -> Self {
2368        if !x.is_finite() {
2369            return Self::from_f64_exact_binary(x);
2370        }
2371
2372        // Decimal parsing can acquire a process-wide locale lock. Cache repeated
2373        // settings/model values per worker, including the target precision in the
2374        // key: a thread-local static is shared by all const-generic instantiations.
2375        thread_local! {
2376            static CACHE: RefCell<HashMap<(u32, u64), Float>> = RefCell::default();
2377        }
2378        CACHE.with_borrow_mut(|cache| {
2379            let key = (N, x.to_bits());
2380            if let Some(float) = cache.get(&key) {
2381                return Self {
2382                    float: float.clone(),
2383                };
2384            }
2385            let valid = Float::parse(format!("{}", x)).unwrap();
2386            let float = Float::with_val(N, valid);
2387            // Dynamic inputs must not cause unbounded retention. Eviction only
2388            // repeats the identical conversion; it never changes its semantics.
2389            if cache.len() == 1024 {
2390                cache.clear();
2391            }
2392            cache.insert(key, float.clone());
2393            Self { float }
2394        })
2395    }
2396
2397    pub(crate) fn from_f64(x: f64) -> Self {
2398        // There are two reasonable f64 -> higher-precision policies:
2399        // preserve the exact binary64 value or reinterpret the visible decimal
2400        // spelling of the f64. GammaLoop currently chooses the decimal route here
2401        // because these upcasts are overwhelmingly user-authored settings, and
2402        // values like 0.1 are less surprising when they retain their decimal
2403        // semantics instead of exposing the hidden binary64 tail. The exact-binary
2404        // helper is kept alongside this for callers that need a faithful embedding
2405        // of an already-computed f64.
2406        Self::from_f64_decimal(x)
2407    }
2408
2409    pub(crate) fn to_f64(&self) -> f64 {
2410        self.float.to_f64()
2411    }
2412
2413    #[allow(dead_code)]
2414    fn as_f64(&self) -> f64 {
2415        self.float.to_f64()
2416    }
2417
2418    #[allow(dead_code)]
2419    fn is_nan_value(&self) -> bool {
2420        self.float.is_nan()
2421    }
2422
2423    #[allow(dead_code)]
2424    fn is_infinite_value(&self) -> bool {
2425        self.float.is_infinite()
2426    }
2427
2428    #[allow(dead_code)]
2429    fn floor_value(&self) -> Self {
2430        self.float.clone().floor().into()
2431    }
2432}
2433
2434impl QuadFloat {
2435    fn pow_u64_via_mul(&self, mut exponent: u64) -> Self {
2436        let mut base = *self;
2437        let mut acc = Self::one();
2438
2439        while exponent > 0 {
2440            if exponent & 1 == 1 {
2441                acc *= base;
2442            }
2443            exponent >>= 1;
2444            if exponent > 0 {
2445                base *= base;
2446            }
2447        }
2448
2449        acc
2450    }
2451
2452    fn machine_epsilon(&self) -> Self {
2453        self.from_i64(2)
2454            .pow((self.get_precision() - 1) as u64)
2455            .inv()
2456    }
2457
2458    #[allow(dead_code)]
2459    fn one() -> Self {
2460        Self(DoubleFloat::from(1.0))
2461    }
2462
2463    #[allow(non_snake_case)]
2464    fn E() -> Self {
2465        Self(DoubleFloat::default().e())
2466    }
2467
2468    #[allow(non_snake_case)]
2469    fn PIHALF() -> Self {
2470        Self::PI() / Self::from_f64(2.0)
2471    }
2472
2473    #[allow(non_snake_case)]
2474    fn PI() -> Self {
2475        Self(DoubleFloat::default().pi())
2476    }
2477
2478    #[allow(non_snake_case)]
2479    fn TAU() -> Self {
2480        Self::PI() + Self::PI()
2481    }
2482
2483    #[allow(non_snake_case)]
2484    fn FRAC_1_PI() -> Self {
2485        Self::PI().inv()
2486    }
2487
2488    #[allow(dead_code)]
2489    pub(crate) fn from_f64_exact_binary(x: f64) -> Self {
2490        Self(DoubleFloat::from(x))
2491    }
2492
2493    pub(crate) fn from_f64_decimal(x: f64) -> Self {
2494        if !x.is_finite() {
2495            return Self::from_f64_exact_binary(x);
2496        }
2497
2498        // Keep decimal promotion (not exact-binary embedding), but avoid the
2499        // parser's locale lock for repeated settings/model values on each worker.
2500        // Bit keys distinguish signed zero and need no model/settings invalidation.
2501        thread_local! {
2502            static CACHE: RefCell<HashMap<u64, QuadFloat>> = RefCell::default();
2503        }
2504        CACHE.with_borrow_mut(|cache| {
2505            let key = x.to_bits();
2506            if let Some(value) = cache.get(&key) {
2507                return *value;
2508            }
2509            let value = SymbolicaFloat::parse(
2510                &format!("{}", x),
2511                Some(DoubleFloat::default().get_precision()),
2512            )
2513            .unwrap()
2514            .into();
2515            if cache.len() == 1024 {
2516                cache.clear();
2517            }
2518            cache.insert(key, value);
2519            value
2520        })
2521    }
2522
2523    fn from_f64(x: f64) -> Self {
2524        Self::from_f64_decimal(x)
2525    }
2526
2527    fn floor_via_symbolica(&self) -> Self {
2528        SymbolicaFloat::from(self).into_raw().floor().into()
2529    }
2530
2531    fn trunc_toward_zero(&self) -> Self {
2532        if *self < Self::new_zero() {
2533            -(-self).floor_via_symbolica()
2534        } else {
2535            self.floor_via_symbolica()
2536        }
2537    }
2538
2539    fn truncating_remainder(&self, rhs: &Self) -> Self {
2540        if rhs.is_zero() {
2541            return Self::from_f64_exact_binary(f64::NAN);
2542        }
2543
2544        *self - ((*self / *rhs).trunc_toward_zero() * *rhs)
2545    }
2546
2547    fn as_f64(&self) -> f64 {
2548        self.0.to_f64()
2549    }
2550
2551    fn is_nan_value(&self) -> bool {
2552        self.0.to_f64().is_nan()
2553    }
2554
2555    fn is_infinite_value(&self) -> bool {
2556        self.0.to_f64().is_infinite()
2557    }
2558
2559    fn floor_value(&self) -> Self {
2560        self.floor_via_symbolica()
2561    }
2562}
2563
2564impl<const N: u32> Default for VarFloat<N> {
2565    fn default() -> Self {
2566        VarFloat {
2567            float: rug::Float::with_val(N, 0.0),
2568        }
2569    }
2570}
2571
2572impl PrecisionUpgradable for f128 {
2573    type Higher = ArbPrec;
2574    type Lower = f64;
2575
2576    fn higher(&self) -> Self::Higher {
2577        ArbPrec::from(SymbolicaFloat::from(self))
2578    }
2579
2580    fn lower(&self) -> Self::Lower {
2581        self.as_f64()
2582    }
2583}
2584
2585impl<T: Real + PrecisionUpgradable, H: Real, L: Real> PrecisionUpgradable for Complex<T>
2586where
2587    T: PrecisionUpgradable<Higher = H, Lower = L>,
2588{
2589    type Higher = Complex<H>;
2590    type Lower = Complex<L>;
2591
2592    fn higher(&self) -> Self::Higher {
2593        Complex::new(self.re.higher(), self.im.higher())
2594    }
2595
2596    fn lower(&self) -> Self::Lower {
2597        Complex::new(self.re.lower(), self.im.lower())
2598    }
2599}
2600
2601// #[allow(non_camel_case_types)]
2602// pub type f256 = VarFloat<243>;
2603
2604pub trait PrecisionUpgradable {
2605    type Higher;
2606    type Lower;
2607
2608    fn higher(&self) -> Self::Higher;
2609    fn lower(&self) -> Self::Lower;
2610}
2611
2612pub trait FloatLike:
2613    Real
2614    + Send
2615    + Sync
2616    + 'static
2617    +R
2618    +Default
2619    + Clone
2620    + PartialOrd
2621    + RealLike
2622    + for<'a> RefAdd<&'a Self, Output = Self>
2623    // + for<'a> RefMutAdd<&'a Self, Output = Self>
2624    + RefAdd<Self, Output = Self>
2625    // + RefMutAdd<Self, Output = Self>
2626    + for<'a> RefMul<&'a Self, Output = Self>
2627    // + for<'a> RefMutMul<&'a Self, Output = Self>
2628    + RefMul<Self, Output = Self>
2629    // + RefMutMul<Self, Output = Self>
2630    + for<'a> RefSub<&'a Self, Output = Self>
2631    // + for<'a> RefMutSub<&'a Self, Output = Self>
2632    + RefSub<Self, Output = Self>
2633    // + RefMutSub<Self, Output = Self>
2634    + for<'a> RefDiv<&'a Self, Output = Self>
2635    // + for<'a> RefMutDiv<&'a Self, Output = Self> f64 doesn't have RefMutDiv
2636    + RefDiv<Self, Output = Self>
2637    + for<'a> RefRem<&'a Self, Output = Self>
2638    // + RefMutDiv<Self, Output = Self>
2639    + RefNeg<Output = Self>
2640    + RefZero
2641    + RefOne
2642    // + RefMutNeg<Output = Self> f64 doesn't have RefMutNeg
2643    + PrecisionUpgradable
2644    + Serialize
2645    + Display
2646    + GenericEvaluatorFloat
2647    + Into<symbolica::domains::float::Float>
2648{
2649
2650    #[allow(non_snake_case)]
2651    fn PI(&self) -> Self;
2652    #[allow(non_snake_case)]
2653    fn E(&self) -> Self;
2654    #[allow(non_snake_case)]
2655    fn TAU(&self) -> Self;
2656    #[allow(non_snake_case)]
2657    fn SQRT_2(&self) -> Self;
2658    #[allow(non_snake_case)]
2659    fn SQRT_2_HALF(&self) -> Self;
2660    #[allow(non_snake_case)]
2661    fn PIHALF(&self) -> Self;
2662    #[allow(non_snake_case)]
2663    fn FRAC_1_PI(&self) -> Self;
2664
2665    fn from_f64(x: f64) -> Self;
2666
2667    /// Preserve the exact stored binary64 value of an original Monte Carlo
2668    /// coordinate. User-authored settings retain the existing decimal policy.
2669    fn from_f64_exact_binary(x: f64) -> Self;
2670
2671    /// Round directly from the canonical Arb draw, never through another lane.
2672    /// Materialization uses the checked F::from_arb boundary below.
2673    fn from_arb(value: &ArbPrec) -> Self;
2674
2675    /// Enclose the exact represented native value at the requested MPFR
2676    /// precision. Directed rounding includes both separated Quad limbs; this
2677    /// is a certificate boundary, unlike ordinary nearest-rounded conversion.
2678    fn mpfr_enclosure(&self, precision: u32) -> (Float, Float);
2679
2680    /// Native sampling lane, distinct from the allowed physical stability levels.
2681    fn sampling_precision() -> SamplingPrecision;
2682    fn sampling_bridge_cache(setup: &LmbMultiChannelingSetup) -> &RuntimeCache<std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>>;
2683    fn sampling_bridge_cache_mut(setup: &mut LmbMultiChannelingSetup) -> &mut RuntimeCache<std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>>;
2684
2685
2686    #[allow(clippy::wrong_self_convention)]
2687    fn into_f64(&self) -> f64; // for inverse gamma in tropical sampling
2688
2689    fn is_nan(&self) -> bool;
2690
2691    fn is_infinite(&self) -> bool;
2692
2693    fn floor(&self) -> Self;
2694
2695    fn square(&self) -> Self {
2696        self.pow(2)
2697    }
2698
2699    fn powi(&self, n: i32) -> Self {
2700        let absn = n.unsigned_abs() as u64;
2701        if n.is_negative() {
2702            self.pow(absn).inv()
2703        } else {
2704            self.pow(absn)
2705        }
2706    }
2707
2708    fn epsilon(&self) -> Self;
2709
2710    fn less_than_epsilon(&self) -> bool {
2711        self < &self.epsilon()
2712    }
2713
2714    fn positive(&self) -> bool {
2715        self > &self.zero()
2716    }
2717
2718    fn max_value(&self) -> Self {
2719        Self::from_f64(f64::MAX)
2720    }
2721
2722    fn min_value(&self) -> Self {
2723        Self::from_f64(f64::MIN)
2724    }
2725
2726    fn ln(&self) -> Self {
2727       self.log()
2728    }
2729
2730    fn rem_euclid(&self, rhs: &Self) -> Self;
2731
2732    fn try_extract_externals_from_cache(externals: &Externals) -> Option<&TiVec<ExternalIndex, FourMomentum<F<Self>>>>;
2733}
2734
2735#[derive(
2736    Debug,
2737    Clone,
2738    PartialEq,
2739    PartialOrd,
2740    Copy,
2741    Default,
2742    Serialize,
2743    Deserialize,
2744    Encode,
2745    Decode,
2746    Hash,
2747    JsonSchema,
2748)]
2749pub struct F<T: FloatLike>(pub T);
2750
2751impl<T: FloatLike> ToCoefficient for F<T> {
2752    fn to_coefficient(self) -> Coefficient {
2753        let z = self.zero();
2754        Coefficient::Float(symbolica::domains::float::Complex {
2755            re: self.into(),
2756            im: z.into(),
2757        })
2758    }
2759}
2760
2761use symbolica::evaluate::{EvaluationDomain, ExportNumber};
2762
2763#[cfg(test)]
2764mod evaluation_domain_tests;
2765
2766impl ExportNumber for QuadFloat {
2767    fn export(&self) -> String {
2768        self.to_string()
2769    }
2770
2771    fn is_real(&self) -> bool {
2772        true
2773    }
2774
2775    fn to_complex_double(&self) -> symbolica::domains::float::Complex<f64> {
2776        symbolica::domains::float::Complex::new(self.0.to_f64(), 0.0)
2777    }
2778}
2779
2780impl<const N: u32> ExportNumber for VarFloat<N> {
2781    fn export(&self) -> String {
2782        self.to_string()
2783    }
2784
2785    fn is_real(&self) -> bool {
2786        true
2787    }
2788
2789    fn to_complex_double(&self) -> symbolica::domains::float::Complex<f64> {
2790        symbolica::domains::float::Complex::new(self.to_f64(), 0.0)
2791    }
2792}
2793
2794impl FixedPrecision for QuadFloat {
2795    const BINARY_PRECISION: usize = <DoubleFloat as FixedPrecision>::BINARY_PRECISION;
2796}
2797
2798impl<const N: u32> FixedPrecision for VarFloat<N> {
2799    const BINARY_PRECISION: usize = N as usize;
2800}
2801
2802impl EvaluationDomain for QuadFloat {
2803    const FIXED_PRECISION: Option<u32> = <DoubleFloat as EvaluationDomain>::FIXED_PRECISION;
2804
2805    fn resolve_function(
2806        tags: &[AtomView],
2807        info: &EvaluationInfo,
2808    ) -> Option<Box<dyn ExternalFunction<Self>>> {
2809        if let Some(f) = info.get_evaluator::<Self>(tags) {
2810            return Some(f);
2811        }
2812
2813        let f = DoubleFloat::resolve_function(tags, info)?;
2814        Some(Box::new(move |args: &[Self]| {
2815            let args: SmallVec<[DoubleFloat; 4]> = args.iter().map(|x| x.0).collect();
2816            Self(f(&args))
2817        }))
2818    }
2819
2820    fn try_from_complex_float(
2821        f: symbolica::domains::float::Complex<symbolica::domains::float::Float>,
2822    ) -> Result<Self, String> {
2823        if f.is_real() {
2824            Ok(Self(f.re.to_double_float()))
2825        } else {
2826            Err(format!(
2827                "Cannot convert from Complex<Float> to {} because the result is not real",
2828                std::any::type_name::<Self>()
2829            ))
2830        }
2831    }
2832}
2833
2834impl<const N: u32> EvaluationDomain for VarFloat<N> {
2835    const FIXED_PRECISION: Option<u32> = Some(N);
2836
2837    fn resolve_function(
2838        tags: &[AtomView],
2839        info: &EvaluationInfo,
2840    ) -> Option<Box<dyn ExternalFunction<Self>>> {
2841        if let Some(f) = info.get_evaluator::<Self>(tags) {
2842            return Some(f);
2843        }
2844
2845        let f = SymbolicaFloat::resolve_function(tags, info)?;
2846        Some(Box::new(move |args: &[Self]| {
2847            let args: SmallVec<[SymbolicaFloat; 4]> = args.iter().map(Into::into).collect();
2848            Self::from(f(&args))
2849        }))
2850    }
2851
2852    fn try_from_complex_float(
2853        f: symbolica::domains::float::Complex<symbolica::domains::float::Float>,
2854    ) -> Result<Self, String> {
2855        if f.is_real() {
2856            Ok(Self::from(f.re))
2857        } else {
2858            Err(format!(
2859                "Cannot convert from Complex<Float> to {} because the result is not real",
2860                std::any::type_name::<Self>()
2861            ))
2862        }
2863    }
2864}
2865
2866impl<T: FloatLike + ExportNumber> ExportNumber for F<T> {
2867    fn export(&self) -> String {
2868        self.0.to_string()
2869    }
2870
2871    fn is_real(&self) -> bool {
2872        self.0.is_real()
2873    }
2874
2875    fn to_complex_double(&self) -> symbolica::domains::float::Complex<f64> {
2876        self.0.to_complex_double()
2877    }
2878}
2879
2880impl<T: FloatLike + FixedPrecision> FixedPrecision for F<T> {
2881    const BINARY_PRECISION: usize = T::BINARY_PRECISION;
2882}
2883
2884impl<T: FloatLike + EvaluationDomain> EvaluationDomain for F<T> {
2885    const FIXED_PRECISION: Option<u32> = T::FIXED_PRECISION;
2886
2887    fn resolve_function(
2888        tags: &[AtomView],
2889        info: &EvaluationInfo,
2890    ) -> Option<Box<dyn ExternalFunction<Self>>> {
2891        if let Some(f) = info.get_evaluator::<Self>(tags) {
2892            return Some(f);
2893        }
2894
2895        let f = T::resolve_function(tags, info)?;
2896        Some(Box::new(move |args: &[Self]| {
2897            let args: SmallVec<[T; 4]> = args.iter().map(|x| x.0.clone()).collect();
2898            Self(f(&args))
2899        }))
2900    }
2901
2902    fn try_from_complex_float(
2903        f: symbolica::domains::float::Complex<symbolica::domains::float::Float>,
2904    ) -> Result<Self, String> {
2905        if f.is_real() {
2906            T::try_from_complex_float(f).map(F)
2907        } else {
2908            Err(format!(
2909                "Cannot convert from Complex<Float> to {} because the result is not real",
2910                std::any::type_name::<Self>()
2911            ))
2912        }
2913    }
2914}
2915
2916impl<T: TensorLibraryData + FloatLike> TensorLibraryData for F<T> {
2917    fn one() -> Self {
2918        F(<T as TensorLibraryData>::one())
2919    }
2920
2921    fn minus_one() -> Self {
2922        F(<T as TensorLibraryData>::minus_one())
2923    }
2924
2925    fn zero() -> Self {
2926        F(<T as TensorLibraryData>::zero())
2927    }
2928}
2929
2930impl From<F<f64>> for Coefficient {
2931    fn from(value: F<f64>) -> Self {
2932        Coefficient::from(value.0)
2933    }
2934}
2935
2936impl<'a> From<&'a F<f64>> for Coefficient {
2937    fn from(x: &'a F<f64>) -> Self {
2938        x.0.into()
2939    }
2940}
2941
2942impl ToFloat for F<f64> {
2943    fn to_float(&self) -> symbolica::domains::float::Float {
2944        symbolica::domains::float::Float::with_val(53, self.0)
2945    }
2946}
2947
2948impl ToAtom for F<f64> {
2949    fn to_atom(self) -> Atom {
2950        Atom::num(self.0)
2951    }
2952}
2953
2954pub trait ToCoefficient {
2955    fn to_coefficient(self) -> Coefficient;
2956}
2957
2958impl<T: FloatLike> From<F<T>> for symbolica::domains::float::Float {
2959    fn from(value: F<T>) -> Self {
2960        value.0.into()
2961    }
2962}
2963
2964impl<T: FloatLike> ToCoefficient for Complex<F<T>> {
2965    fn to_coefficient(self) -> Coefficient {
2966        Coefficient::Float(symbolica::domains::float::Complex {
2967            re: self.re.0.into(),
2968            im: self.im.0.into(),
2969        })
2970    }
2971}
2972
2973impl TrySmallestUpgrade<F<f64>> for Atom {
2974    type LCM = Atom;
2975
2976    fn try_upgrade(&'_ self) -> Option<std::borrow::Cow<'_, Self::LCM>> {
2977        Some(std::borrow::Cow::Borrowed(self))
2978    }
2979}
2980
2981impl TrySmallestUpgrade<Atom> for F<f64> {
2982    type LCM = Atom;
2983
2984    fn try_upgrade(&'_ self) -> Option<std::borrow::Cow<'_, Self::LCM>> {
2985        <f64 as TrySmallestUpgrade<Atom>>::try_upgrade(&self.0)
2986    }
2987}
2988
2989impl<T: FloatLike> R for F<T> {}
2990
2991impl<T: FloatLike> Rem<&F<T>> for &F<T> {
2992    type Output = F<T>;
2993
2994    fn rem(self, rhs: &F<T>) -> Self::Output {
2995        F(self.0.ref_rem(&rhs.0))
2996    }
2997}
2998
2999impl<T: FloatLike> RefZero<F<T>> for &F<T> {
3000    fn ref_zero(&self) -> F<T> {
3001        F(self.0.ref_zero())
3002    }
3003}
3004
3005impl<T: FloatLike> RealLike for F<T> {
3006    delegate! {
3007        to self.0{
3008            fn absolute_magnitude(&self)->Magnitude;
3009            fn to_usize_clamped(&self)->usize;
3010            fn to_f64(&self)->f64;
3011            fn round_to_nearest_integer(&self)->Integer;
3012        }
3013    }
3014}
3015
3016impl<T: FloatLike> SingleFloat for F<T> {
3017    delegate! {
3018        to self.0{
3019            fn is_zero(&self)->bool;
3020            fn is_one(&self)->bool;
3021            fn is_finite(&self)->bool;
3022        }
3023    }
3024    fn from_rational(&self, rat: &Rational) -> Self {
3025        F(self.0.from_rational(rat))
3026    }
3027}
3028
3029impl<T: FloatLike> PrecisionUpgradable for F<T>
3030where
3031    T::Higher: FloatLike,
3032    T::Lower: FloatLike,
3033{
3034    type Higher = F<T::Higher>;
3035    type Lower = F<T::Lower>;
3036
3037    fn higher(&self) -> Self::Higher {
3038        F(self.0.higher())
3039    }
3040
3041    fn lower(&self) -> Self::Lower {
3042        F(self.0.lower())
3043    }
3044}
3045
3046impl<T: FloatLike> RefZero for F<T> {
3047    fn ref_zero(&self) -> Self {
3048        F(self.0.zero())
3049    }
3050}
3051
3052impl<T: FloatLike> RefOne for F<T> {
3053    fn ref_one(&self) -> Self {
3054        F(self.0.one())
3055    }
3056}
3057
3058impl<T: FloatLike> TrySmallestUpgrade<F<T>> for F<T> {
3059    type LCM = F<T>;
3060    fn try_upgrade(&'_ self) -> Option<std::borrow::Cow<'_, Self::LCM>> {
3061        Some(std::borrow::Cow::Borrowed(self))
3062    }
3063}
3064
3065impl<T: FloatLike> TrySmallestUpgrade<F<T>> for Complex<F<T>> {
3066    type LCM = Complex<F<T>>;
3067    fn try_upgrade(&'_ self) -> Option<std::borrow::Cow<'_, Self::LCM>> {
3068        Some(std::borrow::Cow::Borrowed(self))
3069    }
3070}
3071
3072impl<T: FloatLike> TrySmallestUpgrade<Complex<F<T>>> for F<T> {
3073    type LCM = Complex<F<T>>;
3074    fn try_upgrade(&'_ self) -> Option<std::borrow::Cow<'_, Self::LCM>> {
3075        let z = self.ref_zero();
3076
3077        Some(std::borrow::Cow::Owned(Complex::new(self.clone(), z)))
3078    }
3079}
3080
3081// impl<T:FloatLike> TrySmallestUpgrade<Complex<F<T>>> for F<T> {
3082//     type LCM = Complex<F<T>>;
3083//     fn try_upgrade(&self) -> Option<std::borrow::Cow<Self::LCM>> {
3084//         Some(std::borrow::Cow::Borrowed(self))
3085//     }
3086// }
3087
3088impl<'a, T: FloatLike> From<&'a Rational> for F<T> {
3089    fn from(x: &'a Rational) -> Self {
3090        F(T::new_zero().from_rational(x))
3091    }
3092}
3093
3094impl<T: FloatLike> From<T> for F<T> {
3095    fn from(x: T) -> Self {
3096        F(x)
3097    }
3098}
3099
3100impl<T: FloatLike> std::fmt::Display for F<T> {
3101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3102        write!(f, "{}", self.0)
3103    }
3104}
3105
3106impl<T: FloatLike> std::fmt::LowerExp for F<T> {
3107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3108        let rendered = match f.precision() {
3109            Some(precision) => format!("{:.*e}", precision, self.0),
3110            None => format!("{:e}", self.0),
3111        };
3112
3113        let (is_nonnegative, body) = match rendered.strip_prefix('-') {
3114            Some(body) => (false, body),
3115            None => (true, rendered.as_str()),
3116        };
3117
3118        f.pad_integral(is_nonnegative, "", body)
3119    }
3120}
3121
3122impl<T: FloatLike> SymFloatLike for F<T> {
3123    #[inline]
3124    fn set_precision(&mut self, precision: u32) {
3125        self.0.set_precision(precision);
3126    }
3127
3128    #[inline]
3129    fn set_from(&mut self, other: &Self) {
3130        self.0.set_from(&other.0);
3131    }
3132
3133    fn mul_add(&self, a: &Self, b: &Self) -> Self {
3134        F(self.0.mul_add(&a.0, &b.0))
3135    }
3136
3137    fn is_fully_zero(&self) -> bool {
3138        self.0.is_fully_zero()
3139    }
3140
3141    fn new_zero() -> Self {
3142        F(T::new_zero())
3143    }
3144    fn sample_unit<R: Rng + ?Sized>(&self, rng: &mut R) -> Self {
3145        F(self.0.sample_unit(rng))
3146    }
3147    fn neg(&self) -> Self {
3148        F(self.0.ref_neg())
3149    }
3150
3151    fn zero(&self) -> Self {
3152        F(self.0.zero())
3153    }
3154    fn one(&self) -> Self {
3155        F(self.0.one())
3156    }
3157    // fn norm(&self) -> Self;
3158    fn from_usize(&self, x: usize) -> Self {
3159        F(self.0.from_usize(x))
3160    }
3161    fn from_i64(&self, x: i64) -> Self {
3162        F(self.0.from_i64(x))
3163    }
3164    fn pow(&self, n: u64) -> Self {
3165        F(self.0.pow(n))
3166    }
3167    fn inv(&self) -> Self {
3168        F(self.0.inv())
3169    }
3170    fn get_precision(&self) -> u32 {
3171        self.0.get_precision()
3172    }
3173
3174    fn get_epsilon(&self) -> f64 {
3175        self.0.get_epsilon()
3176    }
3177    fn fixed_precision(&self) -> bool {
3178        self.0.fixed_precision()
3179    }
3180}
3181
3182impl<T: FloatLike + Constructible> Constructible for F<T> {
3183    fn new_from_i64(a: i64) -> Self {
3184        F(T::new_from_i64(a))
3185    }
3186
3187    fn new_from_usize(a: usize) -> Self {
3188        F(T::new_from_usize(a))
3189    }
3190
3191    fn new_one() -> Self {
3192        F(T::new_one())
3193    }
3194
3195    fn new_sample_unit<R: Rng + ?Sized>(rng: &mut R) -> Self {
3196        F(T::new_sample_unit(rng))
3197    }
3198}
3199
3200impl<T: FloatLike> Real for F<T> {
3201    fn atan2(&self, x: &Self) -> Self {
3202        F(self.0.atan2(&x.0))
3203    }
3204
3205    fn conj(&self) -> Self {
3206        F(self.0.conj())
3207    }
3208
3209    fn i(&self) -> Option<Self> {
3210        None
3211    }
3212
3213    fn powf(&self, e: &Self) -> Self {
3214        F(self.0.powf(&e.0))
3215    }
3216
3217    fn norm(&self) -> Self {
3218        F(self.0.norm())
3219    }
3220
3221    fn e(&self) -> Self {
3222        F(self.0.e())
3223    }
3224    fn phi(&self) -> Self {
3225        F(self.0.phi())
3226    }
3227    fn euler(&self) -> Self {
3228        F(self.0.euler())
3229    }
3230    fn pi(&self) -> Self {
3231        F(self.0.pi())
3232    }
3233    fn sqrt(&self) -> Self {
3234        F(self.0.sqrt())
3235    }
3236    fn log(&self) -> Self {
3237        F(self.0.log())
3238    }
3239    fn exp(&self) -> Self {
3240        F(self.0.exp())
3241    }
3242    fn sin(&self) -> Self {
3243        F(self.0.sin())
3244    }
3245    fn cos(&self) -> Self {
3246        F(self.0.cos())
3247    }
3248    fn tan(&self) -> Self {
3249        F(self.0.tan())
3250    }
3251    fn asin(&self) -> Self {
3252        F(self.0.asin())
3253    }
3254    fn acos(&self) -> Self {
3255        F(self.0.acos())
3256    }
3257    fn sinh(&self) -> Self {
3258        F(self.0.sinh())
3259    }
3260    fn cosh(&self) -> Self {
3261        F(self.0.cosh())
3262    }
3263    fn tanh(&self) -> Self {
3264        F(self.0.tanh())
3265    }
3266    fn asinh(&self) -> Self {
3267        F(self.0.asinh())
3268    }
3269    fn acosh(&self) -> Self {
3270        F(self.0.acosh())
3271    }
3272    fn atanh(&self) -> Self {
3273        F(self.0.atanh())
3274    }
3275}
3276
3277use delegate::delegate;
3278
3279impl<T: FloatLike> F<T> {
3280    pub(crate) fn max(self, other: F<T>) -> F<T> {
3281        if self < other { other } else { self }
3282    }
3283
3284    pub fn negate(&mut self) {
3285        self.0 = -self.0.clone();
3286    }
3287
3288    pub(crate) fn from_ff64(x: F<f64>) -> Self {
3289        F(T::from_f64(x.0))
3290    }
3291
3292    pub(crate) fn zero(&self) -> Self {
3293        F(self.0.zero())
3294    }
3295
3296    pub(crate) fn one(&self) -> Self {
3297        F(self.0.one())
3298    }
3299
3300    #[allow(clippy::wrong_self_convention)]
3301    pub(crate) fn from_usize(&self, x: usize) -> Self {
3302        F(self.0.from_usize(x))
3303    }
3304
3305    #[allow(clippy::wrong_self_convention)]
3306    pub(crate) fn from_i64(&self, x: i64) -> Self {
3307        F(self.0.from_i64(x))
3308    }
3309
3310    pub(crate) fn higher(&self) -> F<T::Higher>
3311    where
3312        T::Higher: FloatLike,
3313    {
3314        F(self.0.higher())
3315    }
3316
3317    pub(crate) fn lower(&self) -> F<T::Lower>
3318    where
3319        T::Lower: FloatLike,
3320    {
3321        F(self.0.lower())
3322    }
3323
3324    pub fn from_f64(x: f64) -> Self {
3325        F(T::from_f64(x))
3326    }
3327
3328    /// Embed the exact represented native value in the canonical Arb container.
3329    /// In particular, two separated Quad limbs need not fit in 1000 bits.
3330    pub(crate) fn to_arb_exact(&self) -> eyre::Result<F<ArbPrec>> {
3331        let (lower, upper) = self.0.mpfr_enclosure(1000);
3332        if !lower.is_finite() || !upper.is_finite() || lower != upper {
3333            return Err(SamplingEvaluationError::Unrepresentable {
3334                operation: "canonical source embedding",
3335                detail: format!(
3336                    "{:?} scalar {self} is not exactly representable at 1000 bits",
3337                    T::sampling_precision()
3338                ),
3339            }
3340            .into());
3341        }
3342        // Opposite signed zeros compare equal in the directed enclosure. At
3343        // exact zero only, the binary64 sign extraction is itself lossless and
3344        // preserves the native signed-zero convention; nonzero values never narrow.
3345        let exact = if lower == 0 {
3346            Float::with_val(1000, self.0.into_f64())
3347        } else {
3348            lower
3349        };
3350        Ok(F(ArbPrec::from(exact)))
3351    }
3352
3353    /// Materialize one canonical scalar without accepting lost range as zero.
3354    /// Relative factor accuracy and physical positivity belong to their owners.
3355    pub(crate) fn from_arb(value: &ArbPrec) -> eyre::Result<Self> {
3356        if !value.float.is_finite() {
3357            return Err(SamplingEvaluationError::Unrepresentable {
3358                operation: "canonical draw materialization",
3359                detail: "nonfinite canonical scalar".into(),
3360            }
3361            .into());
3362        }
3363        let native = T::from_arb(value);
3364        if !native.is_finite() || (native == native.zero() && value.float != 0) {
3365            return Err(SamplingEvaluationError::Unrepresentable {
3366                operation: "canonical draw materialization",
3367                detail: format!(
3368                    "canonical scalar {value} is outside {:?} range",
3369                    T::sampling_precision()
3370                ),
3371            }
3372            .into());
3373        }
3374        Ok(F(native))
3375    }
3376
3377    /// Bound materialization error against the original represented scalar.
3378    /// Sign/positivity requirements of a weight or root remain with its owner.
3379    pub(crate) fn verify_arb_materialization(
3380        &self,
3381        source: &ArbPrec,
3382        tolerance: f64,
3383    ) -> eyre::Result<()> {
3384        const PRECISION: u32 = 2048;
3385        if !tolerance.is_finite() || tolerance <= 0.0 {
3386            return Err(eyre::eyre!(
3387                "materialization requires a finite positive relative budget"
3388            ));
3389        }
3390        if !self.0.is_finite() || !source.float.is_finite() {
3391            return Err(SamplingEvaluationError::Unrepresentable {
3392                operation: "canonical draw materialization",
3393                detail: "nonfinite source or native scalar in relative check".into(),
3394            }
3395            .into());
3396        }
3397        let (source_lo, source_hi) = source.mpfr_enclosure(PRECISION);
3398        let (native_lo, native_hi) = self.0.mpfr_enclosure(PRECISION);
3399        let error = Float::with_val_round(PRECISION, &native_hi - &source_lo, Round::Up)
3400            .0
3401            .max(&Float::with_val_round(PRECISION, &source_hi - &native_lo, Round::Up).0);
3402        let magnitude = if source_lo >= 0 {
3403            source_lo
3404        } else if source_hi <= 0 {
3405            -source_hi
3406        } else {
3407            Float::with_val(PRECISION, 0)
3408        };
3409        // Borrowed operands keep arithmetic unevaluated until directed rounding.
3410        let allowed = Float::with_val_round(PRECISION, &magnitude * tolerance, Round::Down).0;
3411        if !error.is_finite() || !allowed.is_finite() || error > allowed {
3412            return Err(SamplingEvaluationError::UncertainGeometry {
3413                detail: format!("canonical scalar {source} materialized as {self} exceeds relative budget {tolerance} in {:?}", T::sampling_precision()),
3414            }.into());
3415        }
3416        Ok(())
3417    }
3418
3419    #[allow(clippy::wrong_self_convention)]
3420    pub(crate) fn into_ff64(&self) -> F<f64> {
3421        F(self.0.into_f64())
3422    }
3423
3424    pub(crate) fn abs(&self) -> Self {
3425        F(self.0.norm())
3426    }
3427
3428    /// Euclidean magnitude without squaring unscaled native components.
3429    pub(crate) fn hypot(&self, other: &Self) -> Self {
3430        if !self.0.is_finite() || !other.0.is_finite() {
3431            return self.abs() + other.abs();
3432        }
3433        let scale = self.abs().max(other.abs());
3434        if scale == scale.zero() {
3435            return scale;
3436        }
3437        ((self / &scale).square() + (other / &scale).square()).sqrt() * scale
3438    }
3439
3440    pub(crate) fn sqrt(&self) -> Self {
3441        F(self.0.sqrt())
3442    }
3443
3444    pub(crate) fn powf(&self, e: &Self) -> Self {
3445        F(self.0.powf(&e.0))
3446    }
3447
3448    pub(crate) fn log10(&self) -> Self {
3449        let ten = self.from_i64(10);
3450        self.ln() / ten.ln()
3451    }
3452
3453    pub(crate) fn rem_euclid(&self, rhs: &Self) -> Self {
3454        F(self.0.rem_euclid(&rhs.0))
3455    }
3456
3457    #[allow(non_snake_case)]
3458    pub(crate) fn PI(&self) -> Self {
3459        F(self.0.PI())
3460    }
3461    #[allow(non_snake_case)]
3462    pub fn E(&self) -> Self {
3463        F(self.0.E())
3464    }
3465    #[allow(non_snake_case)]
3466    pub fn TAU(&self) -> Self {
3467        F(self.0.TAU())
3468    }
3469    #[allow(non_snake_case)]
3470    pub fn PIHALF(&self) -> Self {
3471        F(self.0.PIHALF())
3472    }
3473    #[allow(non_snake_case)]
3474    pub fn SQRT_2(&self) -> Self {
3475        F(self.0.SQRT_2())
3476    }
3477    #[allow(non_snake_case)]
3478    pub fn SQRT_2_HALF(&self) -> Self {
3479        F(self.0.SQRT_2_HALF())
3480    }
3481    #[allow(non_snake_case)]
3482    pub(crate) fn FRAC_1_PI(&self) -> Self {
3483        F(self.0.FRAC_1_PI())
3484    }
3485    #[allow(clippy::wrong_self_convention)]
3486    pub(crate) fn into_f64(&self) -> f64 {
3487        self.0.into_f64()
3488    }
3489    pub(crate) fn square(&self) -> Self {
3490        F(self.0.square())
3491    }
3492    pub(crate) fn powi(&self, n: i32) -> Self {
3493        F(self.0.powi(n))
3494    }
3495    pub(crate) fn epsilon(&self) -> Self {
3496        F(self.0.epsilon())
3497    }
3498    pub(crate) fn less_than_epsilon(&self) -> bool {
3499        self.0.less_than_epsilon()
3500    }
3501    pub(crate) fn positive(&self) -> bool {
3502        self.0.positive()
3503    }
3504    pub(crate) fn max_value(&self) -> Self {
3505        F(self.0.max_value())
3506    }
3507    pub(crate) fn min_value(&self) -> Self {
3508        F(self.0.min_value())
3509    }
3510    pub(crate) fn ln(&self) -> Self {
3511        F(self.0.ln())
3512    }
3513    pub(crate) fn inv(&self) -> Self {
3514        F(self.0.inv())
3515    }
3516    pub(crate) fn is_nan(&self) -> bool {
3517        self.0.is_nan()
3518    }
3519    pub(crate) fn is_infinite(&self) -> bool {
3520        self.0.is_infinite()
3521    }
3522    pub fn floor(&self) -> Self {
3523        F(self.0.floor())
3524    }
3525}
3526
3527// impl CompiledEvaluatorFloat for F<f64> {
3528//     fn evaluate(
3529//         eval: &mut symbolica::evaluate::CompiledEvaluator,
3530//         args: &[Self],
3531//         out: &mut [Self],
3532//     ) {
3533//         // cast to f64
3534//         let args_f64: Vec<f64> = args.iter().map(|x| x.0).collect_vec();
3535//         let mut out_f64 = out.iter().map(|x| x.0).collect_vec();
3536
3537//         eval.evaluate_double(&args_f64, &mut out_f64);
3538
3539//         // write the result to out
3540//         out.iter_mut()
3541//             .zip(out_f64)
3542//             .for_each(|(out_ff64, out_f64)| *out_ff64 = F(out_f64));
3543//     }
3544// }
3545
3546impl<T: FloatLike> Add<F<T>> for F<T> {
3547    type Output = F<T>;
3548    fn add(self, rhs: F<T>) -> Self::Output {
3549        F(self.0 + rhs.0)
3550    }
3551}
3552
3553impl<T: FloatLike> Add<&F<T>> for F<T> {
3554    type Output = F<T>;
3555    fn add(self, rhs: &F<T>) -> Self::Output {
3556        F(self.0 + &rhs.0)
3557    }
3558}
3559
3560impl<T: FloatLike> Add<&F<T>> for &F<T> {
3561    type Output = F<T>;
3562    fn add(self, rhs: &F<T>) -> Self::Output {
3563        F(self.0.ref_add(&rhs.0))
3564    }
3565}
3566
3567impl<T: FloatLike> Add<F<T>> for &F<T> {
3568    type Output = F<T>;
3569    fn add(self, rhs: F<T>) -> Self::Output {
3570        F(self.0.ref_add(rhs.0))
3571    }
3572}
3573
3574impl<T: FloatLike> AddAssign<&F<T>> for F<T> {
3575    fn add_assign(&mut self, rhs: &F<T>) {
3576        self.0 += &rhs.0;
3577    }
3578}
3579
3580impl<T: FloatLike> AddAssign<F<T>> for F<T> {
3581    fn add_assign(&mut self, rhs: F<T>) {
3582        self.0 += rhs.0;
3583    }
3584}
3585
3586impl<T: FloatLike> Sub<F<T>> for F<T> {
3587    type Output = F<T>;
3588    fn sub(self, rhs: F<T>) -> Self::Output {
3589        F(self.0 - rhs.0)
3590    }
3591}
3592
3593impl<T: FloatLike> Sub<&F<T>> for F<T> {
3594    type Output = F<T>;
3595    fn sub(self, rhs: &F<T>) -> Self::Output {
3596        F(self.0 - &rhs.0)
3597    }
3598}
3599
3600impl<T: FloatLike> Sub<&F<T>> for &F<T> {
3601    type Output = F<T>;
3602    fn sub(self, rhs: &F<T>) -> Self::Output {
3603        F(self.0.ref_sub(&rhs.0))
3604    }
3605}
3606
3607impl<T: FloatLike> Sub<F<T>> for &F<T> {
3608    type Output = F<T>;
3609    fn sub(self, rhs: F<T>) -> Self::Output {
3610        F(self.0.ref_sub(rhs.0))
3611    }
3612}
3613
3614impl<T: FloatLike> SubAssign<&F<T>> for F<T> {
3615    fn sub_assign(&mut self, rhs: &F<T>) {
3616        self.0 -= &rhs.0;
3617    }
3618}
3619
3620impl<T: FloatLike> SubAssign<F<T>> for F<T> {
3621    fn sub_assign(&mut self, rhs: F<T>) {
3622        self.0 -= rhs.0;
3623    }
3624}
3625
3626impl<T: FloatLike> Mul<F<T>> for F<T> {
3627    type Output = F<T>;
3628    fn mul(self, rhs: F<T>) -> Self::Output {
3629        F(self.0 * rhs.0)
3630    }
3631}
3632
3633impl<T: FloatLike> Mul<&F<T>> for F<T> {
3634    type Output = F<T>;
3635    fn mul(self, rhs: &F<T>) -> Self::Output {
3636        F(self.0 * &rhs.0)
3637    }
3638}
3639
3640impl<T: FloatLike> Mul<&F<T>> for &F<T> {
3641    type Output = F<T>;
3642    fn mul(self, rhs: &F<T>) -> Self::Output {
3643        F(self.0.ref_mul(&rhs.0))
3644    }
3645}
3646
3647impl<T: FloatLike> Mul<F<T>> for &F<T> {
3648    type Output = F<T>;
3649    fn mul(self, rhs: F<T>) -> Self::Output {
3650        F(self.0.ref_mul(rhs.0))
3651    }
3652}
3653
3654impl<T: FloatLike> MulAssign<&F<T>> for F<T> {
3655    fn mul_assign(&mut self, rhs: &F<T>) {
3656        self.0 *= &rhs.0;
3657    }
3658}
3659
3660impl<T: FloatLike> MulAssign<F<T>> for F<T> {
3661    fn mul_assign(&mut self, rhs: F<T>) {
3662        self.0 *= rhs.0;
3663    }
3664}
3665
3666impl<T: FloatLike> Div<F<T>> for F<T> {
3667    type Output = F<T>;
3668    fn div(self, rhs: F<T>) -> Self::Output {
3669        F(self.0 / rhs.0)
3670    }
3671}
3672
3673impl<T: FloatLike> Div<&F<T>> for F<T> {
3674    type Output = F<T>;
3675    fn div(self, rhs: &F<T>) -> Self::Output {
3676        F(self.0 / &rhs.0)
3677    }
3678}
3679
3680impl<T: FloatLike> Div<&F<T>> for &F<T> {
3681    type Output = F<T>;
3682    fn div(self, rhs: &F<T>) -> Self::Output {
3683        F(self.0.ref_div(&rhs.0))
3684    }
3685}
3686
3687impl<T: FloatLike> Div<F<T>> for &F<T> {
3688    type Output = F<T>;
3689    fn div(self, rhs: F<T>) -> Self::Output {
3690        F(self.0.ref_div(rhs.0))
3691    }
3692}
3693
3694impl<T: FloatLike> DivAssign<&F<T>> for F<T> {
3695    fn div_assign(&mut self, rhs: &F<T>) {
3696        self.0 /= &rhs.0;
3697    }
3698}
3699
3700impl<T: FloatLike> DivAssign<F<T>> for F<T> {
3701    fn div_assign(&mut self, rhs: F<T>) {
3702        self.0 /= rhs.0;
3703    }
3704}
3705
3706impl<T: FloatLike> Neg for F<T> {
3707    type Output = F<T>;
3708    fn neg(self) -> Self::Output {
3709        F(-self.0)
3710    }
3711}
3712
3713impl<T: FloatLike> Neg for &F<T> {
3714    type Output = F<T>;
3715    fn neg(self) -> Self::Output {
3716        F(self.0.ref_neg())
3717    }
3718}
3719
3720pub trait RefDefault {
3721    fn default(&self) -> Self;
3722}
3723
3724impl<T: FloatLike> RefDefault for T {
3725    fn default(&self) -> Self {
3726        self.zero()
3727    }
3728}
3729
3730impl<T: FloatLike> RefDefault for F<T> {
3731    fn default(&self) -> Self {
3732        F(self.0.default())
3733    }
3734}
3735impl PrecisionUpgradable for f64 {
3736    type Higher = f128;
3737    type Lower = f64;
3738
3739    fn higher(&self) -> Self::Higher {
3740        f128::from_f64(*self)
3741    }
3742
3743    fn lower(&self) -> Self::Lower {
3744        *self
3745    }
3746}
3747
3748impl FloatLike for f64 {
3749    fn mpfr_enclosure(&self, precision: u32) -> (Float, Float) {
3750        (
3751            Float::with_val_round(precision, *self, Round::Down).0,
3752            Float::with_val_round(precision, *self, Round::Up).0,
3753        )
3754    }
3755
3756    fn PI(&self) -> Self {
3757        std::f64::consts::PI
3758    }
3759
3760    fn SQRT_2(&self) -> Self {
3761        std::f64::consts::SQRT_2
3762    }
3763
3764    fn SQRT_2_HALF(&self) -> Self {
3765        std::f64::consts::SQRT_2 / 2.0
3766    }
3767
3768    fn PIHALF(&self) -> Self {
3769        std::f64::consts::PI / 2.0
3770    }
3771
3772    fn E(&self) -> Self {
3773        std::f64::consts::E
3774    }
3775
3776    fn TAU(&self) -> Self {
3777        std::f64::consts::TAU
3778    }
3779
3780    fn FRAC_1_PI(&self) -> Self {
3781        std::f64::consts::FRAC_1_PI
3782    }
3783
3784    fn from_f64_exact_binary(x: f64) -> Self {
3785        x
3786    }
3787
3788    fn from_arb(value: &ArbPrec) -> Self {
3789        value.float.to_f64()
3790    }
3791
3792    fn sampling_precision() -> SamplingPrecision {
3793        SamplingPrecision::Double
3794    }
3795
3796    fn sampling_bridge_cache(
3797        setup: &LmbMultiChannelingSetup,
3798    ) -> &RuntimeCache<std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>>
3799    {
3800        &setup.sampling_bridge
3801    }
3802
3803    fn sampling_bridge_cache_mut(
3804        setup: &mut LmbMultiChannelingSetup,
3805    ) -> &mut RuntimeCache<std::result::Result<SamplingChannelBridge<Self>, SamplingEvaluationError>>
3806    {
3807        &mut setup.sampling_bridge
3808    }
3809
3810    fn from_f64(x: f64) -> Self {
3811        x
3812    }
3813
3814    fn into_f64(&self) -> f64 {
3815        *self
3816    }
3817
3818    fn is_nan(&self) -> bool {
3819        f64::is_nan(*self)
3820    }
3821
3822    fn is_infinite(&self) -> bool {
3823        f64::is_infinite(*self)
3824    }
3825
3826    fn floor(&self) -> Self {
3827        f64::floor(*self)
3828    }
3829
3830    fn rem_euclid(&self, rhs: &Self) -> Self {
3831        f64::rem_euclid(*self, *rhs)
3832    }
3833
3834    fn try_extract_externals_from_cache(
3835        externals: &Externals,
3836    ) -> Option<&TiVec<ExternalIndex, FourMomentum<F<Self>>>> {
3837        match externals {
3838            Externals::Constant { f_64_cache, .. } => f_64_cache.as_ref(),
3839        }
3840    }
3841
3842    fn epsilon(&self) -> Self {
3843        f64::EPSILON
3844    }
3845}
3846impl From<F<f64>> for f64 {
3847    fn from(value: F<f64>) -> Self {
3848        value.0
3849    }
3850}
3851
3852impl From<F<f64>> for Rational {
3853    fn from(value: F<f64>) -> Self {
3854        value.0.try_into().unwrap()
3855    }
3856}
3857
3858#[allow(non_camel_case_types)]
3859// Keep this one-line fallback close to the active alias: `VarFloat<113>` is a
3860// slower but safe binary128-like replacement when debugging `DoubleFloat`
3861// issues. The effective epsilon follows the scalar, but the explicit native
3862// evaluator/parameter implementations must also be reviewed when flipping it.
3863// pub type f128 = VarFloat<113>;
3864pub type f128 = QuadFloat;
3865pub type ArbPrec = VarFloat<1000>;
3866/// Fixed source arithmetic; completed values embed exactly in the Arb container.
3867pub type SamplingFloat = VarFloat<256>;
3868
3869/// Numerical sampling lanes include a source-only precision which never becomes
3870/// a physical stability level or a persisted runtime setting.
3871#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
3872pub enum SamplingPrecision {
3873    Double,
3874    Quad,
3875    Fixed256,
3876    Arb,
3877}
3878
3879impl From<crate::settings::runtime::Precision> for SamplingPrecision {
3880    fn from(precision: crate::settings::runtime::Precision) -> Self {
3881        use crate::settings::runtime::Precision;
3882        match precision {
3883            Precision::Double => Self::Double,
3884            Precision::Quad => Self::Quad,
3885            Precision::Arb => Self::Arb,
3886        }
3887    }
3888}
3889
3890impl Display for SamplingPrecision {
3891    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3892        f.write_str(match self {
3893            Self::Double => "f64",
3894            Self::Quad => "f128",
3895            Self::Fixed256 => "fixed256",
3896            Self::Arb => "arb1000",
3897        })
3898    }
3899}
3900
3901/// An iterator which iterates two other iterators simultaneously
3902#[derive(Clone, Debug)]
3903#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
3904pub struct ZipEq<I, J> {
3905    a: I,
3906    b: J,
3907}
3908
3909/// An iterator which iterates two other iterators simultaneously and checks
3910/// if the sizes are equal in debug mode.
3911#[allow(unused)]
3912pub(crate) fn zip_eq<I, J>(i: I, j: J) -> ZipEq<I::IntoIter, J::IntoIter>
3913where
3914    I: IntoIterator,
3915    J: IntoIterator,
3916{
3917    ZipEq {
3918        a: i.into_iter(),
3919        b: j.into_iter(),
3920    }
3921}
3922
3923impl<I, J> Iterator for ZipEq<I, J>
3924where
3925    I: Iterator,
3926    J: Iterator,
3927{
3928    type Item = (I::Item, J::Item);
3929
3930    fn next(&mut self) -> Option<Self::Item> {
3931        match (self.a.next(), self.b.next()) {
3932            (None, None) => None,
3933            (Some(a), Some(b)) => Some((a, b)),
3934            (None, Some(_)) => {
3935                #[cfg(debug_assertions)]
3936                panic!("Unequal length of iterators; first iterator finished first");
3937                #[cfg(not(debug_assertions))]
3938                None
3939            }
3940            (Some(_), None) => {
3941                #[cfg(debug_assertions)]
3942                panic!("Unequal length of iterators; second iterator finished first");
3943                #[cfg(not(debug_assertions))]
3944                None
3945            }
3946        }
3947    }
3948
3949    fn size_hint(&self) -> (usize, Option<usize>) {
3950        let sa = self.a.size_hint();
3951        let sb = self.b.size_hint();
3952        (sa.0.min(sb.0), sa.1.zip(sb.1).map(|(ua, ub)| ua.min(ub)))
3953    }
3954}
3955
3956impl<I, J> ExactSizeIterator for ZipEq<I, J>
3957where
3958    I: ExactSizeIterator,
3959    J: ExactSizeIterator,
3960{
3961}
3962
3963/// Format a mean ± sdev as mean(sdev) with the correct number of digits.
3964/// Based on the Python package gvar.
3965pub fn format_uncertainty(mean: F<f64>, sdev: F<f64>) -> String {
3966    let mean = mean.0;
3967    let sdev = sdev.0;
3968
3969    fn ndec(x: f64, offset: usize) -> i32 {
3970        let mut ans = (offset as f64 - x.log10()) as i32;
3971        if ans > 0 && x * 10.0.powi(ans) >= [0.5, 9.5, 99.5][offset] {
3972            ans -= 1;
3973        }
3974        if ans < 0 { 0 } else { ans }
3975    }
3976    let v = mean;
3977    let dv = sdev.abs();
3978
3979    // special cases
3980    if v.is_nan() || dv.is_nan() {
3981        format!("{:e} ± {:e}", v, dv)
3982    } else if dv.is_infinite() {
3983        format!("{:e} ± inf", v)
3984    } else if v.is_zero() && !(1e-4..1e5).contains(&dv) {
3985        if dv.is_zero() {
3986            "0(0)".to_owned()
3987        } else {
3988            let e = format!("{:.1e}", dv);
3989            let mut ans = e.split('e');
3990            let e1 = ans.next().unwrap();
3991            let e2 = ans.next().unwrap();
3992            "0.0(".to_owned() + e1 + ")e" + e2
3993        }
3994    } else if v.is_zero() {
3995        if dv >= 9.95 {
3996            format!("0({:.0})", dv)
3997        } else if dv >= 0.995 {
3998            format!("0.0({:.1})", dv)
3999        } else {
4000            let ndecimal = ndec(dv, 2);
4001            format!(
4002                "{:.*}({:.0})",
4003                ndecimal as usize,
4004                v,
4005                dv * (10.).powi(ndecimal)
4006            )
4007        }
4008    } else if dv.is_zero() {
4009        let e = format!("{:e}", v);
4010        let mut ans = e.split('e');
4011        let e1 = ans.next().unwrap();
4012        let e2 = ans.next().unwrap();
4013        if e2 != "0" {
4014            e1.to_owned() + "(0)e" + e2
4015        } else {
4016            e1.to_owned() + "(0)"
4017        }
4018    } else if dv > 1e4 * v.abs() {
4019        format!("{:.1e} ± {:.2e}", v, dv)
4020    } else if v.abs() >= 1e6 || v.abs() < 1e-5 {
4021        // exponential notation for large |self.mean|
4022        let exponent = v.abs().log10().floor();
4023        let fac = (10.0).powf(&exponent);
4024        let mantissa = format_uncertainty(F(v / fac), F(dv / fac));
4025        let e = format!("{:.0e}", fac);
4026        let mut ee = e.split('e');
4027        mantissa + "e" + ee.nth(1).unwrap()
4028    }
4029    // normal cases
4030    else if dv >= 9.95 {
4031        if v.abs() >= 9.5 {
4032            format!("{:.0}({:.0})", v, dv)
4033        } else {
4034            let ndecimal = ndec(v.abs(), 1);
4035            format!("{:.*}({:.*})", ndecimal as usize, v, ndecimal as usize, dv)
4036        }
4037    } else if dv >= 0.995 {
4038        if v.abs() >= 0.95 {
4039            format!("{:.1}({:.1})", v, dv)
4040        } else {
4041            let ndecimal = ndec(v.abs(), 1);
4042            format!("{:.*}({:.*})", ndecimal as usize, v, ndecimal as usize, dv)
4043        }
4044    } else {
4045        let ndecimal = ndec(v.abs(), 1).max(ndec(dv, 2));
4046        format!(
4047            "{:.*}({:.0})",
4048            ndecimal as usize,
4049            v,
4050            dv * (10.).powi(ndecimal)
4051        )
4052    }
4053}
4054
4055/// Compare two slices, selecting on length first
4056#[allow(unused)]
4057pub(crate) fn compare_slice<T: Ord>(slice1: &[T], slice2: &[T]) -> Ordering {
4058    match slice1.len().cmp(&slice2.len()) {
4059        Ordering::Equal => (),
4060        non_eq => return non_eq,
4061    }
4062
4063    let l = slice1.len();
4064    // Slice to the loop iteration range to enable bound check
4065    // elimination in the compiler
4066    let lhs = &slice1[..l];
4067    let rhs = &slice2[..l];
4068
4069    for i in 0..l {
4070        match lhs[i].cmp(&rhs[i]) {
4071            Ordering::Equal => (),
4072            non_eq => return non_eq,
4073        }
4074    }
4075
4076    Ordering::Equal
4077}
4078
4079pub trait Signum {
4080    fn multiply_sign(&self, sign: i8) -> Self;
4081}
4082
4083// impl Signum for f128::f128 {
4084//     #[inline]
4085//     fn multiply_sign(&self, sign: i8) -> f128::f128 {
4086//         match sign {
4087//             1 => *self,
4088//             0 => f128::f128::zero(),
4089//             -1 => self.neg(),
4090//             _ => unreachable!("Sign should be -1,0,1"),
4091//         }
4092//     }
4093// }
4094
4095impl Signum for f64 {
4096    #[inline]
4097    fn multiply_sign(&self, sign: i8) -> f64 {
4098        match sign {
4099            1 => *self,
4100            0 => self.zero(),
4101            -1 => -self,
4102            _ => unreachable!("Sign should be -1,0,1"),
4103        }
4104    }
4105}
4106
4107impl Signum for f32 {
4108    #[inline]
4109    fn multiply_sign(&self, sign: i8) -> Self {
4110        match sign {
4111            1 => *self,
4112            0 => 0.0,
4113            -1 => self.neg(),
4114            _ => unreachable!("Sign should be -1,0,1"),
4115        }
4116    }
4117}
4118
4119impl<T: FloatLike> Signum for Complex<F<T>> {
4120    #[inline]
4121    fn multiply_sign(&self, sign: i8) -> Complex<F<T>> {
4122        match sign {
4123            1 => self.clone(),
4124            0 => self.ref_zero(),
4125            -1 => -self.clone(),
4126            _ => unreachable!("Sign should be -1,0,1"),
4127        }
4128    }
4129}
4130
4131impl<T: FloatLike> Signum for FourMomentum<F<T>> {
4132    #[inline]
4133    fn multiply_sign(&self, sign: i8) -> FourMomentum<F<T>> {
4134        match sign {
4135            1 => self.clone(),
4136            0 => self.ref_zero(),
4137            -1 => -self,
4138            _ => unreachable!("Sign should be -1,0,1"),
4139        }
4140    }
4141}
4142
4143#[allow(unused)]
4144#[inline]
4145/// Invert with better precision
4146pub(crate) fn finv<T: FloatLike>(c: Complex<F<T>>) -> Complex<F<T>> {
4147    let norm = c.norm_squared();
4148    c.conj() / norm
4149}
4150
4151#[allow(unused)]
4152#[inline]
4153pub(crate) fn powi<T: FloatLike>(c: Complex<F<T>>, n: i32) -> Complex<F<T>> {
4154    if n.is_negative() {
4155        let u = -n as u64;
4156        finv(c.pow(u))
4157    } else {
4158        let u = n as u64;
4159        c.pow(u)
4160    }
4161}
4162
4163#[allow(unused)]
4164pub(crate) fn evaluate_signature<T>(
4165    signature: &[i8],
4166    momenta: &[FourMomentum<F<T>>],
4167) -> FourMomentum<F<T>>
4168where
4169    T: FloatLike,
4170{
4171    let mut momentum = momenta[0].zero();
4172    for (&sign, mom) in zip_eq(signature, momenta) {
4173        match sign {
4174            0 => {}
4175            1 => momentum += mom,
4176            -1 => momentum -= mom,
4177            _ => {
4178                #[cfg(debug_assertions)]
4179                panic!("Sign should be -1,0,1")
4180            }
4181        }
4182    }
4183
4184    momentum
4185}
4186
4187#[allow(unused)]
4188#[inline]
4189pub(crate) fn pinch_dampening_function<T: FloatLike>(
4190    dampening_arg: F<T>,
4191    delta_t: F<T>,
4192    powers: (u64, u64),
4193    multiplier: f64,
4194) -> F<T> {
4195    // Make sure the function is even in t-tstar
4196    assert!(powers.1.is_multiple_of(2));
4197    let a = dampening_arg.pow(powers.0);
4198    &a / (&a + F::<T>::from_f64(multiplier) * delta_t.pow(powers.1))
4199}
4200
4201pub(crate) fn h_dual<T: FloatLike>(
4202    t: &HyperDual<F<T>>,
4203    tstar: Option<HyperDual<F<T>>>,
4204    sigma: Option<F<T>>,
4205    h_function_settings: &crate::settings::runtime::HFunctionSettings,
4206) -> HyperDual<F<T>> {
4207    let sigma = sigma.unwrap_or_else(|| F::<T>::from_f64(h_function_settings.sigma));
4208    let sig = new_constant(t, &sigma);
4209    let two = new_constant(t, &sigma.from_usize(2));
4210    let power = h_function_settings.power;
4211    let prefactor = || {
4212        let normalisation = new_constant(t, &h_function_settings.normalization(&sigma));
4213        match power {
4214            None | Some(0) => normalisation.inv(),
4215            Some(p) => (t.clone() / &sig).inv().pow(p as u64) / normalisation,
4216        }
4217    };
4218    match h_function_settings.function {
4219        crate::settings::runtime::HFunction::Exponential => {
4220            // This profile has no power.
4221            (-(t.clone() * t) / (sig.clone() * &sig)).exp()
4222                / new_constant(t, &h_function_settings.normalization(&sigma))
4223        }
4224        crate::settings::runtime::HFunction::PolyExponential => {
4225            // Normalized by the integral of (t/sigma)^{-p} exp(2-t^2/sigma^2-sigma^2/t^2).
4226            prefactor()
4227                * (two
4228                    - (t.clone() * t) / (sig.clone() * &sig)
4229                    - (sig.clone() * &sig) / (t.clone() * t))
4230                    .exp()
4231        }
4232        crate::settings::runtime::HFunction::PolyLeftRightExponential => {
4233            // Normalized by the integral of (t/sigma)^{-p} exp(-((t^2/sigma^2+1)/(t/sigma)-2)).
4234            prefactor()
4235                * (two - ((t.clone() * t) / (sig.clone() * &sig) + t.one()) / (t.clone() / &sig))
4236                    .exp()
4237        }
4238        crate::settings::runtime::HFunction::ExponentialCT => {
4239            let delta_t_sq = (tstar.clone().unwrap() - t) * (tstar.clone().unwrap() - t);
4240            let tstar_sq = tstar.clone().unwrap() * tstar.unwrap();
4241            // info!("dampener: {}", dampener);
4242            // info!("delta_t_sq: {}", delta_t_sq);
4243            // info!("tstar_sq: {}", tstar_sq);
4244            // info!(
4245            //     "Exp arg: {}",
4246            //     -sig.inv() * (delta_t_sq / tstar_sq + sig * sig * (dampener * dampener))
4247            // );
4248            // info!(
4249            //     "result: {}",
4250            //     (-sig.inv() * (delta_t_sq / tstar_sq + sig * sig * (dampener * dampener))).exp()
4251            // );
4252            if h_function_settings.enabled_dampening {
4253                let dampener = delta_t_sq.clone() / (delta_t_sq.clone() - &tstar_sq);
4254                (-sig.inv()
4255                    * (delta_t_sq.clone() / tstar_sq
4256                        + sig.clone() * sig * (dampener.clone() * dampener)))
4257                    .exp()
4258            } else {
4259                (-sig.inv() * (delta_t_sq / tstar_sq)).exp()
4260            }
4261        }
4262    }
4263}
4264
4265pub(crate) fn h<T: FloatLike>(
4266    t: &F<T>,
4267    tstar: Option<F<T>>,
4268    sigma: Option<F<T>>,
4269    h_function_settings: &crate::settings::runtime::HFunctionSettings,
4270) -> F<T> {
4271    let sig = sigma.unwrap_or_else(|| F::<T>::from_f64(h_function_settings.sigma));
4272    let two = sig.from_usize(2);
4273    let power = h_function_settings.power;
4274    let prefactor = || {
4275        let normalisation = h_function_settings.normalization(&sig);
4276        match power {
4277            None | Some(0) => normalisation.inv(),
4278            Some(p) => (t / &sig).powi(-(p as i32)) / normalisation,
4279        }
4280    };
4281    match h_function_settings.function {
4282        crate::settings::runtime::HFunction::Exponential => {
4283            // This profile has no power.
4284            (-(t.square()) / (sig.square())).exp() / h_function_settings.normalization(&sig)
4285        }
4286        crate::settings::runtime::HFunction::PolyExponential => {
4287            // Normalized by the integral of (t/sigma)^{-p} exp(2-t^2/sigma^2-sigma^2/t^2).
4288            prefactor()
4289                * (two - (t.square()) / (sig.square()) - (sig.square()) / (t.square())).exp()
4290        }
4291        crate::settings::runtime::HFunction::PolyLeftRightExponential => {
4292            // Normalized by the integral of (t/sigma)^{-p} exp(-((t^2/sigma^2+1)/(t/sigma)-2)).
4293            prefactor() * (two - ((t.square()) / (sig.square()) + t.one()) / (t / &sig)).exp()
4294        }
4295        crate::settings::runtime::HFunction::ExponentialCT => {
4296            let delta_t_sq = (tstar.clone().unwrap() - t).square();
4297            let tstar_sq = tstar.unwrap().square();
4298            // info!("dampener: {}", dampener);
4299            // info!("delta_t_sq: {}", delta_t_sq);
4300            // info!("tstar_sq: {}", tstar_sq);
4301            // info!(
4302            //     "Exp arg: {}",
4303            //     -sig.inv() * (delta_t_sq / tstar_sq + sig * sig * (dampener * dampener))
4304            // );
4305            // info!(
4306            //     "result: {}",
4307            //     (-sig.inv() * (delta_t_sq / tstar_sq + sig * sig * (dampener * dampener))).exp()
4308            // );
4309            if h_function_settings.enabled_dampening {
4310                let dampener = delta_t_sq.clone() / (delta_t_sq.clone() - &tstar_sq);
4311                (-sig.inv() * (delta_t_sq.clone() / tstar_sq + sig.square() * (dampener.square())))
4312                    .exp()
4313            } else {
4314                (-sig.inv() * (delta_t_sq / tstar_sq)).exp()
4315            }
4316        }
4317    }
4318}
4319
4320/// Calculate the determinant of any complex-valued input matrix using LU-decomposition.
4321/// Original C-code by W. Gong and D.E. Soper.
4322#[allow(unused)]
4323pub(crate) fn determinant<T: FloatLike>(bb: &[Complex<F<T>>], dimension: usize) -> Complex<F<T>> {
4324    let one = bb[0].re.one();
4325    let zero = one.zero();
4326    // Define matrix related variables.
4327    let mut determinant = Complex::new(one.clone(), zero.clone());
4328    let mut indx = [0; MAX_DIMENSION];
4329    let mut d = 1; // initialize parity parameter
4330
4331    // Inintialize the matrix to be decomposed with the transferred matrix b.
4332    let mut aa = bb.to_vec();
4333
4334    // Define parameters used in decomposition.
4335    let mut imax = 0;
4336    let mut flag = 1;
4337    let mut dumc;
4338    let mut sum;
4339
4340    let mut aamax;
4341    let mut dumr;
4342    let mut vv = vec![zero.clone(); MAX_DIMENSION];
4343
4344    // Get the implicit scaling information.
4345    for i in 0..dimension {
4346        aamax = zero.clone();
4347        for j in 0..dimension {
4348            let r = aa[i * dimension + j].norm_squared();
4349            if r > aamax {
4350                aamax = r;
4351            }
4352        }
4353        // Set a flag to check if the determinant is zero.
4354        if aamax.is_zero() {
4355            flag = 0;
4356        }
4357        // Save the scaling.
4358        vv[i] = aamax.inv();
4359    }
4360    if flag == 1 {
4361        for j in 0..dimension {
4362            for i in 0..j {
4363                sum = aa[i * dimension + j].clone();
4364                for k in 0..i {
4365                    sum -= &aa[i * dimension + k] * &aa[k * dimension + j];
4366                }
4367                aa[i * dimension + j] = sum;
4368            }
4369            //Initialize for the search for largest pivot element.
4370            aamax = zero.clone();
4371            for i in j..dimension {
4372                sum = aa[i * dimension + j].clone();
4373                for k in 0..j {
4374                    sum -= &aa[i * dimension + k] * &aa[k * dimension + j];
4375                }
4376                aa[i * dimension + j] = sum.clone();
4377                // Figure of merit for the pivot.
4378                dumr = &vv[i] * sum.norm_squared();
4379                // Is it better than the best so far?
4380                if dumr >= aamax {
4381                    imax = i;
4382                    aamax = dumr;
4383                }
4384            }
4385            // See if we need to interchange rows.
4386            if j != imax {
4387                for k in 0..dimension {
4388                    dumc = aa[imax * dimension + k].clone();
4389                    aa[imax * dimension + k] = aa[j * dimension + k].clone();
4390                    aa[j * dimension + k] = dumc.clone();
4391                }
4392                // Change the parity of d.
4393                d = -d;
4394                // Interchange the scale factor.
4395                vv[imax] = vv[j].clone();
4396            }
4397            indx[j] = imax;
4398            if j + 1 != dimension {
4399                dumc = aa[j * dimension + j].inv();
4400                for i in j + 1..dimension {
4401                    aa[i * dimension + j] *= &dumc;
4402                }
4403            }
4404        }
4405    }
4406    // Calculate the determinant using the decomposed matrix.
4407    if flag == 0 {
4408        determinant = Complex::new(zero.clone(), zero.clone());
4409    } else {
4410        // Multiply the diagonal elements.
4411        for diagonal in 0..dimension {
4412            determinant *= &aa[diagonal * dimension + diagonal];
4413        }
4414        determinant *= &zero.from_i64(d);
4415    }
4416    determinant
4417}
4418
4419#[allow(unused)]
4420pub(crate) fn next_combination_with_replacement(state: &mut [usize], max_entry: usize) -> bool {
4421    for i in (0..state.len()).rev() {
4422        if state[i] < max_entry {
4423            state[i] += 1;
4424            for j in i + 1..state.len() {
4425                state[j] = state[i]
4426            }
4427            return true;
4428        }
4429    }
4430    false
4431}
4432
4433pub(crate) fn compute_loop_part<T: FloatLike>(
4434    loop_signature: &LoopSignature,
4435    loop_moms: &LoopMomenta<F<T>>,
4436) -> ThreeMomentum<F<T>> {
4437    loop_signature.apply_typed(loop_moms)
4438}
4439
4440pub(crate) fn compute_loop_part_subspace<T: FloatLike>(
4441    loop_signature: &LoopSignature,
4442    loop_moms: &LoopMomenta<F<T>>,
4443    subspace: &SubspaceData,
4444) -> ThreeMomentum<F<T>> {
4445    let projected: LoopSignature = subspace.project_loop_signature(loop_signature).collect();
4446    projected.apply_typed(loop_moms)
4447}
4448
4449pub(crate) fn compute_shift_part<T: FloatLike>(
4450    external_signature: &ExternalSignature,
4451    external_moms: &ExternalFourMomenta<F<T>>,
4452) -> FourMomentum<F<T>> {
4453    external_signature
4454        .apply_typed::<FourMomentum<F<T>>, ExternalIndex, ExternalFourMomenta<F<T>>>(external_moms)
4455}
4456
4457pub(crate) fn compute_shift_part_subspace<T: FloatLike>(
4458    loop_signature: &LoopSignature,
4459    external_signature: &ExternalSignature,
4460    loop_moms: &LoopMomenta<F<T>>,
4461    external_moms: &ExternalThreeMomenta<F<T>>,
4462    subspace: &SubspaceData,
4463) -> ThreeMomentum<F<T>> {
4464    let projected_loop_complement: LoopSignature = subspace
4465        .project_complement_loop_signature(loop_signature)
4466        .collect();
4467
4468    let loop_part = projected_loop_complement.apply_typed(loop_moms);
4469    let external_part: ThreeMomentum<F<T>> = external_signature
4470        .apply_typed::<ThreeMomentum<F<T>>, ExternalIndex, ExternalThreeMomenta<F<T>>>(
4471            external_moms,
4472        );
4473    loop_part + external_part
4474}
4475
4476pub(crate) fn compute_t_part_of_shift_part<T: FloatLike>(
4477    external_signature: &ExternalSignature,
4478    external_moms: &ExternalFourMomenta<F<T>>,
4479) -> F<T> {
4480    // external_signature.panic_validate_basis(external_moms);
4481    external_signature
4482        .apply_iter(external_moms.iter().map(|m| m.temporal.value.clone()))
4483        .unwrap_or(external_moms[ExternalIndex(0)].temporal.value.zero())
4484}
4485
4486// Bilinear form for E-surface defined as sqrt[(k+p1)^2+m1sq] + sqrt[(k+p2)^2+m2sq] + e_shift
4487// The Bilinear system then reads 4 k.a.k + 4 k.n + C = 0
4488#[allow(unused, clippy::type_complexity)]
4489pub(crate) fn one_loop_e_surface_bilinear_form<T: FloatLike>(
4490    p1: &[F<T>; 3],
4491    p2: &[F<T>; 3],
4492    m1_sq: F<T>,
4493    m2_sq: F<T>,
4494    e_shift: F<T>,
4495) -> ([[F<T>; 3]; 3], [F<T>; 3], F<T>) {
4496    let zero = e_shift.zero();
4497    let two = zero.from_i64(2);
4498    let e_shift_sq = e_shift.square();
4499    let p1_sq = p1[0].square() + p1[1].square() + p1[2].square();
4500    let p2_sq = p2[0].square() + p2[1].square() + p2[2].square();
4501
4502    let zeros = [zero.clone(), zero.clone(), zero.clone()];
4503    let mut a = [zeros.clone(), zeros.clone(), zeros.clone()];
4504    a[0][0] = (&p1[0] - &p2[0] - &e_shift) * (&p2[0] - &p1[0] - &e_shift);
4505    a[0][1] = (&p1[0] - &p2[0]) * (&p2[1] - &p1[1]);
4506    a[1][0] = a[0][1].clone();
4507    a[0][2] = (&p1[0] - &p2[0]) * (&p2[2] - &p1[2]);
4508    a[2][0] = a[0][2].clone();
4509    a[1][1] = (&p1[1] - &p2[1] - &e_shift) * (&p2[1] - &p1[1] - &e_shift);
4510    a[1][2] = (&p1[1] - &p2[1]) * (&p2[2] - &p1[2]);
4511    a[2][1] = a[1][2].clone();
4512    a[2][2] = (&p1[2] - &p2[2] - &e_shift) * (&p2[2] - &p1[2] - &e_shift);
4513
4514    let mut b = zeros.clone();
4515    b[0] =
4516        (&p2[0] - &p1[0]) * (&m1_sq - &m2_sq + &p1_sq - &p2_sq) + &e_shift_sq * (&p1[0] + &p2[0]);
4517    b[1] =
4518        (&p2[1] - &p1[1]) * (&m1_sq - &m2_sq + &p1_sq - &p2_sq) + &e_shift_sq * (&p1[1] + &p2[1]);
4519    b[2] =
4520        (&p2[2] - &p1[2]) * (&m1_sq - &m2_sq + &p1_sq - &p2_sq) + &e_shift_sq * (&p1[2] + &p2[2]);
4521
4522    let c = -&e_shift_sq * &e_shift_sq + &two * &e_shift_sq * (&m1_sq + &m2_sq + &p1_sq + &p2_sq)
4523        - (&m1_sq - &m2_sq + &p1_sq - &p2_sq) * (&m1_sq - &m2_sq + &p1_sq - &p2_sq);
4524
4525    (a, b, c)
4526}
4527
4528use color_eyre::Result;
4529use eyre::eyre;
4530#[allow(unused)]
4531use std::fmt::LowerExp;
4532
4533pub trait ApproxEq<U: LowerExp, T: LowerExp>: LowerExp {
4534    fn approx_eq(&self, other: &U, tolerance: &T) -> bool;
4535
4536    fn approx_eq_slice(lhs: &[Self], rhs: &[U], tolerance: &T) -> bool
4537    where
4538        Self: Sized,
4539    {
4540        lhs.iter()
4541            .zip_eq(rhs)
4542            .all(|(l, r)| l.approx_eq(r, tolerance))
4543    }
4544
4545    fn approx_eq_iterator<'a, I, J>(lhs: I, rhs: J, tolerance: &'a T) -> bool
4546    where
4547        Self: Sized + 'a,
4548        U: 'a,
4549        I: IntoIterator<Item = &'a Self>,
4550        J: IntoIterator<Item = &'a U>,
4551    {
4552        lhs.into_iter()
4553            .zip_eq(rhs)
4554            .all(|(l, r)| l.approx_eq(r, tolerance))
4555    }
4556
4557    fn assert_approx_eq(&self, other: &U, tolerance: &T) {
4558        assert!(
4559            self.approx_eq(other, tolerance),
4560            "assert_approx_eq failed: \n{:+e} != \n{:+e} with tolerance {:+e}",
4561            self,
4562            other,
4563            tolerance
4564        )
4565    }
4566    fn approx_eq_res(&self, other: &U, tolerance: &T) -> Result<()> {
4567        if self.approx_eq(other, tolerance) {
4568            Ok(())
4569        } else {
4570            Err(eyre!(
4571                "assert_approx_eq failed: \n{:+e} != \n{:+e} with tolerance {:+e}",
4572                self,
4573                other,
4574                tolerance
4575            ))
4576        }
4577    }
4578}
4579
4580// pub trait ApproxEqable: Real+PartialOrd+ for<'a> RefSub<&'a Self,Output = Self>+IsZero{}
4581
4582// impl<T: Real+PartialOrd+ for<'a> RefSub<&'a T,Output = T>+IsZero> ApproxEqable for T{}
4583
4584impl<T: FloatLike> ApproxEq<F<T>, F<T>> for F<T> {
4585    fn approx_eq(&self, other: &F<T>, tolerance: &F<T>) -> bool {
4586        if other.is_zero() {
4587            self.norm() < tolerance.clone()
4588        } else {
4589            ((self.ref_sub(other)) / other).norm() < tolerance.clone()
4590        }
4591    }
4592}
4593
4594impl<T: FloatLike> F<T> {
4595    // Return the circular difference and its existing RHS-relative comparison
4596    // value. Only the reference angle is wrapped: adding a tiny negative
4597    // difference to TAU can erase it before the tolerance check.
4598    fn phase_differences(lhs: &Complex<Self>, rhs: &Complex<Self>) -> (Self, Self) {
4599        // Binary scaling retains the represented directions. Dividing each
4600        // vector by an arbitrary maximum can round distinct ratios to equality.
4601        // The native magnitude bound supplies the binade without allocating
4602        // MPFR enclosures or narrowing the source components.
4603        let scale = |value: &Complex<Self>| {
4604            let maximum = value.re.abs().max(value.im.abs());
4605            let exponent = maximum.absolute_magnitude().exponent();
4606            // Give small inputs a full significand plus one guard binade.
4607            // A phase rounding to the smallest nonzero binary64 value can
4608            // still carry a meaningful relative gap: its minor component
4609            // must not lose source bits before the determinant is formed.
4610            // The guard covers half-subnormal phase rounding and the coarse
4611            // magnitude bound. Never downscale sources before cancellation:
4612            // a sparse double-double low limb can lie far below that budget.
4613            let headroom = i32::try_from(maximum.0.get_precision())
4614                .expect("working precision fits a binary scale exponent")
4615                + 1;
4616            let shift = headroom - exponent;
4617            // The preceding finite, nonzero squared-component norm bounds
4618            // the source exponents enough to keep this factor representable.
4619            let factor = maximum.from_usize(2).powi(shift.max(0));
4620            (&value.re * &factor, &value.im * &factor, shift.min(0))
4621        };
4622        let (lhs_re, lhs_im, lhs_shift) = scale(lhs);
4623        let (rhs_re, rhs_im, rhs_shift) = scale(rhs);
4624        // Compensate the rounded product in the determinant when nearby
4625        // directions cancel. The finite squared-norm gate bounds each product;
4626        // upscaling small sources to the headroom also leaves products finite.
4627        let product = &lhs_re * &rhs_im;
4628        let product_error = lhs_re.mul_add(&rhs_im, &(-&product));
4629        let cross = lhs_im.mul_add(&rhs_re, &(-product)) - &product_error;
4630        let dot = lhs_re.mul_add(&rhs_re, &(&lhs_im * &rhs_im));
4631        // Apply any downscaling only after cancellation. This keeps atan2's
4632        // internal reciprocal away from underflow without erasing input limbs.
4633        // Retain the original products for gaps below native angular range.
4634        let reduced;
4635        let (angle_cross, angle_dot) = if lhs_shift + rhs_shift < 0 {
4636            let factor = cross.from_usize(2).powi(lhs_shift + rhs_shift);
4637            // At the upper norm boundary, fused sums can overflow even when
4638            // separately rounded squared norms are finite. Reduce the finite
4639            // individual products before combining them in that case.
4640            let reduced_cross = if cross.0.is_finite() {
4641                &cross * &factor
4642            } else {
4643                (&lhs_im * &rhs_re) * &factor
4644                    - (&lhs_re * &rhs_im) * &factor
4645                    - &product_error * &factor
4646            };
4647            let reduced_dot = if dot.0.is_finite() {
4648                &dot * &factor
4649            } else {
4650                (&lhs_re * &rhs_re) * &factor + (&lhs_im * &rhs_im) * &factor
4651            };
4652            reduced = (reduced_cross, reduced_dot);
4653            (&reduced.0, &reduced.1)
4654        } else {
4655            (&cross, &dot)
4656        };
4657        // Keep the internal atan2 ratio bounded too: the double-double
4658        // backend can overflow when a near-perpendicular dot is subnormal.
4659        let difference = if angle_cross.abs() > angle_dot.abs() {
4660            let angle = angle_cross.PIHALF() - angle_dot.atan2(&angle_cross.abs());
4661            if angle_cross < &angle_cross.zero() {
4662                -angle
4663            } else {
4664                angle
4665            }
4666        } else {
4667            angle_cross.atan2(angle_dot)
4668        };
4669        let rhs_phase = rhs.arg().rem_euclid(&rhs.re.TAU());
4670        let relative = if rhs_phase.is_zero()
4671            || (difference.is_zero() && cross.is_zero() && rhs_phase.0.is_finite())
4672        {
4673            // Some backends divide through a reciprocal: even zero divided by
4674            // a nonzero subnormal reference can then become NaN.
4675            difference.clone()
4676        } else if angle_dot > &angle_dot.zero()
4677            && !cross.is_zero()
4678            && difference.0.is_finite()
4679            && (difference.is_zero() || difference.0.needs_rescaling())
4680        {
4681            // In this underflow range atan(t)/t rounds to one. Combine the
4682            // RHS normalization before rounding the angle: a subnormal (or
4683            // unrepresentable) difference can still give a finite ratio.
4684            if rhs_phase >= rhs_phase.one() {
4685                // A wrapped reference near TAU could overflow the original
4686                // dot product. The reduced products retain representable gaps.
4687                angle_cross / (angle_dot * rhs_phase)
4688            } else if dot.0.is_finite() {
4689                &cross / (&dot * rhs_phase)
4690            } else {
4691                // Combine the tiny reference with the inverse reduction before
4692                // multiplying, so the overflowing dot is never materialized.
4693                let factor = cross.from_usize(2).powi(lhs_shift + rhs_shift);
4694                &cross / (angle_dot * (rhs_phase / factor))
4695            }
4696        } else {
4697            &difference / rhs_phase
4698        };
4699        (difference, relative)
4700    }
4701}
4702
4703impl<T: FloatLike> ApproxEq<Complex<F<T>>, F<T>> for Complex<F<T>> {
4704    fn approx_eq(&self, other: &Complex<F<T>>, tolerance: &F<T>) -> bool {
4705        if !self.norm().re.approx_eq(&other.norm().re, tolerance) {
4706            return false;
4707        } else if self.norm().is_zero() || other.norm().is_zero() {
4708            return true;
4709        }
4710        let (_, relative_phase) = F::phase_differences(self, other);
4711        relative_phase.approx_eq(&relative_phase.zero(), tolerance)
4712    }
4713    fn approx_eq_res(&self, other: &Complex<F<T>>, tolerance: &F<T>) -> Result<()> {
4714        if !self.norm().re.approx_eq(&other.norm().re, tolerance) {
4715            return Err(eyre!(
4716                "Norms are not approximately equal: \n{:+e} != \n{:+e} with tolerance {:+e}",
4717                &self.norm().re,
4718                other.norm().re,
4719                tolerance
4720            ));
4721        } else if self.norm().is_zero() || other.norm().is_zero() {
4722            return Ok(());
4723        }
4724
4725        let (phase_difference, relative_phase) = F::phase_differences(self, other);
4726        if !relative_phase.approx_eq(&relative_phase.zero(), tolerance) {
4727            return Err(eyre!(
4728                "Phases are not approximately equal: \nRHS-relative comparison value {:+e} (rounded circular difference {:+e}) between \n{:+e} and \n{:+e} with tolerance {:+e}",
4729                relative_phase,
4730                phase_difference,
4731                self.arg(),
4732                other.arg(),
4733                tolerance
4734            ));
4735        }
4736        Ok(())
4737    }
4738}
4739
4740impl<T: FloatLike> ApproxEq<F<T>, F<T>> for Complex<F<T>> {
4741    fn approx_eq(&self, other: &F<T>, tolerance: &F<T>) -> bool {
4742        self.re.approx_eq(other, tolerance) && self.im.approx_eq(tolerance, tolerance)
4743    }
4744    fn approx_eq_res(&self, other: &F<T>, tolerance: &F<T>) -> Result<()> {
4745        if self.im.approx_eq(tolerance, tolerance) {
4746            return Err(eyre!(
4747                "Non-zero imaginary part: \n{:+e} with tolerance {:+e}",
4748                &self.im,
4749                tolerance
4750            ));
4751        }
4752        if !self.re.approx_eq(other, tolerance) {
4753            return Err(eyre!(
4754                "Real parts are not approximately equal: \n{:+e} != \n{:+e} with tolerance {:+e}",
4755                &self.re,
4756                other,
4757                tolerance
4758            ));
4759        }
4760        Ok(())
4761    }
4762}
4763
4764impl<T: FloatLike> ApproxEq<Complex<F<T>>, F<T>> for F<T> {
4765    fn approx_eq(&self, other: &Complex<F<T>>, tolerance: &F<T>) -> bool {
4766        other.re.approx_eq(self, tolerance) && other.im.approx_eq(tolerance, tolerance)
4767    }
4768
4769    fn approx_eq_res(&self, other: &Complex<F<T>>, tolerance: &F<T>) -> Result<()> {
4770        if other.im.approx_eq(tolerance, tolerance) {
4771            return Err(eyre!(
4772                "Non-zero imaginary part: \n{:+e} with tolerance {:+e}",
4773                &other.im,
4774                tolerance
4775            ));
4776        }
4777        if !other.re.approx_eq(self, tolerance) {
4778            return Err(eyre!(
4779                "Real parts are not approximately equal: \n{:+e} != \n{:+e} with tolerance {:+e}",
4780                &other.re,
4781                self,
4782                tolerance
4783            ));
4784        }
4785        Ok(())
4786    }
4787}
4788
4789#[allow(unused)]
4790pub(crate) fn one_loop_eval_e_surf<T: FloatLike>(
4791    k: &[F<T>; 3],
4792    p1: &[F<T>; 3],
4793    p2: &[F<T>; 3],
4794    m1_sq: F<T>,
4795    m2_sq: F<T>,
4796    e_shift: F<T>,
4797) -> F<T> {
4798    ((&k[0] + &p1[0]) * (&k[0] + &p1[0])
4799        + (&k[1] + &p1[1]) * (&k[1] + &p1[1])
4800        + (&k[2] + &p1[2]) * (&k[2] + &p1[2])
4801        + m1_sq)
4802        .sqrt()
4803        + ((&k[0] + &p2[0]) * (&k[0] + &p2[0])
4804            + (&k[1] + &p2[1]) * (&k[1] + &p2[1])
4805            + (&k[2] + &p2[2]) * (&k[2] + &p2[2])
4806            + m2_sq)
4807            .sqrt()
4808        + e_shift
4809}
4810
4811#[allow(unused)]
4812pub(crate) fn one_loop_eval_e_surf_k_derivative<T: FloatLike>(
4813    k: &[F<T>; 3],
4814    p1: &[F<T>; 3],
4815    p2: &[F<T>; 3],
4816    m1_sq: F<T>,
4817    m2_sq: F<T>,
4818) -> [F<T>; 3] {
4819    let e1 = ((&k[0] + &p1[0]) * (&k[0] + &p1[0])
4820        + (&k[1] + &p1[1]) * (&k[1] + &p1[1])
4821        + (&k[2] + &p1[2]) * (&k[2] + &p1[2])
4822        + m1_sq)
4823        .sqrt();
4824    let e2 = ((&k[0] + &p2[0]) * (&k[0] + &p2[0])
4825        + (&k[1] + &p2[1]) * (&k[1] + &p2[1])
4826        + (&k[2] + &p2[2]) * (&k[2] + &p2[2])
4827        + m2_sq)
4828        .sqrt();
4829    [
4830        (&k[0] + &p1[0]) / &e1 + (&k[0] + &p2[0]) / &e2,
4831        (&k[1] + &p1[1]) / &e1 + (&k[1] + &p2[1]) / &e2,
4832        (&k[2] + &p1[2]) / &e1 + (&k[2] + &p2[2]) / &e2,
4833    ]
4834}
4835
4836#[allow(unused)]
4837pub(crate) fn one_loop_get_e_surf_t_scaling<T: FloatLike>(
4838    k: &[F<T>; 3],
4839    p1: &[F<T>; 3],
4840    p2: &[F<T>; 3],
4841    m1_sq: F<T>,
4842    m2_sq: F<T>,
4843    e_shift: F<T>,
4844) -> [F<T>; 2] {
4845    let zero = e_shift.zero();
4846    let one = zero.one();
4847    let (a, b, c_coef) = one_loop_e_surface_bilinear_form(p1, p2, m1_sq, m2_sq, e_shift);
4848    let mut a_coef = zero.clone();
4849    for i in 0..=2 {
4850        for j in 0..=2 {
4851            a_coef += &k[i] * &a[i][j] * &k[j];
4852        }
4853    }
4854    a_coef *= zero.from_i64(4);
4855    let mut b_coef = zero.clone();
4856    for i in 0..=2 {
4857        b_coef += &k[i] * &b[i];
4858    }
4859    b_coef *= zero.from_i64(4);
4860    let discr = b_coef.square() - zero.from_i64(4) * &a_coef * &c_coef;
4861    if discr < zero {
4862        [zero.clone(), zero.clone()]
4863    } else {
4864        [
4865            (-&b_coef + discr.sqrt()) / (zero.from_i64(2) * &a_coef),
4866            (-&b_coef - discr.sqrt()) / (zero.from_i64(2) * &a_coef),
4867        ]
4868    }
4869}
4870
4871pub(crate) fn box_muller<T: FloatLike>(x1: F<T>, x2: F<T>) -> (F<T>, F<T>) {
4872    let r = (-x1.from_i64(2) * x1.log()).sqrt();
4873    let theta = r.from_i64(2) * r.PI() * x2;
4874    (r.clone() * theta.cos(), r * theta.sin())
4875}
4876
4877pub(crate) fn compute_surface_and_volume<T: FloatLike>(n_dim: usize, radius: F<T>) -> (F<T>, F<T>) {
4878    let mut surface = radius.from_i64(2);
4879    let one = radius.one();
4880    let mut volume = one.clone();
4881    for i in 1..n_dim + 1 {
4882        (surface, volume) = (
4883            one.from_i64(2) * one.PI() * volume,
4884            surface / one.from_i64(i as i64),
4885        );
4886    }
4887    (
4888        surface * radius.pow(n_dim as u64),
4889        volume * radius.pow(n_dim as u64),
4890    )
4891}
4892
4893pub(crate) fn get_n_dim_for_n_loop_momenta(
4894    settings: &SamplingSettings,
4895    n_loop_momenta: usize,
4896    n_edges: Option<usize>, // for tropical parameterization, we need to know the number of edges
4897) -> usize {
4898    if let Some(parameterization_settings) = settings.get_parameterization_settings() {
4899        match parameterization_settings.mode {
4900            ParameterizationMode::HyperSphericalFlat => {
4901                // Because we use Box-Muller, we need to have an even number of angular dimensions
4902                let mut n_dim = 3 * n_loop_momenta;
4903                if n_dim % 2 == 1 {
4904                    n_dim += 1;
4905                }
4906                n_dim + 1
4907            }
4908            ParameterizationMode::HyperSpherical
4909            | ParameterizationMode::Cartesian
4910            | ParameterizationMode::Spherical
4911            | ParameterizationMode::RelativeSpherical
4912            | ParameterizationMode::SphericalCommonRadial
4913            | ParameterizationMode::SphericalProductCommonRadial
4914            | ParameterizationMode::MomentumSpace => 3 * n_loop_momenta,
4915        }
4916    } else {
4917        let tropical_part = 2 * n_edges.expect("No tropical subgraph table generated, please run without tropical sampling or regenerate with tables") - 1;
4918        let d_l = 3 * n_loop_momenta;
4919        if d_l % 2 == 1 {
4920            tropical_part + d_l + 1
4921        } else {
4922            tropical_part + d_l
4923        }
4924    }
4925}
4926
4927pub(crate) fn global_parameterize<T: FloatLike>(
4928    x: &[F<T>],
4929    e_cm: F<T>,
4930    settings: &ParameterizationSettings,
4931) -> (Vec<[F<T>; 3]>, F<T>) {
4932    debug!("b: {}", settings.b);
4933    let zero = e_cm.zero();
4934    let one = zero.one();
4935    match settings.mode {
4936        ParameterizationMode::HyperSpherical | ParameterizationMode::HyperSphericalFlat => {
4937            let mut jac = one.clone();
4938
4939            let radius: F<T> = match settings.mapping {
4940                ParameterizationMapping::Log => {
4941                    // r = e_cm * ln(1 + b*x/(1-x))
4942                    let b = F::<T>::from_f64(settings.b);
4943                    let radius = &e_cm * (&one + &b * &x[0] / (&one - &x[0])).log();
4944                    jac *= &e_cm * &b / (&one - &x[0]) / (&one + &x[0] * (&b - &one));
4945                    radius
4946                }
4947                ParameterizationMapping::Power => {
4948                    // r = e_cm * b * (x/(1-x))^p; p=1 reproduces the linear map.
4949                    let b = F::<T>::from_f64(settings.b);
4950                    let power = F::<T>::from_f64(settings.power);
4951                    let odds = &x[0] / (&one - &x[0]);
4952                    let power_minus_one = &power - &one;
4953                    let radius = &e_cm * &b * odds.powf(&power);
4954                    jac *=
4955                        &e_cm * &b * &power * odds.powf(&power_minus_one) / (&one - &x[0]).square();
4956                    radius
4957                }
4958                ParameterizationMapping::Linear => {
4959                    // r = e_cm * b * x/(1-x)
4960                    let b = F::<T>::from_f64(settings.b);
4961                    let radius = &e_cm * &b * &x[0] / (&one - &x[0]);
4962                    jac *= (&e_cm * &b + &radius).powi(2) / &e_cm / &b;
4963                    radius
4964                }
4965            };
4966            match settings.mode {
4967                ParameterizationMode::HyperSpherical => {
4968                    let phi = zero.from_i64(2) * zero.PI() * &x[1];
4969                    jac *= zero.from_i64(2) * zero.PI();
4970
4971                    let mut cos_thetas = Vec::with_capacity(x.len() - 2);
4972                    let mut sin_thetas = Vec::with_capacity(x.len() - 2);
4973
4974                    for (i, xi) in x[2..].iter().enumerate() {
4975                        let cos_theta = -&one + zero.from_i64(2) * xi;
4976                        jac *= zero.from_i64(2);
4977                        let sin_theta = (&one - cos_theta.square()).sqrt();
4978                        // Uniform cos(theta_i) leaves the angular factor
4979                        // sin(theta_i)^(D-3-i) for this Cartesian ordering.
4980                        let angular_power = x.len() - 3 - i;
4981                        if angular_power > 0 {
4982                            jac *= sin_theta.pow(angular_power as u64);
4983                        }
4984                        cos_thetas.push(cos_theta);
4985                        sin_thetas.push(sin_theta);
4986                    }
4987
4988                    let mut concatenated_vecs = Vec::with_capacity(x.len() / 3);
4989                    let mut base = radius.clone();
4990                    for (cos_theta, sin_theta) in cos_thetas.iter().zip(sin_thetas.iter()) {
4991                        concatenated_vecs.push(&base * cos_theta);
4992                        base *= sin_theta;
4993                    }
4994                    concatenated_vecs.push(&base * phi.cos());
4995                    concatenated_vecs.push(&base * phi.sin());
4996
4997                    jac *= radius.pow((x.len() - 1) as u64); // hyperspherical coords
4998
4999                    (
5000                        concatenated_vecs
5001                            .chunks(3)
5002                            .map(|v| [v[0].clone(), v[1].clone(), v[2].clone()])
5003                            .collect(),
5004                        jac,
5005                    )
5006                }
5007                ParameterizationMode::HyperSphericalFlat => {
5008                    // As we will use Box Muller we expect an even number of random variables
5009                    assert!(x[1..].len().is_multiple_of(2));
5010                    let mut normal_distributed_xs = vec![];
5011                    for x_pair in x[1..].chunks(2) {
5012                        let (z1, z2) = box_muller(x_pair[0].clone(), x_pair[1].clone());
5013                        normal_distributed_xs.push(z1);
5014                        normal_distributed_xs.push(z2);
5015                    }
5016                    // ignore the last variable generated if we had to pad to get the 3*n_loop_momenta
5017                    if normal_distributed_xs.len() % 3 != 0 {
5018                        normal_distributed_xs.pop();
5019                    }
5020                    let curr_norm = normal_distributed_xs[..]
5021                        .iter()
5022                        .map(|x| x.square())
5023                        .reduce(|acc, e| acc + &e)
5024                        .unwrap_or(zero.clone())
5025                        .sqrt();
5026                    let surface =
5027                        compute_surface_and_volume(normal_distributed_xs.len() - 1, radius.clone())
5028                            .0;
5029                    jac *= surface;
5030                    let rescaling_factor = &radius / &curr_norm;
5031                    (
5032                        normal_distributed_xs
5033                            .chunks(3)
5034                            .map(|v| {
5035                                [
5036                                    &v[0] * &rescaling_factor,
5037                                    &v[1] * &rescaling_factor,
5038                                    &v[2] * &rescaling_factor,
5039                                ]
5040                            })
5041                            .collect(),
5042                        jac,
5043                    )
5044                }
5045                _ => unreachable!(),
5046            }
5047        }
5048        ParameterizationMode::Cartesian | ParameterizationMode::Spherical => {
5049            let mut jac = one.clone();
5050            let mut vecs = Vec::with_capacity(x.len() / 3);
5051            for xi in x.chunks(3) {
5052                let (vec_i, jac_i) = parameterize3d(xi, e_cm.clone(), settings);
5053                vecs.push(vec_i);
5054                jac *= jac_i;
5055            }
5056            (vecs, jac)
5057        }
5058        ParameterizationMode::RelativeSpherical => {
5059            if x.len() != 6 {
5060                panic!(
5061                    "relative_spherical parameterization currently requires exactly two loop three-momenta"
5062                );
5063            }
5064            let spherical_settings = ParameterizationSettings {
5065                mode: ParameterizationMode::Spherical,
5066                mapping: settings.mapping.clone(),
5067                b: settings.b,
5068                power: settings.power,
5069                lmb_basis_ids: Default::default(),
5070                sampling_channels: Default::default(),
5071            };
5072            let (common, common_jac) = parameterize3d(&x[0..3], e_cm.clone(), &spherical_settings);
5073            let (relative, relative_jac) =
5074                parameterize3d(&x[3..6], e_cm.clone(), &spherical_settings);
5075            let half = &one / one.from_i64(2);
5076            let first = [
5077                &common[0] + &half * &relative[0],
5078                &common[1] + &half * &relative[1],
5079                &common[2] + &half * &relative[2],
5080            ];
5081            let second = [
5082                &common[0] - &half * &relative[0],
5083                &common[1] - &half * &relative[1],
5084                &common[2] - &half * &relative[2],
5085            ];
5086            (vec![first, second], common_jac * relative_jac)
5087        }
5088        ParameterizationMode::SphericalCommonRadial => {
5089            if x.is_empty() || !x.len().is_multiple_of(3) {
5090                panic!(
5091                    "spherical_common_radial parameterization requires complete loop three-momenta"
5092                );
5093            }
5094            let n_loop_momenta = x.len() / 3;
5095
5096            let mut jac = one.clone();
5097            let radius = match settings.mapping {
5098                ParameterizationMapping::Log => {
5099                    let b = F::<T>::from_f64(settings.b);
5100                    let radius = &e_cm * (&one + &b * &x[0] / (&one - &x[0])).log();
5101                    jac *= &e_cm * &b / (&one - &x[0]) / (&one + &x[0] * (&b - &one));
5102                    radius
5103                }
5104                ParameterizationMapping::Power => {
5105                    let b = F::<T>::from_f64(settings.b);
5106                    let power = F::<T>::from_f64(settings.power);
5107                    let odds = &x[0] / (&one - &x[0]);
5108                    let power_minus_one = &power - &one;
5109                    let radius = &e_cm * &b * odds.powf(&power);
5110                    jac *=
5111                        &e_cm * &b * &power * odds.powf(&power_minus_one) / (&one - &x[0]).square();
5112                    radius
5113                }
5114                ParameterizationMapping::Linear => {
5115                    let b = F::<T>::from_f64(settings.b);
5116                    let radius = &e_cm * &b * &x[0] / (&one - &x[0]);
5117                    jac *= (&e_cm * &b + &radius).powi(2) / &e_cm / &b;
5118                    radius
5119                }
5120            };
5121
5122            let mut remaining_fraction = one.clone();
5123            let mut stick_jac = one.clone();
5124            let mut radii = Vec::with_capacity(n_loop_momenta);
5125            for i in 0..n_loop_momenta {
5126                let fraction = if i + 1 == n_loop_momenta {
5127                    remaining_fraction.clone()
5128                } else {
5129                    stick_jac *= &remaining_fraction;
5130                    let fraction = &remaining_fraction * &x[1 + i];
5131                    remaining_fraction *= &one - &x[1 + i];
5132                    fraction
5133                };
5134                radii.push(&radius * fraction);
5135            }
5136
5137            jac *= radius.pow((n_loop_momenta - 1) as u64) * stick_jac;
5138            for radius_i in &radii {
5139                jac *= radius_i.square();
5140            }
5141
5142            let angle_offset = n_loop_momenta;
5143            let mut momenta = Vec::with_capacity(n_loop_momenta);
5144            for (i, radius_i) in radii.iter().enumerate() {
5145                let phi = zero.from_i64(2) * zero.PI() * &x[angle_offset + 2 * i];
5146                jac *= zero.from_i64(2) * zero.PI();
5147                let cos_theta = -&one + zero.from_i64(2) * &x[angle_offset + 2 * i + 1];
5148                jac *= zero.from_i64(2);
5149                let sin_theta = (&one - cos_theta.square()).sqrt();
5150                momenta.push([
5151                    radius_i * &sin_theta * phi.cos(),
5152                    radius_i * &sin_theta * phi.sin(),
5153                    radius_i * cos_theta,
5154                ]);
5155            }
5156
5157            (momenta, jac)
5158        }
5159        ParameterizationMode::SphericalProductCommonRadial => {
5160            if x.len() != 6 {
5161                panic!(
5162                    "spherical_product_common_radial parameterization currently requires exactly two loop three-momenta"
5163                );
5164            }
5165            let mut branch_x = x.to_vec();
5166            let branch_settings = if x[0] < (&one / one.from_i64(2)) {
5167                branch_x[0] = &x[0] * zero.from_i64(2);
5168                ParameterizationSettings {
5169                    mode: ParameterizationMode::Spherical,
5170                    mapping: settings.mapping.clone(),
5171                    b: settings.b,
5172                    power: settings.power,
5173                    lmb_basis_ids: Default::default(),
5174                    sampling_channels: Default::default(),
5175                }
5176            } else {
5177                branch_x[0] = (&x[0] - (&one / one.from_i64(2))) * zero.from_i64(2);
5178                ParameterizationSettings {
5179                    mode: ParameterizationMode::SphericalCommonRadial,
5180                    mapping: settings.mapping.clone(),
5181                    b: settings.b,
5182                    power: settings.power,
5183                    lmb_basis_ids: Default::default(),
5184                    sampling_channels: Default::default(),
5185                }
5186            };
5187            let (momenta, jac) = global_parameterize(&branch_x, e_cm, &branch_settings);
5188            (momenta, jac * zero.from_i64(2))
5189        }
5190        ParameterizationMode::MomentumSpace => (x.as_chunks::<3>().0.to_vec(), one),
5191    }
5192}
5193
5194#[allow(unused)]
5195pub(crate) fn global_inv_parameterize<T: FloatLike>(
5196    moms: &[ThreeMomentum<F<T>>],
5197    e_cm: F<T>,
5198    settings: &ParameterizationSettings,
5199) -> (Vec<F<T>>, F<T>) {
5200    let one = e_cm.one();
5201    let zero = one.zero();
5202
5203    match settings.mode {
5204        ParameterizationMode::HyperSpherical => {
5205            let mut inv_jac = one.clone();
5206            let mut xs = Vec::with_capacity(moms.len() * 3);
5207
5208            let cartesian_xs = moms
5209                .iter()
5210                .flat_map(|lv| lv.clone().into_iter())
5211                .collect::<Vec<F<T>>>();
5212
5213            let mut k_r_sq = cartesian_xs
5214                .iter()
5215                .map(|xi| xi.square())
5216                .reduce(|acc, e| acc + &e)
5217                .unwrap_or(zero.clone());
5218            // cover the degenerate case
5219            if k_r_sq.is_zero() {
5220                return (vec![zero.clone(); cartesian_xs.len()], zero);
5221            }
5222            let k_r = k_r_sq.sqrt();
5223            match settings.mapping {
5224                ParameterizationMapping::Log => {
5225                    let b = F::<T>::from_f64(settings.b);
5226                    let x1 = &one - &b / (-&one + &b + (&k_r / &e_cm).exp());
5227                    inv_jac /= e_cm * &b / (&one - &x1) / (&one + &x1 * (&b - &one));
5228                    xs.push(x1);
5229                }
5230                ParameterizationMapping::Power => {
5231                    let b = F::<T>::from_f64(settings.b);
5232                    let power = F::<T>::from_f64(settings.power);
5233                    let inv_power = &one / &power;
5234                    let odds = (&k_r / (&e_cm * &b)).powf(&inv_power);
5235                    let x1 = &odds / (&one + &odds);
5236                    let power_minus_one = &power - &one;
5237                    inv_jac /=
5238                        &e_cm * &b * &power * odds.powf(&power_minus_one) / (&one - &x1).square();
5239                    xs.push(x1);
5240                }
5241                ParameterizationMapping::Linear => {
5242                    let b = F::<T>::from_f64(settings.b);
5243                    inv_jac /= (&e_cm * &b + &k_r).powi(2) / &e_cm / &b;
5244                    xs.push(&k_r / (&e_cm * &b + &k_r));
5245                }
5246            };
5247
5248            let y = cartesian_xs[cartesian_xs.len() - 2].clone();
5249            let x = cartesian_xs[cartesian_xs.len() - 1].clone();
5250            let xphi = if x < zero {
5251                &one + (&one / one.from_i64(2)) * zero.FRAC_1_PI() * x.atan2(&y)
5252            } else {
5253                (&one / one.from_i64(2)) * zero.FRAC_1_PI() * x.atan2(&y)
5254            };
5255            xs.push(xphi);
5256            inv_jac /= zero.from_i64(2) * zero.PI();
5257
5258            for (i, x) in cartesian_xs[..cartesian_xs.len() - 2].iter().enumerate() {
5259                xs.push((&one / one.from_i64(2)) * (&one + x / k_r_sq.sqrt()));
5260                inv_jac /= zero.from_i64(2);
5261                let angular_power = cartesian_xs.len() - 3 - i;
5262                if angular_power > 0 {
5263                    inv_jac /= (&one - (x * x / &k_r_sq)).sqrt().pow(angular_power as u64);
5264                }
5265                k_r_sq -= x * x;
5266            }
5267
5268            inv_jac /= k_r.powi((cartesian_xs.len() - 1) as i32);
5269
5270            (xs, inv_jac)
5271        }
5272        ParameterizationMode::HyperSphericalFlat => {
5273            panic!(
5274                "Inverse of flat hyperspherical sampling is not available since it is not bijective."
5275            );
5276        }
5277        ParameterizationMode::Cartesian | ParameterizationMode::Spherical => {
5278            let mut inv_jac = one;
5279            let mut xs = Vec::with_capacity(moms.len() * 3);
5280            for (i, mom) in moms.iter().enumerate() {
5281                let (xs_i, inv_jac_i) = inv_parametrize3d(mom, e_cm.clone(), settings);
5282
5283                xs.extend(xs_i);
5284                inv_jac *= inv_jac_i;
5285            }
5286            (xs, inv_jac)
5287        }
5288        ParameterizationMode::RelativeSpherical => {
5289            if moms.len() != 2 {
5290                panic!(
5291                    "relative_spherical inverse parameterization currently requires exactly two loop three-momenta"
5292                );
5293            }
5294            let half = &one / one.from_i64(2);
5295            let common = ThreeMomentum::new(
5296                (&moms[0].px + &moms[1].px) * &half,
5297                (&moms[0].py + &moms[1].py) * &half,
5298                (&moms[0].pz + &moms[1].pz) * &half,
5299            );
5300            let relative = ThreeMomentum::new(
5301                &moms[0].px - &moms[1].px,
5302                &moms[0].py - &moms[1].py,
5303                &moms[0].pz - &moms[1].pz,
5304            );
5305            let spherical_settings = ParameterizationSettings {
5306                mode: ParameterizationMode::Spherical,
5307                mapping: settings.mapping.clone(),
5308                b: settings.b,
5309                power: settings.power,
5310                lmb_basis_ids: Default::default(),
5311                sampling_channels: Default::default(),
5312            };
5313            let (common_xs, common_inv_jac) =
5314                inv_parametrize3d(&common, e_cm.clone(), &spherical_settings);
5315            let (relative_xs, relative_inv_jac) =
5316                inv_parametrize3d(&relative, e_cm.clone(), &spherical_settings);
5317            (
5318                common_xs.into_iter().chain(relative_xs).collect(),
5319                common_inv_jac * relative_inv_jac,
5320            )
5321        }
5322        ParameterizationMode::SphericalCommonRadial => {
5323            if moms.is_empty() {
5324                panic!(
5325                    "spherical_common_radial inverse parameterization requires at least one loop three-momentum"
5326                );
5327            }
5328
5329            let phi_x = |x: &F<T>, y: &F<T>| {
5330                if y < &zero {
5331                    &one + (&one / one.from_i64(2)) * zero.FRAC_1_PI() * y.atan2(x)
5332                } else {
5333                    (&one / one.from_i64(2)) * zero.FRAC_1_PI() * y.atan2(x)
5334                }
5335            };
5336
5337            let radii_sq = moms
5338                .iter()
5339                .map(|mom| mom.px.square() + mom.py.square() + mom.pz.square())
5340                .collect::<Vec<_>>();
5341            let radii = radii_sq
5342                .iter()
5343                .map(|radius_sq| radius_sq.sqrt())
5344                .collect::<Vec<_>>();
5345            let radius = radii
5346                .iter()
5347                .fold(zero.clone(), |acc, radius_i| acc + radius_i);
5348
5349            let mut xs = Vec::with_capacity(3 * moms.len());
5350            if radius.is_zero() || radii.iter().any(F::is_zero) {
5351                xs.resize(3 * moms.len(), zero.clone());
5352                return (xs, zero);
5353            }
5354
5355            let mut inv_jac = one.clone();
5356            let radial_x = match settings.mapping {
5357                ParameterizationMapping::Log => {
5358                    let b = F::<T>::from_f64(settings.b);
5359                    let x1 = &one - &b / (-&one + &b + (&radius / &e_cm).exp());
5360                    inv_jac /= &e_cm * &b / (&one - &x1) / (&one + &x1 * (&b - &one));
5361                    x1
5362                }
5363                ParameterizationMapping::Power => {
5364                    let b = F::<T>::from_f64(settings.b);
5365                    let power = F::<T>::from_f64(settings.power);
5366                    let inv_power = &one / &power;
5367                    let odds = (&radius / (&e_cm * &b)).powf(&inv_power);
5368                    let x1 = &odds / (&one + &odds);
5369                    let power_minus_one = &power - &one;
5370                    inv_jac /=
5371                        &e_cm * &b * &power * odds.powf(&power_minus_one) / (&one - &x1).square();
5372                    x1
5373                }
5374                ParameterizationMapping::Linear => {
5375                    let b = F::<T>::from_f64(settings.b);
5376                    inv_jac /= (&e_cm * &b + &radius).powi(2) / &e_cm / &b;
5377                    &radius / (&e_cm * &b + &radius)
5378                }
5379            };
5380
5381            xs.push(radial_x);
5382            let mut remaining_fraction = one.clone();
5383            let mut stick_jac = one.clone();
5384            for (i, radius_i) in radii.iter().enumerate().take(moms.len() - 1) {
5385                let fraction = radius_i / &radius;
5386                xs.push(&fraction / &remaining_fraction);
5387                stick_jac *= &remaining_fraction;
5388                remaining_fraction -= fraction;
5389                if remaining_fraction.is_zero() && i + 2 < moms.len() {
5390                    return (vec![zero.clone(); 3 * moms.len()], zero);
5391                }
5392            }
5393
5394            inv_jac /= radius.pow((moms.len() - 1) as u64) * stick_jac;
5395            for radius_sq in &radii_sq {
5396                inv_jac /= radius_sq;
5397            }
5398
5399            for (mom, radius_i) in moms.iter().zip(radii.iter()) {
5400                xs.push(phi_x(&mom.px, &mom.py));
5401                inv_jac /= zero.from_i64(2) * zero.PI();
5402                xs.push((&one / one.from_i64(2)) * (&one + &mom.pz / radius_i));
5403                inv_jac /= zero.from_i64(2);
5404            }
5405
5406            (xs, inv_jac)
5407        }
5408        ParameterizationMode::SphericalProductCommonRadial => {
5409            if moms.len() != 2 {
5410                panic!(
5411                    "spherical_product_common_radial inverse parameterization currently requires exactly two loop three-momenta"
5412                );
5413            }
5414            let spherical_settings = ParameterizationSettings {
5415                mode: ParameterizationMode::Spherical,
5416                mapping: settings.mapping.clone(),
5417                b: settings.b,
5418                power: settings.power,
5419                lmb_basis_ids: Default::default(),
5420                sampling_channels: Default::default(),
5421            };
5422            let common_radial_settings = ParameterizationSettings {
5423                mode: ParameterizationMode::SphericalCommonRadial,
5424                mapping: settings.mapping.clone(),
5425                b: settings.b,
5426                power: settings.power,
5427                lmb_basis_ids: Default::default(),
5428                sampling_channels: Default::default(),
5429            };
5430            let (mut xs, product_inv_jac) =
5431                global_inv_parameterize(moms, e_cm.clone(), &spherical_settings);
5432            let (_, common_inv_jac) = global_inv_parameterize(moms, e_cm, &common_radial_settings);
5433            if let Some(first_x) = xs.first_mut() {
5434                *first_x = &*first_x / zero.from_i64(2);
5435            }
5436            (xs, product_inv_jac + common_inv_jac)
5437        }
5438        ParameterizationMode::MomentumSpace => (
5439            moms.iter()
5440                .flat_map(|mom| [mom.px.clone(), mom.py.clone(), mom.pz.clone()])
5441                .collect(),
5442            one,
5443        ),
5444    }
5445}
5446
5447/// Map a vector in the unit hypercube to the infinite hypercube.
5448/// Also compute the Jacobian.
5449pub(crate) fn parameterize3d<T: FloatLike>(
5450    x: &[F<T>],
5451    e_cm: F<T>,
5452    settings: &ParameterizationSettings,
5453) -> ([F<T>; 3], F<T>) {
5454    let zero = e_cm.zero();
5455    let one = zero.one();
5456    let mut l_space = [zero.clone(), zero.clone(), zero.clone()];
5457    let mut jac = one.clone();
5458
5459    match settings.mode {
5460        ParameterizationMode::Cartesian => match settings.mapping {
5461            ParameterizationMapping::Log => {
5462                for i in 0..3 {
5463                    let x = x[i].clone();
5464                    l_space[i] = &e_cm * (&x / (&one - &x)).log();
5465                    jac *= &e_cm / (&x - &x * &x);
5466                }
5467            }
5468            ParameterizationMapping::Linear => {
5469                for i in 0..3 {
5470                    let x = x[i].clone();
5471                    l_space[i] = &e_cm * (&one / (&one - &x) - &one / &x);
5472                    jac *= &e_cm * (&one / (&x * &x) + &one / ((&one - &x) * (&one - &x)));
5473                }
5474            }
5475            ParameterizationMapping::Power => {
5476                panic!("Power radial mapping is only supported for spherical coordinates");
5477            }
5478        },
5479        ParameterizationMode::Spherical => {
5480            let radius = match settings.mapping {
5481                ParameterizationMapping::Log => {
5482                    // r = &e_cm * ln(1 + b*&x/(1-&x))
5483                    let x = x[0].clone();
5484                    let b = F::<T>::from_f64(settings.b);
5485                    let radius = &e_cm * (&one + &b * &x / (&one - &x)).log();
5486                    jac *= &e_cm * &b / (&one - &x) / (&one + &x * (&b - &one));
5487
5488                    radius
5489                }
5490                ParameterizationMapping::Power => {
5491                    // r = e_cm * b * (x/(1-x))^p; p=1 reproduces the linear map.
5492                    let x = x[0].clone();
5493                    let b = F::<T>::from_f64(settings.b);
5494                    let power = F::<T>::from_f64(settings.power);
5495                    let odds = &x / (&one - &x);
5496                    let power_minus_one = &power - &one;
5497                    let radius = &e_cm * &b * odds.powf(&power);
5498                    jac *= &e_cm * &b * &power * odds.powf(&power_minus_one) / (&one - &x).square();
5499
5500                    radius
5501                }
5502                ParameterizationMapping::Linear => {
5503                    // r = &e_cm * b * x/(1-x)
5504                    let b = F::<T>::from_f64(settings.b);
5505                    let radius = &e_cm * &b * &x[0] / (&one - &x[0]);
5506                    jac *= (&e_cm * &b + &radius).powi(2) / &e_cm / &b;
5507                    radius
5508                }
5509            };
5510            let phi = zero.from_i64(2) * zero.PI() * &x[1];
5511            jac *= zero.from_i64(2) * zero.PI();
5512
5513            let cos_theta = -&one + zero.from_i64(2) * &x[2]; // out of range
5514            jac *= zero.from_i64(2);
5515            let sin_theta = (&one - cos_theta.square()).sqrt();
5516
5517            l_space[0] = &radius * &sin_theta * phi.cos();
5518            l_space[1] = &radius * &sin_theta * phi.sin();
5519            l_space[2] = &radius * &cos_theta;
5520
5521            jac *= radius.square(); // spherical coord
5522        }
5523        _ => {
5524            panic!(
5525                "Inappropriate parameterization mapping specified for parameterize: {:?}.",
5526                settings.mode.clone()
5527            );
5528        }
5529    }
5530
5531    (l_space, jac)
5532}
5533
5534pub(crate) fn inv_parametrize3d<T: FloatLike>(
5535    mom: &ThreeMomentum<F<T>>,
5536    e_cm: F<T>,
5537    settings: &ParameterizationSettings,
5538) -> ([F<T>; 3], F<T>) {
5539    let one = e_cm.one();
5540    let zero = one.zero();
5541    if settings.mode == ParameterizationMode::Cartesian {
5542        let two = one.from_i64(2);
5543        let mut coordinates = [zero.clone(), zero.clone(), zero.clone()];
5544        let mut jac = one.clone();
5545        for (coordinate, momentum) in coordinates.iter_mut().zip([&mom.px, &mom.py, &mom.pz]) {
5546            let scaled = momentum / &e_cm;
5547            let magnitude = scaled.abs();
5548            // Invert the negative half first to avoid overflow or cancellation in the tails.
5549            let lower = match settings.mapping {
5550                ParameterizationMapping::Log => {
5551                    let exponential = (-magnitude).exp();
5552                    &exponential / (&one + &exponential)
5553                }
5554                ParameterizationMapping::Linear => {
5555                    if magnitude > one {
5556                        let reciprocal = &one / &magnitude;
5557                        let twice_reciprocal = &two * reciprocal;
5558                        &twice_reciprocal
5559                            / ((&one + twice_reciprocal.square()).sqrt() + &one + &twice_reciprocal)
5560                    } else {
5561                        &two / ((magnitude.square() + two.square()).sqrt() + magnitude + &two)
5562                    }
5563                }
5564                ParameterizationMapping::Power => {
5565                    panic!("Power radial mapping is only supported for spherical coordinates");
5566                }
5567            };
5568            let upper = &one - &lower;
5569            jac *= match settings.mapping {
5570                ParameterizationMapping::Log => &lower * &upper / &e_cm,
5571                ParameterizationMapping::Linear => {
5572                    lower.square() * upper.square() / (&e_cm * (lower.square() + upper.square()))
5573                }
5574                ParameterizationMapping::Power => unreachable!(),
5575            };
5576            *coordinate = if scaled < zero { lower } else { upper };
5577        }
5578        return (coordinates, jac);
5579    }
5580    if settings.mode != ParameterizationMode::Spherical {
5581        panic!("Inverse mapping requires cartesian or spherical coordinates");
5582    }
5583
5584    let mut jac = one.clone();
5585
5586    let x = &mom.px;
5587    let y = &mom.py;
5588    let z = &mom.pz;
5589
5590    let k_r_sq = x.square() + y.square() + z.square();
5591    let k_r = k_r_sq.sqrt();
5592
5593    let x2 = if y < &zero {
5594        &one + (&one / one.from_i64(2)) * zero.FRAC_1_PI() * y.atan2(x)
5595    } else {
5596        (&one / one.from_i64(2)) * zero.FRAC_1_PI() * y.atan2(x)
5597    };
5598
5599    // cover the degenerate case
5600    if k_r_sq.is_zero() {
5601        return ([zero.clone(), x2.clone(), zero.clone()], zero.clone());
5602    }
5603
5604    let x1 = match settings.mapping {
5605        ParameterizationMapping::Log => {
5606            let b = F::<T>::from_f64(settings.b);
5607            let x1 = &one - &b / (-&one + &b + (&k_r / &e_cm).exp());
5608            jac /= &e_cm * &b / (&one - &x1) / (&one + &x1 * (&b - &one));
5609            x1
5610        }
5611        ParameterizationMapping::Power => {
5612            let b = F::<T>::from_f64(settings.b);
5613            let power = F::<T>::from_f64(settings.power);
5614            let inv_power = &one / &power;
5615            let odds = (&k_r / (&e_cm * &b)).powf(&inv_power);
5616            let x1 = &odds / (&one + &odds);
5617            let power_minus_one = &power - &one;
5618            jac /= &e_cm * &b * &power * odds.powf(&power_minus_one) / (&one - &x1).square();
5619            x1
5620        }
5621        ParameterizationMapping::Linear => {
5622            let b = F::<T>::from_f64(settings.b);
5623            jac /= (&e_cm * &b + &k_r).powi(2) / &e_cm / &b;
5624            &k_r / (&e_cm * &b + &k_r)
5625        }
5626    };
5627
5628    let x3 = (&one / one.from_i64(2)) * (&one + z / &k_r);
5629    jac /= zero.from_i64(2) * zero.PI();
5630    jac /= zero.from_i64(2);
5631    jac /= k_r.square();
5632
5633    let x = [x1, x2, x3];
5634
5635    (x, jac)
5636}
5637
5638pub const MINUTE: usize = 60;
5639pub const HOUR: usize = 3_600;
5640pub const DAY: usize = 86_400;
5641pub const WEEK: usize = 604_800;
5642pub(crate) fn format_wdhms(seconds: usize) -> String {
5643    let mut compound_duration = vec![];
5644    if seconds == 0 {
5645        compound_duration.push("0s".to_string());
5646        return compound_duration.join(" ");
5647    }
5648
5649    let mut sec = seconds % WEEK;
5650    // weeks
5651    let ws = seconds / WEEK;
5652    if ws != 0 {
5653        compound_duration.push(format!("{ws}w"));
5654    }
5655
5656    // days
5657    let ds = sec / DAY;
5658    sec %= DAY;
5659    if ds != 0 {
5660        compound_duration.push(format!("{ds}d"));
5661    }
5662
5663    // hours
5664    let hs = sec / HOUR;
5665    sec %= HOUR;
5666    if hs != 0 {
5667        compound_duration.push(format!("{hs}h"));
5668    }
5669
5670    // minutes
5671    let ms = sec / MINUTE;
5672    sec %= MINUTE;
5673    if ms != 0 {
5674        compound_duration.push(format!("{ms}m"));
5675    }
5676
5677    // seconds
5678    if sec != 0 {
5679        compound_duration.push(format!("{sec}s"));
5680    }
5681
5682    compound_duration.join(" ")
5683}
5684
5685#[allow(unused)]
5686pub(crate) fn inv_3x3_sig_matrix(mat: [[isize; 3]; 3]) -> [[isize; 3]; 3] {
5687    let denom = -mat[0][2] * mat[1][1] * mat[2][0]
5688        + mat[0][1] * mat[1][2] * mat[2][0]
5689        + mat[0][2] * mat[1][0] * mat[2][1]
5690        - mat[0][0] * mat[1][2] * mat[2][1]
5691        - mat[0][1] * mat[1][0] * mat[2][2]
5692        + mat[0][0] * mat[1][1] * mat[2][2];
5693    if denom != 1 && denom != -1 {
5694        panic!("Non invertible signature matrix.");
5695    }
5696    let mut inv_mat = [[0; 3]; 3];
5697    inv_mat[0][0] = (-mat[1][2] * mat[2][1] + mat[1][1] * mat[2][2]) * denom;
5698    inv_mat[0][1] = (mat[0][2] * mat[2][1] - mat[0][1] * mat[2][2]) * denom;
5699    inv_mat[0][2] = (-mat[0][2] * mat[1][1] + mat[0][1] * mat[1][2]) * denom;
5700    inv_mat[1][0] = (mat[1][2] * mat[2][0] - mat[1][0] * mat[2][2]) * denom;
5701    inv_mat[1][1] = (-mat[0][2] * mat[2][0] + mat[0][0] * mat[2][2]) * denom;
5702    inv_mat[1][2] = (mat[0][2] * mat[1][0] - mat[0][0] * mat[1][2]) * denom;
5703    inv_mat[2][0] = (-mat[1][1] * mat[2][0] + mat[1][0] * mat[2][1]) * denom;
5704    inv_mat[2][1] = (mat[0][1] * mat[2][0] - mat[0][0] * mat[2][1]) * denom;
5705    inv_mat[2][2] = (-mat[0][1] * mat[1][0] + mat[0][0] * mat[1][1]) * denom;
5706
5707    inv_mat
5708}
5709
5710pub mod index_vec;
5711
5712#[allow(unused)]
5713pub(crate) fn format_for_compare_digits(x: F<f64>, y: F<f64>) -> (String, String) {
5714    let mut string_x = format!("{:.16e}", x);
5715    let mut string_y = format!("{:.16e}", y);
5716
5717    #[allow(clippy::comparison_chain)]
5718    if string_x.len() > string_y.len() {
5719        for _ in 0..(string_x.len() - string_y.len()) {
5720            string_y.push(' ');
5721        }
5722    } else if string_y.len() > string_x.len() {
5723        for _ in 0..(string_y.len() - string_x.len()) {
5724            string_x.push(' ');
5725        }
5726    }
5727
5728    let string_vec = string_x
5729        .chars()
5730        .zip(string_y.chars())
5731        .map(|(char_x, char_y)| {
5732            if char_x == char_y {
5733                (char_x.to_string().green(), char_y.to_string().green())
5734            } else {
5735                (char_x.to_string().red(), char_y.to_string().red())
5736            }
5737        })
5738        .collect_vec();
5739
5740    let string_x = string_vec.iter().map(|(x, _)| x).join("");
5741    let string_y = string_vec.iter().map(|(_, y)| y).join("");
5742
5743    (string_x, string_y)
5744}
5745
5746#[allow(unused)]
5747pub(crate) fn format_evaluation_time(time: Duration) -> String {
5748    let seconds = time.as_secs_f64();
5749    let (value, unit) = if seconds >= 1.0 {
5750        (seconds, "s")
5751    } else if seconds >= 1.0e-3 {
5752        (seconds * 1.0e3, "ms")
5753    } else {
5754        (seconds * 1.0e6, "µs")
5755    };
5756
5757    let precision = if value >= 100.0 {
5758        0
5759    } else if value >= 10.0 {
5760        1
5761    } else {
5762        2
5763    };
5764
5765    format!("{value:.precision$} {unit}")
5766}
5767
5768pub(crate) fn duration_from_secs_f64_saturating(time: f64) -> Duration {
5769    if time.is_nan() || time <= 0.0 {
5770        return Duration::ZERO;
5771    }
5772
5773    if time.is_infinite() {
5774        return Duration::MAX;
5775    }
5776
5777    let max_seconds = Duration::MAX.as_secs();
5778    if time >= max_seconds as f64 {
5779        return Duration::MAX;
5780    }
5781
5782    let seconds = time.trunc() as u64;
5783    let fractional = (time - seconds as f64).clamp(0.0, 0.999_999_999_999);
5784    let nanos = (fractional * 1_000_000_000.0) as u32;
5785    Duration::new(seconds, nanos)
5786}
5787
5788pub(crate) fn format_evaluation_time_from_f64(time: f64) -> String {
5789    format_evaluation_time(duration_from_secs_f64_saturating(time))
5790}
5791
5792pub(crate) fn normalize_tabled_separator_rows(rendered: &str) -> String {
5793    let original_lines = rendered.lines().collect_vec();
5794    let visible_lines = original_lines
5795        .iter()
5796        .map(|line| strip_ansi_escape_codes(line).chars().collect_vec())
5797        .collect_vec();
5798
5799    original_lines
5800        .iter()
5801        .enumerate()
5802        .map(|(row_index, line)| {
5803            let visible_line = &visible_lines[row_index];
5804            if is_top_border_row(visible_line) {
5805                return rebuild_top_border_row(&visible_lines, row_index);
5806            }
5807
5808            if is_internal_separator_row(visible_line) {
5809                return rebuild_internal_separator_row(&visible_lines, row_index);
5810            }
5811
5812            if is_bottom_border_row(visible_line) {
5813                return rebuild_bottom_border_row(&visible_lines, row_index);
5814            }
5815
5816            (*line).to_string()
5817        })
5818        .join("\n")
5819}
5820
5821fn rebuild_top_border_row(visible_lines: &[Vec<char>], row_index: usize) -> String {
5822    rebuild_border_row(visible_lines, row_index, '╭', '╮', |_, _, has_below| {
5823        if has_below { '┬' } else { '─' }
5824    })
5825}
5826
5827fn rebuild_internal_separator_row(visible_lines: &[Vec<char>], row_index: usize) -> String {
5828    rebuild_border_row(
5829        visible_lines,
5830        row_index,
5831        '├',
5832        '┤',
5833        |row_index, column, has_below| match (
5834            row_index > 0 && has_vertical_border(&visible_lines[row_index - 1], column),
5835            has_below,
5836        ) {
5837            (false, false) => '─',
5838            (false, true) => '┬',
5839            (true, false) => '┴',
5840            (true, true) => '┼',
5841        },
5842    )
5843}
5844
5845fn rebuild_bottom_border_row(visible_lines: &[Vec<char>], row_index: usize) -> String {
5846    rebuild_border_row(
5847        visible_lines,
5848        row_index,
5849        '╰',
5850        '╯',
5851        |row_index, column, _| {
5852            if row_index > 0 && has_vertical_border(&visible_lines[row_index - 1], column) {
5853                '┴'
5854            } else {
5855                '─'
5856            }
5857        },
5858    )
5859}
5860
5861fn rebuild_border_row<F>(
5862    visible_lines: &[Vec<char>],
5863    row_index: usize,
5864    left: char,
5865    right: char,
5866    mut intersection_for_column: F,
5867) -> String
5868where
5869    F: FnMut(usize, usize, bool) -> char,
5870{
5871    let border = &visible_lines[row_index];
5872    if border.len() < 2 {
5873        return border.iter().collect();
5874    }
5875
5876    let last = border.len() - 1;
5877    let mut rebuilt = String::with_capacity(border.len());
5878    rebuilt.push(left);
5879
5880    for column in 1..last {
5881        let has_vertical_below = row_index + 1 < visible_lines.len()
5882            && has_vertical_border(&visible_lines[row_index + 1], column);
5883        rebuilt.push(intersection_for_column(
5884            row_index,
5885            column,
5886            has_vertical_below,
5887        ));
5888    }
5889
5890    rebuilt.push(right);
5891    rebuilt
5892}
5893
5894fn has_vertical_border(line: &[char], column: usize) -> bool {
5895    line.get(column)
5896        .copied()
5897        .is_some_and(|ch| matches!(ch, '│' | '├' | '┤' | '┬' | '┴' | '┼'))
5898}
5899
5900fn is_internal_separator_row(line: &[char]) -> bool {
5901    matches!(line.first(), Some('├')) && matches!(line.last(), Some('┤'))
5902}
5903
5904fn is_top_border_row(line: &[char]) -> bool {
5905    matches!(line.first(), Some('╭')) && matches!(line.last(), Some('╮'))
5906}
5907
5908fn is_bottom_border_row(line: &[char]) -> bool {
5909    matches!(line.first(), Some('╰')) && matches!(line.last(), Some('╯'))
5910}
5911
5912fn strip_ansi_escape_codes(line: &str) -> String {
5913    let mut stripped = String::with_capacity(line.len());
5914    let mut chars = line.chars().peekable();
5915
5916    while let Some(ch) = chars.next() {
5917        if ch == '\u{1b}' && chars.peek() == Some(&'[') {
5918            chars.next();
5919            for code in chars.by_ref() {
5920                if ('@'..='~').contains(&code) {
5921                    break;
5922                }
5923            }
5924            continue;
5925        }
5926
5927        stripped.push(ch);
5928    }
5929
5930    stripped
5931}
5932
5933pub(crate) fn into_complex_ff64<T: FloatLike>(c: &Complex<F<T>>) -> Complex<F<f64>> {
5934    Complex::new(c.re.into_ff64(), c.im.into_ff64())
5935}
5936
5937#[test]
5938fn exact_binary_cube_promotion_preserves_original_value_and_settings_policy() {
5939    fn check<T: FloatLike>() {
5940        let one = F::<T>::from_f64(1.0);
5941        let exact = F(T::from_f64_exact_binary(0.1));
5942        let expected = one.from_i64(3602879701896397) / one.from_i64(2).powi(55);
5943        assert_eq!(exact, expected);
5944        assert_eq!(exact.into_f64().to_bits(), 0.1_f64.to_bits());
5945        if one.epsilon() < F::<T>::from_f64(f64::EPSILON) {
5946            let settings_value = F::<T>::from_f64(0.1);
5947            assert!(exact > settings_value);
5948            assert!((settings_value - &one / one.from_i64(10)).abs() <= one.epsilon());
5949        }
5950    }
5951    check::<f64>();
5952    check::<QuadFloat>();
5953    check::<ArbPrec>();
5954}
5955
5956#[test]
5957fn decimal_promotion_cache_preserves_parsing_and_precision() {
5958    // Include non-binary decimals, signed zero, subnormals and overflow-range
5959    // exponents. Repeat after more unique inputs than the cache can retain.
5960    let mut inputs = vec![
5961        0.0,
5962        -0.0,
5963        0.1,
5964        -0.3,
5965        1.0,
5966        0.5,
5967        f64::MIN_POSITIVE,
5968        f64::from_bits(1),
5969        f64::MAX,
5970        -f64::MAX,
5971        f64::INFINITY,
5972        f64::NEG_INFINITY,
5973        f64::NAN,
5974    ];
5975    inputs.extend((0..1200).map(|i| f64::from_bits(0x3fb999999999999a + i)));
5976    for _ in 0..2 {
5977        for &input in &inputs {
5978            let expected: QuadFloat = if input.is_finite() {
5979                SymbolicaFloat::parse(
5980                    &input.to_string(),
5981                    Some(DoubleFloat::default().get_precision()),
5982                )
5983                .unwrap()
5984                .into()
5985            } else {
5986                QuadFloat::from_f64_exact_binary(input)
5987            };
5988            // Hit the cache as well as populating it. Conversion back to f64
5989            // additionally checks the sign of zero and non-finite handling.
5990            for _ in 0..2 {
5991                let actual = QuadFloat::from_f64_decimal(input);
5992                if input.is_nan() {
5993                    assert!(F(actual).is_nan());
5994                } else {
5995                    assert_eq!(actual, expected);
5996                    assert_eq!(
5997                        F(actual).into_f64().to_bits(),
5998                        F(expected).into_f64().to_bits()
5999                    );
6000                }
6001            }
6002            // Interleave precisions on one thread; the numeric spelling alone
6003            // must never let a lower-precision result satisfy a higher request.
6004            for precision in [256, 1000, 256, 1000] {
6005                let actual = match precision {
6006                    256 => VarFloat::<256>::from_f64_decimal(input).float,
6007                    1000 => VarFloat::<1000>::from_f64_decimal(input).float,
6008                    _ => unreachable!(),
6009                };
6010                let expected = if input.is_finite() {
6011                    Float::with_val(precision, Float::parse(input.to_string()).unwrap())
6012                } else {
6013                    Float::with_val(precision, input)
6014                };
6015                assert_eq!(actual.prec(), precision);
6016                if input.is_nan() {
6017                    assert!(actual.is_nan());
6018                } else {
6019                    assert_eq!(actual, expected);
6020                    assert_eq!(actual.is_sign_negative(), expected.is_sign_negative());
6021                }
6022            }
6023        }
6024    }
6025}
6026
6027#[test]
6028fn complex_compare() {
6029    let ltd = Complex::new(0.11773583919739394, -0.22157450463964778).map(F);
6030
6031    let cff = Complex::new(0.11773583589023458, -0.22157450446824836).map(F);
6032
6033    ltd.approx_eq_res(&cff, &F(0.00000001)).unwrap();
6034}
6035
6036#[cfg(test)]
6037mod formatting_tests {
6038    use super::{ArbPrec, F, FloatLike, f128};
6039
6040    fn assert_has_scientific_exponent(rendered: &str) {
6041        let (mantissa, exponent) = rendered
6042            .split_once('e')
6043            .unwrap_or_else(|| panic!("missing exponent marker in: {rendered}"));
6044        assert!(
6045            !mantissa.is_empty(),
6046            "missing mantissa in scientific output: {rendered}"
6047        );
6048        assert!(
6049            exponent.parse::<i32>().is_ok(),
6050            "invalid exponent in scientific output: {rendered}"
6051        );
6052    }
6053
6054    fn assert_fractional_digits(rendered: &str, expected_digits: usize) {
6055        let (mantissa, _) = rendered
6056            .split_once('e')
6057            .unwrap_or_else(|| panic!("missing exponent marker in: {rendered}"));
6058        let (_, fractional) = mantissa
6059            .trim_start_matches(['+', '-'])
6060            .split_once('.')
6061            .unwrap_or_else(|| panic!("missing decimal point in mantissa: {rendered}"));
6062        assert_eq!(
6063            fractional.len(),
6064            expected_digits,
6065            "unexpected number of fractional digits in: {rendered}"
6066        );
6067    }
6068
6069    fn assert_scientific_formatting_for_backend<T: FloatLike>(x: F<T>) {
6070        let plain = format!("{:e}", x.clone());
6071        assert_has_scientific_exponent(&plain);
6072
6073        let plus = format!("{:+e}", x.clone());
6074        assert_has_scientific_exponent(&plus);
6075        assert!(plus.starts_with('+') || plus.starts_with('-'));
6076
6077        let precision = format!("{:+.16e}", x.clone());
6078        assert_has_scientific_exponent(&precision);
6079        assert!(
6080            precision.contains('.'),
6081            "missing decimal point in scientific output: {precision}"
6082        );
6083
6084        let padded = format!("{:>24.6e}", x);
6085        assert!(
6086            padded.len() >= 24,
6087            "formatted width should be at least requested width: {padded}"
6088        );
6089        assert_has_scientific_exponent(padded.trim_start());
6090    }
6091
6092    #[test]
6093    fn display_matches_underlying_f64() {
6094        let value = F(12.5f64);
6095        assert_eq!(format!("{}", value), "12.5");
6096    }
6097
6098    #[test]
6099    fn lower_exp_keeps_exponent_with_precision() {
6100        let rendered = format!("{:+.16e}", F(1.23456789e-8f64));
6101        assert_has_scientific_exponent(&rendered);
6102        assert_fractional_digits(&rendered, 16);
6103    }
6104
6105    #[test]
6106    fn lower_exp_width_and_alignment_behave_as_expected() {
6107        let rendered = format!("{:>20.4e}", F(12.345f64));
6108        assert_eq!(rendered.len(), 20);
6109        assert_has_scientific_exponent(rendered.trim_start());
6110
6111        let left_aligned = format!("{:<20.4e}", F(12.345f64));
6112        assert_eq!(left_aligned.len(), 20);
6113        assert_has_scientific_exponent(left_aligned.trim_end());
6114    }
6115
6116    #[test]
6117    fn lower_exp_sign_and_zero_pad_behave_as_expected() {
6118        let positive = format!("{:+020.4e}", F(12.345f64));
6119        assert_eq!(positive.len(), 20);
6120        assert!(positive.starts_with('+'));
6121        assert_has_scientific_exponent(&positive);
6122
6123        let negative = format!("{:+020.4e}", F(-12.345f64));
6124        assert_eq!(negative.len(), 20);
6125        assert!(negative.starts_with('-'));
6126        assert_has_scientific_exponent(&negative);
6127    }
6128
6129    #[test]
6130    fn lower_exp_precision_controls_fractional_digits() {
6131        let p2 = format!("{:.2e}", F(1.0f64 / 3.0f64));
6132        assert_fractional_digits(&p2, 2);
6133
6134        let p9 = format!("{:.9e}", F(1.0f64 / 3.0f64));
6135        assert_fractional_digits(&p9, 9);
6136    }
6137
6138    #[test]
6139    fn lower_exp_works_across_float_backends() {
6140        assert_scientific_formatting_for_backend(F::<f64>::from_f64(1.23456789e-8));
6141        assert_scientific_formatting_for_backend(F::<f128>::from_f64(1.23456789e-8));
6142        assert_scientific_formatting_for_backend(F::<ArbPrec>::from_f64(1.23456789e-8));
6143    }
6144
6145    #[test]
6146    fn quad_square_matches_multiplication() {
6147        let zero = F::<f128>::from_f64(0.0);
6148        let zero_sq = zero.square();
6149        assert!(!zero_sq.is_nan());
6150        assert!(!zero_sq.is_infinite());
6151        assert_eq!(zero_sq, zero);
6152
6153        let x = F::<f128>::from_f64(500.0);
6154        let x_sq = x.square();
6155        assert!(!x_sq.is_nan());
6156        assert!(!x_sq.is_infinite());
6157        assert_eq!(x_sq, x * x);
6158        assert_eq!(x_sq.sqrt(), x);
6159    }
6160}
6161
6162pub mod symbols;
6163pub use symbols::{GS, W_};
6164
6165type TensorLibStore = RwLock<TensorLibrary<ParamTensor<ExplicitKey<Aind>>, Aind>>;
6166type FunLibStore = SymbolLib<ParamTensor<ShadowedStructure<Aind>>, Wrap>;
6167
6168pub static TENSORLIB: LazyLock<TensorLibStore> = LazyLock::new(|| RwLock::new(hep_lib_atom()));
6169
6170pub static FUN_LIB: LazyLock<FunLibStore> = LazyLock::new(|| {
6171    let mut lib = Wrap::new_lib();
6172    lib.insert(INBUILTS.conj, |a: ParamTensor<ShadowedStructure<Aind>>| {
6173        a.map_data_self(|x| x.conj())
6174    });
6175    lib
6176});
6177
6178pub static PARAM_FUN_LIB: LazyLock<SymbolLib<ParamTensor<ShadowedStructure<Aind>>, Panic>> =
6179    LazyLock::new(|| {
6180        let mut lib = Panic::new_lib();
6181        lib.insert(INBUILTS.conj, |a: ParamTensor<ShadowedStructure<Aind>>| {
6182            a.map_data_self(|x| x.conj())
6183        });
6184        lib
6185    });
6186
6187pub static VAKINT: OnceLock<Result<Vakint>> = OnceLock::new();
6188
6189pub fn init_vakint() -> Result<()> {
6190    let r: &Result<Vakint, eyre::Report> =
6191        VAKINT.get_or_init(|| Vakint::new().map_err(|e| eyre!(e.to_string())));
6192
6193    match r {
6194        Ok(_) => Ok(()),
6195        Err(e) => Err(eyre!(e.to_string())),
6196    }
6197}
6198
6199pub fn vakint() -> Result<&'static Vakint> {
6200    let r = VAKINT
6201        .get()
6202        .ok_or_else(|| eyre!("Vakint not initialised"))?;
6203    match r {
6204        Ok(v) => Ok(v),
6205        Err(e) => Err(eyre!(e.to_string())),
6206    }
6207}
6208
6209impl<T: FloatLike> momtrop::float::MomTropFloat for F<T> {
6210    #[inline]
6211    fn PI(&self) -> Self {
6212        self.PI()
6213    }
6214
6215    #[inline]
6216    fn abs(&self) -> Self {
6217        self.abs()
6218    }
6219
6220    #[inline]
6221    fn cos(&self) -> Self {
6222        <F<T> as Real>::cos(self)
6223    }
6224
6225    #[inline]
6226    fn exp(&self) -> Self {
6227        <F<T> as Real>::exp(self)
6228    }
6229
6230    #[inline]
6231    fn one(&self) -> Self {
6232        <F<T> as SymFloatLike>::one(self)
6233    }
6234
6235    #[inline]
6236    fn from_f64(&self, value: f64) -> Self {
6237        F::from_f64(value)
6238    }
6239
6240    #[inline]
6241    fn from_isize(&self, value: isize) -> Self {
6242        Self(self.0.from_i64(value as i64))
6243    }
6244
6245    #[inline]
6246    fn inv(&self) -> Self {
6247        <F<T> as SymFloatLike>::inv(self)
6248    }
6249
6250    #[inline]
6251    fn ln(&self) -> Self {
6252        <F<T> as Real>::log(self)
6253    }
6254
6255    #[inline]
6256    fn powf(&self, power: &Self) -> Self {
6257        <F<T> as Real>::powf(self, power)
6258    }
6259
6260    #[inline]
6261    fn sin(&self) -> Self {
6262        <F<T> as Real>::sin(self)
6263    }
6264
6265    #[inline]
6266    fn sqrt(&self) -> Self {
6267        <F<T> as Real>::sqrt(self)
6268    }
6269
6270    #[inline]
6271    fn zero(&self) -> Self {
6272        <F<T> as SymFloatLike>::zero(self)
6273    }
6274
6275    #[inline]
6276    fn to_f64(&self) -> f64 {
6277        self.into_f64()
6278    }
6279}
6280
6281pub trait Length {
6282    fn len(&self) -> usize;
6283    fn is_empty(&self) -> bool {
6284        self.len() == 0
6285    }
6286}
6287
6288impl<I, T> Length for TiVec<I, T> {
6289    fn len(&self) -> usize {
6290        self.len()
6291    }
6292
6293    fn is_empty(&self) -> bool {
6294        self.is_empty()
6295    }
6296}
6297
6298impl<T> Length for Vec<T> {
6299    fn len(&self) -> usize {
6300        self.len()
6301    }
6302}
6303
6304pub fn ose_atom_from_index(index: EdgeIndex) -> Atom {
6305    function!(
6306        GS.ose,
6307        usize::from(index) as i64 // Atom::from(FlatIndex::from(0))
6308    )
6309}
6310
6311pub(crate) fn cut_energy(index: EdgeIndex) -> Atom {
6312    function!(GS.energy, usize::from(index) as i64)
6313}
6314
6315pub fn external_energy_atom_from_index(index: EdgeIndex) -> Atom {
6316    GS.emr_mom(index, Atom::from(ExpandedIndex::from_iter([0])))
6317}
6318
6319pub mod newton_solver;
6320use include_dir::{Dir, include_dir};
6321static BUILTIN_MODELS: Dir = include_dir!("$CARGO_MANIFEST_DIR/../../assets/models/json");
6322
6323pub fn load_generic_model(name: &str) -> Model {
6324    if let Some(file) = BUILTIN_MODELS.get_file(format!("{}/{}.json", name, name)) {
6325        Model::from_json(file.contents_utf8().unwrap()).unwrap()
6326    } else {
6327        panic!("Model {} not found in built-in models.", name);
6328    }
6329}
6330
6331#[cfg(test)]
6332pub mod test_utils;
6333
6334#[cfg(feature = "python")]
6335impl<'py> pyo3::IntoPyObject<'py> for F<f64> {
6336    type Target = pyo3::types::PyFloat;
6337    type Output = pyo3::Bound<'py, Self::Target>;
6338    type Error = std::convert::Infallible;
6339
6340    #[inline]
6341    fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
6342        Ok(pyo3::types::PyFloat::new(py, self.0))
6343    }
6344}
6345
6346#[cfg(feature = "python")]
6347impl<'py> pyo3::IntoPyObject<'py> for &F<f64> {
6348    type Target = pyo3::types::PyFloat;
6349    type Output = pyo3::Bound<'py, Self::Target>;
6350    type Error = std::convert::Infallible;
6351
6352    #[inline]
6353    fn into_pyobject(self, py: pyo3::Python<'py>) -> Result<Self::Output, Self::Error> {
6354        (*self).into_pyobject(py)
6355    }
6356}
6357
6358#[cfg(feature = "python")]
6359impl<'a, 'py> pyo3::FromPyObject<'a, 'py> for F<f64> {
6360    type Error = pyo3::PyErr;
6361
6362    fn extract(obj: pyo3::Borrowed<'a, 'py, pyo3::types::PyAny>) -> Result<Self, Self::Error> {
6363        obj.extract::<f64>().map(F)
6364    }
6365}