russell_lab 1.13.0

Scientific laboratory for linear algebra and numerical mathematics
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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
use std::mem;

/// Sorts 2 values in ascending order
///
/// # Examples
///
/// ```
/// use russell_lab::sort2;
///
/// let mut numbers = (3.0, 2.0);
/// sort2(&mut numbers);
/// assert_eq!(numbers, (2.0, 3.0));
/// ```
pub fn sort2<T>(x: &mut (T, T))
where
    T: PartialOrd,
{
    if x.1 < x.0 {
        mem::swap(&mut x.1, &mut x.0);
    }
}

/// Sorts 3 values in ascending order
///
/// # Examples
///
/// ```
/// use russell_lab::sort3;
///
/// let mut numbers = (1.0, 3.0, 2.0);
/// sort3(&mut numbers);
/// assert_eq!(numbers, (1.0, 2.0, 3.0));
/// ```
pub fn sort3<T>(x: &mut (T, T, T))
where
    T: PartialOrd,
{
    if x.1 < x.0 {
        mem::swap(&mut x.1, &mut x.0);
    }
    if x.2 < x.1 {
        mem::swap(&mut x.2, &mut x.1);
    }
    if x.1 < x.0 {
        mem::swap(&mut x.1, &mut x.0);
    }
}

/// Sorts 4 values in ascending order
///
/// # Examples
///
/// ```
/// use russell_lab::sort4;
///
/// let mut numbers = (1.0, 3.0, 2.0, 0.0);
/// sort4(&mut numbers);
/// assert_eq!(numbers, (0.0, 1.0, 2.0, 3.0));
/// ```
pub fn sort4<T>(x: &mut (T, T, T, T))
where
    T: PartialOrd,
{
    if x.1 < x.0 {
        mem::swap(&mut x.0, &mut x.1);
    }
    if x.2 < x.1 {
        mem::swap(&mut x.1, &mut x.2);
    }
    if x.3 < x.2 {
        mem::swap(&mut x.2, &mut x.3);
    }
    if x.1 < x.0 {
        mem::swap(&mut x.0, &mut x.1);
    }
    if x.2 < x.1 {
        mem::swap(&mut x.1, &mut x.2);
    }
    if x.1 < x.0 {
        mem::swap(&mut x.0, &mut x.1);
    }
}

/// Returns the indices that would sort a f64 array in ascending order
///
/// **Warning:** The NaN values are considered equal in this function, i.e., they
/// are not handled well enough and **care should be taken** if NaNs are expected.
///
/// # Arguments
///
/// * `data` -- vector to sort
/// * `tol` -- tolerance for comparing floating-point numbers
///
/// # Returns
///
/// A vector of indices that would sort the input vector
///
/// # Examples
///
/// ```
/// use russell_lab::argsort_f64;
///
/// let data = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0, 5.0, 3.0];
/// assert_eq!(argsort_f64(&data, 1e-9), &[1, 3, 6, 0, 9, 2, 4, 8, 7, 5]);
/// ```
pub fn argsort_f64(data: &[f64], tol: f64) -> Vec<usize> {
    let mut indices: Vec<usize> = (0..data.len()).collect();
    indices.sort_by(|&i, &j| {
        if (data[i] - data[j]).abs() < tol {
            std::cmp::Ordering::Equal
        } else {
            data[i].partial_cmp(&data[j]).unwrap_or(std::cmp::Ordering::Equal)
        }
    });
    indices
}

/// Returns the indices that would sort two f64 arrays in ascending order
///
/// The function sorts primarily by `y`, then by `x`.
/// Both input vectors must have the same length.
///
/// **Warning:** The NaN values are considered equal in this function, i.e., they
/// are not handled well enough and **care should be taken** if NaNs are expected.
///
/// # Arguments
///
/// * `y` -- first vector to sort by
/// * `x` -- second vector to sort by when `y` values are equal
/// * `tol` -- slice of two tolerances for comparing floating-point numbers
///    One tolerance for each vector y and x. For example: `[tol_y, tol_x]`.
///
/// # Returns
///
/// A vector of indices that would sort the input vectors
///
/// # Panics
///
/// Panics if the input vectors have different lengths or if the tolerance slice does not have exactly two elements
///
/// # Examples
///
/// ```
/// use russell_lab::argsort2_f64;
///
/// //     y
/// // 4.0 +                  (0)
/// //     |
/// // 3.0 +   (4)
/// //     |
/// // 2.0 +   (2)
/// //     |
/// // 1.0 +        (3)  (1)
/// //     |
/// //     +----+----+----+----+-- x
/// //    0.0  1.0  2.0  3.0  4.0
/// let x = vec![4.0, 3.0, 1.0, 2.0, 1.0];
/// let y = vec![4.0, 1.0, 2.0, 1.0, 3.0];
/// let sorted_indices = argsort2_f64(&y, &x, &[1e-9, 1e-9]);
/// assert_eq!(sorted_indices, vec![3, 1, 2, 4, 0]);
/// ```
pub fn argsort2_f64(y: &[f64], x: &[f64], tol: &[f64]) -> Vec<usize> {
    assert_eq!(y.len(), x.len(), "vectors must have equal length");
    assert_eq!(tol.len(), 2, "tolerance slice must have exactly two elements");

    let mut indices: Vec<usize> = (0..y.len()).collect();
    indices.sort_by(|&i, &j| {
        if (y[i] - y[j]).abs() < tol[0] {
            std::cmp::Ordering::Equal
        } else {
            y[i].partial_cmp(&y[j]).unwrap_or(std::cmp::Ordering::Equal)
        }
        .then_with(|| {
            if (x[i] - x[j]).abs() < tol[1] {
                std::cmp::Ordering::Equal
            } else {
                x[i].partial_cmp(&x[j]).unwrap_or(std::cmp::Ordering::Equal)
            }
        })
    });
    indices
}

/// Returns the indices that would sort three f64 arrays in ascending order
///
/// The function sorts primarily by `z`, then by `y`, and finally by `x`.
/// All input vectors must have the same length.
///
/// **Warning:** The NaN values are considered equal in this function, i.e., they
/// are not handled well enough and **care should be taken** if NaNs are expected.
///
/// # Arguments
///
/// * `z` -- first vector to sort by
/// * `y` -- second vector to sort by when `z` values are equal
/// * `x` -- third vector to sort by when both `z` and `y` values are equal
/// * `tol` -- slice of three tolerances for comparing floating-point numbers.
///    One tolerance for each vector z, y, and x. For example: `[tol_z, tol_y, tol_x]`.
///
/// # Returns
///
/// A vector of indices that would sort the input vectors
///
/// # Panics
///
/// Panics if the input vectors have different lengths or if the tolerance slice does not have exactly three elements
///
/// # Examples
///
/// ```
/// use russell_lab::argsort3_f64;
///
/// //       4--------------7  1.0
/// //      /.             /|
/// //     / .            / |
/// //    /  .           /  |
/// //   /   .          /   |
/// //  5--------------6    |          z
/// //  |    .         |    |          ↑
/// //  |    0---------|----3  0.0     o → y
/// //  |   /          |   /          ↙
/// //  |  /           |  /          x
/// //  | /            | /
/// //  |/             |/
/// //  1--------------2   1.0
/// // 0.0            1.0
/// let x = vec![0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0];
/// let y = vec![0.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0];
/// let z = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0];
/// let indices = argsort3_f64(&z, &y, &x, &[1e-9, 1e-9, 1e-9]);
/// assert_eq!(indices, vec![/*z=0*/ 0, 1, 3, 2, /*z=1*/ 4, 5, 7, 6]);
/// ```
pub fn argsort3_f64(z: &[f64], y: &[f64], x: &[f64], tol: &[f64]) -> Vec<usize> {
    assert!(
        z.len() == y.len() && y.len() == x.len(),
        "vectors must have equal length"
    );
    assert_eq!(tol.len(), 3, "tolerance slice must have exactly three elements");

    let mut indices: Vec<usize> = (0..z.len()).collect();

    indices.sort_by(|&a, &b| {
        if (z[a] - z[b]).abs() < tol[0] {
            std::cmp::Ordering::Equal
        } else {
            z[a].partial_cmp(&z[b]).unwrap_or(std::cmp::Ordering::Equal)
        }
        .then_with(|| {
            if (y[a] - y[b]).abs() < tol[1] {
                std::cmp::Ordering::Equal
            } else {
                y[a].partial_cmp(&y[b]).unwrap_or(std::cmp::Ordering::Equal)
            }
        })
        .then_with(|| {
            if (x[a] - x[b]).abs() < tol[2] {
                std::cmp::Ordering::Equal
            } else {
                x[a].partial_cmp(&x[b]).unwrap_or(std::cmp::Ordering::Equal)
            }
        })
    });
    indices
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::{argsort2_f64, argsort3_f64, argsort_f64, sort2, sort3, sort4};

    #[test]
    fn sort2_works() {
        let mut x = (1, 2);
        sort2(&mut x);
        assert_eq!(x, (1, 2));

        let mut x = (2, 1);
        sort2(&mut x);
        assert_eq!(x, (1, 2));

        let mut x = (1.0, 2.0);
        sort2(&mut x);
        assert_eq!(x, (1.0, 2.0));

        let mut x = (2.0, 1.0);
        sort2(&mut x);
        assert_eq!(x, (1.0, 2.0));
    }

    #[test]
    fn sort3_works() {
        let mut x = (1, 2, 3);
        sort3(&mut x);
        assert_eq!(x, (1, 2, 3));

        let mut x = (1, 3, 2);
        sort3(&mut x);
        assert_eq!(x, (1, 2, 3));

        let mut x = (3, 2, 1);
        sort3(&mut x);
        assert_eq!(x, (1, 2, 3));
    }

    #[test]
    fn sort4_works() {
        let mut x = (1, 2, 3, 4);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (2, 1, 3, 4);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (2, 3, 1, 4);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (2, 3, 4, 1);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (1, 3, 2, 4);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (1, 3, 4, 2);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (3, 1, 2, 4);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (4, 1, 2, 3);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (1, 4, 2, 3);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));

        let mut x = (4, 3, 2, 1);
        sort4(&mut x);
        assert_eq!(x, (1, 2, 3, 4));
    }

    #[test]
    fn argsort_f64_works() {
        let data = [3.0, 1.0, 4.0, 1.0, 5.0, 9.0, 2.0, 6.0, 5.0, 3.0];
        assert_eq!(argsort_f64(&data, 1e-9), &[1, 3, 6, 0, 9, 2, 4, 8, 7, 5]);

        let data = [3.0, 1.0, 8.0, -5.0];
        assert_eq!(argsort_f64(&data, 1e-9), &[3, 1, 0, 2]);
    }

    #[test]
    fn argsort2_f64_works_basic() {
        let x = vec![1.0, 2.0, 1.0, 3.0];
        let y = vec![3.0, 1.0, 2.0, 1.0];
        let tol = [1e-9, 1e-9];

        let sorted_indices = argsort2_f64(&y, &x, &tol);
        assert_eq!(sorted_indices, vec![1, 3, 2, 0]);
    }

    #[test]
    fn argsort2_f64_works_equal_y() {
        let y = vec![1.0, 1.0, 1.0];
        let x = vec![3.0, 2.0, 1.0];
        let tol = [1e-9, 1e-9];

        let sorted_indices = argsort2_f64(&y, &x, &tol);
        assert_eq!(sorted_indices, vec![2, 1, 0]);
    }

    #[test]
    fn argsort2_f64_works_equal_x_y() {
        let y = vec![2.0, 2.0, 2.0];
        let x = vec![2.0, 2.0, 2.0];
        let tol = [1e-9, 1e-9];

        let sorted_indices = argsort2_f64(&y, &x, &tol);
        assert_eq!(sorted_indices, vec![0, 1, 2]);
    }

    #[test]
    fn argsort2_f64_works_single_element() {
        let y = vec![1.0];
        let x = vec![2.0];
        let tol = [1e-9, 1e-9];

        let sorted_indices = argsort2_f64(&y, &x, &tol);
        assert_eq!(sorted_indices, vec![0]);
    }

    #[test]
    #[should_panic(expected = "vectors must have equal length")]
    fn argsort2_f64_works_different_lengths() {
        let y = vec![1.0, 2.0];
        let x = vec![1.0];
        let tol = [1e-9, 1e-9];

        argsort2_f64(&y, &x, &tol);
    }

    #[test]
    #[should_panic(expected = "tolerance slice must have exactly two elements")]
    fn argsort2_f64_works_invalid_tol_length() {
        let y = vec![1.0, 2.0];
        let x = vec![1.0, 2.0];
        let tol = [1e-9];

        argsort2_f64(&y, &x, &tol);
    }

    #[test]
    fn argsort3_f64_works_basic() {
        let x = vec![3.0, 1.0, 2.0, 1.0];
        let y = vec![1.0, 2.0, 1.0, 3.0];
        let z = vec![5.0, 4.0, 3.0, 2.0];
        let tol = [1e-9, 1e-9, 1e-9];

        let sorted_indices = argsort3_f64(&x, &y, &z, &tol);
        assert_eq!(sorted_indices, vec![1, 3, 2, 0]);
    }

    #[test]
    fn argsort3_f64_works_equal_x() {
        let x = vec![1.0, 1.0, 1.0];
        let y = vec![3.0, 2.0, 1.0];
        let z = vec![1.0, 2.0, 3.0];
        let tol = [1e-9, 1e-9, 1e-9];

        let sorted_indices = argsort3_f64(&x, &y, &z, &tol);
        assert_eq!(sorted_indices, vec![2, 1, 0]);
    }

    #[test]
    fn argsort3_f64_works_equal_x_y() {
        let x = vec![1.0, 1.0, 1.0];
        let y = vec![2.0, 2.0, 2.0];
        let z = vec![3.0, 1.0, 2.0];
        let tol = [1e-9, 1e-9, 1e-9];

        let sorted_indices = argsort3_f64(&x, &y, &z, &tol);
        assert_eq!(sorted_indices, vec![1, 2, 0]);
    }

    #[test]
    fn argsort3_f64_works_equal_x_y_z() {
        let x = vec![1.0, 1.0, 1.0];
        let y = vec![2.0, 2.0, 2.0];
        let z = vec![3.0, 3.0, 3.0];
        let tol = [1e-9, 1e-9, 1e-9];

        let sorted_indices = argsort3_f64(&x, &y, &z, &tol);
        assert_eq!(sorted_indices, vec![0, 1, 2]);
    }

    #[test]
    fn argsort3_f64_works_single_element() {
        let x = vec![1.0];
        let y = vec![2.0];
        let z = vec![3.0];
        let tol = [1e-9, 1e-9, 1e-9];

        let sorted_indices = argsort3_f64(&x, &y, &z, &tol);
        assert_eq!(sorted_indices, vec![0]);
    }

    #[test]
    #[should_panic(expected = "vectors must have equal length")]
    fn argsort3_f64_works_different_lengths() {
        let x = vec![1.0, 2.0];
        let y = vec![1.0];
        let z = vec![1.0];
        let tol = [1e-9, 1e-9, 1e-9];

        argsort3_f64(&x, &y, &z, &tol);
    }

    #[test]
    #[should_panic(expected = "tolerance slice must have exactly three elements")]
    fn argsort3_f64_works_invalid_tol_length() {
        let x = vec![1.0, 2.0];
        let y = vec![1.0, 2.0];
        let z = vec![1.0, 2.0];
        let tol = [1e-9, 1e-9];

        argsort3_f64(&x, &y, &z, &tol);
    }

    #[test]
    fn argsort3_f64_works_with_imprecision() {
        let x = vec![
            0.7886751345948129,
            0.21132486540518716,
            0.788675134594813,
            0.7886751345948129,
            0.21132486540518716,
            0.788675134594813,
            0.21132486540518716,
            0.7886751345948129,
            0.21132486540518713,
            0.7886751345948129,
            0.21132486540518713,
            0.21132486540518716,
            0.788675134594813,
            0.21132486540518716,
            0.788675134594813,
            0.21132486540518716,
        ];
        let y = vec![
            0.7886751345948129,
            0.21132486540518716,
            0.21132486540518716,
            0.21132486540518716,
            0.788675134594813,
            0.788675134594813,
            0.21132486540518713,
            0.21132486540518716,
            0.7886751345948129,
            0.7886751345948129,
            0.7886751345948129,
            0.21132486540518716,
            0.21132486540518716,
            0.788675134594813,
            0.788675134594813,
            0.21132486540518713,
        ];
        let z = vec![
            0.2113248654051872,
            0.7886751345948129,
            0.7886751345948129,
            0.21132486540518716,
            0.788675134594813,
            0.788675134594813,
            1.211324865405187,
            1.2113248654051871,
            0.21132486540518716,
            1.2113248654051871,
            1.2113248654051874,
            1.7886751345948129,
            1.7886751345948129,
            1.788675134594813,
            1.788675134594813,
            0.21132486540518713,
        ];
        let tol = [1e-9, 1e-9, 1e-9];
        let indices = argsort3_f64(&z, &y, &x, &tol);
        let mut buf = String::new();
        for i in indices {
            buf.push_str(&format!("{:.5},{:.5},{:.5}\n", x[i], y[i], z[i]));
        }
        assert_eq!(
            buf,
            "0.21132,0.21132,0.21132\n\
             0.78868,0.21132,0.21132\n\
             0.21132,0.78868,0.21132\n\
             0.78868,0.78868,0.21132\n\
             0.21132,0.21132,0.78868\n\
             0.78868,0.21132,0.78868\n\
             0.21132,0.78868,0.78868\n\
             0.78868,0.78868,0.78868\n\
             0.21132,0.21132,1.21132\n\
             0.78868,0.21132,1.21132\n\
             0.21132,0.78868,1.21132\n\
             0.78868,0.78868,1.21132\n\
             0.21132,0.21132,1.78868\n\
             0.78868,0.21132,1.78868\n\
             0.21132,0.78868,1.78868\n\
             0.78868,0.78868,1.78868\n"
        );
    }
}