1use neco_algnum::{AlgnumError, RealAlgebraic};
2use neco_bigint::{BigUint, BigintError, Dyadic, RawRational, ReducedRational};
3use neco_calculus::MAX_PRECISION_BITS;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
6pub enum EncodingFormat {
7 F32,
8}
9
10#[derive(Clone, Copy, Debug, PartialEq)]
11pub struct EncodingBounds {
12 pub format: EncodingFormat,
13 pub round_bound: f64,
14}
15
16#[derive(Clone, Copy, Debug, PartialEq)]
17pub struct EncodingPrecision {
18 enclosure_bits: u32,
19 maximum_round_bound: f64,
20}
21
22impl EncodingPrecision {
23 pub fn new(enclosure_bits: u32, maximum_round_bound: f64) -> Result<Self, EncodingFailure> {
24 if enclosure_bits == 0 || enclosure_bits > MAX_PRECISION_BITS {
25 return Err(EncodingFailure::PrecisionLimitExceeded {
26 requested: enclosure_bits,
27 maximum: MAX_PRECISION_BITS,
28 });
29 }
30 if !maximum_round_bound.is_finite() || maximum_round_bound < 0.0 {
31 return Err(EncodingFailure::InvalidRoundBound {
32 requested: maximum_round_bound,
33 });
34 }
35 Ok(Self {
36 enclosure_bits,
37 maximum_round_bound,
38 })
39 }
40
41 pub fn enclosure_bits(self) -> u32 {
42 self.enclosure_bits
43 }
44 pub fn maximum_round_bound(self) -> f64 {
45 self.maximum_round_bound
46 }
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum EncodingLocation {
51 Coefficient {
52 polynomial: usize,
53 term: usize,
54 },
55 DomainEndpoint {
56 axis: usize,
57 upper: bool,
58 },
59 TrimVertex {
60 hole: Option<usize>,
61 vertex: usize,
62 axis: usize,
63 },
64 SeamEndpoint {
65 endpoint: usize,
66 axis: usize,
67 },
68}
69
70#[derive(Debug, PartialEq)]
71pub enum EncodingFailure {
72 PrecisionLimitExceeded {
73 requested: u32,
74 maximum: u32,
75 },
76 InvalidRoundBound {
77 requested: f64,
78 },
79 Arithmetic {
80 location: EncodingLocation,
81 cause: BigintError,
82 },
83 Algebraic {
84 location: EncodingLocation,
85 cause: AlgnumError,
86 },
87 NonFiniteEncoding {
88 location: EncodingLocation,
89 approximation: f64,
90 },
91 PrecisionShortage {
92 location: EncodingLocation,
93 established: f64,
94 maximum: f64,
95 },
96}
97
98pub(crate) struct ScalarEncoder {
99 precision: EncodingPrecision,
100 round_bound: f64,
101}
102
103impl ScalarEncoder {
104 pub(crate) fn new(precision: EncodingPrecision) -> Self {
105 Self {
106 precision,
107 round_bound: 0.0,
108 }
109 }
110
111 pub(crate) fn bounds(&self) -> EncodingBounds {
112 EncodingBounds {
113 format: EncodingFormat::F32,
114 round_bound: self.round_bound,
115 }
116 }
117 pub(crate) fn rational(
118 &mut self,
119 value: &ReducedRational,
120 location: EncodingLocation,
121 ) -> Result<f32, EncodingFailure> {
122 let arithmetic = |cause| EncodingFailure::Arithmetic { location, cause };
123 let lower = value
124 .dyadic_floor(self.precision.enclosure_bits)
125 .map_err(arithmetic)?;
126 let upper = value
127 .dyadic_ceil(self.precision.enclosure_bits)
128 .map_err(arithmetic)?;
129 self.enclosure(&lower, &upper, location, None)
130 }
131 pub(crate) fn algebraic(
132 &mut self,
133 value: &RealAlgebraic,
134 location: EncodingLocation,
135 ) -> Result<f32, EncodingFailure> {
136 let enclosed = value
137 .enclose(self.precision.enclosure_bits)
138 .map_err(|cause| EncodingFailure::Algebraic { location, cause })?;
139 self.enclosure(
140 enclosed.enclosure().lower(),
141 enclosed.enclosure().upper(),
142 location,
143 Some(value),
144 )
145 }
146 fn enclosure(
147 &mut self,
148 lower: &Dyadic,
149 upper: &Dyadic,
150 location: EncodingLocation,
151 source: Option<&RealAlgebraic>,
152 ) -> Result<f32, EncodingFailure> {
153 let arithmetic = |cause| EncodingFailure::Arithmetic { location, cause };
154 let approximation = lower
155 .midpoint(upper)
156 .map_err(arithmetic)?
157 .round_to_f64_ties_even()
158 .map_err(arithmetic)?;
159 let encoded = approximation as f32;
160 if !encoded.is_finite() {
161 return Err(EncodingFailure::NonFiniteEncoding {
162 location,
163 approximation,
164 });
165 }
166 let represented = Dyadic::from_f64_exact(f64::from(encoded)).map_err(arithmetic)?;
167 let distance = |endpoint: &Dyadic| {
168 if &represented >= endpoint {
169 represented.sub(endpoint)
170 } else {
171 endpoint.sub(&represented)
172 }
173 };
174 let lower_error = distance(lower).map_err(arithmetic)?;
175 let upper_error = distance(upper).map_err(arithmetic)?;
176 let error = core::cmp::max(lower_error, upper_error);
177 let source_matches = match source {
178 Some(source) if !error.is_zero() && lower <= &represented && &represented <= upper => {
179 let denominator = BigUint::one()
180 .map_err(arithmetic)?
181 .shl_bits(represented.exponent() as usize)
182 .map_err(arithmetic)?;
183 let rational = RawRational::new(
184 represented.integer().try_clone().map_err(arithmetic)?,
185 denominator,
186 )
187 .reduce()
188 .map_err(arithmetic)?
189 .into_reduced();
190 let algebraic = |cause| EncodingFailure::Algebraic { location, cause };
191 let candidate =
192 RealAlgebraic::from_reduced_rational(&rational).map_err(algebraic)?;
193 source.compare(&candidate).map_err(algebraic)?.is_eq()
194 }
195 _ => false,
196 };
197 let rounded = error.round_to_f64_ties_even().map_err(arithmetic)?;
198 let established = if error.is_zero() || source_matches {
199 0.0
200 } else {
201 f64::from_bits(rounded.to_bits() + 1)
202 };
203 if !established.is_finite() || established > self.precision.maximum_round_bound {
204 return Err(EncodingFailure::PrecisionShortage {
205 location,
206 established,
207 maximum: self.precision.maximum_round_bound,
208 });
209 }
210 self.round_bound = self.round_bound.max(established);
211 Ok(encoded)
212 }
213}
214#[cfg(test)]
215mod tests {
216 use super::*;
217 use neco_bigint::BigInt;
218
219 fn value(numerator: i32, denominator: u32) -> RealAlgebraic {
220 let rational = RawRational::new(
221 BigInt::try_from(numerator).unwrap(),
222 BigUint::try_from(denominator).unwrap(),
223 )
224 .reduce()
225 .unwrap()
226 .into_reduced();
227 RealAlgebraic::from_reduced_rational(&rational).unwrap()
228 }
229
230 #[test]
231 fn exact_algebraic_candidate_satisfies_zero_round_bound() {
232 let location = EncodingLocation::DomainEndpoint {
233 axis: 0,
234 upper: true,
235 };
236 for (numerator, denominator, expected) in [(-1, 1, -1.0), (1, 1, 1.0), (7, 8, 0.875)] {
237 let mut encoder = ScalarEncoder::new(EncodingPrecision::new(48, 0.0).unwrap());
238 assert_eq!(
239 encoder
240 .algebraic(&value(numerator, denominator), location)
241 .unwrap(),
242 expected
243 );
244 assert_eq!(encoder.bounds().round_bound, 0.0);
245 }
246 }
247
248 #[test]
249 fn non_dyadic_source_keeps_positive_bound_and_precision_shortage() {
250 let source = value(1, 3);
251 let location = EncodingLocation::SeamEndpoint {
252 endpoint: 1,
253 axis: 0,
254 };
255 let mut encoder = ScalarEncoder::new(EncodingPrecision::new(48, 1e-6).unwrap());
256 let encoded = encoder.algebraic(&source, location).unwrap();
257 assert_eq!(encoded, 1.0f32 / 3.0);
258 assert!(encoder.bounds().round_bound > 0.0);
259 let mut exact_only = ScalarEncoder::new(EncodingPrecision::new(48, 0.0).unwrap());
260 assert!(matches!(
261 exact_only.algebraic(&source, location),
262 Err(EncodingFailure::PrecisionShortage { location: observed, maximum: 0.0, .. })
263 if observed == location
264 ));
265 }
266
267 #[test]
268 fn precision_validation_keeps_requested_values() {
269 for requested in [0, MAX_PRECISION_BITS + 1] {
270 assert_eq!(
271 EncodingPrecision::new(requested, 1.0),
272 Err(EncodingFailure::PrecisionLimitExceeded {
273 requested,
274 maximum: MAX_PRECISION_BITS
275 })
276 );
277 }
278 for requested in [-1.0, f64::INFINITY, f64::NAN] {
279 assert!(matches!(
280 EncodingPrecision::new(32, requested),
281 Err(EncodingFailure::InvalidRoundBound { .. })
282 ));
283 }
284 let precision = EncodingPrecision::new(32, 0.0).unwrap();
285 assert_eq!(precision.enclosure_bits(), 32);
286 assert_eq!(precision.maximum_round_bound(), 0.0);
287 }
288}