Files

216 lines
9.0 KiB
Python

"""Counting core tests — FCP counting-logic parity."""
import copy
import pytest
from src.config import DEFAULTS, load_config
from src.counting import LineCrossCounter, MultiClassLineCounter
from src.interfaces import Detection
from src.validation import ValidationError, validate_config
def _det(tid: int, y1: int, cls: str = "sack", cx: float = 150.0) -> Detection:
"""Detection with top edge at y1, centred on cx."""
return Detection(bbox=(cx - 50.0, float(y1), cx + 50.0, float(y1 + 50)),
confidence=0.9, class_id=0, class_name=cls, track_id=tid)
def test_unloading_requires_prior_loading():
"""Track first seen below the line never counts as unloading."""
c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000)
assert c.update([_det(7, 130)]) == [] # first seen below -> no event
assert c.update([_det(7, 10)]) == [] # now above -> still no unloading
assert c.unloading_count == 0
assert c.loading_count == 0
def test_track_counted_at_most_once():
"""FCP single-direction lock: one track counts once overall, as loading.
A track that loads and then leaves the truck again is not counted twice —
the loading stays, the unloading never happens.
"""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
c.update([_det(1, 250)]) # first seen below -> initial zone "below"
c.update([_det(1, 140)]) # above
events = c.update([_det(1, 250)]) # below again -> loading
assert [e["direction"] for e in events] == ["loading"]
c.update([_det(1, 140)]) # above again (streak 1)
c.update([_det(1, 140)]) # streak 2
events = c.update([_det(1, 140)]) # streak 3 -> would be an unloading
assert events == []
assert c.loading_count == 1
assert c.unloading_count == 0
def test_reset_clears_loaded_tracks():
"""reset() clears the loaded-track registry (FCP src/counting.py:235)."""
c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000)
c.update([_det(1, 10)])
c.update([_det(1, 130)])
assert c._loaded_tracks == {1}
c.reset()
assert c._loaded_tracks == set()
c.update([_det(1, 130)])
assert c.update([_det(1, 10)]) == []
assert c.unloading_count == 0
def test_reset_state_keeps_totals_but_clears_track_state():
"""reset_state() clears dedup state but keeps the clip totals."""
c = LineCrossCounter(line_y=100, line_x_start=0, line_x_end=1000)
c.update([_det(4, 10)])
c.update([_det(4, 130)])
assert c.loading_count == 1
c.reset_state()
assert c.loading_count == 1 # totals survive
assert c.unloading_count == 0
assert c._loaded_tracks == set() # per-track state cleared
# the same track may cross again in the next batch
assert [e["direction"] for e in c.update([_det(4, 10)])] == []
assert [e["direction"] for e in c.update([_det(4, 130)])] == ["loading"]
# ── FCP counting gates (karung_counter_semarang, main, src/counting.py) ───
def test_constructor_defaults_match_fcp_config():
"""Defaults mirror FCP's runtime config values (config_loader.py CountingConfig)."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
assert c._capture_below == 100.0
assert c._max_step_dy == 160.0
assert c._max_gap_frames == 15
assert c._unload_confirm_frames == 1
def test_corridor_below_capture_below_never_counts():
"""A sack deep in the truck bed never triggers a loading count."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
capture_below=100)
c.update([_det(1, 100)]) # above the line
events = c.update([_det(1, 400)]) # 180 px below -> beyond the corridor
assert events == []
assert c.loading_count == 0
def test_corridor_keeps_initial_zone():
"""FCP parity: the corridor filter preserves the initial zone."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
capture_below=100)
c.update([_det(1, 100)]) # above -> initial zone "above"
assert c._initial_zone[1] == "above"
c.update([_det(1, 400)]) # deep in the bed -> corridor filter
assert c._initial_zone[1] == "above"
events = c.update([_det(1, 250)]) # back in corridor -> still no loading (_has_been_above cleared)
assert events == []
assert c.loading_count == 0
def test_id_switch_large_dy_resets_history():
"""A vertical jump (ID switch) drops the track history, so no loading."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
max_step_dy=120)
c.update([_det(1, 100)]) # above
c.update([_det(1, 300)]) # 200 px jump -> history reset
events = c.update([_det(1, 300)])
assert events == []
assert c.loading_count == 0
def test_stale_gap_resets_history():
"""A track that vanished longer than max_gap_frames loses its history."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
max_step_dy=0, max_gap_frames=2)
c.update([_det(1, 100)]) # above
c.update([]) # missing
c.update([]) # missing
events = c.update([_det(1, 300)]) # reappears below after the gap
assert events == []
assert c.loading_count == 0
def test_unload_confirm_frames_requires_consecutive_above_frames():
"""The unload gate counts consecutive "above" frames only.
The streak is the gate's input: it grows while the track stays above the
line and resets on every other frame. FCP's unloading branch also needs
an empty direction set, which a counted track cannot have, so no
unloading is published either way.
"""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280,
unload_confirm_frames=3)
c.update([_det(1, 250)]) # below the line
c.update([_det(1, 140)]) # above: streak 1
c.update([_det(1, 140)]) # above: streak 2
assert c._above_streak[1] == 2
c.update([_det(1, 250)]) # back below: streak reset
assert c._above_streak[1] == 0
c.update([_det(1, 140)]) # streak 1
c.update([_det(1, 140)]) # streak 2
c.update([_det(1, 140)]) # streak 3 -> confirm threshold reached
assert c._above_streak[1] == 3
assert c.unloading_count == 0
def test_same_direction_dx_dedup():
"""Two tracks crossing at nearly the same x count once (same direction)."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
c.update([_det(1, 140, cx=600.0)])
events = c.update([_det(1, 250, cx=600.0)])
assert [e["direction"] for e in events] == ["loading"]
c.update([_det(2, 140, cx=610.0)])
c.update([_det(2, 200, cx=610.0)])
events = c.update([_det(2, 300, cx=610.0)]) # 10 px sideways, 50 px lower
assert events == []
assert c.loading_count == 1
def test_update_line_keeps_existing_track_history():
"""update_line changes the geometry only — per-track history survives."""
c = LineCrossCounter(line_y=220, line_x_start=0, line_x_end=1280)
c.update([_det(1, 140)]) # above the old line
c.update_line(500, 0, 1280) # new line, far below
c.update([_det(1, 250)]) # still above the new line
c.update([_det(1, 370)])
c.update([_det(1, 490)]) # in the band of the new line
events = c.update([_det(1, 550)]) # below the new line
assert len(events) == 1
assert events[0]["direction"] == "loading"
def test_multiclass_forwards_gates_and_update_line():
"""Both class counters get the same gates and the same line geometry."""
c = MultiClassLineCounter(line_y=220, line_x_start=0, line_x_end=1280,
capture_below=100.0, max_step_dy=160.0,
max_gap_frames=15, unload_confirm_frames=1)
for counter in (c._sack, c._box):
assert counter._capture_below == 100.0
assert counter._max_step_dy == 160.0
assert counter._max_gap_frames == 15
assert counter._unload_confirm_frames == 1
c.update_line(500, 10, 1200)
assert c._sack.line_y == 500 and c._box.line_y == 500
assert c._sack.line_x_start == 10 and c._box.line_x_end == 1200
# ── counting config section ───────────────────────────────────────────
def test_counting_config_section_matches_fcp_values():
"""config.yaml + DEFAULTS carry the four counting gates (FCP runtime values)."""
cfg = load_config()
counting = cfg["counting"]
assert counting["capture_below_px"] == 100
assert counting["max_step_dy_px"] == 160
assert counting["max_gap_frames"] == 15
assert counting["unload_confirm_frames"] == 1
assert DEFAULTS["counting"] == counting
def test_validate_config_rejects_negative_counting_value():
cfg = copy.deepcopy(DEFAULTS)
cfg["counting"]["capture_below_px"] = -1
with pytest.raises(ValidationError):
validate_config(cfg)