labeledarray 0.4.1

LabeledArray: labeled n-dimensional arrays with spatial-aware helpers for geospatial and scientific workflows.
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use ndarray::{ArrayD, Axis};
use std::any::Any;
use std::collections::HashMap;
use std::fmt::Debug;

// New trait to handle vectors of different types
pub trait AnyVec: Any + Debug {
    fn as_any(&self) -> &dyn Any;
    fn clone_box(&self) -> Box<dyn AnyVec>;
    fn len(&self) -> usize;
    fn is_empty(&self) -> bool;
}

impl<T: Any + Clone + Debug + 'static> AnyVec for Vec<T> {
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn clone_box(&self) -> Box<dyn AnyVec> {
        Box::new(self.clone())
    }

    fn len(&self) -> usize {
        self.len()
    }

    fn is_empty(&self) -> bool {
        self.is_empty()
    }
}

impl Clone for Box<dyn AnyVec> {
    fn clone(&self) -> Self {
        self.clone_box()
    }
}

// Newtype wrapper to allow custom Debug implementation
#[derive(Clone)]
pub struct CoordinateVec(pub Box<dyn AnyVec>);

impl Debug for CoordinateVec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Coordinate vector with {} elements", self.0.len())
    }
}

/// A marker trait for types that can be used as coordinates.
pub trait Coordinate: Any + Clone + Debug + PartialEq + 'static {}
impl<T: Any + Clone + Debug + PartialEq + 'static> Coordinate for T {}

pub trait FindIndex: 'static {
    fn find_index_in(&self, coords: &dyn AnyVec) -> Option<usize>;
}

impl<C: Coordinate> FindIndex for C {
    fn find_index_in(&self, coords: &dyn AnyVec) -> Option<usize> {
        coords
            .as_any()
            .downcast_ref::<Vec<C>>()
            .and_then(|vec| vec.iter().position(|item| item == self))
    }
}

pub trait SliceSelector {
    fn find_indices(&self, coords: &dyn AnyVec) -> Vec<usize>;
    fn new_coords(&self) -> Box<dyn AnyVec>;
}

impl<C: Coordinate> SliceSelector for Vec<C> {
    fn find_indices(&self, coords: &dyn AnyVec) -> Vec<usize> {
        let coord_vec = coords
            .as_any()
            .downcast_ref::<Vec<C>>()
            .expect("Coordinate type mismatch for slicing");
        self.iter()
            .map(|label| {
                coord_vec
                    .iter()
                    .position(|item| item == label)
                    .expect("Label not found")
            })
            .collect()
    }

    fn new_coords(&self) -> Box<dyn AnyVec> {
        Box::new(self.clone())
    }
}

pub enum Selector {
    Label(Box<dyn FindIndex>),
    Slice(Box<dyn SliceSelector>),
}

#[derive(Debug, thiserror::Error)]
pub enum LabeledError {
    #[error("Dimension not found: {0}")]
    DimensionNotFound(String),
    #[error(
        "Coordinate length mismatch for dimension '{dim}': expected {expected}, found {found}"
    )]
    CoordinateLengthMismatch {
        dim: String,
        expected: usize,
        found: usize,
    },
}

/// A high-level, labeled multi-dimensional array structure for geospatial data.
#[derive(Debug, Clone)]
pub struct LabeledArray<T> {
    data: ArrayD<T>,
    dims: Vec<String>,
    coords: HashMap<String, CoordinateVec>,
}

impl<T> LabeledArray<T>
where
    T: Clone,
{
    pub fn new(data: ArrayD<T>, dims: Vec<String>) -> Self {
        assert_eq!(data.ndim(), dims.len());
        Self {
            data,
            dims,
            coords: HashMap::new(),
        }
    }

    pub fn new_with_coords(
        data: ArrayD<T>,
        dims: Vec<String>,
        coords: HashMap<String, CoordinateVec>,
    ) -> Self {
        assert_eq!(data.ndim(), dims.len());
        for (i, dim_name) in dims.iter().enumerate() {
            if let Some(coord) = coords.get(dim_name) {
                assert_eq!(coord.0.len(), data.shape()[i]);
            }
        }
        Self { data, dims, coords }
    }

    pub fn dims(&self) -> &[String] {
        &self.dims
    }

    pub fn shape(&self) -> &[usize] {
        self.data.shape()
    }

    pub fn ndim(&self) -> usize {
        self.data.ndim()
    }

    pub fn data(&self) -> &ArrayD<T> {
        &self.data
    }

    pub fn data_mut(&mut self) -> &mut ArrayD<T> {
        &mut self.data
    }

    pub fn coords<C: Coordinate>(&self, dim: &str) -> Option<&[C]> {
        self.coords
            .get(dim)
            .and_then(|any_vec| any_vec.0.as_any().downcast_ref::<Vec<C>>())
            .map(|vec| vec.as_slice())
    }

    pub fn all_coords(&self) -> &HashMap<String, CoordinateVec> {
        &self.coords
    }

    pub fn set_coords<C: Coordinate>(
        &mut self,
        dim: &str,
        coords: Vec<C>,
    ) -> Result<(), LabeledError> {
        let dim_index = self
            .dims
            .iter()
            .position(|d| d == dim)
            .ok_or_else(|| LabeledError::DimensionNotFound(dim.to_string()))?;

        let expected_len = self.data.shape()[dim_index];
        if coords.len() != expected_len {
            return Err(LabeledError::CoordinateLengthMismatch {
                dim: dim.to_string(),
                expected: expected_len,
                found: coords.len(),
            });
        }

        self.coords
            .insert(dim.to_string(), CoordinateVec(Box::new(coords)));
        Ok(())
    }

    pub fn dim_index(&self, dim: &str) -> Option<usize> {
        self.dims.iter().position(|d| d == dim)
    }

    pub fn select_by_label<C: Coordinate>(&self, dim: &str, label: &C) -> Option<usize> {
        self.coords::<C>(dim)
            .and_then(|coords| coords.iter().position(|c| c == label))
    }

    /// Select a subset of the array using dimension and coordinate labels.
    ///
    /// # Arguments
    ///
    /// * `selectors` - A HashMap where keys are dimension names and values
    ///   are `Selector` enums (`Selector::Label` or `Selector::Slice`).
    ///
    /// # Returns
    ///
    /// A new `LabeledArray` containing the sliced data.
    ///
    /// # Panics
    ///
    /// Panics if a specified dimension does not exist or if a label is not found.
    pub fn sel(&self, selectors: HashMap<&str, Selector>) -> Self {
        let mut new_data = self.data.clone();
        let mut new_dims = self.dims.clone();
        let mut new_coords = self.coords.clone();

        // Validate all dimension names before starting
        for dim_name in selectors.keys() {
            self.dim_index(dim_name).expect("Dimension not found");
        }

        // Collect and sort selectors by dimension index in descending order
        let mut sorted_selectors: Vec<_> = selectors
            .iter()
            .map(|(dim_name, selector)| {
                let dim_index = new_dims.iter().position(|d| d == *dim_name).unwrap();
                (dim_index, *dim_name, selector)
            })
            .collect();

        // Sort descending by dimension index. This is crucial for correctness,
        // as removing an axis shifts the indices of all subsequent axes.
        // By processing from highest index to lowest, we avoid invalidating indices.
        sorted_selectors.sort_by(|a, b| b.0.cmp(&a.0));

        for (dim_index, dim_name, selector) in sorted_selectors {
            let current_coords = self
                .coords
                .get(dim_name)
                .expect("Coordinates not found for dimension.");

            match selector {
                Selector::Label(label_selector) => {
                    let index = label_selector
                        .find_index_in(&*current_coords.0)
                        .expect("Label not found in coordinates.");
                    // `index_axis` removes the dimension
                    new_data = new_data.index_axis(Axis(dim_index), index).to_owned();
                    // Update metadata
                    new_dims.remove(dim_index);
                    new_coords.remove(dim_name);
                }
                Selector::Slice(slice_selector) => {
                    let indices = slice_selector.find_indices(&*current_coords.0);
                    // `select` keeps the dimension but slices it
                    new_data = new_data.select(Axis(dim_index), &indices).to_owned();
                    // Update metadata
                    new_coords.insert(
                        dim_name.to_string(),
                        CoordinateVec(slice_selector.new_coords()),
                    );
                }
            }
        }

        LabeledArray {
            data: new_data,
            dims: new_dims,
            coords: new_coords,
        }
    }
}

impl<T: Clone + Debug> LabeledArray<T> {
    pub fn info(&self) -> String {
        let mut info = String::new();
        info.push_str(&format!("LabeledArray<{:?}>\n", std::any::type_name::<T>()));
        info.push_str(&format!("Dimensions: {:?}\n", self.dims));
        info.push_str(&format!("Shape: {:?}\n", self.shape()));

        if !self.coords.is_empty() {
            info.push_str("Coordinates:\n");
            for (dim, coord_vec) in &self.coords {
                info.push_str(&format!("  {}: {:?}\n", dim, coord_vec));
            }
        }
        info
    }
}

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

    #[test]
    fn test_new_labeled_array() {
        let data = ArrayD::from_shape_vec(vec![2, 3], vec![1, 2, 3, 4, 5, 6]).unwrap();
        let dims = vec!["y".to_string(), "x".to_string()];
        let array: LabeledArray<i32> = LabeledArray::new(data, dims);
        assert_eq!(array.shape(), &[2, 3]);
    }

    #[test]
    #[should_panic]
    fn test_new_labeled_array_dimension_mismatch() {
        let data = ArrayD::from_shape_vec(vec![2, 3], vec![1, 2, 3, 4, 5, 6]).unwrap();
        let dims = vec!["y".to_string()];
        LabeledArray::new(data, dims);
    }

    #[test]
    fn test_set_coords_and_coords() {
        let data = ArrayD::from_shape_vec(vec![2, 3], vec![0; 6]).unwrap();
        let mut array = LabeledArray::new(data, vec!["y".to_string(), "x".to_string()]);

        array
            .set_coords("y", vec![10.0, 20.0])
            .expect("Failed to set y coords");
        array
            .set_coords("x", vec!["a".to_string(), "b".to_string(), "c".to_string()])
            .expect("Failed to set x coords");

        assert_eq!(array.coords::<f64>("y").unwrap(), &[10.0, 20.0]);
        assert_eq!(
            array.coords::<String>("x").unwrap(),
            &["a".to_string(), "b".to_string(), "c".to_string()]
        );
    }

    #[test]
    fn test_select_by_label_generic() {
        let data = ArrayD::from_shape_vec(vec![2, 3], vec![0; 6]).unwrap();
        let mut array = LabeledArray::new(data, vec!["y".to_string(), "x".to_string()]);

        array
            .set_coords("y", vec![10, 20])
            .expect("Failed to set y coords");
        array
            .set_coords("x", vec!["a".to_string(), "b".to_string(), "c".to_string()])
            .expect("Failed to set x coords");

        assert_eq!(array.select_by_label("y", &20), Some(1));
        assert_eq!(array.select_by_label("x", &"b".to_string()), Some(1));
    }

    #[test]
    fn test_sel_label_and_slice() {
        let data = ArrayD::from_shape_vec(vec![2, 3, 4], vec![0.0; 24]).unwrap();
        let mut array = LabeledArray::new(
            data,
            vec!["time".to_string(), "y".to_string(), "x".to_string()],
        );

        array
            .set_coords("time", vec![0, 1])
            .expect("Failed to set time coords");
        array
            .set_coords("y", vec![10.0, 20.0, 30.0])
            .expect("Failed to set y coords");
        array
            .set_coords(
                "x",
                vec![
                    "a".to_string(),
                    "b".to_string(),
                    "c".to_string(),
                    "d".to_string(),
                ],
            )
            .expect("Failed to set x coords");

        let result = array.sel(HashMap::from([
            ("time", Selector::Label(Box::new(1))),
            ("y", Selector::Slice(Box::new(vec![10.0, 30.0]))),
        ]));

        assert_eq!(result.ndim(), 2);
        assert_eq!(result.shape(), &[2, 4]);
        assert_eq!(result.dims(), &["y", "x"]);
        assert_eq!(result.coords::<f64>("y").unwrap(), &[10.0, 30.0]);
    }

    #[test]
    fn test_sel_single_label() {
        let data = ArrayD::from_shape_vec(vec![2, 3], vec![0; 6]).unwrap();
        let mut array = LabeledArray::new(data, vec!["y".to_string(), "x".to_string()]);
        array
            .set_coords("y", vec![10, 20])
            .expect("Failed to set y coords");
        array
            .set_coords("x", vec!["a".to_string(), "b".to_string(), "c".to_string()])
            .expect("Failed to set x coords");

        let result = array.sel(HashMap::from([(
            "y",
            Selector::Label(Box::new(20) as Box<dyn FindIndex>),
        )]));
        assert_eq!(result.shape(), &[3]);
        assert_eq!(result.dims(), &["x"]);
        assert_eq!(
            result.coords::<String>("x").unwrap(),
            &["a".to_string(), "b".to_string(), "c".to_string()]
        );
    }

    #[test]
    fn test_sel_multi_slice() {
        let data = ArrayD::from_shape_vec(vec![2, 3, 4], (0..24).collect::<Vec<i32>>()).unwrap();
        let mut array = LabeledArray::new(
            data,
            vec!["time".to_string(), "y".to_string(), "x".to_string()],
        );
        array
            .set_coords("time", vec![100, 200])
            .expect("Failed to set time coords");
        array
            .set_coords("y", vec![10.0, 20.0, 30.0])
            .expect("Failed to set y coords");
        array
            .set_coords(
                "x",
                vec![
                    "a".to_string(),
                    "b".to_string(),
                    "c".to_string(),
                    "d".to_string(),
                ],
            )
            .expect("Failed to set x coords");

        let result = array.sel(HashMap::from([
            (
                "x",
                Selector::Slice(Box::new(vec!["a".to_string(), "c".to_string()])),
            ),
            ("y", Selector::Slice(Box::new(vec![10.0, 30.0]))),
        ]));

        assert_eq!(result.shape(), &[2, 2, 2]);
        assert_eq!(result.dims(), &["time", "y", "x"]);
        assert_eq!(result.coords::<f64>("y").unwrap(), &[10.0, 30.0]);
        assert_eq!(
            result.coords::<String>("x").unwrap(),
            &["a".to_string(), "c".to_string()]
        );
    }

    #[test]
    fn test_info_with_mixed_coords() {
        let data = ArrayD::from_shape_vec(vec![2, 3], vec![0; 6]).unwrap();
        let mut array = LabeledArray::new(data, vec!["y".to_string(), "x".to_string()]);
        array
            .set_coords("y", vec![10, 20])
            .expect("Failed to set y coords");
        array
            .set_coords("x", vec!["a".to_string(), "b".to_string(), "c".to_string()])
            .expect("Failed to set x coords");

        let info = array.info();
        assert!(info.contains("y: Coordinate vector with 2 elements"));
        assert!(info.contains("x: Coordinate vector with 3 elements"));
    }
}