Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173"""wait_for_change's detector over generated frames of noisy regions.
The defects: noise counted as change (random noise, blocks that flicker fromthe start, blocks that start moving while the floor is measured), a changeseen during calibration, min_change not added to the noise floor, a changeunder min_change accepted or one over it missed, the wrong frame or fractionreported, and a timeout message that misstates what was seen. The detectoris pure, so frames stand in for screenshots; a real browser only adds thesleeps."""
from dataclasses import dataclassfrom pathlib import Pathimport randomimport sysimport unittest
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python"))sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import hypothesis_profiles # noqa: E402, F401from hypothesis import given, settings, strategies as st # noqa: E402from albedo_plugins.browser.pixels import ChangeDetector # noqa: E402
# How far a changed block moves: past any noise and tolerance generated here.DELTA = 130.0# How far a flickering block jumps every frame.FLICKER = 90.0
Frame = list[tuple[float, ...]]
@dataclass(frozen=True)class Scene: blocks: int calibration: int floor: int tolerance: float # Random noise every frame, within this many channel units of the base. amplitude: float seed: int # Disjoint block sets: flickering from the first frame, moving from the # first floor frame on, and changing from frame `start` on. flicker: frozenset[int] drift: frozenset[int] change: frozenset[int] start: int # min_change sits halfway between two block counts, so it is never a tie. wanted: int
@property def min_change(self) -> float: return (self.wanted + 0.5) / self.blocks
def frames(self, count: int) -> list[Frame]: rng = random.Random(self.seed) base = [rng.uniform(0, 100) for _ in range(self.blocks)] floor_start = 1 + self.calibration frames: list[Frame] = [] for n in range(count): frame: Frame = [] for b, value in enumerate(base): value += rng.uniform(-self.amplitude, self.amplitude) if b in self.flicker and n % 2: value += FLICKER if b in self.drift and n >= floor_start: value += DELTA if b in self.change and n >= self.start: value += DELTA frame.append((value,)) frames.append(frame) return frames
@st.compositedef scenes(draw): blocks = draw(st.integers(4, 40)) calibration = draw(st.integers(0, 5)) floor = draw(st.integers(1, 4)) tolerance = draw(st.sampled_from([0.0, 8.0, 24.0, 40.0])) amplitude = draw(st.sampled_from([0.0, tolerance / 4, tolerance / 2])) roles = draw( st.lists( st.sampled_from(["still", "still", "flicker", "drift", "change"]), min_size=blocks, max_size=blocks, ) )
def having(role): return frozenset(b for b, r in enumerate(roles) if r == role)
# Flicker is learned as noise from a calibration frame, and random noise # around it must stay inside the tolerance that learning adds. learnable = calibration and amplitude <= tolerance / 4 flicker = having("flicker") if learnable else frozenset() measured = 1 + calibration + floor start = draw(st.integers(measured, measured + 4)) wanted = draw(st.integers(0, blocks - 1)) return Scene( blocks, calibration, floor, tolerance, amplitude, draw(st.integers(0, 2**32)), flicker, having("drift"), having("change"), start, wanted, )
def run(scene, horizon): """Feed frames until the detector answers; the frame index and fraction, or None and the detector after `horizon` frames.""" detector = ChangeDetector( scene.min_change, scene.tolerance, scene.calibration, scene.floor ) for n, frame in enumerate(scene.frames(horizon)): assert detector.measuring == (n <= scene.calibration + scene.floor) fraction = detector.feed(frame) if fraction is not None: return n, fraction, detector return None, None, detector
class ChangeDetectorTests(unittest.TestCase): @settings(max_examples=hypothesis_profiles.cases(400)) @given(scenes()) def test_a_change_counts_only_above_the_noise_floor(self, scene): floor = len(scene.drift) / scene.blocks changed = len(scene.change) / scene.blocks horizon = scene.start + 6 found, fraction, detector = run(scene, horizon) self.assertAlmostEqual(detector.floor, floor) if changed >= scene.min_change: # Seen on the frame it happened, with the floor's blocks counted. self.assertEqual(found, scene.start) self.assertAlmostEqual(fraction, changed + floor) else: self.assertIsNone(found) self.assertAlmostEqual(detector.most, changed + floor) self.assertEqual( detector.shortfall(), f"Region did not change enough: max change {changed + floor:.1%}," f" noise floor {floor:.1%}, wanted {scene.min_change:.1%}.", )
def test_a_timeout_during_calibration_reports_an_unmeasured_floor(self): detector = ChangeDetector(0.02, 24, 4, 3) detector.feed([(0.0,)]) self.assertIn("noise floor unmeasured", detector.shortfall())
def test_half_the_region_holds_to_min_change(self): """The old browser case: half of a quiet region turns blue.""" quiet: Frame = [(0.0,)] * 8 half: Frame = [(200.0,)] * 4 + [(0.0,)] * 4 frames = [quiet] * 8 + [half] short = ChangeDetector(0.6, 24, 4, 3) self.assertEqual([short.feed(frame) for frame in frames][-1], None) self.assertEqual( short.shortfall(), "Region did not change enough: max change 50.0%," " noise floor 0.0%, wanted 60.0%.", ) enough = ChangeDetector(0.4, 24, 4, 3) self.assertEqual([enough.feed(frame) for frame in frames][-1], 0.5)
if __name__ == "__main__": unittest.main()