Skip to main content

fdars_core/
fdata.rs

1//! Functional data operations: mean, center, derivatives, norms, and geometric median.
2
3use crate::helpers::{simpsons_weights, simpsons_weights_2d, NUMERICAL_EPS};
4use crate::iter_maybe_parallel;
5use crate::matrix::FdMatrix;
6#[cfg(feature = "parallel")]
7use rayon::iter::ParallelIterator;
8
9/// Compute finite difference for a 1D function at a given index.
10///
11/// Uses forward difference at left boundary, backward difference at right boundary,
12/// and central difference for interior points.
13fn finite_diff_1d(
14    values: impl Fn(usize) -> f64,
15    idx: usize,
16    n_points: usize,
17    step_sizes: &[f64],
18) -> f64 {
19    if idx == 0 {
20        (values(1) - values(0)) / step_sizes[0]
21    } else if idx == n_points - 1 {
22        (values(n_points - 1) - values(n_points - 2)) / step_sizes[n_points - 1]
23    } else {
24        (values(idx + 1) - values(idx - 1)) / step_sizes[idx]
25    }
26}
27
28/// Compute 2D partial derivatives at a single grid point.
29///
30/// Returns (∂f/∂s, ∂f/∂t, ∂²f/∂s∂t) using finite differences.
31fn compute_2d_derivatives(
32    get_val: impl Fn(usize, usize) -> f64,
33    si: usize,
34    ti: usize,
35    m1: usize,
36    m2: usize,
37    hs: &[f64],
38    ht: &[f64],
39) -> (f64, f64, f64) {
40    // ∂f/∂s
41    let ds = finite_diff_1d(|s| get_val(s, ti), si, m1, hs);
42
43    // ∂f/∂t
44    let dt = finite_diff_1d(|t| get_val(si, t), ti, m2, ht);
45
46    // ∂²f/∂s∂t (mixed partial)
47    let denom = hs[si] * ht[ti];
48
49    // Get the appropriate indices for s and t differences
50    let (s_lo, s_hi) = if si == 0 {
51        (0, 1)
52    } else if si == m1 - 1 {
53        (m1 - 2, m1 - 1)
54    } else {
55        (si - 1, si + 1)
56    };
57
58    let (t_lo, t_hi) = if ti == 0 {
59        (0, 1)
60    } else if ti == m2 - 1 {
61        (m2 - 2, m2 - 1)
62    } else {
63        (ti - 1, ti + 1)
64    };
65
66    let dsdt = (get_val(s_hi, t_hi) - get_val(s_lo, t_hi) - get_val(s_hi, t_lo)
67        + get_val(s_lo, t_lo))
68        / denom;
69
70    (ds, dt, dsdt)
71}
72
73/// Perform Weiszfeld iteration to compute geometric median.
74///
75/// This is the core algorithm shared by 1D and 2D geometric median computations.
76fn weiszfeld_iteration(data: &FdMatrix, weights: &[f64], max_iter: usize, tol: f64) -> Vec<f64> {
77    let (n, m) = data.shape();
78
79    // Initialize with the mean
80    let mut median: Vec<f64> = (0..m)
81        .map(|j| {
82            let col = data.column(j);
83            col.iter().sum::<f64>() / n as f64
84        })
85        .collect();
86
87    for _ in 0..max_iter {
88        // Compute distances from current median to all curves
89        let distances: Vec<f64> = (0..n)
90            .map(|i| {
91                let mut dist_sq = 0.0;
92                for j in 0..m {
93                    let diff = data[(i, j)] - median[j];
94                    dist_sq += diff * diff * weights[j];
95                }
96                dist_sq.sqrt()
97            })
98            .collect();
99
100        // Compute weights (1/distance), handling zero distances
101        let inv_distances: Vec<f64> = distances
102            .iter()
103            .map(|d| {
104                if *d > NUMERICAL_EPS {
105                    1.0 / d
106                } else {
107                    1.0 / NUMERICAL_EPS
108                }
109            })
110            .collect();
111
112        let sum_inv_dist: f64 = inv_distances.iter().sum();
113
114        // Update median using Weiszfeld iteration
115        let new_median: Vec<f64> = (0..m)
116            .map(|j| {
117                let mut weighted_sum = 0.0;
118                for i in 0..n {
119                    weighted_sum += data[(i, j)] * inv_distances[i];
120                }
121                weighted_sum / sum_inv_dist
122            })
123            .collect();
124
125        // Check convergence
126        let diff: f64 = median
127            .iter()
128            .zip(new_median.iter())
129            .map(|(a, b)| (a - b).abs())
130            .sum::<f64>()
131            / m as f64;
132
133        median = new_median;
134
135        if diff < tol {
136            break;
137        }
138    }
139
140    median
141}
142
143/// Compute the mean function across all samples (1D).
144///
145/// # Arguments
146/// * `data` - Functional data matrix (n x m)
147///
148/// # Returns
149/// Mean function values at each evaluation point
150pub fn mean_1d(data: &FdMatrix) -> Vec<f64> {
151    let (n, m) = data.shape();
152    if n == 0 || m == 0 {
153        return Vec::new();
154    }
155
156    iter_maybe_parallel!(0..m)
157        .map(|j| {
158            let col = data.column(j);
159            col.iter().sum::<f64>() / n as f64
160        })
161        .collect()
162}
163
164/// Compute the mean function for 2D surfaces.
165///
166/// Data is stored as n x (m1*m2) matrix where each row is a flattened surface.
167pub fn mean_2d(data: &FdMatrix) -> Vec<f64> {
168    // Same computation as 1D - just compute pointwise mean
169    mean_1d(data)
170}
171
172/// Center functional data by subtracting the mean function.
173///
174/// # Arguments
175/// * `data` - Functional data matrix (n x m)
176///
177/// # Returns
178/// Centered data matrix
179pub fn center_1d(data: &FdMatrix) -> FdMatrix {
180    let (n, m) = data.shape();
181    if n == 0 || m == 0 {
182        return FdMatrix::zeros(0, 0);
183    }
184
185    // First compute the mean for each column (parallelized)
186    let means: Vec<f64> = iter_maybe_parallel!(0..m)
187        .map(|j| {
188            let col = data.column(j);
189            col.iter().sum::<f64>() / n as f64
190        })
191        .collect();
192
193    // Create centered data
194    let mut centered = FdMatrix::zeros(n, m);
195    for j in 0..m {
196        let col = centered.column_mut(j);
197        let src = data.column(j);
198        for i in 0..n {
199            col[i] = src[i] - means[j];
200        }
201    }
202
203    centered
204}
205
206/// Compute Lp norm for each sample.
207///
208/// # Arguments
209/// * `data` - Functional data matrix (n x m)
210/// * `argvals` - Evaluation points for integration
211/// * `p` - Order of the norm (e.g., 2.0 for L2)
212///
213/// # Returns
214/// Vector of Lp norms for each sample
215pub fn norm_lp_1d(data: &FdMatrix, argvals: &[f64], p: f64) -> Vec<f64> {
216    let (n, m) = data.shape();
217    if n == 0 || m == 0 || argvals.len() != m {
218        return Vec::new();
219    }
220
221    let weights = simpsons_weights(argvals);
222
223    if (p - 2.0).abs() < 1e-14 {
224        iter_maybe_parallel!(0..n)
225            .map(|i| {
226                let mut integral = 0.0;
227                for j in 0..m {
228                    let v = data[(i, j)];
229                    integral += v * v * weights[j];
230                }
231                integral.sqrt()
232            })
233            .collect()
234    } else if (p - 1.0).abs() < 1e-14 {
235        iter_maybe_parallel!(0..n)
236            .map(|i| {
237                let mut integral = 0.0;
238                for j in 0..m {
239                    integral += data[(i, j)].abs() * weights[j];
240                }
241                integral
242            })
243            .collect()
244    } else {
245        iter_maybe_parallel!(0..n)
246            .map(|i| {
247                let mut integral = 0.0;
248                for j in 0..m {
249                    integral += data[(i, j)].abs().powf(p) * weights[j];
250                }
251                integral.powf(1.0 / p)
252            })
253            .collect()
254    }
255}
256
257/// Compute numerical derivative of functional data (parallelized over rows).
258///
259/// # Arguments
260/// * `data` - Functional data matrix (n x m)
261/// * `argvals` - Evaluation points
262/// * `nderiv` - Order of derivative
263///
264/// # Returns
265/// Derivative data matrix
266/// Compute one derivative step: forward/central/backward differences written column-wise.
267fn deriv_1d_step(current: &FdMatrix, n: usize, m: usize, h0: f64, hn: f64, h_central: &[f64]) -> FdMatrix {
268    let mut next = FdMatrix::zeros(n, m);
269    // Column 0: forward difference
270    let src_col0 = current.column(0);
271    let src_col1 = current.column(1);
272    let dst = next.column_mut(0);
273    for i in 0..n {
274        dst[i] = (src_col1[i] - src_col0[i]) / h0;
275    }
276    // Interior columns: central difference
277    for j in 1..(m - 1) {
278        let src_prev = current.column(j - 1);
279        let src_next = current.column(j + 1);
280        let dst = next.column_mut(j);
281        let h = h_central[j - 1];
282        for i in 0..n {
283            dst[i] = (src_next[i] - src_prev[i]) / h;
284        }
285    }
286    // Column m-1: backward difference
287    let src_colm2 = current.column(m - 2);
288    let src_colm1 = current.column(m - 1);
289    let dst = next.column_mut(m - 1);
290    for i in 0..n {
291        dst[i] = (src_colm1[i] - src_colm2[i]) / hn;
292    }
293    next
294}
295
296pub fn deriv_1d(data: &FdMatrix, argvals: &[f64], nderiv: usize) -> FdMatrix {
297    let (n, m) = data.shape();
298    if n == 0 || m == 0 || argvals.len() != m || nderiv < 1 {
299        return FdMatrix::zeros(n, m);
300    }
301
302    let mut current = data.clone();
303
304    // Pre-compute step sizes for central differences
305    let h0 = argvals[1] - argvals[0];
306    let hn = argvals[m - 1] - argvals[m - 2];
307    let h_central: Vec<f64> = (1..(m - 1))
308        .map(|j| argvals[j + 1] - argvals[j - 1])
309        .collect();
310
311    for _ in 0..nderiv {
312        current = deriv_1d_step(&current, n, m, h0, hn, &h_central);
313    }
314
315    current
316}
317
318/// Result of 2D partial derivatives.
319pub struct Deriv2DResult {
320    /// Partial derivative with respect to s (∂f/∂s)
321    pub ds: FdMatrix,
322    /// Partial derivative with respect to t (∂f/∂t)
323    pub dt: FdMatrix,
324    /// Mixed partial derivative (∂²f/∂s∂t)
325    pub dsdt: FdMatrix,
326}
327
328/// Compute finite-difference step sizes for a grid.
329///
330/// Uses forward/backward difference at boundaries and central difference for interior.
331fn compute_step_sizes(argvals: &[f64]) -> Vec<f64> {
332    let m = argvals.len();
333    (0..m)
334        .map(|j| {
335            if j == 0 {
336                argvals[1] - argvals[0]
337            } else if j == m - 1 {
338                argvals[m - 1] - argvals[m - 2]
339            } else {
340                argvals[j + 1] - argvals[j - 1]
341            }
342        })
343        .collect()
344}
345
346/// Collect per-curve row vectors into a column-major FdMatrix.
347fn reassemble_colmajor(rows: &[Vec<f64>], n: usize, ncol: usize) -> FdMatrix {
348    let mut mat = FdMatrix::zeros(n, ncol);
349    for i in 0..n {
350        for j in 0..ncol {
351            mat[(i, j)] = rows[i][j];
352        }
353    }
354    mat
355}
356
357/// Compute 2D partial derivatives for surface data.
358///
359/// For a surface f(s,t), computes:
360/// - ds: partial derivative with respect to s (∂f/∂s)
361/// - dt: partial derivative with respect to t (∂f/∂t)
362/// - dsdt: mixed partial derivative (∂²f/∂s∂t)
363///
364/// # Arguments
365/// * `data` - Functional data matrix, n surfaces, each stored as m1*m2 values
366/// * `argvals_s` - Grid points in s direction (length m1)
367/// * `argvals_t` - Grid points in t direction (length m2)
368/// * `m1` - Grid size in s direction
369/// * `m2` - Grid size in t direction
370pub fn deriv_2d(
371    data: &FdMatrix,
372    argvals_s: &[f64],
373    argvals_t: &[f64],
374    m1: usize,
375    m2: usize,
376) -> Option<Deriv2DResult> {
377    let n = data.nrows();
378    let ncol = m1 * m2;
379    if n == 0 || ncol == 0 || argvals_s.len() != m1 || argvals_t.len() != m2 {
380        return None;
381    }
382
383    let hs = compute_step_sizes(argvals_s);
384    let ht = compute_step_sizes(argvals_t);
385
386    // Compute all derivatives in parallel over surfaces
387    let results: Vec<(Vec<f64>, Vec<f64>, Vec<f64>)> = iter_maybe_parallel!(0..n)
388        .map(|i| {
389            let mut ds = vec![0.0; ncol];
390            let mut dt = vec![0.0; ncol];
391            let mut dsdt = vec![0.0; ncol];
392
393            let get_val = |si: usize, ti: usize| -> f64 { data[(i, si + ti * m1)] };
394
395            for ti in 0..m2 {
396                for si in 0..m1 {
397                    let idx = si + ti * m1;
398                    let (ds_val, dt_val, dsdt_val) =
399                        compute_2d_derivatives(get_val, si, ti, m1, m2, &hs, &ht);
400                    ds[idx] = ds_val;
401                    dt[idx] = dt_val;
402                    dsdt[idx] = dsdt_val;
403                }
404            }
405
406            (ds, dt, dsdt)
407        })
408        .collect();
409
410    let (ds_vecs, (dt_vecs, dsdt_vecs)): (Vec<Vec<f64>>, (Vec<Vec<f64>>, Vec<Vec<f64>>)) =
411        results.into_iter().map(|(a, b, c)| (a, (b, c))).unzip();
412
413    Some(Deriv2DResult {
414        ds: reassemble_colmajor(&ds_vecs, n, ncol),
415        dt: reassemble_colmajor(&dt_vecs, n, ncol),
416        dsdt: reassemble_colmajor(&dsdt_vecs, n, ncol),
417    })
418}
419
420/// Compute the geometric median (L1 median) of functional data using Weiszfeld's algorithm.
421///
422/// The geometric median minimizes sum of L2 distances to all curves.
423///
424/// # Arguments
425/// * `data` - Functional data matrix (n x m)
426/// * `argvals` - Evaluation points for integration
427/// * `max_iter` - Maximum iterations
428/// * `tol` - Convergence tolerance
429pub fn geometric_median_1d(
430    data: &FdMatrix,
431    argvals: &[f64],
432    max_iter: usize,
433    tol: f64,
434) -> Vec<f64> {
435    let (n, m) = data.shape();
436    if n == 0 || m == 0 || argvals.len() != m {
437        return Vec::new();
438    }
439
440    let weights = simpsons_weights(argvals);
441    weiszfeld_iteration(data, &weights, max_iter, tol)
442}
443
444/// Compute the geometric median for 2D functional data.
445///
446/// Data is stored as n x (m1*m2) matrix where each row is a flattened surface.
447///
448/// # Arguments
449/// * `data` - Functional data matrix (n x m) where m = m1*m2
450/// * `argvals_s` - Grid points in s direction (length m1)
451/// * `argvals_t` - Grid points in t direction (length m2)
452/// * `max_iter` - Maximum iterations
453/// * `tol` - Convergence tolerance
454pub fn geometric_median_2d(
455    data: &FdMatrix,
456    argvals_s: &[f64],
457    argvals_t: &[f64],
458    max_iter: usize,
459    tol: f64,
460) -> Vec<f64> {
461    let (n, m) = data.shape();
462    let expected_cols = argvals_s.len() * argvals_t.len();
463    if n == 0 || m == 0 || m != expected_cols {
464        return Vec::new();
465    }
466
467    let weights = simpsons_weights_2d(argvals_s, argvals_t);
468    weiszfeld_iteration(data, &weights, max_iter, tol)
469}
470
471#[cfg(test)]
472mod tests {
473    use super::*;
474    use std::f64::consts::PI;
475
476    fn uniform_grid(n: usize) -> Vec<f64> {
477        (0..n).map(|i| i as f64 / (n - 1) as f64).collect()
478    }
479
480    // ============== Mean tests ==============
481
482    #[test]
483    fn test_mean_1d() {
484        // 2 samples, 3 points each
485        // Sample 1: [1, 2, 3]
486        // Sample 2: [3, 4, 5]
487        // Mean should be [2, 3, 4]
488        let data = vec![1.0, 3.0, 2.0, 4.0, 3.0, 5.0]; // column-major
489        let mat = FdMatrix::from_column_major(data, 2, 3).unwrap();
490        let mean = mean_1d(&mat);
491        assert_eq!(mean, vec![2.0, 3.0, 4.0]);
492    }
493
494    #[test]
495    fn test_mean_1d_single_sample() {
496        let data = vec![1.0, 2.0, 3.0];
497        let mat = FdMatrix::from_column_major(data, 1, 3).unwrap();
498        let mean = mean_1d(&mat);
499        assert_eq!(mean, vec![1.0, 2.0, 3.0]);
500    }
501
502    #[test]
503    fn test_mean_1d_invalid() {
504        assert!(mean_1d(&FdMatrix::zeros(0, 0)).is_empty());
505    }
506
507    #[test]
508    fn test_mean_2d_delegates() {
509        let data = vec![1.0, 3.0, 2.0, 4.0];
510        let mat = FdMatrix::from_column_major(data, 2, 2).unwrap();
511        let mean1d = mean_1d(&mat);
512        let mean2d = mean_2d(&mat);
513        assert_eq!(mean1d, mean2d);
514    }
515
516    // ============== Center tests ==============
517
518    #[test]
519    fn test_center_1d() {
520        let data = vec![1.0, 3.0, 2.0, 4.0, 3.0, 5.0]; // column-major
521        let mat = FdMatrix::from_column_major(data, 2, 3).unwrap();
522        let centered = center_1d(&mat);
523        // Mean is [2, 3, 4], so centered should be [-1, 1, -1, 1, -1, 1]
524        assert_eq!(centered.as_slice(), &[-1.0, 1.0, -1.0, 1.0, -1.0, 1.0]);
525    }
526
527    #[test]
528    fn test_center_1d_mean_zero() {
529        let data = vec![1.0, 3.0, 2.0, 4.0, 3.0, 5.0];
530        let mat = FdMatrix::from_column_major(data, 2, 3).unwrap();
531        let centered = center_1d(&mat);
532        let centered_mean = mean_1d(&centered);
533        for m in centered_mean {
534            assert!(m.abs() < 1e-10, "Centered data should have zero mean");
535        }
536    }
537
538    #[test]
539    fn test_center_1d_invalid() {
540        let centered = center_1d(&FdMatrix::zeros(0, 0));
541        assert!(centered.is_empty());
542    }
543
544    // ============== Norm tests ==============
545
546    #[test]
547    fn test_norm_lp_1d_constant() {
548        // Constant function 2 on [0, 1] has L2 norm = 2
549        let argvals = uniform_grid(21);
550        let data: Vec<f64> = vec![2.0; 21];
551        let mat = FdMatrix::from_column_major(data, 1, 21).unwrap();
552        let norms = norm_lp_1d(&mat, &argvals, 2.0);
553        assert_eq!(norms.len(), 1);
554        assert!(
555            (norms[0] - 2.0).abs() < 0.1,
556            "L2 norm of constant 2 should be 2"
557        );
558    }
559
560    #[test]
561    fn test_norm_lp_1d_sine() {
562        // L2 norm of sin(pi*x) on [0, 1] = sqrt(0.5)
563        let argvals = uniform_grid(101);
564        let data: Vec<f64> = argvals.iter().map(|&x| (PI * x).sin()).collect();
565        let mat = FdMatrix::from_column_major(data, 1, 101).unwrap();
566        let norms = norm_lp_1d(&mat, &argvals, 2.0);
567        let expected = 0.5_f64.sqrt();
568        assert!(
569            (norms[0] - expected).abs() < 0.05,
570            "Expected {}, got {}",
571            expected,
572            norms[0]
573        );
574    }
575
576    #[test]
577    fn test_norm_lp_1d_invalid() {
578        assert!(norm_lp_1d(&FdMatrix::zeros(0, 0), &[], 2.0).is_empty());
579    }
580
581    // ============== Derivative tests ==============
582
583    #[test]
584    fn test_deriv_1d_linear() {
585        // Derivative of linear function x should be 1
586        let argvals = uniform_grid(21);
587        let data = argvals.clone();
588        let mat = FdMatrix::from_column_major(data, 1, 21).unwrap();
589        let deriv = deriv_1d(&mat, &argvals, 1);
590        // Interior points should have derivative close to 1
591        for j in 2..19 {
592            assert!(
593                (deriv[(0, j)] - 1.0).abs() < 0.1,
594                "Derivative of x should be 1"
595            );
596        }
597    }
598
599    #[test]
600    fn test_deriv_1d_quadratic() {
601        // Derivative of x^2 should be 2x
602        let argvals = uniform_grid(51);
603        let data: Vec<f64> = argvals.iter().map(|&x| x * x).collect();
604        let mat = FdMatrix::from_column_major(data, 1, 51).unwrap();
605        let deriv = deriv_1d(&mat, &argvals, 1);
606        // Check interior points
607        for j in 5..45 {
608            let expected = 2.0 * argvals[j];
609            assert!(
610                (deriv[(0, j)] - expected).abs() < 0.1,
611                "Derivative of x^2 should be 2x"
612            );
613        }
614    }
615
616    #[test]
617    fn test_deriv_1d_invalid() {
618        let result = deriv_1d(&FdMatrix::zeros(0, 0), &[], 1);
619        assert!(result.is_empty() || result.as_slice().iter().all(|&x| x == 0.0));
620    }
621
622    // ============== Geometric median tests ==============
623
624    #[test]
625    fn test_geometric_median_identical_curves() {
626        // All curves identical -> median = that curve
627        let argvals = uniform_grid(21);
628        let n = 5;
629        let m = 21;
630        let mut data = vec![0.0; n * m];
631        for i in 0..n {
632            for j in 0..m {
633                data[i + j * n] = (2.0 * PI * argvals[j]).sin();
634            }
635        }
636        let mat = FdMatrix::from_column_major(data, n, m).unwrap();
637        let median = geometric_median_1d(&mat, &argvals, 100, 1e-6);
638        for j in 0..m {
639            let expected = (2.0 * PI * argvals[j]).sin();
640            assert!(
641                (median[j] - expected).abs() < 0.01,
642                "Median should equal all curves"
643            );
644        }
645    }
646
647    #[test]
648    fn test_geometric_median_converges() {
649        let argvals = uniform_grid(21);
650        let n = 10;
651        let m = 21;
652        let mut data = vec![0.0; n * m];
653        for i in 0..n {
654            for j in 0..m {
655                data[i + j * n] = (i as f64 / n as f64) * argvals[j];
656            }
657        }
658        let mat = FdMatrix::from_column_major(data, n, m).unwrap();
659        let median = geometric_median_1d(&mat, &argvals, 100, 1e-6);
660        assert_eq!(median.len(), m);
661        assert!(median.iter().all(|&x| x.is_finite()));
662    }
663
664    #[test]
665    fn test_geometric_median_invalid() {
666        assert!(geometric_median_1d(&FdMatrix::zeros(0, 0), &[], 100, 1e-6).is_empty());
667    }
668
669    // ============== 2D derivative tests ==============
670
671    #[test]
672    fn test_deriv_2d_linear_surface() {
673        // f(s, t) = 2*s + 3*t
674        // ∂f/∂s = 2, ∂f/∂t = 3, ∂²f/∂s∂t = 0
675        let m1 = 11;
676        let m2 = 11;
677        let argvals_s: Vec<f64> = (0..m1).map(|i| i as f64 / (m1 - 1) as f64).collect();
678        let argvals_t: Vec<f64> = (0..m2).map(|i| i as f64 / (m2 - 1) as f64).collect();
679
680        let n = 1; // single surface
681        let ncol = m1 * m2;
682        let mut data = vec![0.0; n * ncol];
683
684        for si in 0..m1 {
685            for ti in 0..m2 {
686                let s = argvals_s[si];
687                let t = argvals_t[ti];
688                let idx = si + ti * m1;
689                data[idx] = 2.0 * s + 3.0 * t;
690            }
691        }
692
693        let mat = FdMatrix::from_column_major(data, n, ncol).unwrap();
694        let result = deriv_2d(&mat, &argvals_s, &argvals_t, m1, m2).unwrap();
695
696        // Check interior points for ∂f/∂s ≈ 2
697        for si in 2..(m1 - 2) {
698            for ti in 2..(m2 - 2) {
699                let idx = si + ti * m1;
700                assert!(
701                    (result.ds[(0, idx)] - 2.0).abs() < 0.2,
702                    "∂f/∂s at ({}, {}) = {}, expected 2",
703                    si,
704                    ti,
705                    result.ds[(0, idx)]
706                );
707            }
708        }
709
710        // Check interior points for ∂f/∂t ≈ 3
711        for si in 2..(m1 - 2) {
712            for ti in 2..(m2 - 2) {
713                let idx = si + ti * m1;
714                assert!(
715                    (result.dt[(0, idx)] - 3.0).abs() < 0.2,
716                    "∂f/∂t at ({}, {}) = {}, expected 3",
717                    si,
718                    ti,
719                    result.dt[(0, idx)]
720                );
721            }
722        }
723
724        // Check interior points for mixed partial ≈ 0
725        for si in 2..(m1 - 2) {
726            for ti in 2..(m2 - 2) {
727                let idx = si + ti * m1;
728                assert!(
729                    result.dsdt[(0, idx)].abs() < 0.5,
730                    "∂²f/∂s∂t at ({}, {}) = {}, expected 0",
731                    si,
732                    ti,
733                    result.dsdt[(0, idx)]
734                );
735            }
736        }
737    }
738
739    #[test]
740    fn test_deriv_2d_quadratic_surface() {
741        // f(s, t) = s*t
742        // ∂f/∂s = t, ∂f/∂t = s, ∂²f/∂s∂t = 1
743        let m1 = 21;
744        let m2 = 21;
745        let argvals_s: Vec<f64> = (0..m1).map(|i| i as f64 / (m1 - 1) as f64).collect();
746        let argvals_t: Vec<f64> = (0..m2).map(|i| i as f64 / (m2 - 1) as f64).collect();
747
748        let n = 1;
749        let ncol = m1 * m2;
750        let mut data = vec![0.0; n * ncol];
751
752        for si in 0..m1 {
753            for ti in 0..m2 {
754                let s = argvals_s[si];
755                let t = argvals_t[ti];
756                let idx = si + ti * m1;
757                data[idx] = s * t;
758            }
759        }
760
761        let mat = FdMatrix::from_column_major(data, n, ncol).unwrap();
762        let result = deriv_2d(&mat, &argvals_s, &argvals_t, m1, m2).unwrap();
763
764        // Check interior points for ∂f/∂s ≈ t
765        for si in 3..(m1 - 3) {
766            for ti in 3..(m2 - 3) {
767                let idx = si + ti * m1;
768                let expected = argvals_t[ti];
769                assert!(
770                    (result.ds[(0, idx)] - expected).abs() < 0.1,
771                    "∂f/∂s at ({}, {}) = {}, expected {}",
772                    si,
773                    ti,
774                    result.ds[(0, idx)],
775                    expected
776                );
777            }
778        }
779
780        // Check interior points for ∂f/∂t ≈ s
781        for si in 3..(m1 - 3) {
782            for ti in 3..(m2 - 3) {
783                let idx = si + ti * m1;
784                let expected = argvals_s[si];
785                assert!(
786                    (result.dt[(0, idx)] - expected).abs() < 0.1,
787                    "∂f/∂t at ({}, {}) = {}, expected {}",
788                    si,
789                    ti,
790                    result.dt[(0, idx)],
791                    expected
792                );
793            }
794        }
795
796        // Check interior points for mixed partial ≈ 1
797        for si in 3..(m1 - 3) {
798            for ti in 3..(m2 - 3) {
799                let idx = si + ti * m1;
800                assert!(
801                    (result.dsdt[(0, idx)] - 1.0).abs() < 0.3,
802                    "∂²f/∂s∂t at ({}, {}) = {}, expected 1",
803                    si,
804                    ti,
805                    result.dsdt[(0, idx)]
806                );
807            }
808        }
809    }
810
811    #[test]
812    fn test_deriv_2d_invalid_input() {
813        // Empty data
814        let result = deriv_2d(&FdMatrix::zeros(0, 0), &[], &[], 0, 0);
815        assert!(result.is_none());
816
817        // Mismatched dimensions
818        let mat = FdMatrix::from_column_major(vec![1.0; 4], 1, 4).unwrap();
819        let argvals = vec![0.0, 1.0];
820        let result = deriv_2d(&mat, &argvals, &[0.0, 0.5, 1.0], 2, 2);
821        assert!(result.is_none());
822    }
823
824    // ============== 2D geometric median tests ==============
825
826    #[test]
827    fn test_geometric_median_2d_basic() {
828        // Three identical surfaces -> median = that surface
829        let m1 = 5;
830        let m2 = 5;
831        let m = m1 * m2;
832        let n = 3;
833        let argvals_s: Vec<f64> = (0..m1).map(|i| i as f64 / (m1 - 1) as f64).collect();
834        let argvals_t: Vec<f64> = (0..m2).map(|i| i as f64 / (m2 - 1) as f64).collect();
835
836        let mut data = vec![0.0; n * m];
837
838        // Create identical surfaces: f(s, t) = s + t
839        for i in 0..n {
840            for si in 0..m1 {
841                for ti in 0..m2 {
842                    let idx = si + ti * m1;
843                    let s = argvals_s[si];
844                    let t = argvals_t[ti];
845                    data[i + idx * n] = s + t;
846                }
847            }
848        }
849
850        let mat = FdMatrix::from_column_major(data, n, m).unwrap();
851        let median = geometric_median_2d(&mat, &argvals_s, &argvals_t, 100, 1e-6);
852        assert_eq!(median.len(), m);
853
854        // Check that median equals the surface
855        for si in 0..m1 {
856            for ti in 0..m2 {
857                let idx = si + ti * m1;
858                let expected = argvals_s[si] + argvals_t[ti];
859                assert!(
860                    (median[idx] - expected).abs() < 0.01,
861                    "Median at ({}, {}) = {}, expected {}",
862                    si,
863                    ti,
864                    median[idx],
865                    expected
866                );
867            }
868        }
869    }
870}