|
| 1 | +"""Appearance-descriptor sidecar: a seeded, pixel-free, GT-derived re-id cue. |
| 2 | +
|
| 3 | +Covers the contract of :mod:`multicam_sim.appearance`: deterministic sampling |
| 4 | +across seeds, unit-norm/shape invariants, edge cases, the monotonic |
| 5 | +``separation`` dose-response knob, and — the safety property — that attaching the |
| 6 | +sidecar to a :class:`Scene` leaves the byte-golden analytic manifest untouched |
| 7 | +(the manifest builder ignores it). |
| 8 | +
|
| 9 | +The descriptor deliberately does NOT encode the ground-truth ``entity_id``; it |
| 10 | +models OSNet-style confusability, and ``separation`` is the axis a re-id |
| 11 | +evaluation sweeps to trace accuracy vs. identity separability. |
| 12 | +""" |
| 13 | + |
| 14 | +from __future__ import annotations |
| 15 | + |
| 16 | +import math |
| 17 | + |
| 18 | +import numpy as np |
| 19 | +import pytest |
| 20 | + |
| 21 | +from multicam_sim import build_manifest, build_smoke_scene |
| 22 | +from multicam_sim.appearance import AppearanceTable, EntityAppearance |
| 23 | +from multicam_sim.scene import Scene |
| 24 | + |
| 25 | +_ENTITY_IDS = ["entity_a", "entity_b", "entity_c", "entity_d"] |
| 26 | + |
| 27 | + |
| 28 | +def _is_unit(vec: list[float], *, tol: float = 1e-9) -> bool: |
| 29 | + return math.isclose(math.sqrt(sum(x * x for x in vec)), 1.0, abs_tol=tol) |
| 30 | + |
| 31 | + |
| 32 | +def _mean_pairwise_cosine(table: AppearanceTable) -> float: |
| 33 | + """Mean cosine similarity over all distinct entity pairs (unit descriptors, so |
| 34 | + cosine == dot product).""" |
| 35 | + vecs = [np.asarray(e.descriptor) for e in table.entries] |
| 36 | + sims = [float(vecs[i] @ vecs[j]) for i in range(len(vecs)) for j in range(i + 1, len(vecs))] |
| 37 | + return sum(sims) / len(sims) |
| 38 | + |
| 39 | + |
| 40 | +def test_determinism_same_inputs_identical() -> None: |
| 41 | + """Same (entity_ids, dim, separation, seed) -> byte-identical descriptors.""" |
| 42 | + a = AppearanceTable.sample(_ENTITY_IDS, dim=512, separation=0.8, seed=7) |
| 43 | + b = AppearanceTable.sample(_ENTITY_IDS, dim=512, separation=0.8, seed=7) |
| 44 | + assert a == b |
| 45 | + assert [e.descriptor for e in a.entries] == [e.descriptor for e in b.entries] |
| 46 | + |
| 47 | + |
| 48 | +@pytest.mark.parametrize("seed", [0, 7, 42]) |
| 49 | +def test_seeds_give_distinct_valid_unit_vectors(seed: int) -> None: |
| 50 | + """Each seed yields valid unit-norm descriptors; different seeds differ.""" |
| 51 | + table = AppearanceTable.sample(_ENTITY_IDS, dim=256, separation=0.9, seed=seed) |
| 52 | + assert len(table.entries) == len(_ENTITY_IDS) |
| 53 | + for entry in table.entries: |
| 54 | + assert len(entry.descriptor) == 256 |
| 55 | + assert _is_unit(entry.descriptor) |
| 56 | + assert all(math.isfinite(x) for x in entry.descriptor) |
| 57 | + |
| 58 | + other = AppearanceTable.sample(_ENTITY_IDS, dim=256, separation=0.9, seed=seed + 1) |
| 59 | + assert table.entries[0].descriptor != other.entries[0].descriptor |
| 60 | + |
| 61 | + |
| 62 | +def test_descriptor_does_not_encode_entity_id() -> None: |
| 63 | + """Renaming entities (same seed/dim/separation) keeps the descriptor vectors |
| 64 | + identical: the vector is a function of draw order, not of the id string, so it |
| 65 | + cannot be inverted to the GT id.""" |
| 66 | + a = AppearanceTable.sample(["x0", "x1", "x2"], dim=128, separation=0.7, seed=3) |
| 67 | + b = AppearanceTable.sample(["y0", "y1", "y2"], dim=128, separation=0.7, seed=3) |
| 68 | + assert [e.descriptor for e in a.entries] == [e.descriptor for e in b.entries] |
| 69 | + |
| 70 | + |
| 71 | +@pytest.mark.parametrize("seed", [0, 7, 42]) |
| 72 | +def test_separation_knob_monotonic(seed: int) -> None: |
| 73 | + """Mean pairwise inter-entity cosine similarity increases monotonically as |
| 74 | + separation falls 1.0 -> 0.0 (the re-id dose-response axis). Coarse steps clear |
| 75 | + the ~1/sqrt(dim) noise floor comfortably.""" |
| 76 | + separations = [1.0, 0.75, 0.5, 0.25, 0.0] |
| 77 | + sims = [ |
| 78 | + _mean_pairwise_cosine(AppearanceTable.sample(_ENTITY_IDS, dim=512, separation=s, seed=seed)) |
| 79 | + for s in separations |
| 80 | + ] |
| 81 | + # separations descend, so similarities must strictly ascend. |
| 82 | + for lower, higher in zip(sims, sims[1:], strict=False): |
| 83 | + assert higher > lower, f"non-monotone at seed {seed}: {sims}" |
| 84 | + |
| 85 | + # Endpoints: near-orthogonal (perfectly separable) at 1.0, collapsed at 0.0. |
| 86 | + assert sims[0] < 0.2 |
| 87 | + assert math.isclose(sims[-1], 1.0, abs_tol=1e-6) |
| 88 | + |
| 89 | + |
| 90 | +def test_unit_norm_and_shape_invariants() -> None: |
| 91 | + """Every descriptor is unit-norm and exactly `dim` long, across separations.""" |
| 92 | + for separation in (1.0, 0.5, 0.0): |
| 93 | + table = AppearanceTable.sample(_ENTITY_IDS, dim=64, separation=separation, seed=11) |
| 94 | + assert table.dim == 64 |
| 95 | + for entry in table.entries: |
| 96 | + assert len(entry.descriptor) == 64 |
| 97 | + assert _is_unit(entry.descriptor) |
| 98 | + |
| 99 | + |
| 100 | +def test_empty_entity_ids() -> None: |
| 101 | + """No entities -> empty table, no crash (mean never computed).""" |
| 102 | + table = AppearanceTable.sample([], dim=512, separation=0.5, seed=1) |
| 103 | + assert table.entries == [] |
| 104 | + assert table.dim == 512 |
| 105 | + |
| 106 | + |
| 107 | +def test_single_entity() -> None: |
| 108 | + """One entity -> its unchanged unit anchor, no mean-blend, no pairwise math.""" |
| 109 | + table = AppearanceTable.sample(["solo"], dim=128, separation=0.3, seed=2) |
| 110 | + assert len(table.entries) == 1 |
| 111 | + assert _is_unit(table.entries[0].descriptor) |
| 112 | + # Separation is irrelevant with one entity: any separation gives the same |
| 113 | + # anchor for a fixed seed. |
| 114 | + other = AppearanceTable.sample(["solo"], dim=128, separation=0.9, seed=2) |
| 115 | + assert table.entries[0].descriptor == other.entries[0].descriptor |
| 116 | + |
| 117 | + |
| 118 | +def test_default_dim_is_512() -> None: |
| 119 | + table = AppearanceTable.sample(_ENTITY_IDS, separation=0.8, seed=5) |
| 120 | + assert table.dim == 512 |
| 121 | + assert all(len(e.descriptor) == 512 for e in table.entries) |
| 122 | + |
| 123 | + |
| 124 | +def test_validation_rejects_out_of_range_separation() -> None: |
| 125 | + with pytest.raises(ValueError): |
| 126 | + AppearanceTable(dim=8, separation=1.5, seed=0, entries=[]) |
| 127 | + with pytest.raises(ValueError): |
| 128 | + AppearanceTable(dim=0, separation=0.5, seed=0, entries=[]) |
| 129 | + with pytest.raises(ValueError): |
| 130 | + EntityAppearance(entity_id="e", descriptor=[]) |
| 131 | + |
| 132 | + |
| 133 | +def test_roundtrip_json() -> None: |
| 134 | + """Table survives a JSON round-trip unchanged (the sidecar payload).""" |
| 135 | + table = AppearanceTable.sample(_ENTITY_IDS, dim=32, separation=0.6, seed=9) |
| 136 | + restored = AppearanceTable.model_validate_json(table.to_json()) |
| 137 | + assert restored == table |
| 138 | + |
| 139 | + |
| 140 | +def _scene_with_appearance(*, attach: bool) -> Scene: |
| 141 | + scene = build_smoke_scene() |
| 142 | + if not attach: |
| 143 | + return scene |
| 144 | + ids = [e.id for e in scene.entities] |
| 145 | + table = AppearanceTable.sample(ids, dim=512, separation=0.7, seed=13) |
| 146 | + return scene.model_copy(update={"appearance": table}) |
| 147 | + |
| 148 | + |
| 149 | +def test_manifest_byte_identical_with_and_without_sidecar() -> None: |
| 150 | + """Attaching the appearance sidecar changes NOTHING in the analytic manifest: |
| 151 | + the serialized bytes with and without it are exactly equal (manifest builder |
| 152 | + ignores the sidecar; byte-golden default preserved).""" |
| 153 | + with_side = build_manifest(_scene_with_appearance(attach=True)).to_json().encode() |
| 154 | + without = build_manifest(_scene_with_appearance(attach=False)).to_json().encode() |
| 155 | + assert with_side == without |
| 156 | + |
| 157 | + |
| 158 | +def test_manifest_excludes_appearance_sidecar() -> None: |
| 159 | + """The manifest never contains appearance GT, even when the scene carries it.""" |
| 160 | + manifest_json = build_manifest(_scene_with_appearance(attach=True)).to_json() |
| 161 | + assert "appearance" not in manifest_json |
| 162 | + assert "descriptor" not in manifest_json |
0 commit comments