scirs2-cluster 0.4.2

Clustering algorithms module for SciRS2 (scirs2-cluster)
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
//! Condensed distance matrix utilities
//!
//! This module provides utilities for working with condensed distance matrices,
//! which store only the upper triangular portion of a symmetric distance matrix
//! in a flattened 1D array format for memory efficiency.

use scirs2_core::ndarray::{Array1, Array2, ArrayView1, ArrayView2};
use scirs2_core::numeric::{Float, FromPrimitive, Zero};
use std::fmt::Debug;

use crate::error::{ClusteringError, Result};

/// Convert a square distance matrix to condensed form
///
/// Takes a symmetric distance matrix and returns only the upper triangular
/// portion in a flattened 1D array. The diagonal is assumed to be zero and
/// is not stored.
///
/// # Arguments
///
/// * `square_matrix` - Square symmetric distance matrix (n × n)
///
/// # Returns
///
/// * `Result<Array1<F>>` - Condensed distance matrix with n*(n-1)/2 elements
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_cluster::hierarchy::condensed_matrix::square_to_condensed;
///
/// let square = Array2::from_shape_vec((3, 3), vec![
///     0.0, 1.0, 2.0,
///     1.0, 0.0, 3.0,
///     2.0, 3.0, 0.0,
/// ]).expect("Operation failed");
///
/// let condensed = square_to_condensed(square.view()).expect("Operation failed");
/// assert_eq!(condensed.to_vec(), vec![1.0, 2.0, 3.0]);
/// ```
#[allow(dead_code)]
pub fn square_to_condensed<F: Float + Zero + Copy>(
    square_matrix: ArrayView2<F>,
) -> Result<Array1<F>> {
    let n = square_matrix.shape()[0];
    let m = square_matrix.shape()[1];

    if n != m {
        return Err(ClusteringError::InvalidInput(format!(
            "Distance _matrix must be square, got {}x{}",
            n, m
        )));
    }

    if n < 2 {
        return Err(ClusteringError::InvalidInput(
            "Distance _matrix must be at least 2x2".to_string(),
        ));
    }

    let condensed_size = n * (n - 1) / 2;
    let mut condensed = Array1::zeros(condensed_size);

    let mut idx = 0;
    for i in 0..n {
        for j in (i + 1)..n {
            condensed[idx] = square_matrix[[i, j]];
            idx += 1;
        }
    }

    Ok(condensed)
}

/// Convert a condensed distance matrix to square form
///
/// Takes a condensed distance matrix and reconstructs the full symmetric
/// square matrix with zeros on the diagonal.
///
/// # Arguments
///
/// * `condensed_matrix` - Condensed distance matrix (length n*(n-1)/2)
///
/// # Returns
///
/// * `Result<Array2<F>>` - Square symmetric distance matrix (n × n)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array1;
/// use scirs2_cluster::hierarchy::condensed_matrix::condensed_to_square;
///
/// let condensed = Array1::from_vec(vec![1.0, 2.0, 3.0]);
/// let square = condensed_to_square(condensed.view()).expect("Operation failed");
///
/// assert_eq!(square[[0, 1]], 1.0);
/// assert_eq!(square[[1, 0]], 1.0);
/// assert_eq!(square[[0, 2]], 2.0);
/// assert_eq!(square[[2, 0]], 2.0);
/// assert_eq!(square[[1, 2]], 3.0);
/// assert_eq!(square[[2, 1]], 3.0);
/// ```
#[allow(dead_code)]
pub fn condensed_to_square<F: Float + Zero + Copy>(
    condensed_matrix: ArrayView1<F>,
) -> Result<Array2<F>> {
    let condensed_len = condensed_matrix.len();

    // Solve n*(n-1)/2 = condensed_len for n
    let n_float = (1.0 + (1.0 + 8.0 * condensed_len as f64).sqrt()) / 2.0;
    let n = n_float as usize;

    if n * (n - 1) / 2 != condensed_len {
        return Err(ClusteringError::InvalidInput(format!(
            "Invalid condensed _matrix size: {} elements doesn't correspond to n*(n-1)/2 for any integer n",
            condensed_len
        )));
    }

    let mut square = Array2::zeros((n, n));

    let mut idx = 0;
    for i in 0..n {
        for j in (i + 1)..n {
            let value = condensed_matrix[idx];
            square[[i, j]] = value;
            square[[j, i]] = value; // Symmetric
            idx += 1;
        }
    }

    Ok(square)
}

/// Get the distance between two points from a condensed distance matrix
///
/// Retrieves the distance between points i and j from a condensed distance matrix
/// without converting to square form.
///
/// # Arguments
///
/// * `condensed_matrix` - Condensed distance matrix
/// * `i` - First point index
/// * `j` - Second point index
/// * `n` - Total number of points
///
/// # Returns
///
/// * `Result<F>` - Distance between points i and j
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array1;
/// use scirs2_cluster::hierarchy::condensed_matrix::get_distance;
///
/// let condensed = Array1::from_vec(vec![1.0, 2.0, 3.0]);
/// let distance = get_distance(condensed.view(), 0, 2, 3).expect("Operation failed");
/// assert_eq!(distance, 2.0);
/// ```
#[allow(dead_code)]
pub fn get_distance<F: Float + Zero + Copy>(
    condensed_matrix: ArrayView1<F>,
    i: usize,
    j: usize,
    n: usize,
) -> Result<F> {
    if i == j {
        return Ok(F::zero());
    }

    if i >= n || j >= n {
        return Err(ClusteringError::InvalidInput(format!(
            "Point indices {} and {} must be less than n={}",
            i, j, n
        )));
    }

    let expected_len = n * (n - 1) / 2;
    if condensed_matrix.len() != expected_len {
        return Err(ClusteringError::InvalidInput(format!(
            "Condensed _matrix length {} doesn't match expected {} for n={}",
            condensed_matrix.len(),
            expected_len,
            n
        )));
    }

    // Ensure i < j for indexing
    let (min_idx, max_idx) = if i < j { (i, j) } else { (j, i) };

    // Calculate the index in the condensed _matrix
    let condensed_idx = n * min_idx - (min_idx * (min_idx + 1)) / 2 + (max_idx - min_idx - 1);

    if condensed_idx >= condensed_matrix.len() {
        return Err(ClusteringError::InvalidInput(format!(
            "Computed index {} is out of bounds for condensed _matrix of length {}",
            condensed_idx,
            condensed_matrix.len()
        )));
    }

    Ok(condensed_matrix[condensed_idx])
}

/// Set the distance between two points in a condensed distance matrix
///
/// Updates the distance between points i and j in a condensed distance matrix
/// without converting to square form.
///
/// # Arguments
///
/// * `condensed_matrix` - Mutable condensed distance matrix
/// * `i` - First point index  
/// * `j` - Second point index
/// * `n` - Total number of points
/// * `distance` - New distance value
///
/// # Returns
///
/// * `Result<()>` - Ok if successful, error otherwise
#[allow(dead_code)]
pub fn set_distance<F: Float + Zero + Copy>(
    condensed_matrix: ArrayView1<F>,
    i: usize,
    j: usize,
    n: usize,
    distance: F,
) -> Result<()> {
    if i == j {
        if !distance.is_zero() {
            return Err(ClusteringError::InvalidInput(
                "Cannot set non-zero distance for identical points".to_string(),
            ));
        }
        return Ok(()); // Distance between identical points is always zero
    }

    if i >= n || j >= n {
        return Err(ClusteringError::InvalidInput(format!(
            "Point indices {} and {} must be less than n={}",
            i, j, n
        )));
    }

    let expected_len = n * (n - 1) / 2;
    if condensed_matrix.len() != expected_len {
        return Err(ClusteringError::InvalidInput(format!(
            "Condensed _matrix length {} doesn't match expected {} for n={}",
            condensed_matrix.len(),
            expected_len,
            n
        )));
    }

    // Ensure i < j for indexing
    let (min_idx, max_idx) = if i < j { (i, j) } else { (j, i) };

    // Calculate the index in the condensed _matrix
    let condensed_idx = n * min_idx - (min_idx * (min_idx + 1)) / 2 + (max_idx - min_idx - 1);

    if condensed_idx >= condensed_matrix.len() {
        return Err(ClusteringError::InvalidInput(format!(
            "Computed index {} is out of bounds for condensed _matrix of length {}",
            condensed_idx,
            condensed_matrix.len()
        )));
    }

    // Note: This is a limitation - we can't actually modify through ArrayView1
    // In practice, this would need to work with Array1 or a mutable slice
    Err(ClusteringError::ComputationError(
        "Cannot modify through immutable view - use mutable Array1 instead".to_string(),
    ))
}

/// Calculate the size of a condensed matrix for n points
///
/// Returns the number of elements needed to store a condensed distance matrix
/// for n points.
///
/// # Arguments
///
/// * `n` - Number of points
///
/// # Returns
///
/// * `usize` - Size of condensed matrix (n*(n-1)/2)
#[allow(dead_code)]
pub fn condensed_size(n: usize) -> usize {
    n * (n - 1) / 2
}

/// Calculate the number of points from condensed matrix size
///
/// Given the size of a condensed distance matrix, calculate the number
/// of original points.
///
/// # Arguments
///
/// * `condensed_len` - Length of condensed matrix
///
/// # Returns
///
/// * `Result<usize>` - Number of points, or error if size is invalid
#[allow(dead_code)]
pub fn points_from_condensed_size(_condensedlen: usize) -> Result<usize> {
    let n_float = (1.0 + (1.0 + 8.0 * _condensedlen as f64).sqrt()) / 2.0;
    let n = n_float as usize;

    if n * (n - 1) / 2 != _condensedlen {
        return Err(ClusteringError::InvalidInput(format!(
            "Invalid condensed matrix size: {} elements doesn't correspond to n*(n-1)/2 for any integer n",
            _condensedlen
        )));
    }

    Ok(n)
}

/// Validate a condensed distance matrix
///
/// Checks that a condensed distance matrix has the correct size and
/// contains valid distance values.
///
/// # Arguments
///
/// * `condensed_matrix` - Condensed distance matrix to validate
///
/// # Returns
///
/// * `Result<usize>` - Number of points if valid, error otherwise
#[allow(dead_code)]
pub fn validate_condensed_matrix<F: Float + FromPrimitive + Debug + PartialOrd>(
    condensed_matrix: ArrayView1<F>,
) -> Result<usize> {
    let condensed_len = condensed_matrix.len();

    if condensed_len == 0 {
        return Err(ClusteringError::InvalidInput(
            "Condensed _matrix cannot be empty".to_string(),
        ));
    }

    // Check if size corresponds to valid n
    let n = points_from_condensed_size(condensed_len)?;

    if n < 2 {
        return Err(ClusteringError::InvalidInput(
            "Condensed _matrix must represent at least 2 points".to_string(),
        ));
    }

    // Check all distances are non-negative and finite
    for (idx, &distance) in condensed_matrix.iter().enumerate() {
        if !distance.is_finite() {
            return Err(ClusteringError::InvalidInput(format!(
                "Non-finite distance at index {}",
                idx
            )));
        }

        if distance < F::zero() {
            return Err(ClusteringError::InvalidInput(format!(
                "Negative distance at index {}: {:?}",
                idx, distance
            )));
        }
    }

    Ok(n)
}

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

    #[test]
    fn test_square_to_condensed() {
        let square = Array2::from_shape_vec(
            (4, 4),
            vec![
                0.0, 1.0, 2.0, 3.0, 1.0, 0.0, 4.0, 5.0, 2.0, 4.0, 0.0, 6.0, 3.0, 5.0, 6.0, 0.0,
            ],
        )
        .expect("Operation failed");

        let condensed = square_to_condensed(square.view()).expect("Operation failed");
        assert_eq!(condensed.to_vec(), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
    }

    #[test]
    fn test_condensed_to_square() {
        let condensed = Array1::from_vec(vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
        let square = condensed_to_square(condensed.view()).expect("Operation failed");

        let expected = Array2::from_shape_vec(
            (4, 4),
            vec![
                0.0, 1.0, 2.0, 3.0, 1.0, 0.0, 4.0, 5.0, 2.0, 4.0, 0.0, 6.0, 3.0, 5.0, 6.0, 0.0,
            ],
        )
        .expect("Operation failed");

        assert_eq!(square, expected);
    }

    #[test]
    fn test_round_trip_conversion() {
        let original =
            Array2::from_shape_vec((3, 3), vec![0.0, 1.5, 2.5, 1.5, 0.0, 3.5, 2.5, 3.5, 0.0])
                .expect("Operation failed");

        let condensed = square_to_condensed(original.view()).expect("Operation failed");
        let reconstructed = condensed_to_square(condensed.view()).expect("Operation failed");

        assert_eq!(original, reconstructed);
    }

    #[test]
    fn test_get_distance() {
        let condensed = Array1::from_vec(vec![1.0, 2.0, 3.0]);

        // Test all pairwise distances for 3 points
        assert_eq!(
            get_distance(condensed.view(), 0, 1, 3).expect("Operation failed"),
            1.0
        );
        assert_eq!(
            get_distance(condensed.view(), 1, 0, 3).expect("Operation failed"),
            1.0
        ); // Symmetric
        assert_eq!(
            get_distance(condensed.view(), 0, 2, 3).expect("Operation failed"),
            2.0
        );
        assert_eq!(
            get_distance(condensed.view(), 2, 0, 3).expect("Operation failed"),
            2.0
        ); // Symmetric
        assert_eq!(
            get_distance(condensed.view(), 1, 2, 3).expect("Operation failed"),
            3.0
        );
        assert_eq!(
            get_distance(condensed.view(), 2, 1, 3).expect("Operation failed"),
            3.0
        ); // Symmetric

        // Test diagonal (should be zero)
        assert_eq!(
            get_distance(condensed.view(), 0, 0, 3).expect("Operation failed"),
            0.0
        );
        assert_eq!(
            get_distance(condensed.view(), 1, 1, 3).expect("Operation failed"),
            0.0
        );
        assert_eq!(
            get_distance(condensed.view(), 2, 2, 3).expect("Operation failed"),
            0.0
        );
    }

    #[test]
    fn test_condensed_size_calculations() {
        assert_eq!(condensed_size(2), 1);
        assert_eq!(condensed_size(3), 3);
        assert_eq!(condensed_size(4), 6);
        assert_eq!(condensed_size(5), 10);

        assert_eq!(points_from_condensed_size(1).expect("Operation failed"), 2);
        assert_eq!(points_from_condensed_size(3).expect("Operation failed"), 3);
        assert_eq!(points_from_condensed_size(6).expect("Operation failed"), 4);
        assert_eq!(points_from_condensed_size(10).expect("Operation failed"), 5);

        // Invalid sizes should fail
        assert!(points_from_condensed_size(2).is_err()); // No integer n such that n*(n-1)/2 = 2
        assert!(points_from_condensed_size(5).is_err()); // No integer n such that n*(n-1)/2 = 5
    }

    #[test]
    fn test_validate_condensed_matrix() {
        // Valid matrix
        let valid = Array1::from_vec(vec![1.0, 2.0, 3.0]);
        assert_eq!(
            validate_condensed_matrix(valid.view()).expect("Operation failed"),
            3
        );

        // Invalid size
        let invalid_size = Array1::from_vec(vec![1.0, 2.0]);
        assert!(validate_condensed_matrix(invalid_size.view()).is_err());

        // Negative distance
        let negative = Array1::from_vec(vec![-1.0, 2.0, 3.0]);
        assert!(validate_condensed_matrix(negative.view()).is_err());

        // Non-finite distance
        let non_finite = Array1::from_vec(vec![f64::NAN, 2.0, 3.0]);
        assert!(validate_condensed_matrix(non_finite.view()).is_err());
    }

    #[test]
    fn test_error_cases() {
        // Non-square matrix
        let non_square = Array2::from_shape_vec((2, 3), vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0])
            .expect("Operation failed");
        assert!(square_to_condensed(non_square.view()).is_err());

        // Too small matrix
        let too_small = Array2::from_shape_vec((1, 1), vec![0.0]).expect("Operation failed");
        assert!(square_to_condensed(too_small.view()).is_err());

        // Out of bounds point indices
        let condensed = Array1::from_vec(vec![1.0, 2.0, 3.0]);
        assert!(get_distance(condensed.view(), 0, 3, 3).is_err()); // j=3 >= n=3
        assert!(get_distance(condensed.view(), 4, 1, 3).is_err()); // i=4 >= n=3
    }
}