1use std::borrow::Cow;
21
22use ndarray::{Array, ArrayBase, Data, Dimension};
23use num_traits::Float;
24use numcodecs::{
25 AnyArray, AnyArrayAssignError, AnyArrayDType, AnyArrayView, AnyArrayViewMut, AnyCowArray,
26 Codec, StaticCodec, StaticCodecConfig, StaticCodecVersion,
27};
28use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
29use serde::{Deserialize, Deserializer, Serialize, Serializer};
30use thiserror::Error;
31
32#[cfg(test)]
33use ::serde_json as _;
34
35#[derive(Clone, Serialize, Deserialize, JsonSchema)]
36#[serde(deny_unknown_fields)]
37pub struct RoundCodec {
42 pub precision: NonNegative<f64>,
44 #[serde(default, rename = "_version")]
46 pub version: StaticCodecVersion<1, 0, 0>,
47}
48
49impl Codec for RoundCodec {
50 type Error = RoundCodecError;
51
52 fn encode(&self, data: AnyCowArray) -> Result<AnyArray, Self::Error> {
53 match data {
54 #[expect(clippy::cast_possible_truncation)]
55 AnyCowArray::F32(data) => Ok(AnyArray::F32(round(
56 data,
57 NonNegative(self.precision.0 as f32),
58 ))),
59 AnyCowArray::F64(data) => Ok(AnyArray::F64(round(data, self.precision))),
60 encoded => Err(RoundCodecError::UnsupportedDtype(encoded.dtype())),
61 }
62 }
63
64 fn decode(&self, encoded: AnyCowArray) -> Result<AnyArray, Self::Error> {
65 match encoded {
66 AnyCowArray::F32(encoded) => Ok(AnyArray::F32(encoded.into_owned())),
67 AnyCowArray::F64(encoded) => Ok(AnyArray::F64(encoded.into_owned())),
68 encoded => Err(RoundCodecError::UnsupportedDtype(encoded.dtype())),
69 }
70 }
71
72 fn decode_into(
73 &self,
74 encoded: AnyArrayView,
75 mut decoded: AnyArrayViewMut,
76 ) -> Result<(), Self::Error> {
77 if !matches!(encoded.dtype(), AnyArrayDType::F32 | AnyArrayDType::F64) {
78 return Err(RoundCodecError::UnsupportedDtype(encoded.dtype()));
79 }
80
81 Ok(decoded.assign(&encoded)?)
82 }
83}
84
85impl StaticCodec for RoundCodec {
86 const CODEC_ID: &'static str = "round.rs";
87
88 type Config<'de> = Self;
89
90 fn from_config(config: Self::Config<'_>) -> Self {
91 config
92 }
93
94 fn get_config(&self) -> StaticCodecConfig<'_, Self> {
95 StaticCodecConfig::from(self)
96 }
97}
98
99#[expect(clippy::derive_partial_eq_without_eq)] #[derive(Copy, Clone, PartialEq, PartialOrd, Hash)]
101pub struct NonNegative<T: Float>(T);
103
104impl Serialize for NonNegative<f64> {
105 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
106 serializer.serialize_f64(self.0)
107 }
108}
109
110impl<'de> Deserialize<'de> for NonNegative<f64> {
111 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
112 let x = f64::deserialize(deserializer)?;
113
114 if x >= 0.0 {
115 Ok(Self(x))
116 } else {
117 Err(serde::de::Error::invalid_value(
118 serde::de::Unexpected::Float(x),
119 &"a non-negative value",
120 ))
121 }
122 }
123}
124
125impl JsonSchema for NonNegative<f64> {
126 fn inline_schema() -> bool {
127 true
128 }
129
130 fn schema_name() -> Cow<'static, str> {
131 Cow::Borrowed("NonNegativeF64")
132 }
133
134 fn schema_id() -> Cow<'static, str> {
135 Cow::Borrowed(concat!(module_path!(), "::", "NonNegative<f64>"))
136 }
137
138 fn json_schema(_gen: &mut SchemaGenerator) -> Schema {
139 json_schema!({
140 "type": "number",
141 "minimum": 0.0
142 })
143 }
144}
145
146#[derive(Debug, Error)]
147pub enum RoundCodecError {
149 #[error("Round does not support the dtype {0}")]
151 UnsupportedDtype(AnyArrayDType),
152 #[error("Round cannot decode into the provided array")]
154 MismatchedDecodeIntoArray {
155 #[from]
157 source: AnyArrayAssignError,
158 },
159}
160
161#[must_use]
162pub fn round<T: Float, S: Data<Elem = T>, D: Dimension>(
167 data: ArrayBase<S, D>,
168 precision: NonNegative<T>,
169) -> Array<T, D> {
170 let mut encoded = data.into_owned();
171
172 if precision.0.is_zero() {
173 return encoded;
174 }
175
176 encoded.mapv_inplace(|x| {
177 let n = x / precision.0;
178
179 if !n.is_finite() {
182 return x;
183 }
184
185 n.round() * precision.0
187 });
188
189 encoded
190}
191
192#[cfg(test)]
193mod tests {
194 use ndarray::array;
195
196 use super::*;
197
198 #[test]
199 fn round_zero_precision() {
200 let data = array![1.1, 2.1];
201
202 let rounded = round(data.view(), NonNegative(0.0));
203
204 assert_eq!(data, rounded);
205 }
206
207 #[test]
208 fn round_minimal_precision() {
209 let data = array![0.1, 1.0, 11.0, 21.0];
210
211 assert_eq!(11.0 / f64::MIN_POSITIVE, f64::INFINITY);
212 let rounded = round(data.view(), NonNegative(f64::MIN_POSITIVE));
213
214 assert_eq!(data, rounded);
215 }
216
217 #[test]
218 fn round_roundoff_errors() {
219 let data = array![0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0];
220
221 let rounded = round(data.view(), NonNegative(0.1));
222
223 assert_eq!(
224 rounded,
225 array![
226 0.0,
227 0.1,
228 0.2,
229 0.300_000_000_000_000_04,
230 0.4,
231 0.5,
232 0.600_000_000_000_000_1,
233 0.700_000_000_000_000_1,
234 0.8,
235 0.9,
236 1.0
237 ]
238 );
239
240 let rounded_twice = round(rounded.view(), NonNegative(0.1));
241
242 assert_eq!(rounded, rounded_twice);
243 }
244
245 #[test]
246 fn round_edge_cases() {
247 let data = array![
248 -f64::NAN,
249 -f64::INFINITY,
250 -42.0,
251 -0.0,
252 0.0,
253 42.0,
254 f64::INFINITY,
255 f64::NAN
256 ];
257
258 let rounded = round(data.view(), NonNegative(1.0));
259
260 #[expect(clippy::float_cmp)]
261 for (d, r) in data.into_iter().zip(rounded) {
262 assert!(d == r || d.to_bits() == r.to_bits());
263 }
264 }
265}