Add Elo, pair selection and comparison metrics with tests

Ratings are replayed from an event log (undo = skip the target event). K decays
48 -> 16 over a school's first 15 games. Smart pairing favours rarely compared
schools, then close ratings, with 10% exploration and random sides. metrics.js
derives grant, out-of-pocket cost, language and subject fit and the duel rows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HA82gXkMmmRRKLSnY6vQN3
This commit is contained in:
agent 2026-11-12 20:55:35 +00:00
parent 783c4d2f9a
commit 226e5f46f8
6 changed files with 672 additions and 0 deletions

97
test/elo.test.js Normal file
View file

@ -0,0 +1,97 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { expected, kFactor, replay, ranking, pairKey } from '../public/js/elo.js';
import { nextPair } from '../public/js/pairing.js';
const codes = ['A', 'B', 'C', 'D'];
let n = 0;
const ev = (fields) => ({ id: `ev${String(++n).padStart(6, '0')}`, t: '2026-11-10T10:00:00Z', ...fields });
test('expected score is symmetric and 0.5 for equal ratings', () => {
assert.equal(expected(1500, 1500), 0.5);
assert.ok(Math.abs(expected(1600, 1400) + expected(1400, 1600) - 1) < 1e-12);
assert.ok(expected(1900, 1500) > 0.9);
});
test('K decays linearly from kMax to kMin over decayGames', () => {
const o = { kMax: 48, kMin: 16, decayGames: 16 };
assert.equal(kFactor(0, o), 48);
assert.equal(kFactor(8, o), 32);
assert.equal(kFactor(16, o), 16);
assert.equal(kFactor(100, o), 16);
});
test('a win moves both ratings; equal newcomers swap K/2', () => {
const { stats } = replay([ev({ type: 'match', a: 'A', b: 'B', r: 'a' })], codes);
assert.equal(stats.get('A').rating, 1524);
assert.equal(stats.get('B').rating, 1476);
assert.equal(stats.get('A').wins, 1);
assert.equal(stats.get('B').losses, 1);
});
test('draw between equals changes nothing but counts the game', () => {
const { stats } = replay([ev({ type: 'match', a: 'A', b: 'B', r: 'draw' })], codes);
assert.equal(stats.get('A').rating, 1500);
assert.equal(stats.get('A').draws, 1);
assert.equal(stats.get('A').games, 1);
});
test('undo removes the targeted event as if it never happened', () => {
const m = ev({ type: 'match', a: 'A', b: 'B', r: 'a' });
const d = ev({ type: 'drop', code: 'C' });
const { stats, lastUndoable, pairCounts } = replay([m, d, ev({ type: 'undo', target: m.id })], codes);
assert.equal(stats.get('A').rating, 1500);
assert.equal(stats.get('A').games, 0);
assert.equal(stats.get('C').dropped, true);
assert.equal(lastUndoable.id, d.id, 'the drop is now the latest undoable action');
assert.equal(pairCounts.size, 0);
});
test('drop / restore / review', () => {
const { stats } = replay([
ev({ type: 'drop', code: 'A' }), ev({ type: 'restore', code: 'A' }), ev({ type: 'review', code: 'B' }),
], codes);
assert.equal(stats.get('A').dropped, false);
assert.equal(stats.get('A').reviewed, true, 'a drop counts as reviewed');
assert.equal(stats.get('B').reviewed, true);
});
test('events for unknown schools are ignored', () => {
const { stats, matches } = replay([ev({ type: 'match', a: 'A', b: 'ZZZ', r: 'a' })], codes);
assert.equal(matches.length, 0);
assert.equal(stats.get('A').games, 0);
});
test('ranking sorts by rating and hides dropped schools', () => {
const { stats } = replay([
ev({ type: 'match', a: 'C', b: 'D', r: 'a' }), ev({ type: 'drop', code: 'C' }),
], codes);
const order = ranking(stats).map((s) => s.code);
assert.deepEqual(order.slice(-1), ['D']);
assert.ok(!order.includes('C'));
assert.ok(ranking(stats, { includeDropped: true }).some((s) => s.code === 'C'));
});
test('consistent preferences converge to the true order', () => {
// Hidden truth: A > B > C > D. Pick pairs with the real pairing code and answer by the truth.
const truth = { A: 4, B: 3, C: 2, D: 1 };
let seed = 42;
const rng = () => { // mulberry32
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
const events = [];
for (let i = 0; i < 40; i++) {
const { stats, pairCounts } = replay(events, codes);
const [a, b] = nextPair(stats, { rng, pairCounts });
events.push(ev({ type: 'match', a, b, r: truth[a] > truth[b] ? 'a' : 'b' }));
}
const { stats } = replay(events, codes);
assert.deepEqual(ranking(stats).map((s) => s.code), ['A', 'B', 'C', 'D']);
});
test('pairKey is order-independent', () => {
assert.equal(pairKey('X', 'Y'), pairKey('Y', 'X'));
});

91
test/metrics.test.js Normal file
View file

@ -0,0 +1,91 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
DEFAULT_SETTINGS, languageFit, subjectFit, monthlyGrant, netCost, money, moneyRange, rowWinner, COMPARE_ROWS,
} from '../public/js/metrics.js';
const settings = { ...DEFAULT_SETTINGS };
const ag = (isced, languages = []) => ({ isced, languages, places: 2, scope: 'FEL', levels: ['N'] });
const L = (lang, level) => ({ lang, level });
test('language fit: one satisfied language is enough', () => {
const s = { agreements: [ag(['0714'], [L('de', 'B2'), L('en', 'B2')])] };
assert.equal(languageFit(s, settings.languages).status, 'ok');
});
test('language fit: German-only fails, Slovak is covered by Czech', () => {
assert.equal(languageFit({ agreements: [ag(['0533'], [L('de', 'B1')])] }, settings.languages).status, 'fail');
assert.equal(languageFit({ agreements: [ag(['0610'], [L('sk', 'B1')])] }, settings.languages).status, 'ok');
});
test('language fit: Spanish B1 fails with A2, unlisted is unknown, best agreement wins', () => {
assert.equal(languageFit({ agreements: [ag([], [L('es', 'B1')])] }, settings.languages).status, 'fail');
assert.equal(languageFit({ agreements: [ag([])] }, settings.languages).status, 'unknown');
const mixed = { agreements: [ag([], [L('de', 'B2')]), ag([])] };
assert.equal(languageFit(mixed, settings.languages).status, 'unknown');
});
test('subject fit for an Open Informatics AI student', () => {
assert.equal(subjectFit({ agreements: [ag(['0713', '0610'])] }).level, 'best');
assert.equal(subjectFit({ agreements: [ag(['0714'])] }).level, 'good');
assert.equal(subjectFit({ agreements: [ag([])] }).level, 'good', 'no codes = unrestricted');
assert.equal(subjectFit({ agreements: [ag(['0533'])] }).level, 'weak');
assert.equal(subjectFit({ agreements: [ag(['0730']), ag(['0000'])] }).level, 'good');
});
const school = (over = {}) => ({
code: 'X', country: 'Austria', agreements: [ag(['0610'])],
funding: { scheme: 'erasmus', group: 1, monthlyEUR: 660, label: 'Erasmus+ group 1' },
research: {
living: { totalEUR: [800, 1000] },
travel: { mode: 'train', roundTripEUR: [100, 200] },
fees: { mandatoryEUR: 25, hostFunding: { monthlyEUR: 100 } },
},
...over,
});
const data = { fx: { EURCZK: 25 }, funding: { erasmus: { fewerOpportunitiesTopUpEUR: 250 } }, countries: {} };
test('grant with optional top-ups', () => {
assert.equal(monthlyGrant(school(), settings, data).eur, 660);
assert.equal(monthlyGrant(school(), { ...settings, fewerOpportunities: true }, data).eur, 910);
assert.equal(monthlyGrant(school(), { ...settings, countHostFunding: true }, data).eur, 760);
assert.equal(monthlyGrant(school({ funding: null }), settings, data).eur, null);
});
test('net cost = living*months + travel + visa + fees - grant', () => {
const n = netCost(school(), settings, data);
// lo: 800*5 + 100 + 0 + 25 - 3300 = 825 ; hi: 1000*5 + 200 + 25 - 3300 = 1925
assert.deepEqual([n.lo, n.hi], [825, 1925]);
const withVisa = netCost(school({ country: 'Japan' }), settings,
{ ...data, countries: { Japan: { visa: { required: true, costEUR: 50 } } } });
assert.deepEqual([withVisa.lo, withVisa.hi], [875, 1975]);
const swap = netCost(school({ funding: { scheme: 'ctu', monthlyEUR: 616, extraPerSemesterEUR: 2260 } }), settings, data);
assert.equal(swap.lo, 800 * 5 + 100 + 25 + 2260 - 616 * 5);
assert.equal(netCost(school({ research: { living: null } }), settings, data), null);
});
test('money formatting in EUR and CZK', () => {
assert.equal(money(1234, settings, data), '€1,234');
assert.equal(money(1234, settings, data, { compact: true }), '€1.2k');
assert.equal(money(-300, settings, data), '−€300');
assert.equal(money(100, { ...settings, currency: 'CZK' }, data), '2,500 Kč');
assert.equal(moneyRange([750, 1050], settings, data), '€750–1,050');
assert.equal(moneyRange([750, 1050], { ...settings, currency: 'CZK' }, data, { compact: true }), '19k–26k Kč');
assert.equal(money(null, settings, data), '–');
});
test('row winner respects direction and unknowns', () => {
const high = { better: 'high' };
const low = { better: 'low' };
assert.equal(rowWinner(high, { v: 7 }, { v: 5 }), 'a');
assert.equal(rowWinner(low, { v: 7 }, { v: 5 }), 'b');
assert.equal(rowWinner(high, { v: 5 }, { v: 5 }), null);
assert.equal(rowWinner(high, null, { v: 5 }), null);
});
test('every comparison row tolerates a school without research', () => {
const bare = school({ research: null });
for (const row of COMPARE_ROWS) {
assert.doesNotThrow(() => row.get(bare, { settings, data }), row.id);
}
});

79
test/pairing.test.js Normal file
View file

@ -0,0 +1,79 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { nextPair } from '../public/js/pairing.js';
import { pairKey } from '../public/js/elo.js';
// mulberry32: small seeded PRNG. (A plain LCG's consecutive outputs are correlated enough to
// bias the side coin-flip in these tests.)
function seeded(a = 7) {
return () => {
a = (a + 0x6d2b79f5) | 0;
let t = Math.imul(a ^ (a >>> 15), 1 | a);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const mk = (code, rating = 1500, games = 0, dropped = false) => [code, { code, rating, games, dropped }];
test('never pairs a school with itself and never uses dropped schools', () => {
const stats = new Map([mk('A'), mk('B'), mk('C', 1500, 0, true)]);
const rng = seeded();
for (let i = 0; i < 200; i++) {
const [a, b] = nextPair(stats, { rng });
assert.notEqual(a, b);
assert.ok(a !== 'C' && b !== 'C');
}
});
test('returns null with fewer than two active schools', () => {
assert.equal(nextPair(new Map([mk('A'), mk('B', 1500, 0, true)])), null);
});
test('smart mode favours rarely compared schools', () => {
const stats = new Map([mk('NEW', 1500, 0), ...['A', 'B', 'C', 'D', 'E', 'F'].map((c) => mk(c, 1500, 30))]);
const rng = seeded(3);
let withNew = 0;
for (let i = 0; i < 500; i++) if (nextPair(stats, { rng }).includes('NEW')) withNew++;
// Uniform would give ~2/7 = 29%; the weighting should push it far above that.
assert.ok(withNew / 500 > 0.6, `NEW appeared in ${withNew}/500 pairs`);
});
test('smart mode prefers close ratings once schools are established', () => {
const stats = new Map([mk('X', 1500, 20), mk('NEAR', 1520, 20), mk('FAR', 1900, 20)]);
const rng = seeded(11);
let near = 0;
let far = 0;
for (let i = 0; i < 600; i++) {
const p = nextPair(stats, { rng });
if (p.includes('X') && p.includes('NEAR')) near++;
if (p.includes('X') && p.includes('FAR')) far++;
}
assert.ok(near > far * 3, `near=${near} far=${far}`);
});
test('recently shown pairs are avoided', () => {
const stats = new Map([mk('A'), mk('B'), mk('C'), mk('D')]);
const rng = seeded(5);
const recent = [pairKey('A', 'B'), pairKey('C', 'D')];
let repeats = 0;
for (let i = 0; i < 300; i++) {
const [a, b] = nextPair(stats, { rng, recent });
if (recent.includes(pairKey(a, b))) repeats++;
}
assert.ok(repeats < 15, `recent pairs reappeared ${repeats}/300 times`);
});
test('sides are randomised', () => {
const stats = new Map([mk('A', 1500, 0), mk('B', 1500, 50)]);
const rng = seeded(9);
let aLeft = 0;
for (let i = 0; i < 400; i++) if (nextPair(stats, { rng })[0] === 'A') aLeft++;
assert.ok(aLeft > 120 && aLeft < 280, `A on the left ${aLeft}/400`);
});
test('random mode works', () => {
const stats = new Map([mk('A'), mk('B'), mk('C')]);
const p = nextPair(stats, { mode: 'random', rng: seeded(1) });
assert.equal(p.length, 2);
assert.notEqual(p[0], p[1]);
});