scirs2-spatial 0.4.1

Spatial algorithms module for SciRS2 (scirs2-spatial)
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
//! High-dimensional geometric calculations for convex hull operations
//!
//! This module provides utility functions for geometric computations
//! in dimensions higher than 3, commonly used in high-dimensional
//! convex hull algorithms.

use crate::error::SpatialResult;
use scirs2_core::ndarray::ArrayView2;

/// Compute volume for high-dimensional convex hulls using facet equations
///
/// Uses the divergence theorem approach for high-dimensional volume calculation.
///
/// # Arguments
///
/// * `points` - Input points array
/// * `vertex_indices` - Indices of hull vertices
/// * `equations` - Facet equations in the form [a₁, a₂, ..., aₙ, b] where
///                aᵢx₍ᵢ₎ + b ≤ 0 defines the half-space
///
/// # Returns
///
/// * Result containing the high-dimensional volume
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::high_dimensional::compute_high_dim_volume;
/// use scirs2_core::ndarray::array;
///
/// // 4D hypercube vertices (subset)
/// let points = array![
///     [0.0, 0.0, 0.0, 0.0],
///     [1.0, 0.0, 0.0, 0.0],
///     [0.0, 1.0, 0.0, 0.0],
///     [0.0, 0.0, 1.0, 0.0],
///     [0.0, 0.0, 0.0, 1.0]
/// ];
/// let vertices = vec![0, 1, 2, 3, 4];
/// let equations = array![
///     [1.0, 0.0, 0.0, 0.0, 0.0],
///     [-1.0, 0.0, 0.0, 0.0, 1.0]
/// ];
///
/// let volume = compute_high_dim_volume(&points.view(), &vertices, &equations.view()).expect("Operation failed");
/// assert!(volume >= 0.0);
/// ```
pub fn compute_high_dim_volume(
    points: &ArrayView2<'_, f64>,
    vertex_indices: &[usize],
    equations: &ArrayView2<'_, f64>,
) -> SpatialResult<f64> {
    let ndim = points.ncols();
    let nfacets = equations.nrows();

    if nfacets == 0 {
        return Ok(0.0);
    }

    // For high-dimensional convex hulls, we use the divergence theorem:
    // V = (1/d) * Σ(A_i * h_i)
    // where A_i is the area of facet i and h_i is the distance from origin to facet i

    let mut total_volume = 0.0;

    // Find a point inside the hull (centroid of vertices)
    let mut centroid = vec![0.0; ndim];
    for &vertex_idx in vertex_indices {
        for d in 0..ndim {
            centroid[d] += points[[vertex_idx, d]];
        }
    }
    for item in centroid.iter_mut().take(ndim) {
        *item /= vertex_indices.len() as f64;
    }

    // Process each facet
    for facet_idx in 0..nfacets {
        // Extract normal vector and offset from equation
        let mut normal = vec![0.0; ndim];
        for d in 0..ndim {
            normal[d] = equations[[facet_idx, d]];
        }
        let offset = equations[[facet_idx, ndim]];

        // Normalize the normal vector
        let normal_length = (normal.iter().map(|x| x * x).sum::<f64>()).sqrt();
        if normal_length < 1e-12 {
            continue; // Skip degenerate facets
        }

        for item in normal.iter_mut().take(ndim) {
            *item /= normal_length;
        }
        let normalized_offset = offset / normal_length;

        // Distance from centroid to facet plane
        let distance_to_centroid: f64 = normal
            .iter()
            .zip(centroid.iter())
            .map(|(n, c)| n * c)
            .sum::<f64>()
            + normalized_offset;

        // For volume computation, we need to use the absolute distance
        // The contribution of this facet to the volume calculation
        let height = distance_to_centroid.abs();

        // For high-dimensional case, we approximate the facet area
        // This is a simplified approach - a full implementation would compute exact facet areas
        let facet_area = estimate_facet_area(points, vertex_indices, facet_idx, ndim)?;

        // Add this facet's contribution to the total volume
        total_volume += facet_area * height;
    }

    // Final volume is divided by dimension
    let volume = total_volume / (ndim as f64);

    Ok(volume)
}

/// Estimate the area of a facet in high dimensions
///
/// This is a simplified approach that works for well-formed convex hulls.
///
/// # Arguments
///
/// * `points` - Input points array
/// * `vertex_indices` - Indices of hull vertices
/// * `facet_idx` - Index of the facet to estimate (currently unused in simple estimation)
/// * `ndim` - Number of dimensions
///
/// # Returns
///
/// * Result containing the estimated facet area
pub fn estimate_facet_area(
    points: &ArrayView2<'_, f64>,
    vertex_indices: &[usize],
    _facet_idx: usize,
    ndim: usize,
) -> SpatialResult<f64> {
    // For high dimensions, computing exact facet areas is complex
    // We use a simplified estimation based on the convex hull size

    // Calculate the bounding box volume as a reference
    let mut min_coords = vec![f64::INFINITY; ndim];
    let mut max_coords = vec![f64::NEG_INFINITY; ndim];

    for &vertex_idx in vertex_indices {
        for d in 0..ndim {
            let coord = points[[vertex_idx, d]];
            min_coords[d] = min_coords[d].min(coord);
            max_coords[d] = max_coords[d].max(coord);
        }
    }

    // Calculate the characteristic size of the hull
    let mut size_product = 1.0;
    for d in 0..ndim {
        let size = max_coords[d] - min_coords[d];
        if size > 0.0 {
            size_product *= size;
        }
    }

    // Estimate facet area as a fraction of the hull's characteristic area
    // This is approximate but provides reasonable results for well-formed hulls
    let estimated_area =
        size_product.powf((ndim - 1) as f64 / ndim as f64) / vertex_indices.len() as f64;

    Ok(estimated_area)
}

/// Compute surface area (hypervolume) for high-dimensional convex hulls
///
/// # Arguments
///
/// * `points` - Input points array
/// * `vertex_indices` - Indices of hull vertices
/// * `equations` - Facet equations
///
/// # Returns
///
/// * Result containing the surface area/hypervolume
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::high_dimensional::compute_high_dim_surface_area;
/// use scirs2_core::ndarray::array;
///
/// // 4D simplex
/// let points = array![
///     [0.0, 0.0, 0.0, 0.0],
///     [1.0, 0.0, 0.0, 0.0],
///     [0.0, 1.0, 0.0, 0.0],
///     [0.0, 0.0, 1.0, 0.0],
///     [0.0, 0.0, 0.0, 1.0]
/// ];
/// let vertices = vec![0, 1, 2, 3, 4];
/// let equations = array![
///     [1.0, 0.0, 0.0, 0.0, 0.0],
///     [0.0, 1.0, 0.0, 0.0, 0.0],
///     [0.0, 0.0, 1.0, 0.0, 0.0],
///     [0.0, 0.0, 0.0, 1.0, 0.0],
///     [-1.0, -1.0, -1.0, -1.0, 1.0]
/// ];
///
/// let surface_area = compute_high_dim_surface_area(&points.view(), &vertices, &equations.view()).expect("Operation failed");
/// assert!(surface_area >= 0.0);
/// ```
pub fn compute_high_dim_surface_area(
    points: &ArrayView2<'_, f64>,
    vertex_indices: &[usize],
    equations: &ArrayView2<'_, f64>,
) -> SpatialResult<f64> {
    let ndim = points.ncols();
    let nfacets = equations.nrows();

    if nfacets == 0 {
        return Ok(0.0);
    }

    let mut total_surface_area = 0.0;

    // Sum the areas of all facets
    for facet_idx in 0..nfacets {
        let facet_area = estimate_facet_area(points, vertex_indices, facet_idx, ndim)?;
        total_surface_area += facet_area;
    }

    Ok(total_surface_area)
}

/// Compute the centroid of a set of high-dimensional points
///
/// # Arguments
///
/// * `points` - Input points array
/// * `vertex_indices` - Indices of points to include in centroid calculation
///
/// # Returns
///
/// * Vector representing the centroid coordinates
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::high_dimensional::compute_centroid;
/// use scirs2_core::ndarray::array;
///
/// let points = array![
///     [0.0, 0.0, 0.0],
///     [3.0, 0.0, 0.0],
///     [0.0, 3.0, 0.0],
///     [0.0, 0.0, 3.0]
/// ];
/// let vertices = vec![0, 1, 2, 3];
///
/// let centroid = compute_centroid(&points.view(), &vertices);
/// assert_eq!(centroid, vec![0.75, 0.75, 0.75]);
/// ```
pub fn compute_centroid(points: &ArrayView2<'_, f64>, vertex_indices: &[usize]) -> Vec<f64> {
    let ndim = points.ncols();
    let mut centroid = vec![0.0; ndim];

    for &vertex_idx in vertex_indices {
        for d in 0..ndim {
            centroid[d] += points[[vertex_idx, d]];
        }
    }

    for item in centroid.iter_mut().take(ndim) {
        *item /= vertex_indices.len() as f64;
    }

    centroid
}

/// Compute the bounding box of a set of high-dimensional points
///
/// # Arguments
///
/// * `points` - Input points array
/// * `vertex_indices` - Indices of points to include
///
/// # Returns
///
/// * Tuple of (min_coords, max_coords) vectors
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::high_dimensional::compute_bounding_box;
/// use scirs2_core::ndarray::array;
///
/// let points = array![
///     [0.0, 5.0, -1.0],
///     [3.0, 0.0, 2.0],
///     [1.0, 3.0, 0.0]
/// ];
/// let vertices = vec![0, 1, 2];
///
/// let (min_coords, max_coords) = compute_bounding_box(&points.view(), &vertices);
/// assert_eq!(min_coords, vec![0.0, 0.0, -1.0]);
/// assert_eq!(max_coords, vec![3.0, 5.0, 2.0]);
/// ```
pub fn compute_bounding_box(
    points: &ArrayView2<'_, f64>,
    vertex_indices: &[usize],
) -> (Vec<f64>, Vec<f64>) {
    let ndim = points.ncols();
    let mut min_coords = vec![f64::INFINITY; ndim];
    let mut max_coords = vec![f64::NEG_INFINITY; ndim];

    for &vertex_idx in vertex_indices {
        for d in 0..ndim {
            let coord = points[[vertex_idx, d]];
            min_coords[d] = min_coords[d].min(coord);
            max_coords[d] = max_coords[d].max(coord);
        }
    }

    (min_coords, max_coords)
}

/// Compute the characteristic size of a high-dimensional convex hull
///
/// This is used as a reference measure for volume and surface area estimations.
///
/// # Arguments
///
/// * `points` - Input points array
/// * `vertex_indices` - Indices of hull vertices
///
/// # Returns
///
/// * Characteristic size (geometric mean of bounding box dimensions)
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::high_dimensional::compute_characteristic_size;
/// use scirs2_core::ndarray::array;
///
/// let points = array![
///     [0.0, 0.0, 0.0],
///     [2.0, 0.0, 0.0],
///     [0.0, 4.0, 0.0],
///     [0.0, 0.0, 8.0]
/// ];
/// let vertices = vec![0, 1, 2, 3];
///
/// let size = compute_characteristic_size(&points.view(), &vertices);
/// assert!(size > 0.0);
/// ```
pub fn compute_characteristic_size(points: &ArrayView2<'_, f64>, vertex_indices: &[usize]) -> f64 {
    let (min_coords, max_coords) = compute_bounding_box(points, vertex_indices);
    let ndim = min_coords.len();

    let mut size_product = 1.0;
    let mut valid_dims = 0;

    for d in 0..ndim {
        let size = max_coords[d] - min_coords[d];
        if size > 1e-12 {
            size_product *= size;
            valid_dims += 1;
        }
    }

    if valid_dims == 0 {
        0.0
    } else {
        size_product.powf(1.0 / valid_dims as f64)
    }
}

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

    #[test]
    fn test_compute_centroid() {
        let points = arr2(&[
            [0.0, 0.0, 0.0],
            [3.0, 0.0, 0.0],
            [0.0, 3.0, 0.0],
            [0.0, 0.0, 3.0],
        ]);
        let vertices = vec![0, 1, 2, 3];

        let centroid = compute_centroid(&points.view(), &vertices);
        assert_eq!(centroid, vec![0.75, 0.75, 0.75]);
    }

    #[test]
    fn test_compute_bounding_box() {
        let points = arr2(&[[0.0, 5.0, -1.0], [3.0, 0.0, 2.0], [1.0, 3.0, 0.0]]);
        let vertices = vec![0, 1, 2];

        let (min_coords, max_coords) = compute_bounding_box(&points.view(), &vertices);
        assert_eq!(min_coords, vec![0.0, 0.0, -1.0]);
        assert_eq!(max_coords, vec![3.0, 5.0, 2.0]);
    }

    #[test]
    fn test_compute_characteristic_size() {
        let points = arr2(&[
            [0.0, 0.0, 0.0],
            [2.0, 0.0, 0.0],
            [0.0, 4.0, 0.0],
            [0.0, 0.0, 8.0],
        ]);
        let vertices = vec![0, 1, 2, 3];

        let size = compute_characteristic_size(&points.view(), &vertices);
        assert!(size > 0.0);
        // Geometric mean of [2, 4, 8] = (2*4*8)^(1/3) = 64^(1/3) = 4
        assert!((size - 4.0).abs() < 1e-10);
    }

    #[test]
    fn test_estimate_facet_area() {
        let points = arr2(&[
            [0.0, 0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ]);
        let vertices = vec![0, 1, 2, 3, 4];

        let area = estimate_facet_area(&points.view(), &vertices, 0, 4).expect("Operation failed");
        assert!(area > 0.0);
    }

    #[test]
    fn test_high_dim_surface_area() {
        let points = arr2(&[
            [0.0, 0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ]);
        let vertices = vec![0, 1, 2, 3, 4];
        let equations = arr2(&[
            [1.0, 0.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 0.0, 1.0, 0.0],
            [-1.0, -1.0, -1.0, -1.0, 1.0],
        ]);

        let surface_area =
            compute_high_dim_surface_area(&points.view(), &vertices, &equations.view())
                .expect("Operation failed");
        assert!(surface_area >= 0.0);
    }

    #[test]
    fn test_high_dim_volume() {
        let points = arr2(&[
            [0.0, 0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0, 0.0],
            [0.0, 1.0, 0.0, 0.0],
            [0.0, 0.0, 1.0, 0.0],
            [0.0, 0.0, 0.0, 1.0],
        ]);
        let vertices = vec![0, 1, 2, 3, 4];
        let equations = arr2(&[[1.0, 0.0, 0.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0, 1.0]]);

        let volume = compute_high_dim_volume(&points.view(), &vertices, &equations.view())
            .expect("Operation failed");
        assert!(volume >= 0.0);
    }
}