File size: 3,160 Bytes
dadf189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import random
from collections import defaultdict

import numpy as np
from torch.utils.data import Sampler


class CrossSensorBatchSampler(Sampler):
    """Batch sampler that guarantees k_cross (identity, finger) groups each
    contribute ≥2 samples from *different* sensors per batch.

    Remaining slots are filled randomly from the full index pool.

    FVC records (single-sensor per identity, dataset starts with "fvc") are
    excluded from anchor groups but are eligible for random fill slots.
    """

    def __init__(
        self,
        records: list[dict],
        batch_size: int,
        k_cross: int = 16,
        seed: int = 42,
    ):
        self.batch_size = batch_size
        self.k_cross = k_cross
        self.rng = random.Random(seed)

        # Build: (identity_id, finger_id) → sensor_id → [indices]
        raw: dict[tuple, dict[str, list[int]]] = defaultdict(
            lambda: defaultdict(list)
        )
        for i, rec in enumerate(records):
            ds = rec.get("dataset", "")
            if ds.startswith("fvc"):
                continue  # FVC: single sensor per identity — cannot anchor
            # PolyU (v11): contact vs contactless pairs ARE the L_sens signal.
            # Include PolyU in anchor groups.
            key = (rec["identity_id"], rec["finger_id"])
            raw[key][rec["sensor_id"]].append(i)

        # Keep only groups with ≥2 different sensors
        self.eligible: list[dict[str, list[int]]] = [
            dict(sensor_map)
            for sensor_map in raw.values()
            if len(sensor_map) >= 2
        ]

        self._all = np.arange(len(records), dtype=np.int64)
        self._n_batches = max(1, len(records) // batch_size)

        print(
            f"CrossSensorBatchSampler: {len(self.eligible)} eligible anchor groups "
            f"| k_cross={k_cross} anchored pairs/batch "
            f"| {self._n_batches} batches/epoch"
        )

    def __len__(self) -> int:
        return self._n_batches

    def __iter__(self):
        rng = self.rng
        eligible = self.eligible
        k = min(self.k_cross, len(eligible))

        for _ in range(self._n_batches):
            # Sample k anchor groups (no replacement within this batch)
            anchor_groups = rng.sample(eligible, k)
            anchor_set: set[int] = set()

            for sensor_map in anchor_groups:
                sensors = list(sensor_map.keys())
                s1, s2 = rng.sample(sensors, 2)
                anchor_set.add(rng.choice(sensor_map[s1]))
                anchor_set.add(rng.choice(sensor_map[s2]))

            batch = list(anchor_set)

            # Fill remaining slots using fast numpy boolean mask
            remaining = self.batch_size - len(batch)
            if remaining > 0:
                mask = np.ones(len(self._all), dtype=bool)
                mask[np.fromiter(anchor_set, dtype=np.int64)] = False
                pool = self._all[mask].tolist()
                fill_n = min(remaining, len(pool))
                batch.extend(rng.sample(pool, fill_n))

            rng.shuffle(batch)
            yield batch