panlabel 0.6.0

The universal annotation converter
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
//! Dataset sampling utilities.

use rand::seq::SliceRandom;
use rand::{rngs::StdRng, Rng, RngExt, SeedableRng};
use std::collections::{HashMap, HashSet};

use crate::error::PanlabelError;
use crate::ir::{CategoryId, Dataset, ImageId};

/// Image sampling strategy.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SampleStrategy {
    /// Uniform random sampling.
    Random,
    /// Category-aware weighted sampling.
    Stratified,
}

/// Category filtering mode.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CategoryMode {
    /// Keep whole images that contain at least one selected category.
    Images,
    /// Keep only matching annotations; drop images with no remaining annotations.
    Annotations,
}

/// Sampling options.
#[derive(Clone, Debug)]
pub struct SampleOptions {
    pub n: Option<usize>,
    pub fraction: Option<f64>,
    pub seed: Option<u64>,
    pub strategy: SampleStrategy,
    pub categories: Vec<String>,
    pub category_mode: CategoryMode,
}

/// Validate sampling options before running.
pub fn validate_sample_options(opts: &SampleOptions) -> Result<(), PanlabelError> {
    match (opts.n, opts.fraction) {
        (Some(_), Some(_)) => {
            return Err(PanlabelError::InvalidSampleParams {
                message: "-n and --fraction are mutually exclusive".to_string(),
            });
        }
        (None, None) => {
            return Err(PanlabelError::InvalidSampleParams {
                message: "set exactly one of -n or --fraction".to_string(),
            });
        }
        _ => {}
    }

    if let Some(n) = opts.n {
        if n == 0 {
            return Err(PanlabelError::InvalidSampleParams {
                message: "-n must be greater than 0".to_string(),
            });
        }
    }

    if let Some(fraction) = opts.fraction {
        if !(0.0 < fraction && fraction <= 1.0) {
            return Err(PanlabelError::InvalidSampleParams {
                message: "--fraction must be in the interval (0.0, 1.0]".to_string(),
            });
        }
    }

    Ok(())
}

/// Sample a dataset according to options.
pub fn sample_dataset(dataset: &Dataset, opts: &SampleOptions) -> Result<Dataset, PanlabelError> {
    validate_sample_options(opts)?;

    let filtered = filter_dataset_by_categories(dataset, &opts.categories, opts.category_mode)?;
    if filtered.images.is_empty() {
        return Err(PanlabelError::SampleFailed {
            message: "no images available after category filtering".to_string(),
        });
    }

    let target = target_image_count(filtered.images.len(), opts.n, opts.fraction);
    if target == 0 {
        return Err(PanlabelError::SampleFailed {
            message: "requested sample size is zero".to_string(),
        });
    }

    let selected_ids = match opts.strategy {
        SampleStrategy::Random => select_image_ids_random(&filtered, target, opts.seed),
        SampleStrategy::Stratified => select_image_ids_stratified(&filtered, target, opts.seed),
    };

    let keep: HashSet<ImageId> = selected_ids.into_iter().collect();
    Ok(subset_by_image_ids(&filtered, &keep))
}

/// Filter dataset by categories according to mode.
pub fn filter_dataset_by_categories(
    dataset: &Dataset,
    categories: &[String],
    mode: CategoryMode,
) -> Result<Dataset, PanlabelError> {
    if categories.is_empty() {
        return Ok(dataset.clone());
    }

    let requested: HashSet<String> = categories
        .iter()
        .map(|c| c.trim())
        .filter(|c| !c.is_empty())
        .map(str::to_string)
        .collect();

    if requested.is_empty() {
        return Ok(dataset.clone());
    }

    let mut selected_category_ids: HashSet<CategoryId> = HashSet::new();
    for category in &dataset.categories {
        if requested.contains(&category.name) {
            selected_category_ids.insert(category.id);
        }
    }

    if selected_category_ids.is_empty() {
        return Err(PanlabelError::InvalidSampleParams {
            message: "none of the requested categories were found in the dataset".to_string(),
        });
    }

    let (images, annotations) = match mode {
        CategoryMode::Images => {
            let keep_image_ids: HashSet<ImageId> = dataset
                .annotations
                .iter()
                .filter(|ann| selected_category_ids.contains(&ann.category_id))
                .map(|ann| ann.image_id)
                .collect();

            let images = dataset
                .images
                .iter()
                .filter(|image| keep_image_ids.contains(&image.id))
                .cloned()
                .collect();

            let annotations = dataset
                .annotations
                .iter()
                .filter(|ann| keep_image_ids.contains(&ann.image_id))
                .cloned()
                .collect();

            (images, annotations)
        }
        CategoryMode::Annotations => {
            let annotations: Vec<_> = dataset
                .annotations
                .iter()
                .filter(|ann| selected_category_ids.contains(&ann.category_id))
                .cloned()
                .collect();

            let keep_image_ids: HashSet<ImageId> =
                annotations.iter().map(|ann| ann.image_id).collect();

            let images = dataset
                .images
                .iter()
                .filter(|image| keep_image_ids.contains(&image.id))
                .cloned()
                .collect();

            (images, annotations)
        }
    };

    Ok(Dataset {
        info: dataset.info.clone(),
        licenses: dataset.licenses.clone(),
        images,
        categories: dataset.categories.clone(),
        annotations,
    })
}

/// Compute target image count from n/fraction.
pub fn target_image_count(total: usize, n: Option<usize>, fraction: Option<f64>) -> usize {
    if total == 0 {
        return 0;
    }

    if let Some(n) = n {
        return n.min(total);
    }

    if let Some(frac) = fraction {
        let raw = (total as f64 * frac).ceil() as usize;
        return raw.clamp(1, total);
    }

    0
}

fn sorted_image_ids(dataset: &Dataset) -> Vec<ImageId> {
    let mut rows: Vec<(String, ImageId)> = dataset
        .images
        .iter()
        .map(|image| (image.file_name.clone(), image.id))
        .collect();

    rows.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
    rows.into_iter().map(|(_, id)| id).collect()
}

/// Select image IDs uniformly at random.
pub fn select_image_ids_random(dataset: &Dataset, k: usize, seed: Option<u64>) -> Vec<ImageId> {
    let mut ids = sorted_image_ids(dataset);

    if k >= ids.len() {
        return ids;
    }

    if let Some(seed) = seed {
        let mut rng = StdRng::seed_from_u64(seed);
        ids.shuffle(&mut rng);
    } else {
        let mut rng = rand::rng();
        ids.shuffle(&mut rng);
    }

    ids.truncate(k);
    ids.sort();
    ids
}

/// Select image IDs with category-aware weighted sampling without replacement.
pub fn select_image_ids_stratified(dataset: &Dataset, k: usize, seed: Option<u64>) -> Vec<ImageId> {
    let ids = sorted_image_ids(dataset);
    if k >= ids.len() {
        return ids;
    }

    let mut category_freq: HashMap<CategoryId, usize> = HashMap::new();
    for ann in &dataset.annotations {
        *category_freq.entry(ann.category_id).or_insert(0) += 1;
    }

    let mut image_categories: HashMap<ImageId, HashSet<CategoryId>> = HashMap::new();
    for ann in &dataset.annotations {
        image_categories
            .entry(ann.image_id)
            .or_default()
            .insert(ann.category_id);
    }

    let mut candidates: Vec<(ImageId, f64)> = ids
        .iter()
        .map(|id| {
            let weight = image_categories
                .get(id)
                .map(|cats| {
                    cats.iter()
                        .map(|cat_id| {
                            let freq = *category_freq.get(cat_id).unwrap_or(&1) as f64;
                            1.0 / freq
                        })
                        .sum::<f64>()
                })
                .unwrap_or(0.0);
            (*id, weight)
        })
        .collect();

    let mut selected: Vec<ImageId> = Vec::with_capacity(k);

    if let Some(seed) = seed {
        let mut rng = StdRng::seed_from_u64(seed);
        weighted_sample_without_replacement(&mut candidates, k, &mut selected, &mut rng);
    } else {
        let mut rng = rand::rng();
        weighted_sample_without_replacement(&mut candidates, k, &mut selected, &mut rng);
    }

    selected.sort();
    selected
}

fn weighted_sample_without_replacement<R: Rng + ?Sized>(
    candidates: &mut Vec<(ImageId, f64)>,
    k: usize,
    selected: &mut Vec<ImageId>,
    rng: &mut R,
) {
    while selected.len() < k && !candidates.is_empty() {
        let total_weight: f64 = candidates.iter().map(|(_, w)| w.max(0.0)).sum();

        let pick_index = if total_weight <= 0.0 {
            rng.random_range(0..candidates.len())
        } else {
            let mut draw = rng.random::<f64>() * total_weight;
            let mut index = candidates.len() - 1;

            for (i, (_, weight)) in candidates.iter().enumerate() {
                draw -= weight.max(0.0);
                if draw <= 0.0 {
                    index = i;
                    break;
                }
            }

            index
        };

        let (image_id, _) = candidates.swap_remove(pick_index);
        selected.push(image_id);
    }
}

/// Create a subset dataset by selected image IDs, preserving original IDs.
pub fn subset_by_image_ids(dataset: &Dataset, keep: &HashSet<ImageId>) -> Dataset {
    let images = dataset
        .images
        .iter()
        .filter(|image| keep.contains(&image.id))
        .cloned()
        .collect();

    let annotations = dataset
        .annotations
        .iter()
        .filter(|ann| keep.contains(&ann.image_id))
        .cloned()
        .collect();

    Dataset {
        info: dataset.info.clone(),
        licenses: dataset.licenses.clone(),
        images,
        categories: dataset.categories.clone(),
        annotations,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::{Annotation, BBoxXYXY, Category, Image, Pixel};

    fn make_dataset() -> Dataset {
        Dataset {
            images: vec![
                Image::new(1u64, "a.jpg", 100, 100),
                Image::new(2u64, "b.jpg", 100, 100),
                Image::new(3u64, "c.jpg", 100, 100),
            ],
            categories: vec![Category::new(1u64, "person"), Category::new(2u64, "dog")],
            annotations: vec![
                Annotation::new(
                    1u64,
                    1u64,
                    1u64,
                    BBoxXYXY::<Pixel>::from_xyxy(1.0, 1.0, 10.0, 10.0),
                ),
                Annotation::new(
                    2u64,
                    1u64,
                    2u64,
                    BBoxXYXY::<Pixel>::from_xyxy(2.0, 2.0, 12.0, 12.0),
                ),
                Annotation::new(
                    3u64,
                    2u64,
                    1u64,
                    BBoxXYXY::<Pixel>::from_xyxy(3.0, 3.0, 14.0, 14.0),
                ),
            ],
            ..Default::default()
        }
    }

    #[test]
    fn validate_opts_rejects_invalid_combinations() {
        let both = SampleOptions {
            n: Some(1),
            fraction: Some(0.5),
            seed: None,
            strategy: SampleStrategy::Random,
            categories: Vec::new(),
            category_mode: CategoryMode::Images,
        };
        assert!(validate_sample_options(&both).is_err());

        let none = SampleOptions {
            n: None,
            fraction: None,
            seed: None,
            strategy: SampleStrategy::Random,
            categories: Vec::new(),
            category_mode: CategoryMode::Images,
        };
        assert!(validate_sample_options(&none).is_err());
    }

    #[test]
    fn random_sampling_is_deterministic_with_seed() {
        let dataset = make_dataset();
        let a = select_image_ids_random(&dataset, 2, Some(42));
        let b = select_image_ids_random(&dataset, 2, Some(42));
        assert_eq!(a, b);
    }

    #[test]
    fn annotations_mode_keeps_all_categories() {
        let dataset = make_dataset();
        let filtered = filter_dataset_by_categories(
            &dataset,
            &["person".to_string()],
            CategoryMode::Annotations,
        )
        .expect("filter ok");

        assert_eq!(filtered.categories.len(), 2);
        assert!(filtered
            .annotations
            .iter()
            .all(|ann| ann.category_id == 1u64.into()));
    }
}