diff --git a/public/js/elo.js b/public/js/elo.js new file mode 100644 index 0000000..1ae8102 --- /dev/null +++ b/public/js/elo.js @@ -0,0 +1,90 @@ +// Elo ratings computed by replaying the event log. Pure functions: shared by the browser and +// the Node test suite, no DOM access. +// +// K-factor decays with experience: a school's first comparisons move it a lot (it is still +// finding its level), later ones fine-tune. With kMax=48, kMin=16, decayGames=15 a school's +// K goes 48 -> 16 linearly over its first 15 games. Like FIDE's provisional ratings this makes +// a single match non-zero-sum when the two schools have different experience; that is intended. + +export const DEFAULTS = Object.freeze({ initial: 1500, kMax: 48, kMin: 16, decayGames: 15 }); +export const PROVISIONAL_GAMES = 5; +const UNDOABLE = new Set(['match', 'drop', 'restore', 'review']); + +/** Probability that a player rated `ra` beats one rated `rb`. */ +export function expected(ra, rb) { + return 1 / (1 + 10 ** ((rb - ra) / 400)); +} + +export function kFactor(games, opts = DEFAULTS) { + const { kMax, kMin, decayGames } = { ...DEFAULTS, ...opts }; + if (games >= decayGames) return kMin; + return kMax - ((kMax - kMin) * games) / decayGames; +} + +/** Order-independent key for a pair of schools. */ +export function pairKey(a, b) { + return a < b ? `${a}|${b}` : `${b}|${a}`; +} + +function blankStats(code, initial) { + return { code, rating: initial, games: 0, wins: 0, losses: 0, draws: 0, dropped: false, reviewed: false, history: [] }; +} + +/** + * Replay events (already in authoritative order) into per-school stats. + * Events whose id is the target of an `undo` are skipped entirely, as if they never happened. + * Events naming unknown schools are ignored (the dataset may change between versions). + */ +export function replay(events, codes, opts = {}) { + const o = { ...DEFAULTS, ...opts }; + const undone = new Set(events.filter((e) => e.type === 'undo').map((e) => e.target)); + const stats = new Map(codes.map((c) => [c, blankStats(c, o.initial)])); + const matches = []; + const pairCounts = new Map(); + + for (const ev of events) { + if (ev.type === 'undo' || undone.has(ev.id)) continue; + if (ev.type === 'match') { + const A = stats.get(ev.a); + const B = stats.get(ev.b); + if (!A || !B || A === B) continue; + const ea = expected(A.rating, B.rating); + const sa = ev.r === 'a' ? 1 : ev.r === 'b' ? 0 : 0.5; + const da = kFactor(A.games, o) * (sa - ea); + const db = kFactor(B.games, o) * (1 - sa - (1 - ea)); + A.rating += da; + B.rating += db; + A.games += 1; + B.games += 1; + if (sa === 1) { A.wins += 1; B.losses += 1; } + else if (sa === 0) { A.losses += 1; B.wins += 1; } + else { A.draws += 1; B.draws += 1; } + const m = { id: ev.id, t: ev.t, a: ev.a, b: ev.b, r: ev.r, da, db, ratingA: A.rating, ratingB: B.rating }; + matches.push(m); + A.history.push(m); + B.history.push(m); + const key = pairKey(ev.a, ev.b); + pairCounts.set(key, (pairCounts.get(key) ?? 0) + 1); + } else { + const s = stats.get(ev.code); + if (!s) continue; + if (ev.type === 'drop') { s.dropped = true; s.reviewed = true; } + else if (ev.type === 'restore') s.dropped = false; + else if (ev.type === 'review') s.reviewed = true; + } + } + + let lastUndoable = null; + for (let i = events.length - 1; i >= 0; i--) { + const ev = events[i]; + if (UNDOABLE.has(ev.type) && !undone.has(ev.id)) { lastUndoable = ev; break; } + } + return { stats, matches, pairCounts, undone, lastUndoable }; +} + +/** Schools ordered best-first. Ties broken by more games, then code for stability. */ +export function ranking(stats, { includeDropped = false } = {}) { + return [...stats.values()] + .filter((s) => includeDropped || !s.dropped) + .sort((x, y) => y.rating - x.rating || y.games - x.games || x.code.localeCompare(y.code)); +} diff --git a/public/js/metrics.js b/public/js/metrics.js new file mode 100644 index 0000000..89a9f49 --- /dev/null +++ b/public/js/metrics.js @@ -0,0 +1,249 @@ +// Derived, comparable values for a school: names, fit checks, money, and the rows of the +// side-by-side comparison. Pure functions (no DOM) so they're unit-tested in Node. +// +// `s` is one entry of data/schools.json `schools`; `data` is the whole file; `settings` are +// the user's synced preferences (see DEFAULT_SETTINGS). + +export const DEFAULT_SETTINGS = Object.freeze({ + stayMonths: 5, + currency: 'EUR', + pairing: 'smart', + fewerOpportunities: false, + countHostFunding: false, + languages: [ + { lang: 'en', level: 'C2' }, + { lang: 'cs', level: 'C2' }, + { lang: 'es', level: 'A2' }, + ], +}); + +const CEFR = { A1: 1, A2: 2, B1: 3, B2: 4, C1: 5, C2: 6 }; +// A language you speak that covers another one (Czech speakers read Slovak at about C1). +const COVERS = { sk: [{ lang: 'cs', minLevel: 'B2', asLevel: 'C1' }] }; + +// ISCED subject codes vs an Open Informatics (AI) student oriented to robotics. +const SUBJECT_FIT = { + '061': 'best', '0610': 'best', '0611': 'best', '0612': 'best', '0613': 'best', '0619': 'best', + '071': 'good', '0710': 'good', '0714': 'good', '0719': 'good', '00': 'good', '0000': 'good', + '0713': 'weak', '0715': 'weak', '0716': 'weak', '0533': 'weak', '0541': 'weak', + '0730': 'none', +}; +const FIT_RANK = { best: 3, good: 2, weak: 1, none: 0 }; +const FIT_TEXT = { best: 'Computing (fits)', good: 'Engineering / any (ok)', weak: 'Other field (weak)', none: 'Unrelated field' }; + +export const LANG_NAMES = { + en: 'English', de: 'German', fr: 'French', es: 'Spanish', it: 'Italian', pt: 'Portuguese', ca: 'Catalan', + sk: 'Slovak', sl: 'Slovenian', tr: 'Turkish', cs: 'Czech', nl: 'Dutch', sv: 'Swedish', pl: 'Polish', +}; + +/* ---------- names ---------- */ + +export function shortName(s) { + return s.research?.shortName || s.research?.name || s.catalogName.replace(/\.\.\.$/, '…'); +} + +export function fullName(s) { + return s.research?.name || s.catalogName.replace(/\.\.\.$/, '…'); +} + +export function place(s) { + return s.research?.city ? `${s.research.city}, ${s.countryShort}` : s.countryShort; +} + +/* ---------- fit checks ---------- */ + +function speaks(userLangs, lang) { + const own = userLangs.find((l) => l.lang === lang); + let best = own ? CEFR[own.level] : 0; + for (const c of COVERS[lang] ?? []) { + const via = userLangs.find((l) => l.lang === c.lang); + if (via && CEFR[via.level] >= CEFR[c.minLevel]) best = Math.max(best, CEFR[c.asLevel]); + } + return best; +} + +/** + * CTU lists the language(s) of instruction per agreement. When several are listed, one of + * them is normally enough (you take courses in that language). An agreement without a listed + * language is "unknown" (check the host). Across several agreements the best one wins: + * ok > unknown > fail. + * @returns {{status: 'ok'|'fail'|'unknown', text: string}} + */ +export function languageFit(s, userLangs) { + const rank = { ok: 2, unknown: 1, fail: 0 }; + let best = null; + for (const ag of s.agreements) { + let fit; + if (!ag.languages.length) { + fit = { status: 'unknown', text: 'Not listed: check the host' }; + } else { + const checks = ag.languages.map((l) => ({ ...l, ok: speaks(userLangs, l.lang) >= CEFR[l.level] })); + const met = checks.filter((c) => c.ok); + const shown = (met.length ? met : checks).map((c) => `${c.lang.toUpperCase()} ${c.level}`); + fit = met.length + ? { status: 'ok', text: `✓ ${[...new Set(shown)].join(' or ')}` } + : { status: 'fail', text: `✗ needs ${[...new Set(shown)].join(' or ')}` }; + } + if (!best || rank[fit.status] > rank[best.status]) best = fit; + } + return best ?? { status: 'unknown', text: 'Not listed: check the host' }; +} + +/** How well the agreement's ISCED subject area fits the student (best agreement wins). */ +export function subjectFit(s) { + let best = null; + for (const ag of s.agreements) { + // No subject codes = unrestricted agreement. + const fits = ag.isced.length ? ag.isced.map((c) => SUBJECT_FIT[c] ?? 'weak') : ['good']; + const top = fits.reduce((a, b) => (FIT_RANK[b] > FIT_RANK[a] ? b : a)); + if (!best || FIT_RANK[top] > FIT_RANK[best.level]) best = { level: top, codes: ag.isced }; + } + best ??= { level: 'good', codes: [] }; + return { level: best.level, rank: FIT_RANK[best.level], text: FIT_TEXT[best.level], codes: best.codes }; +} + +/* ---------- money ---------- */ + +/** Monthly money from CTU (+ optional top-ups) in EUR, or null if unknown. */ +export function monthlyGrant(s, settings, data) { + const f = s.funding; + if (!f || f.monthlyEUR == null) return { eur: null, text: f?.label ?? 'Unknown', host: 0 }; + let eur = f.monthlyEUR; + const parts = [f.label]; + if (settings.fewerOpportunities && f.scheme === 'erasmus') { + const top = data?.funding?.erasmus?.fewerOpportunitiesTopUpEUR ?? 250; + eur += top; + parts.push(`+${top} fewer-opportunities top-up`); + } + const host = s.research?.fees?.hostFunding?.monthlyEUR ?? 0; + if (settings.countHostFunding && host > 0) { + eur += host; + parts.push(`+${host} host scholarship`); + } + return { eur, text: parts.join(' '), host }; +} + +const mid = (r) => (r ? (r[0] + r[1]) / 2 : null); + +/** + * Out-of-pocket estimate for the whole stay: living + travel + visa + fees - money received. + * Returns null when living costs or travel are unknown. + */ +export function netCost(s, settings, data) { + const r = s.research; + if (!r?.living?.totalEUR || !r?.travel?.roundTripEUR) return null; + const m = settings.stayMonths; + const country = data?.countries?.[s.country]; + const visa = country?.visa?.required ? country.visa.costEUR ?? 0 : 0; + // Per-semester charges: the host's mandatory fees + CTU-side payments (housing-swap agreements). + const perSemester = (r.fees?.mandatoryEUR ?? 0) + (s.funding?.extraPerSemesterEUR ?? 0); + const fees = perSemester * Math.max(1, Math.ceil(m / 6)); + const grant = (monthlyGrant(s, settings, data).eur ?? 0) * m; + const fixed = visa + fees - grant; + return { + lo: Math.round(r.living.totalEUR[0] * m + r.travel.roundTripEUR[0] + fixed), + hi: Math.round(r.living.totalEUR[1] * m + r.travel.roundTripEUR[1] + fixed), + parts: { living: r.living.totalEUR.map((x) => x * m), travel: r.travel.roundTripEUR, visa, fees, grant }, + }; +} + +/* ---------- formatting ---------- */ + +export function money(eur, settings, data, { compact = false } = {}) { + if (eur == null || Number.isNaN(eur)) return '–'; + const czk = settings.currency === 'CZK'; + const rate = data?.fx?.EURCZK ?? 25; + const v = czk ? eur * rate : eur; + const sign = v < 0 ? '−' : ''; + const a = Math.abs(v); + let body; + if (compact && a >= 10000) body = `${Math.round(a / 1000)}k`; + else if (compact && a >= 1000) body = `${(a / 1000).toFixed(1).replace(/\.0$/, '')}k`; + else body = Math.round(a).toLocaleString('en-US'); + return czk ? `${sign}${body} Kč` : `${sign}€${body}`; +} + +export function moneyRange(range, settings, data, opts) { + if (!range) return '–'; + const [lo, hi] = range; + if (Math.round(lo) === Math.round(hi)) return money(lo, settings, data, opts); + // Negative = you'd end up with money left over; spell the range out to avoid "−€300–200". + if (lo < 0) return `${money(lo, settings, data, opts)} to ${money(hi, settings, data, opts)}`; + const czk = settings.currency === 'CZK'; + // "€750–1,050": currency symbol once, on the low end (EUR) or after the range (CZK). + const a = money(lo, settings, data, opts).replace(czk ? ' Kč' : '€', ''); + const b = money(hi, settings, data, opts).replace(czk ? ' Kč' : '€', ''); + return czk ? `${a}–${b} Kč` : `€${a}–${b}`; +} + +const TRAVEL_ICON = { train: '🚆', bus: '🚌', flight: '✈️', car: '🚗' }; + +/* ---------- comparison rows ---------- */ + +const scoreRow = (id, label, section, pick, hint) => ({ + id, label, section, hint, better: 'high', + get: (s) => { + const v = pick(s.research); + return v == null ? null : { v, text: String(Math.round(v * 10) / 10), bar: v }; + }, +}); + +/** + * Rows of the duel table. Each `get(s, ctx)` returns null (unknown) or + * { v: number to compare, text: string, bar?: 0-10 }. `better` says which direction wins. + */ +export const COMPARE_ROWS = [ + { id: 'subject', label: 'Subject fit', section: 'Fit', better: 'high', hint: 'Agreement subject area vs Open Informatics (AI)', + get: (s) => { const f = subjectFit(s); return { v: f.rank, text: f.text.replace(/ \(.*\)$/, ''), tone: f.level }; } }, + { id: 'language', label: 'Language', section: 'Fit', better: 'high', hint: 'CTU-listed language requirement vs your languages', + get: (s, ctx) => { const f = languageFit(s, ctx.settings.languages); return { v: { ok: 2, unknown: 1, fail: 0 }[f.status], text: f.text, tone: f.status }; } }, + scoreRow('academic', 'AI/robotics research', 'AI & robotics', (r) => r?.aiRobotics?.academic?.score), + scoreRow('practical', 'Hands-on', 'AI & robotics', (r) => r?.aiRobotics?.practical?.score), + scoreRow('access', 'Course access', 'AI & robotics', (r) => r?.aiRobotics?.access?.score, 'Relevant English MSc courses open to you'), + { id: 'grant', label: 'Money from CTU /mo', section: 'Money', better: 'high', + get: (s, ctx) => { const g = monthlyGrant(s, ctx.settings, ctx.data); return g.eur == null ? null : { v: g.eur, text: money(g.eur, ctx.settings, ctx.data) }; } }, + { id: 'living', label: 'Living cost /mo', section: 'Money', better: 'low', + get: (s, ctx) => { const r = s.research?.living?.totalEUR; return r ? { v: mid(r), text: moneyRange(r, ctx.settings, ctx.data, { compact: true }) } : null; } }, + { id: 'travel', label: 'Getting there', section: 'Money', better: 'low', hint: 'Round trip from Prague', + get: (s, ctx) => { + const t = s.research?.travel; + if (!t?.roundTripEUR) return null; + return { v: mid(t.roundTripEUR), text: `${TRAVEL_ICON[t.mode] ?? ''} ${moneyRange(t.roundTripEUR, ctx.settings, ctx.data, { compact: true })}` }; + } }, + { id: 'net', label: 'Out of pocket', section: 'Money', better: 'low', hint: 'Whole stay: living + travel + visa + fees − grants', + get: (s, ctx) => { const n = netCost(s, ctx.settings, ctx.data); return n ? { v: (n.lo + n.hi) / 2, text: moneyRange([n.lo, n.hi], ctx.settings, ctx.data, { compact: true }) } : null; } }, + scoreRow('social', 'Social life', 'Life', (r) => r?.social?.score), + scoreRow('solitude', 'Calm & solitude', 'Life', (r) => r?.solitude?.score), + scoreRow('english', 'Daily-life English', 'Life', (r) => (r?.language?.localNeed == null ? null : 10 - r.language.localNeed)), + scoreRow('climbing', 'Climbing', 'Nature', (r) => r?.nature?.climbing?.score), + scoreRow('hiking', 'Hiking', 'Nature', (r) => r?.nature?.hiking?.score), + scoreRow('ocean', 'Ocean', 'Nature', (r) => r?.nature?.ocean?.score), + scoreRow('skiing', 'Skiing', 'Nature', (r) => r?.nature?.skiing?.score), + scoreRow('safety', 'City safety', 'Safety', (r) => r?.safety?.score), + { id: 'stability', label: 'Country stability', section: 'Safety', better: 'high', + get: (s, ctx) => { const c = ctx.data?.countries?.[s.country]; return c?.stabilityScore == null ? null : { v: c.stabilityScore, text: String(c.stabilityScore), bar: c.stabilityScore }; } }, + { id: 'term', label: 'Term fit', section: 'Admin', better: 'high', + get: (s) => { const f = s.research?.calendar?.fit; return f ? { v: { good: 2, ok: 1, poor: 0 }[f], text: f, tone: f } : null; } }, + { id: 'visa', label: 'Visa', section: 'Admin', better: 'low', + get: (s, ctx) => { + const c = ctx.data?.countries?.[s.country]; + if (!c?.visa) return null; + if (!c.visa.required) return { v: 0, text: 'not needed' }; + return { v: c.visa.costEUR ?? 100, text: c.visa.costEUR != null ? `needed · ${money(c.visa.costEUR, ctx.settings, ctx.data)}` : 'needed' }; + } }, + { id: 'places', label: 'Places', section: 'Admin', better: 'high', hint: 'Exchange slots in the agreement(s)', + get: (s) => { + const p = s.agreements.map((a) => a.places).filter((x) => x != null); + if (!p.length) return null; + const open = p.some((x) => x >= 99); + const n = open ? 99 : p.reduce((a, b) => a + b, 0); + return { v: Math.min(n, 12), text: open ? 'open' : String(n) }; + } }, +]; + +/** Which side wins a row: 'a', 'b' or null (tie/unknown). */ +export function rowWinner(row, va, vb) { + if (!va || !vb || va.v == null || vb.v == null || va.v === vb.v) return null; + const aBetter = row.better === 'high' ? va.v > vb.v : va.v < vb.v; + return aBetter ? 'a' : 'b'; +} diff --git a/public/js/pairing.js b/public/js/pairing.js new file mode 100644 index 0000000..172886e --- /dev/null +++ b/public/js/pairing.js @@ -0,0 +1,66 @@ +// Choosing the next pair to compare. Pure functions; `rng` is injectable for tests. +// +// "smart" mode spends picks where they teach the ranking the most: +// 1. School A is drawn with weight 1/(1+games)^2, so rarely-compared schools come first. +// 2. School B is drawn with weight +// closeness(A,B) * 1/(1+games_B) * repeatPenalty * recentPenalty +// where closeness is a Gaussian on the rating gap. Its width shrinks as both schools +// gain games: wide while ratings are still rough, narrow once they're established. +// 3. 10% of the time B is uniform-random (exploration), so an early lucky streak can't hide +// a school from strong opponents forever. +// "random" mode: uniform pairs, avoiding immediate repeats. + +import { pairKey } from './elo.js'; + +function weightedPick(items, weightOf, rng) { + const weights = items.map((it) => { + const w = weightOf(it); + return Number.isFinite(w) && w > 0 ? w : 0; + }); + const total = weights.reduce((s, w) => s + w, 0); + if (total <= 0) return items[Math.floor(rng() * items.length)]; + let r = rng() * total; + for (let i = 0; i < items.length; i++) { + r -= weights[i]; + if (r < 0) return items[i]; + } + return items[items.length - 1]; +} + +/** + * @param {Map} stats from replay() + * @param {object} opts + * mode 'smart' | 'random' + * rng () => [0,1) + * recent pair keys shown recently (picked or skipped), newest last + * pairCounts Map pairKey -> times compared + * @returns {[string, string] | null} codes [left, right], or null if fewer than 2 active schools + */ +export function nextPair(stats, { mode = 'smart', rng = Math.random, recent = [], pairCounts = new Map() } = {}) { + const pool = [...stats.values()].filter((s) => !s.dropped); + if (pool.length < 2) return null; + const recentSet = new Set(recent.slice(-25)); + const recentPenalty = (a, b) => (recentSet.has(pairKey(a.code, b.code)) && pool.length > 3 ? 0.01 : 1); + + let a; + let b; + if (mode === 'random') { + a = pool[Math.floor(rng() * pool.length)]; + b = weightedPick(pool.filter((s) => s !== a), (s) => recentPenalty(a, s), rng); + } else { + a = weightedPick(pool, (s) => 1 / (1 + s.games) ** 2, rng); + const others = pool.filter((s) => s !== a); + if (rng() < 0.1) { + b = weightedPick(others, (s) => recentPenalty(a, s), rng); + } else { + b = weightedPick(others, (s) => { + const width = 120 + 280 / (1 + Math.min(a.games, s.games) / 4); + const closeness = Math.exp(-(((a.rating - s.rating) / width) ** 2)); + const repeats = pairCounts.get(pairKey(a.code, s.code)) ?? 0; + return closeness * (1 / (1 + s.games)) * (1 / (1 + 2 * repeats)) * recentPenalty(a, s); + }, rng); + } + } + // Random sides: no school should benefit from always being on the left. + return rng() < 0.5 ? [a.code, b.code] : [b.code, a.code]; +} diff --git a/test/elo.test.js b/test/elo.test.js new file mode 100644 index 0000000..efb3b36 --- /dev/null +++ b/test/elo.test.js @@ -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')); +}); diff --git a/test/metrics.test.js b/test/metrics.test.js new file mode 100644 index 0000000..c81a8c2 --- /dev/null +++ b/test/metrics.test.js @@ -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); + } +}); diff --git a/test/pairing.test.js b/test/pairing.test.js new file mode 100644 index 0000000..367ee31 --- /dev/null +++ b/test/pairing.test.js @@ -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]); +});