scirs2-metrics 0.4.2

Machine Learning evaluation metrics module for SciRS2 (scirs2-metrics)
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
//! Keypoint Detection Metrics
//!
//! This module provides evaluation metrics for human pose estimation and
//! keypoint detection tasks, following COCO benchmark conventions:
//!
//! - **OKS** (Object Keypoint Similarity): COCO-standard per-instance metric
//! - **PCK** (Percentage of Correct Keypoints): threshold-based accuracy
//! - **PCKh**: PCK normalised by head size
//! - **Mean OKS**: dataset-level OKS averaging
//! - **Mean Keypoint Error**: average Euclidean distance for visible keypoints

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

// ─────────────────────────────────────────────────────────────────────────────
// Data Structures
// ─────────────────────────────────────────────────────────────────────────────

/// A single pose annotation with 2-D keypoint coordinates and visibility flags.
#[derive(Debug, Clone)]
pub struct KeypointAnnotation {
    /// `(x, y)` coordinates for each keypoint.
    pub keypoints: Vec<[f64; 2]>,
    /// Visibility flag per keypoint: `0` = absent, `1` = occluded, `2` = visible.
    pub visibility: Vec<u8>,
    /// Square root of the object area (used for OKS scale normalisation).
    pub scale: f64,
}

impl KeypointAnnotation {
    /// Validate that `keypoints` and `visibility` have the same length.
    pub fn validate(&self) -> Result<()> {
        if self.keypoints.len() != self.visibility.len() {
            return Err(MetricsError::DimensionMismatch(format!(
                "keypoints len {} != visibility len {}",
                self.keypoints.len(),
                self.visibility.len()
            )));
        }
        Ok(())
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// COCO Constants
// ─────────────────────────────────────────────────────────────────────────────

/// Default COCO sigmas for the 17 COCO body keypoints.
///
/// Order: nose, left_eye, right_eye, left_ear, right_ear,
/// left_shoulder, right_shoulder, left_elbow, right_elbow,
/// left_wrist, right_wrist, left_hip, right_hip,
/// left_knee, right_knee, left_ankle, right_ankle.
pub fn coco_sigmas() -> Vec<f64> {
    vec![
        0.026, // nose
        0.025, // left_eye
        0.025, // right_eye
        0.035, // left_ear
        0.035, // right_ear
        0.079, // left_shoulder
        0.079, // right_shoulder
        0.072, // left_elbow
        0.072, // right_elbow
        0.062, // left_wrist
        0.062, // right_wrist
        0.107, // left_hip
        0.107, // right_hip
        0.087, // left_knee
        0.087, // right_knee
        0.089, // left_ankle
        0.089, // right_ankle
    ]
}

// ─────────────────────────────────────────────────────────────────────────────
// OKS
// ─────────────────────────────────────────────────────────────────────────────

/// Object Keypoint Similarity (OKS) — COCO standard.
///
/// ```text
/// OKS = Σ_i [exp(−d_i² / (2 s² k_i²)) * δ(v_i > 0)] / Σ_i [δ(v_i > 0)]
/// ```
///
/// where `d_i` is the Euclidean distance between predicted and GT keypoint `i`,
/// `s` is the object scale (square root of area), and `k_i` is the per-keypoint
/// constant from `sigmas`.
///
/// # Arguments
/// * `predicted`    — predicted annotation
/// * `ground_truth` — ground-truth annotation
/// * `sigmas`       — per-keypoint sigma constants (same length as keypoints)
pub fn object_keypoint_similarity(
    predicted: &KeypointAnnotation,
    ground_truth: &KeypointAnnotation,
    sigmas: &[f64],
) -> Result<f64> {
    predicted.validate()?;
    ground_truth.validate()?;

    let n = predicted.keypoints.len();
    if n == 0 {
        return Err(MetricsError::InvalidInput(
            "keypoint annotations must have at least one keypoint".to_string(),
        ));
    }
    if ground_truth.keypoints.len() != n {
        return Err(MetricsError::DimensionMismatch(format!(
            "predicted has {n} keypoints but GT has {}",
            ground_truth.keypoints.len()
        )));
    }
    if sigmas.len() != n {
        return Err(MetricsError::DimensionMismatch(format!(
            "sigmas len {} != keypoints len {n}",
            sigmas.len()
        )));
    }

    let s = ground_truth.scale;
    if s <= 0.0 {
        return Err(MetricsError::InvalidInput(
            "object scale must be positive".to_string(),
        ));
    }

    let mut numerator = 0.0_f64;
    let mut denominator = 0.0_f64;

    for i in 0..n {
        let v_gt = ground_truth.visibility[i];
        if v_gt == 0 {
            // Keypoint absent in GT — skip.
            continue;
        }
        denominator += 1.0;

        let [px, py] = predicted.keypoints[i];
        let [gx, gy] = ground_truth.keypoints[i];
        let d_sq = (px - gx).powi(2) + (py - gy).powi(2);
        let ki = sigmas[i];
        let e = -d_sq / (2.0 * s * s * ki * ki);
        numerator += e.exp();
    }

    if denominator == 0.0 {
        return Ok(0.0);
    }
    Ok(numerator / denominator)
}

// ─────────────────────────────────────────────────────────────────────────────
// PCK / PCKh
// ─────────────────────────────────────────────────────────────────────────────

/// Percentage of Correct Keypoints (PCK) at threshold `t`.
///
/// A keypoint is "correct" when the predicted distance to GT is
/// `< threshold_fraction * reference_distance`.
///
/// Only visible keypoints (`visibility[i] > 0`) are evaluated.
pub fn pck(
    predicted: &[[f64; 2]],
    ground_truth: &[[f64; 2]],
    visibility: &[u8],
    threshold_fraction: f64,
    reference_distance: f64,
) -> Result<f64> {
    let n = predicted.len();
    if n == 0 {
        return Err(MetricsError::InvalidInput(
            "predicted keypoints must not be empty".to_string(),
        ));
    }
    if ground_truth.len() != n || visibility.len() != n {
        return Err(MetricsError::DimensionMismatch(format!(
            "predicted, ground_truth and visibility must all have length {n}"
        )));
    }
    if threshold_fraction <= 0.0 || reference_distance <= 0.0 {
        return Err(MetricsError::InvalidInput(
            "threshold_fraction and reference_distance must be positive".to_string(),
        ));
    }

    let threshold = threshold_fraction * reference_distance;
    let mut correct = 0usize;
    let mut total = 0usize;

    for i in 0..n {
        if visibility[i] == 0 {
            continue;
        }
        total += 1;
        let [px, py] = predicted[i];
        let [gx, gy] = ground_truth[i];
        let dist = ((px - gx).powi(2) + (py - gy).powi(2)).sqrt();
        if dist < threshold {
            correct += 1;
        }
    }

    if total == 0 {
        return Ok(0.0);
    }
    Ok(correct as f64 / total as f64)
}

/// PCKh: PCK with threshold relative to head size.
///
/// A keypoint is correct when predicted distance < `threshold_fraction * head_size`.
pub fn pckh(
    predicted: &[[f64; 2]],
    ground_truth: &[[f64; 2]],
    visibility: &[u8],
    head_size: f64,
    threshold_fraction: f64,
) -> Result<f64> {
    pck(
        predicted,
        ground_truth,
        visibility,
        threshold_fraction,
        head_size,
    )
}

// ─────────────────────────────────────────────────────────────────────────────
// Dataset-level metrics
// ─────────────────────────────────────────────────────────────────────────────

/// Mean OKS over a dataset.
///
/// Computes OKS for each (prediction, GT) pair and returns the mean.
pub fn mean_oks(
    predictions: &[KeypointAnnotation],
    ground_truths: &[KeypointAnnotation],
    sigmas: &[f64],
) -> Result<f64> {
    if predictions.is_empty() {
        return Err(MetricsError::InvalidInput(
            "predictions must not be empty".to_string(),
        ));
    }
    if predictions.len() != ground_truths.len() {
        return Err(MetricsError::DimensionMismatch(format!(
            "predictions len {} != ground_truths len {}",
            predictions.len(),
            ground_truths.len()
        )));
    }
    let total: f64 = predictions
        .iter()
        .zip(ground_truths)
        .map(|(pred, gt)| object_keypoint_similarity(pred, gt, sigmas))
        .sum::<Result<f64>>()?;
    Ok(total / predictions.len() as f64)
}

/// Mean Euclidean keypoint error for visible keypoints.
///
/// Returns the average distance between predicted and GT keypoints
/// where `visibility[i] > 0`.
pub fn mean_keypoint_error(
    predicted: &[[f64; 2]],
    ground_truth: &[[f64; 2]],
    visibility: &[u8],
) -> Result<f64> {
    let n = predicted.len();
    if n == 0 {
        return Err(MetricsError::InvalidInput(
            "predicted keypoints must not be empty".to_string(),
        ));
    }
    if ground_truth.len() != n || visibility.len() != n {
        return Err(MetricsError::DimensionMismatch(format!(
            "predicted, ground_truth and visibility must all have length {n}"
        )));
    }

    let mut total_dist = 0.0_f64;
    let mut count = 0usize;

    for i in 0..n {
        if visibility[i] == 0 {
            continue;
        }
        let [px, py] = predicted[i];
        let [gx, gy] = ground_truth[i];
        total_dist += ((px - gx).powi(2) + (py - gy).powi(2)).sqrt();
        count += 1;
    }

    if count == 0 {
        return Ok(0.0);
    }
    Ok(total_dist / count as f64)
}

// ─────────────────────────────────────────────────────────────────────────────
// Tests
// ─────────────────────────────────────────────────────────────────────────────

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

    fn make_annotation(kps: Vec<[f64; 2]>, vis: Vec<u8>, scale: f64) -> KeypointAnnotation {
        KeypointAnnotation {
            keypoints: kps,
            visibility: vis,
            scale,
        }
    }

    #[test]
    fn test_oks_perfect_prediction() {
        let kps = vec![[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]];
        let vis = vec![2, 2, 2];
        let sigmas = vec![0.05, 0.05, 0.05];
        let pred = make_annotation(kps.clone(), vis.clone(), 50.0);
        let gt = make_annotation(kps, vis, 50.0);
        let oks = object_keypoint_similarity(&pred, &gt, &sigmas).expect("should succeed");
        assert!(
            (oks - 1.0).abs() < 1e-10,
            "perfect OKS should be 1.0, got {oks}"
        );
    }

    #[test]
    fn test_oks_large_distance_near_zero() {
        let gt_kps = vec![[0.0, 0.0], [0.0, 0.0]];
        let pred_kps = vec![[1000.0, 1000.0], [1000.0, 1000.0]];
        let vis = vec![2, 2];
        let sigmas = vec![0.05, 0.05];
        let pred = make_annotation(pred_kps, vis.clone(), 1.0);
        let gt = make_annotation(gt_kps, vis, 1.0);
        let oks = object_keypoint_similarity(&pred, &gt, &sigmas).expect("should succeed");
        assert!(
            oks < 1e-6,
            "OKS for very large error should be ~0, got {oks}"
        );
    }

    #[test]
    fn test_pck_all_correct() {
        let kps: Vec<[f64; 2]> = vec![[1.0, 1.0], [2.0, 2.0], [3.0, 3.0]];
        let vis = vec![2, 2, 2];
        let score = pck(&kps, &kps, &vis, 0.1, 100.0).expect("should succeed");
        assert!(
            (score - 1.0).abs() < 1e-12,
            "perfect PCK should be 1.0, got {score}"
        );
    }

    #[test]
    fn test_pck_none_correct() {
        let pred = vec![[0.0, 0.0], [0.0, 0.0]];
        let gt = vec![[100.0, 100.0], [200.0, 200.0]];
        let vis = vec![2, 2];
        // threshold = 0.01 * 1.0 = 0.01; distances are >> 0.01
        let score = pck(&pred, &gt, &vis, 0.01, 1.0).expect("should succeed");
        assert!((score - 0.0).abs() < 1e-12, "expected PCK=0, got {score}");
    }

    #[test]
    fn test_pckh_head_size_reference() {
        let pred = vec![[10.0, 10.0], [20.0, 20.0]];
        let gt = vec![[10.0, 10.0], [20.0, 20.0]];
        let vis = vec![2, 2];
        let score = pckh(&pred, &gt, &vis, 200.0, 0.5).expect("should succeed");
        assert!(
            (score - 1.0).abs() < 1e-12,
            "expected PCKh=1.0, got {score}"
        );
    }

    #[test]
    fn test_mean_oks_batch() {
        let kps = vec![[5.0, 5.0], [10.0, 10.0]];
        let vis = vec![2, 2];
        let sigmas = vec![0.05, 0.05];
        let ann = make_annotation(kps.clone(), vis.clone(), 20.0);
        let predictions = vec![ann.clone(), ann.clone()];
        let ground_truths = vec![ann.clone(), ann];
        let moks = mean_oks(&predictions, &ground_truths, &sigmas).expect("should succeed");
        assert!(
            (moks - 1.0).abs() < 1e-10,
            "mean OKS for perfect predictions should be 1.0, got {moks}"
        );
    }

    #[test]
    fn test_mean_keypoint_error_perfect() {
        let kps = vec![[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]];
        let vis = vec![2, 2, 2];
        let err = mean_keypoint_error(&kps, &kps, &vis).expect("should succeed");
        assert!(
            err.abs() < 1e-12,
            "perfect predictions → error = 0, got {err}"
        );
    }

    #[test]
    fn test_coco_sigmas_returns_17() {
        let s = coco_sigmas();
        assert_eq!(s.len(), 17, "COCO has 17 body keypoints, got {}", s.len());
        for (i, &sigma) in s.iter().enumerate() {
            assert!(sigma > 0.0, "sigma[{i}] must be positive, got {sigma}");
        }
    }

    #[test]
    fn test_oks_invisible_keypoints_excluded() {
        // GT visibility = 0 for first keypoint → should not contribute to denominator
        let pred_kps = vec![[999.0, 999.0], [10.0, 10.0]];
        let gt_kps = vec![[0.0, 0.0], [10.0, 10.0]];
        let vis_gt = vec![0, 2]; // first invisible
        let sigmas = vec![0.05, 0.05];
        let pred = KeypointAnnotation {
            keypoints: pred_kps,
            visibility: vec![2, 2],
            scale: 50.0,
        };
        let gt = KeypointAnnotation {
            keypoints: gt_kps,
            visibility: vis_gt,
            scale: 50.0,
        };
        let oks = object_keypoint_similarity(&pred, &gt, &sigmas).expect("should succeed");
        // Only second keypoint evaluated; perfect match → OKS = 1.0
        assert!(
            (oks - 1.0).abs() < 1e-10,
            "invisible GT keypoints should be excluded, OKS={oks}"
        );
    }
}