oxigdal-compress 0.1.6

Advanced compression codecs and auto-selection for geospatial data
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
//! ZFP-style floating-point compression
//!
//! ZFP is a compressed format for arrays of floating-point data.
//! This implementation provides similar functionality with configurable
//! compression modes.

use super::FpMode;
use crate::error::Result;
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use std::io::Cursor;

/// ZFP compression mode
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ZfpMode {
    /// Fixed rate mode (bits per value)
    FixedRate(usize),
    /// Fixed precision mode (bit planes)
    FixedPrecision(usize),
    /// Fixed accuracy mode (error bound)
    FixedAccuracy(f64),
    /// Reversible mode (lossless)
    Reversible,
}

impl From<FpMode> for ZfpMode {
    fn from(mode: FpMode) -> Self {
        match mode {
            FpMode::FixedRate(rate) => ZfpMode::FixedRate(rate),
            FpMode::FixedPrecision(prec) => ZfpMode::FixedPrecision(prec),
            FpMode::FixedAccuracy(acc) => ZfpMode::FixedAccuracy(acc),
            FpMode::Reversible => ZfpMode::Reversible,
        }
    }
}

/// ZFP codec configuration
#[derive(Debug, Clone)]
pub struct ZfpConfig {
    /// Compression mode
    pub mode: ZfpMode,

    /// Block size (must be power of 2)
    pub block_size: usize,
}

impl Default for ZfpConfig {
    fn default() -> Self {
        Self {
            mode: ZfpMode::FixedRate(16),
            block_size: 4,
        }
    }
}

impl ZfpConfig {
    /// Create configuration with mode
    pub fn with_mode(mode: ZfpMode) -> Self {
        Self {
            mode,
            ..Default::default()
        }
    }

    /// Set block size
    pub fn with_block_size(mut self, size: usize) -> Self {
        self.block_size = size;
        self
    }
}

/// ZFP compression codec
pub struct ZfpCodec {
    config: ZfpConfig,
}

impl ZfpCodec {
    /// Create a new ZFP codec with default configuration
    pub fn new() -> Self {
        Self {
            config: ZfpConfig::default(),
        }
    }

    /// Create a new ZFP codec with custom configuration
    pub fn with_config(config: ZfpConfig) -> Self {
        Self { config }
    }

    /// Compress f32 array
    pub fn compress_f32(&self, input: &[f32]) -> Result<Vec<u8>> {
        if input.is_empty() {
            return Ok(Vec::new());
        }

        match self.config.mode {
            ZfpMode::Reversible => self.compress_f32_reversible(input),
            ZfpMode::FixedRate(rate) => self.compress_f32_fixed_rate(input, rate),
            ZfpMode::FixedPrecision(prec) => self.compress_f32_fixed_precision(input, prec),
            ZfpMode::FixedAccuracy(acc) => self.compress_f32_fixed_accuracy(input, acc),
        }
    }

    /// Decompress f32 array
    pub fn decompress_f32(&self, input: &[u8], len: usize) -> Result<Vec<f32>> {
        if input.is_empty() {
            return Ok(Vec::new());
        }

        match self.config.mode {
            ZfpMode::Reversible => self.decompress_f32_reversible(input, len),
            ZfpMode::FixedRate(rate) => self.decompress_f32_fixed_rate(input, len, rate),
            ZfpMode::FixedPrecision(prec) => self.decompress_f32_fixed_precision(input, len, prec),
            ZfpMode::FixedAccuracy(acc) => self.decompress_f32_fixed_accuracy(input, len, acc),
        }
    }

    /// Compress f64 array
    pub fn compress_f64(&self, input: &[f64]) -> Result<Vec<u8>> {
        if input.is_empty() {
            return Ok(Vec::new());
        }

        match self.config.mode {
            ZfpMode::Reversible => self.compress_f64_reversible(input),
            ZfpMode::FixedRate(rate) => self.compress_f64_fixed_rate(input, rate),
            ZfpMode::FixedPrecision(prec) => self.compress_f64_fixed_precision(input, prec),
            ZfpMode::FixedAccuracy(acc) => self.compress_f64_fixed_accuracy(input, acc),
        }
    }

    /// Decompress f64 array
    pub fn decompress_f64(&self, input: &[u8], len: usize) -> Result<Vec<f64>> {
        if input.is_empty() {
            return Ok(Vec::new());
        }

        match self.config.mode {
            ZfpMode::Reversible => self.decompress_f64_reversible(input, len),
            ZfpMode::FixedRate(rate) => self.decompress_f64_fixed_rate(input, len, rate),
            ZfpMode::FixedPrecision(prec) => self.decompress_f64_fixed_precision(input, len, prec),
            ZfpMode::FixedAccuracy(acc) => self.decompress_f64_fixed_accuracy(input, len, acc),
        }
    }

    // Reversible (lossless) compression for f32
    fn compress_f32_reversible(&self, input: &[f32]) -> Result<Vec<u8>> {
        let mut output = Vec::with_capacity(input.len() * 4);

        for &val in input {
            output.write_u32::<LittleEndian>(val.to_bits())?;
        }

        Ok(output)
    }

    fn decompress_f32_reversible(&self, input: &[u8], len: usize) -> Result<Vec<f32>> {
        let mut cursor = Cursor::new(input);
        let mut output = Vec::with_capacity(len);

        for _ in 0..len {
            let bits = cursor.read_u32::<LittleEndian>()?;
            output.push(f32::from_bits(bits));
        }

        Ok(output)
    }

    // Fixed-rate compression for f32
    fn compress_f32_fixed_rate(&self, input: &[f32], bits_per_value: usize) -> Result<Vec<u8>> {
        let mut output = Vec::new();

        // Store metadata
        output.write_u32::<LittleEndian>(input.len() as u32)?;
        output.write_u32::<LittleEndian>(bits_per_value as u32)?;

        // Simple quantization based on bit budget
        let range = Self::compute_range_f32(input);
        let levels = 1u64 << bits_per_value;
        let scale = (levels - 1) as f32 / range.1;

        output.write_f32::<LittleEndian>(range.0)?; // min
        output.write_f32::<LittleEndian>(scale)?; // scale

        // Quantize and encode
        for &val in input {
            let quantized = ((val - range.0) * scale) as u32;
            output.write_u32::<LittleEndian>(quantized)?;
        }

        Ok(output)
    }

    fn decompress_f32_fixed_rate(
        &self,
        input: &[u8],
        len: usize,
        _bits_per_value: usize,
    ) -> Result<Vec<f32>> {
        let mut cursor = Cursor::new(input);

        let _stored_len = cursor.read_u32::<LittleEndian>()?;
        let _stored_bits = cursor.read_u32::<LittleEndian>()?;

        let min = cursor.read_f32::<LittleEndian>()?;
        let scale = cursor.read_f32::<LittleEndian>()?;

        let mut output = Vec::with_capacity(len);

        for _ in 0..len {
            let quantized = cursor.read_u32::<LittleEndian>()?;
            let val = min + (quantized as f32 / scale);
            output.push(val);
        }

        Ok(output)
    }

    // Fixed-precision compression for f32 (simplified)
    fn compress_f32_fixed_precision(&self, input: &[f32], precision: usize) -> Result<Vec<u8>> {
        // Use fixed-rate with precision-based bit count
        let bits = (precision + 8).min(32);
        self.compress_f32_fixed_rate(input, bits)
    }

    fn decompress_f32_fixed_precision(
        &self,
        input: &[u8],
        len: usize,
        precision: usize,
    ) -> Result<Vec<f32>> {
        let bits = (precision + 8).min(32);
        self.decompress_f32_fixed_rate(input, len, bits)
    }

    // Fixed-accuracy compression for f32 (simplified)
    fn compress_f32_fixed_accuracy(&self, input: &[f32], accuracy: f64) -> Result<Vec<u8>> {
        let range = Self::compute_range_f32(input);
        let levels = (range.1 / accuracy as f32).ceil() as u64;
        let bits = (levels as f64).log2().ceil() as usize;
        let bits = bits.clamp(4, 32);
        self.compress_f32_fixed_rate(input, bits)
    }

    fn decompress_f32_fixed_accuracy(
        &self,
        input: &[u8],
        len: usize,
        _accuracy: f64,
    ) -> Result<Vec<f32>> {
        // Determine bits from stored metadata
        let mut cursor = Cursor::new(input);
        let _stored_len = cursor.read_u32::<LittleEndian>()?;
        let bits = cursor.read_u32::<LittleEndian>()? as usize;

        self.decompress_f32_fixed_rate(input, len, bits)
    }

    // f64 versions (similar implementations)
    fn compress_f64_reversible(&self, input: &[f64]) -> Result<Vec<u8>> {
        let mut output = Vec::with_capacity(input.len() * 8);

        for &val in input {
            output.write_u64::<LittleEndian>(val.to_bits())?;
        }

        Ok(output)
    }

    fn decompress_f64_reversible(&self, input: &[u8], len: usize) -> Result<Vec<f64>> {
        let mut cursor = Cursor::new(input);
        let mut output = Vec::with_capacity(len);

        for _ in 0..len {
            let bits = cursor.read_u64::<LittleEndian>()?;
            output.push(f64::from_bits(bits));
        }

        Ok(output)
    }

    fn compress_f64_fixed_rate(&self, input: &[f64], bits_per_value: usize) -> Result<Vec<u8>> {
        let mut output = Vec::new();

        output.write_u32::<LittleEndian>(input.len() as u32)?;
        output.write_u32::<LittleEndian>(bits_per_value as u32)?;

        let range = Self::compute_range_f64(input);
        let levels = 1u64 << bits_per_value.min(63);
        let scale = (levels - 1) as f64 / range.1;

        output.write_f64::<LittleEndian>(range.0)?;
        output.write_f64::<LittleEndian>(scale)?;

        for &val in input {
            let quantized = ((val - range.0) * scale) as u64;
            output.write_u64::<LittleEndian>(quantized)?;
        }

        Ok(output)
    }

    fn decompress_f64_fixed_rate(
        &self,
        input: &[u8],
        len: usize,
        _bits_per_value: usize,
    ) -> Result<Vec<f64>> {
        let mut cursor = Cursor::new(input);

        let _stored_len = cursor.read_u32::<LittleEndian>()?;
        let _stored_bits = cursor.read_u32::<LittleEndian>()?;

        let min = cursor.read_f64::<LittleEndian>()?;
        let scale = cursor.read_f64::<LittleEndian>()?;

        let mut output = Vec::with_capacity(len);

        for _ in 0..len {
            let quantized = cursor.read_u64::<LittleEndian>()?;
            let val = min + (quantized as f64 / scale);
            output.push(val);
        }

        Ok(output)
    }

    fn compress_f64_fixed_precision(&self, input: &[f64], precision: usize) -> Result<Vec<u8>> {
        let bits = (precision + 11).min(64);
        self.compress_f64_fixed_rate(input, bits)
    }

    fn decompress_f64_fixed_precision(
        &self,
        input: &[u8],
        len: usize,
        precision: usize,
    ) -> Result<Vec<f64>> {
        let bits = (precision + 11).min(64);
        self.decompress_f64_fixed_rate(input, len, bits)
    }

    fn compress_f64_fixed_accuracy(&self, input: &[f64], accuracy: f64) -> Result<Vec<u8>> {
        let range = Self::compute_range_f64(input);
        let levels = (range.1 / accuracy).ceil() as u64;
        let bits = (levels as f64).log2().ceil() as usize;
        let bits = bits.clamp(8, 64);
        self.compress_f64_fixed_rate(input, bits)
    }

    fn decompress_f64_fixed_accuracy(
        &self,
        input: &[u8],
        len: usize,
        _accuracy: f64,
    ) -> Result<Vec<f64>> {
        let mut cursor = Cursor::new(input);
        let _stored_len = cursor.read_u32::<LittleEndian>()?;
        let bits = cursor.read_u32::<LittleEndian>()? as usize;

        self.decompress_f64_fixed_rate(input, len, bits)
    }

    // Helper: compute data range for f32
    fn compute_range_f32(data: &[f32]) -> (f32, f32) {
        if data.is_empty() {
            return (0.0, 0.0);
        }

        let mut min = data[0];
        let mut max = data[0];

        for &val in data {
            min = min.min(val);
            max = max.max(val);
        }

        let range = max - min;
        (min, range)
    }

    // Helper: compute data range for f64
    fn compute_range_f64(data: &[f64]) -> (f64, f64) {
        if data.is_empty() {
            return (0.0, 0.0);
        }

        let mut min = data[0];
        let mut max = data[0];

        for &val in data {
            min = min.min(val);
            max = max.max(val);
        }

        let range = max - min;
        (min, range)
    }
}

impl Default for ZfpCodec {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_zfp_reversible_f32() {
        let config = ZfpConfig::with_mode(ZfpMode::Reversible);
        let codec = ZfpCodec::with_config(config);

        let data: Vec<f32> = (0..100).map(|i| i as f32 * 0.1).collect();

        let compressed = codec.compress_f32(&data).expect("Compression failed");
        let decompressed = codec
            .decompress_f32(&compressed, data.len())
            .expect("Decompression failed");

        assert_eq!(decompressed, data);
    }

    #[test]
    fn test_zfp_fixed_rate_f32() {
        let config = ZfpConfig::with_mode(ZfpMode::FixedRate(16));
        let codec = ZfpCodec::with_config(config);

        let data: Vec<f32> = (0..100).map(|i| i as f32 * 0.1).collect();

        let compressed = codec.compress_f32(&data).expect("Compression failed");
        let decompressed = codec
            .decompress_f32(&compressed, data.len())
            .expect("Decompression failed");

        assert_eq!(decompressed.len(), data.len());
    }
}