mvp-ai's picture
download
raw
11.4 kB
"""Local, per-activity skill rating — the Flow-Matching brain (fully offline).
Nothing here ever touches the broker. The rating lives in <state>/ratings.json
and is used only to *sort* the match suggestions poll.py already shows. It is
seeded from the user's self-rated level (onboarding Frage 1, profile.yaml
`skill:`) and sharpened after each meetup by the "who was better?" answer that
feedback.py already collects.
Design (documented because the input signal is unusual):
* We keep one Glicko-style rating per activity: r (skill) + rd (uncertainty).
* The post-meetup signal is a RELATIVE judgment ("they were a bit stronger"),
not a win/loss. We treat it as a game against a notional EVEN opponent at
the player's own current rating (expected score 0.5): reporting that the
other was stronger pushes r down, weaker pushes r up, scaled by the margin.
So a club player who self-rated "casual" climbs to club over a few meetups.
* rd starts wide (a self-rating is noisy) and shrinks with games, so the first
couple of meetups dominate — exactly what the research on fast rating
convergence predicts.
Bands (self-rating -> starting rating), spaced ~200 so one band gap ≈ 64% win
expectation for the stronger player, two bands ≈ 76%:
beginner 1200 · casual 1400 · club 1600 · competitive 1800
CLI:
python3 rating.py # show your current ratings
python3 rating.py --selftest # run the math self-checks
"""
from __future__ import annotations
import argparse
import json
import math
import os
import client
RATINGS_FILE = os.path.join(client.STATE_DIR, "ratings.json")
BANDS = {"beginner": 1200.0, "casual": 1400.0, "club": 1600.0, "competitive": 1800.0}
BAND_ORDER = ["beginner", "casual", "club", "competitive"]
DEFAULT_RATING = 1400.0
DEFAULT_RD = 350.0 # max uncertainty for a fresh self-rating (Glicko default)
MIN_RD = 60.0 # a rating never becomes "perfectly known"
NOTIONAL_OPP_RD = 200.0 # uncertainty we ascribe to the "even-match" reference
SKILL_STEP = 100.0 # rating points per perceived skill notch (them/you _bit)
_Q = math.log(10.0) / 400.0
# --- Glicko-style math ----------------------------------------------------
def _g(rd: float) -> float:
"""Glicko's uncertainty-attenuation factor: a foggy opponent rating pulls
the expected score toward 0.5."""
return 1.0 / math.sqrt(1.0 + 3.0 * _Q**2 * rd**2 / math.pi**2)
def expected_score(r: float, r_opp: float, rd_opp: float = 0.0) -> float:
"""Win probability of a player rated r against one rated r_opp (logistic,
Elo/Glicko 400-scale). gap 0/100/200/370 -> ~50/64/76/90%."""
return 1.0 / (1.0 + 10.0 ** (-_g(rd_opp) * (r - r_opp) / 400.0))
def band_for(r: float) -> str:
"""Nearest self-rating band name for a numeric rating."""
return min(BAND_ORDER, key=lambda b: abs(BANDS[b] - r))
def flow_quality(my_r: float, their_r: float, *, target: float = 0.58,
sigma: float = 0.18) -> float:
"""How "fun" a pairing is, in [0, 1]. Peaks when the stronger player's win
expectation ≈ target (slightly above 50%, per the flow-channel / churn
research) and falls off toward blowouts."""
p_stronger = expected_score(max(my_r, their_r), min(my_r, their_r))
return math.exp(-((p_stronger - target) ** 2) / (2.0 * sigma**2))
# delta > 0 = opponent was stronger = my performance was lower
SKILL_TO_SCORE = {2: 0.0, 1: 0.25, 0: 0.5, -1: 0.75, -2: 1.0}
def score_from_skill_delta(delta: int) -> float:
"""Map feedback.py's relative-strength delta (-2..+2) to a pseudo game
score in [0, 1] against an even opponent."""
return SKILL_TO_SCORE.get(max(-2, min(2, int(delta))), 0.5)
def estimate_partner_rating(my_r: float, skill_delta: int) -> float:
"""Place a known partner on the rating scale relative to us, from the coarse
'who was better' memory. Used only to flow-rank their future offers."""
return my_r + SKILL_STEP * max(-2, min(2, int(skill_delta)))
# --- peer rating exchange (transitivity, never on the board) --------------
# Plausible band any real player falls in; clamps a relayed rating before we
# trust it for a head-to-head update (a counterpart could mis-report it).
OPP_R_MIN, OPP_R_MAX = 1000.0, 2000.0
def self_report(activity: str, profile: dict | None = None) -> dict | None:
"""Compact rating payload to hand to a *matched* counterpart over the sealed
relay (never the board), or None if we have no rating for this activity yet.
Seeds from the profile self-rating (Frage 1) first if given."""
if profile is not None:
ensure_from_profile(profile)
st = get(activity)
if not st:
return None
return {"activity": activity, "r": round(float(st["r"]), 1),
"rd": round(float(st["rd"]), 1)}
def sanitize_opp(payload) -> dict | None:
"""Validate + clamp a counterpart-reported rating before we store or trust
it for a head-to-head update (PROTOCOL §4.1: the recipient plausibility-
checks/clamps a relayed rating). Returns a clean ``{activity?, r, rd}`` dict
— numeric ``r``/``rd`` clamped into the plausible band, every other key
dropped — or None if the shape is wrong, so a malicious/buggy counterpart
can't skew the local rating with an out-of-band value. (Until offer-v2
exposes a coarse public band to cross-check against, this wide clamp is the
defense against a mis-reported rating; single liars wash out over games.)"""
if not isinstance(payload, dict):
return None
try:
r = float(payload["r"])
rd = float(payload["rd"])
except (KeyError, TypeError, ValueError):
return None
if not (math.isfinite(r) and math.isfinite(rd)): # reject NaN/±inf
return None
clean = {"r": min(OPP_R_MAX, max(OPP_R_MIN, r)),
"rd": min(DEFAULT_RD, max(MIN_RD, rd))}
act = payload.get("activity")
if isinstance(act, str): # keep the one other known key
clean = {"activity": act, **clean}
return clean
# --- persistence ----------------------------------------------------------
def load() -> dict:
if os.path.exists(RATINGS_FILE):
try:
data = json.load(open(RATINGS_FILE))
if isinstance(data, dict):
return data
except (json.JSONDecodeError, OSError):
pass # corrupt state: start fresh rather than wedging the poll
return {}
def save(data: dict) -> None:
os.makedirs(client.STATE_DIR, exist_ok=True)
tmp = RATINGS_FILE + ".tmp"
with open(tmp, "w") as f:
json.dump(data, f, indent=2)
os.replace(tmp, RATINGS_FILE) # atomic: a crash mid-write can't truncate
# --- public API -----------------------------------------------------------
def ensure(activity: str, level: str | None = None) -> dict:
"""Seed a rating for an activity from a self-rated band, once. No-op if it
already exists (real games must not be overwritten by the self-rating)."""
data = load()
if activity not in data:
data[activity] = {"r": BANDS.get(level or "", DEFAULT_RATING),
"rd": DEFAULT_RD, "games": 0}
save(data)
return data[activity]
def ensure_from_profile(profile: dict | None) -> None:
"""Bootstrap every activity the user gave a `skill:` level for."""
for act, lvl in ((profile or {}).get("skill") or {}).items():
ensure(act, lvl)
def get(activity: str) -> dict | None:
return load().get(activity)
def update(activity: str, s: float, *, opp_r: float | None = None,
opp_rd: float = NOTIONAL_OPP_RD) -> dict:
"""One Glicko-style game update. Default opponent = an even match at the
player's current rating (expected score 0.5), so a relative 'who was better'
judgment nudges the rating toward where the comparisons place the player."""
data = load()
st = data.get(activity) or {"r": DEFAULT_RATING, "rd": DEFAULT_RD, "games": 0}
r, rd = float(st["r"]), float(st["rd"])
r_opp = r if opp_r is None else float(opp_r)
g = _g(opp_rd)
e = 1.0 / (1.0 + 10.0 ** (-g * (r - r_opp) / 400.0))
d2 = 1.0 / (_Q**2 * g**2 * e * (1.0 - e))
denom = 1.0 / rd**2 + 1.0 / d2
st = {"r": r + (_Q / denom) * g * (s - e),
"rd": max(MIN_RD, math.sqrt(1.0 / denom)),
"games": int(st.get("games", 0)) + 1}
data[activity] = st
save(data)
return st
# --- CLI / self-test ------------------------------------------------------
def _selftest() -> None:
assert band_for(1600) == "club"
assert band_for(1190) == "beginner"
assert abs(expected_score(1500, 1500) - 0.5) < 1e-9
assert abs(expected_score(1700, 1500) - 0.76) < 0.02 # 200 gap ≈ 76%
assert score_from_skill_delta(0) == 0.5
assert score_from_skill_delta(2) == 0.0 and score_from_skill_delta(-2) == 1.0
# "you were stronger" repeatedly => rating climbs; "they were" => drops
r0 = {"r": 1400.0, "rd": 350.0, "games": 0}
def step(st, s):
r, rd = st["r"], st["rd"]
g = _g(NOTIONAL_OPP_RD)
e = 1.0 / (1.0 + 10.0 ** (-g * (r - r) / 400.0))
d2 = 1.0 / (_Q**2 * g**2 * e * (1.0 - e))
denom = 1.0 / rd**2 + 1.0 / d2
return {"r": r + (_Q / denom) * g * (s - e),
"rd": max(MIN_RD, math.sqrt(1.0 / denom)), "games": st["games"] + 1}
up = step(step(r0, 1.0), 1.0)
down = step(step(r0, 0.0), 0.0)
assert up["r"] > 1400.0 < down["r"] + 1e9 and down["r"] < 1400.0
assert up["rd"] < 350.0 and down["rd"] < 350.0 # uncertainty shrinks
# flow: a slight favourite beats both a coin-flip and a blowout
assert flow_quality(1600, 1490) > flow_quality(1600, 1600) # ~58% > 50%
assert flow_quality(1600, 1600) > flow_quality(1600, 1980) # 50% > blowout
assert estimate_partner_rating(1600, 1) == 1700 # a bit stronger
# sanitize_opp: clamp out-of-band r/rd, drop unknown keys, reject bad shape
assert sanitize_opp({"activity": "table_tennis", "r": 9999, "rd": 0.01}) == \
{"activity": "table_tennis", "r": OPP_R_MAX, "rd": MIN_RD}
lo = sanitize_opp({"r": -500, "rd": 99999})
assert lo == {"r": OPP_R_MIN, "rd": DEFAULT_RD} # no activity key
assert sanitize_opp({"r": 1600, "rd": 200, "evil": 1}) == {"r": 1600.0, "rd": 200.0}
for bad in (None, "x", {}, {"r": 1500}, {"r": "n/a", "rd": 1},
{"r": float("inf"), "rd": 100}):
assert sanitize_opp(bad) is None, bad # malformed -> rejected
print("rating.py self-test: all checks passed ✓")
def main() -> None:
ap = argparse.ArgumentParser(description="Local per-activity skill ratings.")
ap.add_argument("--selftest", action="store_true", help="run math self-checks")
args = ap.parse_args()
if args.selftest:
_selftest()
return
data = load()
if not data:
print("No ratings yet. They appear after your first table-tennis meetup "
"(or set `skill:` in profile.yaml).")
return
print("Your skill ratings (local, never published):")
for act in sorted(data):
st = data[act]
print(f" {client.activity_label(act):16s} {band_for(st['r']):11s} "
f"rating {st['r']:.0f} ± {st['rd']:.0f} ({st['games']} game(s))")
if __name__ == "__main__":
main()

Xet Storage Details

Size:
11.4 kB
·
Xet hash:
19472df1ebd9adf9ffc920fbf4435872d47656e1cfd164f54e728f8ff03b37b2

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.