Algorithmadvanced
Nucleolus by sequential linear programming
Also called Kopelowitz algorithm, Maschler-Peleg-Shapley procedure.
Computes the nucleolus of a TU game with a sequence of linear programs; each round minimizes the largest free excess and fixes the coalitions that stay tight on the whole optimal face.
- Time
- poly(2^n, L) worst
- Space
- O(4^n) extra
- Where
- L = the bit length of the coalition values; n = the number of players
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- A. Kopelowitz, Michael Maschler, Bezalel Peleg, Lloyd S. Shapley, 1967
The nucleolus of a TU game is the imputation whose worst excess is as small as possible, then whose second worst excess is as small as possible, and so on. This page is the algorithm that computes it. The definition and its properties are on the nucleolus page. The first round of the algorithm is the linear program of the least core; each later round solves a least core problem again, inside the set that the earlier rounds left. Kopelowitz described the method in 1967. With exact arithmetic it returns the exact nucleolus after at most rounds.
In plain words
Some players must share a sum of money, and every group of players can say how much it could earn alone. The complaint of a group is what it could earn alone minus what it gets in the shared plan. First find the plans that make the largest complaint as small as possible. This is one linear program. Some groups have this largest complaint in every one of those plans: nothing can make them happier without making a group at least as unhappy. Freeze their complaints at that level. Then, among the plans left, make the largest complaint of the other groups as small as possible, and freeze again. Each freeze fixes at least one more direction in which the plan can move. After at most one round fewer than the number of players, only one plan is left, and that plan is the nucleolus.
The problem
The input is a TU game : players and a value for each coalition , with . For a payoff vector let , and let the excess of at be , the amount by which is short of what it can earn alone. The imputations are the vectors with and for every . They exist exactly when . For an imputation let be the vector of the excesses of the coalitions with , sorted from the largest to the smallest. The output is the nucleolus, the imputation with the lexicographically smallest . Schmeidler proved that it exists and is unique. If the bounds are dropped, the same minimum over all with is the prenucleolus, and the algorithm computes it with the same steps.
The excesses of and are 0 at every imputation, so it makes no difference whether lists them. The input has numbers, so the algorithm is meant for games given as a full table. For games with a short description, see "Variants and improvements".
The algorithm
NUCLEOLUS(N, v)- 1
if v(N) < v({1}) + ... + v({n}): stop, the game has no imputation - 2
F ← all coalitions S with ∅ ≠ S ≠ N; E ← ∅ - 3
while the indicator vectors of N and of the coalitions in E have rank < n: - 4
t* ← min t over the imputations x with v(S) - x(S) = t_S for (S, t_S) in E and v(S) - x(S) ≤ t for S in F - 5
for each S in F: - 6
if the row of S has a nonzero dual value at L4, or max{x(S) : x optimal at L4} = v(S) - t*: - 7
remove S from F and add (S, t*) to E - 8
for each S in F: - 9
if the indicator vector of S is in the span of those of N and E: remove S from F - 10
return the unique x with x(N) = v(N) and x(S) = v(S) - t_S for every (S, t_S) in E
The set holds the free coalitions, whose excess the algorithm still tries to lower. The set holds the fixed coalitions, each with the level at which its excess is frozen. Line L4 is a linear program with the numbers and the level as variables. It finds the smallest possible largest free excess, , inside the set that the earlier rounds left. Its optimal points form a face of a polyhedron, and lines L5 to L7 freeze the free coalitions whose excess is on the whole face. Line L6 has two tests. A constraint with a nonzero dual value is tight at every optimal point, by complementary slackness, so it needs no more work. For the other coalitions, one more LP checks whether can be raised above , which would lower the excess of below somewhere on the face. Lines L8 and L9 drop the free coalitions whose excess is already a fixed number, because their indicator vector is a linear combination of fixed ones. Line L10 solves the final linear system.
The proof shows that at least one coalition is frozen in each round, and that its indicator vector is new. So the rank in line L3 grows by at least 1 per round, from 1 to .
Example
Take the bankruptcy problem with claims and an estate of . Its game gives a coalition what is left after it pays the claims of the others in full: . Here , , and every other coalition has value 0. Since every is 0, the imputations are the vectors with .
Round 1. The free excesses are , , , , and . A pair of players never has the largest excess, because its excess is below that of each of its members. The largest of and is smallest at , where both are . Then , and holds whenever both are at least 50. So , and the optimal face is . On the whole face, and have excess ; the others do not. Line L7 fixes both. Their indicators are and , and the span of these and has rank 2. No free coalition is in this span, so line L9 drops nothing.
Round 2. Now and . The free excesses are , , and . The largest is smallest at , so , and the face is that single point. Line L7 fixes and , the rank becomes 3, and line L9 drops and .
| round | fixed in this round | dropped | rank after the round | |
|---|---|---|---|---|
| 1 | , | none | 2 | |
| 2 | , | , | 3 |
Line L10 returns , the award of the Talmud rule for this estate. The excess vector is . The estates 100 and 300 give and , which are also Talmud awards.
A game with a one-round run is the glove game: player 1 owns a left glove, players 2 and 3 own right gloves, and a pair is worth 1. So when contains player 1 and at least one other player, and otherwise. Round 1 gives and fixes all five coalitions except , whose indicator is then in the span. Line L10 returns , the only point of the core. The three-player majority game, where every pair is worth 1, also takes one round: , the three pairs are fixed, and the result is .
Correctness
The file proofs/correctness.md has the full proof. It keeps the set of imputations that satisfy the fixed equations, and an invariant with three parts: the nucleolus is in ; the dropped coalitions have indicators in the fixed span and the free ones do not; and minimizes the sorted vector of free excesses over . The last part needs a small lemma. Adding the same numbers to two vectors does not change which of the two sorted vectors is lexicographically smaller. Then, in each round:
- the first entry of the sorted free excesses is the largest free excess, so is optimal at line L4;
- lines L5 to L7 fix exactly the free coalitions that are tight on the whole optimal face, and there is at least one, because the average of points that each loosen one coalition would loosen all of them and beat ;
- a fixed coalition was free, so its indicator was not in the span, and the rank grows.
When the rank reaches , the fixed equations have exactly one solution. Every point of solves them, and is in , so line L10 returns . The same lemma also gives the uniqueness of the nucleolus (Schmeidler's midpoint argument), which the proof includes.
Proof: The sequential LP returns the nucleolus after at most n - 1 roundsfull
Let be a TU game with players and . For a payoff vector write and . Let be the set of coalitions with , and . The base set is the set of imputations, , or, in the prenucleolus mode, the set of preimputations . For a set let be the vector of the numbers , , sorted in nonincreasing order, and . The nucleolus is the point of with the lexicographically smallest . Line L1 stops when , because then there is no imputation. From now on . If , then , , the rank test of line L3 fails at once, and line L10 returns . So let .
Lemma 1 (the nucleolus exists and is unique; Schmeidler 1969). The minimum of over exists and is attained at exactly one point.
Proof. Existence. Fix and let , where . A point of outside is worse than , so it suffices to minimize over . On , gives , and with this bounds every from above too. So is compact and nonempty. The -th entry is the -th largest of continuous functions, so it is continuous. Let and let be the set of minimizers of on . Each is nonempty and compact, and is the set of lexicographic minimizers.
Uniqueness. Let both be minimizers, so , and let . Then for every . List as with nonincreasing. Any excesses at sum to at most , and the same holds at , so
If , let be the first index with . The partial sums up to are equal, so and is lexicographically better than , which is impossible. So , every inequality above is an equation, and so for every . Subtracting consecutive equations gives for every , and in the same way . So and have the same excess at every coalition in , in particular at every singleton, and .
Lemma 2 (common entries do not change the order). Let be vectors of the same length and a third vector. Write for the concatenation. Then if and only if , where sort means nonincreasing order.
Proof. For a vector let be the number of entries . Let and differ first at position , with . For the entries at positions and later are below in both vectors, and the entries before are equal, so . At we get and . So sorted vectors compare as follows: exactly when at the largest where and differ, and the sorted vectors are equal exactly when . Since and , the two differences are the same function, and the comparison does not change.
The state. At the start of each round the code holds three disjoint sets that cover : the fixed pairs (a coalition with its level ), the free set and the dropped set . Let be the span of and the indicators , , and
Invariant. At the start of each round:
- ;
- every has , and no has ;
- minimizes over .
A consequence of part 2: for the excess is constant on . For this is the definition of . For , write ; then is the same for all .
Start. Line L2 sets , and . Part 1 holds by Lemma 1. For part 2, is the line of , and the indicator of a proper coalition has entries 0 and 1 and is not a multiple of . Part 3 is the definition of .
One round. Let the invariant hold and let (line L3).
The free set is not empty. The singleton indicators span , so some has . It is not in or , whose indicators are in , so it is in .
The LP of line L4 has an optimum. It minimizes over the pairs with and for . It is feasible, because contains . If it were unbounded, there would be a direction with , for and for every (in the imputation mode is bounded, so this case does not arise there). By the consequence above, for . Take any . The coalitions and are both in , and . Neither value is negative, so both are 0, and . So , which contradicts on the nonempty . So the LP has an optimal value , and
Let , the set of optimal . It is convex. The first entry of is , and minimizes on (part 3), so it minimizes the first entry too: .
Lines L5 to L7 move exactly the set . If the dual value of the row of is not zero, complementary slackness says that the row is tight at every optimal primal solution, because it holds between every primal optimum and every dual optimum; so . Otherwise line L6 maximizes over . This LP is bounded: the complement is in , and on either its excess is at most (if it is free) or constant (if it is in ), so is bounded above. On we have , that is, . So the maximum of equals exactly when on all of , that is, when . So line L7 moves if and only if .
is not empty. Suppose it is. Then for each there is with . Let be the average of the points . It is in by convexity. For each , is the average of the numbers , which are all , and one of them, , is . So for every in the finite set , and . This contradicts the definition of .
The rank grows. Every is in , so by part 2. Adding the pairs , , to therefore raises the rank of by at least 1.
Lines L8 and L9 move to every remaining free coalition whose indicator is in the new span . Let , , and be the new state, so . We check the invariant.
Part 1: , and every has excess on , so .
Part 2 holds by the construction of lines L8 and L9, since the old members of had indicators in .
Part 3. Take . We show . Note that , and that gives for all .
- If , some has . This is not in , where the excess is on . It is not in either, because there the excess is constant on and so equals . So , and the first entry of is , while every entry of is . So is strictly better.
- If , split . On the excesses on are all and those on are constant, so and have the same entries there. Part 3 for the old state gives , since . By Lemma 2 we may delete the common entries, which gives .
So the invariant holds at the start of the next round.
Theorem. The algorithm stops after at most rounds and line L10 returns .
Proof. The rank of starts at 1, grows by at least 1 in each round and never exceeds , so line L3 ends the loop after at most rounds. At the end , so the system , for has at most one solution. Every point of solves it, and by part 1. So the system has exactly one solution, , and line L10 returns it. In the imputation mode the bounds are not part of this system, but they hold at because .
Remarks.
- The levels do not increase from one round to the next. At the end of a round every free excess at is at most , and is feasible for the next LP.
- The code writes the LP in the form of the shared simplex code, where every variable is nonnegative. In the imputation mode it uses with , and in the prenucleolus mode with . The level is . All numbers are fractions, so the tests $t^* = $ value and dual are exact.
- The tests in
impl/python/test_nucleolus_sequential_lp.pycheck the result against a brute force over a fine grid of imputations for 3 and 4 players, against Kohlberg's criterion for the prenucleolus (every set of coalitions with excess at least a given level is balanced), against the Talmud values, and the bound of rounds.
Complexity
The loop runs at most times. Each round solves one LP at line L4 and at most LPs at line L6, so there are at most LPs in total. Each has variables and at most constraints. With a polynomial LP method, such as the ellipsoid method or an interior point method, each LP takes time polynomial in and the bit length of the values, so the whole run is polynomial in the size of the table, which already has entries. The span tests of lines L8 and L9 are Gaussian elimination on vectors of length , operations per coalition with the reduced rows kept up to date.
The code uses the shared exact simplex method with Bland's rule and fractions, so it is exact but not polynomial in the worst case; on the small tables of the tests it is fast. Its tableau is dense, with one slack column per constraint, which takes numbers; this is the space bound in the front matter. A sparse LP solver needs only . Most of the LPs of line L6 are not needed in practice: a basic optimal dual solution gives many tight coalitions at once, and a coalition whose excess is below at the optimal point of line L4 is clearly not tight on the whole face.
Properties
- Exact. All numbers are fractions, so the tests "dual is nonzero" and "the maximum equals " have no tolerance. With floating point, a coalition that is tight only up to rounding can be fixed by mistake, and the final system can become inconsistent.
- Levels do not increase. The values of the rounds form a nonincreasing sequence, and they are entries of : the largest is , the least core value.
- Covariant. If for and an additive game , the run on makes the same choices and returns . The tests check this.
- Symmetric. Renaming the players renames the result; equal players get equal payoffs.
- In the core when the core is not empty. Then in round 1, so every excess at the result is at most 0, and the result is in the core.
Variants and improvements
- Prenucleolus. Drop the bounds from line L4 and the check of line L1. The proof is the same. For games where the core is not empty, the nucleolus and the prenucleolus are equal, because both are in the core.
- Fewer LPs. In a strictly complementary pair of optimal primal and dual solutions, the coalitions with a nonzero dual value are exactly the coalitions that are tight on the whole optimal face. So a solver that returns such a pair, as interior point methods do, makes the extra LPs of line L6 unnecessary.
- One balancedness check. Kohlberg's criterion characterizes the prenucleolus: is the prenucleolus exactly when, for every level , the coalitions with excess at least form a balanced collection. It does not give a fast algorithm, but it is a good certificate; the tests use it to check the prenucleolus mode.
- Compact games. When the game has a short description, the exponential number of constraints can be handled by a separation oracle and the ellipsoid method. Faigle, Kern and Kuipers (2001) show that the nucleolus can then be computed in polynomial time when the separation problem of the least core can be solved in polynomial time, and they apply this to convex games. For assignment games, Solymosi and Raghavan give a direct polynomial algorithm. For minimum cost spanning tree games the nucleolus is NP-hard to compute (Faigle, Kern and Kuipers 1998).
- Bankruptcy games. The nucleolus of a bankruptcy game is the Talmud rule, which runs in time; there is no need for LPs.
When to use it
Use the sequential LP when the game is given as a full table of values, is small, and you need the exact nucleolus or prenucleolus. It is the reference method to test special algorithms against, as the tests of the Talmud rule do. For larger games use a structure of the game: a polynomial special algorithm, or constraint generation when the largest excess can be found by a combinatorial search.
Pitfalls
- Fixing every coalition that is tight at one optimal point. A coalition can have excess at the point that the solver returns but less elsewhere on the face. Fixing it at cuts the face and can exclude the nucleolus. Only fix a coalition that is tight on the whole face (line L6).
- Forgetting the dependent coalitions. If a free coalition with a fixed excess stays in , a later round can return equal to its constant excess and fix only that coalition. The round then does not raise the rank, and the bound of rounds is lost. Line L9 prevents this.
- Nucleolus and prenucleolus mixed up. They can differ when the core is empty. In the game with , , , and , the prenucleolus is , which gives player 1 less than it can get alone, while the nucleolus is .
- No imputation. If , the nucleolus does not exist, but the prenucleolus does. The code raises an error in the first case and computes the prenucleolus on request.
- Floating point tolerances. With a floating point solver, compare with a tolerance that scales with the values, and check the result at the end by Kohlberg's criterion.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Exact linear programming in Fraction, by the two-phase simplex method with Bland's rule.
lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None) maximizes c x subject to A_ub x <= b_ub,
A_eq x = b_eq and x >= 0. lp_min does the same for minimization. Free variables must be
split by the caller (x = x+ - x-). Every input number is converted to Fraction, so the
result is exact: there is no tolerance anywhere.
Both functions return (status, x, value, dual). status is "optimal", "infeasible" or
"unbounded". When status is not "optimal", x, value and dual are None. dual has one entry
per constraint, the A_ub rows first and then the A_eq rows. It is the vector of shadow
prices: the value is sum_i b_i dual_i (strong duality). For lp_max, dual_i >= 0 on the
A_ub rows and A^T dual >= c. For lp_min, dual_i <= 0 on the A_ub rows and A^T dual <= c.
The entries for the A_eq rows have no sign condition.
Bland's rule (the smallest improving column enters, and among the rows with the smallest
ratio the one with the smallest basic variable leaves) makes the method finite on every
input, degenerate inputs included. There is no game algorithm in this module.
"""
from fractions import Fraction
def _frac(v):
return v if isinstance(v, Fraction) else Fraction(v)
def _pivot(T, obj, basis, r, j):
p = T[r][j]
row = [v / p for v in T[r]]
T[r] = row
for k in range(len(T)):
f = T[k][j]
if k != r and f != 0:
T[k] = [a - f * b for a, b in zip(T[k], row)]
f = obj[j]
if f != 0:
obj[:] = [a - f * b for a, b in zip(obj, row)]
basis[r] = j
def _simplex(T, obj, basis, ncols):
"""Maximize. obj[j] is the reduced cost of column j and obj[-1] is minus the value."""
while True:
enter = next((j for j in range(ncols) if obj[j] > 0), None)
if enter is None:
return "optimal"
best = None
for r, row in enumerate(T):
a = row[enter]
if a > 0:
key = (row[-1] / a, basis[r])
if best is None or key < best[0]:
best = (key, r)
if best is None:
return "unbounded"
_pivot(T, obj, basis, best[1], enter)
def _objective_row(cost, T, basis):
obj = list(cost) + [Fraction(0)]
for r, j in enumerate(basis):
f = obj[j]
if f != 0:
obj = [a - f * b for a, b in zip(obj, T[r])]
return obj
def _any_solution(M, rhs, nvars):
"""Return one solution y of M y = rhs (a consistent system), with the free variables 0."""
rows = [list(M[k]) + [rhs[k]] for k in range(len(M))]
pivots = []
r = 0
for col in range(nvars):
p = next((k for k in range(r, len(rows)) if rows[k][col] != 0), None)
if p is None:
continue
rows[r], rows[p] = rows[p], rows[r]
pv = rows[r][col]
rows[r] = [v / pv for v in rows[r]]
for k in range(len(rows)):
f = rows[k][col]
if k != r and f != 0:
rows[k] = [a - f * b for a, b in zip(rows[k], rows[r])]
pivots.append(col)
r += 1
if r == len(rows):
break
y = [Fraction(0)] * nvars
for k, col in enumerate(pivots):
y[col] = rows[k][-1]
return y
def _matrix(A, width, name):
A = [[_frac(v) for v in row] for row in (A or [])]
if any(len(row) != width for row in A):
raise ValueError(name + " must have one column per variable")
return A
def lp_max(c, A_ub, b_ub, A_eq=None, b_eq=None):
"""Maximize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
c = [_frac(v) for v in c]
n = len(c)
A_ub = _matrix(A_ub, n, "A_ub")
A_eq = _matrix(A_eq, n, "A_eq")
b_ub = [_frac(v) for v in (b_ub or [])]
b_eq = [_frac(v) for v in (b_eq or [])]
if len(b_ub) != len(A_ub) or len(b_eq) != len(A_eq):
raise ValueError("b_ub and b_eq must have one entry per row")
m1, m2 = len(A_ub), len(A_eq)
m = m1 + m2
width = n + m1
# Rows in the original orientation, with a slack column for each A_ub row.
orig = [A_ub[i] + [Fraction(int(k == i)) for k in range(m1)] for i in range(m1)]
orig += [A_eq[i] + [Fraction(0)] * m1 for i in range(m2)]
rhs = b_ub + b_eq
# A row gets an artificial variable if it is an equation or if its right side is negative.
need = [i >= m1 or rhs[i] < 0 for i in range(m)]
nart = sum(need)
T, basis = [], []
a = 0
for i in range(m):
sign = -1 if rhs[i] < 0 else 1
row = [sign * v for v in orig[i]] + [Fraction(0)] * nart + [sign * rhs[i]]
if need[i]:
row[width + a] = Fraction(1)
basis.append(width + a)
a += 1
else:
basis.append(n + i)
T.append(row)
if nart:
# Phase 1: maximize minus the sum of the artificial variables.
obj = _objective_row([Fraction(0)] * width + [Fraction(-1)] * nart, T, basis)
_simplex(T, obj, basis, width + nart)
if obj[-1] != 0:
return "infeasible", None, None, None
keep = []
for r in range(m):
if basis[r] >= width:
j = next((j for j in range(width) if T[r][j] != 0), None)
if j is None:
continue # the row is a combination of the other rows
_pivot(T, [Fraction(0)] * (width + nart + 1), basis, r, j)
keep.append(r)
T = [T[r][:width] + [T[r][-1]] for r in keep]
basis = [basis[r] for r in keep]
# Phase 2: the original objective, without the artificial columns.
cost = c + [Fraction(0)] * m1
obj = _objective_row(cost, T, basis)
if _simplex(T, obj, basis, width) == "unbounded":
return "unbounded", None, None, None
x = [Fraction(0)] * n
for r, j in enumerate(basis):
if j < n:
x[j] = T[r][-1]
value = sum((ci * xi for ci, xi in zip(c, x)), Fraction(0))
# The dual solves y^T A_B = c_B, where A_B holds the basic columns of the original rows.
M = [[orig[i][j] for i in range(m)] for j in basis]
dual = _any_solution(M, [cost[j] for j in basis], m)
return "optimal", x, value, dual
def lp_min(c, A_ub, b_ub, A_eq=None, b_eq=None):
"""Minimize c x subject to A_ub x <= b_ub, A_eq x = b_eq and x >= 0, exactly."""
status, x, value, dual = lp_max([-_frac(v) for v in c], A_ub, b_ub, A_eq, b_eq)
if status != "optimal":
return status, None, None, None
return status, x, -value, [-v for v in dual]
nucleolus_sequential_lp.py 231 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nucleolus-sequential-lp/. The authors are listed in prov/F1V2JQ.jsonl.
"""The nucleolus of a TU game by a sequence of linear programs (Kopelowitz 1967).
A game with n players 0, ..., n - 1 is a sequence v of 2^n numbers indexed by bitmask:
v[S] is the value of the coalition whose members are the set bits of S, and v[0] = 0.
The excess of a coalition S at a payoff vector x is e(S, x) = v[S] - x(S).
nucleolus(v) returns the nucleolus: the imputation (x(N) = v(N) and x_i >= v({i}))
whose vector of excesses over the coalitions S with 0 < S < N, sorted in nonincreasing
order, is lexicographically smallest. nucleolus(v, imputations=False) returns the
prenucleolus, the same minimum over all x with x(N) = v(N).
Each round solves one LP for the smallest maximum excess t* of the free coalitions, then
fixes every free coalition whose excess equals t* at every optimal point. A coalition with
a nonzero dual value is fixed at once (complementary slackness); for the others one more
LP decides. A free coalition whose indicator vector is a linear combination of the fixed
ones has a constant excess from then on, so it is dropped. Every round raises the rank of
the fixed system by at least 1, so there are at most n - 1 rounds, each with at most
2^n - 1 LPs on n + 1 free variables. All arithmetic is exact, in Fraction, through the
simplex method of agtlp.
"""
from fractions import Fraction
from agtlp import lp_max, lp_min
def members(S, n):
"""Return the list of the players in the coalition with bitmask S."""
return [i for i in range(n) if S >> i & 1]
def num_players(v):
"""Return n for a game given as a sequence of 2^n values."""
n = len(v).bit_length() - 1
if len(v) != 1 << n or n < 1:
raise ValueError("v must have 2^n entries for some n >= 1")
if v[0] != 0:
raise ValueError("v of the empty coalition must be 0")
return n
def excess(v, S, x):
"""Return e(S, x) = v[S] - x(S)."""
n = len(x)
return Fraction(v[S]) - sum((x[i] for i in members(S, n)), Fraction(0))
def excess_vector(v, x):
"""Return the excesses of all coalitions 0 < S < N, sorted in nonincreasing order."""
full = (1 << len(x)) - 1
return sorted((excess(v, S, x) for S in range(1, full)), reverse=True)
class _Span:
"""Rows in reduced echelon form over Fraction, for rank and span tests."""
def __init__(self, n):
self.n = n
self.rows = [] # (pivot column, row), each row with a 1 at its pivot
def reduce(self, vec):
vec = [Fraction(a) for a in vec]
for p, row in self.rows:
f = vec[p]
if f != 0:
vec = [a - f * b for a, b in zip(vec, row)]
return vec
def contains(self, vec):
return all(a == 0 for a in self.reduce(vec))
def add(self, vec):
vec = self.reduce(vec)
p = next((j for j, a in enumerate(vec) if a != 0), None)
if p is None:
return False
vec = [a / vec[p] for a in vec]
self.rows = [(q, [a - r[p] * b for a, b in zip(r, vec)]) for q, r in self.rows]
self.rows.append((p, vec))
return True
def rank(self):
return len(self.rows)
def _indicator(S, n):
return [1 if S >> i & 1 else 0 for i in range(n)]
def _build(v, n, free, fixed, imputations):
"""Constraint rows of the round LP in agtlp form.
The variables are y_0, ..., y_{n-1} and then t+ and t-. In imputation mode,
x_i = v({i}) + y_i with y_i >= 0; in the other mode, x_i = y_i - z_i with two
nonnegative parts, and the z columns come after the y columns. Returns
(A_ub, b_ub, A_eq, b_eq, nx, base), where nx is the number of x columns and base[i]
is the constant part of x_i.
"""
if imputations:
nx = n
base = [Fraction(v[1 << i]) for i in range(n)]
else:
nx = 2 * n
base = [Fraction(0)] * n
def xrow(S):
row = [Fraction(0)] * (nx + 2)
for i in members(S, n):
row[i] = Fraction(1)
if not imputations:
row[n + i] = Fraction(-1)
const = sum((base[i] for i in members(S, n)), Fraction(0))
return row, const
A_ub, b_ub = [], []
for S in free: # v(S) - x(S) <= t, written as -x(S) - t <= -v(S)
row, const = xrow(S)
row = [-a for a in row]
row[nx], row[nx + 1] = Fraction(-1), Fraction(1)
A_ub.append(row)
b_ub.append(const - Fraction(v[S]))
full = (1 << n) - 1
A_eq, b_eq = [], []
row, const = xrow(full)
A_eq.append(row)
b_eq.append(Fraction(v[full]) - const)
for S, tS in fixed: # x(S) = v(S) - t_S
row, const = xrow(S)
A_eq.append(row)
b_eq.append(Fraction(v[S]) - tS - const)
return A_ub, b_ub, A_eq, b_eq, nx, base
def _x_of(sol, n, nx, base, imputations):
if imputations:
return [base[i] + sol[i] for i in range(n)]
return [sol[i] - sol[n + i] for i in range(n)]
def nucleolus(v, imputations=True):
"""Return the nucleolus of the game v as a list of n Fractions.
v is a sequence of 2^n numbers indexed by bitmask, with v[0] = 0. With
imputations=False the result is the prenucleolus. Raises ValueError if the set of
imputations is empty (v(N) < sum of v({i})).
Cost: at most n - 1 rounds; each round solves at most 2^n - 1 LPs with O(n)
variables and O(2^n) constraints.
"""
return nucleolus_trace(v, imputations)[0]
def nucleolus_trace(v, imputations=True):
"""Return (x, rounds): the nucleolus and, for each round, the triple
(t*, the coalitions fixed at t*, the coalitions dropped as dependent)."""
n = num_players(v)
full = (1 << n) - 1
if imputations and Fraction(v[full]) < sum(Fraction(v[1 << i]) for i in range(n)):
raise ValueError("the game has no imputation") # @line L1
free = list(range(1, full)) # @line L2
fixed = []
span = _Span(n)
span.add(_indicator(full, n))
rounds = []
while span.rank() < n: # @line L3
A_ub, b_ub, A_eq, b_eq, nx, base = _build(v, n, free, fixed, imputations)
c = [Fraction(0)] * nx + [Fraction(1), Fraction(-1)]
status, _, tstar, dual = lp_min(c, A_ub, b_ub, A_eq, b_eq) # @line L4
if status != "optimal":
raise ArithmeticError("round LP is " + status)
# The optimal face: t+ - t- = t* as one more equation.
face_eq = A_eq + [[Fraction(0)] * nx + [Fraction(1), Fraction(-1)]]
face_b = b_eq + [tstar]
moved = []
for k, S in enumerate(free): # @line L5
tight = dual[k] != 0
if not tight:
row, const = [Fraction(0)] * (nx + 2), Fraction(0)
for i in members(S, n):
row[i] = Fraction(1)
if not imputations:
row[n + i] = Fraction(-1)
const += base[i]
st, _, best, _ = lp_max(row, A_ub, b_ub, face_eq, face_b)
tight = st == "optimal" and best + const == Fraction(v[S]) - tstar
if tight: # @line L6
moved.append(S)
fixed.append((S, tstar)) # @line L7
if not moved:
raise ArithmeticError("no coalition is tight at every optimal point")
for S in moved:
span.add(_indicator(S, n))
rest, dropped = [], []
for S in free: # @line L8
if S in moved:
continue
if span.contains(_indicator(S, n)):
dropped.append(S) # @line L9
else:
rest.append(S)
free = rest
rounds.append((tstar, moved, dropped))
rows = [_indicator(full, n)] + [_indicator(S, n) for S, _ in fixed]
rhs = [Fraction(v[full])] + [Fraction(v[S]) - tS for S, tS in fixed]
return _solve(rows, rhs, n), rounds # @line L10
def _solve(rows, rhs, n):
"""Solve a consistent linear system of rank n exactly, by Gauss-Jordan elimination."""
M = [[Fraction(a) for a in r] + [Fraction(b)] for r, b in zip(rows, rhs)]
r = 0
piv = []
for col in range(n):
p = next((k for k in range(r, len(M)) if M[k][col] != 0), None)
if p is None:
continue
M[r], M[p] = M[p], M[r]
M[r] = [a / M[r][col] for a in M[r]]
for k in range(len(M)):
if k != r and M[k][col] != 0:
f = M[k][col]
M[k] = [a - f * b for a, b in zip(M[k], M[r])]
piv.append(col)
r += 1
if len(piv) != n:
raise ArithmeticError("the fixed system does not determine x")
x = [Fraction(0)] * n
for k, col in enumerate(piv):
x[col] = M[k][-1]
return x
test_nucleolus_sequential_lp.py 232 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/nucleolus-sequential-lp/. The authors are listed in prov/F1V2JQ.jsonl.
"""Tests for nucleolus_sequential_lp: check values, a grid brute force, Kohlberg's criterion."""
import itertools
import random
import unittest
from fractions import Fraction as F
from agtlp import lp_max
from nucleolus_sequential_lp import (
excess,
excess_vector,
members,
nucleolus,
nucleolus_trace,
)
def bankruptcy_game(c, E):
n = len(c)
v = [0] * (1 << n)
for S in range(1, 1 << n):
rest = sum(c[i] for i in range(n) if not S >> i & 1)
v[S] = max(0, E - rest)
return v
def random_game(rng, n, top):
v = [0] + [rng.randint(0, top) for _ in range((1 << n) - 1)]
for i in range(n):
v[1 << i] = rng.randint(0, 1)
full = (1 << n) - 1
v[full] = max(v[full], sum(v[1 << i] for i in range(n))) # the imputation set is nonempty
return v
def grid_imputations(v, n, D):
"""All imputations x with x_i - v({i}) a multiple of 1/D."""
full = (1 << n) - 1
base = [F(v[1 << i]) for i in range(n)]
slack = (F(v[full]) - sum(base)) * D
if slack.denominator != 1 or slack < 0:
return
slack = int(slack)
for ks in itertools.product(range(slack + 1), repeat=n - 1):
last = slack - sum(ks)
if last < 0:
continue
ks = list(ks) + [last]
yield [base[i] + F(ks[i], D) for i in range(n)]
def balanced(collection, n):
"""True if the coalitions have positive weights with sum of w_S 1_S = 1_N."""
m = len(collection)
# Variables: w_S for S in the collection, then s. Maximize s with s <= w_S and s <= 1.
c = [F(0)] * m + [F(1)]
A_ub, b_ub = [], []
for k in range(m):
row = [F(0)] * (m + 1)
row[k], row[m] = F(-1), F(1)
A_ub.append(row)
b_ub.append(F(0))
A_ub.append([F(0)] * m + [F(1)])
b_ub.append(F(1))
A_eq = [[F(1) if S >> i & 1 else F(0) for S in collection] + [F(0)] for i in range(n)]
b_eq = [F(1)] * n
status, _, value, _ = lp_max(c, A_ub, b_ub, A_eq, b_eq)
return status == "optimal" and value > 0
def kohlberg(v, x):
"""Kohlberg's criterion for the prenucleolus: every upper level set of excesses is balanced."""
n = len(x)
full = (1 << n) - 1
coalitions = range(1, full)
for level in {excess(v, S, x) for S in coalitions}:
top = [S for S in coalitions if excess(v, S, x) >= level]
if not balanced(top, n):
return False
return True
def in_core(v, x):
n = len(x)
full = (1 << n) - 1
return sum(x) == v[full] and all(excess(v, S, x) <= 0 for S in range(1, full))
class CheckValues(unittest.TestCase):
def test_glove_game(self):
# One left glove (player 0) and two right gloves; also the game [51; 50, 49, 1].
v = [0, 0, 0, 1, 0, 1, 0, 1]
self.assertEqual(nucleolus(v), [1, 0, 0])
self.assertEqual(nucleolus(v, imputations=False), [1, 0, 0])
def test_majority_game(self):
v = [0, 0, 0, 1, 0, 1, 1, 1]
x, rounds = nucleolus_trace(v)
self.assertEqual(x, [F(1, 3)] * 3)
self.assertEqual(len(rounds), 1)
self.assertEqual(rounds[0][0], F(1, 3))
def test_half_pairs(self):
v = [0, 0, 0, F(1, 2), 0, F(1, 2), F(1, 2), 1]
x, rounds = nucleolus_trace(v)
self.assertEqual(x, [F(1, 3)] * 3)
self.assertEqual(rounds[0][0], F(-1, 6))
def test_talmud_values(self):
claims = [100, 200, 300]
expected = {
100: [F(100, 3)] * 3,
200: [50, 75, 75],
300: [50, 100, 150],
}
for E, want in expected.items():
self.assertEqual(nucleolus(bankruptcy_game(claims, E)), want)
def test_bankruptcy_trace(self):
x, rounds = nucleolus_trace(bankruptcy_game([100, 200, 300], 200))
self.assertEqual(x, [50, 75, 75])
self.assertEqual([r[0] for r in rounds], [-50, -75])
self.assertEqual(rounds[0][1], [1, 6])
def test_small_n(self):
self.assertEqual(nucleolus([0, 5]), [5])
self.assertEqual(nucleolus([0, 5, 7, 20]), [9, 11])
self.assertEqual(nucleolus([0, 5, 7, 20], imputations=False), [9, 11])
def test_imputation_bound_binds(self):
v = [0, 0, 0, 2, 0, 3, 4, 2]
self.assertEqual(nucleolus(v), [0, F(1, 2), F(3, 2)])
self.assertEqual(nucleolus(v, imputations=False), [F(-1, 3), F(2, 3), F(5, 3)])
def test_no_imputation(self):
with self.assertRaises(ValueError):
nucleolus([0, 2, 2, 3])
# The prenucleolus exists all the same.
self.assertEqual(nucleolus([0, 2, 2, 3], imputations=False), [F(3, 2), F(3, 2)])
def test_bad_input(self):
with self.assertRaises(ValueError):
nucleolus([0, 1, 2])
with self.assertRaises(ValueError):
nucleolus([1, 1, 1, 1])
class BruteForce(unittest.TestCase):
def check_against_grid(self, v, n, D):
x = nucleolus(v)
full = (1 << n) - 1
self.assertEqual(sum(x), v[full])
self.assertTrue(all(x[i] >= v[1 << i] for i in range(n)))
theta = excess_vector(v, x)
best = min(excess_vector(v, y) for y in grid_imputations(v, n, D))
on_grid = all(((xi - v[1 << i]) * D).denominator == 1 for i, xi in enumerate(x))
if on_grid:
self.assertEqual(theta, best)
else:
self.assertLess(theta, best)
def test_three_players(self):
rng = random.Random(7)
for _ in range(25):
self.check_against_grid(random_game(rng, 3, 6), 3, 12)
def test_four_players(self):
rng = random.Random(11)
for _ in range(5):
self.check_against_grid(random_game(rng, 4, 4), 4, 6)
class Properties(unittest.TestCase):
def test_kohlberg(self):
rng = random.Random(3)
for n in (3, 4):
for _ in range(4):
v = random_game(rng, n, 5)
x = nucleolus(v, imputations=False)
self.assertEqual(sum(x), v[(1 << n) - 1])
self.assertTrue(kohlberg(v, x))
def test_core_games(self):
rng = random.Random(5)
for found in range(4):
n = 3 + found % 2
# A convex game: v(S) = (sum of weights in S)^2, so the core is nonempty.
w = [rng.randint(0, 3) for _ in range(n)]
v = [sum(w[i] for i in members(S, n)) ** 2 for S in range(1 << n)]
x = nucleolus(v)
self.assertTrue(in_core(v, x))
self.assertEqual(x, nucleolus(v, imputations=False))
def test_covariance(self):
rng = random.Random(9)
for _ in range(5):
v = random_game(rng, 3, 6)
a, b = F(3, 2), [F(1), F(-2), F(5, 7)]
w = [a * v[S] + sum(b[i] for i in members(S, 3)) for S in range(8)]
x, y = nucleolus(v), nucleolus(w)
self.assertEqual(y, [a * x[i] + b[i] for i in range(3)])
def test_symmetry(self):
rng = random.Random(13)
for _ in range(5):
v = random_game(rng, 3, 6)
perm = [2, 0, 1] # player i becomes player perm[i]
def image(S):
return sum(1 << perm[i] for i in members(S, 3))
w = [0] * 8
for S in range(8):
w[image(S)] = v[S]
x, y = nucleolus(v), nucleolus(w)
self.assertEqual([y[perm[i]] for i in range(3)], x)
def test_round_count(self):
rng = random.Random(17)
for n in (3, 4):
for _ in range(3):
v = random_game(rng, n, 5)
_, rounds = nucleolus_trace(v, imputations=False)
self.assertLessEqual(len(rounds), n - 1)
levels = [r[0] for r in rounds]
self.assertEqual(levels, sorted(levels, reverse=True))
if __name__ == "__main__":
unittest.main()
History
Schmeidler defined the nucleolus and proved its existence and uniqueness in a paper published in 1969. Kopelowitz, at the Hebrew University of Jerusalem, wrote the sequence of linear programs in a research memorandum of 1967, which was never published as a paper but is the usual source for the method. Kohlberg characterized the nucleolus by balanced collections in 1971. Maschler, Peleg and Shapley described in 1979 the nested sequence of least cores whose last element is the nucleolus, which is the geometric picture behind the rounds. Later work replaced the exponential LPs by polynomial algorithms for structured classes: assignment games (Solymosi and Raghavan 1994) and, with the ellipsoid method, convex games and other classes (Faigle, Kern and Kuipers 2001).
References
- A. Kopelowitz, Computation of the kernels of simple games and the nucleolus of n-person games, Research Memorandum 31, Department of Mathematics, The Hebrew University of Jerusalem, 1967, the computation of the nucleolus by a sequence of linear programs (an unpublished memorandum)
- David Schmeidler, The nucleolus of a characteristic function game, SIAM Journal on Applied Mathematics 17(6) (1969), 1163-1170, the definition of the nucleolus and the proof that it exists and is unique
- Michael Maschler, Bezalel Peleg and Lloyd S. Shapley, Geometric properties of the kernel, nucleolus, and related solution concepts, Mathematics of Operations Research 4(4) (1979), 303-338, the least core and the nested sequence of least cores that ends in the nucleolus
- Elon Kohlberg, On the nucleolus of a characteristic function game, SIAM Journal on Applied Mathematics 20(1) (1971), 62-66, the characterization of the nucleolus by balanced collections of coalitions
- Michael Maschler, Eilon Solan and Shmuel Zamir, Game Theory, Cambridge University Press, 2013, Chapter 20, The nucleolus (Section 20.2 on nonemptiness and uniqueness, Section 20.4 on computing the nucleolus, Section 20.5 on the characterization of the prenucleolus)
- Introduction to the Theory of Cooperative Games, Chapter 5 (the prekernel, kernel and nucleolus) and Chapter 6 (the prenucleolus, with Kohlberg's criterion)
- Tamas Solymosi and T. E. S. Raghavan, An algorithm for finding the nucleolus of assignment games, International Journal of Game Theory 23 (1994), 119-143, a polynomial algorithm for the nucleolus of the assignment game
- Ulrich Faigle, Walter Kern and Jeroen Kuipers, On the computation of the nucleolus of a cooperative game, International Journal of Game Theory 30 (2001), 79-98, the nucleolus in polynomial time from a separation oracle for the least core, by the ellipsoid method; the case of convex games
- Ulrich Faigle, Walter Kern and Jeroen Kuipers, Computing the nucleolus of min-cost spanning tree games is NP-hard, International Journal of Game Theory 27(3) (1998), 443-450, the NP-hardness of the nucleolus of minimum cost spanning tree games
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag F1V2JQ Edit this page History Report an error Markdown