{"status":"computed","sport":"tennis","label":"Historical ATP tour-level main-draw singles match-winner baseline; not live predictions or deployed accuracy.","candidates":[{"name":"Jeff Sackmann tennis_atp","url":"https://github.com/JeffSackmann/tennis_atp","licenceName":"CC BY-NC-SA 4.0 (preserved author README)","licenceUrl":"https://raw.githubusercontent.com/beta2k/tennis_atp/master/README.md","quotedTerms":[{"url":"https://raw.githubusercontent.com/beta2k/tennis_atp/master/README.md","quote":"In other words: Attribution is required. Non-commercial use only."}],"commercialReuse":"not_permitted","fetched":false,"note":"Original repository/README: HTTP 404. Preserved author licence opened in the beta2k mirror; no results downloaded."},{"name":"Tennis-Data","url":"https://www.tennis-data.co.uk/index.php","licenceName":"Proprietary; private individuals only","licenceUrl":"https://www.tennis-data.co.uk/data.php","quotedTerms":[{"url":"https://www.tennis-data.co.uk/data.php","quote":"Its use is intended for private individuals only, not commerical or data training products using automated bots/scrapers/AI."}],"commercialReuse":"not_permitted","fetched":false},{"name":"ATP World Tour tennis data, DataHub/core and serve-and-volley","url":"https://datahub.io/core/atp-world-tour-tennis-data","licenceName":"Creative Commons Attribution 4.0 International (CC BY 4.0)","licenceUrl":"https://creativecommons.org/licenses/by/4.0/deed.en","quotedTerms":[{"url":"https://raw.githubusercontent.com/datasets/atp-world-tour-tennis-data/master/README.md","quote":"This work is licensed under a [Creative Commons Attribution 4.0 International License](http://creativecommons.org/licenses/by/4.0/)."},{"url":"https://creativecommons.org/licenses/by/4.0/deed.en","quote":"material for any purpose, even commercially."}],"commercialReuse":"permitted","fetched":true}],"candidateFetchMeaning":"Data files only; licence quotes fetched with User-Agent Mozilla/5.0.","dataset":{"publisher":"DataHub/core (datasets/atp-world-tour-tennis-data); original archive serve-and-volley","files":[{"name":"matches_1991_2016.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/2_match_scores/match_scores_1991-2016_UNINDEXED.csv","role":"results","sha256":"0cfc68b58a5479073585b306951550335eb600f6477ed1e107e03e79afaa9439","bytes":22688239,"retrievedUtc":"2026-11-26T03:30:18.900597Z"},{"name":"matches_2017.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/2_match_scores/match_scores_2017_UNINDEXED.csv","role":"results","sha256":"0cbbeb4f7176c5442032e5542d041b4e31574b6cff993dac39ec607dabb4da64","bytes":919598,"retrievedUtc":"2026-11-26T03:30:18.476584Z"},{"name":"tournaments.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/1_tournaments/tournaments_1877-2017_UNINDEXED.csv","role":"tournaments","sha256":"47e31b7d1c44003fa699c68ceaeb332a56ca0983d627d5acc19bfa5e11ba7700","bytes":1412907,"retrievedUtc":"2026-11-26T03:30:18.504585Z"},{"name":"rankings_2011.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/4_rankings/rankings_2011.csv","role":"rankings","sha256":"6f7795ce43f3c6daa42c6ecf60ec3fe5ab7fd45b8b4c8d91e1ed07342e083c38","bytes":9221854,"retrievedUtc":"2026-11-26T03:34:57.129241Z"},{"name":"rankings_2012.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/4_rankings/rankings_2012.csv","role":"rankings","sha256":"e4c1d3ddb0023e3bcf3bdf7cff76023da8222ba7bc61e3ff0a825e2e788877af","bytes":9869050,"retrievedUtc":"2026-11-26T03:34:54.453157Z"},{"name":"rankings_2013.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/4_rankings/rankings_2013.csv","role":"rankings","sha256":"2d27ef80253f8a15a9cf5192e66fa806a1e37dc64a974eaebb497836ba762439","bytes":10293497,"retrievedUtc":"2026-11-26T03:34:56.505221Z"},{"name":"rankings_2014.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/4_rankings/rankings_2014.csv","role":"rankings","sha256":"66c816249b0210448e7f729071312934b3ec0238fefa4831b52a14b49f2cf336","bytes":10974869,"retrievedUtc":"2026-11-26T03:34:57.521253Z"},{"name":"rankings_2015.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/4_rankings/rankings_2015.csv","role":"rankings","sha256":"4c9a80fe033accc41aada72426e7fa5e465ccd3312ce059a48ff4f007f41a575","bytes":11095450,"retrievedUtc":"2026-11-26T03:34:55.993205Z"},{"name":"rankings_2016.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/4_rankings/rankings_2016.csv","role":"rankings","sha256":"f40d5c185e9c5ff790c9823356ffb1e6a4181aefecd13d96fb3bd498eddf23c0","bytes":10784984,"retrievedUtc":"2026-11-26T03:34:54.993174Z"},{"name":"rankings_2017.csv","url":"https://datahub.io/core/atp-world-tour-tennis-data/_r/-/csv/4_rankings/rankings_2017.csv","role":"rankings","sha256":"a1fa8ffc5a5baf0672a7194a43c167b783746e489a8b9bec14cc5daec09caebf","bytes":9494390,"retrievedUtc":"2026-11-26T03:32:15.816209Z"},{"name":"match_scores_2010-2019.csv","url":"https://raw.githubusercontent.com/serve-and-volley/atp-world-tour-tennis-data/a92c6192c5e775df9d6be81d3ef978052b012cd9/csv/2_match_scores/match_scores_2010-2019.csv","role":"dates_only","sha256":"3b89a81ea3a19c7bf14a03c8392350b04708ef5b672bd5f54074a99d1271dfa0","bytes":14444860,"retrievedUtc":"2026-11-26T03:32:41.885019Z"},{"name":"tournaments_2010-2019.csv","url":"https://raw.githubusercontent.com/serve-and-volley/atp-world-tour-tennis-data/a92c6192c5e775df9d6be81d3ef978052b012cd9/csv/1_tournaments/tournaments_2010-2019.csv","role":"event_types_only","sha256":"8f9ffbeaf169d88cee77874410cc524669f2e5a23d0da663a7b663ff62c9ef74","bytes":266197,"retrievedUtc":"2026-11-26T03:32:41.329001Z"}],"retrievedUtc":"2026-11-26T03:34:57.521253Z","selection":"Primary results end in 2017. Auxiliary 2010-2019 files supply only dates/types for 2012-2017; no outcomes or later-year data.","completeness":"Latest primary year: 2017; all 67 tournament IDs have finals, including ATP Finals (2017-605). Archive-season closure, not an independent census."},"creditLine":"ATP World Tour tennis data: serve-and-volley (https://github.com/serve-and-volley/atp-world-tour-tennis-data), DataHub/core (https://datahub.io/core/atp-world-tour-tennis-data). CC BY 4.0: https://creativecommons.org/licenses/by/4.0/. Modified: filtering, joins, baselines. No endorsement.","columnsUsed":{"primaryResults":["tourney_year_id","tourney_round_name","match_order","winner_player_id","loser_player_id","match_score_tiebreaks","match_stats_url_suffix"],"primaryTournaments":["tourney_year","tourney_year_id","tourney_dates","tourney_name","tourney_surface"],"rankings":["week_title","rank_number","player_id"],"auxiliaryDates":"Zero-based: 0=tourney_year_id,5=start_date,9=end_date.","auxiliaryTypes":"Zero-based: 0=tourney_year_id,2=tourney_type.","predictors":"Rank baseline: rankings. Elo: IDs and earlier results. Other columns filter/enforce time. Surface preserved verbatim, not used to predict."},"splitDeclaredBeforeComputation":"Training 2012-2015; calibration 2016; test 2017 (latest primary year).","outcomeRule":"A=min(player IDs) lexicographically; y=1 iff A is the recorded winner. Retirements/default retained; W/O and UNP/ambiguous results excluded. Winner/loser source order is not a feature.","exclusionRule":"Sequential disjoint counts across primary files. Other levels=Olympics (128); team=World Team Championship (26). Memphis: invalid dates 2012-2013, missing joins 2014-2017. Zeros describe detected rows, not universal coverage.","method":{"baseline":"q=better-ranked training wins/ranked training events. Lower rank gets q; other gets 1-q; missing/equal rank gets 0.5. Latest global ranking date strictly before start; no player carry-forward.","elo":"1500 initial; K=32; scale=400; p(A)=1/(1+10^((Rb-Ra)/400)). Fixed a priori; no decay/resets/surface terms/warm-up. Queue delta=32*(y-p); apply +/-delta after tournament end, strictly before next start. Same-start forecasts share available state; continue ratings through test.","scaling":"sigmoid(logit(p_raw)/T). Fit calibration log loss only: 80 gradient bisections on 1/T in [0.25,4], checking endpoints. T frozen before test scoring; raw Elo updates unchanged.","metrics":"Brier=mean((p-y)^2+((1-p)-(1-y))^2), range 0-2. Natural-log loss clips p to [1e-15,1-1e-15]. Identical test events.","reliability":"10 equal bins for P(A wins), observed=A wins/n. Left-closed/right-open; last includes 1. Empty means=null."},"leakageRule":"Freeze state at tournament start for the given pair; admit only results with tournament end < start and rankings dated < start. Splits are disjoint; calibration alone fits T. See checks and executable assertions.","limitations":["Retrospective 2017 evidence only. No individual match timestamps: first/last dates mean tournament starts; omit earlier rounds from same-tournament forecasts.","Coverage/corrections lack independent verification. Excluding Memphis leaves 66/67 test tournaments. Tour-only history, cold start and pooled surfaces limit Elo.","Rank publication dates lack verified release times. Eight test events use 0.5 for missing ranks. Archive errors remain possible.","Cluster intervals omit cross-tournament player dependence and fitting uncertainty. Calibration does not guarantee future improvement."],"splits":{"training":{"period":["2012-01-01","2015-12-31"],"firstDate":"2012-01-01","lastDate":"2015-11-15","lastTournamentEnd":"2015-11-22","n":10178,"tournaments":252,"outcomeCounts":{"A_won":5208,"B_won":4970},"missingRankingEvents":25,"equalRankEvents":0,"retirementsRetained":356,"defaultsRetained":1},"calibration":{"period":["2016-01-01","2016-12-31"],"firstDate":"2016-01-04","lastDate":"2016-11-13","lastTournamentEnd":"2016-11-20","n":2554,"tournaments":64,"outcomeCounts":{"A_won":1236,"B_won":1318},"missingRankingEvents":7,"equalRankEvents":0,"retirementsRetained":79,"defaultsRetained":0},"test":{"period":["2017-01-01","2017-12-31"],"firstDate":"2017-01-01","lastDate":"2017-11-12","lastTournamentEnd":"2017-11-19","n":2592,"tournaments":66,"outcomeCounts":{"A_won":1332,"B_won":1260},"missingRankingEvents":8,"equalRankEvents":0,"retirementsRetained":88,"defaultsRetained":0}},"exclusions":{"sequential_exclusions":{"outside_nominal_year_window":73683,"doubles":0,"qualifying":9760,"team_events":26,"exhibition_events":0,"other_tournament_levels":128,"unknown_round":0,"missing_tournament_metadata":108,"missing_or_invalid_date_range":62,"outside_calendar_window":0,"crosses_split_boundary":0,"walkovers":98,"unplayed_or_ambiguous_result":0,"missing_or_same_player":0,"duplicate_event":0},"counts":{"walkover_markers_in_window_before_filters":124,"raw_result_rows":99189,"retained_events":15324,"retirement_markers_in_window_before_filters":806,"retirements_retained":523,"retirements_excluded":283,"primary_test_tournaments":67,"primary_test_tournaments_with_final":67},"retirements_excluded_by_reason":{"qualifying":277,"missing_or_invalid_date_range":2,"other_tournament_levels":2,"missing_tournament_metadata":2},"missing_metadata_tournaments":{"2014-402":27,"2015-402":27,"2016-402":27,"2017-402":27},"missing_date_tournaments":["2012-402","2013-402"]},"fitted":{"trainingRankedEvents":10153,"trainingBetterRankedWins":6817,"baselineProbability":0.6714271643849109,"T":1.1514634329386175},"testResults":{"baseline":{"n":2592,"brier":"0.4578","logLoss":"0.6504","brier95":["0.4428","0.4749"],"logLoss95":["0.6348","0.6683"]},"rawElo":{"n":2592,"brier":"0.4273","logLoss":"0.6181","brier95":["0.4077","0.4487"],"logLoss95":["0.5949","0.6433"]},"scaledElo":{"n":2592,"brier":"0.4255","logLoss":"0.6146","brier95":["0.4073","0.4452"],"logLoss95":["0.5936","0.6372"]}},"reliabilityBins":{"baseline":[{"bin":"[0.0,0.1)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.1,0.2)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.2,0.3)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.3,0.4)","n":1338,"meanPredicted":0.328573,"observedRate":0.37145},{"bin":"[0.4,0.5)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.5,0.6)","n":8,"meanPredicted":0.5,"observedRate":0.375},{"bin":"[0.6,0.7)","n":1246,"meanPredicted":0.671427,"observedRate":0.667737},{"bin":"[0.7,0.8)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.8,0.9)","n":0,"meanPredicted":null,"observedRate":null},{"bin":"[0.9,1.0]","n":0,"meanPredicted":null,"observedRate":null}],"rawElo":[{"bin":"[0.0,0.1)","n":68,"meanPredicted":0.070136,"observedRate":0.132353},{"bin":"[0.1,0.2)","n":195,"meanPredicted":0.152282,"observedRate":0.2},{"bin":"[0.2,0.3)","n":295,"meanPredicted":0.250896,"observedRate":0.301695},{"bin":"[0.3,0.4)","n":337,"meanPredicted":0.350713,"observedRate":0.367953},{"bin":"[0.4,0.5)","n":398,"meanPredicted":0.448817,"observedRate":0.487437},{"bin":"[0.5,0.6)","n":395,"meanPredicted":0.549847,"observedRate":0.567089},{"bin":"[0.6,0.7)","n":321,"meanPredicted":0.649106,"observedRate":0.616822},{"bin":"[0.7,0.8)","n":281,"meanPredicted":0.748103,"observedRate":0.715302},{"bin":"[0.8,0.9)","n":212,"meanPredicted":0.846566,"observedRate":0.820755},{"bin":"[0.9,1.0]","n":90,"meanPredicted":0.938763,"observedRate":0.888889}],"scaledElo":[{"bin":"[0.0,0.1)","n":36,"meanPredicted":0.076464,"observedRate":0.111111},{"bin":"[0.1,0.2)","n":161,"meanPredicted":0.156419,"observedRate":0.173913},{"bin":"[0.2,0.3)","n":277,"meanPredicted":0.253791,"observedRate":0.259928},{"bin":"[0.3,0.4)","n":369,"meanPredicted":0.350876,"observedRate":0.373984},{"bin":"[0.4,0.5)","n":450,"meanPredicted":0.449825,"observedRate":0.473333},{"bin":"[0.5,0.6)","n":450,"meanPredicted":0.549555,"observedRate":0.582222},{"bin":"[0.6,0.7)","n":342,"meanPredicted":0.649163,"observedRate":0.622807},{"bin":"[0.7,0.8)","n":283,"meanPredicted":0.747107,"observedRate":0.766784},{"bin":"[0.8,0.9)","n":172,"meanPredicted":0.844401,"observedRate":0.813953},{"bin":"[0.9,1.0]","n":52,"meanPredicted":0.938665,"observedRate":0.865385}]},"checks":{"hashVerifiedFiles":12,"uniqueEventKeys":15324,"rankingAudit":{"nonmissing_player_rankings":30608,"invalid_rank_rows":0,"identical_duplicate_rank_rows":0,"max_snapshot_age_days":14,"ranking_date_violations":0},"eloEndBeforeStartAssertions":15324,"disjointChronologicalSplits":true,"prefixInvariance":true,"inputOrderInvariance":true,"futureLabelPerturbation":true,"temperatureIndependentOfTestLabels":true,"binCountsMatchTest":true},"bootstrap":{"unit":"tournament (paired clusters across all three forecasters)","replicates":2000,"seed":20261126,"clusters":66,"interval":"percentile 2.5% and 97.5%, linear interpolation; event-weighted mean per replicate"},"reproduce":{"runtime":"Python 3 standard library. First run downloads inputs; cached runs accept --offline.","commands":["mkdir -p test/scratch/tennis-repro","python3 -c 'import json,pathlib; r=json.loads(pathlib.Path(\"artifacts/goal/batches/sport-baselines-v5/items/tennis/result.json\").read_text()); pathlib.Path(\"test/scratch/tennis-repro/reproduce.py\").write_text(r[\"reproduce\"][\"script\"],encoding=\"utf-8\")'","python3 test/scratch/tennis-repro/reproduce.py artifacts/goal/batches/sport-baselines-v5/items/tennis/result.json test/scratch/tennis-repro/cache > test/scratch/tennis-repro/recomputed.json","python3 -c 'import json,pathlib; r=json.loads(pathlib.Path(\"artifacts/goal/batches/sport-baselines-v5/items/tennis/result.json\").read_text()); c=json.loads(pathlib.Path(\"test/scratch/tennis-repro/recomputed.json\").read_text()); assert all(r[k]==v for k,v in c.items()); print(\"Reproduction matches\")'"],"script":"\"\"\"Historical ATP baseline; standard library only. Inputs are hash-checked.\"\"\"\nimport argparse\nimport bisect\nimport collections\nimport csv\nimport datetime as dt\nimport hashlib\nimport heapq\nimport itertools\nimport json\nimport math\nfrom pathlib import Path\nimport random\nimport re\nimport urllib.request\nTRAIN = (2012, 2015)\nCAL, TEST = 2016, 2017\nK, INITIAL, SCALE = 32.0, 1500.0, 400.0\nBETA_BOUNDS, BISECTIONS = (0.25, 4.0), 80\nSEED, REPLICATES, EPS = 20261126, 2000, 1e-15\nLEVELS = {'ATP 250', 'ATP 500', 'Masters 1000', 'Grand Slam', 'ATP Finals'}\nROUNDS = {'Finals', 'Semi-Finals', 'Quarter-Finals', 'Round of 16',\n     'Round of 32', 'Round of 64', 'Round of 128', 'Round Robin'}\ndef date(s):\n  return dt.date.fromisoformat(s.replace('.', '-'))\ndef sigmoid(z):\n  if z >= 0:\n    return 1.0 / (1.0 + math.exp(-z))\n  e = math.exp(z)\n  return e / (1.0 + e)\ndef period(d):\n  return 'training' if d.year <= TRAIN[1] else 'calibration' if d.year == CAL else 'test'\ndef get_files(config, cache, offline):\n  paths = {}\n  for f in config['dataset']['files']:\n    p = cache / f['name']\n    if not p.exists():\n      if offline:\n        raise RuntimeError('Missing cached input: ' + f['name'])\n      with urllib.request.urlopen(f['url'], timeout=120) as response:\n        data = response.read()\n      assert len(data) == f['bytes'] and hashlib.sha256(data).hexdigest() == f['sha256']\n      p.write_bytes(data)\n    data = p.read_bytes()\n    assert len(data) == f['bytes'], f['name']\n    assert hashlib.sha256(data).hexdigest() == f['sha256'], f['name']\n    paths[f['name']] = p\n  return paths\ndef dictionaries(path):\n  with path.open(encoding='utf-8-sig', newline='') as f:\n    yield from csv.DictReader(f)\ndef load_events(paths):\n  ranges = collections.defaultdict(set)\n  with paths['match_scores_2010-2019.csv'].open(newline='') as f:\n    for row in csv.reader(f):\n      assert len(row) == 36\n      if TRAIN[0] <= int(row[0][:4]) <= TEST:\n        ranges[row[0]].add((row[5], row[9]))\n  assert all(len(v) == 1 for v in ranges.values())\n  ranges = {k: next(iter(v)) for k, v in ranges.items()}\n  types = {}\n  with paths['tournaments_2010-2019.csv'].open(newline='') as f:\n    for row in csv.reader(f):\n      assert len(row) == 31\n      if TRAIN[0] <= int(row[0][:4]) <= TEST:\n        assert row[0] not in types\n        types[row[0]] = row[2]\n  tours = {}\n  for r in dictionaries(paths['tournaments.csv']):\n    if TRAIN[0] <= int(r['tourney_year']) <= TEST:\n      key = r['tourney_year_id']\n      assert key not in tours\n      tours[key] = (r['tourney_dates'], r['tourney_name'], r['tourney_surface'])\n  reasons = ['outside_nominal_year_window', 'doubles', 'qualifying', 'team_events',\n       'exhibition_events', 'other_tournament_levels', 'unknown_round',\n       'missing_tournament_metadata', 'missing_or_invalid_date_range',\n       'outside_calendar_window', 'crosses_split_boundary', 'walkovers',\n       'unplayed_or_ambiguous_result', 'missing_or_same_player', 'duplicate_event']\n  excluded = dict.fromkeys(reasons, 0)\n  events, keys = [], set()\n  raw_count, latest, window_rets = 0, 0, 0\n  audit = collections.Counter()\n  missing_date_tournaments = set()\n  metadata_failures = collections.Counter()\n  retirements_excluded = collections.Counter()\n  test_tournaments, test_finals = set(), set()\n  for filename in ['matches_1991_2016.csv', 'matches_2017.csv']:\n    for r in dictionaries(paths[filename]):\n      raw_count += 1\n      tid = r['tourney_year_id']\n      year = int(tid[:4]); latest = max(latest, year)\n      reason = None\n      if not TRAIN[0] <= year <= TEST:\n        excluded['outside_nominal_year_window'] += 1\n        continue\n      score = r['match_score_tiebreaks'].strip().upper()\n      rnd = r['tourney_round_name']\n      if year == TEST:\n        test_tournaments.add(tid)\n        if rnd == 'Finals': test_finals.add(tid)\n      window_rets += int('RET' in score)\n      audit['walkover_markers_in_window_before_filters'] += int('W/O' in score)\n      if re.search(r'/(MD|QD)\\d+', r['match_stats_url_suffix'], re.I):\n        reason = 'doubles'\n      elif 'Qualifying' in rnd:\n        reason = 'qualifying'\n      elif tid in tours and ('World Team' in tours[tid][1] or types.get(tid) in {'Laver Cup', 'ATP Cup', 'Davis Cup'}):\n        reason = 'team_events'\n      elif types.get(tid) in {'Next Gen Finals', 'Exhibition'}:\n        reason = 'exhibition_events'\n      elif tid not in tours or tid not in types or tid not in ranges:\n        reason = 'missing_tournament_metadata'\n      elif types[tid] not in LEVELS:\n        reason = 'other_tournament_levels'\n      elif rnd not in ROUNDS:\n        reason = 'unknown_round'\n      if reason:\n        excluded[reason] += 1\n        retirements_excluded[reason] += int('RET' in score)\n        if reason == 'missing_tournament_metadata': metadata_failures[tid] += 1\n        continue\n      try:\n        start, end = map(date, ranges[tid])\n        assert start <= end and start == date(tours[tid][0])\n      except (ValueError, AssertionError):\n        excluded['missing_or_invalid_date_range'] += 1\n        retirements_excluded['missing_or_invalid_date_range'] += int('RET' in score)\n        missing_date_tournaments.add(tid)\n        continue\n      if not TRAIN[0] <= start.year <= TEST:\n        reason = 'outside_calendar_window'\n      elif period(start) != period(end) or end.year > TEST:\n        reason = 'crosses_split_boundary'\n      elif 'W/O' in score:\n        reason = 'walkovers'\n      elif not score or 'UNP' in score or set(re.findall(r'[A-Z/]+', score)) - {'RET', 'DEF'}:\n        reason = 'unplayed_or_ambiguous_result'\n      w, l = r['winner_player_id'].strip(), r['loser_player_id'].strip()\n      if not reason and (not w or not l or w == l):\n        reason = 'missing_or_same_player'\n      if reason:\n        excluded[reason] += 1\n        retirements_excluded[reason] += int('RET' in score)\n        continue\n      a, b = sorted((w, l))\n      key = (tid, rnd, r['match_order'], a, b)\n      if key in keys:\n        excluded['duplicate_event'] += 1\n        retirements_excluded['duplicate_event'] += int('RET' in score)\n        continue\n      keys.add(key)\n      events.append(dict(key=key, tid=tid, start=start, end=end, a=a, b=b,\n               y=int(w == a), retired='RET' in score, defaulted='DEF' in score,\n               surface=tours[tid][2], split=period(start)))\n  assert latest == TEST\n  assert test_tournaments == test_finals\n  assert f'{TEST}-605' in test_finals\n  assert raw_count == len(events) + sum(excluded.values())\n  audit.update(raw_result_rows=raw_count, retained_events=len(events),\n        retirement_markers_in_window_before_filters=window_rets,\n        retirements_retained=sum(e['retired'] for e in events),\n        retirements_excluded=sum(retirements_excluded.values()),\n        primary_test_tournaments=len(test_tournaments),\n        primary_test_tournaments_with_final=len(test_finals))\n  assert audit['retirements_retained'] + audit['retirements_excluded'] == window_rets\n  return sorted(events, key=lambda e: (e['start'], e['key'])), {\n    'sequential_exclusions': excluded, 'counts': dict(audit),\n    'retirements_excluded_by_reason':{k:v for k,v in retirements_excluded.items() if v},\n    'missing_metadata_tournaments':dict(metadata_failures),\n    'missing_date_tournaments': sorted(missing_date_tournaments)}\ndef attach_rankings(events, paths):\n  players = {e[s] for e in events for s in ('a', 'b')}\n  snapshots = collections.defaultdict(dict)\n  invalid, duplicates = 0, 0\n  for year in range(2011, TEST + 1):\n    for r in dictionaries(paths[f'rankings_{year}.csv']):\n      d = date(r['week_title'])\n      snap = snapshots[d]  # Preserve every publication date, even if no target player.\n      if r['player_id'] not in players:\n        continue\n      rank = r['rank_number'].strip()\n      if not rank.isdigit() or int(rank) < 1:\n        invalid += 1\n        continue\n      pid, rank = r['player_id'], int(rank)\n      if pid in snap:\n        duplicates += 1\n        assert snap[pid] == rank, 'Conflicting ranking snapshot'\n      snap[pid] = rank\n  dates = sorted(snapshots)\n  max_age, nonmissing = 0, 0\n  for e in events:\n    i = bisect.bisect_left(dates, e['start']) - 1\n    d = dates[i] if i >= 0 else None\n    snap = snapshots[d] if d else {}\n    assert d is None or d < e['start']\n    e['rank_a'], e['rank_b'] = snap.get(e['a']), snap.get(e['b'])\n    e['rank_date'] = d\n    nonmissing += (e['rank_a'] is not None) + (e['rank_b'] is not None)\n    if d:\n      max_age = max(max_age, (e['start'] - d).days)\n  return dict(nonmissing_player_rankings=nonmissing, invalid_rank_rows=invalid,\n        identical_duplicate_rank_rows=duplicates, max_snapshot_age_days=max_age,\n        ranking_date_violations=0)\ndef elo(events):\n  ratings = collections.defaultdict(lambda: INITIAL)\n  pending, predictions = [], {}\n  max_used_end, comparisons = None, 0\n  for start, group in itertools.groupby(sorted(events, key=lambda e:(e['start'], e['key'])), key=lambda e:e['start']):\n    while pending and pending[0][0] < start:\n      end, key, a, b, change = heapq.heappop(pending)\n      assert end < start\n      ratings[a] += change; ratings[b] -= change\n      max_used_end = end if max_used_end is None else max(max_used_end, end)\n    batch = list(group)\n    for e in batch:\n      assert max_used_end is None or max_used_end < start\n      comparisons += 1\n      z = math.log(10.0) * (ratings[e['a']] - ratings[e['b']]) / SCALE\n      predictions[e['key']] = z\n    for e in batch:\n      change = K * (e['y'] - sigmoid(predictions[e['key']]))\n      heapq.heappush(pending, (e['end'], e['key'], e['a'], e['b'], change))\n  return predictions, comparisons\ndef fit_temperature(calibration, logits):\n  def gradient(beta):\n    return math.fsum(logits[e['key']] * (sigmoid(beta * logits[e['key']]) - e['y']) for e in calibration)\n  lo, hi = BETA_BOUNDS\n  if gradient(lo) >= 0:\n    beta = lo\n  elif gradient(hi) <= 0:\n    beta = hi\n  else:\n    for _ in range(BISECTIONS):\n      mid = (lo + hi) / 2\n      if gradient(mid) < 0: lo = mid\n      else: hi = mid\n    beta = (lo + hi) / 2\n  return 1.0 / beta\ndef losses(p, y):\n  q = min(1.0 - EPS, max(EPS, p))\n  return 2.0 * (p - y) ** 2, -(y * math.log(q) + (1-y) * math.log1p(-q))\ndef quantile(xs, p):\n  xs = sorted(xs); pos = (len(xs)-1)*p; i = int(pos)\n  return xs[i] if i+1 == len(xs) else xs[i]+(pos-i)*(xs[i+1]-xs[i])\ndef evaluate(test, probabilities):\n  names = list(probabilities)\n  groups = collections.defaultdict(list)\n  for i, e in enumerate(test): groups[e['tid']].append(i)\n  clusters = list(sorted(groups))\n  totals = {m: [(len(groups[t]), math.fsum(losses(probabilities[m][i],test[i]['y'])[0] for i in groups[t]),\n         math.fsum(losses(probabilities[m][i],test[i]['y'])[1] for i in groups[t])) for t in clusters] for m in names}\n  rng = random.Random(SEED)\n  boots = {m: [[], []] for m in names}\n  for _ in range(REPLICATES):\n    draws = [rng.randrange(len(clusters)) for _ in clusters]\n    n = sum(totals[names[0]][i][0] for i in draws)\n    for m in names:\n      for k in (1,2): boots[m][k-1].append(math.fsum(totals[m][i][k] for i in draws)/n)\n  results, bins = {}, {}\n  for m in names:\n    results[m] = {'n':len(test), 'brier':format(math.fsum(x[1] for x in totals[m])/len(test),'.4f'),\n           'logLoss':format(math.fsum(x[2] for x in totals[m])/len(test),'.4f'),\n           'brier95':[format(quantile(boots[m][0],p),'.4f') for p in (.025,.975)],\n           'logLoss95':[format(quantile(boots[m][1],p),'.4f') for p in (.025,.975)]}\n    bins[m] = []\n    for b in range(10):\n      idx = [i for i,p in enumerate(probabilities[m]) if min(9,int(p*10)) == b]\n      bins[m].append({'bin':f'[{b/10:.1f},{(b+1)/10:.1f}'+(']' if b==9 else ')'), 'n':len(idx),\n              'meanPredicted':round(math.fsum(probabilities[m][i] for i in idx)/len(idx),6) if idx else None,\n              'observedRate':round(sum(test[i]['y'] for i in idx)/len(idx),6) if idx else None})\n    assert sum(b['n'] for b in bins[m]) == len(test)\n  return results, bins, len(clusters)\ndef compute(config, cache, offline):\n  paths = get_files(config, cache, offline)\n  events, exclusions = load_events(paths)\n  rank_audit = attach_rankings(events, paths)\n  splits = {s:[e for e in events if e['split']==s] for s in ['training','calibration','test']}\n  train, cal, test = (splits[s] for s in splits)\n  assert max(e['end'] for e in train) < min(e['start'] for e in cal)\n  assert max(e['end'] for e in cal) < min(e['start'] for e in test)\n  ranked = [e for e in train if e['rank_a'] and e['rank_b'] and e['rank_a'] != e['rank_b']]\n  better_wins = sum(e['y'] == int(e['rank_a'] < e['rank_b']) for e in ranked)\n  q = better_wins / len(ranked)\n  logits, checked = elo(events)\n  before_test, _ = elo(train+cal)\n  assert all(before_test[e['key']] == logits[e['key']] for e in train+cal)\n  assert elo(list(reversed(events)))[0] == logits\n  changed = [dict(e, y=1-e['y']) if e['split']=='test' else e for e in events]\n  changed_logits, _ = elo(changed)\n  assert all(changed_logits[e['key']] == logits[e['key']] for e in train+cal)\n  first_test_start = min(e['start'] for e in test)\n  assert all(changed_logits[e['key']] == logits[e['key']] for e in test if e['start']==first_test_start)\n  assert any(changed_logits[e['key']] != logits[e['key']] for e in test)\n  T = fit_temperature(cal, before_test)  # No test logits/labels supplied to fitter.\n  assert T == fit_temperature(cal, changed_logits)\n  p_base = [0.5 if not e['rank_a'] or not e['rank_b'] or e['rank_a']==e['rank_b']\n       else q if e['rank_a'] < e['rank_b'] else 1-q for e in test]\n  probabilities = {'baseline':p_base, 'rawElo':[sigmoid(logits[e['key']]) for e in test],\n          'scaledElo':[sigmoid(logits[e['key']]/T) for e in test]}\n  results, bins, cluster_count = evaluate(test, probabilities)\n  periods = {'training':['2012-01-01','2015-12-31'], 'calibration':['2016-01-01','2016-12-31'], 'test':['2017-01-01','2017-12-31']}\n  summary = {}\n  for s, es in splits.items():\n    summary[s] = {'period':periods[s], 'firstDate':min(e['start'] for e in es).isoformat(),\n           'lastDate':max(e['start'] for e in es).isoformat(),\n           'lastTournamentEnd':max(e['end'] for e in es).isoformat(),\n           'n':len(es), 'tournaments':len({e['tid'] for e in es}),\n           'outcomeCounts':{'A_won':sum(e['y'] for e in es),'B_won':sum(1-e['y'] for e in es)},\n           'missingRankingEvents':sum(not e['rank_a'] or not e['rank_b'] for e in es),\n           'equalRankEvents':sum(bool(e['rank_a']) and e['rank_a']==e['rank_b'] for e in es),\n           'retirementsRetained':sum(e['retired'] for e in es),\n           'defaultsRetained':sum(e['defaulted'] for e in es)}\n  return {'splits':summary, 'exclusions':exclusions,\n      'fitted':{'trainingRankedEvents':len(ranked),'trainingBetterRankedWins':better_wins,\n           'baselineProbability':q,'T':T},\n      'testResults':results,'reliabilityBins':bins,\n      'checks':{'hashVerifiedFiles':len(paths),'uniqueEventKeys':len(events),\n           'rankingAudit':rank_audit,'eloEndBeforeStartAssertions':checked,\n           'disjointChronologicalSplits':True,'prefixInvariance':True,\n           'inputOrderInvariance':True,'futureLabelPerturbation':True,\n           'temperatureIndependentOfTestLabels':True,'binCountsMatchTest':True},\n      'bootstrap':{'unit':'tournament (paired clusters across all three forecasters)',\n            'replicates':REPLICATES,'seed':SEED,'clusters':cluster_count,\n            'interval':'percentile 2.5% and 97.5%, linear interpolation; event-weighted mean per replicate'}}\ndef main():\n  parser = argparse.ArgumentParser()\n  parser.add_argument('result_json')\n  parser.add_argument('cache_directory')\n  parser.add_argument('--offline', action='store_true')\n  args = parser.parse_args()\n  config = json.loads(Path(args.result_json).read_text())\n  cache = Path(args.cache_directory); cache.mkdir(parents=True, exist_ok=True)\n  out = compute(config, cache, args.offline)\n  print(json.dumps(out, ensure_ascii=False, indent=2, allow_nan=False))\nif __name__ == '__main__':\n  main()\n"}}
