Download benchmarks.py from oettaM123/swordmasters-optimizer: direct link, hf CLI and curl.
- Browser
- Download file 40.3 kB
-
https://huggingface.co/spaces/oettaM123/swordmasters-optimizer/resolve/main/benchmarks.py
- Command line
-
hf download hf://spaces/oettaM123/swordmasters-optimizer/benchmarks.py
-
curl -L -o benchmarks.py https://huggingface.co/spaces/oettaM123/swordmasters-optimizer/resolve/main/benchmarks.py
40.3 kB
| """benchmarks.py -- "Is this account good for its level?" benchmark bands. | |
| Pure, dependency-light aggregator (stdlib; numpy is used when available, results are the same). | |
| It turns ONE complete leaderboard sweep (every account: level, power, gold, active gear, ban flag) | |
| into a SMALL JSON of per-level percentile bands that the optimizer serves statically; the | |
| "where do I stand" comparison then happens in the browser. | |
| Where it runs (minimal Space load is a hard requirement): | |
| * production: the home leaderboard pusher (sm/anticheat/leaderboard_pusher.py, SP7) feeds every | |
| account it scans into an Accumulator and, after a FULL sweep (at most once a day), POSTs the | |
| result to the optimizer's /benchmarks-ingest. The Space only stores + serves the file. | |
| * manual / local: tools/build_benchmarks.py builds the same file from the census DB or a | |
| leaderboard cache (and can push it). | |
| Keep the copy next to the pusher byte-identical to this file (SCHEMA guards incompatible pushes). | |
| Method (design locked 2026-11-16): | |
| * per-level percentile bands P25/P50/P75/P90 -- never a single average. | |
| * banned accounts are excluded. Nobody is excluded for being too GOOD (2026-11-23: the old | |
| cheating wave is fixed, the strong accounts are legit) -- the old 10x-median injection rule is | |
| off by default (DEFAULT_OUTLIER_RATIO = 0; pass a ratio to turn it back on for analysis). | |
| Only quit / gear-stripped accounts (power < P90/STRIP_RATIO of their level) are left out. | |
| * sparse levels are smoothed with an adaptive sliding window over neighbouring levels: the exact | |
| level if it alone has >= min_n accounts, otherwise the window widens (+-0.5%, 1%, 2% ...) until | |
| it does (capped at +-50%). Each anchor records its window and sample count. | |
| * widened windows are level-corrected: every pooled sample is rescaled to the anchor level along | |
| the local log-log slope of the median curve (iterated), otherwise the many weaker lower-level | |
| accounts flatten the curve at the sparse top (2026-11-16 round 3). | |
| * besides the drawn bands (P25..P90) each anchor stores tail quantiles P1..P99.9 (null where the | |
| window is too small for them) and the window max -> exact "Top x%" ranks client-side. | |
| * the sparse top (anchors with < BLEND_N accounts): every band line continues from its last real | |
| value along one shared power-law slope of the FIT_N highest-level accounts (upper-quantile | |
| regression in log-log) -> one continuous line up to the highest level; flagged est=1. | |
| * anchors are a geometric level grid (~2.5% apart) -> ~300 points from Lv100 to the top. | |
| Schema (extensible -- Phase 2/3 add metrics to the same level cohort or new cohorts): | |
| { | |
| "kind": "sm-benchmarks", "schema": 1, "generated_at": <unix sec>, "source": "...", | |
| "method": {...}, "population": {...}, | |
| "metrics": {"power": {"label": "Power", "fmt": "big"}, "gold": {...}, "dmg": {...}}, | |
| "cohorts": { | |
| "level": {"axis": "level", "x": [100, 103, ...], | |
| "series": {"power": {"p25": [...], "p50": [...], "p75": [...], "p90": [...], | |
| "n": [...], "lo": [...], "hi": [...]}, | |
| "gold": {...}, "dmg": {...}}} | |
| } | |
| } | |
| Values are null where an anchor has too few accounts. lo/hi = the level window actually used. | |
| """ | |
| from __future__ import annotations | |
| import gzip | |
| import math | |
| import struct | |
| import time | |
| from array import array | |
| from pathlib import Path | |
| from bisect import bisect_left, bisect_right | |
| try: # optional speed-up; the pure-Python path gives the same numbers | |
| import numpy as _np | |
| except Exception: # noqa: BLE001 | |
| _np = None | |
| SCHEMA = 1 | |
| KIND = "sm-benchmarks" | |
| # bands are drawn from P25..P90; the finer tail quantiles give the per-account "Top x%" rank | |
| PERCENTILES = (1, 5, 10, 25, 50, 75, 90, 95, 99, 99.9) | |
| BAND_PERCENTILES = (25, 50, 75, 90) | |
| DEFAULT_MIN_N = 200 # accounts an anchor's window should contain | |
| DEFAULT_MIN_N_FLOOR = 40 # below this (even at the widest window) the data band is null | |
| SPARSE_N = 40 # anchors with fewer accounts are flagged "few players" in the UI | |
| DEFAULT_STEP = 1.025 # geometric anchor spacing (2.5%) | |
| DEFAULT_OUTLIER_RATIO = 0.0 # 0 = off (was 10x, band_outliers.py bo_min_ratio) | |
| STRIP_RATIO = 100.0 # power < P90/100 of its level = quit / gear-stripped account | |
| WINDOWS = (0.0, 0.005, 0.01, 0.02, 0.035, 0.05, 0.08, 0.12, 0.18, 0.25) | |
| FIT_N = 400 # sparse top: power-law slope measured on the FIT_N highest-level accounts | |
| BLEND_N = 100 # data-driven anchors need >= this many accounts; above, the trend continues | |
| MIN_METRIC_N = 1000 # metrics with fewer accounts are not published (would be noise) | |
| TREND_ITERS = 3 # passes of the level-trend correction for widened windows | |
| SLOPE_K = 6 # local slope = log-log fit over +-K anchors (~+-16% level) | |
| SLOPE_MIN, SLOPE_MAX = -3.0, 8.0 | |
| ROUND_SIG = 4 # significant digits stored | |
| # account-age cohort (Phase 2). Account creation time = the 4-byte timestamp at the start of the | |
| # game's MongoDB ObjectId (`_id` in every getPlayersPagination row, `player_id` in our rows) -- no | |
| # extra request. Earliest account seen: 2024-02-09 (game launch window). | |
| AGE_DAILY_DAYS = 30 # one anchor per day for the first 30 days (young accounts move fast) | |
| AGE_STEP_DAYS = 7 # then one anchor per week, window = that week (+-3 days) | |
| AGE_MAX_HALF = 28 # a thin age window widens (x2 steps) up to +-28 days, else null | |
| AGE_ID_MIN = 1577836800 # 2020-01-01: an ObjectId stamp before this is not a real account time | |
| AGE_METRICS = {"level": {"label": "Level", "fmt": "int"}} # extra y-metrics only on the age axis | |
| AGE_MAX_UNKNOWN = 0.10 # age window not published if >10% of its accounts have unknown activity | |
| AGE_MIN_WATCH_DAYS = 2 # ...until they were watched this long: then = accounts seen levelling so far | |
| # activity (age cohort only): an account is ACTIVE if its level rose within the last ACTIVE_DAYS. | |
| # Measured 2026-11-19 against the Sept census (74 days earlier): 97-99% of accounts older than a year | |
| # had not gained a single level -> left in, quitters (intact gear, low level) make old accounts look | |
| # weaker than young ones. The pusher keeps one compact store (account id -> last level, time of the | |
| # last level-up) across sweeps; a one-time seed from the census (name -> level) makes it usable at once. | |
| ACTIVE_DAYS = 30 | |
| ACT_MAGIC = b"SMACT1\0\0" | |
| def pkey(q) -> str: | |
| """Column name of a percentile: 25 -> 'p25', 99.9 -> 'p99_9'.""" | |
| return "p" + f"{q:g}".replace(".", "_") | |
| def _need_n(q) -> int: | |
| """Fewest samples for which percentile q is more than an extrapolation (n * tail share >= 1).""" | |
| tail = min(q, 100 - q) / 100.0 | |
| return int(math.ceil(1.0 / tail - 1e-9)) if tail > 0 else 1 | |
| METRICS = { | |
| "power": {"label": "Power", "fmt": "big"}, | |
| "gold": {"label": "Gold", "fmt": "big"}, | |
| "dmg": {"label": "Damage / Hit", "fmt": "big", | |
| "note": "(sword damage + 2*sqrt(power) + 1) * (1 + shield damage multiplier), active gear"}, | |
| } | |
| # ── damage per hit (same formula as the optimizer's Account Lookup, app-core.js aiCalc) ────────── | |
| def gear_tables(catalog: dict | None): | |
| """{type: base} tables for sword damage + shield damage multiplier from game_catalog.json.""" | |
| catalog = catalog or {} | |
| scale = float(catalog.get("level_scale_per_level", 0.25) or 0.25) | |
| swords, shields = {}, {} | |
| for it in catalog.get("swords") or []: | |
| try: | |
| swords[int(it["type"])] = float(it.get("damage") or 0.0) | |
| except (KeyError, TypeError, ValueError): | |
| pass | |
| for it in catalog.get("shields") or []: | |
| try: | |
| shields[int(it["type"])] = float(it.get("damageMultiplier") or 0.0) | |
| except (KeyError, TypeError, ValueError): | |
| pass | |
| if not swords: | |
| return None | |
| return {"scale": scale, "swords": swords, "shields": shields} | |
| def _gear_scale(base: float, level, scale: float) -> float: | |
| try: | |
| lv = max(1, int(level)) | |
| except (TypeError, ValueError): | |
| lv = 1 | |
| return base * (1.0 + scale * (lv - 1)) | |
| def dmg_per_hit(power, sword_type, sword_level, shield_type, shield_level, tables) -> float | None: | |
| """(ds + 2*sqrt(power) + 1) * (1 + ms). None if the active sword is unknown (no gear in the row).""" | |
| if not tables or sword_type is None: | |
| return None | |
| try: | |
| p = float(power) | |
| st = int(sword_type) | |
| except (TypeError, ValueError): | |
| return None | |
| if not math.isfinite(p) or p < 0 or st not in tables["swords"]: | |
| return None | |
| ds = _gear_scale(tables["swords"][st], sword_level, tables["scale"]) | |
| ms = 0.0 | |
| if shield_type is not None: | |
| try: | |
| sh = int(shield_type) | |
| except (TypeError, ValueError): | |
| sh = None | |
| if sh in tables["shields"]: | |
| ms = _gear_scale(tables["shields"][sh], shield_level, tables["scale"]) | |
| return (ds + 2.0 * math.sqrt(p) + 1.0) * (1.0 + ms) | |
| def _num(v) -> float: | |
| if v is None or v == "": | |
| return math.nan | |
| try: | |
| x = float(v) | |
| except (TypeError, ValueError): | |
| return math.nan | |
| return x if math.isfinite(x) else math.nan | |
| # ── accumulator: compact arrays (1.6M accounts ~ 45 MB) ───────────────────────────────────────── | |
| class Accumulator: | |
| def __init__(self, keep_names: bool = False): | |
| self.level = array("l") | |
| self.power = array("d") | |
| self.gold = array("d") | |
| self.dmg = array("d") | |
| self.created = array("d") # account creation unix sec (NaN = unknown) | |
| self.pid = bytearray() # 12-byte ObjectId per account (zeros = unknown) -> activity store key | |
| self.names = [] if keep_names else None # usernames (exact case), only for the one-time census seed | |
| self.banned = 0 | |
| self.invalid = 0 | |
| def __len__(self): | |
| return len(self.level) | |
| def add(self, level, power, gold=None, dmg=None, banned=False, name=None, created=None, pid=None): | |
| if banned: | |
| self.banned += 1 | |
| return | |
| try: | |
| lv = int(level) | |
| except (TypeError, ValueError): | |
| self.invalid += 1 | |
| return | |
| pw = _num(power) | |
| if lv < 1 or not (pw > 0): | |
| self.invalid += 1 | |
| return | |
| self.level.append(lv) | |
| self.power.append(pw) | |
| self.gold.append(_num(gold)) | |
| self.dmg.append(_num(dmg)) | |
| self.created.append(_num(created)) | |
| self.pid += _pid_bytes(pid) | |
| if self.names is not None: | |
| self.names.append(str(name or "")) | |
| def add_pushed_row(self, row: dict, tables=None): | |
| """A row in the pusher's /ingest-leaderboard format.""" | |
| if not isinstance(row, dict): | |
| return | |
| power = row.get("power") | |
| dmg = dmg_per_hit(power, row.get("sword_type"), row.get("sword_level"), | |
| row.get("shield_type"), row.get("shield_level"), tables) | |
| self.add(row.get("level"), power, row.get("gold"), dmg, bool(row.get("is_banned")), | |
| name=row.get("username"), created=created_from_id(row.get("player_id")), | |
| pid=row.get("player_id")) | |
| def created_from_id(pid, now: float | None = None) -> float | None: | |
| """Account creation time (unix sec) from a 24-hex MongoDB ObjectId, or None.""" | |
| s = str(pid or "").strip() | |
| if len(s) != 24: | |
| return None | |
| try: | |
| t = int(s[:8], 16) | |
| int(s, 16) | |
| except ValueError: | |
| return None | |
| if t < AGE_ID_MIN or t > (now if now is not None else time.time()) + 86400: | |
| return None | |
| return float(t) | |
| _ZERO_ID = bytes(12) | |
| def _pid_bytes(pid) -> bytes: | |
| s = str(pid or "").strip() | |
| if len(s) == 24: | |
| try: | |
| return bytes.fromhex(s) | |
| except ValueError: | |
| pass | |
| return _ZERO_ID | |
| # ── activity store (pusher side; never on the Space) ──────────────────────────────────────────── | |
| def _act_load(path): | |
| """-> (t_first, ids blob, levels array('l'), ups array('d')) or None. Records sorted by id.""" | |
| try: | |
| raw = Path(path).read_bytes() | |
| except OSError: | |
| return None | |
| if raw[:8] != ACT_MAGIC: | |
| return None | |
| t_first, n = struct.unpack_from("<dI", raw, 8) | |
| o = 8 + 12 | |
| ids = raw[o:o + 12 * n]; o += 12 * n | |
| lv = array("l"); lv.frombytes(raw[o:o + lv.itemsize * n]); o += lv.itemsize * n | |
| up = array("d"); up.frombytes(raw[o:o + 8 * n]) | |
| if len(ids) != 12 * n or len(lv) != n or len(up) != n: | |
| return None | |
| return t_first, ids, lv, up | |
| def _act_save(path, t_first, ids, lv, up): | |
| path = Path(path) | |
| tmp = path.with_suffix(path.suffix + ".tmp") | |
| with open(tmp, "wb") as f: | |
| f.write(ACT_MAGIC + struct.pack("<dI", t_first, len(lv))) | |
| f.write(bytes(ids)); f.write(lv.tobytes()); f.write(up.tobytes()) | |
| tmp.replace(path) | |
| def load_activity_seed(path): | |
| """Census seed: gzip TSV, first line '#t<TAB><unix sec of the census>', then 'name<TAB>level'. | |
| -> (t_seed, {username (exact case): level}) or None.""" | |
| try: | |
| with gzip.open(path, "rt", encoding="utf-8") as f: | |
| head = f.readline().rstrip("\n").split("\t") | |
| t_seed = float(head[1]) | |
| seed = {} | |
| for line in f: | |
| name, _, lv = line.rstrip("\n").rpartition("\t") | |
| if name: | |
| seed[name] = int(lv) | |
| return t_seed, seed | |
| except Exception: # noqa: BLE001 | |
| return None | |
| def activity_needs_names(store_path, seed_path) -> bool: | |
| """True on the very first sweep with a seed waiting (names are needed once to match it).""" | |
| return bool(seed_path) and Path(seed_path).exists() and not (store_path and Path(store_path).exists()) | |
| def update_activity(acc: "Accumulator", store_path, now: float, seed_path=None): | |
| """Merge this sweep into the store and return (active flags per account | None, info dict). | |
| Per account id: level rose since the stored level -> last level-up = now. An id the store does | |
| not know yet has just crossed the sweep's level floor (= levelled up) -> active. On the very first | |
| run the census seed decides instead (level above its census level -> levelled up since then). | |
| Accounts missing from one sweep keep their record. Flags are None while the store is younger | |
| than ACTIVE_DAYS (without a seed it cannot tell quitters apart yet). | |
| Seed bootstrap: a riser since the census counts as active for ACTIVE_DAYS from the first run | |
| (the census is older than the window, so for the first month "active" = levelled since the | |
| census). Accounts created after the census but older than the window cannot be classified from | |
| the seed at all -> unknown until a level rise is seen or the store has watched them a window.""" | |
| n = len(acc) | |
| old = _act_load(store_path) if store_path else None | |
| seed = None | |
| if old is None and seed_path: | |
| seed = load_activity_seed(seed_path) | |
| if old is not None: | |
| t_first, o_ids, o_lv, o_up = old | |
| else: | |
| t_first, o_ids, o_lv, o_up = (seed[0] if seed else now), b"", array("l"), array("d") | |
| pid = bytes(acc.pid) | |
| cur = sorted((k for k in range(n) if pid[12 * k:12 * k + 12] != _ZERO_ID), key=lambda k: pid[12 * k:12 * k + 12]) | |
| m = len(o_lv) | |
| ids_out, lv_out, up_out = bytearray(), array("l"), array("d") | |
| ups = array("d", [0.0]) * n | |
| window = ACTIVE_DAYS * 86400 | |
| names = acc.names | |
| i = j = 0 | |
| seeded = carried = 0 | |
| while i < len(cur) or j < m: | |
| k = cur[i] if i < len(cur) else -1 | |
| kid = pid[12 * k:12 * k + 12] if k >= 0 else None | |
| oid = o_ids[12 * j:12 * j + 12] if j < m else None | |
| if kid is not None and (oid is None or kid < oid): # not in the store | |
| lvl = acc.level[k] | |
| if old is not None: | |
| up = now # crossed the level floor | |
| elif seed is not None: | |
| c = acc.created[k] | |
| sl = seed[1].get(names[k]) if names is not None else None | |
| if sl is not None: | |
| up = now if lvl > sl else 0.0 | |
| seeded += 1 | |
| elif c == c and now - c < window: | |
| up = now # younger than the window and above the floor -> rose inside it | |
| elif c == c and c >= seed[0] - 86400: | |
| # created after the census: "levelled since the census" is trivially true and says | |
| # nothing about the last ACTIVE_DAYS -> unknown, watched from now on (see flags) | |
| up = -now | |
| elif names is not None: | |
| # existed at the census below the seed's level floor, above it now -> levelled up | |
| # since the census, like a seeded riser (a renamed account is the rare exception) | |
| up = now | |
| else: # names not kept -> cannot tell | |
| up = 0.0 | |
| else: | |
| c = acc.created[k] | |
| up = now if (c == c and now - c < window) else 0.0 | |
| ids_out += kid; lv_out.append(lvl); up_out.append(up); ups[k] = up | |
| i += 1 | |
| elif oid is not None and (kid is None or oid < kid): # not seen this sweep -> keep | |
| ids_out += oid; lv_out.append(o_lv[j]); up_out.append(o_up[j]) | |
| carried += 1 | |
| j += 1 | |
| else: # same account | |
| lvl = acc.level[k] | |
| up = now if lvl > o_lv[j] else o_up[j] | |
| ids_out += kid; lv_out.append(max(lvl, o_lv[j])); up_out.append(up); ups[k] = up | |
| i += 1; j += 1 | |
| if store_path: | |
| _act_save(store_path, t_first, ids_out, lv_out, up_out) | |
| usable = now - t_first >= window | |
| info = {"tracked": len(lv_out), "since": int(t_first), "window_days": ACTIVE_DAYS, | |
| "seeded": seeded, "carried": carried, "usable": usable} | |
| if not usable: | |
| return None, info | |
| # True = level rose within the window; None = unknown (negative stamp = "watched since |t|, no rise | |
| # seen yet" and watched for less than the window); False = no rise for the whole window | |
| flags = [True if u >= now - window else (None if u < 0 and now + u < window else False) for u in ups] | |
| info["active"] = sum(1 for f in flags if f) | |
| info["unknown"] = sum(1 for f in flags if f is None) | |
| starts = [-u for u, f in zip(ups, flags) if f is None] | |
| # how long the unknown ones have been watched (the shortest): "active" for them so far means | |
| # "level rose within these days" | |
| info["unknown_watched_days"] = round((now - max(starts)) / 86400, 2) if starts else None | |
| return flags, info | |
| # ── percentile helpers ─────────────────────────────────────────────────────────────────────────── | |
| def _pct_sorted(vals, q: float) -> float: | |
| """Linear-interpolated percentile of an ascending list (== numpy.percentile default).""" | |
| n = len(vals) | |
| if n == 1: | |
| return float(vals[0]) | |
| pos = (n - 1) * q / 100.0 | |
| i = int(math.floor(pos)) | |
| f = pos - i | |
| if i + 1 >= n: | |
| return float(vals[-1]) | |
| return float(vals[i]) + (float(vals[i + 1]) - float(vals[i])) * f | |
| def _percentiles(vals) -> list: | |
| if _np is not None: | |
| return [float(x) for x in _np.percentile(_np.asarray(vals, dtype=float), PERCENTILES)] | |
| s = sorted(vals) | |
| return [_pct_sorted(s, q) for q in PERCENTILES] | |
| def _round(v): | |
| if v is None or not math.isfinite(v): | |
| return None | |
| return float(f"{v:.{ROUND_SIG}g}") | |
| def _anchors(lv_min: int, lv_max: int, step: float) -> list: | |
| out, x = [], float(max(1, lv_min)) | |
| while x < lv_max: | |
| v = int(round(x)) | |
| if not out or v > out[-1]: | |
| out.append(v) | |
| x *= step | |
| if not out or out[-1] != lv_max: | |
| out.append(int(lv_max)) | |
| return out | |
| def _window(levels_sorted, x: int, min_n: int, min_floor: int): | |
| """Smallest window around level x holding >= min_n samples -> (i0, i1, lo, hi) or None.""" | |
| best = None | |
| for w in WINDOWS: | |
| lo = int(math.ceil(x / (1.0 + w))) if w else x | |
| hi = int(math.floor(x * (1.0 + w))) if w else x | |
| i0 = bisect_left(levels_sorted, lo) | |
| i1 = bisect_right(levels_sorted, hi) | |
| best = (i0, i1, lo, hi) | |
| if i1 - i0 >= min_n: | |
| return best | |
| if best and best[1] - best[0] >= min_floor: | |
| return best | |
| return None | |
| def _median(vals) -> float: | |
| if _np is not None: | |
| return float(_np.median(_np.asarray(vals, dtype=float))) | |
| return _pct_sorted(sorted(vals), 50) | |
| def _adjusted(L, V, i0: int, i1: int, x: int, slope: float, logs): | |
| """Window values moved to anchor level x along the local trend: v * (x / level)^slope. | |
| A widened window pools neighbouring levels; at sparse high levels those are mostly LOWER levels | |
| (far more accounts there), and power rises steeply with level (~level^5 at the top), so raw | |
| pooling drags the bands down. Rescaling each sample to the anchor level removes that bias. | |
| Exact-level windows are returned untouched. | |
| """ | |
| if slope == 0.0 or L[i0] == L[i1 - 1] == x: | |
| return V[i0:i1] | |
| lx = math.log(x) | |
| return [V[k] * math.exp(slope * (lx - logs[k])) for k in range(i0, i1)] | |
| def _slopes(anchors, med) -> list: | |
| """Local log-log slope of the median curve (least squares over +-SLOPE_K anchors, clamped).""" | |
| lx = [math.log(a) for a in anchors] | |
| ly = [math.log(m) if (m is not None and m > 0) else None for m in med] | |
| out = [] | |
| for j in range(len(anchors)): | |
| xs, ys = [], [] | |
| for k in range(max(0, j - SLOPE_K), min(len(anchors), j + SLOPE_K + 1)): | |
| if ly[k] is not None: | |
| xs.append(lx[k]); ys.append(ly[k]) | |
| if len(xs) < 3: | |
| out.append(0.0) | |
| continue | |
| mx, my = sum(xs) / len(xs), sum(ys) / len(ys) | |
| sxx = sum((a - mx) ** 2 for a in xs) | |
| s = sum((a - mx) * (b - my) for a, b in zip(xs, ys)) / sxx if sxx > 0 else 0.0 | |
| out.append(max(SLOPE_MIN, min(SLOPE_MAX, s))) | |
| return out | |
| def _pq(vals, q) -> float: | |
| if q == 50: | |
| return _median(vals) | |
| if _np is not None: | |
| return float(_np.percentile(_np.asarray(vals, dtype=float), q)) | |
| return _pct_sorted(sorted(vals), q) | |
| def _trend_fit(L, V, logs, anchors, wins, q=50): | |
| """Iterate percentile-q curve <-> local slope so widened windows are level-corrected. | |
| -> (curve, slopes); q=50 is the median.""" | |
| slopes = [0.0] * len(anchors) | |
| med = [] | |
| for _ in range(TREND_ITERS): | |
| med = [(_pq(_adjusted(L, V, w[0], w[1], x, s, logs), q) if w else None) | |
| for x, w, s in zip(anchors, wins, slopes)] | |
| slopes = _slopes(anchors, med) | |
| return med, slopes | |
| def _top_slope(L, V, q: float = 0.75, iters: int = 80): | |
| """Log-log slope of the top group's upper band: quantile regression (pinball loss, IRLS) of | |
| log value on log level over the FIT_N highest-level accounts. The upper quantile is used because | |
| many high-level accounts hold almost no power (stripped/mule accounts) and would flip a median | |
| fit; ~level^4.7 on the 2026-11 data. -> (slope, n, first level) or None.""" | |
| pairs = [(math.log(l), math.log(v)) for l, v in zip(L[-FIT_N:], V[-FIT_N:]) if v > 0] | |
| if len(pairs) < FIT_N // 2: | |
| return None | |
| xs, ys = [p[0] for p in pairs], [p[1] for p in pairs] | |
| w = [1.0] * len(xs) | |
| b = 0.0 | |
| for _ in range(iters): | |
| sw = sum(w) | |
| mx = sum(wi * x for wi, x in zip(w, xs)) / sw | |
| my = sum(wi * y for wi, y in zip(w, ys)) / sw | |
| sxx = sum(wi * (x - mx) ** 2 for wi, x in zip(w, xs)) | |
| b = sum(wi * (x - mx) * (y - my) for wi, x, y in zip(w, xs, ys)) / sxx if sxx > 0 else 0.0 | |
| a = my - b * mx | |
| w = [(q if y > a + b * x else 1.0 - q) / max(1e-6, abs(y - (a + b * x))) for x, y in zip(xs, ys)] | |
| return max(0.0, min(SLOPE_MAX, b)), len(pairs), (L[-FIT_N] if len(L) >= FIT_N else L[0]) | |
| def _bands(levels_sorted, values_by_level, anchors, min_n, min_floor): | |
| L, V = levels_sorted, values_by_level | |
| logs = [math.log(l) for l in L] | |
| wins = [_window(L, x, min_n, min_floor) for x in anchors] | |
| _, slopes = _trend_fit(L, V, logs, anchors, wins) | |
| cols = {pkey(q): [] for q in PERCENTILES} | |
| cols.update({"max": [], "n": [], "lo": [], "hi": []}) | |
| for x, win, s in zip(anchors, wins, slopes): | |
| if not win: | |
| for q in PERCENTILES: | |
| cols[pkey(q)].append(None) | |
| cols["max"].append(None) | |
| cols["n"].append(0); cols["lo"].append(None); cols["hi"].append(None) | |
| continue | |
| i0, i1, lo, hi = win | |
| n = i1 - i0 | |
| vals = _adjusted(L, V, i0, i1, x, s, logs) | |
| ps = _percentiles(vals) | |
| for q, v in zip(PERCENTILES, ps): | |
| cols[pkey(q)].append(_round(v) if n >= _need_n(q) else None) | |
| cols["max"].append(_round(max(vals))) | |
| cols["n"].append(n); cols["lo"].append(lo); cols["hi"].append(hi) | |
| _apply_trend(cols, anchors, L, V) | |
| return cols | |
| def _apply_trend(cols, anchors, L, V): | |
| """Sparse top: above the last anchor with >= BLEND_N accounts every band line continues from its | |
| last real value along ONE shared power-law slope of the top group (lines stay continuous and | |
| parallel, cannot cross or jump from one single player to the next). Flagged est=1; n/lo/hi then | |
| describe the top group the slope was measured on.""" | |
| keys = [pkey(q) for q in PERCENTILES] + ["max"] | |
| cols["est"] = [0] * len(anchors) | |
| good = [j for j in range(len(anchors)) if cols["n"][j] >= BLEND_N and cols["p50"][j] is not None] | |
| if not good or good[-1] >= len(anchors) - 1: | |
| return | |
| J = good[-1] | |
| tr = _top_slope(L, V) | |
| if not tr: | |
| return | |
| slope, n_fit, lo_fit = tr | |
| xJ = anchors[J] | |
| for j in range(J + 1, len(anchors)): | |
| f = (anchors[j] / xJ) ** slope | |
| for k in keys: | |
| d = cols[k][J] | |
| cols[k][j] = _round(d * f) if d is not None else None | |
| cols["est"][j] = 1 | |
| cols["n"][j] = n_fit; cols["lo"][j] = lo_fit; cols["hi"][j] = L[-1] | |
| def _log_interp_median(anchors, med, lv: int) -> float: | |
| """Local power median at level lv: log-log interpolation between the anchor medians.""" | |
| j = bisect_left(anchors, lv) | |
| if j <= 0: | |
| return med[0] | |
| if j >= len(anchors): | |
| return med[-1] | |
| a0, a1, m0, m1 = anchors[j - 1], anchors[j], med[j - 1], med[j] | |
| if a1 == a0 or m0 <= 0 or m1 <= 0: | |
| return m1 | |
| t = (math.log(lv) - math.log(a0)) / (math.log(a1) - math.log(a0)) | |
| return math.exp(math.log(m0) + (math.log(m1) - math.log(m0)) * t) | |
| def _age_anchors(max_day: int) -> list: | |
| out = list(range(0, min(AGE_DAILY_DAYS, max_day) + 1)) | |
| x = AGE_DAILY_DAYS + AGE_STEP_DAYS | |
| while x <= max_day: | |
| out.append(x) | |
| x += AGE_STEP_DAYS | |
| if out[-1] != max_day: | |
| out.append(max_day) | |
| return out | |
| def _age_window(days_sorted, x: int, min_n: int, min_floor: int): | |
| """Accounts aged x days (daily anchors) or x+-3 days (weekly); widened in x2 steps up to | |
| +-AGE_MAX_HALF days while thin -> (i0, i1, lo, hi) or None. Ages are whole days.""" | |
| h = 0 if x <= AGE_DAILY_DAYS else AGE_STEP_DAYS // 2 | |
| best = None | |
| while True: | |
| lo, hi = max(0, x - h), x + h | |
| i0, i1 = bisect_left(days_sorted, lo), bisect_right(days_sorted, hi) | |
| best = (i0, i1, lo, hi) | |
| if i1 - i0 >= min_n or h >= AGE_MAX_HALF: | |
| break | |
| h = min(AGE_MAX_HALF, max(1, h * 2)) | |
| return best if best[1] - best[0] >= min_floor else None | |
| def _age_cohort(acc: Accumulator, idx: list, now: float, min_n: int, min_floor: int, active=None, | |
| watched_days=None): | |
| """Percentile bands per account age (days since creation) for power/gold/dmg/level. | |
| Uses exactly the accounts the level pass kept (banned, gear-stripped and injected excluded by | |
| the level-relative rules). Age windows are at most a week wide, over which nothing drifts much, | |
| so -- unlike the level axis -- no trend correction and no extrapolated top are needed. | |
| Accounts whose activity is still unknown (active[i] is None) are left out, and an age window in | |
| which they make up more than AGE_MAX_UNKNOWN of the accounts is not published: its bands could | |
| be anything between "only the known-active" and "all of them" -- unless they have been watched | |
| AGE_MIN_WATCH_DAYS already: then the window shows the accounts seen levelling in that time | |
| (a shorter, stricter activity window that grows to ACTIVE_DAYS by itself; flagged per anchor). | |
| -> (cohort dict, used, unknown creation time, inactive, activity unknown)""" | |
| pairs = [] | |
| U = [] | |
| unknown = 0 | |
| inactive = 0 | |
| for i in idx: | |
| f = True if active is None else active[i] | |
| if f is False: | |
| inactive += 1 | |
| continue | |
| c = acc.created[i] | |
| if c != c or c > now + 86400: | |
| unknown += 1 | |
| continue | |
| if f is None: | |
| U.append(max(0, int((now - c) // 86400))) | |
| continue | |
| pairs.append((max(0, int((now - c) // 86400)), i)) | |
| U.sort() | |
| if len(pairs) < MIN_METRIC_N: | |
| return None, len(pairs), unknown, inactive, len(U) | |
| pairs.sort() | |
| D = [d for d, _ in pairs] | |
| anchors = _age_anchors(max(D[-1], U[-1] if U else 0)) | |
| wins = [_age_window(D, x, min_n, min_floor) for x in anchors] | |
| unk = [] | |
| part = [0] * len(wins) | |
| for k, w in enumerate(wins): | |
| if w is None: | |
| unk.append(0) | |
| continue | |
| u = bisect_right(U, w[3]) - bisect_left(U, w[2]) | |
| unk.append(u) | |
| if u > AGE_MAX_UNKNOWN * (u + w[1] - w[0]): | |
| if watched_days is not None and watched_days >= AGE_MIN_WATCH_DAYS: | |
| part[k] = 1 # published: active = seen levelling in the watched days | |
| else: | |
| wins[k] = None | |
| series, metrics = {}, {} | |
| srcs = (("power", acc.power), ("gold", acc.gold), ("dmg", acc.dmg), ("level", acc.level)) | |
| for name, src in srcs: | |
| vals = [float(src[i]) for _, i in pairs] | |
| ok = [v == v and v >= 0 for v in vals] | |
| n_ok = sum(ok) | |
| metrics[name] = n_ok | |
| if n_ok < MIN_METRIC_N: | |
| continue | |
| cols = {pkey(q): [] for q in PERCENTILES} | |
| cols.update({"max": [], "n": [], "lo": [], "hi": [], "est": []}) | |
| for x, w in zip(anchors, wins): | |
| sel = [vals[k] for k in range(w[0], w[1]) if ok[k]] if w else [] | |
| n = len(sel) | |
| if n < min_floor: | |
| for q in PERCENTILES: | |
| cols[pkey(q)].append(None) | |
| cols["max"].append(None); cols["n"].append(n) | |
| cols["lo"].append(w[2] if w else None); cols["hi"].append(w[3] if w else None) | |
| cols["est"].append(0) | |
| continue | |
| for q, v in zip(PERCENTILES, _percentiles(sel)): | |
| cols[pkey(q)].append(_round(v) if n >= _need_n(q) else None) | |
| cols["max"].append(_round(max(sel))); cols["n"].append(n) | |
| cols["lo"].append(w[2]); cols["hi"].append(w[3]); cols["est"].append(0) | |
| series[name] = cols | |
| coh = {"axis": "age", "unit": "days", "x": anchors, "series": series, | |
| "metrics": {k: dict(v, n=metrics.get(k, 0)) for k, v in AGE_METRICS.items()}, | |
| "n": {k: v for k, v in metrics.items()}, | |
| "activity_unknown": unk, | |
| "short_window": part, | |
| "watched_days": watched_days, | |
| "oldest_created": int(min(acc.created[i] for _, i in pairs[-1:])) if pairs else None} | |
| return coh, len(pairs), unknown, inactive, len(U) | |
| def build(acc: Accumulator, *, source: str = "", min_n: int = DEFAULT_MIN_N, | |
| min_n_floor: int = DEFAULT_MIN_N_FLOOR, step: float = DEFAULT_STEP, | |
| outlier_ratio: float = DEFAULT_OUTLIER_RATIO, now: float | None = None, | |
| activity_path=None, activity_seed=None) -> dict: | |
| n_all = len(acc) | |
| order = sorted(range(n_all), key=acc.level.__getitem__) | |
| lv = [acc.level[i] for i in order] | |
| pw = [acc.power[i] for i in order] | |
| base = {"kind": KIND, "schema": SCHEMA, "generated_at": int(now if now is not None else time.time()), | |
| "source": str(source or ""), | |
| "method": {"percentiles": list(PERCENTILES), "bands": list(BAND_PERCENTILES), | |
| "min_n": int(min_n), "min_n_floor": int(min_n_floor), "sparse_n": SPARSE_N, | |
| "anchor_step": step, "windows": list(WINDOWS), | |
| "trend": "widened windows rescaled to the anchor level along the local " | |
| "log-log slope of the median curve", | |
| "exclude": ["banned", f"power < 1/{STRIP_RATIO:g} of the level's P90 (quit / gear-stripped)", | |
| ] + ([f"power >= {outlier_ratio:g}x local level median (anticheat band rule)"] | |
| if outlier_ratio else []), | |
| "age": {"source": "account creation = timestamp in the game's MongoDB ObjectId", | |
| "anchors": f"daily up to {AGE_DAILY_DAYS} d, then every {AGE_STEP_DAYS} d " | |
| f"(window +-{AGE_STEP_DAYS // 2} d, widened up to +-{AGE_MAX_HALF} d if thin)", | |
| "population": "same accounts as the level bands (Lv>=min_level, exclusions above), " | |
| f"only ACTIVE ones: level rose within the last {ACTIVE_DAYS} days " | |
| "(tracked by the pusher per account id across sweeps); " | |
| "accounts created after the census are watched first: until " | |
| f"watched {ACTIVE_DAYS} d, active for them = level rose since " | |
| "watching began (cohort.short_window marks those ages; left " | |
| f"out while watched < {AGE_MIN_WATCH_DAYS} d)"}}, | |
| "metrics": {k: dict(v) for k, v in METRICS.items()}} | |
| if not n_all: | |
| base["population"] = {"accounts": 0, "used": 0, "banned_excluded": acc.banned, | |
| "outliers_excluded": 0, "invalid": acc.invalid} | |
| base["cohorts"] = {"level": {"axis": "level", "x": [], "series": {}}} | |
| return base | |
| anchors = _anchors(lv[0], lv[-1], step) | |
| def _filled(curve): | |
| for j in range(len(curve)): | |
| if curve[j] is None: | |
| curve[j] = curve[j - 1] if j else 0.0 | |
| return curve | |
| # pass 1a: quit / gear-stripped accounts. Above ~Lv3k a growing share of accounts (~30% above | |
| # Lv30k, ~1% below Lv3k) holds less than 1/STRIP_RATIO of its level's top-10% power -- gear given | |
| # away, mules, quit. They are not who a player compares with, and left in they drag the median to | |
| # the floor (and made real players look like 10x "injections"). Reference = the level's own P90. | |
| logs_all = [math.log(l) for l in lv] | |
| wins = [_window(lv, x, min_n, 1) for x in anchors] | |
| p90, _ = _trend_fit(lv, pw, logs_all, anchors, wins, q=90) | |
| _filled(p90) | |
| active = [k for k in range(n_all) if not (pw[k] * STRIP_RATIO < _log_interp_median(anchors, p90, lv[k]))] | |
| stripped = n_all - len(active) | |
| # pass 1b: (level-corrected) median of the active accounts -> drop injected-power outliers | |
| L1 = [lv[k] for k in active] | |
| wins1 = [_window(L1, x, min_n, 1) for x in anchors] | |
| med, _ = _trend_fit(L1, [pw[k] for k in active], [logs_all[k] for k in active], anchors, wins1) | |
| _filled(med) | |
| # where the reference population is thin (sparse top) nothing can be called an outlier: the few | |
| # top players there legitimately sit far above a median extrapolated from lower levels | |
| win_n = [(w[1] - w[0]) if w else 0 for w in wins1] | |
| def _is_outlier(level, power): | |
| if not outlier_ratio: # 0 / None = injection rule off | |
| return False | |
| j = min(bisect_left(anchors, level), len(anchors) - 1) | |
| if win_n[j] < SPARSE_N: | |
| return False | |
| m = _log_interp_median(anchors, med, level) | |
| return m > 0 and power >= outlier_ratio * m | |
| keep = [] | |
| outliers = 0 | |
| for k in active: | |
| if _is_outlier(lv[k], pw[k]): | |
| outliers += 1 | |
| else: | |
| keep.append(k) | |
| # pass 2: final bands per metric (each metric uses only accounts that have a value for it) | |
| series = {} | |
| for name, src in (("power", acc.power), ("gold", acc.gold), ("dmg", acc.dmg)): | |
| L, V = [], [] | |
| for k in keep: | |
| v = src[order[k]] | |
| if v == v and v >= 0: # not NaN | |
| L.append(lv[k]); V.append(v) | |
| base["metrics"][name]["n"] = len(L) | |
| if len(L) < MIN_METRIC_N: # e.g. dmg without gear data -> not published | |
| continue | |
| series[name] = _bands(L, V, anchors, min_n, min_n_floor) | |
| now_s = float(base["generated_at"]) | |
| # age cohort only with a usable activity store: without it quitters dominate the old ages | |
| active, act_info = (update_activity(acc, activity_path, now_s, activity_seed) if activity_path | |
| else (None, {"usable": False})) | |
| age, age_used, age_unknown, age_inactive, age_act_unknown = (None, 0, 0, 0, 0) | |
| if active is not None: | |
| age, age_used, age_unknown, age_inactive, age_act_unknown = _age_cohort( | |
| acc, [order[k] for k in keep], now_s, min_n, min_n_floor, active, | |
| act_info.get("unknown_watched_days")) | |
| base["population"] = {"accounts": n_all + acc.banned + acc.invalid, "used": len(keep), | |
| "banned_excluded": acc.banned, "outliers_excluded": outliers, | |
| "stripped_excluded": stripped, | |
| "invalid": acc.invalid, "min_level": lv[0], "max_level": lv[-1], | |
| "age_used": age_used, "age_unknown": age_unknown, | |
| "age_inactive_excluded": age_inactive, | |
| "age_activity_unknown": age_act_unknown, "activity": act_info} | |
| base["cohorts"] = {"level": {"axis": "level", "x": anchors, "series": series}} | |
| if age: | |
| base["cohorts"]["age"] = age | |
| return base | |
| def validate(doc) -> str: | |
| """'' if doc looks like a benchmarks file this server can serve, else the reason.""" | |
| if not isinstance(doc, dict) or doc.get("kind") != KIND: | |
| return "not a benchmarks document" | |
| if int(doc.get("schema") or 0) != SCHEMA: | |
| return f"schema {doc.get('schema')} != {SCHEMA}" | |
| coh = (doc.get("cohorts") or {}).get("level") or {} | |
| x = coh.get("x") | |
| if not isinstance(x, list) or not x: | |
| return "empty level cohort" | |
| for name, cols in (coh.get("series") or {}).items(): | |
| if not isinstance(cols, dict): | |
| return f"bad series {name}" | |
| for col in [pkey(q) for q in BAND_PERCENTILES] + ["n"]: | |
| if not isinstance(cols.get(col), list) or len(cols[col]) != len(x): | |
| return f"series {name}.{col} length mismatch" | |
| if "power" not in (coh.get("series") or {}): | |
| return "power series missing" | |
| age = (doc.get("cohorts") or {}).get("age") | |
| if age is not None: # optional (additive, Phase 2) | |
| ax = age.get("x") if isinstance(age, dict) else None | |
| if not isinstance(ax, list) or not ax: | |
| return "empty age cohort" | |
| for name, cols in (age.get("series") or {}).items(): | |
| for col in [pkey(q) for q in BAND_PERCENTILES] + ["n"]: | |
| if not isinstance(cols, dict) or not isinstance(cols.get(col), list) or len(cols[col]) != len(ax): | |
| return f"age series {name}.{col} length mismatch" | |
| return "" | |