ecclesia
Version:
Framework for political and electoral simulations
459 lines (444 loc) • 16.3 kB
JavaScript
;
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/election/attribution.ts
var attribution_exports = {};
__export(attribution_exports, {
AttributionFailure: () => AttributionFailure,
addThresholdToSimpleAttribution: () => addThresholdToSimpleAttribution,
averageScore: () => averageScore,
bordaCount: () => bordaCount,
boundedRankIndexMethod: () => boundedRankIndexMethod,
condorcet: () => condorcet,
dHondt: () => dHondt,
hamilton: () => hamilton,
hareLargestRemainders: () => hareLargestRemainders,
highestAverages: () => highestAverages,
huntingtonHill: () => huntingtonHill,
instantRunoff: () => instantRunoff,
jefferson: () => jefferson,
largestRemainders: () => largestRemainders,
medianScore: () => medianScore,
plurality: () => plurality,
proportionalFromDivisorFunction: () => proportionalFromDivisorFunction,
proportionalFromRankIndexFunction: () => proportionalFromRankIndexFunction,
randomize: () => randomize,
rankIndexFunctionFromDivisorFunction: () => rankIndexFunctionFromDivisorFunction,
sainteLague: () => sainteLague,
superMajority: () => superMajority,
webster: () => webster
});
module.exports = __toCommonJS(attribution_exports);
// src/election/attribution/base.ts
var AttributionFailure = class extends Error {
};
// src/election/attribution/transform.ts
var import_collections = require("@gouvernathor/python/collections");
function addThresholdToSimpleAttribution({ threshold, attribution, contingency = attribution }) {
const attrib = (votes, rest = {}) => {
if (threshold > 0) {
const original_votes = votes;
const votes_threshold = threshold * votes.total;
votes = new import_collections.Counter([...votes.entries()].filter(([_, v]) => v >= votes_threshold));
if (votes.size === 0) {
if (contingency === null) {
throw new AttributionFailure("No party reached the threshold");
}
return contingency(original_votes, rest);
}
}
return attribution(votes, rest);
};
return attrib;
}
// src/election/attribution/proportionalBase.ts
var import_collections2 = require("@gouvernathor/python/collections");
// src/election/attribution/metrics.ts
function defaultMetric({ votes, seats }) {
const allVotes = votes.total;
const allSeats = seats.total;
let suum = 0;
for (const party of seats.keys()) {
const partyVotes = votes.get(party);
const partySeats = seats.get(party);
suum += Math.abs(allSeats * partyVotes / allVotes - partySeats);
}
return suum / seats.size;
}
// src/election/attribution/proportionalBase.ts
function proportionalFromRankIndexFunction({ nSeats, rankIndexFunction }) {
const attrib = (votes, rest = {}) => {
const allVotes = votes.total;
const fractions = new Map([...votes.entries()].map(([party, v]) => [party, v / allVotes]));
const rankIndexValues = new Map([...fractions.entries()].map(([party, f]) => [party, rankIndexFunction(f, 0)]));
const parties = [...votes.keys()].sort((a, b) => rankIndexValues.get(a) - rankIndexValues.get(b));
const seats = new import_collections2.Counter();
s: for (let sn = 0; sn < nSeats; sn++) {
const winner = parties.pop();
seats.increment(winner);
rankIndexValues.set(winner, rankIndexFunction(fractions.get(winner), seats.get(winner)));
for (let pn = 0; pn < parties.length; pn++) {
if (rankIndexValues.get(parties[pn]) >= rankIndexValues.get(winner)) {
parties.splice(pn, 0, winner);
continue s;
}
}
parties.push(winner);
}
return seats;
};
attrib.nSeats = nSeats;
return attrib;
}
function boundedRankIndexMethod({ minNSeats, maxNSeats, rankIndexFunction, metric = defaultMetric }) {
const attrib = (votes, rest = {}) => {
const allVotes = votes.total;
const fractions = new Map([...votes.entries()].map(([party, v]) => [party, v / allVotes]));
const rankIndexValues = new Map([...fractions.entries()].map(([party, f]) => [party, rankIndexFunction(f, 0)]));
const parties = [...votes.keys()].sort((a, b) => rankIndexValues.get(a) - rankIndexValues.get(b));
const seats = new import_collections2.Counter();
let bestSeats = seats.pos;
let bestSeatsMetric = Infinity;
s: for (let sn = 1; sn <= maxNSeats; sn++) {
const winner = parties.pop();
seats.increment(winner);
if (sn >= minNSeats) {
const newMetric = metric({ votes, seats });
if (newMetric < bestSeatsMetric) {
bestSeats = seats.pos;
bestSeatsMetric = newMetric;
}
}
rankIndexValues.set(winner, rankIndexFunction(fractions.get(winner), seats.get(winner)));
for (let pn = 0; pn < parties.length; pn++) {
if (rankIndexValues.get(parties[pn]) >= rankIndexValues.get(winner)) {
parties.splice(pn, 0, winner);
continue s;
}
}
parties.push(winner);
}
return bestSeats;
};
attrib.minNSeats = minNSeats;
attrib.maxNSeats = maxNSeats;
return attrib;
}
function stationaryDivisorFunction(r) {
return (k) => k + r;
}
function rankIndexFunctionFromDivisorFunction(divisorFunction) {
return (t, a) => t / divisorFunction(a);
}
function proportionalFromDivisorFunction({ nSeats, divisorFunction }) {
return proportionalFromRankIndexFunction({
nSeats,
rankIndexFunction: rankIndexFunctionFromDivisorFunction(divisorFunction)
});
}
// src/election/attribution/majorityFactory.ts
var import_python = require("@gouvernathor/python");
var import_collections3 = require("@gouvernathor/python/collections");
function plurality({ nSeats }) {
const attrib = (votes, rest = {}) => {
const win = (0, import_python.max)(votes.keys(), (p) => votes.get(p));
if (votes.get(win) > 0) {
return new import_collections3.Counter([[win, nSeats]]);
}
throw new AttributionFailure("No party won any vote");
};
attrib.nSeats = nSeats;
return attrib;
}
function superMajority({ nSeats, threshold, contingency = null }) {
const attrib = (votes, rest = {}) => {
const win = (0, import_python.max)(votes.keys(), (p) => votes.get(p));
if (votes.get(win) / votes.total > threshold) {
return new import_collections3.Counter([[win, nSeats]]);
}
if (contingency === null) {
throw new AttributionFailure("No party reached the threshold");
}
return contingency(votes, rest);
};
attrib.nSeats = nSeats;
return attrib;
}
// src/election/attribution/orderingFactory.ts
var import_python2 = require("@gouvernathor/python");
var import_collections4 = require("@gouvernathor/python/collections");
function instantRunoff({ nSeats }) {
const attrib = (votes, rest = {}) => {
const blacklisted = /* @__PURE__ */ new Set();
const nParties = new Set(votes.flat()).size;
for (let pn = 0; pn < nParties; pn++) {
const firstPlaces = new import_collections4.Counter();
for (const ballot of votes) {
for (const party of ballot) {
if (!blacklisted.has(party)) {
firstPlaces.increment(party);
break;
}
}
}
const total = firstPlaces.total;
for (const [party, score] of firstPlaces) {
if (score / total > 0.5) {
return new import_collections4.Counter([[party, nSeats]]);
}
}
blacklisted.add((0, import_python2.min)(firstPlaces.keys(), (p) => firstPlaces.get(p)));
}
throw new Error("Should not happen");
};
attrib.nSeats = nSeats;
return attrib;
}
function bordaCount({ nSeats }) {
const attrib = (votes, rest = {}) => {
const scores = new import_collections4.Counter();
for (const ballot of votes) {
for (const [i, party] of (0, import_python2.enumerate)(ballot.slice().reverse(), 1)) {
scores.increment(party, i);
}
}
return new import_collections4.Counter([[(0, import_python2.max)(scores.keys(), (p) => scores.get(p)), nSeats]]);
};
attrib.nSeats = nSeats;
return attrib;
}
function condorcet({ nSeats, contingency = null }) {
const attrib = (votes, rest = {}) => {
const counts = new import_collections4.DefaultMap(() => new import_collections4.Counter());
const majority = votes.length / 2;
for (const ballot of votes) {
for (const [i, party1] of (0, import_python2.enumerate)(ballot)) {
for (const party2 of ballot.slice(i + 1)) {
counts.get(party1).increment(party2);
}
}
}
const win = new Set(counts.keys());
for (const [party, partyCounter] of counts) {
for (const value of partyCounter.pos.values()) {
if (value > majority) {
win.delete(party);
break;
}
}
}
if (win.size !== 1) {
if (win.size !== 0) {
throw new Error("Bad attribution");
}
if (contingency === null) {
throw new condorcet.Standoff("No Condorcet winner");
}
return contingency(votes, rest);
}
const [winner] = win;
return new import_collections4.Counter([[winner, nSeats]]);
};
attrib.nSeats = nSeats;
return attrib;
}
condorcet.Standoff = class CondorcetStandoff extends AttributionFailure {
};
// src/election/attribution/scoreFactory.ts
var import_python3 = require("@gouvernathor/python");
var import_collections5 = require("@gouvernathor/python/collections");
var import_statistics = require("@gouvernathor/python/statistics");
// src/election/ballots.ts
var Scores;
((Scores2) => {
function get(key) {
const value = this.get(key);
if (value === void 0) {
return Array(this.ngrades).fill(0);
}
return value;
}
function fromEntries(elements) {
if (elements.length === 0) {
throw new Error("Use the fromGrades method to create an empty Scores instance");
}
const ths = new Map(elements);
ths.ngrades = elements[0][1].length;
ths.get = get.bind(ths);
return ths;
}
Scores2.fromEntries = fromEntries;
function fromGrades(ngrades) {
const ths = /* @__PURE__ */ new Map();
ths.ngrades = ngrades;
ths.get = get.bind(ths);
return ths;
}
Scores2.fromGrades = fromGrades;
})(Scores || (Scores = {}));
// src/election/attribution/scoreFactory.ts
function averageScore({ nSeats }) {
const attrib = (votes, rest = {}) => {
const counts = new import_collections5.DefaultMap(() => []);
for (const [party, grades] of votes) {
for (const [grade, qty] of (0, import_python3.enumerate)(grades)) {
counts.get(party).push(...Array(qty).fill(grade));
}
}
return new import_collections5.Counter([[(0, import_python3.max)(counts.keys(), (party) => (0, import_statistics.fmean)(counts.get(party))), nSeats]]);
};
attrib.nSeats = nSeats;
return attrib;
}
function medianScore({ nSeats, contingency }) {
if (contingency === void 0) {
contingency = averageScore({ nSeats });
}
const attrib = (votes, rest = {}) => {
const counts = new import_collections5.DefaultMap(() => []);
for (const [party, grades] of votes) {
for (const [grade, qty] of (0, import_python3.enumerate)(grades)) {
counts.get(party).push(...Array(qty).fill(grade));
}
}
const medians = new Map([...counts.entries()].map(([party, partigrades]) => [party, (0, import_statistics.median)(partigrades)]));
const winScore = Math.max(...medians.values());
const [winner, ...winners] = [...medians.keys()].filter((p) => medians.get(p) === winScore);
if (winners.length === 0) {
return new import_collections5.Counter([[winner, nSeats]]);
}
winners.unshift(winner);
const trimmedResults = Scores.fromEntries(winners.map((party) => [party, counts.get(party)]));
return contingency(trimmedResults, rest);
};
attrib.nSeats = nSeats;
return attrib;
}
// src/election/attribution/proportionalFactory.ts
var import_python4 = require("@gouvernathor/python");
var import_collections6 = require("@gouvernathor/python/collections");
var divisor1 = stationaryDivisorFunction(1);
function jefferson({ nSeats }) {
return proportionalFromDivisorFunction({
nSeats,
divisorFunction: divisor1
});
}
var dHondt = jefferson;
var divisorPoint5 = (k) => 2 * k + 1;
function webster({ nSeats }) {
return proportionalFromDivisorFunction({
nSeats,
divisorFunction: divisorPoint5
});
}
var sainteLague = webster;
function hamilton({ nSeats }) {
const attrib = (votes, rest = {}) => {
const seats = new import_collections6.Counter();
const remainders = /* @__PURE__ */ new Map();
const sumVotes = votes.total;
for (const [party, scores] of votes) {
const [i, r] = (0, import_python4.divmod)(scores * nSeats, sumVotes);
seats.set(party, i);
remainders.set(party, r);
}
seats.update([...remainders.keys()].sort((a, b) => remainders.get(b) - remainders.get(a)).slice(0, nSeats - seats.total));
return seats;
};
attrib.nSeats = nSeats;
return attrib;
}
var hareLargestRemainders = hamilton;
var huntingtonHillBaseRankIndexFunction = rankIndexFunctionFromDivisorFunction((k) => Math.sqrt(k * (k + 1)));
var huntingtonHillRankIndexFunction = (t, a) => {
if (a <= 0) {
return Infinity;
}
return huntingtonHillBaseRankIndexFunction(t, a);
};
function huntingtonHill({ nSeats, threshold, contingency = null }) {
const attrib = addThresholdToSimpleAttribution({
threshold,
contingency,
attribution: proportionalFromRankIndexFunction({
nSeats,
rankIndexFunction: huntingtonHillRankIndexFunction
})
});
attrib.nSeats = nSeats;
return attrib;
}
var highestAverages = webster;
var largestRemainders = hamilton;
// src/election/attribution/randomFactory.ts
var import_collections7 = require("@gouvernathor/python/collections");
// src/utils.ts
var import_rng = __toESM(require("@gouvernathor/rng"), 1);
function createRandomObj({ randomObj, randomSeed } = {}) {
if (randomObj === void 0) {
randomObj = new import_rng.default(randomSeed);
}
return randomObj;
}
// src/election/attribution/randomFactory.ts
function randomize({ nSeats, ...randomParam }) {
const attrib = (votes, rest = {}) => {
const randomObj = createRandomObj(randomParam);
return new import_collections7.Counter(randomObj.choices([...votes.keys()], { weights: [...votes.values()], k: nSeats }));
};
attrib.nSeats = nSeats;
return attrib;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
AttributionFailure,
addThresholdToSimpleAttribution,
averageScore,
bordaCount,
boundedRankIndexMethod,
condorcet,
dHondt,
hamilton,
hareLargestRemainders,
highestAverages,
huntingtonHill,
instantRunoff,
jefferson,
largestRemainders,
medianScore,
plurality,
proportionalFromDivisorFunction,
proportionalFromRankIndexFunction,
randomize,
rankIndexFunctionFromDivisorFunction,
sainteLague,
superMajority,
webster
});
//# sourceMappingURL=attribution.cjs.map