// Pure scoring and comparison for /panoptiblog's compare dialog. Contributions // use the same weights as panoptiblog-rank.js's treeScore, so their sum is the // weighted score before warning penalties. const count = new Intl.NumberFormat("en"); function weightOf(value) { const number = Number(value); return Number.isFinite(number) && number > 0 ? number : 0; } function availableFactors(row, category) { return (category.factors ?? []).filter((factor) => { return weightOf(factor.weight) > 0 && Number.isFinite(row?.factors?.[factor.id]); }); } function percentile(value) { return typeof value === "number" && Number.isFinite(value) ? value : null; } function numberOrNull(value) { return typeof value === "number" && Number.isFinite(value) ? value : null; } function nameOf(entry) { return entry.name || entry.handle || entry.uri || "this publication"; } /** Every factor's share of the weighted score, before warning penalties. */ export function factorContributions(row, tree) { const categories = (tree ?? []) .map((category) => ({ category, factors: availableFactors(row, category) })) .filter((entry) => weightOf(entry.category.weight) > 0 && entry.factors.length > 0); const totalWeight = categories.reduce( (sum, entry) => sum + weightOf(entry.category.weight), 0, ); if (totalWeight === 0) return []; const contributions = []; for (const { category, factors } of categories) { const factorWeight = factors.reduce((sum, factor) => sum + weightOf(factor.weight), 0); if (factorWeight === 0) continue; const categoryShare = weightOf(category.weight) / totalWeight; for (const factor of factors) { contributions.push({ factorId: factor.id, categoryId: category.id, points: categoryShare * (weightOf(factor.weight) / factorWeight) * row.factors[factor.id], factor: factor.name ?? factor.id, category: category.name ?? category.id, }); } } return contributions; } /** Warning points, five per recorded reason. */ export function penaltyPoints(row) { return 5 * (Array.isArray(row?.spam?.reasons) ? row.spam.reasons.length : 0); } function hasFactors(row) { return Boolean(row?.factors) && typeof row.factors === "object" && Object.keys(row.factors).length > 0; } function rowSummary(row) { return { uri: String(row.uri ?? ""), name: typeof row.name === "string" ? row.name : "", handle: typeof row.handle === "string" ? row.handle : "", rank: numberOrNull(row.rank), score: numberOrNull(row.score), percentile: percentile(row.percentile), previousRank: numberOrNull(row.previousRank), wordCount: numberOrNull(row.wordCount) ?? 0, penalties: penaltyPoints(row), }; } function tieBreakOf(a, b) { const aWords = Number(a.wordCount) || 0; const bWords = Number(b.wordCount) || 0; if (aWords !== bWords) { return { winner: aWords > bWords ? "a" : "b", reason: "wordCount" }; } const aUri = String(a.uri ?? ""); const bUri = String(b.uri ?? ""); if (aUri !== bUri) { return { winner: aUri.localeCompare(bUri) <= 0 ? "a" : "b", reason: "uri" }; } return { winner: null, reason: "identical" }; } function tieBreakExplanation(comparison) { const { a, b } = comparison.summary; const { winner, reason } = comparison.tieBreak; const score = Number.isFinite(a.score) ? a.score.toFixed(1) : "the same score"; if (winner === null) { return `The scores are tied at ${score}, and the word counts and at-uris are also equal.`; } const winning = winner === "a" ? a : b; const losing = winner === "a" ? b : a; if (reason === "wordCount") { return `The scores are tied at ${score}, so rank goes to ${nameOf(winning)} on the higher word count (${count.format(winning.wordCount)} to ${count.format(losing.wordCount)}).`; } return `The scores and word counts are tied at ${score} and ${count.format(winning.wordCount)}, so at-uri order puts ${nameOf(winning)} first.`; } function strength(row) { const points = Number.isFinite(row.pointsDelta); const size = Math.abs(points ? row.pointsDelta : row.delta ?? 0); return { points, size }; } function byDifference(left, right) { const a = strength(left); const b = strength(right); if (a.points !== b.points) return a.points ? -1 : 1; return b.size - a.size; } function gap(left, right) { return Number.isFinite(left) && Number.isFinite(right) ? Math.abs(left - right) : null; } /** * Both rows against the same tree: summaries, composite rows, factor rows by * weighted difference, the top three drivers, penalties and the tie-break. */ export function comparePublications(a, b, tree) { const categories = Array.isArray(tree) ? tree : []; const aContributions = factorContributions(a, categories); const bContributions = factorContributions(b, categories); const usable = hasFactors(a) && hasFactors(b) && aContributions.length > 0 && bContributions.length > 0; const aSummary = rowSummary(a); const bSummary = rowSummary(b); const scored = Number.isFinite(aSummary.score) && Number.isFinite(bSummary.score); const tied = scored && aSummary.score === bSummary.score; let leader = null; if (scored) leader = aSummary.score > bSummary.score ? "a" : aSummary.score < bSummary.score ? "b" : null; const composites = categories.map((category) => { // The leaderboard's six cards show the raw composite score, not its // percentile. Use the same number here so the two views agree. const left = percentile(a.composites?.[category.id]?.raw); const right = percentile(b.composites?.[category.id]?.raw); return { id: category.id, name: category.name ?? category.id, a: left, b: right, delta: left !== null && right !== null ? left - right : null, aPercentile: percentile(a.composites?.[category.id]?.percentile), bPercentile: percentile(b.composites?.[category.id]?.percentile), }; }); const aById = new Map(aContributions.map((entry) => [entry.factorId, entry])); const bById = new Map(bContributions.map((entry) => [entry.factorId, entry])); const factors = []; for (const category of categories) { for (const factor of category.factors ?? []) { const left = aById.get(factor.id); const right = bById.get(factor.id); if (!left && !right) continue; const aPercentile = percentile(a.factors?.[factor.id]); const bPercentile = percentile(b.factors?.[factor.id]); factors.push({ factorId: factor.id, categoryId: category.id, category: category.name ?? category.id, factor: factor.name ?? factor.id, aPercentile, bPercentile, delta: aPercentile !== null && bPercentile !== null ? aPercentile - bPercentile : null, aPoints: left?.points ?? null, bPoints: right?.points ?? null, pointsDelta: left && right ? left.points - right.points : null, }); } } factors.sort(byDifference); const comparison = { usable, summary: { a: aSummary, b: bSummary, rankGap: gap(aSummary.rank, bSummary.rank), scoreGap: gap(aSummary.score, bSummary.score), tied, leader, }, composites, factors, topFactors: factors .filter((factor) => Number.isFinite(factor.pointsDelta) && Math.abs(factor.pointsDelta) >= 0.05) .slice(0, 3), penalty: { a: aSummary.penalties, b: bSummary.penalties, delta: aSummary.penalties - bSummary.penalties, }, tieBreak: { tied, winner: null, reason: null, explanation: null }, }; if (tied) { const result = tieBreakOf(aSummary, bSummary); comparison.summary.leader = result.winner; comparison.tieBreak = { tied, ...result, explanation: null }; comparison.tieBreak.explanation = tieBreakExplanation(comparison); } return comparison; } /** * A short plain-text explanation of the comparison. The dialog's lead line * already states who leads and by how much, so a decided comparison starts * with the factor differences. */ export function explainComparison(comparison, tree) { if (!comparison?.usable) { return "There is not enough factor data to compare these publications."; } const { summary } = comparison; const { a, b } = summary; if (!summary.tied && summary.leader === null) { return "These publications do not have comparable scores."; } const sentences = []; if (summary.tied) { sentences.push(comparison.tieBreak?.explanation ?? `The scores are tied at ${a.score.toFixed(1)}.`); } const top = comparison.topFactors ?? []; if (top.length > 0) { const parts = top.map((factor) => { const winning = factor.pointsDelta > 0 ? a : b; return `${factor.factor} (${nameOf(winning)} +${Math.abs(factor.pointsDelta).toFixed(1)} points)`; }); const list = parts.length === 1 ? parts[0] : parts.length === 2 ? `${parts[0]} and ${parts[1]}` : `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}`; sentences.push(`The largest weighted factor differences are ${list}.`); } if (Number.isFinite(comparison.penalty?.delta) && comparison.penalty.delta !== 0) { const moreA = comparison.penalty.delta > 0; const more = moreA ? a : b; const reasons = (moreA ? comparison.penalty.a : comparison.penalty.b) / 5; sentences.push( `${nameOf(more)} also loses ${Math.abs(comparison.penalty.delta).toFixed(1)} more points to ${reasons} warning${reasons === 1 ? "" : "s"}.`, ); } return sentences.slice(0, 4).join(" "); }