Skip to main content

numcodecs_fixed_offset_scale/
lib.rs

1//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io] [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
2//!
3//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/numcodecs-rs/ci.yml?branch=main
4//! [workflow]: https://github.com/juntyr/numcodecs-rs/actions/workflows/ci.yml?query=branch%3Amain
5//!
6//! [MSRV]: https://img.shields.io/badge/MSRV-1.88.0-blue
7//! [repo]: https://github.com/juntyr/numcodecs-rs
8//!
9//! [Latest Version]: https://img.shields.io/crates/v/numcodecs-fixed-offset-scale
10//! [crates.io]: https://crates.io/crates/numcodecs-fixed-offset-scale
11//!
12//! [Rust Doc Crate]: https://img.shields.io/docsrs/numcodecs-fixed-offset-scale
13//! [docs.rs]: https://docs.rs/numcodecs-fixed-offset-scale/
14//!
15//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
16//! [docs]: https://juntyr.github.io/numcodecs-rs/numcodecs_fixed_offset_scale
17//!
18//! `$\frac{x - o}{s}$` codec implementation for the [`numcodecs`] API.
19
20use ndarray::{Array, ArrayBase, ArrayView, ArrayViewMut, Data, Dimension};
21use num_traits::Float;
22use numcodecs::{
23    AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
24    Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
25};
26use schemars::JsonSchema;
27use serde::{Deserialize, Serialize};
28use thiserror::Error;
29
30#[cfg(test)]
31use ::serde_json as _;
32
33#[derive(Clone, Serialize, Deserialize, JsonSchema)]
34#[serde(deny_unknown_fields)]
35/// Fixed offset-scale codec which calculates `$c = \frac{x - o}{s}$` on
36/// encoding and `$d = (c \cdot s) + o$` on decoding.
37///
38/// - Setting `$o = \text{mean}(x)$` and `$s = \text{std}(x)$` normalizes that
39///   data.
40/// - Setting `$o = \text{min}(x)$` and `$s = \text{max}(x) - \text{min}(x)$`
41///   standardizes the data.
42///
43/// The codec only supports floating point numbers.
44pub struct FixedOffsetScaleCodec {
45    /// The offset of the data.
46    pub offset: f64,
47    /// The scale of the data.
48    pub scale: f64,
49    /// The codec's encoding format version. Do not provide this parameter explicitly.
50    #[serde(default, rename = "_version")]
51    pub version: StaticCodecVersion<1, 0, 0>,
52}
53
54impl Codec for FixedOffsetScaleCodec {
55    type Error = FixedOffsetScaleCodecError;
56
57    fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
58        match data {
59            #[expect(clippy::cast_possible_truncation)]
60            AnyCowArray::F32(data) => Ok(AnyArray::F32(scale(
61                data,
62                self.offset as f32,
63                self.scale as f32,
64            ))),
65            AnyCowArray::F64(data) => Ok(AnyArray::F64(scale(data, self.offset, self.scale))),
66            encoded => Err(FixedOffsetScaleCodecError::UnsupportedDtype(
67                encoded.dtype(),
68            )),
69        }
70    }
71
72    fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
73        match encoded {
74            #[expect(clippy::cast_possible_truncation)]
75            AnyCowArray::F32(encoded) => Ok(AnyArray::F32(unscale(
76                encoded,
77                self.offset as f32,
78                self.scale as f32,
79            ))),
80            AnyCowArray::F64(encoded) => {
81                Ok(AnyArray::F64(unscale(encoded, self.offset, self.scale)))
82            }
83            encoded => Err(FixedOffsetScaleCodecError::UnsupportedDtype(
84                encoded.dtype(),
85            )),
86        }
87    }
88
89    fn decode_into(
90        &self,
91        encoded: AnyArrayView,
92        decoded: AnyArrayViewMut,
93    ) -> Result<(), Self::Error> {
94        match (encoded, decoded) {
95            #[expect(clippy::cast_possible_truncation)]
96            (AnyArrayView::F32(encoded), AnyArrayViewMut::F32(decoded)) => {
97                unscale_into(encoded, decoded, self.offset as f32, self.scale as f32)
98            }
99            (AnyArrayView::F64(encoded), AnyArrayViewMut::F64(decoded)) => {
100                unscale_into(encoded, decoded, self.offset, self.scale)
101            }
102            (encoded @ (AnyArrayView::F32(_) | AnyArrayView::F64(_)), decoded) => {
103                Err(FixedOffsetScaleCodecError::MismatchedDecodeIntoArray {
104                    source: AnyArrayAssignError::DTypeMismatch {
105                        src: encoded.dtype(),
106                        dst: decoded.dtype(),
107                    },
108                })
109            }
110            (encoded, _decoded) => Err(FixedOffsetScaleCodecError::UnsupportedDtype(
111                encoded.dtype(),
112            )),
113        }
114    }
115}
116
117impl StaticCodec for FixedOffsetScaleCodec {
118    const CODEC_ID: &'static str = "fixed-offset-scale.rs";
119
120    type Config<'de> = Self;
121
122    fn from_config(config: Self::Config<'_>) -> Self {
123        config
124    }
125
126    fn get_config(&self) -> StaticCodecConfig<'_, Self> {
127        StaticCodecConfig::from(self)
128    }
129}
130
131#[derive(Debug, Error)]
132/// Errors that may occur when applying the [`FixedOffsetScaleCodec`].
133pub enum FixedOffsetScaleCodecError {
134    /// [`FixedOffsetScaleCodec`] does not support the dtype
135    #[error("FixedOffsetScale does not support the dtype {0}")]
136    UnsupportedDtype(AnyArrayDType),
137    /// [`FixedOffsetScaleCodec`] cannot decode into the provided array
138    #[error("FixedOffsetScale cannot decode into the provided array")]
139    MismatchedDecodeIntoArray {
140        /// The source of the error
141        #[from]
142        source: AnyArrayAssignError,
143    },
144}
145
146/// Compute `$\frac{x - o}{s}$` over the elements of the input `data` array.
147pub fn scale<T: Float, S: Data<Elem = T>, D: Dimension>(
148    data: ArrayBase<S, D>,
149    offset: T,
150    scale: T,
151) -> Array<T, D> {
152    let inverse_scale = scale.recip();
153
154    let mut data = data.into_owned();
155    data.mapv_inplace(|x| (x - offset) * inverse_scale);
156
157    data
158}
159
160/// Compute `$(x \cdot s) + o$` over the elements of the input `data` array.
161pub fn unscale<T: Float, S: Data<Elem = T>, D: Dimension>(
162    data: ArrayBase<S, D>,
163    offset: T,
164    scale: T,
165) -> Array<T, D> {
166    let mut data = data.into_owned();
167    data.mapv_inplace(|x| x.mul_add(scale, offset));
168
169    data
170}
171
172#[expect(clippy::needless_pass_by_value)]
173/// Compute `$(x \cdot s) + o$` over the elements of the input `data` array and
174/// write them into the `out`put array.
175///
176/// # Errors
177///
178/// Errors with
179/// - [`FixedOffsetScaleCodecError::MismatchedDecodeIntoArray`] if the `data`
180///   array's shape does not match the `out`put array's shape
181pub fn unscale_into<T: Float, D: Dimension>(
182    data: ArrayView<T, D>,
183    mut out: ArrayViewMut<T, D>,
184    offset: T,
185    scale: T,
186) -> Result<(), FixedOffsetScaleCodecError> {
187    if data.shape() != out.shape() {
188        return Err(FixedOffsetScaleCodecError::MismatchedDecodeIntoArray {
189            source: AnyArrayAssignError::ShapeMismatch {
190                src: data.shape().to_vec(),
191                dst: out.shape().to_vec(),
192            },
193        });
194    }
195
196    // iteration must occur in synchronised (standard) order
197    for (d, o) in data.iter().zip(out.iter_mut()) {
198        *o = (*d).mul_add(scale, offset);
199    }
200
201    Ok(())
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    #[test]
209    fn identity() {
210        let data = (0..1000).map(f64::from).collect::<Vec<_>>();
211        let data = Array::from_vec(data);
212
213        let encoded = scale(data.view(), 0.0, 1.0);
214
215        for (r, e) in data.iter().zip(encoded.iter()) {
216            assert_eq!((*r).to_bits(), (*e).to_bits());
217        }
218
219        let decoded = unscale(encoded, 0.0, 1.0);
220
221        for (r, d) in data.iter().zip(decoded.iter()) {
222            assert_eq!((*r).to_bits(), (*d).to_bits());
223        }
224    }
225
226    #[test]
227    fn roundtrip() {
228        let data = (0..1000).map(f64::from).collect::<Vec<_>>();
229        let data = Array::from_vec(data);
230
231        let encoded = scale(data.view(), 512.0, 64.0);
232
233        for (r, e) in data.iter().zip(encoded.iter()) {
234            assert_eq!((((*r) - 512.0) / 64.0).to_bits(), (*e).to_bits());
235        }
236
237        let decoded = unscale(encoded, 512.0, 64.0);
238
239        for (r, d) in data.iter().zip(decoded.iter()) {
240            assert_eq!((*r).to_bits(), (*d).to_bits());
241        }
242    }
243}