-
Notifications
You must be signed in to change notification settings - Fork 47
feat: add adaptive zone anomaly baselines using Welford's algorithm #91
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Devnil434
merged 1 commit into
Devnil434:main
from
dilshadalikhan2004:feat/adaptive-zone-baseline
May 19, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| """ | ||
| apps/backend/routes/zones.py — Zone adaptive baseline statistics endpoint. | ||
|
|
||
| GET /zones/{name}/stats | ||
| Returns Welford running statistics for the named zone. | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| from fastapi import APIRouter, Depends, HTTPException, Request | ||
| from pydantic import BaseModel | ||
|
|
||
| from services.memory.baseline import ZoneBaseline, _ZONE_NAME_RE | ||
|
|
||
| router = APIRouter(prefix="/zones", tags=["zones"]) | ||
|
|
||
|
|
||
| class ZoneStatsResponse(BaseModel): | ||
| zone: str | ||
| count: int | ||
| mean: float | ||
| variance: float | ||
| std: float | ||
| m2: float | ||
|
|
||
|
|
||
| def _get_redis(request: Request): | ||
| try: | ||
| return request.app.state.redis | ||
| except AttributeError: | ||
| raise HTTPException(status_code=503, detail="Redis not initialised in app.state") | ||
|
|
||
|
|
||
| @router.get("/{name}/stats", response_model=ZoneStatsResponse) | ||
| def get_zone_stats(name: str, redis=Depends(_get_redis)) -> ZoneStatsResponse: | ||
| """ | ||
| Return adaptive dwell-time statistics for *name* zone. | ||
|
|
||
| Statistics are computed incrementally via Welford's algorithm and | ||
| persisted in Redis under ``zone:{name}:stats``. | ||
| """ | ||
| if not _ZONE_NAME_RE.match(name): | ||
| raise HTTPException(status_code=422, detail="Invalid zone name") | ||
| stats = ZoneBaseline(redis, name).get_stats() | ||
| return ZoneStatsResponse(**stats) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,128 @@ | ||
| """ | ||
| baseline.py — Adaptive anomaly baseline per surveillance zone. | ||
|
|
||
| Uses Welford's online algorithm to maintain a running mean and variance of | ||
| dwell times without batch recomputation. Statistics are persisted in Redis | ||
| under ``zone:{name}:stats`` so they survive restarts. | ||
|
|
||
| Anomaly rule | ||
| ------------ | ||
| dwell > mean + 2.5 * std | ||
| """ | ||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import math | ||
| import re | ||
| from dataclasses import dataclass | ||
| from typing import Optional | ||
|
|
||
| _ZONE_NAME_RE = re.compile(r"^[a-zA-Z0-9_\-]{1,64}$") | ||
|
|
||
| STATS_TTL = 0 # 0 = no expiry — stats should persist indefinitely | ||
| ANOMALY_THRESHOLD = 2.5 | ||
| MIN_COUNT_FOR_ANOMALY = 10 # need enough samples before flagging outliers | ||
|
|
||
|
|
||
| @dataclass | ||
| class WelfordStats: | ||
| count: int = 0 | ||
| mean: float = 0.0 | ||
| m2: float = 0.0 # sum of squared deviations (Welford accumulator) | ||
|
|
||
| @property | ||
| def variance(self) -> float: | ||
| # Sample variance (Bessel's correction) — correct for anomaly detection | ||
| return self.m2 / (self.count - 1) if self.count > 1 else 0.0 | ||
|
|
||
| @property | ||
| def std(self) -> float: | ||
| return math.sqrt(self.variance) | ||
|
|
||
|
|
||
| class ZoneBaseline: | ||
| """ | ||
| Per-zone adaptive dwell-time baseline backed by Redis. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| redis_client: | ||
| Connected ``redis.Redis`` (or FakeRedis for tests). | ||
| zone_name: | ||
| Logical zone identifier, e.g. ``"restricted_exit"``. | ||
| """ | ||
|
|
||
| def __init__(self, redis_client, zone_name: str) -> None: | ||
| if not _ZONE_NAME_RE.match(zone_name): | ||
| raise ValueError( | ||
| f"Invalid zone name '{zone_name}'. " | ||
| "Only alphanumeric characters, hyphens, and underscores are allowed (max 64 chars)." | ||
| ) | ||
| self._r = redis_client | ||
| self._zone = zone_name | ||
| self._key = f"zone:{zone_name}:stats" | ||
| self._stats: Optional[WelfordStats] = None # lazy-loaded | ||
|
|
||
| # ── Public API ──────────────────────────────────────────────────────────── | ||
|
|
||
| def update(self, dwell: float) -> None: | ||
| """Ingest one dwell-time observation and persist updated stats.""" | ||
| s = self._load() | ||
| s.count += 1 | ||
| delta = dwell - s.mean | ||
| s.mean += delta / s.count | ||
| delta2 = dwell - s.mean | ||
| s.m2 += delta * delta2 | ||
| self._save(s) | ||
|
|
||
| def is_anomalous(self, dwell: float) -> bool: | ||
| """ | ||
| Return True when *dwell* exceeds mean + 2.5 * std. | ||
|
|
||
| Returns False until MIN_COUNT_FOR_ANOMALY samples have been collected | ||
| so early noise doesn't produce false positives. | ||
| Returns False when std == 0 (all identical values) to avoid flagging | ||
| any noise as anomalous. | ||
| """ | ||
| s = self._load() | ||
| if s.count < MIN_COUNT_FOR_ANOMALY: | ||
| return False | ||
| if s.std == 0: | ||
| return False | ||
| return dwell > s.mean + ANOMALY_THRESHOLD * s.std | ||
|
|
||
| def get_stats(self) -> dict: | ||
| """Return serialisable stats dict for the API response.""" | ||
| s = self._load() | ||
| return { | ||
| "zone": self._zone, | ||
| "count": s.count, | ||
| "mean": round(s.mean, 4), | ||
| "variance": round(s.variance, 4), | ||
| "std": round(s.std, 4), | ||
| "m2": round(s.m2, 6), | ||
| } | ||
|
|
||
| # ── Redis helpers ───────────────────────────────────────────────────────── | ||
|
|
||
| def _load(self) -> WelfordStats: | ||
| if self._stats is not None: | ||
| return self._stats | ||
| raw = self._r.get(self._key) | ||
| if raw is None: | ||
| self._stats = WelfordStats() | ||
| else: | ||
| d = json.loads(raw) | ||
| self._stats = WelfordStats( | ||
| count = d["count"], | ||
| mean = d["mean"], | ||
| m2 = d["m2"], | ||
| ) | ||
| return self._stats | ||
|
|
||
| def _save(self, s: WelfordStats) -> None: | ||
| payload = json.dumps({"count": s.count, "mean": s.mean, "m2": s.m2}) | ||
| if STATS_TTL: | ||
| self._r.setex(self._key, STATS_TTL, payload) | ||
| else: | ||
| self._r.set(self._key, payload) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: Devnil434/Eagle
Length of output: 3019
🏁 Script executed:
Repository: Devnil434/Eagle
Length of output: 2270
🏁 Script executed:
Repository: Devnil434/Eagle
Length of output: 156
🏁 Script executed:
Repository: Devnil434/Eagle
Length of output: 1679
Resolve this merge conflict and keep a single live
appinstance.These conflict markers at lines 26–35 and 41–83 make the file invalid Python. The unresolved split also decides whether
zones_routeris included and whetherapp.state.redisis initialized—both required becausezones_routerdepends onrequest.app.state.redis(seeapps/backend/routes/zones.py:26).🤖 Prompt for AI Agents