Files
patriothacks/src/lib/ceeiSpike.ts
T

314 lines
11 KiB
TypeScript

import solver, {
type Model,
type SolveResult,
} from "javascript-lp-solver";
/**
* CEEI validation spike (plan todo 13).
*
* This is a STANDALONE math/algorithm module with ZERO app/UI dependencies.
* It exists only to de-risk the Fair Share allocator's core math before the
* production engine (todo 14) is allowed to build on it: the CEEI
* (Competitive Equilibrium from Equal Incomes) allocation is the maximiser
* of the Eisenberg-Gale convex program, NOT a plain linear program, so we
* must prove a JS implementation actually reaches the known equilibrium
* before trusting it.
*
* Two approaches are implemented and cross-validated against a textbook
* closed-form instance:
*
* 1. PRIMARY - iterative price-search (tatonnement by bisection) over
* `javascript-lp-solver` linear programs. Prices are a vector; the last
* good is fixed as the numeraire (price 1) and the remaining good's
* price is bisected. At each price step every agent's linear (Fisher)
* demand is recomputed as an LP, and we check market clearing
* (aggregate demand == supply) to within a documented tolerance.
*
* 2. FALLBACK - a direct combinatorial water-filling / proportional-response
* algorithm specialised to the linear-utility case. Proportional response
* dynamics converge to the Fisher-market equilibrium for linear utilities
* and are used when the price-search fails to clear within the iteration
* cap (e.g. a degenerate instance whose aggregate-demand curve steps
* discontinuously across the clearing price, so scalar bisection can
* never land on exact equality).
*
* The module is deliberately scoped to the 2-good Fisher market the spike
* must validate; the price-search bisects the single free price coordinate.
* The water-filling fallback is written for arbitrary agents/goods.
*/
/** A Fisher-market / CEEI instance with linear utilities. */
export interface CeeiInstance {
/** `utilities[i][j]` = agent i's linear utility weight on good j (a_ij >= 0). */
utilities: number[][];
/** `budgets[i]` = agent i's money endowment b_i (equal for a CEEI instance). */
budgets: number[];
/** `supply[j]` = total available quantity of good j. */
supply: number[];
}
export interface PriceSearchOptions {
/**
* Hard cap on bisection iterations (plan mandates a fixed, documented
* bound). Defaults to 200.
*/
maxIterations?: number;
/**
* Market-clearing tolerance: the search converges once
* max_j |demand_j - supply_j| <= this value. Defaults to 1e-7, which drives
* the recovered prices/allocation to well within the 1e-6 closed-form
* assertion tolerance while staying above the LP solver's rounding floor.
*/
tolerance?: number;
/** Lower bracket for the free price coordinate. Defaults to 1e-6. */
priceLo?: number;
/** Upper bracket for the free price coordinate. Defaults to 1e6. */
priceHi?: number;
}
export interface PriceSearchResult {
converged: boolean;
/** Clearing prices, last good fixed at the numeraire value 1. */
prices: number[];
/** `allocation[i][j]` = agent i's demanded quantity of good j at `prices`. */
allocation: number[][];
/** Number of bisection steps actually taken (<= maxIterations). */
iterations: number;
/** Final max_j |demand_j - supply_j|. */
maxExcess: number;
}
export interface WaterFillingOptions {
/** Hard cap on proportional-response iterations. Defaults to 10000. */
maxIterations?: number;
/**
* Fixed-point tolerance: dynamics stop once no bid moves by more than this
* between iterations. Defaults to 1e-9.
*/
tolerance?: number;
}
export interface WaterFillingResult {
converged: boolean;
prices: number[];
allocation: number[][];
iterations: number;
}
export type CeeiApproach = "price-search" | "water-filling";
export interface CeeiSolution {
/** Which approach actually produced the returned solution. */
approach: CeeiApproach;
prices: number[];
allocation: number[][];
/** `utilities[i]` = agent i's realised linear utility under `allocation`. */
utilities: number[];
/** The price-search attempt (always run, kept for transparency/evidence). */
priceSearch: PriceSearchResult;
/** The water-filling attempt, present only when the fallback engaged. */
fallback?: WaterFillingResult;
}
/**
* Agent i's Fisher demand at the given prices: the bundle maximising the
* agent's linear utility subject to spending no more than its budget. Solved
* as an LP via `javascript-lp-solver`.
*/
function agentDemandLP(
util: number[],
budget: number,
prices: number[],
): number[] {
const variables: Record<string, Record<string, number>> = {};
util.forEach((coeff, j) => {
variables[`x${j}`] = { utility: coeff, budget: prices[j] };
});
const model: Model = {
optimize: "utility",
opType: "max",
constraints: { budget: { max: budget } },
variables,
};
const result = solver.Solve(model) as SolveResult;
return util.map((_, j) => {
const v = result[`x${j}`];
return typeof v === "number" ? v : 0;
});
}
function aggregateDemand(
instance: CeeiInstance,
prices: number[],
): { aggregate: number[]; allocation: number[][] } {
const aggregate = instance.supply.map(() => 0);
const allocation: number[][] = [];
instance.budgets.forEach((budget, i) => {
const demand = agentDemandLP(instance.utilities[i], budget, prices);
allocation.push(demand);
demand.forEach((q, j) => {
aggregate[j] += q;
});
});
return { aggregate, allocation };
}
/** Realised linear utility for each agent under a given allocation. */
export function computeUtilities(
instance: CeeiInstance,
allocation: number[][],
): number[] {
return instance.utilities.map((util, i) =>
util.reduce((sum, coeff, j) => sum + coeff * allocation[i][j], 0),
);
}
/**
* PRIMARY approach: iterative price-search by bisection.
*
* The last good is the numeraire (price fixed at 1). For a 2-good market this
* leaves exactly one free price coordinate, whose aggregate excess demand is
* monotonically decreasing, so plain bisection on the sign of that excess
* drives the market to clearing. Walras' law (every agent spends its full
* budget) means clearing the first good clears the numeraire too.
*/
export function solveCeeiPriceSearch(
instance: CeeiInstance,
options: PriceSearchOptions = {},
): PriceSearchResult {
if (instance.supply.length !== 2) {
throw new Error(
"solveCeeiPriceSearch is a 2-good spike: expected exactly 2 goods",
);
}
const maxIterations = options.maxIterations ?? 200;
const tolerance = options.tolerance ?? 1e-7;
let lo = options.priceLo ?? 1e-6;
let hi = options.priceHi ?? 1e6;
let iterations = 0;
let maxExcess = Infinity;
let prices: number[] = [1, 1];
let allocation: number[][] = [];
while (iterations < maxIterations) {
const freePrice = (lo + hi) / 2;
prices = [freePrice, 1];
const { aggregate, allocation: alloc } = aggregateDemand(instance, prices);
allocation = alloc;
iterations += 1;
maxExcess = Math.max(
...instance.supply.map((s, j) => Math.abs(aggregate[j] - s)),
);
if (maxExcess <= tolerance) {
return { converged: true, prices, allocation, iterations, maxExcess };
}
// Excess demand for good 0 is decreasing in its price: if demand still
// exceeds supply the price is too low (raise the floor), otherwise it is
// too high (lower the ceiling).
if (aggregate[0] - instance.supply[0] > 0) {
lo = freePrice;
} else {
hi = freePrice;
}
}
return { converged: false, prices, allocation, iterations, maxExcess };
}
/**
* FALLBACK approach: proportional-response (water-filling) dynamics for the
* linear-utility Fisher market.
*
* Each agent splits its budget into per-good bids. Prices are total bids per
* unit supply; each agent's allocation is its bid share of each good, so the
* market clears exactly by construction at every step. Bids are then
* reallocated toward the goods delivering the most utility per unit spent.
* This converges to the CEEI equilibrium for linear utilities and is robust
* to the degenerate instances that stall the scalar price-search.
*/
export function solveCeeiWaterFilling(
instance: CeeiInstance,
options: WaterFillingOptions = {},
): WaterFillingResult {
const maxIterations = options.maxIterations ?? 10000;
const tolerance = options.tolerance ?? 1e-9;
const nGoods = instance.supply.length;
// Start every agent with an even split of its budget across the goods.
let bids = instance.budgets.map((b) => Array<number>(nGoods).fill(b / nGoods));
let prices = Array<number>(nGoods).fill(0);
let allocation: number[][] = [];
let iterations = 0;
let converged = false;
while (iterations < maxIterations) {
prices = Array<number>(nGoods).fill(0);
for (const bid of bids) {
for (let j = 0; j < nGoods; j++) prices[j] += bid[j];
}
for (let j = 0; j < nGoods; j++) prices[j] /= instance.supply[j];
allocation = bids.map((bid) => bid.map((b, j) => b / prices[j]));
let delta = 0;
const nextBids = instance.budgets.map((budget, i) => {
const gains = allocation[i].map(
(q, j) => instance.utilities[i][j] * q,
);
const totalGain = gains.reduce((sum, g) => sum + g, 0);
return gains.map((g, j) => {
const nextBid =
totalGain === 0 ? budget / nGoods : budget * (g / totalGain);
delta = Math.max(delta, Math.abs(nextBid - bids[i][j]));
return nextBid;
});
});
bids = nextBids;
iterations += 1;
if (delta <= tolerance) {
converged = true;
break;
}
}
return { converged, prices, allocation, iterations };
}
/**
* Orchestrator: run the primary price-search first; if it fails to clear
* within its iteration cap, automatically engage the water-filling fallback.
* Reports which approach actually produced the answer.
*/
export function solveCeei(
instance: CeeiInstance,
options: {
priceSearch?: PriceSearchOptions;
waterFilling?: WaterFillingOptions;
} = {},
): CeeiSolution {
const priceSearch = solveCeeiPriceSearch(instance, options.priceSearch);
if (priceSearch.converged) {
return {
approach: "price-search",
prices: priceSearch.prices,
allocation: priceSearch.allocation,
utilities: computeUtilities(instance, priceSearch.allocation),
priceSearch,
};
}
const fallback = solveCeeiWaterFilling(instance, options.waterFilling);
return {
approach: "water-filling",
prices: fallback.prices,
allocation: fallback.allocation,
utilities: computeUtilities(instance, fallback.allocation),
priceSearch,
fallback,
};
}