1use std::borrow::Cow;
21
22use ndarray::{Array, ArrayBase, Data, Dimension};
23use numcodecs::{
24 AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
25 Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
26};
27use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
28use serde::{Deserialize, Deserializer, Serialize, Serializer};
29use thiserror::Error;
30
31#[cfg(test)]
32use ::serde_json as _;
33
34#[derive(Clone, Serialize, Deserialize, JsonSchema)]
35#[schemars(deny_unknown_fields)]
36pub struct BitRoundCodec {
46 #[serde(flatten)]
48 pub mode: BitRoundMode,
49 #[serde(default, rename = "_version")]
51 pub version: StaticCodecVersion<2, 0, 0>,
52}
53
54#[derive(Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
55#[serde(tag = "mode")]
56#[serde(deny_unknown_fields)]
57pub enum BitRoundMode {
59 #[serde(rename = "keepbits")]
61 Keepbits {
62 keepbits: u8,
69 },
70 #[serde(rename = "abs")]
72 AbsoluteError {
73 eb_abs: NonNegative<f64>,
78 },
79 #[serde(rename = "rel")]
81 RelativeError {
82 eb_rel: NonNegative<f64>,
87 },
88}
89
90impl Codec for BitRoundCodec {
91 type Error = BitRoundCodecError;
92
93 fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
94 match data {
95 AnyCowArray::F32(data) => Ok(AnyArray::F32(bit_round(data, &self.mode)?)),
96 AnyCowArray::F64(data) => Ok(AnyArray::F64(bit_round(data, &self.mode)?)),
97 encoded => Err(BitRoundCodecError::UnsupportedDtype(encoded.dtype())),
98 }
99 }
100
101 fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
102 match encoded {
103 AnyCowArray::F32(encoded) => Ok(AnyArray::F32(encoded.into_owned())),
104 AnyCowArray::F64(encoded) => Ok(AnyArray::F64(encoded.into_owned())),
105 encoded => Err(BitRoundCodecError::UnsupportedDtype(encoded.dtype())),
106 }
107 }
108
109 fn decode_into(
110 &self,
111 encoded: AnyArrayView,
112 mut decoded: AnyArrayViewMut,
113 ) -> Result<(), Self::Error> {
114 if !matches!(encoded.dtype(), AnyArrayDType::F32 | AnyArrayDType::F64) {
115 return Err(BitRoundCodecError::UnsupportedDtype(encoded.dtype()));
116 }
117
118 Ok(decoded.assign(&encoded)?)
119 }
120}
121
122impl StaticCodec for BitRoundCodec {
123 const CODEC_ID: &'static str = "bit-round.rs";
124
125 type Config<'de> = Self;
126
127 fn from_config(config: Self::Config<'_>) -> Self {
128 config
129 }
130
131 fn get_config(&self) -> StaticCodecConfig<'_, Self> {
132 StaticCodecConfig::from(self)
133 }
134}
135
136#[derive(Debug, Error)]
137pub enum BitRoundCodecError {
139 #[error("BitRound does not support the dtype {0}")]
141 UnsupportedDtype(AnyArrayDType),
142 #[error("BitRound encode {keepbits} bits exceed the mantissa size for {dtype}")]
144 ExcessiveKeepBits {
145 keepbits: u8,
147 dtype: AnyArrayDType,
149 },
150 #[error("BitRound cannot decode into the provided array")]
152 MismatchedDecodeIntoArray {
153 #[from]
155 source: AnyArrayAssignError,
156 },
157}
158
159#[expect(clippy::derive_partial_eq_without_eq)] #[derive(Copy, Clone, PartialEq, PartialOrd, Hash)]
161pub struct NonNegative<T: Float>(T);
163
164impl Serialize for NonNegative<f64> {
165 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
166 serializer.serialize_f64(self.0)
167 }
168}
169
170impl<'de> Deserialize<'de> for NonNegative<f64> {
171 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
172 let x = f64::deserialize(deserializer)?;
173
174 if x >= 0.0 {
175 Ok(Self(x))
176 } else {
177 Err(serde::de::Error::invalid_value(
178 serde::de::Unexpected::Float(x),
179 &"a non-negative value",
180 ))
181 }
182 }
183}
184
185impl JsonSchema for NonNegative<f64> {
186 fn inline_schema() -> bool {
187 true
188 }
189
190 fn schema_name() -> Cow<'static, str> {
191 Cow::Borrowed("NonNegativeF64")
192 }
193
194 fn schema_id() -> Cow<'static, str> {
195 Cow::Borrowed(concat!(module_path!(), "::", "NonNegative<f64>"))
196 }
197
198 fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
199 json_schema!({
200 "type": "number",
201 "minimum": 0.0
202 })
203 }
204}
205
206pub fn bit_round<T: Float, S: Data<Elem = T>, D: Dimension>(
217 data: ArrayBase<S, D>,
218 mode: &BitRoundMode,
219) -> Result<Array<T, D>, BitRoundCodecError> {
220 let (keepbits, keep_non_normal) = match mode {
221 BitRoundMode::Keepbits { keepbits } => {
222 let keepbits = *keepbits;
223 if u32::from(keepbits) > T::MANITSSA_BITS {
224 return Err(BitRoundCodecError::ExcessiveKeepBits {
225 keepbits,
226 dtype: T::TY,
227 });
228 }
229 (u32::from(keepbits), false)
230 }
231 BitRoundMode::AbsoluteError { eb_abs } => {
232 let eb_abs = T::from_f64(eb_abs.0);
233
234 let mut encoded = data.into_owned();
235
236 encoded.mapv_inplace(|x| {
237 if !x.is_normal() {
240 return x;
241 }
242
243 let keepbits = BitRounder::keepbits_from_eb_rel(NonNegative(eb_abs / x.abs()));
244 let bit_round = BitRounder::new(keepbits);
245
246 bit_round.apply(x)
247 });
248
249 return Ok(encoded);
250 }
251 BitRoundMode::RelativeError { eb_rel } => (BitRounder::keepbits_from_eb_rel(*eb_rel), true),
252 };
253
254 let mut encoded = data.into_owned();
255
256 if keepbits == T::MANITSSA_BITS {
259 return Ok(encoded);
260 }
261
262 let bit_round = BitRounder::new(keepbits);
263
264 encoded.mapv_inplace(|x| {
265 if keep_non_normal && !x.is_normal() {
267 return x;
268 }
269
270 bit_round.apply(x)
271 });
272
273 Ok(encoded)
274}
275
276struct BitRounder<T: Float> {
277 ulp_half: T::Binary,
278 keep_mask: T::Binary,
279 shift: u32,
280}
281
282impl<T: Float> BitRounder<T> {
283 #[inline]
284 fn new(keepbits: u32) -> Self {
285 let ulp_half = T::MANTISSA_MASK >> (keepbits + 1);
287 let keep_mask = !(T::MANTISSA_MASK >> keepbits);
289 let shift = T::MANITSSA_BITS - keepbits;
291
292 Self {
293 ulp_half,
294 keep_mask,
295 shift,
296 }
297 }
298
299 fn keepbits_from_eb_rel(eb_rel: NonNegative<T>) -> u32 {
300 let keepbits = -(eb_rel.0.normal_log2_floor()) - 1;
301 #[expect(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
303 let keepbits = i64::from(keepbits).clamp(0, i64::from(T::MANITSSA_BITS)) as u32;
305 keepbits
306 }
307
308 #[inline]
309 fn apply(&self, x: T) -> T {
310 let mut bits = T::to_binary(x);
311
312 bits += self.ulp_half + ((bits >> self.shift) & T::BINARY_ONE);
314
315 bits &= self.keep_mask;
317
318 T::from_binary(bits)
319 }
320}
321
322pub trait Float: Sized + Copy + std::ops::Div<Self, Output = Self> {
324 const MANITSSA_BITS: u32;
326 const MANTISSA_MASK: Self::Binary;
328 const BINARY_ONE: Self::Binary;
330
331 const TY: AnyArrayDType;
333
334 type Binary: Copy
336 + std::ops::Not<Output = Self::Binary>
337 + std::ops::Shr<u32, Output = Self::Binary>
338 + std::ops::Add<Self::Binary, Output = Self::Binary>
339 + std::ops::AddAssign<Self::Binary>
340 + std::ops::BitAnd<Self::Binary, Output = Self::Binary>
341 + std::ops::BitAndAssign<Self::Binary>;
342
343 fn to_binary(self) -> Self::Binary;
345 fn from_binary(u: Self::Binary) -> Self;
347
348 fn is_normal(self) -> bool;
350
351 fn normal_log2_floor(self) -> i16;
353
354 #[must_use]
356 fn abs(self) -> Self;
357
358 fn from_f64(x: f64) -> Self;
360}
361
362impl Float for f32 {
363 type Binary = u32;
364
365 const BINARY_ONE: Self::Binary = 1;
366 const MANITSSA_BITS: u32 = Self::MANTISSA_DIGITS - 1;
367 const MANTISSA_MASK: Self::Binary = (1 << Self::MANITSSA_BITS) - 1;
368 const TY: AnyArrayDType = AnyArrayDType::F32;
369
370 fn to_binary(self) -> Self::Binary {
371 self.to_bits()
372 }
373
374 fn from_binary(u: Self::Binary) -> Self {
375 Self::from_bits(u)
376 }
377
378 fn is_normal(self) -> bool {
379 self.is_normal()
380 }
381
382 fn normal_log2_floor(self) -> i16 {
383 (((self.to_bits() >> 23) & 0xff) as i16) - 127
384 }
385
386 fn abs(self) -> Self {
387 self.abs()
388 }
389
390 #[expect(clippy::cast_possible_truncation)]
391 fn from_f64(x: f64) -> Self {
392 x as Self
393 }
394}
395
396impl Float for f64 {
397 type Binary = u64;
398
399 const BINARY_ONE: Self::Binary = 1;
400 const MANITSSA_BITS: u32 = Self::MANTISSA_DIGITS - 1;
401 const MANTISSA_MASK: Self::Binary = (1 << Self::MANITSSA_BITS) - 1;
402 const TY: AnyArrayDType = AnyArrayDType::F64;
403
404 fn to_binary(self) -> Self::Binary {
405 self.to_bits()
406 }
407
408 fn from_binary(u: Self::Binary) -> Self {
409 Self::from_bits(u)
410 }
411
412 fn is_normal(self) -> bool {
413 self.is_normal()
414 }
415
416 fn normal_log2_floor(self) -> i16 {
417 (((self.to_bits() >> 52) & 0x7ff) as i16) - 1023
418 }
419
420 fn abs(self) -> Self {
421 self.abs()
422 }
423
424 fn from_f64(x: f64) -> Self {
425 x
426 }
427}
428
429#[cfg(test)]
430#[expect(clippy::unwrap_used)]
431mod tests {
432 use ndarray::{Array1, ArrayView1};
433
434 use super::*;
435
436 #[test]
437 #[expect(clippy::too_many_lines)]
438 fn no_mantissa() {
439 assert_eq!(
440 bit_round(
441 ArrayView1::from(&[0.0_f32]),
442 &BitRoundMode::Keepbits { keepbits: 0 }
443 )
444 .unwrap(),
445 Array1::from_vec(vec![0.0_f32])
446 );
447 assert_eq!(
448 bit_round(
449 ArrayView1::from(&[1.0_f32]),
450 &BitRoundMode::Keepbits { keepbits: 0 }
451 )
452 .unwrap(),
453 Array1::from_vec(vec![1.0_f32])
454 );
455 assert_eq!(
457 bit_round(
458 ArrayView1::from(&[1.5_f32]),
459 &BitRoundMode::Keepbits { keepbits: 0 }
460 )
461 .unwrap(),
462 Array1::from_vec(vec![2.0_f32])
463 );
464 assert_eq!(
465 bit_round(
466 ArrayView1::from(&[2.0_f32]),
467 &BitRoundMode::Keepbits { keepbits: 0 }
468 )
469 .unwrap(),
470 Array1::from_vec(vec![2.0_f32])
471 );
472 assert_eq!(
473 bit_round(
474 ArrayView1::from(&[2.5_f32]),
475 &BitRoundMode::Keepbits { keepbits: 0 }
476 )
477 .unwrap(),
478 Array1::from_vec(vec![2.0_f32])
479 );
480 assert_eq!(
482 bit_round(
483 ArrayView1::from(&[3.0_f32]),
484 &BitRoundMode::Keepbits { keepbits: 0 }
485 )
486 .unwrap(),
487 Array1::from_vec(vec![2.0_f32])
488 );
489 assert_eq!(
490 bit_round(
491 ArrayView1::from(&[3.5_f32]),
492 &BitRoundMode::Keepbits { keepbits: 0 }
493 )
494 .unwrap(),
495 Array1::from_vec(vec![4.0_f32])
496 );
497 assert_eq!(
498 bit_round(
499 ArrayView1::from(&[4.0_f32]),
500 &BitRoundMode::Keepbits { keepbits: 0 }
501 )
502 .unwrap(),
503 Array1::from_vec(vec![4.0_f32])
504 );
505 assert_eq!(
506 bit_round(
507 ArrayView1::from(&[5.0_f32]),
508 &BitRoundMode::Keepbits { keepbits: 0 }
509 )
510 .unwrap(),
511 Array1::from_vec(vec![4.0_f32])
512 );
513 assert_eq!(
515 bit_round(
516 ArrayView1::from(&[6.0_f32]),
517 &BitRoundMode::Keepbits { keepbits: 0 }
518 )
519 .unwrap(),
520 Array1::from_vec(vec![8.0_f32])
521 );
522 assert_eq!(
523 bit_round(
524 ArrayView1::from(&[7.0_f32]),
525 &BitRoundMode::Keepbits { keepbits: 0 }
526 )
527 .unwrap(),
528 Array1::from_vec(vec![8.0_f32])
529 );
530 assert_eq!(
531 bit_round(
532 ArrayView1::from(&[8.0_f32]),
533 &BitRoundMode::Keepbits { keepbits: 0 }
534 )
535 .unwrap(),
536 Array1::from_vec(vec![8.0_f32])
537 );
538
539 assert_eq!(
540 bit_round(
541 ArrayView1::from(&[0.0_f64]),
542 &BitRoundMode::Keepbits { keepbits: 0 }
543 )
544 .unwrap(),
545 Array1::from_vec(vec![0.0_f64])
546 );
547 assert_eq!(
548 bit_round(
549 ArrayView1::from(&[1.0_f64]),
550 &BitRoundMode::Keepbits { keepbits: 0 }
551 )
552 .unwrap(),
553 Array1::from_vec(vec![1.0_f64])
554 );
555 assert_eq!(
557 bit_round(
558 ArrayView1::from(&[1.5_f64]),
559 &BitRoundMode::Keepbits { keepbits: 0 }
560 )
561 .unwrap(),
562 Array1::from_vec(vec![2.0_f64])
563 );
564 assert_eq!(
565 bit_round(
566 ArrayView1::from(&[2.0_f64]),
567 &BitRoundMode::Keepbits { keepbits: 0 }
568 )
569 .unwrap(),
570 Array1::from_vec(vec![2.0_f64])
571 );
572 assert_eq!(
573 bit_round(
574 ArrayView1::from(&[2.5_f64]),
575 &BitRoundMode::Keepbits { keepbits: 0 }
576 )
577 .unwrap(),
578 Array1::from_vec(vec![2.0_f64])
579 );
580 assert_eq!(
582 bit_round(
583 ArrayView1::from(&[3.0_f64]),
584 &BitRoundMode::Keepbits { keepbits: 0 }
585 )
586 .unwrap(),
587 Array1::from_vec(vec![2.0_f64])
588 );
589 assert_eq!(
590 bit_round(
591 ArrayView1::from(&[3.5_f64]),
592 &BitRoundMode::Keepbits { keepbits: 0 }
593 )
594 .unwrap(),
595 Array1::from_vec(vec![4.0_f64])
596 );
597 assert_eq!(
598 bit_round(
599 ArrayView1::from(&[4.0_f64]),
600 &BitRoundMode::Keepbits { keepbits: 0 }
601 )
602 .unwrap(),
603 Array1::from_vec(vec![4.0_f64])
604 );
605 assert_eq!(
606 bit_round(
607 ArrayView1::from(&[5.0_f64]),
608 &BitRoundMode::Keepbits { keepbits: 0 }
609 )
610 .unwrap(),
611 Array1::from_vec(vec![4.0_f64])
612 );
613 assert_eq!(
615 bit_round(
616 ArrayView1::from(&[6.0_f64]),
617 &BitRoundMode::Keepbits { keepbits: 0 }
618 )
619 .unwrap(),
620 Array1::from_vec(vec![8.0_f64])
621 );
622 assert_eq!(
623 bit_round(
624 ArrayView1::from(&[7.0_f64]),
625 &BitRoundMode::Keepbits { keepbits: 0 }
626 )
627 .unwrap(),
628 Array1::from_vec(vec![8.0_f64])
629 );
630 assert_eq!(
631 bit_round(
632 ArrayView1::from(&[8.0_f64]),
633 &BitRoundMode::Keepbits { keepbits: 0 }
634 )
635 .unwrap(),
636 Array1::from_vec(vec![8.0_f64])
637 );
638 }
639
640 #[test]
641 #[expect(clippy::cast_possible_truncation)]
642 fn full_mantissa() {
643 fn full<T: Float>(x: T) -> T {
644 T::from_binary(T::to_binary(x) + T::MANTISSA_MASK)
645 }
646
647 for v in [0.0_f32, 1.0_f32, 2.0_f32, 3.0_f32, 4.0_f32] {
648 assert_eq!(
649 bit_round(
650 ArrayView1::from(&[full(v)]),
651 &BitRoundMode::Keepbits {
652 keepbits: f32::MANITSSA_BITS as u8
653 }
654 )
655 .unwrap(),
656 Array1::from_vec(vec![full(v)])
657 );
658 }
659
660 for v in [0.0_f64, 1.0_f64, 2.0_f64, 3.0_f64, 4.0_f64] {
661 assert_eq!(
662 bit_round(
663 ArrayView1::from(&[full(v)]),
664 &BitRoundMode::Keepbits {
665 keepbits: f64::MANITSSA_BITS as u8
666 }
667 )
668 .unwrap(),
669 Array1::from_vec(vec![full(v)])
670 );
671 }
672 }
673
674 #[test]
675 fn normal_log2_floor_f32() {
676 for e in -100_i16..100 {
677 let b = f32::from(e).exp2();
678 for f in [0.55, 0.75, 0.9, 1.0, 1.1, 1.5, 1.95] {
679 let x = b * f;
680
681 #[expect(clippy::cast_possible_truncation)]
682 let math = x.log2().floor() as i16;
683 let binary = x.normal_log2_floor();
684
685 assert_eq!(math, binary, "{x}");
686 }
687 }
688
689 assert_eq!(i32::from(0.0_f32.normal_log2_floor()), f32::MIN_EXP - 2);
690 }
691
692 #[test]
693 fn normal_log2_floor_f64() {
694 for e in -100_i32..100 {
695 let b = f64::from(e).exp2();
696 for f in [0.55, 0.75, 0.9, 1.0, 1.1, 1.5, 1.95] {
697 let x = b * f;
698
699 #[expect(clippy::cast_possible_truncation)]
700 let math = x.log2().floor() as i16;
701 let binary = x.normal_log2_floor();
702
703 assert_eq!(math, binary, "{x}");
704 }
705 }
706
707 assert_eq!(i32::from(0.0_f64.normal_log2_floor()), f64::MIN_EXP - 2);
708 }
709}