mikan-rs 0.1.4

A medical image kit for segmentation metrics evaluation, native Rust support, and Python bindings for cross-language performance.
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
578
579
580
581
582
583
584
use nii::Nifti1Image;
use std::collections::BTreeMap;

use crate::utils::{argwhere, get_binary_edge, get_percentile, mean};
use kdtree::distance::squared_euclidean;
use kdtree::KdTree;
use log::warn;
use ndarray::prelude::*;
use ndarray_stats::QuantileExt;
use rayon::prelude::*;

/// A structure to calculate various metrics based on confusion matrix for binary classification or segmentation tasks.
#[derive(Debug, Clone)]
pub struct ConfusionMatrix {
    tp_count: f64,
    tn_count: f64,
    fp_count: f64,
    fn_count: f64,
    label: u8,
}

impl ConfusionMatrix {
    /// init ConfusionMatrix using two segmentation mask, can be used for segmentation task
    pub fn new(gt: &Nifti1Image<u8>, pred: &Nifti1Image<u8>, label: u8) -> Self {
        let gt_arr = gt.ndarray();
        let pred_arr = pred.ndarray();
        ConfusionMatrix::new_from_ndarray(gt_arr.view(), pred_arr.view(), label)
    }

    pub fn new_from_ndarray(gt: ArrayView3<u8>, pred: ArrayView3<u8>, label: u8) -> Self {
        let gt_slice = gt.as_slice().unwrap();
        let pred_slice = pred.as_slice().unwrap();

        let (tp, fp, fn_, tn) = gt_slice
            .par_iter()
            .zip(pred_slice.par_iter())
            .fold(
                || (0u64, 0u64, 0u64, 0u64),
                |(mut tp, mut fp, mut fn_, mut tn), (&a, &b)| {
                    match (a == label, b == label) {
                        (true, true) => tp += 1,
                        (false, true) => fp += 1,
                        (true, false) => fn_ += 1,
                        (false, false) => tn += 1,
                    }
                    (tp, fp, fn_, tn)
                },
            )
            .reduce(
                || (0, 0, 0, 0),
                |(a1, b1, c1, d1), (a2, b2, c2, d2)| (a1 + a2, b1 + b2, c1 + c2, d1 + d2),
            );

        ConfusionMatrix {
            tp_count: tp as f64,
            fp_count: fp as f64,
            fn_count: fn_ as f64,
            tn_count: tn as f64,
            label,
        }
    }

    /// Recall/Sensitivity/Hit rate/True positive rate (TPR)
    pub fn get_senstivity(&self) -> f64 {
        if (self.tp_count + self.fn_count) == 0.0 {
            return 0.;
        }
        self.tp_count / (self.tp_count + self.fn_count)
    }

    /// Selectivity/Specificity/True negative rate (TNR)
    pub fn get_specificity(&self) -> f64 {
        if (self.tn_count + self.fp_count) == 0.0 {
            return 0.0;
        }
        self.tn_count / (self.tn_count + self.fp_count)
    }

    /// Precision/Positive predictive value (PPV)
    pub fn get_precision(&self) -> f64 {
        if (self.tp_count + self.fp_count) == 0.0 {
            return 0.0;
        }
        self.tp_count / (self.tp_count + self.fp_count)
    }
    /// accuracy/acc/Rand Index/RI/准确性
    pub fn get_accuracy(&self) -> f64 {
        if (self.tp_count + self.tn_count + self.fp_count + self.fn_count) == 0.0 {
            return 0.0;
        }
        (self.tp_count + self.tn_count)
            / (self.tp_count + self.tn_count + self.fp_count + self.fn_count)
    }

    /// balanced accuracy / BACC
    pub fn get_balanced_accuracy(&self) -> f64 {
        (self.get_senstivity() + self.get_specificity()) / 2.0
    }

    /// Dice/DSC
    pub fn get_dice(&self) -> f64 {
        if (2.0 * self.tp_count + self.fp_count + self.fn_count) == 0.0 {
            warn!(
                "label={}, Dice=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        (2.0 * self.tp_count) / (2.0 * self.tp_count + self.fp_count + self.fn_count)
    }

    /// f-score
    pub fn get_f_score(&self) -> f64 {
        if (2.0 * self.tp_count + self.fp_count + self.fn_count) == 0.0 {
            warn!(
                "label={}, f-score=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        (2.0 * self.tp_count) / (2.0 * self.tp_count + self.fp_count + self.fn_count)
    }

    /// f-beta score
    pub fn get_f_beta_score(&self, beta: u8) -> f64 {
        if ((1 + beta.pow(2)) as f64 * self.tp_count
            + beta.pow(2) as f64 * self.fn_count * self.fp_count)
            == 0.0
        {
            warn!(
                "label={}, f-beta-score=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        ((1 + beta.pow(2)) as f64 * self.tp_count)
            / ((1 + beta.pow(2)) as f64 * self.tp_count
                + beta.pow(2) as f64 * self.fn_count * self.fp_count)
    }

    /// jaccard score/IoU
    pub fn get_jaccard_score(&self) -> f64 {
        if (self.tp_count + self.fp_count + self.fn_count) == 0.0 {
            warn!(
                "label={}, jaccard=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        self.tp_count / (self.tp_count + self.fp_count + self.fn_count)
    }

    /// fnr
    pub fn get_fnr(&self) -> f64 {
        if (self.fn_count + self.tp_count) == 0.0 {
            warn!(
                "label={}, fnr=0 due to FP: {}, FN: {}",
                self.label, self.tp_count, self.fn_count
            );
            return 0.0;
        }
        self.fn_count / (self.fn_count + self.tp_count)
    }

    /// fpr
    pub fn get_fpr(&self) -> f64 {
        if (self.fp_count + self.tn_count) == 0.0 {
            warn!(
                "fpr=0 due to TP: {}, FP: {}, FN: {}",
                self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        self.fp_count / (self.fp_count + self.tn_count)
    }

    /// volume similarity/VS/体积相似性
    pub fn get_volume_similarity(&self) -> f64 {
        if (2.0 * self.tp_count + self.fp_count + self.fn_count) == 0.0 {
            warn!(
                "label={}, vs=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        1.0 - (self.fn_count - self.fp_count).abs()
            / (2.0 * self.tp_count + self.fp_count + self.fn_count)
    }

    /// AUC/AUC_trapezoid/binary label AUC
    pub fn get_auc(&self) -> f64 {
        1.0 - 0.5 * (self.get_fpr() + self.get_fnr())
    }

    /// KAP/Kappa/CohensKapp
    pub fn get_kappa(&self) -> f64 {
        let sum_ = self.tp_count + self.tn_count + self.fp_count + self.fn_count;
        let fa = self.tp_count + self.tn_count;
        let fc = ((self.tn_count + self.fn_count) * (self.tn_count + self.fp_count)
            + (self.fp_count + self.tp_count) * (self.fn_count + self.tp_count))
            / sum_;
        if (sum_ - fc) == 0.0 {
            warn!(
                "label={}, kappa=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        (fa - fc) / (sum_ - fc)
    }

    pub fn get_mcc(&self) -> f64 {
        let top = self.tp_count * self.tn_count - self.fp_count * self.fn_count;

        // very huge
        let bot_raw = (self.tp_count + self.fp_count)
            * (self.tp_count + self.fn_count)
            * (self.tn_count + self.fp_count)
            * (self.tn_count + self.fn_count);
        if bot_raw == 0.0 {
            warn!(
                "label={}, mcc=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
        }
        let bot = bot_raw.sqrt();
        top / bot
    }

    pub fn get_nmcc(&self) -> f64 {
        let mcc = self.get_mcc();
        (mcc + 1.0) / 2.0
    }

    pub fn get_amcc(&self) -> f64 {
        self.get_mcc().abs()
    }

    /// adjust rand score/adjust rand index/ARI
    pub fn get_adjust_rand_score(&self) -> f64 {
        let top = self.tp_count * self.tn_count - self.fp_count * self.fn_count;
        let bot = (self.tp_count + self.fn_count) * (self.fn_count + self.tn_count)
            + (self.tp_count + self.fp_count) * (self.fp_count + self.tn_count);
        if bot == 0.0 {
            warn!(
                "label={}, ARI=0 due to TP: {}, FP: {}, FN: {}",
                self.label, self.tp_count, self.fp_count, self.fn_count
            );
            return 0.0;
        }
        2.0 * top / bot
    }

    pub fn get_all(&self) -> BTreeMap<String, f64> {
        let mut map = BTreeMap::new();
        map.insert("tp".to_string(), self.tp_count);
        map.insert("tn".to_string(), self.tn_count);
        map.insert("fp".to_string(), self.fp_count);
        map.insert("fn".to_string(), self.fn_count);
        map.insert("senstivity".to_string(), self.get_senstivity());
        map.insert("specificity".to_string(), self.get_specificity());
        map.insert("precision".to_string(), self.get_precision());
        map.insert("accuracy".to_string(), self.get_accuracy());
        map.insert(
            "balanced_accuracy".to_string(),
            self.get_balanced_accuracy(),
        );
        map.insert("dice".to_string(), self.get_dice());
        map.insert("f_score".to_string(), self.get_f_score());
        map.insert("jaccard_score".to_string(), self.get_jaccard_score());
        map.insert("fnr".to_string(), self.get_fnr());
        map.insert("fpr".to_string(), self.get_fpr());
        map.insert(
            "volume_similarity".to_string(),
            self.get_volume_similarity(),
        );
        map.insert("auc".to_string(), self.get_auc());
        map.insert("kappa".to_string(), self.get_kappa());
        map.insert("mcc".to_string(), self.get_mcc());
        map.insert("nmcc".to_string(), self.get_nmcc());
        map.insert("amcc".to_string(), self.get_amcc());
        map.insert(
            "adjust_rand_score".to_string(),
            self.get_adjust_rand_score(),
        );
        map
    }
}

struct KDTree {
    tree: KdTree<f64, usize, [f64; 3]>,
}

impl KDTree {
    fn new(points: &[(f64, f64, f64)]) -> Self {
        let mut kdtree = KdTree::new(3);
        for (idx, p) in points.iter().enumerate() {
            let point = [p.0 as f64, p.1 as f64, p.2 as f64];
            kdtree.add(point, idx).unwrap();
        }
        KDTree { tree: kdtree }
    }

    fn query(&self, points: &[(f64, f64, f64)]) -> Vec<f64> {
        points
            .par_iter()
            .map(|p| {
                let point = [p.0, p.1, p.2];
                let a = self.tree.nearest(&point, 1, &squared_euclidean).unwrap()[0];
                a.0 as f64
            })
            .collect()
    }
}

/// A structure to calculate various metrics based on distance for binary classification or segmentation tasks.
pub struct Distance {
    dist_pred_to_gt: Vec<f64>,
    dist_gt_to_pred: Vec<f64>,
}

impl Distance {
    pub fn new(gt: &Nifti1Image<u8>, pred: &Nifti1Image<u8>, label: u8) -> Self {
        // TODO: support different size, spacing, direction in the future, now we assume they are the same
        // Actually, having gt and pred in the same world space is enough
        assert_eq!(gt.get_size(), pred.get_size(), "Size mismatch");
        assert_eq!(gt.get_spacing(), pred.get_spacing(), "Spacing mismatch");
        assert_eq!(
            gt.get_direction(),
            pred.get_direction(),
            "Direction mismatch"
        );

        let spacing = gt.get_spacing().map(|x| x as f64);

        let gt_arr = gt.ndarray();
        let pred_arr = pred.ndarray();

        Distance::new_from_ndarray(gt_arr.view(), pred_arr.view(), spacing, label)
    }

    pub fn new_from_ndarray(
        gt_arr: ArrayView3<u8>,
        pred_arr: ArrayView3<u8>,
        spacing: [f64; 3],
        label: u8,
    ) -> Self {
        // Binarize
        let gt_arr = gt_arr.mapv(|x| if x == label { 1 } else { 0 });
        let pred_arr = pred_arr.mapv(|x| if x == label { 1 } else { 0 });

        // Get edge
        let gt_edge = get_binary_edge(&gt_arr);
        let pred_edge = get_binary_edge(&pred_arr);

        // Get edge argwhere
        let gt_argw: Vec<(usize, usize, usize)> = argwhere(&gt_edge, 1); // (z,y,x)
        let pred_argw: Vec<(usize, usize, usize)> = argwhere(&pred_edge, 1);

        // Convert to physical coordinates
        let gt_argw: Vec<(f64, f64, f64)> = gt_argw
            .par_iter()
            .map(|x| {
                let z = x.0 as f64 * spacing[2];
                let y = x.1 as f64 * spacing[1];
                let x = x.2 as f64 * spacing[0];
                (z, y, x)
            })
            .collect();

        let pred_argw: Vec<(f64, f64, f64)> = pred_argw
            .par_iter()
            .map(|x| {
                let z = x.0 as f64 * spacing[2];
                let y = x.1 as f64 * spacing[1];
                let x = x.2 as f64 * spacing[0];
                (z, y, x)
            })
            .collect();

        let dist_pred_to_gt = KDTree::new(&gt_argw).query(&pred_argw);
        let dist_gt_to_pred = KDTree::new(&pred_argw).query(&gt_argw);

        let dist_pred_to_gt = dist_pred_to_gt.par_iter().map(|x| x.sqrt()).collect(); // square
        let dist_gt_to_pred = dist_gt_to_pred.par_iter().map(|x| x.sqrt()).collect(); // square

        Distance {
            dist_pred_to_gt,
            dist_gt_to_pred,
        }
    }

    pub fn get_hausdorff_distance(&self) -> f64 {
        if self.dist_gt_to_pred.len() == 0 || self.dist_pred_to_gt.len() == 0 {
            warn!("hd=0 due to no voxels");
            return 0.0;
        }
        f64::max(
            Array::from(self.dist_pred_to_gt.clone())
                .max()
                .unwrap()
                .clone(),
            Array::from(self.dist_gt_to_pred.clone())
                .max()
                .unwrap()
                .clone(),
        )
    }

    pub fn get_hausdorff_distance_95(&self) -> f64 {
        if self.dist_gt_to_pred.len() == 0 || self.dist_pred_to_gt.len() == 0 {
            warn!("hd95=0 due to no voxels");
            return 0.0;
        }
        let mut dist_pred_to_gt = self.dist_pred_to_gt.clone();
        let mut dist_gt_to_pred = self.dist_gt_to_pred.clone();
        f64::max(
            get_percentile(&mut dist_pred_to_gt, 0.95),
            get_percentile(&mut dist_gt_to_pred, 0.95),
        )
    }

    pub fn get_assd(&self) -> f64 {
        if self.dist_gt_to_pred.len() == 0 || self.dist_pred_to_gt.len() == 0 {
            warn!("assd=0 due to no voxels");
            return 0.0;
        }
        let merged = self
            .dist_pred_to_gt
            .iter()
            .chain(self.dist_gt_to_pred.iter())
            .cloned()
            .collect();
        mean(&merged) as f64
    }

    pub fn get_masd(&self) -> f64 {
        if self.dist_gt_to_pred.len() == 0 || self.dist_pred_to_gt.len() == 0 {
            warn!("masd=0 due to no voxels");
            return 0.0;
        }
        ((mean(&self.dist_pred_to_gt) + mean(&self.dist_gt_to_pred)) / 2.0) as f64
    }

    pub fn get_all(&self) -> BTreeMap<String, f64> {
        let mut results = BTreeMap::new();
        results.insert(
            "hausdorff_distance".to_string(),
            self.get_hausdorff_distance(),
        );
        results.insert(
            "hausdorff_distance_95".to_string(),
            self.get_hausdorff_distance_95(),
        );
        results.insert("assd".to_string(), self.get_assd());
        results.insert("masd".to_string(), self.get_masd());
        results
    }
}

/// A ndarray api for python to calculate lots of metrics for given labels.
pub fn calc_metrics_use_ndarray(
    gt_arr: ArrayView3<u8>,
    pred_arr: ArrayView3<u8>,
    labels: &[u8],
    spacing: [f64; 3],
    with_distance: bool,
) -> Vec<BTreeMap<String, f64>> {
    let mut mat_results: Vec<BTreeMap<String, f64>> = labels
        .par_iter()
        .map(|&label| {
            let cm = ConfusionMatrix::new_from_ndarray(gt_arr, pred_arr, label);
            let mut all_results = cm.get_all();
            all_results.insert("label".to_string(), label as f64);
            all_results
        })
        .collect();

    if with_distance {
        let dist_results: Vec<BTreeMap<String, f64>> = labels
            .par_iter()
            .map(|&label| {
                let dst = Distance::new_from_ndarray(gt_arr, pred_arr, spacing, label);
                let mut all_results = dst.get_all();
                all_results.insert("label".to_string(), label as f64);
                all_results
            })
            .collect();
        for (map1, map2) in mat_results.iter_mut().zip(dist_results.iter()) {
            map1.extend(map2.iter().map(|(k, v)| (k.clone(), *v)));
        }
    }
    mat_results
}

#[cfg(test)]
mod test {

    use super::*;
    use std::error::Error;
    use std::path::Path;
    use std::time::Instant;

    #[test]
    fn test_matrix_from_image() -> Result<(), Box<dyn Error>> {
        let gt = Path::new(r"data\patients_26_ground_truth.nii.gz");
        let pred = Path::new(r"data\patients_26_segmentation.nii.gz");

        let gt = nii::read_image::<u8>(gt);
        let pred = nii::read_image::<u8>(pred);

        let t = Instant::now();

        // let unique_labels = merge_vector(unique(&gt_arr), unique(&pred_arr), true);
        let unique_labels = [1, 2, 3, 4, 5];

        let results: Vec<BTreeMap<String, f64>> = unique_labels
            .par_iter()
            .map(|&label| {
                let cm = ConfusionMatrix::new(&gt, &pred, label);
                let mut all_results = cm.get_all();
                all_results.insert("label".to_string(), label as f64);
                all_results
            })
            .collect();
        println!("{:?}", results);
        println!("Cost {:?} ms", t.elapsed().as_millis());

        Ok(())
    }

    #[test]
    fn test_distances() -> Result<(), Box<dyn Error>> {
        let gt = Path::new(r"data\patients_26_ground_truth.nii.gz");
        let pred = Path::new(r"data\patients_26_segmentation.nii.gz");

        let gt = nii::read_image::<u8>(gt);
        let pred = nii::read_image::<u8>(pred);

        let t = Instant::now();

        let label = 1;
        let dist = Distance::new(&gt, &pred, label);

        let hd = dist.get_hausdorff_distance();
        let hd95 = dist.get_hausdorff_distance_95();
        let assd = dist.get_assd();
        let masd = dist.get_masd();

        println!("Hausdorff distance: {} mm", hd);
        println!("Hausdorff distance 95%: {} mm", hd95);
        println!("Average Symmetric Surface Distance: {} mm", assd);
        println!("Mean Average Surface Distance: {} mm", masd);
        println!("Cost {:?} ms", t.elapsed().as_millis());

        Ok(())
    }

    #[test]
    fn test_mp_distances() -> Result<(), Box<dyn Error>> {
        let gt = Path::new(r"data\patients_26_ground_truth.nii.gz");
        let pred = Path::new(r"data\patients_26_segmentation.nii.gz");

        let gt = nii::read_image::<u8>(gt);
        let pred = nii::read_image::<u8>(pred);

        let t = Instant::now();

        let label: Vec<u8> = vec![1, 2, 3, 4, 5];

        let results: Vec<f64> = label
            .par_iter()
            .map(|label| {
                let dist = Distance::new(&gt, &pred, *label);
                dist.get_hausdorff_distance_95()
            })
            .collect();

        println!("Hausdorff distance 95: {:?} mm", results);
        println!("Cost {:?} ms", t.elapsed().as_millis());

        Ok(())
    }
}