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
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
//! Data preprocessing utilities for clustering algorithms
//!
//! This module provides functions for preprocessing data before applying
//! clustering algorithms, such as:
//! - Whitening: Scaling features to have unit variance
//! - Normalization: Scaling data to a specific range or norm
//! - Standardization: Transforming data to have zero mean and unit variance

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

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

/// Whiten a dataset by rescaling each feature to have unit variance
///
/// This is useful for preprocessing before applying certain clustering algorithms
/// like K-means. Each feature is divided by its standard deviation to give it
/// unit variance.
///
/// # Arguments
///
/// * `data` - Input data as a 2D array (n_samples × n_features)
/// * `check_finite` - Whether to check for NaN or infinite values
///
/// # Returns
///
/// * `Result<Array2<F>>` - The whitened data
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_cluster::preprocess::whiten;
///
/// // Example data with 3 features
/// let data = Array2::from_shape_vec((3, 3), vec![
///     1.9, 2.3, 1.7,
///     1.5, 2.5, 2.2,
///     0.8, 0.6, 1.7,
/// ]).expect("Operation failed");
///
/// // Whiten the data
/// let whitened = whiten(data.view(), true).expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn whiten<F: Float + FromPrimitive + Debug>(
    data: ArrayView2<F>,
    check_finite: bool,
) -> Result<Array2<F>> {
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];

    if n_samples == 0 || n_features == 0 {
        return Err(ClusteringError::InvalidInput("Input data is empty".into()));
    }

    if check_finite {
        // Check for NaN or infinite values
        for element in data.iter() {
            if !element.is_finite() {
                return Err(ClusteringError::InvalidInput(
                    "Input data contains NaN or infinite values".into(),
                ));
            }
        }
    }

    // Calculate the standard deviation for each feature
    let std_dev = standard_deviation(data, Axis(0))?;

    // Create the whitened data
    let mut result = Array2::zeros(data.dim());

    // Scale each feature by its standard deviation
    for j in 0..n_features {
        let std_j = std_dev[j];
        if std_j <= F::epsilon() {
            // If the standard deviation is close to zero, don't scale
            for i in 0..n_samples {
                result[[i, j]] = data[[i, j]];
            }
        } else {
            for i in 0..n_samples {
                result[[i, j]] = data[[i, j]] / std_j;
            }
        }
    }

    Ok(result)
}

/// Standardize a dataset by rescaling each feature to have zero mean and unit variance
///
/// # Arguments
///
/// * `data` - Input data as a 2D array (n_samples × n_features)
/// * `check_finite` - Whether to check for NaN or infinite values
///
/// # Returns
///
/// * `Result<Array2<F>>` - The standardized data
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_cluster::preprocess::standardize;
///
/// // Example data with 3 features
/// let data = Array2::from_shape_vec((3, 3), vec![
///     1.9, 2.3, 1.7,
///     1.5, 2.5, 2.2,
///     0.8, 0.6, 1.7,
/// ]).expect("Operation failed");
///
/// // Standardize the data
/// let standardized = standardize(data.view(), true).expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn standardize<F: Float + FromPrimitive + Debug>(
    data: ArrayView2<F>,
    check_finite: bool,
) -> Result<Array2<F>> {
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];

    if n_samples == 0 || n_features == 0 {
        return Err(ClusteringError::InvalidInput("Input data is empty".into()));
    }

    if check_finite {
        // Check for NaN or infinite values
        for element in data.iter() {
            if !element.is_finite() {
                return Err(ClusteringError::InvalidInput(
                    "Input data contains NaN or infinite values".into(),
                ));
            }
        }
    }

    // Calculate the mean for each feature
    let mean = data.mean_axis(Axis(0)).expect("Operation failed");

    // Calculate the standard deviation for each feature
    let std_dev = standard_deviation(data, Axis(0))?;

    // Create the standardized data
    let mut result = Array2::zeros(data.dim());

    // Scale each feature to zero mean and unit variance
    for j in 0..n_features {
        let mean_j = mean[j];
        let std_j = std_dev[j];

        if std_j <= F::epsilon() {
            // If the standard deviation is close to zero, just subtract the mean
            for i in 0..n_samples {
                result[[i, j]] = data[[i, j]] - mean_j;
            }
        } else {
            for i in 0..n_samples {
                result[[i, j]] = (data[[i, j]] - mean_j) / std_j;
            }
        }
    }

    Ok(result)
}

/// Normalize each sample to a given norm
///
/// # Arguments
///
/// * `data` - Input data as a 2D array (n_samples × n_features)
/// * `norm` - Type of normalization: L1, L2, or Max
/// * `check_finite` - Whether to check for NaN or infinite values
///
/// # Returns
///
/// * `Result<Array2<F>>` - The normalized data
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_cluster::preprocess::{normalize, NormType};
///
/// // Example data with 3 features
/// let data = Array2::from_shape_vec((3, 3), vec![
///     1.9, 2.3, 1.7,
///     1.5, 2.5, 2.2,
///     0.8, 0.6, 1.7,
/// ]).expect("Operation failed");
///
/// // Normalize the data using L2 norm
/// let normalized = normalize(data.view(), NormType::L2, true).expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn normalize<F: Float + FromPrimitive + Debug>(
    data: ArrayView2<F>,
    norm: NormType,
    check_finite: bool,
) -> Result<Array2<F>> {
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];

    if n_samples == 0 || n_features == 0 {
        return Err(ClusteringError::InvalidInput("Input data is empty".into()));
    }

    if check_finite {
        // Check for NaN or infinite values
        for element in data.iter() {
            if !element.is_finite() {
                return Err(ClusteringError::InvalidInput(
                    "Input data contains NaN or infinite values".into(),
                ));
            }
        }
    }

    // Calculate the norm for each sample
    let norms = match norm {
        NormType::L1 => {
            // L1 norm (sum of absolute values)
            let mut norms = Array1::zeros(n_samples);
            for i in 0..n_samples {
                let row = data.row(i);
                let row_norm = row.iter().fold(F::zero(), |acc, &x| acc + x.abs());
                norms[i] = row_norm;
            }
            norms
        }
        NormType::L2 => {
            // L2 norm (square root of sum of squares)
            let mut norms = Array1::zeros(n_samples);
            for i in 0..n_samples {
                let row = data.row(i);
                let row_norm = row.iter().fold(F::zero(), |acc, &x| acc + x * x).sqrt();
                norms[i] = row_norm;
            }
            norms
        }
        NormType::Max => {
            // Max norm (maximum absolute value)
            let mut norms = Array1::zeros(n_samples);
            for i in 0..n_samples {
                let row = data.row(i);
                let row_norm = row.iter().fold(F::zero(), |acc, &x| acc.max(x.abs()));
                norms[i] = row_norm;
            }
            norms
        }
    };

    // Create the normalized data
    let mut result = Array2::zeros(data.dim());

    // Scale each sample by its norm
    for i in 0..n_samples {
        let norm_i = norms[i];
        if norm_i <= F::epsilon() {
            // If the norm is close to zero, don't normalize
            for j in 0..n_features {
                result[[i, j]] = data[[i, j]];
            }
        } else {
            for j in 0..n_features {
                result[[i, j]] = data[[i, j]] / norm_i;
            }
        }
    }

    Ok(result)
}

/// Normalize data to a specified range (min-max scaling)
///
/// # Arguments
///
/// * `data` - Input data as a 2D array (n_samples × n_features)
/// * `feature_range` - Tuple of (min, max) values to scale to
/// * `check_finite` - Whether to check for NaN or infinite values
///
/// # Returns
///
/// * `Result<Array2<F>>` - The scaled data
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array2;
/// use scirs2_cluster::preprocess::min_max_scale;
///
/// // Example data with 3 features
/// let data = Array2::from_shape_vec((3, 3), vec![
///     1.9, 2.3, 1.7,
///     1.5, 2.5, 2.2,
///     0.8, 0.6, 1.7,
/// ]).expect("Operation failed");
///
/// // Scale the data to the range [0, 1]
/// let scaled = min_max_scale(data.view(), (0.0, 1.0), true).expect("Operation failed");
/// ```
#[allow(dead_code)]
pub fn min_max_scale<F: Float + FromPrimitive + Debug>(
    data: ArrayView2<F>,
    feature_range: (f64, f64),
    check_finite: bool,
) -> Result<Array2<F>> {
    let n_samples = data.shape()[0];
    let n_features = data.shape()[1];

    if n_samples == 0 || n_features == 0 {
        return Err(ClusteringError::InvalidInput("Input data is empty".into()));
    }

    if check_finite {
        // Check for NaN or infinite values
        for element in data.iter() {
            if !element.is_finite() {
                return Err(ClusteringError::InvalidInput(
                    "Input data contains NaN or infinite values".into(),
                ));
            }
        }
    }

    let (min_val, max_val) = feature_range;
    if min_val >= max_val {
        return Err(ClusteringError::InvalidInput(
            "Feature range minimum must be less than maximum".into(),
        ));
    }

    let feature_min = F::from_f64(min_val).expect("Operation failed");
    let feature_max = F::from_f64(max_val).expect("Operation failed");

    // Calculate the min and max for each feature
    let mut min_values = Array1::zeros(n_features);
    let mut max_values = Array1::zeros(n_features);

    for j in 0..n_features {
        let column = data.column(j);
        let (min_j, max_j) = column.iter().fold(
            (F::infinity(), F::neg_infinity()),
            |(min_val, max_val), &x| (min_val.min(x), max_val.max(x)),
        );
        min_values[j] = min_j;
        max_values[j] = max_j;
    }

    // Create the scaled data
    let mut result = Array2::zeros(data.dim());

    // Scale each feature to the specified range
    for j in 0..n_features {
        let min_j = min_values[j];
        let max_j = max_values[j];
        let range_j = max_j - min_j;

        if range_j <= F::epsilon() {
            // If the feature has no variation, set to the middle of the feature range
            let middle = (feature_min + feature_max) / F::from_f64(2.0).expect("Operation failed");
            for i in 0..n_samples {
                result[[i, j]] = middle;
            }
        } else {
            for i in 0..n_samples {
                // Scale to [0, 1]
                let scaled = (data[[i, j]] - min_j) / range_j;
                // Scale to [feature_min, feature_max]
                result[[i, j]] = scaled * (feature_max - feature_min) + feature_min;
            }
        }
    }

    Ok(result)
}

/// Normalization types for the normalize function
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NormType {
    /// L1 norm (sum of absolute values)
    L1,
    /// L2 norm (square root of sum of squares)
    L2,
    /// Max norm (maximum absolute value)
    Max,
}

/// Calculate the standard deviation along the specified axis
#[allow(dead_code)]
fn standard_deviation<F: Float + FromPrimitive + Debug>(
    data: ArrayView2<F>,
    axis: Axis,
) -> Result<Array1<F>> {
    let mean = data.mean_axis(axis).expect("Operation failed");
    let n = F::from_usize(match axis {
        Axis(0) => data.shape()[0],
        Axis(1) => data.shape()[1],
        _ => return Err(ClusteringError::InvalidInput("Invalid axis".into())),
    })
    .expect("Operation failed");

    let mut variance = match axis {
        Axis(0) => Array1::zeros(data.shape()[1]),
        Axis(1) => Array1::zeros(data.shape()[0]),
        _ => return Err(ClusteringError::InvalidInput("Invalid axis".into())),
    };

    if axis == Axis(0) {
        // Calculate variance along rows (for each feature)
        let n_features = data.shape()[1];
        for j in 0..n_features {
            let mut sum_squared_diff = F::zero();
            for i in 0..data.shape()[0] {
                let diff = data[[i, j]] - mean[j];
                sum_squared_diff = sum_squared_diff + diff * diff;
            }
            // Avoid division by zero for single sample
            if n > F::one() {
                variance[j] = sum_squared_diff / (n - F::one());
            } else {
                variance[j] = F::zero();
            }
        }
    } else {
        // Calculate variance along columns (for each sample)
        let n_samples = data.shape()[0];
        for i in 0..n_samples {
            let mut sum_squared_diff = F::zero();
            for j in 0..data.shape()[1] {
                let diff = data[[i, j]] - mean[i];
                sum_squared_diff = sum_squared_diff + diff * diff;
            }
            // Avoid division by zero for single feature
            if n > F::one() {
                variance[i] = sum_squared_diff / (n - F::one());
            } else {
                variance[i] = F::zero();
            }
        }
    }

    // Calculate standard deviation
    let std_dev = variance.mapv(|x| x.sqrt());

    // Replace zeros with ones to avoid division by zero
    let std_dev = std_dev.mapv(|x| if x <= F::epsilon() { F::one() } else { x });

    Ok(std_dev)
}

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

    #[test]
    fn test_whiten() {
        let data =
            Array2::from_shape_vec((3, 3), vec![1.9, 2.3, 1.7, 1.5, 2.5, 2.2, 0.8, 0.6, 1.7])
                .expect("Operation failed");

        let whitened = whiten(data.view(), true).expect("Operation failed");

        // Check that each feature has approximately unit variance
        let std_dev = standard_deviation(whitened.view(), Axis(0)).expect("Operation failed");
        for &std in std_dev.iter() {
            assert_abs_diff_eq!(std, 1.0, epsilon = 1e-10);
        }
    }

    #[test]
    fn test_standardize() {
        let data =
            Array2::from_shape_vec((3, 3), vec![1.9, 2.3, 1.7, 1.5, 2.5, 2.2, 0.8, 0.6, 1.7])
                .expect("Operation failed");

        let standardized = standardize(data.view(), true).expect("Operation failed");

        // Check that each feature has approximately zero mean
        let mean = standardized.mean_axis(Axis(0)).expect("Operation failed");
        for mean_val in mean.iter() {
            assert_abs_diff_eq!(*mean_val, 0.0, epsilon = 1e-10);
        }

        // Check that each feature has approximately unit variance
        let std_dev = standard_deviation(standardized.view(), Axis(0)).expect("Operation failed");
        for std_val in std_dev.iter() {
            assert_abs_diff_eq!(*std_val, 1.0, epsilon = 1e-10);
        }
    }

    #[test]
    fn test_normalize_l2() {
        let data =
            Array2::from_shape_vec((3, 3), vec![1.9, 2.3, 1.7, 1.5, 2.5, 2.2, 0.8, 0.6, 1.7])
                .expect("Operation failed");

        let normalized = normalize(data.view(), NormType::L2, true).expect("Operation failed");

        // Check that each sample has L2 norm approximately equal to 1
        for i in 0..data.shape()[0] {
            let row = normalized.row(i);
            let norm_sq: f64 = row.iter().fold(0.0, |acc, &x| acc + x * x);
            let norm = norm_sq.sqrt();
            assert_abs_diff_eq!(norm, 1.0, epsilon = 1e-10);
        }
    }

    #[test]
    fn test_min_max_scale() {
        let data =
            Array2::from_shape_vec((3, 3), vec![1.9, 2.3, 1.7, 1.5, 2.5, 2.2, 0.8, 0.6, 1.7])
                .expect("Operation failed");

        let scaled = min_max_scale(data.view(), (0.0, 1.0), true).expect("Operation failed");

        // Check that all values are in the range [0, 1]
        for val in scaled.iter() {
            assert!(*val >= 0.0 && *val <= 1.0);
        }

        // Check that for each feature, the minimum value is 0.0 and the maximum is 1.0
        for j in 0..data.shape()[1] {
            let column = scaled.column(j);

            // Convert the values to f64 for stable comparison
            let column_values: Vec<f64> = column.iter().copied().collect();

            if !column_values.is_empty() {
                let min_val = column_values
                    .iter()
                    .fold(f64::INFINITY, |min, &x| min.min(x));
                let max_val = column_values
                    .iter()
                    .fold(f64::NEG_INFINITY, |max, &x| max.max(x));

                // Only check if the feature had different values in the original data
                if data.column(j).iter().any(|&x| x != data[[0, j]]) {
                    assert_abs_diff_eq!(min_val, 0.0, epsilon = 1e-10);
                    assert_abs_diff_eq!(max_val, 1.0, epsilon = 1e-10);
                }
            }
        }
    }
}