elorasmus/public/js/metrics.js
agent 226e5f46f8 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
2026-11-12 20:55:35 +00:00

249 lines
12 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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';
}