scirs2-spatial 0.4.2

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
//! 3D geometric calculations for convex hull operations
//!
//! This module provides utility functions for 3D geometric computations
//! commonly used in convex hull algorithms.

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

/// Compute the signed volume of a tetrahedron
///
/// # Arguments
///
/// * `p0` - First vertex [x, y, z]
/// * `p1` - Second vertex [x, y, z]  
/// * `p2` - Third vertex [x, y, z]
/// * `p3` - Fourth vertex [x, y, z]
///
/// # Returns
///
/// * Signed volume of tetrahedron formed by the four points
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::tetrahedron_volume;
///
/// let p0 = [0.0, 0.0, 0.0];
/// let p1 = [1.0, 0.0, 0.0];
/// let p2 = [0.0, 1.0, 0.0];
/// let p3 = [0.0, 0.0, 1.0];
///
/// let volume = tetrahedron_volume(p0, p1, p2, p3);
/// assert!((volume - 1.0/6.0).abs() < 1e-10);
/// ```
pub fn tetrahedron_volume(p0: [f64; 3], p1: [f64; 3], p2: [f64; 3], p3: [f64; 3]) -> f64 {
    let v1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]];
    let v2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]];
    let v3 = [p3[0] - p0[0], p3[1] - p0[1], p3[2] - p0[2]];

    // Compute scalar triple product: v1 · (v2 × v3)
    let cross = [
        v2[1] * v3[2] - v2[2] * v3[1],
        v2[2] * v3[0] - v2[0] * v3[2],
        v2[0] * v3[1] - v2[1] * v3[0],
    ];

    (v1[0] * cross[0] + v1[1] * cross[1] + v1[2] * cross[2]).abs() / 6.0
}

/// Compute the area of a 3D triangle
///
/// # Arguments
///
/// * `p0` - First vertex [x, y, z]
/// * `p1` - Second vertex [x, y, z]
/// * `p2` - Third vertex [x, y, z]
///
/// # Returns
///
/// * Area of the triangle in 3D space
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::triangle_area_3d;
///
/// let p0 = [0.0, 0.0, 0.0];
/// let p1 = [1.0, 0.0, 0.0];
/// let p2 = [0.0, 1.0, 0.0];
///
/// let area = triangle_area_3d(p0, p1, p2);
/// assert!((area - 0.5).abs() < 1e-10);
/// ```
pub fn triangle_area_3d(p0: [f64; 3], p1: [f64; 3], p2: [f64; 3]) -> f64 {
    let v1 = [p1[0] - p0[0], p1[1] - p0[1], p1[2] - p0[2]];
    let v2 = [p2[0] - p0[0], p2[1] - p0[1], p2[2] - p0[2]];

    // Compute cross product v1 × v2
    let cross = [
        v1[1] * v2[2] - v1[2] * v2[1],
        v1[2] * v2[0] - v1[0] * v2[2],
        v1[0] * v2[1] - v1[1] * v2[0],
    ];

    // Magnitude of cross product gives twice the triangle area
    let magnitude = (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt();
    magnitude / 2.0
}

/// Compute the volume of a 3D polyhedron using triangulation from centroid
///
/// # Arguments
///
/// * `points` - Input points array
/// * `simplices` - Triangular faces of the polyhedron
///
/// # Returns
///
/// * Result containing the polyhedron volume
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::compute_polyhedron_volume;
/// use scirs2_core::ndarray::array;
///
/// // Unit tetrahedron
/// let points = array![
///     [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]
/// ];
/// let simplices = vec![
///     vec![0, 1, 2], vec![0, 1, 3], vec![0, 2, 3], vec![1, 2, 3]
/// ];
///
/// let volume = compute_polyhedron_volume(&points.view(), &simplices).expect("Operation failed");
/// assert!(volume > 0.0);
/// ```
pub fn compute_polyhedron_volume(
    points: &ArrayView2<'_, f64>,
    simplices: &[Vec<usize>],
) -> SpatialResult<f64> {
    if simplices.is_empty() {
        return Ok(0.0);
    }

    // Compute the centroid of all vertices
    let vertex_indices: std::collections::HashSet<usize> =
        simplices.iter().flat_map(|s| s.iter()).cloned().collect();

    let mut centroid = [0.0, 0.0, 0.0];
    for &idx in &vertex_indices {
        centroid[0] += points[[idx, 0]];
        centroid[1] += points[[idx, 1]];
        centroid[2] += points[[idx, 2]];
    }
    let n = vertex_indices.len() as f64;
    centroid[0] /= n;
    centroid[1] /= n;
    centroid[2] /= n;

    let mut total_volume = 0.0;

    // For each triangular face, form a tetrahedron with the centroid
    for simplex in simplices {
        if simplex.len() != 3 {
            continue; // Skip non-triangular faces
        }

        let p0 = [
            points[[simplex[0], 0]],
            points[[simplex[0], 1]],
            points[[simplex[0], 2]],
        ];
        let p1 = [
            points[[simplex[1], 0]],
            points[[simplex[1], 1]],
            points[[simplex[1], 2]],
        ];
        let p2 = [
            points[[simplex[2], 0]],
            points[[simplex[2], 1]],
            points[[simplex[2], 2]],
        ];

        // Compute the volume of the tetrahedron formed by centroid, p0, p1, p2
        let tet_volume = tetrahedron_volume(centroid, p0, p1, p2);
        total_volume += tet_volume.abs();
    }

    Ok(total_volume)
}

/// Compute the surface area of a 3D polyhedron
///
/// # Arguments
///
/// * `points` - Input points array
/// * `simplices` - Triangular faces of the polyhedron
///
/// # Returns
///
/// * Result containing the polyhedron surface area
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::compute_polyhedron_surface_area;
/// use scirs2_core::ndarray::array;
///
/// // Unit tetrahedron
/// let points = array![
///     [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]
/// ];
/// let simplices = vec![
///     vec![0, 1, 2], vec![0, 1, 3], vec![0, 2, 3], vec![1, 2, 3]
/// ];
///
/// let surface_area = compute_polyhedron_surface_area(&points.view(), &simplices).expect("Operation failed");
/// assert!(surface_area > 0.0);
/// ```
pub fn compute_polyhedron_surface_area(
    points: &ArrayView2<'_, f64>,
    simplices: &[Vec<usize>],
) -> SpatialResult<f64> {
    if simplices.is_empty() {
        return Ok(0.0);
    }

    let mut surface_area = 0.0;

    // For each triangular face, compute its area
    for simplex in simplices {
        if simplex.len() != 3 {
            continue; // Skip non-triangular faces
        }

        let p0 = [
            points[[simplex[0], 0]],
            points[[simplex[0], 1]],
            points[[simplex[0], 2]],
        ];
        let p1 = [
            points[[simplex[1], 0]],
            points[[simplex[1], 1]],
            points[[simplex[1], 2]],
        ];
        let p2 = [
            points[[simplex[2], 0]],
            points[[simplex[2], 1]],
            points[[simplex[2], 2]],
        ];

        let area = triangle_area_3d(p0, p1, p2);
        surface_area += area;
    }

    Ok(surface_area)
}

/// Compute cross product of two 3D vectors
///
/// # Arguments
///
/// * `v1` - First vector [x, y, z]
/// * `v2` - Second vector [x, y, z]
///
/// # Returns
///
/// * Cross product v1 × v2 as [x, y, z]
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::cross_product_3d;
///
/// let v1 = [1.0, 0.0, 0.0];
/// let v2 = [0.0, 1.0, 0.0];
///
/// let cross = cross_product_3d(v1, v2);
/// assert_eq!(cross, [0.0, 0.0, 1.0]);
/// ```
pub fn cross_product_3d(v1: [f64; 3], v2: [f64; 3]) -> [f64; 3] {
    [
        v1[1] * v2[2] - v1[2] * v2[1],
        v1[2] * v2[0] - v1[0] * v2[2],
        v1[0] * v2[1] - v1[1] * v2[0],
    ]
}

/// Compute dot product of two 3D vectors
///
/// # Arguments
///
/// * `v1` - First vector [x, y, z]
/// * `v2` - Second vector [x, y, z]
///
/// # Returns
///
/// * Dot product v1 · v2
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::dot_product_3d;
///
/// let v1 = [1.0, 2.0, 3.0];
/// let v2 = [4.0, 5.0, 6.0];
///
/// let dot = dot_product_3d(v1, v2);
/// assert_eq!(dot, 32.0); // 1*4 + 2*5 + 3*6 = 32
/// ```
pub fn dot_product_3d(v1: [f64; 3], v2: [f64; 3]) -> f64 {
    v1[0] * v2[0] + v1[1] * v2[1] + v1[2] * v2[2]
}

/// Compute the magnitude of a 3D vector
///
/// # Arguments
///
/// * `v` - Vector [x, y, z]
///
/// # Returns
///
/// * Magnitude (length) of the vector
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::vector_magnitude_3d;
///
/// let v = [3.0, 4.0, 0.0];
/// let magnitude = vector_magnitude_3d(v);
/// assert_eq!(magnitude, 5.0);
/// ```
pub fn vector_magnitude_3d(v: [f64; 3]) -> f64 {
    (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
}

/// Normalize a 3D vector
///
/// # Arguments
///
/// * `v` - Vector to normalize [x, y, z]
///
/// # Returns
///
/// * Normalized vector, or zero vector if input has zero magnitude
///
/// # Examples
///
/// ```
/// use scirs2_spatial::convex_hull::geometry::calculations_3d::normalize_3d;
///
/// let v = [3.0, 4.0, 0.0];
/// let normalized = normalize_3d(v);
/// assert_eq!(normalized, [0.6, 0.8, 0.0]);
/// ```
pub fn normalize_3d(v: [f64; 3]) -> [f64; 3] {
    let magnitude = vector_magnitude_3d(v);
    if magnitude < 1e-12 {
        [0.0, 0.0, 0.0]
    } else {
        [v[0] / magnitude, v[1] / magnitude, v[2] / magnitude]
    }
}

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

    #[test]
    fn test_tetrahedron_volume() {
        let p0 = [0.0, 0.0, 0.0];
        let p1 = [1.0, 0.0, 0.0];
        let p2 = [0.0, 1.0, 0.0];
        let p3 = [0.0, 0.0, 1.0];

        let volume = tetrahedron_volume(p0, p1, p2, p3);
        assert!((volume - 1.0 / 6.0).abs() < 1e-10);
    }

    #[test]
    fn test_triangle_area_3d() {
        let p0 = [0.0, 0.0, 0.0];
        let p1 = [1.0, 0.0, 0.0];
        let p2 = [0.0, 1.0, 0.0];

        let area = triangle_area_3d(p0, p1, p2);
        assert!((area - 0.5).abs() < 1e-10);
    }

    #[test]
    fn test_cross_product_3d() {
        let v1 = [1.0, 0.0, 0.0];
        let v2 = [0.0, 1.0, 0.0];

        let cross = cross_product_3d(v1, v2);
        assert_eq!(cross, [0.0, 0.0, 1.0]);
    }

    #[test]
    fn test_dot_product_3d() {
        let v1 = [1.0, 2.0, 3.0];
        let v2 = [4.0, 5.0, 6.0];

        let dot = dot_product_3d(v1, v2);
        assert_eq!(dot, 32.0);
    }

    #[test]
    fn test_vector_magnitude_3d() {
        let v = [3.0, 4.0, 0.0];
        let magnitude = vector_magnitude_3d(v);
        assert_eq!(magnitude, 5.0);
    }

    #[test]
    fn test_normalize_3d() {
        let v = [3.0, 4.0, 0.0];
        let normalized = normalize_3d(v);
        assert!((normalized[0] - 0.6).abs() < 1e-10);
        assert!((normalized[1] - 0.8).abs() < 1e-10);
        assert_eq!(normalized[2], 0.0);
    }

    #[test]
    fn test_polyhedron_volume() {
        // Unit tetrahedron
        let points = arr2(&[
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
        ]);
        let simplices = vec![vec![0, 1, 2], vec![0, 1, 3], vec![0, 2, 3], vec![1, 2, 3]];

        let volume =
            compute_polyhedron_volume(&points.view(), &simplices).expect("Operation failed");
        assert!(volume > 0.0);
        // Unit tetrahedron volume should be 1/6
        assert!((volume - 1.0 / 6.0).abs() < 0.1); // Allow some numerical error
    }

    #[test]
    fn test_polyhedron_surface_area() {
        // Unit tetrahedron
        let points = arr2(&[
            [0.0, 0.0, 0.0],
            [1.0, 0.0, 0.0],
            [0.0, 1.0, 0.0],
            [0.0, 0.0, 1.0],
        ]);
        let simplices = vec![vec![0, 1, 2], vec![0, 1, 3], vec![0, 2, 3], vec![1, 2, 3]];

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