scirs2-core 0.4.3

Core utilities and common functionality for SciRS2 (scirs2-core)
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
//! Implementation of masked arrays for handling missing or invalid data
//!
//! Masked arrays are useful in scientific computing when working with:
//! - Data that contains missing values
//! - Operations that produce invalid results (NaN, Inf)
//! - Operations that should be applied only to a subset of data
//! - Statistical computations that should ignore certain values
//!
//! The implementation is inspired by ``NumPy``'s `MaskedArray` and provides similar functionality
//! in a Rust-native way.

use ::ndarray::{Array, ArrayBase, Data, Dimension, Ix1};
use num_traits::{Float, Zero};
use std::cmp::PartialEq;
use std::fmt;
use std::ops::{Add, Div, Mul, Sub};

/// Error type for array operations
#[derive(Debug, Clone)]
pub enum ArrayError {
    /// Shape mismatch error
    ShapeMismatch {
        expected: Vec<usize>,
        found: Vec<usize>,
        msg: String,
    },
    /// Value error
    ValueError(String),
}

impl std::fmt::Display for ArrayError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::ShapeMismatch {
                expected,
                found,
                msg,
            } => {
                write!(
                    f,
                    "Shape mismatch: expected {expected:?}, found {found:?}: {msg}"
                )
            }
            Self::ValueError(msg) => write!(f, "Value error: {msg}"),
        }
    }
}

impl std::error::Error for ArrayError {}

/// Represents an array with a mask to identify invalid or missing values
#[derive(Clone)]
pub struct MaskedArray<A, S, D>
where
    A: Clone,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    /// The underlying data array
    pub data: ArrayBase<S, D>,

    /// The mask array: true = masked (invalid), false = valid
    pub mask: Array<bool, D>,

    /// The fill value used when creating a filled array
    pub fill_value: A,
}

/// Represents a "no mask" indicator, which is equivalent to an array of all false
pub struct NoMask;

/// The global "no mask" constant
pub const NOMASK: NoMask = NoMask;

impl<A, S, D> MaskedArray<A, S, D>
where
    A: Clone + PartialEq,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    /// Create a new `MaskedArray` from data and mask
    ///
    /// # Errors
    /// Returns `ArrayError::ShapeMismatch` if the mask shape doesn't match the data shape.
    pub fn new(
        data: ArrayBase<S, D>,
        mask: Option<Array<bool, D>>,
        fill_value: Option<A>,
    ) -> Result<Self, ArrayError> {
        let mask = match mask {
            Some(m) => {
                // Validate mask shape matches data shape
                if m.shape() != data.shape() {
                    return Err(ArrayError::ShapeMismatch {
                        expected: data.shape().to_vec(),
                        found: m.shape().to_vec(),
                        msg: "Mask shape must match data shape".to_string(),
                    });
                }
                m
            }
            None => Array::<bool, D>::from_elem(data.raw_dim(), false),
        };

        // Use provided fill value or create a default
        let fill_value = fill_value.unwrap_or_else(|| default_fill_value(&data));

        Ok(Self {
            data,
            mask,
            fill_value,
        })
    }

    /// Get a view of the data with masked values replaced by `fill_value`
    pub fn value_2(&self, fillvalue: Option<A>) -> Array<A, D>
    where
        <D as Dimension>::Pattern: crate::ndarray::NdIndex<D>,
    {
        let fill = fillvalue.unwrap_or_else(|| self.fill_value.clone());

        // Create new array with same shape as data
        let mut result = Array::from_elem(self.data.raw_dim(), fill);

        // Copy unmasked values from original data
        for (i, val) in self.data.iter().enumerate() {
            if !*self.mask.iter().nth(i).unwrap_or(&true) {
                // Only copy if not masked
                if let Some(v) = result.iter_mut().nth(i) {
                    *v = val.clone();
                }
            }
        }

        result
    }

    /// Returns true if the array has at least one masked element
    pub fn has_masked(&self) -> bool {
        self.mask.iter().any(|&x| x)
    }

    /// Returns the count of non-masked elements
    pub fn count(&self) -> usize {
        self.mask.iter().filter(|&&x| !x).count()
    }

    /// Get a copy of the current mask
    pub fn get_mask(&self) -> Array<bool, D> {
        self.mask.clone()
    }

    /// Set a new mask for the array
    ///
    /// # Errors
    /// Returns `ArrayError::ShapeMismatch` if the mask shape doesn't match the data shape.
    pub fn set_mask(&mut self, mask: Array<bool, D>) -> Result<(), ArrayError> {
        // Validate mask shape
        if mask.shape() != self.data.shape() {
            return Err(ArrayError::ShapeMismatch {
                expected: self.data.shape().to_vec(),
                found: mask.shape().to_vec(),
                msg: "Mask shape must match data shape".to_string(),
            });
        }

        self.mask = mask;
        Ok(())
    }

    /// Set the fill value for the array
    pub fn value_3(&mut self, fillvalue: A) {
        self.fill_value = fillvalue;
    }

    /// Returns a new array containing only unmasked values
    pub fn compressed(&self) -> Array<A, Ix1> {
        // Count non-masked elements
        let count = self.count();

        // Create output array
        let mut result = Vec::with_capacity(count);

        // Fill output array with non-masked elements
        for (i, val) in self.data.iter().enumerate() {
            if !self.mask.iter().nth(i).unwrap_or(&true) {
                result.push(val.clone());
            }
        }

        // Convert to ndarray
        Array::from_vec(result)
    }

    /// Returns the shape of the array
    pub fn shape(&self) -> &[usize] {
        self.data.shape()
    }

    /// Returns the number of dimensions of the array
    pub fn ndim(&self) -> usize {
        self.data.ndim()
    }

    /// Returns the number of elements in the array
    pub fn size(&self) -> usize {
        self.data.len()
    }

    /// Returns a tuple of (data, mask)
    pub const fn data_and_mask(&self) -> (&ArrayBase<S, D>, &Array<bool, D>) {
        (&self.data, &self.mask)
    }

    /// Creates a new masked array with the given mask operation applied
    #[must_use]
    pub fn mask_op<F>(&self, op: F) -> Self
    where
        F: Fn(&Array<bool, D>) -> Array<bool, D>,
    {
        let new_mask = op(&self.mask);

        Self {
            data: self.data.clone(),
            mask: new_mask,
            fill_value: self.fill_value.clone(),
        }
    }

    /// Creates a new masked array with a hardened mask (copy)
    #[must_use]
    pub fn harden_mask(&self) -> Self {
        // Create a copy with the same mask
        Self {
            data: self.data.clone(),
            mask: self.mask.clone(),
            fill_value: self.fill_value.clone(),
        }
    }

    /// Create a new masked array with a softened mask (copy)
    #[must_use]
    pub fn soften_mask(&self) -> Self {
        // Create a copy with the same mask
        Self {
            data: self.data.clone(),
            mask: self.mask.clone(),
            fill_value: self.fill_value.clone(),
        }
    }

    /// Create a new masked array where the result of applying the function to each element is masked
    #[must_use]
    pub fn mask_where<F>(&self, condition: F) -> Self
    where
        F: Fn(&A) -> bool,
    {
        // Apply condition to each element of data
        let new_mask = self.data.mapv(|x| condition(&x));

        // Combine with existing mask
        let combined_mask = &self.mask | &new_mask;

        Self {
            data: self.data.clone(),
            mask: combined_mask,
            fill_value: self.fill_value.clone(),
        }
    }

    /// Create a logical OR of the mask with another mask
    ///
    /// # Errors
    /// Returns `ArrayError::ShapeMismatch` if the mask shapes don't match.
    pub fn mask_or(&self, othermask: &Array<bool, D>) -> Result<Self, ArrayError> {
        // Check that shapes match
        if self.mask.shape() != othermask.shape() {
            return Err(ArrayError::ShapeMismatch {
                expected: self.mask.shape().to_vec(),
                found: othermask.shape().to_vec(),
                msg: "Mask shapes must match for mask_or operation".to_string(),
            });
        }

        // Combine masks
        let combined_mask = &self.mask | othermask;

        Ok(Self {
            data: self.data.clone(),
            mask: combined_mask,
            fill_value: self.fill_value.clone(),
        })
    }

    /// Create a logical AND of the mask with another mask
    ///
    /// # Errors
    /// Returns `ArrayError::ShapeMismatch` if the mask shapes don't match.
    pub fn mask_and(&self, othermask: &Array<bool, D>) -> Result<Self, ArrayError> {
        // Check that shapes match
        if self.mask.shape() != othermask.shape() {
            return Err(ArrayError::ShapeMismatch {
                expected: self.mask.shape().to_vec(),
                found: othermask.shape().to_vec(),
                msg: "Mask shapes must match for mask_and operation".to_string(),
            });
        }

        // Combine masks
        let combined_mask = &self.mask & othermask;

        Ok(Self {
            data: self.data.clone(),
            mask: combined_mask,
            fill_value: self.fill_value.clone(),
        })
    }

    /// Reshape the masked array
    ///
    /// # Errors
    /// Returns `ArrayError::ValueError` if the reshape operation fails.
    pub fn reshape<E>(
        &self,
        shape: E,
    ) -> Result<MaskedArray<A, crate::ndarray::OwnedRepr<A>, E>, ArrayError>
    where
        E: Dimension,
        D: Dimension,
    {
        // Try to reshape the data and mask
        let reshaped_data = match self.data.clone().into_shape_with_order(shape.clone()) {
            Ok(d) => d,
            Err(e) => {
                return Err(ArrayError::ValueError(format!(
                    "Failed to reshape data: {e}"
                )))
            }
        };

        let reshaped_mask = match self.mask.clone().into_shape_with_order(shape) {
            Ok(m) => m,
            Err(e) => {
                return Err(ArrayError::ValueError(format!(
                    "Failed to reshape mask: {e}"
                )))
            }
        };

        Ok(MaskedArray {
            data: reshaped_data.into_owned(),
            mask: reshaped_mask,
            fill_value: self.fill_value.clone(),
        })
    }

    /// Convert to a different type
    ///
    /// # Errors
    /// Currently this method doesn't return errors, but the signature is kept for future compatibility.
    pub fn astype<B>(&self) -> Result<MaskedArray<B, crate::ndarray::OwnedRepr<B>, D>, ArrayError>
    where
        A: Into<B> + Clone,
        B: Clone + PartialEq + 'static,
    {
        // Convert each element
        let converted_data = self.data.mapv(std::convert::Into::into);

        Ok(MaskedArray {
            data: converted_data,
            mask: self.mask.clone(),
            fill_value: self.fill_value.clone().into(),
        })
    }
}

/// Implementation of statistical methods
impl<A, S, D> MaskedArray<A, S, D>
where
    A: Clone + PartialEq + num_traits::NumAssign + num_traits::Zero + num_traits::One + PartialOrd,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    /// Compute the sum of all unmasked elements
    pub fn sum(&self) -> A {
        let mut sum = A::zero();

        for (i, val) in self.data.iter().enumerate() {
            if !*self.mask.iter().nth(i).unwrap_or(&true) {
                sum += val.clone();
            }
        }

        sum
    }

    /// Compute the product of all unmasked elements
    pub fn product(&self) -> A {
        let mut product = A::one();

        for (i, val) in self.data.iter().enumerate() {
            if !*self.mask.iter().nth(i).unwrap_or(&true) {
                product *= val.clone();
            }
        }

        product
    }

    /// Find the minimum value among unmasked elements
    pub fn min(&self) -> Option<A> {
        let mut min_val = None;

        for (i, val) in self.data.iter().enumerate() {
            if !*self.mask.iter().nth(i).unwrap_or(&true) {
                if let Some(ref current_min) = min_val {
                    if val < current_min {
                        min_val = Some(val.clone());
                    }
                } else {
                    min_val = Some(val.clone());
                }
            }
        }

        min_val
    }

    /// Find the maximum value among unmasked elements
    pub fn max(&self) -> Option<A> {
        let mut max_val = None;

        for (i, val) in self.data.iter().enumerate() {
            if !*self.mask.iter().nth(i).unwrap_or(&true) {
                if let Some(ref current_max) = max_val {
                    if val > current_max {
                        max_val = Some(val.clone());
                    }
                } else {
                    max_val = Some(val.clone());
                }
            }
        }

        max_val
    }

    /// Find the index of the minimum value among unmasked elements
    pub fn argmin(&self) -> Option<usize> {
        let mut min_idx = None;
        let mut min_val = None;

        for (i, val) in self.data.iter().enumerate() {
            if !*self.mask.iter().nth(i).unwrap_or(&true) {
                if let Some(ref current_min) = min_val {
                    if val < current_min {
                        min_val = Some(val.clone());
                        min_idx = Some(i);
                    }
                } else {
                    min_val = Some(val.clone());
                    min_idx = Some(0);
                }
            }
        }

        min_idx
    }

    /// Find the index of the maximum value among unmasked elements
    pub fn argmax(&self) -> Option<usize> {
        let mut max_idx = None;
        let mut max_val = None;

        for (i, val) in self.data.iter().enumerate() {
            if !*self.mask.iter().nth(i).unwrap_or(&true) {
                if let Some(ref current_max) = max_val {
                    if val > current_max {
                        max_val = Some(val.clone());
                        max_idx = Some(i);
                    }
                } else {
                    max_val = Some(val.clone());
                    max_idx = Some(0);
                }
            }
        }

        max_idx
    }
}

/// Implementation of statistical methods for floating point types
impl<A, S, D> MaskedArray<A, S, D>
where
    A: Clone + PartialEq + num_traits::Float + std::iter::Sum<A>,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    /// Compute the mean of all unmasked elements
    ///
    /// Returns `None` if there are no unmasked elements or if count conversion fails.
    pub fn mean(&self) -> Option<A> {
        let count = self.count();

        if count == 0 {
            return None;
        }

        let sum: A = self
            .data
            .iter()
            .enumerate()
            .filter(|(i, _)| !*self.mask.iter().nth(*i).unwrap_or(&true))
            .map(|(_, val)| *val)
            .sum();

        // Safe conversion with proper error handling
        A::from(count).map(|count_val| sum / count_val)
    }

    /// Compute the variance of all unmasked elements
    ///
    /// Returns `None` if there are insufficient unmasked elements or if count conversion fails.
    pub fn var(&self, ddof: usize) -> Option<A> {
        let count = self.count();

        if count <= ddof {
            return None;
        }

        // Calculate mean
        let mean = self.mean()?;

        // Calculate sum of squared differences
        let sum_sq_diff: A = self
            .data
            .iter()
            .enumerate()
            .filter(|(i, _)| !*self.mask.iter().nth(*i).unwrap_or(&true))
            .map(|(_, val)| (*val - mean) * (*val - mean))
            .sum();

        // Apply degrees of freedom correction with safe conversion
        A::from(count - ddof).map(|denom| sum_sq_diff / denom)
    }

    /// Compute the standard deviation of all unmasked elements
    pub fn std(&self, ddof: usize) -> Option<A> {
        self.var(ddof).map(num_traits::Float::sqrt)
    }

    /// Check if all unmasked elements are finite
    pub fn all_finite(&self) -> bool {
        self.data
            .iter()
            .enumerate()
            .filter(|(i, _)| !*self.mask.iter().nth(*i).unwrap_or(&true))
            .all(|(_, val)| val.is_finite())
    }
}

/// Helper function to create a default fill value for a given type
#[allow(dead_code)]
fn default_fill_value<A, S, D>(data: &ArrayBase<S, D>) -> A
where
    A: Clone,
    S: Data<Elem = A>,
    D: Dimension,
{
    // In a real implementation, this would use type traits to determine
    // appropriate default values based on the type (like `NumPy` does)
    data.iter().next().map_or_else(
        || {
            // This is a placeholder - in reality you'd need to handle this by type
            panic!("Cannot determine default fill value for empty array");
        },
        std::clone::Clone::clone,
    )
}

/// Function to check if a value is masked
pub const fn is_masked<A>(value: &A) -> bool
where
    A: PartialEq,
{
    // In `NumPy` this would check against the masked singleton
    // Here we just return false as a placeholder
    false
}

/// Create a masked array with elements equal to a given value masked
#[allow(dead_code)]
pub fn masked_equal<A, S, D>(data: ArrayBase<S, D>, value: A) -> MaskedArray<A, S, D>
where
    A: Clone + PartialEq,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    // Create a mask indicating where elements equal the value
    let mask = data.mapv(|x| x == value);

    MaskedArray {
        data,
        mask,
        fill_value: value,
    }
}

/// Create a masked array with NaN and infinite values masked
#[allow(dead_code)]
pub fn masked_invalid<A, S, D>(data: ArrayBase<S, D>) -> MaskedArray<A, S, D>
where
    A: Clone + PartialEq + Float,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    // Create a mask indicating where elements are NaN or infinite
    let mask = data.mapv(|val| val.is_nan() || val.is_infinite());

    let fill_value = A::nan();

    MaskedArray {
        data,
        mask,
        fill_value,
    }
}

/// Create a masked array
///
/// # Errors
/// Returns `ArrayError::ShapeMismatch` if the mask shape doesn't match the data shape.
#[allow(dead_code)]
pub fn mask_array<A, S, D>(
    data: ArrayBase<S, D>,
    mask: Option<Array<bool, D>>,
    fill_value: Option<A>,
) -> Result<MaskedArray<A, S, D>, ArrayError>
where
    A: Clone + PartialEq,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    MaskedArray::new(data, mask, fill_value)
}

/// Create a masked array with values outside a range masked
#[allow(dead_code)]
pub fn masked_outside<A, S, D>(
    data: ArrayBase<S, D>,
    min_val: &A,
    max_val: &A,
) -> MaskedArray<A, S, D>
where
    A: Clone + PartialEq + PartialOrd,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    // Create a mask indicating where elements are outside the range
    let mask = data.mapv(|x| x < *min_val || x > *max_val);

    // Choose a fill value (using min_val as default)
    let fill_value = min_val.clone();

    MaskedArray {
        data,
        mask,
        fill_value,
    }
}

/// Create a masked array with values inside a range masked
#[allow(dead_code)]
pub fn masked_inside<A, S, D>(
    data: ArrayBase<S, D>,
    min_val: &A,
    max_val: &A,
) -> MaskedArray<A, S, D>
where
    A: Clone + PartialEq + PartialOrd,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    // Create a mask indicating where elements are inside the range
    let mask = data.mapv(|x| x >= *min_val && x <= *max_val);

    // Choose a fill value (using min_val as default)
    let fill_value = min_val.clone();

    MaskedArray {
        data,
        mask,
        fill_value,
    }
}

/// Create a masked array with values greater than a given value masked
#[allow(dead_code)]
pub fn masked_greater<A, S, D>(data: ArrayBase<S, D>, value: &A) -> MaskedArray<A, S, D>
where
    A: Clone + PartialEq + PartialOrd,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    // Create a mask indicating where elements are greater than the value
    let mask = data.mapv(|x| x > *value);

    // Use the specified value as fill_value
    let fill_value = value.clone();

    MaskedArray {
        data,
        mask,
        fill_value,
    }
}

/// Create a masked array with values less than a given value masked
#[allow(dead_code)]
pub fn masked_less<A, S, D>(data: ArrayBase<S, D>, value: &A) -> MaskedArray<A, S, D>
where
    A: Clone + PartialEq + PartialOrd,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    // Create a mask indicating where elements are less than the value
    let mask = data.mapv(|x| x < *value);

    // Use the specified value as fill_value
    let fill_value = value.clone();

    MaskedArray {
        data,
        mask,
        fill_value,
    }
}

/// Create a masked array with values where a condition is true
#[allow(dead_code)]
pub fn masked_where<A, S, D, F>(
    condition: F,
    data: ArrayBase<S, D>,
    fill_value: Option<A>,
) -> MaskedArray<A, S, D>
where
    A: Clone + PartialEq,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
    F: Fn(&A) -> bool,
{
    // Create a mask by applying the condition function to each element
    let mask = data.map(condition);

    // Use provided fill value or create a default
    let fill_value = fill_value.unwrap_or_else(|| default_fill_value(&data));

    MaskedArray {
        data,
        mask,
        fill_value,
    }
}

/// Implementation of Display for `MaskedArray`
impl<A, S, D> fmt::Display for MaskedArray<A, S, D>
where
    A: Clone + PartialEq + fmt::Display,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(f, "MaskedArray(")?;

        writeln!(f, "  data=[")?;
        for (i, elem) in self.data.iter().enumerate() {
            if i > 0 && i % 10 == 0 {
                writeln!(f)?;
            }
            if *self.mask.iter().nth(0).unwrap_or(&false) {
                write!(f, " --,")?;
            } else {
                write!(f, " {elem},")?;
            }
        }
        writeln!(f, "\n  ],")?;

        writeln!(f, "  mask=[")?;
        for (i, &elem) in self.mask.iter().enumerate() {
            if i > 0 && i % 10 == 0 {
                writeln!(f)?;
            }
            write!(f, " {elem},")?;
        }
        writeln!(f, "\n  ],")?;

        writeln!(f, "  fill_value={}", self.fill_value)?;
        write!(f, ")")
    }
}

/// Implementation of Debug for `MaskedArray`
impl<A, S, D> fmt::Debug for MaskedArray<A, S, D>
where
    A: Clone + PartialEq + fmt::Debug,
    S: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("MaskedArray")
            .field("data", &self.data)
            .field("mask", &self.mask)
            .field("fill_value", &self.fill_value)
            .finish()
    }
}

// Arithmetic operations for MaskedArray
// These could be expanded to handle more operations and types

impl<A, S1, S2, D> Add<&MaskedArray<A, S2, D>> for &MaskedArray<A, S1, D>
where
    A: Clone + Add<Output = A> + PartialEq,
    S1: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    S2: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    type Output = MaskedArray<A, crate::ndarray::OwnedRepr<A>, D>;

    fn add(self, rhs: &MaskedArray<A, S2, D>) -> Self::Output {
        // Create combined mask: true if either input is masked
        let combined_mask = &self.mask | &rhs.mask;

        // Create output data by adding input data
        let data = &self.data + &rhs.data;

        MaskedArray {
            data,
            mask: combined_mask,
            fill_value: self.fill_value.clone(),
        }
    }
}

impl<A, S1, S2, D> Sub<&MaskedArray<A, S2, D>> for &MaskedArray<A, S1, D>
where
    A: Clone + Sub<Output = A> + PartialEq,
    S1: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    S2: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    type Output = MaskedArray<A, crate::ndarray::OwnedRepr<A>, D>;

    fn sub(self, rhs: &MaskedArray<A, S2, D>) -> Self::Output {
        // Create combined mask: true if either input is masked
        let combined_mask = &self.mask | &rhs.mask;

        // Create output data by subtracting input data
        let data = &self.data - &rhs.data;

        MaskedArray {
            data,
            mask: combined_mask,
            fill_value: self.fill_value.clone(),
        }
    }
}

impl<A, S1, S2, D> Mul<&MaskedArray<A, S2, D>> for &MaskedArray<A, S1, D>
where
    A: Clone + Mul<Output = A> + PartialEq,
    S1: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    S2: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    type Output = MaskedArray<A, crate::ndarray::OwnedRepr<A>, D>;

    fn mul(self, rhs: &MaskedArray<A, S2, D>) -> Self::Output {
        // Create combined mask: true if either input is masked
        let combined_mask = &self.mask | &rhs.mask;

        // Create output data by multiplying input data
        let data = &self.data * &rhs.data;

        MaskedArray {
            data,
            mask: combined_mask,
            fill_value: self.fill_value.clone(),
        }
    }
}

impl<A, S1, S2, D> Div<&MaskedArray<A, S2, D>> for &MaskedArray<A, S1, D>
where
    A: Clone + Div<Output = A> + PartialEq + Zero,
    S1: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    S2: Data<Elem = A> + Clone + crate::ndarray::RawDataClone,
    D: Dimension,
{
    type Output = MaskedArray<A, crate::ndarray::OwnedRepr<A>, D>;

    fn div(self, rhs: &MaskedArray<A, S2, D>) -> Self::Output {
        // Create combined mask: true if either input is masked or rhs is zero
        let mut combined_mask = &self.mask | &rhs.mask;

        // Also mask division by zero
        let zero = A::zero();
        let additional_mask = rhs.data.mapv(|x| x == zero);

        // Update combined mask to also mask division by zero
        combined_mask = combined_mask | additional_mask;

        // Create output data by dividing input data
        let data = &self.data / &rhs.data;

        MaskedArray {
            data,
            mask: combined_mask,
            fill_value: self.fill_value.clone(),
        }
    }
}

// Add more arithmetic operations as needed

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

    #[test]
    fn test_masked_array_creation() {
        let data = array![1.0, 2.0, 3.0, 4.0, 5.0];
        let mask = array![false, true, false, true, false];

        let ma = MaskedArray::new(data.clone(), Some(mask.clone()), None)
            .expect("Failed to create MaskedArray in test");

        assert_eq!(ma.data, data);
        assert_eq!(ma.mask, mask);
        assert_eq!(ma.count(), 3);
        assert!(ma.has_masked());
    }

    #[test]
    fn test_masked_array_filled() {
        let data = array![1.0, 2.0, 3.0, 4.0, 5.0];
        let mask = array![false, true, false, true, false];

        let ma = MaskedArray::new(data, Some(mask), Some(999.0))
            .expect("Failed to create MaskedArray in test");

        let filled = ma.value_2(None);
        assert_eq!(filled, array![1.0, 999.0, 3.0, 999.0, 5.0]);

        let filled_custom = ma.value_2(Some(-1.0));
        assert_eq!(filled_custom, array![1.0, -1.0, 3.0, -1.0, 5.0]);
    }

    #[test]
    fn test_masked_equal() {
        let data = array![1.0, 2.0, 3.0, 2.0, 5.0];

        let ma = masked_equal(data, 2.0);

        assert_eq!(ma.mask, array![false, true, false, true, false]);
        assert_eq!(ma.count(), 3);
    }

    #[test]
    fn test_masked_invalid() {
        let data = array![1.0, f64::NAN, 3.0, f64::INFINITY, 5.0];

        let ma = masked_invalid(data);

        // Cannot directly compare masks with NaN values using assert_eq
        // So we check each element individually
        assert!(!ma.mask[0]); // 1.0 is valid
        assert!(ma.mask[1]); // NaN is invalid
        assert!(!ma.mask[2]); // 3.0 is valid
        assert!(ma.mask[3]); // INFINITY is invalid
        assert!(!ma.mask[4]); // 5.0 is valid

        assert_eq!(ma.count(), 3);
    }

    #[test]
    fn test_masked_array_arithmetic() {
        let a = MaskedArray::new(
            array![1.0, 2.0, 3.0, 4.0, 5.0],
            Some(array![false, true, false, false, false]),
            Some(0.0),
        )
        .expect("Failed to create MaskedArray in test");

        let b = MaskedArray::new(
            array![5.0, 4.0, 3.0, 2.0, 1.0],
            Some(array![false, false, false, true, false]),
            Some(0.0),
        )
        .expect("Failed to create MaskedArray in test");

        // Addition
        let c = &a + &b;
        assert_eq!(c.data, array![6.0, 6.0, 6.0, 6.0, 6.0]);
        assert_eq!(c.mask, array![false, true, false, true, false]);

        // Subtraction
        let d = &a - &b;
        assert_eq!(d.data, array![-4.0, -2.0, 0.0, 2.0, 4.0]);
        assert_eq!(d.mask, array![false, true, false, true, false]);

        // Multiplication
        let e = &a * &b;
        assert_eq!(e.data, array![5.0, 8.0, 9.0, 8.0, 5.0]);
        assert_eq!(e.mask, array![false, true, false, true, false]);

        // Division
        let f = &a / &b;
        assert_eq!(f.data, array![0.2, 0.5, 1.0, 2.0, 5.0]);
        assert_eq!(f.mask, array![false, true, false, true, false]);

        // Division by zero
        let g = MaskedArray::new(
            array![1.0, 2.0, 3.0],
            Some(array![false, false, false]),
            Some(0.0),
        )
        .expect("Failed to create MaskedArray in test");

        let h = MaskedArray::new(
            array![1.0, 0.0, 3.0],
            Some(array![false, false, false]),
            Some(0.0),
        )
        .expect("Failed to create MaskedArray in test");

        let i = &g / &h;
        assert_eq!(i.mask, array![false, true, false]);
    }

    #[test]
    fn test_compressed() {
        let ma = MaskedArray::new(
            array![1.0, 2.0, 3.0, 4.0, 5.0],
            Some(array![false, true, false, true, false]),
            Some(0.0),
        )
        .expect("Failed to create MaskedArray in test");

        let compressed = ma.compressed();
        assert_eq!(compressed, array![1.0, 3.0, 5.0]);
    }
}