{"version":3,"sources":["../src/index.ts","../src/types.ts","../src/utils/make-matrix.ts","../src/utils/scores.ts","../src/classes/method.ts","../src/classes/score-method.ts","../src/classes/ballot-score-method.ts","../src/utils/normalize.ts","../src/utils/scores-zero.ts","../src/methods/first-past-the-post/iterate-first-choices.ts","../src/methods/first-past-the-post/index.ts","../src/methods/absolute-majority/index.ts","../src/methods/approbation/index.ts","../src/methods/baldwin/index.ts","../src/utils/array-at.ts","../src/classes/ballot-method.ts","../src/classes/round-ballot-method.ts","../src/methods/borda/index.ts","../src/methods/bottom-two-runoff/index.ts","../src/methods/biggest-support/index.ts","../src/methods/copeland/index.ts","../src/classes/matrix-score-method.ts","../src/methods/coombs/index.ts","../src/utils/index.ts","../src/methods/ranked-pairs/generate-acyclic-graph.ts","../src/methods/ranked-pairs/vertex-stack.ts","../src/methods/ranked-pairs/tarjan.ts","../src/methods/ranked-pairs/vertex.ts","../src/utils/condorcet.ts","../src/methods/instant-runoff/index.ts","../src/methods/kemeny/index.ts","../src/methods/majority-judgment/index.ts","../src/methods/maximal-lotteries/index.ts","../src/classes/random-matrix-method.ts","../src/utils/shuffle-array.ts","../src/classes/random-method.ts","../src/simplex/find-nash-equilibrium.ts","../src/methods/minimax/index.ts","../src/methods/minimax-td/index.ts","../src/methods/nanson/index.ts","../src/methods/random-candidates/index.ts","../src/classes/random-ballot-method.ts","../src/methods/random-dictator/index.ts","../src/methods/randomized-condorcet/index.ts","../src/methods/ranked-pairs/index.ts","../src/methods/schulze/index.ts","../src/methods/smith/index.ts","../src/methods/two-round-runoff/index.ts","../src/methods/index.ts","../src/utils/categories.ts"],"sourcesContent":["import './typings/javascript-lp-solver.d.ts'\n\nexport type { Round } from './classes/round-ballot-method'\nexport { type Methods, methods } from './methods'\nexport { AbsoluteMajority } from './methods/absolute-majority'\nexport { Approbation } from './methods/approbation'\nexport { Baldwin } from './methods/baldwin'\nexport { Borda } from './methods/borda'\nexport { BottomTwoRunoff } from './methods/bottom-two-runoff'\nexport { Coombs } from './methods/coombs'\nexport { Copeland } from './methods/copeland'\nexport { FirstPastThePost } from './methods/first-past-the-post'\nexport { InstantRunoff } from './methods/instant-runoff'\nexport { Kemeny } from './methods/kemeny'\nexport { type Judgements, MajorityJudgment } from './methods/majority-judgment'\nexport { MaximalLotteries } from './methods/maximal-lotteries'\nexport { Minimax, MinimaxVariant } from './methods/minimax'\nexport { MinimaxTD } from './methods/minimax-td'\nexport { Nanson } from './methods/nanson'\nexport { RandomCandidates } from './methods/random-candidates'\nexport { RandomDictator } from './methods/random-dictator'\nexport { RandomizedCondorcet } from './methods/randomized-condorcet'\nexport { RankedPairs } from './methods/ranked-pairs'\nexport { Schulze } from './methods/schulze'\nexport { Smith } from './methods/smith'\nexport { TwoRoundRunoff } from './methods/two-round-runoff'\nexport type { Ballot, Matrix, ScoreObject } from './types'\nexport { VotingSystem } from './types'\nexport * as utils from './utils'\nexport type {\n  BallotMethods,\n  BallotSystem,\n  MatrixMethods,\n  MatrixSystem,\n  RandomMethods,\n  RandomSystem,\n} from './utils/categories'\nexport {\n  isBallotMethod,\n  isBallotSystem,\n  isMatrixMethod,\n  isMatrixSystem,\n  isRandomMethod,\n  isRandomSystem,\n} from './utils/categories'\n","export interface Ballot {\n  ranking: string[][]\n  weight: number\n}\n\nexport type Matrix = {\n  candidates: string[]\n  array: number[][]\n}\n\nexport type ScoreObject = Record<string, number>\n\nexport enum VotingSystem {\n  Approbation = 'APPROBATION',\n  AbsoluteMajority = 'ABSOLUTE_MAJORITY',\n  Baldwin = 'BALDWIN',\n  Borda = 'BORDA',\n  BottomTwoRunoff = 'BOTTOM_TWO_RUNOFF',\n  Coombs = 'COOMBS',\n  Copeland = 'COPELAND',\n  FirstPastThePost = 'FIRST_PAST_THE_POST',\n  Kemeny = 'KEMENY',\n  InstantRunoff = 'INSTANT_RUNOFF',\n  MajorityJudgment = 'MAJORITY_JUDGEMENT',\n  MaximalLotteries = 'MAXIMAL_LOTTERIES',\n  Minimax = 'MINIMAX',\n  MinimaxTD = 'MINIMAX_TD',\n  Nanson = 'NANSON',\n  RandomizedCondorcet = 'RANDOMIZED_CONDORCET',\n  RandomCandidates = 'RANDOM_CANDIDATES',\n  RandomDictator = 'RANDOM_DICTATOR',\n  RankedPairs = 'RANKED_PAIRS',\n  Schulze = 'SCHULZE',\n  Smith = 'SMITH',\n  TwoRoundRunoff = 'TWO_ROUND_RUNOFF',\n}\n","import { difference, range, times } from 'lodash-es'\n\nimport type { Ballot, Matrix } from '../types'\n\nexport const matrixFromBallots = (\n  ballots: Ballot[],\n  candidates: string[],\n): Matrix => {\n  const array: number[][] = times(candidates.length, () =>\n    times(candidates.length, () => 0),\n  )\n  for (const ranking of ballots) {\n    const rIndex = ranking.ranking.map((rank) =>\n      rank.map((c) => candidates.indexOf(c)),\n    )\n    let rankedLower = range(candidates.length)\n    for (const rank of rIndex) {\n      rankedLower = difference(rankedLower, rank)\n      for (const w of rank)\n        for (const l of rankedLower) {\n          array[w][l] += ranking.weight\n        }\n    }\n  }\n  return { array, candidates }\n}\n\nexport const makeAntisymetric = (matrix: Matrix): Matrix => ({\n  array: matrix.array.map((values, row) =>\n    values.map((v, col) => v - matrix.array[col][row]),\n  ),\n  candidates: matrix.candidates,\n})\n\nexport const subMatrix = (\n  matrix: Matrix,\n  selectedCandidates: string[],\n): Matrix => {\n  const selectedIdxs = new Set(\n    selectedCandidates.map((selectedCandidate) => {\n      const idx = matrix.candidates.indexOf(selectedCandidate)\n      if (idx === -1)\n        throw new Error(\n          `Selected candidates should be in the matrix. \"${selectedCandidates}\" is missing.`,\n        )\n      return idx\n    }),\n  )\n\n  return {\n    array: matrix.array\n      .filter((row, rowIdx) => selectedIdxs.has(rowIdx))\n      .map((row) => row.filter((col, colIdx) => selectedIdxs.has(colIdx))),\n    candidates: matrix.candidates.filter((c) => selectedCandidates.includes(c)),\n  }\n}\n","import { groupBy, sortBy, toPairs } from 'lodash-es'\n\nexport const scoresToRanking = (scores: {\n  [candidate: string]: number\n}): string[][] =>\n  sortBy(\n    groupBy(toPairs(scores), (e) => e[1]),\n    (e) => -e[0][1],\n  ).map((e) => e.map((f) => f[0]))\n","import _ from 'lodash-es'\n\nimport { scoresToRanking } from '../utils/scores'\n\nexport interface Ranker {\n  ranking(): string[][]\n}\n\nexport abstract class Method implements Ranker {\n  public static readonly needsMatrix: boolean = false\n  public static readonly needsBallot: boolean = false\n  public static readonly isRandom: boolean = false\n\n  constructor(readonly candidates: string[]) {}\n\n  /**\n   * Result of the vote. The first item lists the winners of the vote.\n   *\n   * For example this ranking means that `Bear` wins, `Sheep` is second and `Lion` third\n   * `[ [ 'Bear' ], [ 'Sheep' ], [ 'Lion' ] ]`\n   */\n  public abstract ranking(): string[][]\n\n  /**\n   * Split tied candidates in a ranking.\n   *\n   * @param rankingToTieBreak - a ranking in which ties will be attempted to be broken by the current voting system\n   */\n  public tieBreak(rankingToTieBreak: string[][]): string[][] {\n    const ranking = this.ranking()\n\n    const scores = ranking.reduce((acc, rank, idx) => {\n      return {\n        ...acc,\n        ..._.zipObject(rank, new Array(rank.length).fill(-idx)),\n      }\n    }, {} as { [candidate: string]: number })\n\n    return rankingToTieBreak.flatMap((rank) =>\n      scoresToRanking(_.pick(scores, rank)),\n    )\n  }\n}\n","import type { ScoreObject } from '../types'\nimport { scoresToRanking } from '../utils/scores'\n\nimport type { Ranker } from './method'\nimport { Method } from './method'\n\nexport interface Scorer extends Ranker {\n  scores(): ScoreObject\n}\n\n/**\n * Voting method for which the ballots are not necessary: the matrix of duels in enough.\n */\nexport abstract class ScoreMethod extends Method implements Scorer {\n  public abstract scores(): ScoreObject\n\n  public ranking(): string[][] {\n    return scoresToRanking(this.scores())\n  }\n}\n","import type { Ballot, Matrix } from '../types'\nimport { matrixFromBallots } from '../utils/make-matrix'\n\nimport type { Matrixer } from './matrix-score-method'\nimport type { Scorer } from './score-method'\nimport { ScoreMethod } from './score-method'\n\nexport abstract class BallotScoreMethod\n  extends ScoreMethod\n  implements Scorer, Matrixer\n{\n  public static readonly needsBallot = true\n  protected readonly ballots: Ballot[]\n  private _matrix?: Matrix\n\n  constructor({\n    ballots,\n    candidates,\n  }: {\n    ballots: Ballot[]\n    candidates: string[]\n  }) {\n    super(candidates)\n    this.ballots = ballots\n  }\n\n  get matrix(): Matrix {\n    if (!this._matrix)\n      this._matrix = matrixFromBallots(this.ballots, this.candidates)\n\n    return this._matrix\n  }\n}\n","import _ from 'lodash-es'\n\nimport type { Ballot } from '../types'\n\n/**\n * Returns true if the 2 ballots are equivalent. The order of the candidates inside a rank is irrelevant. Reflexive check.\n *\n * @param a - first ballot\n * @param b - second ballot\n */\nexport const isBallotEqual = (a: string[][], b: string[][]): boolean => {\n  if (a.length !== b.length) return false\n  if (a.length === 0) return true\n  return _.every(a, (rank, k) => _.isEqual([...rank].sort(), [...b[k]].sort()))\n}\n\n/**\n * Convert `(string | string[])[]` to `string[][]`.\n * Elements of the input that are strings are converted to singletons.\n *\n * @param rankInput - Input rank\n */\nexport const normalizeRankInput = (\n  rankInput: (string | string[])[],\n): string[][] =>\n  rankInput.map((rank) => (typeof rank === 'string' ? [rank] : rank))\n\n/**\n * Group ballots by merging equivalent ballots (see {@link isBallotEqual}).\n *\n * @param ballots - ballots to group\n */\nexport const groupBallots = <B extends Ballot>(ballots: B[]): B[] =>\n  ballots\n    .reduce((acc, ballot) => {\n      const match = acc.findIndex((b) =>\n        isBallotEqual(b.ranking, ballot.ranking),\n      )\n      if (match === -1) return [...acc, ballot]\n      return acc.map((b, k) =>\n        k === match\n          ? {\n              ...b,\n              weight: b.weight + ballot.weight,\n            }\n          : b,\n      )\n    }, [] as B[])\n    .filter((b) => b.weight !== 0)\n    .sort((a, b) => b.weight - a.weight)\n\nexport const toWeightedBallots = (ballots: string[][][]): Ballot[] =>\n  ballots.reduce((w, ballot) => {\n    const match = w.findIndex((ww) => isBallotEqual(ww.ranking, ballot))\n    if (match === -1) {\n      return [...w, { ranking: ballot, weight: 1 }]\n    }\n    return w.map((ww, k) =>\n      k === match\n        ? {\n            ranking: w[match].ranking,\n            weight: w[match].weight + 1,\n          }\n        : ww,\n    )\n  }, [] as Ballot[])\n\nexport const checkDuplicatedCandidate = (ranking: string[][]): void => {\n  ranking.reduce((acc, rank) => {\n    const inter = _.intersection(acc, rank)\n    if (inter.length > 0) {\n      throw new Error(`Some candidates are present multiple times: ${inter}`)\n    }\n    return [...acc, ...rank]\n  }, [])\n}\n\n/**\n * Remove candidates that are duplicated inside a ranking. Prevents cheating!\n *\n * @param ranking - input ranking\n */\nexport const removeDuplicatedCandidates = (ranking: string[][]): string[][] =>\n  ranking.reduce(\n    (acc, cur) => {\n      const unique = _.difference(_.uniq(cur), acc.usedCandidates)\n      return {\n        ranking: unique.length > 0 ? [...acc.ranking, unique] : acc.ranking,\n        usedCandidates: [...acc.usedCandidates, ...unique],\n      }\n    },\n    {\n      ranking: [] as string[][],\n      usedCandidates: [] as string[],\n    },\n  ).ranking\n\n/**\n * Remove candidates in `ranking` that don't exist in `candidates`. Prevents cheating!\n *\n * @param ranking - ranking to check\n * @param candidates - official candidates\n */\nexport const removeInvalidCandidates = (\n  ranking: string[][],\n  candidates: string[],\n): string[][] =>\n  ranking\n    .map((names) => names.filter((name) => candidates.includes(name)))\n    .filter((rank) => rank.length)\n\n/**\n * Prevents cheating!\n *\n * @param ranking - ranking to normalize\n * @param candidates - official candidates\n */\nexport const normalizeRanking = (\n  ranking: string[][],\n  candidates: string[],\n): string[][] =>\n  removeDuplicatedCandidates(removeInvalidCandidates(ranking, candidates))\n\n/**\n * Prevents cheating!\n *\n * @param ballot - ballot to normalize\n * @param candidates - official candidates\n */\nexport const normalizeBallot = <B extends Ballot>(\n  ballot: B,\n  candidates: string[],\n): B => ({\n  ...ballot,\n  ranking: normalizeRanking(ballot.ranking, candidates),\n})\n\n/**\n * Gather all the candidates present in `ballots`\n *\n * @param ballots - ranking to normalize\n */\nexport const candidatesFromBallots = (ballots: Ballot[]): string[] =>\n  ballots.reduce(\n    (acc, curr) => _.uniq([...acc, ...curr.ranking.flat()]),\n    [] as string[],\n  )\n\nexport const normalizeBallots = <B extends Ballot>(\n  ballots: B[],\n  candidates?: string[],\n): B[] => {\n  const c = candidates || candidatesFromBallots(ballots)\n  return ballots.map((ballot) => normalizeBallot(ballot, c))\n}\n\nexport const totalBallotsWeight = (ballots: Ballot[]): number =>\n  ballots.reduce((acc, ballot) => acc + ballot.weight, 0)\n","import { zipObject } from 'lodash-es'\n\nimport type { ScoreObject } from '../types'\n\nexport const scoresAny = (candidates: string[], value: number): ScoreObject =>\n  zipObject(candidates, new Array(candidates.length).fill(value))\n\nexport const scoresZero = (candidates: string[]): ScoreObject =>\n  scoresAny(candidates, 0)\n","import type { Ballot, ScoreObject } from '../../types'\nimport { normalizeBallots } from '../../utils/normalize'\nimport { scoresZero } from '../../utils/scores-zero'\n\nexport const iterateFirstChoices = (\n  ballots: Ballot[],\n  candidates: string[],\n  computeBallotScore: (rank: string[], rankIdx: number) => number,\n): ScoreObject => iterateNthChoices(ballots, candidates, computeBallotScore, 0)\n\nexport const iterateNthChoices = (\n  ballots: Ballot[],\n  candidates: string[],\n  computeBallotScore: (rank: string[], rankIdx: number) => number,\n  rankIdx: number,\n): ScoreObject => {\n  const result: ScoreObject = scoresZero(candidates)\n  for (const ballot of normalizeBallots(ballots, candidates))\n    if (ballot.ranking.length > rankIdx) {\n      const votes = ballot.ranking[rankIdx].filter((c) =>\n        candidates.includes(c),\n      )\n      for (const candidate of votes)\n        result[candidate] += computeBallotScore(votes, rankIdx) * ballot.weight\n    }\n  return result\n}\n","import { BallotScoreMethod } from '../../classes/ballot-score-method'\nimport type { Ballot, ScoreObject } from '../../types'\n\nimport { iterateFirstChoices } from './iterate-first-choices'\n\nconst computeScores = (candidates: string[], ballots: Ballot[]) => {\n  return iterateFirstChoices(ballots, candidates, (rank) => 1 / rank.length)\n}\n\n/**\n * #### Wikipedia: [First-past-the-post voting](https://en.wikipedia.org/wiki/First-past-the-post_voting)\n */\nexport class FirstPastThePost extends BallotScoreMethod {\n  public scores(): ScoreObject {\n    return computeScores(this.candidates, this.ballots)\n  }\n}\n","import { BallotScoreMethod } from '../../classes/ballot-score-method'\nimport type { ScoreObject } from '../../types'\nimport { totalBallotsWeight } from '../../utils/normalize'\nimport { scoresZero } from '../../utils/scores-zero'\nimport { FirstPastThePost } from '../first-past-the-post'\n\n/**\n * #### Wikipedia: [Majority](https://en.wikipedia.org/wiki/Majority)\n */\nexport class AbsoluteMajority extends BallotScoreMethod {\n  public scores(): ScoreObject {\n    const totalWeight = totalBallotsWeight(this.ballots)\n\n    const fptp = new FirstPastThePost({\n      ballots: this.ballots,\n      candidates: this.candidates,\n    })\n    const topRank = fptp.ranking()[0]\n    const fptpScores = fptp.scores()\n\n    if (topRank?.length === 1 && fptpScores[topRank[0]] > totalWeight / 2)\n      return {\n        ...scoresZero(this.candidates),\n        [topRank[0]]: fptpScores[topRank[0]],\n      }\n    return scoresZero(this.candidates)\n  }\n}\n","import { BallotScoreMethod } from '../../classes/ballot-score-method'\nimport type { ScoreObject } from '../../types'\nimport { iterateFirstChoices } from '../first-past-the-post/iterate-first-choices'\n\n/**\n * #### Wikipedia: [Approval voting](https://en.wikipedia.org/wiki/Approval_voting)\n */\nexport class Approbation extends BallotScoreMethod {\n  public scores(): ScoreObject {\n    return iterateFirstChoices(this.ballots, this.candidates, () => 1)\n  }\n}\n","import _ from 'lodash-es'\n\nimport { RoundBallotMethod } from '../../classes/round-ballot-method'\nimport type { Ballot, ScoreObject } from '../../types'\nimport { arrayAt } from '../../utils/array-at'\nimport { Borda } from '../borda'\n\nconst round = (\n  candidates: string[],\n  ballots: Ballot[],\n): {\n  qualified: string[]\n  eliminated: string[]\n  scores: ScoreObject\n} => {\n  const borda = new Borda({ candidates, ballots })\n\n  const ranking = borda.ranking()\n\n  const eliminated = arrayAt(ranking, -1) || []\n  const qualified = _.difference(candidates, eliminated)\n\n  return { eliminated, qualified, scores: borda.scores() }\n}\n\n/**\n * Iterative {@link Borda | Borda count} in which, each round, candidates scoring the lowest score are eliminated.\n */\nexport class Baldwin extends RoundBallotMethod {\n  protected round(candidates: string[]): {\n    qualified: string[]\n    eliminated: string[]\n    scores: ScoreObject\n  } {\n    return round(candidates, this.ballots)\n  }\n}\n","/**\n * Replacement for `Array.at`. Should have the exact same behaviour.\n */\nexport const arrayAt = <T>(array: T[], at: number): T =>\n  array[at < 0 ? array.length + at : at]\n","import type { Ballot, Matrix } from '../types'\nimport { matrixFromBallots } from '../utils/make-matrix'\n\nimport type { Ranker } from './method'\nimport { Method } from './method'\n\nexport abstract class BallotMethod extends Method implements Ranker {\n  public static readonly needsBallot = true\n  protected readonly ballots: Ballot[]\n  private _matrix?: Matrix\n\n  /**\n   * @param ballots - ballots cast by the voters\n   * @param candidates - canidates to consider\n   */\n  constructor({\n    ballots,\n    candidates,\n  }: {\n    ballots: Ballot[]\n    candidates: string[]\n  }) {\n    super(candidates)\n    this.ballots = ballots\n  }\n\n  /**\n   * Return a matrix of duels from all the ballots\n   */\n  get matrix(): Matrix {\n    if (!this._matrix)\n      this._matrix = matrixFromBallots(this.ballots, this.candidates)\n\n    return this._matrix\n  }\n}\n","import type { ScoreObject } from '../types'\nimport { arrayAt } from '../utils/array-at'\n\nimport { BallotMethod } from './ballot-method'\nimport type { Ranker } from './method'\n\nexport type Round = {\n  finished?: boolean\n  idx: number\n  candidates: string[]\n  roundResult: {\n    eliminated: string[]\n    qualified: string[]\n    scores: ScoreObject\n  }\n}\n\n/**\n * Voting system in which candidates are iteratively eliminated.\n */\nexport abstract class RoundBallotMethod extends BallotMethod implements Ranker {\n  protected rounds: Round[] = []\n\n  public computeRounds(): Round[] {\n    while (this.lastRoundQualified().length > 0) {\n      this.computeNextRound()\n    }\n    return this.rounds\n  }\n\n  public ranking(): string[][] {\n    return [...this.computeRounds()]\n      .reverse()\n      .map((r) => r.roundResult.eliminated)\n      .filter((eliminated) => eliminated.length)\n  }\n\n  protected abstract round(\n    candidates: string[],\n    idx?: number,\n  ): {\n    qualified: string[]\n    eliminated: string[]\n    scores: ScoreObject\n  }\n\n  private computeNextRound(): void {\n    const previousRound = arrayAt(this.rounds, -1)\n    const candidates = previousRound?.roundResult.qualified || this.candidates\n\n    const idx = previousRound ? previousRound.idx + 1 : 0\n\n    const round = {\n      candidates,\n      idx,\n      roundResult: this.round(candidates, idx),\n    }\n\n    this.rounds = [\n      ...this.rounds,\n      {\n        finished: round.roundResult.qualified.length === 0,\n        ...round,\n      },\n    ]\n  }\n\n  private lastRoundQualified(): string[] {\n    const previousRound = arrayAt(this.rounds, -1)\n    return previousRound?.roundResult.qualified || this.candidates\n  }\n}\n","import { BallotScoreMethod } from '../../classes/ballot-score-method'\nimport type { Ballot, ScoreObject } from '../../types'\nimport { normalizeBallots } from '../../utils/normalize'\nimport { scoresZero } from '../../utils/scores-zero'\n\nconst computeScores = (\n  candidates: string[],\n  _ballots: Ballot[],\n): ScoreObject => {\n  const scores = scoresZero(candidates)\n  const ballots = normalizeBallots(_ballots, candidates)\n  for (const ballot of normalizeBallots(ballots, candidates)) {\n    let voteValue = candidates.length // - 1\n    for (const candidatesAtRank of ballot.ranking) {\n      const value = voteValue - (candidatesAtRank.length - 1) / 2\n      for (const candidate of candidatesAtRank) {\n        scores[candidate] += value * ballot.weight\n      }\n      voteValue -= candidatesAtRank.length\n    }\n  }\n  return scores\n}\n\n/**\n * For each voter, every candidate is given a number of points which equals the number of candidates ranked lower in the voter's preference.\n *\n * #### Wikipedia: [Borda count](https://en.wikipedia.org/wiki/Borda_count)\n */\nexport class Borda extends BallotScoreMethod {\n  public scores(): ScoreObject {\n    return computeScores(this.candidates, this.ballots)\n  }\n}\n","import _ from 'lodash-es'\n\nimport { RoundBallotMethod } from '../../classes/round-ballot-method'\nimport type { Ballot, ScoreObject } from '../../types'\nimport { arrayAt } from '../../utils/array-at'\nimport { matrixFromBallots } from '../../utils/make-matrix'\nimport { normalizeBallots } from '../../utils/normalize'\nimport { scoresAny } from '../../utils/scores-zero'\nimport { BiggestSupport } from '../biggest-support'\nimport { Copeland } from '../copeland'\n\n/**\n * #### Electowiki: [Bottom-Two-Runoff IRV](https://electowiki.org/wiki/Bottom-Two-Runoff_IRV)\n */\nexport class BottomTwoRunoff extends RoundBallotMethod {\n  private copeland: Copeland\n  constructor(i: { ballots: Ballot[]; candidates: string[] }) {\n    super(i)\n    this.copeland = new Copeland(matrixFromBallots(i.ballots, i.candidates))\n  }\n\n  protected round(candidates: string[]): {\n    qualified: string[]\n    eliminated: string[]\n    scores: ScoreObject\n  } {\n    const biggestSupport = new BiggestSupport({\n      ballots: normalizeBallots(this.ballots, candidates),\n      candidates,\n    }).ranking()\n\n    const leastSupport = arrayAt(biggestSupport, -1)\n\n    const bottom = []\n    if (leastSupport) bottom.push(...leastSupport)\n    if (bottom.length === 1) {\n      const leastSupport2 = arrayAt(biggestSupport, -2)\n      if (leastSupport2) bottom.push(...leastSupport2)\n    }\n\n    const eliminated = arrayAt(this.copeland.tieBreak([bottom]), -1)\n\n    if (!eliminated || eliminated.length === 0)\n      throw new Error('Unexpected round result!')\n\n    return {\n      eliminated,\n      qualified: _.difference(candidates, eliminated),\n      scores: {\n        ...scoresAny(candidates, 2),\n        ...scoresAny(bottom, 1),\n        ...scoresAny(eliminated, 0),\n      },\n    }\n  }\n}\n","import _ from 'lodash-es'\n\nimport { BallotMethod } from '../../classes/ballot-method'\nimport type { Ballot } from '../../types'\nimport { iterateFirstChoices } from '../first-past-the-post/iterate-first-choices'\n\nconst deTie = (ranking: string[][], ballots: Ballot[]): string[][] =>\n  ranking.flatMap((rank) => {\n    if (rank.length < 2) return [rank]\n\n    const scores = iterateFirstChoices(ballots, rank, (r) => 1 / r.length)\n    const pickedScores = _.pick(scores, rank)\n    const groups = _.groupBy(rank, (c) => pickedScores[c])\n    return Object.keys(groups)\n      .sort((a, b) => Number(b) - Number(a))\n      .map((score) => groups[score])\n  })\n\nexport const isTied = (ranking: string[][]): boolean =>\n  ranking.some((rank) => rank.length > 1)\n\nexport class BiggestSupport extends BallotMethod {\n  public ranking(): string[][] {\n    let ranking = [this.candidates]\n\n    let rankIdx = 0\n    while (isTied(ranking) && rankIdx < this.candidates.length) {\n      ranking = deTie(ranking, this.ballots)\n\n      rankIdx++\n    }\n\n    return ranking\n  }\n}\n","import _ from 'lodash-es'\n\nimport { MatrixScoreMethod } from '../../classes/matrix-score-method'\nimport type { Matrix, ScoreObject } from '../../types'\n\nconst computeFromMatrix = (matrix: Matrix) => {\n  const n = matrix.candidates.length\n\n  const p: number[][] = _.range(n).map(() => _.range(n).map(() => 0))\n  for (let i = 0; i < n; i++) {\n    for (let j = 0; j < n; j++) {\n      if (i !== j) {\n        p[i][j] = (Math.sign(matrix.array[i][j] - matrix.array[j][i]) + 1) / 2\n      }\n    }\n  }\n\n  const scores = p.map((m) => m.reduce((acc, cur) => acc + cur, 0))\n\n  return _.zipObject(matrix.candidates, scores)\n}\n\nexport class Copeland extends MatrixScoreMethod {\n  public scores(): ScoreObject {\n    return computeFromMatrix(this.matrix)\n  }\n}\n","import type { Matrix } from '../types'\n\nimport type { Scorer } from './score-method'\nimport { ScoreMethod } from './score-method'\n\nexport interface Matrixer {\n  matrix: Matrix\n}\n\nexport abstract class MatrixScoreMethod\n  extends ScoreMethod\n  implements Scorer, Matrixer\n{\n  public static readonly needsMatrix = true\n  private readonly _matrix: Matrix\n\n  constructor(i: Matrix) {\n    super(i.candidates)\n    this._matrix = {\n      array: i.array,\n      candidates: i.candidates,\n    }\n  }\n\n  get matrix(): Matrix {\n    return this._matrix\n  }\n}\n","import _ from 'lodash-es'\n\nimport { RoundBallotMethod } from '../../classes/round-ballot-method'\nimport type { Ballot, ScoreObject } from '../../types'\nimport { normalizeBallots } from '../../utils'\nimport { scoresZero } from '../../utils/scores-zero'\nimport { AbsoluteMajority } from '../absolute-majority'\nimport { FirstPastThePost } from '../first-past-the-post'\n\nconst reverseBallots = (ballots: Ballot[]) =>\n  ballots.map((ballot) => ({\n    ...ballot,\n    ranking: [...ballot.ranking].reverse(),\n  }))\n\nconst round = (\n  candidates: string[],\n  _ballots: Ballot[],\n): {\n  qualified: string[]\n  eliminated: string[]\n  scores: ScoreObject\n  absoluteMajority?: true\n} => {\n  if (candidates.length < 2)\n    return {\n      eliminated: candidates,\n      qualified: [],\n      scores: scoresZero(candidates),\n    }\n\n  const ballots = normalizeBallots(_ballots, candidates)\n\n  const absoluteMajority = new AbsoluteMajority({ candidates, ballots })\n\n  if (absoluteMajority.ranking()[0].length === 1) {\n    const qualified = absoluteMajority.ranking()[0]\n    return {\n      eliminated: _.difference(candidates, qualified),\n      qualified,\n      scores: absoluteMajority.scores(),\n      absoluteMajority: true,\n    }\n  }\n\n  const reversedFptp = new FirstPastThePost({\n    ballots: reverseBallots(ballots),\n    candidates,\n  })\n  const eliminated = reversedFptp.ranking()[0]\n  return {\n    eliminated,\n    qualified: _.difference(candidates, eliminated),\n    scores: _.mapValues(reversedFptp.scores(), (s) => -s),\n  }\n}\n\n/**\n * #### Wikipedia: [Coombs' method](https://en.wikipedia.org/wiki/Coombs%27_method)\n */\nexport class Coombs extends RoundBallotMethod {\n  protected round(candidates: string[]): {\n    eliminated: string[]\n    qualified: string[]\n    scores: ScoreObject\n  } {\n    return round(candidates, this.ballots)\n  }\n}\n","export { generateAcyclicGraph } from '../methods/ranked-pairs/generate-acyclic-graph'\nexport { findCondorcet, findSmithSet } from './condorcet'\nexport { makeAntisymetric, matrixFromBallots } from './make-matrix'\nexport {\n  candidatesFromBallots,\n  checkDuplicatedCandidate,\n  groupBallots,\n  normalizeBallot,\n  normalizeBallots,\n  normalizeRanking,\n  normalizeRankInput,\n  removeDuplicatedCandidates,\n  removeInvalidCandidates,\n  toWeightedBallots,\n} from './normalize'\nexport { scoresToRanking } from './scores'\n","import _ from 'lodash-es'\n\nimport { Tarjan } from './tarjan'\nimport { Vertex } from './vertex'\n\ntype Edge = { from: number; to: number; value: number }\n\nexport const generateAcyclicGraph = (\n  graph: Edge[],\n  edgesToAdd: Edge[],\n): Edge[] => {\n  const allEdges = [...graph, ...edgesToAdd]\n  const vDict = {} as { [i: number]: Vertex }\n  for (const c of _.uniq(allEdges.flatMap((e) => [e.from, e.to])))\n    vDict[c] = new Vertex(c)\n\n  for (const e of allEdges) vDict[e.from].connect(vDict[e.to])\n  const tarjan = new Tarjan(Object.values(vDict))\n  tarjan.run()\n  return [\n    ...graph,\n    ...edgesToAdd.filter(\n      (edge) => vDict[edge.from].lowlink !== vDict[edge.to].lowlink,\n    ),\n  ]\n}\n","// From chadhutchins:\n// https://gist.github.com/chadhutchins/1440602\n\nimport type { Vertex } from './vertex'\n\nexport class VertexStack {\n  public vertices: Vertex[]\n\n  constructor() {\n    this.vertices = []\n  }\n\n  public contains(vertex: Vertex): boolean {\n    for (const i in this.vertices)\n      if (this.vertices[i].equals(vertex)) return true\n    return false\n  }\n}\n","// From chadhutchins:\n// https://gist.github.com/chadhutchins/1440602\n\nimport type { Vertex } from './vertex'\nimport { VertexStack } from './vertex-stack'\n\nexport class Tarjan {\n  private index: number\n  private stack: VertexStack\n  private readonly graph: Vertex[]\n  private readonly scc: Vertex[][]\n\n  constructor(graph: Vertex[]) {\n    this.index = 0\n    this.stack = new VertexStack()\n    this.graph = graph\n    this.scc = []\n  }\n  public run(): Vertex[][] {\n    for (const i in this.graph)\n      if (this.graph[i].index < 0) this.strongconnect(this.graph[i])\n    return this.scc\n  }\n  private strongconnect(vertex: Vertex): void {\n    // Set the depth index for v to the smallest unused index\n    vertex.index = this.index\n    vertex.lowlink = this.index\n    this.index = this.index + 1\n    this.stack.vertices.push(vertex)\n\n    // Consider successors of v\n    // aka... consider each vertex in vertex.connections\n    for (const connection of vertex.connections) {\n      const v = vertex\n      const w = connection\n      if (w.index < 0) {\n        // Successor w has not yet been visited; recurse on it\n        this.strongconnect(w)\n        v.lowlink = Math.min(v.lowlink, w.lowlink)\n      } else if (this.stack.contains(w)) {\n        // Successor w is in stack S and hence in the current SCC\n        v.lowlink = Math.min(v.lowlink, w.index)\n      }\n    }\n\n    // If v is a root node, pop the stack and generate an SCC\n    if (vertex.lowlink === vertex.index) {\n      // start a new strongly connected component\n      const vertices: Vertex[] = []\n      let w = null\n      if (this.stack.vertices.length > 0)\n        do {\n          w = this.stack.vertices.pop()\n          // add w to current strongly connected component\n          if (w) vertices.push(w)\n        } while (w && !vertex.equals(w))\n      // output the current strongly connected component\n      // ... i'm going to push the results to a member scc array variable\n      if (vertices.length > 0) this.scc.push(vertices)\n    }\n  }\n}\n","// From chadhutchins:\n// https://gist.github.com/chadhutchins/1440602\n\nexport class Vertex {\n  public index: number\n  public lowlink: number\n  public connections: Vertex[]\n  private readonly name: number | string\n  constructor(name: number | string) {\n    this.connections = []\n    this.name = name\n\n    // used in tarjan algorithm\n    // went ahead and explicity initalized them\n    this.index = -1\n    this.lowlink = -1\n  }\n\n  public equals(vertex: Vertex): boolean {\n    // equality check based on vertex name\n    return this.name === vertex.name\n  }\n\n  public connect(vertex: Vertex): void {\n    this.connections.push(vertex)\n  }\n}\n","import _ from 'lodash-es'\n\nimport type { Matrix } from '../types'\n\nimport { makeAntisymetric } from './make-matrix'\n\nexport const findSmithSet = (_matrix: Matrix): Matrix => {\n  const { candidates, array } = makeAntisymetric(_matrix)\n  const dominatingDirectList = candidates.map((_c, k) =>\n    array[k].map((_v, k2) => k2).filter((k2) => array[k][k2] >= 0),\n  )\n  const dominatingList = candidates.map((c, k) => {\n    let dominating = [k]\n    let toCheck = [k]\n    while (toCheck.length > 0) {\n      const check = toCheck.pop() as number\n      const toAdd = _.difference(dominatingDirectList[check], dominating)\n      dominating = [...dominating, ...toAdd]\n      toCheck = [...toCheck, ...toAdd]\n    }\n    return dominating.length === candidates.length\n  })\n\n  return {\n    array: array\n      .filter((row, k1) => dominatingList[k1])\n      .map((row) => row.filter((v, k2) => dominatingList[k2])),\n    candidates: candidates.filter((c, k) => dominatingList[k]),\n  }\n}\n\n// We renamed findCondorcet -> findSmithSet\n// Keeping the old name exported, so we don't introduce breaking changes\nexport const findCondorcet = findSmithSet\n","import { RoundBallotMethod } from '../../classes/round-ballot-method'\nimport type { Ballot, ScoreObject } from '../../types'\nimport { normalizeBallots } from '../../utils'\nimport { FirstPastThePost } from '../first-past-the-post'\n\nconst round = (\n  candidates: string[],\n  ballots: Ballot[],\n): {\n  qualified: string[]\n  eliminated: string[]\n  scores: ScoreObject\n} => {\n  const normalizedBallots = normalizeBallots(ballots, candidates)\n\n  const fptp = new FirstPastThePost({\n    ballots: normalizedBallots,\n    candidates,\n  })\n  const round1 = fptp.scores()\n  const minScore = Math.min(...Object.values(round1))\n  const qualified = candidates.filter((c) => round1[c] > minScore)\n  const eliminated = candidates.filter((c) => round1[c] <= minScore)\n  return {\n    eliminated,\n    qualified,\n    scores: round1,\n  }\n}\n\n/**\n * #### Wikipedia: [Instant-runoff voting](https://en.wikipedia.org/wiki/Instant-runoff_voting)\n */\nexport class InstantRunoff extends RoundBallotMethod {\n  protected round(candidates: string[]): {\n    qualified: string[]\n    eliminated: string[]\n    scores: ScoreObject\n  } {\n    return round(candidates, this.ballots)\n  }\n}\n","import { range, zipObject } from 'lodash-es'\n\nimport { MatrixScoreMethod } from '../../classes/matrix-score-method'\nimport type { Matrix, ScoreObject } from '../../types'\n\nconst rankingPenalty = (ranking: number[], matrix: number[][]) => {\n  let p = 0\n  for (let i = 0; i < matrix.length; i += 1) {\n    for (let j = i + 1; j < matrix.length; j += 1) {\n      p += matrix[ranking[i]][ranking[j]]\n    }\n  }\n  return p\n}\n\nconst nextPermutation = (arr: number[]) => {\n  // Find longest non-increasing suffix\n  const array = [...arr]\n  let i = array.length - 1\n  while (i > 0 && array[i - 1] >= array[i]) i -= 1\n  // Now i is the head index of the suffix\n\n  // Are we at the last permutation already?\n  if (i <= 0) return false\n\n  // Let array[i - 1] be the pivot\n  // Find rightmost element that exceeds the pivot\n  let j = array.length - 1\n  while (array[j] <= array[i - 1]) j -= 1\n  // Now the value array[j] will become the new pivot\n  // Assertion: j >= i\n\n  // Swap the pivot with j\n  let temp = array[i - 1]\n  array[i - 1] = array[j]\n  array[j] = temp\n\n  // Reverse the suffix\n  j = array.length - 1\n  while (i < j) {\n    temp = array[i]\n    array[i] = array[j]\n    array[j] = temp\n    i += 1\n    j -= 1\n  }\n\n  // Successfully computed the next permutation\n  return array\n}\n\nconst computeScores = (matrix: Matrix): ScoreObject => {\n  let bestPermutations: number[][] = []\n  let bestScore = Infinity\n  let p: number[] | false = range(matrix.candidates.length)\n  while (p) {\n    const s = rankingPenalty(p, matrix.array)\n    if (s === bestScore) bestPermutations.push(p)\n    else if (s < bestScore) {\n      bestScore = s\n      bestPermutations = [p]\n    }\n    p = nextPermutation(p)\n  }\n  const sumIdx = matrix.candidates.map((c, cIdx) =>\n    bestPermutations\n      .map((perm) => perm.indexOf(cIdx))\n      .reduce((a, v) => a + v, 0),\n  )\n  return zipObject(matrix.candidates, sumIdx)\n}\n\n/**\n * #### Wikipedia: [Kemeny–Young method](https://en.wikipedia.org/wiki/Kemeny%E2%80%93Young_method)\n */\nexport class Kemeny extends MatrixScoreMethod {\n  public scores(): ScoreObject {\n    return computeScores(this.matrix)\n  }\n}\n","import _ from 'lodash-es'\n\nimport { BallotMethod } from '../../classes/ballot-method'\nimport type { Ballot, ScoreObject } from '../../types'\nimport { scoresToRanking } from '../../utils'\n\nexport type Judgements = {\n  [candidate: string]: [number, number, number, number, number, number]\n}\n\nconst makeJudgement = (candidates: string[], ballots: Ballot[]): Judgements => {\n  const judgements: Judgements = _.zipObject(\n    candidates,\n    candidates.map(() => [0, 0, 0, 0, 0, 0]),\n  )\n\n  for (const ballot of ballots)\n    for (const [rankIdx, rank] of ballot.ranking.entries())\n      for (const can of rank)\n        if (candidates.includes(can))\n          judgements[can][rankIdx < 5 ? rankIdx : 5] += ballot.weight\n\n  return judgements\n}\n\nexport const getMedian = (arr: number[]): number => {\n  const sumWeights = _.sum(arr)\n\n  let s = 0\n  let i = 0\n  let prevI = 0\n  let med = 0\n  for (const j of arr) {\n    s += j\n    i++\n    if (s === sumWeights / 2 + 1) med = (prevI + i) / 2\n    else if (s > sumWeights / 2) med = i\n    else {\n      if (j > 0) prevI = i\n      continue\n    }\n    break\n  }\n  return med - 1\n}\n\nconst getMedians = (judgements: Judgements) => {\n  const candidates = Object.keys(judgements)\n\n  const medians: { [candidate: string]: number } = {}\n  for (const c of candidates) medians[c] = getMedian(judgements[c])\n  return medians\n}\n\nconst majorityJudgmentRanking = (\n  candidates: string[],\n  ballots: Ballot[],\n): string[][] => {\n  const judgements = makeJudgement(candidates, ballots)\n  return tieBreak(judgements).reverse()\n}\n\nconst tieBreak = (judgements: Judgements): string[][] => {\n  const medians = getMedians(judgements)\n  const ranking = scoresToRanking(medians)\n  return ranking.flatMap((cs) => {\n    const median = medians[cs[0]]\n    if (median === -1 || !Number.isInteger(median)) return [cs]\n    const j = _.pick(judgements, cs)\n    const minGroup = Math.min(...cs.map((c) => j[c][median]))\n    if (minGroup <= 0) return [cs]\n    const j2 = _.mapValues(j, (jc) =>\n      Object.assign([], jc, { [median]: jc[median] - minGroup }),\n    )\n    return tieBreak(j2)\n  })\n}\n\nexport class MajorityJudgment extends BallotMethod {\n  public judgements(): Judgements {\n    return makeJudgement(this.candidates, this.ballots)\n  }\n\n  public medians(): ScoreObject {\n    return getMedians(this.judgements())\n  }\n\n  public ranking(): string[][] {\n    return majorityJudgmentRanking(this.candidates, this.ballots)\n  }\n}\n","import { zipObject } from 'lodash-es'\n\nimport { RandomMatrixMethod } from '../../classes/random-matrix-method'\nimport { findNashEquilibrium } from '../../simplex/find-nash-equilibrium'\nimport type { Matrix, ScoreObject } from '../../types'\nimport { findSmithSet, makeAntisymetric } from '../../utils'\nimport { scoresZero } from '../../utils/scores-zero'\n\nexport const computeLottery = (\n  _matrix: Matrix,\n): { [candidate: string]: number } => {\n  const matrix = makeAntisymetric(_matrix)\n  const condorset = findSmithSet(matrix)\n\n  const solution = findNashEquilibrium(condorset.array).map((v) =>\n    Math.max(0, v),\n  )\n\n  return {\n    ...scoresZero(matrix.candidates),\n    ...zipObject(condorset.candidates, solution),\n  }\n}\n\nexport class MaximalLotteries extends RandomMatrixMethod {\n  public scores(): ScoreObject {\n    return computeLottery(this.matrix)\n  }\n}\n","import _ from 'lodash-es'\n\nimport type { Matrix, ScoreObject } from '../types'\nimport { shuffleArray } from '../utils/shuffle-array'\n\nimport type { Matrixer } from './matrix-score-method'\nimport { RandomMethod } from './random-method'\nimport type { Scorer } from './score-method'\n\nconst randomRankingFromSores = (\n  scoreObject: ScoreObject,\n  random: () => number,\n): string[] => {\n  const candidates = Object.keys(scoreObject)\n  if (candidates.length < 2) return candidates\n\n  const sumScores = _.sum(Object.values(scoreObject))\n\n  if (sumScores <= 0) return shuffleArray(candidates, random)\n\n  const normalizedScoreObject = _.mapValues(scoreObject, (s) => s / sumScores)\n\n  const pickAt = random()\n  let w = 0\n\n  for (const candidate of candidates) {\n    w += normalizedScoreObject[candidate]\n    if (w >= pickAt)\n      return [\n        candidate,\n        ...randomRankingFromSores(_.omit(scoreObject, candidate), random),\n      ]\n  }\n\n  throw new Error('Unable to generate random ranking from scores')\n}\n\nexport abstract class RandomMatrixMethod\n  extends RandomMethod\n  implements Scorer, Matrixer\n{\n  public static readonly needsMatrix = true\n\n  private readonly _matrix: Matrix\n\n  constructor(i: Matrix & { rng?: () => number }) {\n    super(i)\n\n    this._matrix = {\n      array: i.array,\n      candidates: i.candidates,\n    }\n  }\n\n  get matrix(): Matrix {\n    return this._matrix\n  }\n\n  public abstract scores(): ScoreObject\n\n  public ranking(): string[][] {\n    return randomRankingFromSores(this.scores(), this.rng).map((c) => [c])\n  }\n}\n","export const shuffleArray = <T>(_array: T[], rng: () => number): T[] => {\n  const array = [..._array]\n  let m = array.length\n  let t\n  let i\n\n  // While there remain elements to shuffle…\n  while (m) {\n    // Pick a remaining element…\n    const r = rng()\n    i = Math.floor(r * m--)\n    t = array[m]\n    array[m] = array[i]\n    array[i] = t\n  }\n  return array\n}\n","import type { ScoreObject } from '../types'\n\nimport { Method } from './method'\nimport type { Scorer } from './score-method'\n\n/**\n * Voting method that involves some randomness in the computation in the winners.\n */\nexport abstract class RandomMethod extends Method implements Scorer {\n  public static readonly isRandom = true\n\n  protected readonly rng: () => number\n\n  constructor(i: { candidates: string[]; rng?: () => number }) {\n    super(i.candidates)\n\n    this.rng = i.rng || Math.random\n  }\n\n  public abstract scores(): ScoreObject\n\n  public abstract ranking(): string[][]\n}\n","import solver from 'javascript-lp-solver'\n\ntype SkewSymmetricMatrix = number[][]\n\nconst isZero = (matrix: number[][]): boolean => {\n  for (let i = 0; i < matrix.length; i++)\n    for (let j = 0; j < matrix.length; j++) if (matrix[i][j] !== 0) return false\n  return true\n}\n\nconst normalizeVector = (vector: number[]): number[] => {\n  const positive = vector.map((v) => (v > 0 ? v : 0))\n  const sum = positive.reduce((acc, cur) => acc + cur, 0)\n  return positive.map((v) => v / sum)\n}\n\nexport const findNashEquilibrium = (matrix: SkewSymmetricMatrix): number[] => {\n  if (isZero(matrix)) return matrix.map(() => 1 / matrix.length)\n\n  const constraints: Record<string, Record<string, number>> = {\n    sum: { equal: 1 },\n  }\n  const variables: Record<string, Record<string, number>> = {}\n  for (let i = 0; i < matrix.length; i++) {\n    constraints[`p${i + 1}`] = { min: 0 }\n\n    const variable: Record<string, number> = { v: matrix[i][0], sum: 1 }\n    for (let j = 0; j < matrix.length; j++) variable[`p${j + 1}`] = matrix[i][j]\n    variables[`p${i + 1}`] = variable\n  }\n\n  const model = {\n    optimize: 'v',\n    opType: 'min',\n    constraints,\n    variables,\n  }\n\n  const result = solver.Solve(model)\n\n  const probabilities = []\n  for (let i = 0; i < matrix.length; i++)\n    probabilities.push(result[`p${i + 1}`] || 0)\n\n  return normalizeVector(probabilities)\n}\n","import { MatrixScoreMethod } from '../../classes/matrix-score-method'\nimport type { Matrix, ScoreObject } from '../../types'\n\nexport enum MinimaxVariant {\n  WinningVotes = 'WINNING_VOTES',\n  Margins = 'MARGINS',\n  PairwiseOpposition = 'PAIRWISE_OPPOSITION',\n}\n\nconst scoreXY = {\n  [MinimaxVariant.Margins]: (xOverY: number, yOverX: number) => xOverY - yOverX, // default\n  [MinimaxVariant.PairwiseOpposition]: (xOverY: number) => xOverY,\n  [MinimaxVariant.WinningVotes]: (xOverY: number, yOverX: number) =>\n    xOverY > yOverX ? xOverY : 0,\n}\n\nconst computeScores = (\n  matrix: Matrix,\n  variant: MinimaxVariant,\n  excludeTies: boolean,\n): ScoreObject => {\n  const s: ScoreObject = {}\n  for (const [c1Index, candidate] of matrix.candidates.entries()) {\n    s[candidate] = -Math.max(\n      ...(matrix.array[c1Index]\n        .map((yOverX, c2Index) => {\n          const xOverY = matrix.array[c2Index][c1Index]\n          return xOverY === yOverX && excludeTies\n            ? null\n            : scoreXY[variant](xOverY, yOverX)\n        })\n        .filter((_, c2Index) => c2Index !== c1Index)\n        .filter((v) => v !== null) as number[]),\n    )\n  }\n  return s\n}\n\n/**\n * #### Wikipedia: [Minimax Condorcet method](https://en.wikipedia.org/wiki/Minimax_Condorcet_method)\n */\nexport class Minimax extends MatrixScoreMethod {\n  public minimaxVariant: MinimaxVariant\n  public excludeTies: boolean\n\n  public static Variants = MinimaxVariant\n\n  constructor(i: Matrix & { variant?: MinimaxVariant; excludeTies?: boolean }) {\n    super(i)\n    this.minimaxVariant = i.variant || MinimaxVariant.Margins\n    this.excludeTies = i.excludeTies || false\n  }\n\n  public scores(): ScoreObject {\n    return computeScores(this.matrix, this.minimaxVariant, this.excludeTies)\n  }\n}\n","import _ from 'lodash-es'\n\nimport type { Matrix, ScoreObject } from '../../types'\nimport { findSmithSet } from '../../utils/condorcet'\nimport { scoresAny } from '../../utils/scores-zero'\nimport type { MinimaxVariant } from '../minimax'\nimport { Minimax } from '../minimax'\n\nconst computeScores = (\n  matrix: Matrix,\n  variant: MinimaxVariant,\n  excludeTies: boolean,\n): ScoreObject => {\n  const minimax = new Minimax({ ...matrix, variant, excludeTies })\n  const smithSet = findSmithSet(matrix)\n  const minimaxScores = minimax.scores()\n  const smithSetScores = _.pick(minimaxScores, smithSet.candidates)\n  const smithSetScoresMin = Math.min(...Object.values(smithSetScores))\n  return {\n    // give all non-Smith-set candidates a score worse than the worst of the Smith set\n    ...scoresAny(matrix.candidates, Math.min(smithSetScoresMin, 0) * 2 - 1),\n    ...smithSetScores,\n  }\n}\n\n/**\n * Requested in https://github.com/lzear/votes/issues/76\n *\n * The Minimax-TD process:\n * 1. Do the pairwise comparisons using Margins (the number of voters ranking X above Y minus the number of voters ranking Y above X. )\n * 1. Find the [Smith Set](https://en.wikipedia.org/wiki/Smith_set), the smallest non-empty set of candidates such that each member defeats every candidate outside the set in a pairwise comparison. [That Algorithm may be found here.](https://electowiki.org/wiki/Maximal_elements_algorithms)\n * 1. If there is one member of the Smith set, that is the winner.\n * 1. If there are multiple members of the Smith set, using Margins [Minimax method](https://en.wikipedia.org/wiki/Minimax_Condorcet_method), the candidate in the Smith set with the lowest 'worst pairwise defeat' (which can be negative, equivalent to the lowest 'worst pairwise victory' if there are no defeats) is the winner. See examples below...\n * 1. Remove the winner and repeat the process to find each successive place (2nd, 3rd, etc)\n *\n * #### Example 1:\n *\n * A, B, and C are the members of the Smith set.\n *\n * - A beat B: 58% to 42%. (16% margin)\n * - B beat C: 68% to 32% (36% margin)\n * - C beat A: 70% to 30%. (40% margin)\n * - A beat D: 55% to 45%. (10% margin)\n * - B beat D: 60% to 40%. (20% margin)\n * - C beat D: 99% to 1%. (98% margin)\n *\n * Look for the lowest 'worst pairwise defeat' in all of the comparisons (not just within the smith set):\n * - A's 'worst pairwise defeat' is 40% margin against C (70%-30%)\n * - B's 'worst pairwise defeat' is 16% margin against A (58%-42%)\n * - C's 'worst pairwise defeat' is 36% margin against B (68%-32%)\n *\n * B has the smallest 'worst pairwise defeat', therefore B is the winner.\n *\n * #### Example 2:\n *\n * A and B are the members of the Smith set. Both of them beat every other candidate but they tied each other.\n * - A tied B: 50% to 50% (0% margin)\n * - A beat C: 68% to 32% (36% margin)\n * - A beat D: 99% to 1% (98% margin)\n * - B beat C: 70% to 30% (40% margin)\n * - B beat D: 60% to 40% (20% margin)\n * - C beat D: 55% to 45% (10% margin)\n *\n * Look for the lowest 'worst pairwise defeat', and since there are no defeats, look for the lowest 'worst pairwise victory' (not just within the smith set):\n * - A's 'worst pairwise victory' is -36% margin against C (32% -68%)\n * - B's 'worst pairwise victory' is -20% margin against C (40% -60%)\n *\n * A has the lowest \"worst pairwise victory\" against all the candidates, therefore A is the winner.\n */\nexport class MinimaxTD extends Minimax {\n  public scores(): ScoreObject {\n    return computeScores(this.matrix, this.minimaxVariant, this.excludeTies)\n  }\n}\n","import _ from 'lodash-es'\n\nimport { RoundBallotMethod } from '../../classes/round-ballot-method'\nimport type { Ballot, ScoreObject } from '../../types'\nimport { Borda } from '../borda'\n\nconst round = (\n  candidates: string[],\n  ballots: Ballot[],\n): {\n  qualified: string[]\n  eliminated: string[]\n  scores: ScoreObject\n} => {\n  const borda = new Borda({ candidates, ballots })\n  const bordaScores = borda.scores()\n  const scores = Object.values(bordaScores)\n  const avg = _.sum(scores) / scores.length\n  const eliminated = candidates.filter((c) => bordaScores[c] <= avg)\n  const qualified = _.difference(candidates, eliminated)\n  return { eliminated, qualified, scores: bordaScores }\n}\n\n/**\n * #### Wikipedia: [Nanson's method](https://en.wikipedia.org/wiki/Nanson%27s_method)\n */\nexport class Nanson extends RoundBallotMethod {\n  protected round(candidates: string[]): {\n    qualified: string[]\n    eliminated: string[]\n    scores: ScoreObject\n  } {\n    return round(candidates, this.ballots)\n  }\n}\n","import { zipObject } from 'lodash-es'\n\nimport { RandomMethod } from '../../classes/random-method'\nimport type { ScoreObject } from '../../types'\nimport { shuffleArray } from '../../utils/shuffle-array'\n\n/**\n * Pick a candidate at random, regardless of the ballots\n */\nexport class RandomCandidates extends RandomMethod {\n  public ranking(): string[][] {\n    return shuffleArray(this.candidates, this.rng).map((c) => [c])\n  }\n\n  public scores(): ScoreObject {\n    return zipObject(\n      this.candidates,\n      new Array(this.candidates.length).fill(1 / this.candidates.length),\n    )\n  }\n}\n","import type { Ballot } from '../types'\n\nimport { BallotMethod } from './ballot-method'\nimport type { Ranker } from './method'\n\nexport abstract class RandomBallotMethod\n  extends BallotMethod\n  implements Ranker\n{\n  public static readonly isRandom = true\n\n  protected readonly rng: () => number\n\n  protected constructor(i: {\n    candidates: string[]\n    ballots: Ballot[]\n    rng?: () => number\n  }) {\n    super(i)\n\n    this.rng = i.rng || Math.random\n  }\n\n  public abstract ranking(): string[][]\n}\n","import { RandomBallotMethod } from '../../classes/random-ballot-method'\nimport type { Ballot } from '../../types'\nimport { totalBallotsWeight } from '../../utils/normalize'\n\nconst pickBallotIdx = (ballots: Ballot[], ratio: number) => {\n  const W = totalBallotsWeight(ballots)\n  const pickAt = ratio * W\n  let w = 0\n  let i = 0\n\n  while (w < pickAt) {\n    const b = ballots[i] as Ballot | undefined\n    if (!b) throw new Error('Could not pick a ballot?!')\n    w += b.weight\n    if (w >= pickAt) return i\n    i++\n  }\n  throw new Error('Could not pick a ballot?!')\n}\n\nconst rank = (candidates: string[], ballots: Ballot[], rng: () => number) => {\n  if (candidates.length === 0) return []\n  if (ballots.length === 0) return [candidates]\n\n  const ratio = rng()\n  const idx = pickBallotIdx(ballots, ratio)\n  return ballots[idx].ranking\n}\n\nexport class RandomDictator extends RandomBallotMethod {\n  constructor(i: {\n    ballots: Ballot[]\n    candidates: string[]\n    rng?: () => number\n  }) {\n    super(i)\n  }\n\n  public ranking(): string[][] {\n    return rank(this.candidates, this.ballots, this.rng)\n  }\n}\n","import { RandomMatrixMethod } from '../../classes/random-matrix-method'\nimport type { Matrix, ScoreObject } from '../../types'\nimport { makeAntisymetric } from '../../utils'\nimport { computeLottery } from '../maximal-lotteries'\n\nconst computeScores = (matrix: Matrix): ScoreObject => {\n  const antisymetric = makeAntisymetric(matrix)\n  const antisymetricUnit = {\n    ...antisymetric,\n    array: antisymetric.array.map((r) => r.map((v) => Math.sign(v))),\n  }\n  return computeLottery(antisymetricUnit)\n}\n\nexport class RandomizedCondorcet extends RandomMatrixMethod {\n  public scores(): ScoreObject {\n    return computeScores(this.matrix)\n  }\n}\n","import { groupBy, range, zipObject } from 'lodash-es'\n\nimport { MatrixScoreMethod } from '../../classes/matrix-score-method'\nimport type { Matrix, ScoreObject } from '../../types'\n\nimport { generateAcyclicGraph } from './generate-acyclic-graph'\n\ntype Edge = { from: number; to: number; value: number }\n\nconst computeFromMatrix = (matrix: Matrix): ScoreObject => {\n  const allEdges: Edge[] = matrix.array.flatMap(\n    (row, from) =>\n      row\n        .map((value, to) =>\n          value > 0 && to !== from ? { from, to, value } : null,\n        )\n        .filter(Boolean) as Edge[],\n  )\n  const edgesGroups = groupBy(allEdges, 'value')\n  const groups = Object.keys(edgesGroups)\n    .sort((a, b) => Number(b) - Number(a))\n    .map((value) => edgesGroups[value])\n\n  const acyclicGraph = groups.reduce(\n    (graph: Edge[], edgesToAdd) => generateAcyclicGraph(graph, edgesToAdd),\n    [] as Edge[],\n  )\n  const graphsWinners = range(matrix.candidates.length).filter(\n    (candidate, key) => !acyclicGraph.some(({ to }) => to === key),\n  )\n  const scores = graphsWinners.reduce((acc, curr) => {\n    acc[curr] = (acc[curr] || 0) + 1\n    return acc\n  }, {} as { [k: number]: number })\n  const maxScore1 = Math.max(...Object.values(scores))\n  const winnersIdx = range(matrix.candidates.length).filter(\n    (i) => scores[i] === maxScore1,\n  )\n  if (winnersIdx.length === matrix.candidates.length)\n    return zipObject(\n      matrix.candidates,\n      new Array(matrix.candidates.length).fill(1),\n    )\n  const nextResults = computeFromMatrix({\n    array: matrix.array\n      .filter((c, k) => !winnersIdx.includes(k))\n      .map((row) => row.filter((c, k) => !winnersIdx.includes(k))),\n    candidates: matrix.candidates.filter((c, k) => !winnersIdx.includes(k)),\n  })\n  const maxScore2 = Math.max(...Object.values(nextResults))\n  return winnersIdx.reduce(\n    (scoreObject, winnerIdx) => ({\n      ...scoreObject,\n      [matrix.candidates[winnerIdx]]: maxScore2 + 1,\n    }),\n    nextResults,\n  )\n}\n\n/**\n * #### Wikipedia: [Ranked pairs](https://en.wikipedia.org/wiki/Ranked_pairs)\n */\nexport class RankedPairs extends MatrixScoreMethod {\n  public scores(): ScoreObject {\n    return computeFromMatrix(this.matrix)\n  }\n}\n","import { range } from 'lodash-es'\n\nimport { MatrixScoreMethod } from '../../classes/matrix-score-method'\nimport type { Matrix, ScoreObject } from '../../types'\n\nconst computeFromMatrix = (matrix: Matrix): ScoreObject => {\n  const n = matrix.candidates.length\n  const p: number[][] = range(n).map(() => range(n).map(() => 0))\n\n  for (let i = 0; i < n; i++)\n    for (let j = 0; j < n; j++)\n      if (i !== j)\n        p[i][j] =\n          matrix.array[i][j] > matrix.array[j][i] ? matrix.array[i][j] : 0\n\n  for (let i = 0; i < n; i++)\n    for (let j = 0; j < n; j++)\n      if (i !== j)\n        for (let k = 0; k < n; k++)\n          if (i !== k && j !== k)\n            p[j][k] = Math.max(p[j][k], Math.min(p[j][i], p[i][k]))\n\n  const s: ScoreObject = {}\n  for (const [k, c] of matrix.candidates.entries())\n    s[c] = p[k].filter((v, k2) => v > p[k2][k]).length\n\n  return s\n}\n\n/**\n * #### Wikipedia: [Schulze method](https://en.wikipedia.org/wiki/Schulze_method)\n */\nexport class Schulze extends MatrixScoreMethod {\n  public scores(): ScoreObject {\n    return computeFromMatrix(this.matrix)\n  }\n}\n","import { MatrixScoreMethod } from '../../classes/matrix-score-method'\nimport type { Matrix, ScoreObject } from '../../types'\nimport { findSmithSet } from '../../utils/condorcet'\nimport { scoresAny } from '../../utils/scores-zero'\n\nconst computeScores = (matrix: Matrix): ScoreObject => {\n  const smithSet = findSmithSet(matrix)\n  return {\n    // give all non-Smith-set candidates a score of 0\n    // and all the Smith set a score of 1\n    ...scoresAny(matrix.candidates, 0),\n    ...scoresAny(smithSet.candidates, 1),\n  }\n}\n\n/**\n * #### Wikipedia: [Smith's method](https://en.wikipedia.org/wiki/Smith_set#Smith's_method)\n */\nexport class Smith extends MatrixScoreMethod {\n  public scores(): ScoreObject {\n    return computeScores(this.matrix)\n  }\n}\n","import _ from 'lodash-es'\n\nimport { RoundBallotMethod } from '../../classes/round-ballot-method'\nimport type { ScoreObject } from '../../types'\nimport { AbsoluteMajority } from '../absolute-majority'\nimport { FirstPastThePost } from '../first-past-the-post'\n\n/**\n * #### Wikipedia: [Two-round system](https://en.wikipedia.org/wiki/Two-round_system)\n */\nexport class TwoRoundRunoff extends RoundBallotMethod {\n  protected round(\n    candidates: string[],\n    idx: number,\n  ): {\n    eliminated: string[]\n    qualified: string[]\n    scores: ScoreObject\n  } {\n    const scores: ScoreObject = new FirstPastThePost({\n      ballots: this.ballots,\n      candidates,\n    }).scores()\n\n    const absoluteMajority = new AbsoluteMajority({\n      ballots: this.ballots,\n      candidates,\n    })\n    if (absoluteMajority.ranking().length > 1) {\n      const qualified = absoluteMajority.ranking()[0]\n      if (!qualified)\n        throw new Error('Unexpected error in absolute majority computation')\n\n      return {\n        eliminated: _.difference(candidates, qualified),\n        qualified,\n        scores,\n      }\n    }\n    const scoreValues = Object.values(scores).sort((a, b) => b - a)\n\n    if (idx === 0) {\n      const qualified = candidates.filter((c) => scores[c] >= scoreValues[1])\n      return {\n        eliminated: _.difference(candidates, qualified),\n        qualified,\n        scores,\n      }\n    }\n    if (idx === 1) {\n      const qualified = candidates.filter((c) => scores[c] >= scoreValues[0])\n      return {\n        eliminated: _.difference(candidates, qualified),\n        qualified,\n        scores,\n      }\n    }\n    return {\n      eliminated: candidates,\n      qualified: [],\n      scores,\n    }\n  }\n}\n","import { VotingSystem } from '../types'\n\nimport { AbsoluteMajority } from './absolute-majority'\nimport { Approbation } from './approbation'\nimport { Baldwin } from './baldwin'\nimport { Borda } from './borda'\nimport { BottomTwoRunoff } from './bottom-two-runoff'\nimport { Coombs } from './coombs'\nimport { Copeland } from './copeland'\nimport { FirstPastThePost } from './first-past-the-post'\nimport { InstantRunoff } from './instant-runoff'\nimport { Kemeny } from './kemeny'\nimport { MajorityJudgment } from './majority-judgment'\nimport { MaximalLotteries } from './maximal-lotteries'\nimport { Minimax } from './minimax'\nimport { MinimaxTD } from './minimax-td'\nimport { Nanson } from './nanson'\nimport { RandomCandidates } from './random-candidates'\nimport { RandomDictator } from './random-dictator'\nimport { RandomizedCondorcet } from './randomized-condorcet'\nimport { RankedPairs } from './ranked-pairs'\nimport { Schulze } from './schulze'\nimport { Smith } from './smith'\nimport { TwoRoundRunoff } from './two-round-runoff'\n\nexport const methods = {\n  [VotingSystem.AbsoluteMajority]: AbsoluteMajority,\n  [VotingSystem.Approbation]: Approbation,\n  [VotingSystem.Baldwin]: Baldwin,\n  [VotingSystem.Borda]: Borda,\n  [VotingSystem.BottomTwoRunoff]: BottomTwoRunoff,\n  [VotingSystem.Coombs]: Coombs,\n  [VotingSystem.Copeland]: Copeland,\n  [VotingSystem.FirstPastThePost]: FirstPastThePost,\n  [VotingSystem.InstantRunoff]: InstantRunoff,\n  [VotingSystem.Kemeny]: Kemeny,\n  [VotingSystem.MajorityJudgment]: MajorityJudgment,\n  [VotingSystem.MaximalLotteries]: MaximalLotteries,\n  [VotingSystem.Minimax]: Minimax,\n  [VotingSystem.MinimaxTD]: MinimaxTD,\n  [VotingSystem.Nanson]: Nanson,\n  [VotingSystem.RandomCandidates]: RandomCandidates,\n  [VotingSystem.RandomDictator]: RandomDictator,\n  [VotingSystem.RandomizedCondorcet]: RandomizedCondorcet,\n  [VotingSystem.RankedPairs]: RankedPairs,\n  [VotingSystem.Schulze]: Schulze,\n  [VotingSystem.Smith]: Smith,\n  [VotingSystem.TwoRoundRunoff]: TwoRoundRunoff,\n} as const\n\nexport type Methods = (typeof methods)[keyof typeof methods]\n","import { type Methods, methods } from '../methods'\nimport type { VotingSystem } from '../types'\n\ntype MethodsContaining<\n  StaticProp extends 'isRandom' | 'needsBallot' | 'needsMatrix',\n  Method,\n> = Method extends Methods\n  ? Method[StaticProp] extends true\n    ? Method\n    : never\n  : never\n\ntype SystemsBeing<\n  MethodType extends Methods,\n  System,\n> = System extends VotingSystem\n  ? (typeof methods)[System] extends MethodType\n    ? System\n    : never\n  : never\n\nexport type RandomMethods = MethodsContaining<'isRandom', Methods>\nexport type BallotMethods = MethodsContaining<'needsBallot', Methods>\nexport type MatrixMethods = MethodsContaining<'needsMatrix', Methods>\n\nexport type RandomSystem = SystemsBeing<RandomMethods, VotingSystem>\nexport type BallotSystem = SystemsBeing<BallotMethods, VotingSystem>\nexport type MatrixSystem = SystemsBeing<MatrixMethods, VotingSystem>\n\nexport const isRandomMethod = (Method: Methods): Method is RandomMethods =>\n  Method.isRandom\nexport const isBallotMethod = (Method: Methods): Method is BallotMethods =>\n  Method.needsBallot\nexport const isMatrixMethod = (Method: Methods): Method is MatrixMethods =>\n  Method.needsMatrix\n\nexport const isRandomSystem = (system: VotingSystem): system is RandomSystem =>\n  isRandomMethod(methods[system])\nexport const isBallotSystem = (system: VotingSystem): system is BallotSystem =>\n  isBallotMethod(methods[system])\nexport const isMatrixSystem = (system: VotingSystem): system is MatrixSystem =>\n  isMatrixMethod(methods[system])\n"],"mappings":"8kBAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,sBAAAE,EAAA,gBAAAC,EAAA,YAAAC,EAAA,UAAAC,EAAA,oBAAAC,EAAA,WAAAC,EAAA,aAAAC,EAAA,qBAAAC,EAAA,kBAAAC,EAAA,WAAAC,EAAA,qBAAAC,EAAA,qBAAAC,EAAA,YAAAC,EAAA,cAAAC,EAAA,mBAAAC,GAAA,WAAAC,EAAA,qBAAAC,EAAA,mBAAAC,EAAA,wBAAAC,EAAA,gBAAAC,EAAA,YAAAC,GAAA,UAAAC,GAAA,mBAAAC,GAAA,iBAAAC,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,mBAAAC,GAAA,YAAAC,GAAA,UAAAC,KAAA,eAAAC,GAAAlC,ICYO,IAAKmC,QACVA,EAAA,YAAc,cACdA,EAAA,iBAAmB,oBACnBA,EAAA,QAAU,UACVA,EAAA,MAAQ,QACRA,EAAA,gBAAkB,oBAClBA,EAAA,OAAS,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L,WAAY,GAAAD,QAAE,WAAWP,EAAYM,CAAS,EAC9C,UAAAA,EACA,OAAAJ,CACF,CACF,CACA,GAAID,IAAQ,EAAG,CACb,IAAMK,EAAYN,EAAW,OAAQW,GAAMT,EAAOS,CAAC,GAAKH,EAAY,CAAC,CAAC,EACtE,MAAO,CACL,WAAY,GAAAD,QAAE,WAAWP,EAAYM,CAAS,EAC9C,UAAAA,EACA,OAAAJ,CACF,CACF,CACA,MAAO,CACL,WAAYF,EACZ,UAAW,CAAC,EACZ,OAAAE,CACF,CACF,CACF,ECtCO,IAAMU,GAAU,CACpB,kBAAgCC,EAChC,YAA2BC,EAC3B,QAAuBC,EACvB,MAAqBC,EACrB,kBAA+BC,EAC/B,OAAsBC,EACtB,SAAwBC,EACxB,oBAAgCC,EAChC,eAA6BC,EAC7B,OAAsBC,EACtB,mBAAgCC,EAChC,kBAAgCC,EAChC,QAAuBC,EACvB,WAAyBC,EACzB,OAAsBC,EACtB,kBAAgCC,EAChC,gBAA8BC,EAC9B,qBAAmCC,EACnC,aAA2BC,EAC3B,QAAuBC,GACvB,MAAqBC,GACrB,iBAA8BC,EACjC,ECnBO,IAAMC,GAAkBC,GAC7BA,EAAO,SACIC,GAAkBD,GAC7BA,EAAO,YACIE,GAAkBF,GAC7BA,EAAO,YAEIG,GAAkBC,GAC7BL,GAAeM,GAAQD,CAAM,CAAC,EACnBE,GAAkBF,GAC7BH,GAAeI,GAAQD,CAAM,CAAC,EACnBG,GAAkBH,GAC7BF,GAAeG,GAAQD,CAAM,CAAC","names":["src_exports","__export","AbsoluteMajority","Approbation","Baldwin","Borda","BottomTwoRunoff","Coombs","Copeland","FirstPastThePost","InstantRunoff","Kemeny","MajorityJudgment","MaximalLotteries","Minimax","MinimaxTD","MinimaxVariant","Nanson","RandomCandidates","RandomDictator","RandomizedCondorcet","RankedPairs","Schulze","Smith","TwoRoundRunoff","VotingSystem","isBallotMethod","isBallotSystem","isMatrixMethod","isMatrixSystem","isRandomMethod","isRandomSystem","methods","utils_exports","__toCommonJS","VotingSystem","import_lodash_es","matrixFromBallots","ballots","candidates","array","ranking","rIndex","rank","c","rankedLower","w","l","makeAntisymetric","matrix","values","row","v","col","import_lodash_es","scoresToRanking","scores","e","f","import_lodash_es","Method","candidates","rankingToTieBreak","scores","acc","rank","idx","_","scoresToRanking","ScoreMethod","Method","scoresToRanking","BallotScoreMethod","ScoreMethod","ballots","candidates","matrixFromBallots","import_lodash_es","isBallotEqual","a","b","_","rank","k","normalizeRankInput","rankInput","groupBallots","ballots","acc","ballot","match","toWeightedBallots","w","ww","checkDuplicatedCandidate","ranking","inter","removeDuplicatedCandidates","cur","unique","removeInvalidCandidates","candidates","names","name","normalizeRanking","normalizeBallot","candidatesFromBallots","curr","normalizeBallots","c","totalBallotsWeight","import_lodash_es","scoresAny","candidates","value","scoresZero","iterateFirstChoices","ballots","candidates","computeBallotScore","iterateNthChoices","rankIdx","result","scoresZero","ballot","normalizeBallots","votes","c","candidate","computeScores","candidates","ballots","iterateFirstChoices","rank","FirstPastThePost","BallotScoreMethod","AbsoluteMajority","BallotScoreMethod","totalWeight","totalBallotsWeight","fptp","FirstPastThePost","topRank","fptpScores","scoresZero","Approbation","BallotScoreMethod","iterateFirstChoices","import_lodash_es","arrayAt","array","at","BallotMethod","Method","ballots","candidates","matrixFromBallots","RoundBallotMethod","BallotMethod","eliminated","previousRound","arrayAt","candidates","idx","round","computeScores","candidates","_ballots","scores","scoresZero","ballots","normalizeBallots","ballot","voteValue","candidatesAtRank","value","candidate","Borda","BallotScoreMethod","round","candidates","ballots","borda","Borda","ranking","eliminated","arrayAt","qualified","_","Baldwin","RoundBallotMethod","import_lodash_es","import_lodash_es","deTie","ranking","ballots","rank","scores","iterateFirstChoices","r","pickedScores","_","groups","c","a","b","score","isTied","BiggestSupport","BallotMethod","rankIdx","import_lodash_es","MatrixScoreMethod","ScoreMethod","i","computeFromMatrix","matrix","n","p","_","i","j","scores","m","acc","cur","Copeland","MatrixScoreMethod","BottomTwoRunoff","RoundBallotMethod","i","Copeland","matrixFromBallots","candidates","biggestSupport","BiggestSupport","normalizeBallots","leastSupport","arrayAt","bottom","leastSupport2","eliminated","_","scoresAny","import_lodash_es","utils_exports","__export","candidatesFromBallots","checkDuplicatedCandidate","findCondorcet","findSmithSet","generateAcyclicGraph","groupBallots","makeAntisymetric","matrixFromBallots","normalizeBallot","normalizeBallots","normalizeRankInput","normalizeRanking","removeDuplicatedCandidates","removeInvalidCandidates","scoresToRanking","toWeightedBallots","import_lodash_es","VertexStack","vertex","i","Tarjan","graph","VertexStack","i","vertex","connection","v","w","vertices","Vertex","name","vertex","generateAcyclicGraph","graph","edgesToAdd","allEdges","vDict","c","_","e","Vertex","Tarjan","edge","import_lodash_es","findSmithSet","_matrix","candidates","array","makeAntisymetric","dominatingDirectList","_c","k","_v","k2","dominatingList","c","dominating","toCheck","check","toAdd","_","row","k1","v","findCondorcet","reverseBallots","ballots","ballot","round","candidates","_ballots","scoresZero","normalizeBallots","absoluteMajority","AbsoluteMajority","qualified","_","reversedFptp","FirstPastThePost","eliminated","Coombs","RoundBallotMethod","round","candidates","ballots","normalizedBallots","normalizeBallots","round1","FirstPastThePost","minScore","qualified","InstantRunoff","RoundBallotMethod","import_lodash_es","rankingPenalty","ranking","matrix","p","i","j","nextPermutation","arr","array","temp","computeScores","bestPermutations","bestScore","s","sumIdx","c","cIdx","perm","v","Kemeny","MatrixScoreMethod","import_lodash_es","makeJudgement","candidates","ballots","judgements","_","ballot","rankIdx","rank","can","getMedian","arr","sumWeights","s","i","prevI","med","j","getMedians","medians","c","majorityJudgmentRanking","tieBreak","scoresToRanking","cs","median","minGroup","j2","jc","MajorityJudgment","BallotMethod","import_lodash_es","import_lodash_es","shuffleArray","_array","rng","array","m","t","r","RandomMethod","Method","i","randomRankingFromSores","scoreObject","random","candidates","sumScores","_","shuffleArray","normalizedScoreObject","s","pickAt","w","candidate","RandomMatrixMethod","RandomMethod","i","c","import_javascript_lp_solver","isZero","matrix","i","j","normalizeVector","vector","positive","v","sum","acc","cur","findNashEquilibrium","constraints","variables","variable","model","result","solver","probabilities","computeLottery","_matrix","matrix","makeAntisymetric","condorset","findSmithSet","solution","findNashEquilibrium","v","scoresZero","MaximalLotteries","RandomMatrixMethod","MinimaxVariant","scoreXY","xOverY","yOverX","computeScores","matrix","variant","excludeTies","s","c1Index","candidate","c2Index","_","v","Minimax","MatrixScoreMethod","i","import_lodash_es","computeScores","matrix","variant","excludeTies","minimax","Minimax","smithSet","findSmithSet","minimaxScores","smithSetScores","_","smithSetScoresMin","scoresAny","MinimaxTD","import_lodash_es","round","candidates","ballots","bordaScores","Borda","scores","avg","_","eliminated","qualified","Nanson","RoundBallotMethod","import_lodash_es","RandomCandidates","RandomMethod","shuffleArray","c","RandomBallotMethod","BallotMethod","i","pickBallotIdx","ballots","ratio","W","totalBallotsWeight","pickAt","w","b","rank","candidates","rng","idx","RandomDictator","RandomBallotMethod","i","computeScores","matrix","antisymetric","makeAntisymetric","antisymetricUnit","r","v","computeLottery","RandomizedCondorcet","RandomMatrixMethod","import_lodash_es","computeFromMatrix","matrix","allEdges","row","from","value","to","edgesGroups","acyclicGraph","a","b","graph","edgesToAdd","generateAcyclicGraph","scores","candidate","key","acc","curr","maxScore1","winnersIdx","i","nextResults","c","k","maxScore2","scoreObject","winnerIdx","RankedPairs","MatrixScoreMethod","import_lodash_es","computeFromMatrix","matrix","n","p","i","j","k","s","c","v","k2","Schulze","MatrixScoreMethod","computeScores","matrix","smithSet","findSmithSet","scoresAny","Smith","MatrixScoreMethod","import_lodash_es","TwoRoundRunoff","RoundBallotMethod","candidates","idx","scores","FirstPastThePost","absoluteMajority","AbsoluteMajority","qualified","_","scoreValues","a","b","c","methods","AbsoluteMajority","Approbation","Baldwin","Borda","BottomTwoRunoff","Coombs","Copeland","FirstPastThePost","InstantRunoff","Kemeny","MajorityJudgment","MaximalLotteries","Minimax","MinimaxTD","Nanson","RandomCandidates","RandomDictator","RandomizedCondorcet","RankedPairs","Schulze","Smith","TwoRoundRunoff","isRandomMethod","Method","isBallotMethod","isMatrixMethod","isRandomSystem","system","methods","isBallotSystem","isMatrixSystem"]}