Route model: first attempts are their own shadow roll; experiment plan and automated bot cycle
- game.yaml: `givens` (first or later attempt) and `distinct` levels that are not pooled; the shadow roll
depends on the attempt first. Form submissions show the shadow on 9% of first attempts and 0.3% of later ones.
- Reporting bias: a roll whose bias cannot be measured can borrow another roll's (`borrow: {shadow: meadow}`),
so form submissions inform the shadow again. An assumption, stated in planner/policy.yaml.
- policy.json: targets.<colour>.firstAttempt (this attempt, eventually). Black: about 1.4% on a first attempt,
0.07% on a later one.
- solver.js: advisor options `attempt`, `fix`, sampling "uniform"; assign() and armFor() for the plan.
- planner/experiments.yaml + build_experiments.py -> data/public/experiments.json (progress and status per
experiment, rebuilt from the bot's runs).
- python -m collection cycle: import bot runs, refit, re-plan, deliver the kit; .gitea/workflows/bot-cycle.yml.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014jqCC2LZ4x1WHQ1V57nTsv
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
ee07ee143e
commit
ab3664f369
+100
-14
@@ -11,6 +11,9 @@
|
||||
*
|
||||
* Public API (unchanged for the bot): advisor(sample, colour, objective, { only }), recommendOption(adv, h, texts),
|
||||
* solverHistory(formVars, seen), makeParams(tables, { alphas, game }), ENCOUNTERS (set from the first sample).
|
||||
* Since November 2026: advisor options `attempt` (the account's attempt number: a first attempt has its own
|
||||
* shadow odds), `fix` (hold some decisions to given options: an experiment arm) and sampling "uniform" (mapping);
|
||||
* assign(plan, { accountSeq, attempt }) reads the experiment plan (experiments.json) and says what an attempt is for.
|
||||
* UMD: window.ThreshSolver in the browser, module.exports in Node. No dependencies.
|
||||
*/
|
||||
(function (root, factory) {
|
||||
@@ -48,22 +51,31 @@
|
||||
}
|
||||
|
||||
/* ---------- the odds: posterior means (or, with rand, one posterior draw) with hierarchical back-off ---------- */
|
||||
function makeParams(T, { alphas = {}, game, rand = null }) {
|
||||
/** The givens of a run (game.yaml `givens`): the defaults, with `attempt` set from an attempt number or name. */
|
||||
function givenFor(game, { attempt = null, given = null } = {}) {
|
||||
const g = Object.fromEntries(Object.entries(game.givens || {}).map(([k, v]) => [k, v.default]));
|
||||
if (attempt != null && game.givens && game.givens.attempt) g.attempt = attempt === 1 || attempt === "1" || attempt === "First attempt" ? "First attempt" : "Later attempt";
|
||||
return { ...g, ...(given || {}) };
|
||||
}
|
||||
// given: the run's givens; memo: pass the same Map to get the same posterior draw for another given
|
||||
function makeParams(T, { alphas = {}, game, rand = null, given = null, memo = new Map() }) {
|
||||
const normalise = (a) => { let sum = 0; for (const x of a) sum += x; return a.map((x) => x / sum); };
|
||||
const estimate = rand ? (a) => dirichlet(a, rand) : normalise;
|
||||
const memo = new Map();
|
||||
const known = given || givenFor(game);
|
||||
const ctxKey = (s, names) => names.map((k) => (s[k] == null ? "?" : s[k])).join("|");
|
||||
function chance(node, state) {
|
||||
function chance(node, walked) {
|
||||
const sp = game.chance[node], cats = sp.outcomes;
|
||||
// a closed gate (game.yaml `requires`): the roll always comes out as `otherwise`
|
||||
if (sp.requires && Object.entries(sp.requires).some(([k, v]) => state[k] !== v)) return Object.fromEntries(cats.map((k) => [k, k === sp.otherwise ? 1 : 0]));
|
||||
if (sp.requires && Object.entries(sp.requires).some(([k, v]) => walked[k] !== v)) return Object.fromEntries(cats.map((k) => [k, k === sp.otherwise ? 1 : 0]));
|
||||
const state = { ...known, ...walked };
|
||||
let p = null;
|
||||
for (let L = 0; L <= sp.context.length; L++) {
|
||||
const names = sp.context.slice(0, L);
|
||||
if (names.some((k) => state[k] == null)) break;
|
||||
const key = L + ":" + ctxKey(state, names), mk = node + "#" + key;
|
||||
if (memo.has(mk)) { p = memo.get(mk); continue; }
|
||||
const c = T[node][key] || {}, al = alphas[node] || ALPHA;
|
||||
// a level that is not pooled (game.yaml `distinct`) keeps a token prior of one run
|
||||
const c = T[node][key] || {}, al = L <= (sp.distinct || 0) ? 1 : alphas[node] || ALPHA;
|
||||
const a = cats.map((k, i) => (c[k] || 0) + (p ? al * p[i] : 0.5));
|
||||
p = estimate(a);
|
||||
memo.set(mk, p);
|
||||
@@ -174,22 +186,50 @@
|
||||
* the deadly roll just passed on the step after it. When h already has a later step but skips an earlier
|
||||
* decision (an older form record, say), the recommended option is assumed for the skipped one.
|
||||
*/
|
||||
function advisor(sample, X, objective = "eventually", { only = null, sampling = "best", seed = 1, draws = 40 } = {}) {
|
||||
function advisor(sample, X, objective = "eventually", { only = null, sampling = "best", seed = 1, draws = 40, attempt = null, given = null, fix = null } = {}) {
|
||||
const m = sample.model, game = m.game;
|
||||
api.game = game; api.ENCOUNTERS = game.by_colour;
|
||||
const solveWith = (params) => (objective === "eventually" ? solveRatio(params, game, m.support, X, only) : solve(params, game, m.support, X, 0, only));
|
||||
// attempt: the account's attempt number (or "First attempt" / "Later attempt"). A first attempt has its own odds
|
||||
// for the rolls that depend on it (the shadow); without it, a later attempt is assumed.
|
||||
const defaults = givenFor(game), known = givenFor(game, { attempt, given });
|
||||
const special = Object.keys(known).some((k) => known[k] !== defaults[k]);
|
||||
// "uniform" (mapping) may take any option the game has, so it is solved without the minimum-support rule
|
||||
const all = Object.fromEntries(Object.entries(game.decisions).map(([k, d]) => [k, d.options]));
|
||||
const base = sampling === "uniform" ? { ...all, encounter: m.support.encounter } : m.support;
|
||||
// fix: { decision: option } holds those decisions to one option (an experiment arm); the rest is solved around it
|
||||
let support = base;
|
||||
if (fix) {
|
||||
support = { ...base };
|
||||
for (const [k, o] of Object.entries(fix)) {
|
||||
if (!game.decisions[k] || !game.decisions[k].options.includes(o)) throw new Error(`fix: ${k} has no option "${o}"`);
|
||||
support[k] = [o];
|
||||
if (game.decisions[k].support_by) for (const key of Object.keys(support)) if (key.startsWith(k + ":")) support[key] = [o];
|
||||
}
|
||||
}
|
||||
// One world (the posterior means, or one draw): the odds for this run's givens, solved for the objective.
|
||||
// "Eventually" on a first attempt: every later attempt is an ordinary one, worth its own ratio (lam), so the
|
||||
// best play now maximises P(X now) + P(no bond now) * lam: the same score with lam fixed.
|
||||
const solveWith = (rand) => {
|
||||
const memo = new Map();
|
||||
const mk = (g) => makeParams(m.tables, { alphas: m.alphas, game, rand, given: g, memo });
|
||||
if (objective !== "eventually") { const params = mk(known); return { params, sol: solve(params, game, support, X, 0, only) }; }
|
||||
if (!special) { const params = mk(known); return { params, sol: solveRatio(params, game, support, X, only) }; }
|
||||
const lam = solveRatio(mk(defaults), game, base, X, only).lam;
|
||||
const params = mk(known);
|
||||
return { params, sol: { ...solve(params, game, support, X, lam, only), lam } };
|
||||
};
|
||||
// "best": the best route under the posterior means. "thompson": the best route of one posterior draw of the odds
|
||||
// (one per attempt: make a new advisor with a new seed for each attempt), so every option is tried about as
|
||||
// often as it is likely to be the best one; as the data firm up, sampling settles on the best route.
|
||||
// "uniform": every option on the screen is equally likely (recommendOption picks; see there).
|
||||
const thompson = sampling === "thompson";
|
||||
const params = makeParams(m.tables, { alphas: m.alphas, game, rand: thompson ? rng(seed) : null });
|
||||
const sol = solveWith(params);
|
||||
const { params, sol } = solveWith(thompson ? rng(seed) : null);
|
||||
// the chance Thompson sampling picks each option at a history, estimated from `draws` other draws: the
|
||||
// propensity to log, so the runs can be re-weighted later
|
||||
let worlds = null;
|
||||
const propensityAt = (key, choice) => {
|
||||
if (!thompson) return 1;
|
||||
if (!worlds) worlds = Array.from({ length: draws }, (_, i) => solveWith(makeParams(m.tables, { alphas: m.alphas, game, rand: rng(seed * 7919 + i + 1) })).choices);
|
||||
if (!worlds) worlds = Array.from({ length: draws }, (_, i) => solveWith(rng(seed * 7919 + i + 1)).sol.choices);
|
||||
return worlds.filter((c) => c.get(key) === choice).length / draws;
|
||||
};
|
||||
const VARS = new Set([...Object.keys(game.decisions), ...Object.keys(game.chance), "encounter"]);
|
||||
@@ -236,7 +276,7 @@
|
||||
throw new Error("the game has no end");
|
||||
}
|
||||
return {
|
||||
colour: X, objective, only, sampling, seed: thompson ? seed : null, value: sol.value, step, params, game,
|
||||
colour: X, objective, only, sampling, seed: sampling === "best" ? null : seed, given: known, fix, value: sol.value, step, params, game,
|
||||
/** attempts recorded at an encounter (genuine attempts only), to show how much data a bond chance rests on */
|
||||
attempts: (ctx) => Object.values(((m.tables.encounter || {})[ctx] || { outcomes: {} }).outcomes).reduce((a, b) => a + b, 0),
|
||||
/** the next decision only (null when the next step is a roll or the run is over) */
|
||||
@@ -258,8 +298,18 @@
|
||||
function recommendOption(adv, h, offered) {
|
||||
const rec = adv.next(h);
|
||||
if (!rec) return null;
|
||||
const pat = ((adv.game.bot_text || {})[rec.decision] || {})[rec.choice];
|
||||
const idx = pat ? offered.map(norm).findIndex((t) => new RegExp(pat).test(t)) : -1;
|
||||
const texts = offered.map(norm), pats = (adv.game.bot_text || {})[rec.decision] || {};
|
||||
// mapping (sampling "uniform"): every option on the screen that the game knows is equally likely, except a
|
||||
// decision held by `fix` and the bonding encounter (where the advisor's own choice stands)
|
||||
if (adv.sampling === "uniform" && rec.decision !== "encounter" && !(adv.fix && adv.fix[rec.decision])) {
|
||||
const on = Object.keys(rec.options).map((o) => [o, pats[o] ? texts.findIndex((t) => new RegExp(pats[o]).test(t)) : -1]).filter(([, i]) => i >= 0);
|
||||
if (on.length) {
|
||||
const [o, i] = on[Math.floor(rng(hash(`${adv.seed}|${rec.decision}|${canon(h)}`))() * on.length)];
|
||||
return { index: i, decision: rec.decision, choice: o, propensity: 1 / on.length, margin: null, options: rec.options, reason: `${rec.label}: ${o} (mapping: 1 of ${on.length} at random)` };
|
||||
}
|
||||
}
|
||||
const pat = pats[rec.choice];
|
||||
const idx = pat ? texts.findIndex((t) => new RegExp(pat).test(t)) : -1;
|
||||
const values = Object.values(rec.options).map((v) => v.pX).sort((a, b) => b - a);
|
||||
return { index: idx < 0 ? null : idx, decision: rec.decision, choice: rec.choice, propensity: rec.propensity,
|
||||
margin: values.length > 1 ? values[0] - values[1] : null,
|
||||
@@ -302,8 +352,44 @@
|
||||
return h;
|
||||
}
|
||||
|
||||
/* ---------- the experiment plan (planner/experiments.yaml, published as experiments.json) ---------- */
|
||||
function hash(s) { let x = 2166136261; for (const ch of String(s)) { x ^= ch.codePointAt(0); x = Math.imul(x, 16777619) >>> 0; } return x || 1; }
|
||||
/** The arm of the n-th unit (0-based) of an experiment: balanced blocks, each block a seeded shuffle of the arms. */
|
||||
function armFor(experiment, n) {
|
||||
const arms = experiment.arms, k = arms.length, rand = rng(hash(`${experiment.id}|${experiment.seed || 0}|${Math.floor(n / k)}`));
|
||||
const order = arms.map((_, i) => i);
|
||||
for (let i = k - 1; i > 0; i--) { const j = Math.floor(rand() * (i + 1)); [order[i], order[j]] = [order[j], order[i]]; }
|
||||
return arms[order[n % k]];
|
||||
}
|
||||
/**
|
||||
* What an attempt is for, under the plan: assign(plan, { accountSeq, attempt }) ->
|
||||
* { experimentId, arm, fix, target, objective, sampling, seed, propensity, burn, planId }, or null when no
|
||||
* experiment covers the attempt (use the account's own goal).
|
||||
* accountSeq: the account's number in the order the accounts were made (0, 1, 2, ...), the same for its whole
|
||||
* life; attempt: the account's attempt number (1 = its first threshing). The answer is the same every time for
|
||||
* the same plan id, so a restart mid-attempt changes nothing. Pass the result to advisor():
|
||||
* advisor(policy.samples.all, a.target, a.objective, { attempt, fix: a.fix, sampling: a.sampling, seed: a.seed })
|
||||
* and log experimentId, arm, planId and the propensity on the run.
|
||||
*/
|
||||
function assign(plan, { accountSeq, attempt }) {
|
||||
let open = (plan.experiments || []).filter((e) => e.status === "running" && attempt >= e.attempts.from && (e.attempts.to == null || attempt <= e.attempts.to)
|
||||
&& (!e.accounts || (accountSeq % e.accounts.every) < e.accounts.take));
|
||||
if (!open.length) return null;
|
||||
if (open.some((e) => e.exclusive)) open = open.filter((e) => e.exclusive); // an exclusive experiment takes its attempts whole
|
||||
const total = open.reduce((s, e) => s + e.share, 0);
|
||||
let u = rng(hash(`${plan.seed || 0}|${accountSeq}|${attempt}`))() * total, exp = open[open.length - 1];
|
||||
for (const e of open) { if (u < e.share) { exp = e; break; } u -= e.share; }
|
||||
// the unit that is randomised: the account (one arm for life) or the attempt (blocks within the account)
|
||||
// (accounts are counted among those the experiment takes, so its blocks stay balanced)
|
||||
const nth = exp.accounts ? Math.floor(accountSeq / exp.accounts.every) * exp.accounts.take + (accountSeq % exp.accounts.every) : accountSeq;
|
||||
const arm = exp.unit === "account" ? armFor(exp, nth) : armFor({ ...exp, seed: `${exp.seed || 0}|${accountSeq}` }, attempt - exp.attempts.from);
|
||||
return { experimentId: exp.id, arm: arm.id, fix: arm.fix || null, target: exp.target, objective: exp.objective || "eventually",
|
||||
sampling: exp.sampling || "best", seed: hash(`${plan.seed || 0}|${exp.id}|${accountSeq}|${attempt}`),
|
||||
propensity: (exp.share / total) / exp.arms.length, burn: exp.burn || null, planId: plan.id };
|
||||
}
|
||||
|
||||
return Object.assign(api, {
|
||||
advisor, recommendOption, solverHistory, norm,
|
||||
advisor, recommendOption, solverHistory, norm, assign, armFor, givenFor,
|
||||
makeParams: (T, { alphas, game } = {}) => makeParams(T, { alphas, game: game || api.game }),
|
||||
/** remember the game of a policy sample (sets ENCOUNTERS) without solving anything */
|
||||
useGame(sample) { api.game = sample.model.game; api.ENCOUNTERS = api.game.by_colour; return api.game; },
|
||||
|
||||
Reference in New Issue
Block a user