Algorithm Search⌘K

Data structureadvanced

Marginal contribution nets

Also called MC-nets.

Represents a TU game by rules of the form pattern of players gives value, with Shapley values computable in time linear in the rules.

Time
O(z + n) banzhaf · shapleyO(z) value
Space
O(z) rules
Where
n = the number of players; z = the total number of literals in all rules
Properties
not concurrentnot externalnot persistent
Origin
Samuel Ieong, Yoav Shoham, 2005

A marginal contribution net (MC-net) stores a TU game as a list of rules. Each rule names some players that must be in a coalition, some players that must be out of it, and a value. The worth of a coalition is the sum of the values of the rules that it meets. A game in which the players interact in small groups gets a short net, where the table of vv has 2n2^n entries. The main point of the structure is that the Shapley value of a net takes time linear in its size, because each rule is a small game with a closed-form value and the value is additive (Shapley's uniqueness theorem). An MC-net is a representation of one game; the solution concepts on top of it, such as the core, have their own pages.

In plain words

Think of a list of bonus rules for a team. "If Ann and Bob both join, add 4." "If Ann and Cid both join, add 2." "If Dan joins and Eve does not, add 1." To find what a team is worth, check every rule and add up the bonuses that apply. To split the worth fairly with the Shapley value, you do not need to look at all the teams. Each rule hands out its own bonus: a rule with only people who must be present splits its bonus equally among them, and a rule that also names people who must be absent gives a share to the first kind and takes a share from the second kind. Add up the shares from all the rules, and you have each person's value.

The abstract type

The structure holds a TU game (N,v)(N, v) with N={1,…,n}N = \{1, \ldots, n\} and v(∅)=0v(\emptyset) = 0, and supports these operations:

  • VALUE(S)(S): return v(S)v(S) for a coalition S⊆NS \subseteq N.
  • SHAPLEY: return the Shapley value φ(v)∈Rn\varphi(v) \in \mathbb{R}^n.
  • BANZHAF: return the Banzhaf value β(v)\beta(v), where βi(v)=2−(n−1)∑S⊆N∖{i}(v(S∪{i})−v(S))\beta_i(v) = 2^{-(n-1)} \sum_{S \subseteq N \setminus \{i\}} (v(S \cup \{i\}) - v(S)).
  • Build the net from a table of vv (FROM-GAME), and add or remove a rule.

Representation

A rule is a triple r=(P,Q,x)r = (P, Q, x): a nonempty set PP of positive literals, a set QQ of negative literals with P∩Q=∅P \cap Q = \emptyset, and a number xx. Ieong and Shoham write it as a pattern of literals, for example {1,3,¬2}→1\{1, 3, \neg 2\} \to 1. The rule applies to SS if P⊆SP \subseteq S and Q∩S=∅Q \cap S = \emptyset. The net is a list RR of rules, and its game is

vR(S)=∑(P,Q,x)∈R, P⊆S, Q∩S=∅x.v_R(S) = \sum_{(P, Q, x) \in R,\ P \subseteq S,\ Q \cap S = \emptyset} x.

Since P≠∅P \ne \emptyset, no rule applies to ∅\emptyset, so vR(∅)=0v_R(\emptyset) = 0. The size of the net is z=∑r(∣P∣+∣Q∣)z = \sum_{r} (|P| + |Q|), the number of literals. In memory, each rule is two short lists or two bit masks of players and one number. With bit masks and nn at most the word size, a test "P⊆SP \subseteq S and Q∩S=∅Q \cap S = \emptyset" is two word operations.

Every game has a net with positive literals only. Write v=∑T≠∅dT uTv = \sum_{T \ne \emptyset} d_T\, u_T, where uTu_T is the unanimity game of TT and dT=∑S⊆T(−1)∣T∣−∣S∣v(S)d_T = \sum_{S \subseteq T} (-1)^{|T| - |S|} v(S) is the Harsanyi dividend (Möbius inversion). The rules (T,∅,dT)(T, \emptyset, d_T) for the TT with dT≠0d_T \ne 0 form a net for vv. With negative literals the net can be much shorter, as the example below shows.

Operations

Write a=∣P∣a = |P| and b=∣Q∣b = |Q| for a rule.

  1. VALUE(R, S)
  2. 1total ← 0
  3. 2for each rule (P, Q, x) in R do
  4. 3if P ⊆ S and Q ∩ S = ∅ then total ← total + x
  5. 4return total
  6. SHAPLEY(R, n)
  7. 5phi[i] ← 0 for each player i
  8. 6for each rule (P, Q, x) in R do ▷ a = |P|, b = |Q|
  9. 7for each i in P do
  10. 8phi[i] ← phi[i] + x (a-1)! b! / (a+b)!
  11. 9for each j in Q do
  12. 10phi[j] ← phi[j] - x a! (b-1)! / (a+b)!
  13. 11return phi
  14. BANZHAF(R, n)
  15. 12beta[i] ← 0 for each player i
  16. 13for each rule (P, Q, x) in R do
  17. 14share ← x / 2^(a+b-1)
  18. 15for each i in P do beta[i] ← beta[i] + share
  19. 16for each j in Q do beta[j] ← beta[j] - share
  20. 17return beta

Players that occur in no rule are null players and keep the value 0. A rule with b=0b = 0 splits xx equally among the players of PP, which is the value of the game x uPx\, u_P. To add a rule, append it; to remove one, delete it. Both change vv by the game of that one rule.

FROM-GAME computes the dividends of all 2n−12^n - 1 nonempty coalitions from a table of vv and keeps the nonzero ones. The direct sum over subsets takes O(3n)O(3^n) time. The fast Möbius transform over the subset lattice takes O(n 2n)O(n\, 2^n).

Example

Positive rules only. The game with v({1,2})=4v(\{1, 2\}) = 4, v({1,3})=2v(\{1, 3\}) = 2, v(N)=6v(N) = 6 and v(S)=0v(S) = 0 otherwise is the net

{1,2}→4,{1,3}→2.\{1, 2\} \to 4, \qquad \{1, 3\} \to 2.

VALUE({1,2,3})=4+2=6(\{1, 2, 3\}) = 4 + 2 = 6, and VALUE({2,3})=0(\{2, 3\}) = 0 since no rule applies. SHAPLEY gives player 1 the share 4⋅1! 0!/2!=24 \cdot 1!\, 0!/2! = 2 from the first rule and 11 from the second, player 2 gets 22 and player 3 gets 11: φ=(3,2,1)\varphi = (3, 2, 1). BANZHAF gives the shares 4/21=24/2^{1} = 2 and 2/21=12/2^1 = 1 in the same way, so β=(3,2,1)\beta = (3, 2, 1) as well.

A rule with a negative literal. The weighted voting game [51;50,49,1][51; 50, 49, 1] wins exactly on {1,2}\{1, 2\}, {1,3}\{1, 3\} and {1,2,3}\{1, 2, 3\}. Two rules describe it:

{1,2}→1,{1,3,¬2}→1.\{1, 2\} \to 1, \qquad \{1, 3, \neg 2\} \to 1.

The first rule applies to {1,2}\{1, 2\} and {1,2,3}\{1, 2, 3\}, and the second only to {1,3}\{1, 3\}, so each winning coalition gets exactly 1. For SHAPLEY, the first rule (a=2a = 2, b=0b = 0) gives 1/21/2 to players 1 and 2. The second rule (a=2a = 2, b=1b = 1) gives 1⋅1! 1!/3!=1/61 \cdot 1!\, 1!/3! = 1/6 to players 1 and 3 and −1⋅2! 0!/3!=−1/3-1 \cdot 2!\, 0!/3! = -1/3 to player 2. The sums are

φ=(12+16, 12−13, 16)=(23,16,16),\varphi = \left(\tfrac{1}{2} + \tfrac{1}{6},\ \tfrac{1}{2} - \tfrac{1}{3},\ \tfrac{1}{6}\right) = \left(\tfrac{2}{3}, \tfrac{1}{6}, \tfrac{1}{6}\right),

the Shapley-Shubik index of the game. For BANZHAF the shares are 1/21/2 from the first rule and ±1/4\pm 1/4 from the second, so β=(3/4,1/4,1/4)\beta = (3/4, 1/4, 1/4), the raw Banzhaf index. A single rule can give a negative share, but the sum is right. The net from the dividends has three rules instead: {1,2}→1\{1, 2\} \to 1, {1,3}→1\{1, 3\} \to 1 and {1,2,3}→−1\{1, 2, 3\} \to -1.

Negative literals save space. Let v(S)=1v(S) = 1 if SS meets a set A={a1,…,ak}A = \{a_1, \ldots, a_k\} and v(S)=0v(S) = 0 if not. Its dividends are dT=(−1)∣T∣+1d_T = (-1)^{|T|+1} for every nonempty T⊆AT \subseteq A, so the net with positive literals only has 2k−12^k - 1 rules. With negative literals, kk rules are enough: {a1}→1\{a_1\} \to 1, {a2,¬a1}→1\{a_2, \neg a_1\} \to 1, and in general {aj,¬a1,…,¬aj−1}→1\{a_j, \neg a_1, \ldots, \neg a_{j-1}\} \to 1. For each SS that meets AA, exactly the rule of the smallest jj with aj∈Sa_j \in S applies. SHAPLEY gives each player of AA the value 1/k1/k.

Graph games. For a weighted graph on the players, let v(S)v(S) be the total weight of the edges with both ends in SS (Deng and Papadimitriou 1994). The net has one rule {i,j}→wij\{i, j\} \to w_{ij} per edge, and SHAPLEY gives each player half the weight of its edges.

Correctness

VALUE adds exactly the values of the rules that apply, which is the definition of vRv_R. For SHAPLEY, take one rule (P,Q,x)(P, Q, x) and a uniform random order. A player i∈Pi \in P adds xx exactly when all of P∖{i}P \setminus \{i\} comes before it and all of QQ comes after it. Among the (a+b)!(a+b)! relative orders of P∪QP \cup Q, there are (a−1)! b!(a-1)!\, b! such orders. A player j∈Qj \in Q adds −x-x exactly when all of PP comes before it and all of Q∖{j}Q \setminus \{j\} after it, in a! (b−1)!a!\, (b-1)! orders. The other players never change whether the rule applies. The Shapley value is additive, so the values of the rules add up. For BANZHAF, the marginal contribution of i∈Pi \in P to SS is xx for the 2n−a−b2^{n-a-b} sets S⊆N∖{i}S \subseteq N \setminus \{i\} that contain P∖{i}P \setminus \{i\} and avoid QQ, which gives x/2a+b−1x / 2^{a+b-1}, and the same count holds for j∈Qj \in Q. The full proofs are in the proof file.

Proof: The value of a coalition and the Shapley and Banzhaf values of an MC-netfull

An MC-net on the players N={1,…,n}N = \{1, \ldots, n\} is a list RR of rules r=(P,Q,x)r = (P, Q, x), where P⊆NP \subseteq N is nonempty, Q⊆NQ \subseteq N is disjoint from PP and xx is a number. The rule applies to SS if P⊆SP \subseteq S and Q∩S=∅Q \cap S = \emptyset. The game of the net is vR(S)=∑r∈Rvr(S)v_R(S) = \sum_{r \in R} v_r(S), where vr(S)=xv_r(S) = x if rr applies to SS and vr(S)=0v_r(S) = 0 if not. Since P≠∅P \neq \emptyset, no rule applies to ∅\emptyset, so vR(∅)=0v_R(\emptyset) = 0 and vRv_R is a TU game.

Lemma (VALUE). VALUE(R,S)(R, S) returns vR(S)v_R(S).

Proof. Line L1 sets total=0total = 0. The loop of line L2 visits each rule once, and line L3 adds xx exactly when the rule applies to SS. So after the loop, total=∑rvr(S)=vR(S)total = \sum_r v_r(S) = v_R(S), which line L4 returns. □\square

Lemma (one rule). Let r=(P,Q,x)r = (P, Q, x) with a=∣P∣a = |P| and b=∣Q∣b = |Q|. The Shapley value of the game vrv_r is

φi(vr)=x(a−1)! b!(a+b)! for i∈P,φj(vr)=−xa! (b−1)!(a+b)! for j∈Q,\varphi_i(v_r) = x \frac{(a-1)!\, b!}{(a+b)!} \text{ for } i \in P, \qquad \varphi_j(v_r) = -x \frac{a!\, (b-1)!}{(a+b)!} \text{ for } j \in Q,

and φk(vr)=0\varphi_k(v_r) = 0 for k∉P∪Qk \notin P \cup Q. The raw Banzhaf value is βi(vr)=x/2a+b−1\beta_i(v_r) = x / 2^{a+b-1} for i∈Pi \in P, βj(vr)=−x/2a+b−1\beta_j(v_r) = -x / 2^{a+b-1} for j∈Qj \in Q, and 0 for the other players.

Proof. We use the order form of the Shapley value: φi(v)\varphi_i(v) is the mean over the n!n! orders π\pi of v(Piπ∪{i})−v(Piπ)v(P_i^\pi \cup \{i\}) - v(P_i^\pi), where PiπP_i^\pi is the set of the players before ii in π\pi.

A player k∉P∪Qk \notin P \cup Q does not change whether the rule applies, so vr(S∪{k})=vr(S)v_r(S \cup \{k\}) = v_r(S) for every SS. Every marginal contribution of kk is 0.

Let i∈Pi \in P and let B=PiπB = P_i^\pi. Since i∈Pi \in P and i∉Bi \notin B, the rule does not apply to BB, so vr(B)=0v_r(B) = 0. The rule applies to B∪{i}B \cup \{i\} if and only if P∖{i}⊆BP \setminus \{i\} \subseteq B and Q∩B=∅Q \cap B = \emptyset. So the marginal contribution is xx if, in π\pi, all the other players of PP come before ii and all the players of QQ come after ii, and 0 if not. This event depends only on the relative order of the a+ba + b players of P∪QP \cup Q, which is uniform over the (a+b)!(a+b)! orders of these players when π\pi is uniform. The orders in the event put P∖{i}P \setminus \{i\} in the first a−1a - 1 places in any order, ii in place aa, and QQ in the last bb places in any order. There are (a−1)! b!(a-1)!\, b! of them, which gives the first formula.

Let j∈Qj \in Q and B=PjπB = P_j^\pi. The rule does not apply to B∪{j}B \cup \{j\}, because j∈Qj \in Q. It applies to BB if and only if P⊆BP \subseteq B and (Q∖{j})∩B=∅(Q \setminus \{j\}) \cap B = \emptyset. So the marginal contribution is −x-x if all of PP comes before jj and all of Q∖{j}Q \setminus \{j\} comes after jj, and 0 if not. The same count gives a! (b−1)!a!\, (b-1)! orders out of (a+b)!(a+b)!.

For the Banzhaf value of i∈Pi \in P, the marginal contribution to S⊆N∖{i}S \subseteq N \setminus \{i\} is xx if P∖{i}⊆SP \setminus \{i\} \subseteq S and Q∩S=∅Q \cap S = \emptyset, and 0 if not. Such a set SS contains the a−1a - 1 fixed players, avoids the bb fixed players and is free on the other n−a−bn - a - b players, so there are 2n−a−b2^{n-a-b} of them. Divided by 2n−12^{n-1}, this gives x/2a+b−1x / 2^{a+b-1}. For j∈Qj \in Q, the sets SS with marginal −x-x contain PP and avoid Q∖{j}Q \setminus \{j\}, which again fixes a+b−1a + b - 1 players and leaves 2n−a−b2^{n-a-b} sets. □\square

Theorem (SHAPLEY and BANZHAF). SHAPLEY(R,n)(R, n) returns φ(vR)\varphi(v_R), and BANZHAF(R,n)(R, n) returns the raw Banzhaf values β(vR)\beta(v_R).

Proof. Both values are linear in the game: the order form and the subset form are sums of terms v(T)v(T) with coefficients that do not depend on vv. So φ(vR)=∑r∈Rφ(vr)\varphi(v_R) = \sum_{r \in R} \varphi(v_r) and β(vR)=∑r∈Rβ(vr)\beta(v_R) = \sum_{r \in R} \beta(v_r). Line L5 sets each φi\varphi_i to 0. The loop of line L6 visits each rule once, and lines L7 to L10 add the terms of the one-rule lemma for the players in PP and in QQ. Players outside P∪QP \cup Q get 0 from the rule, so they need no update. After the loop, φi\varphi_i is the sum of the contributions of all rules, which line L11 returns. Lines L12 to L17 do the same for the Banzhaf value with the term x/2a+b−1x / 2^{a+b-1} of line L14. ■\blacksquare

Check of efficiency. For one rule with b≥1b \ge 1, the Shapley values sum to a⋅x(a−1)! b!(a+b)!−b⋅xa! (b−1)!(a+b)!=0=vr(N)a \cdot x \frac{(a-1)!\,b!}{(a+b)!} - b \cdot x \frac{a!\,(b-1)!}{(a+b)!} = 0 = v_r(N), since Q∩N≠∅Q \cap N \ne \emptyset. For b=0b = 0, they sum to a⋅x/a=x=vr(N)a \cdot x/a = x = v_r(N).

Lemma (from a table). For every TU game vv on NN, the rules (T,∅,dT)(T, \emptyset, d_T) with dT=∑S⊆T(−1)∣T∣−∣S∣v(S)d_T = \sum_{S \subseteq T} (-1)^{|T| - |S|} v(S), over the nonempty TT with dT≠0d_T \ne 0, form an MC-net with vR=vv_R = v.

Proof. The rule (T,∅,dT)(T, \emptyset, d_T) applies to SS if and only if T⊆ST \subseteq S, so vR(S)=∑∅≠T⊆SdTv_R(S) = \sum_{\emptyset \ne T \subseteq S} d_T. By Möbius inversion on the lattice of subsets, ∑T⊆SdT=v(S)\sum_{T \subseteq S} d_T = v(S) for every SS, and d∅=v(∅)=0d_\emptyset = v(\emptyset) = 0. So vR(S)=v(S)v_R(S) = v(S). □\square

Complexity

Let zz be the number of literals in the net and nn the number of players.

  • VALUE takes O(z)O(z) time with SS in a hash set or a Boolean array. With bit masks and nn at most the word size, it takes O(k)O(k) time for kk rules.
  • SHAPLEY and BANZHAF take O(z+n)O(z + n) arithmetic operations: O(n)O(n) to clear the output, and O(1)O(1) per literal with a table of the factorials 0!,…,n!0!, \ldots, n! or of the powers of 2. With integer rule values the results are rationals whose denominators divide n!n! (for SHAPLEY) or 2n−12^{n-1} (for BANZHAF), so exact arithmetic adds O(nlog⁡n)O(n \log n) bits to the numbers.
  • Space is O(z)O(z) words for the rules.
  • FROM-GAME takes O(n 2n)O(n\, 2^n) time from a table of vv, and can return 2n−12^n - 1 rules.

The size of the net is the right measure: the Shapley value is linear in it, but a net can itself be large. The OR game above needs 2k−12^k - 1 positive rules, and other games, such as a majority game on many players, have dense dividends and need long nets.

Other questions are harder on nets. Ieong and Shoham (2005) show that questions about the core are intractable on general nets. They give algorithms for core membership and core emptiness whose time is exponential only in the treewidth of the graph that links two players when they share a rule, using a tree decomposition.

Variants

  • Positive literals only. The net is the list of the nonzero Harsanyi dividends. It is unique for each game and has the dividend formula φi=∑T∋idT/∣T∣\varphi_i = \sum_{T \ni i} d_T / |T| directly.
  • Graph games (induced subgraph games): rules with two positive literals. The Shapley value is half the weighted degree. Deng and Papadimitriou (1994) study their core.
  • Patterns other than conjunctions. A rule can use a Boolean formula as the pattern. A conjunction of literals keeps the closed form of SHAPLEY; for other formulas the value of a rule is no longer a single formula in aa and bb.
  • Banzhaf and other semivalues. Any value that is linear in vv can be computed rule by rule in the same way, with the value of one rule in closed form, as BANZHAF does.

When to use it

Use an MC-net when the worth of a coalition comes from many small interactions: pairs or small groups of players that create a bonus together, with some exceptions when a certain player is present. It is the natural format when you need Shapley or Banzhaf values exactly for many players and the game is sparse in this sense. If the game is a weighted voting game, use its weights and dynamic programming instead, since threshold games rarely have short nets. If the game is only an oracle, use sampling.

Pitfalls

  • An empty positive part. A rule with P=∅P = \emptyset applies to the empty coalition and breaks v(∅)=0v(\emptyset) = 0. A rule with P∩Q≠∅P \cap Q \ne \emptyset never applies. Reject both when the net is built.
  • Signs of the negative literals. The share of j∈Qj \in Q is −x a! (b−1)!/(a+b)!-x\, a!\, (b-1)!/(a+b)!, with a!a! and (b−1)!(b-1)!, not the mirror of the share of PP. With a=2a = 2, b=1b = 1 and x=1x = 1, the players of PP get 1/61/6 each and the player of QQ gets −1/3-1/3.
  • Negative shares are normal. A single rule can give a negative share even when the game is monotone. Check only the total.
  • The net is not unique. With negative literals, many nets describe the same game. Two nets are equal as games only if their dividends are equal, and computing the dividends can take exponential time.
  • Converting into a net can be expensive. The Shapley value is linear in the size of the net, not in the size of some other description of the game.

Implementations

The Python version stores a rule as two frozensets and a value, and returns exact Fractions for the Shapley and Banzhaf values. FROM-GAME uses the direct dividend sum, which is fine for the small nn where a full table of vv exists.

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.

marginal_contribution_nets.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/marginal-contribution-nets/. The authors are listed in prov/J0TAYV.jsonl.
"""Marginal contribution nets (MC-nets): a TU game written as a list of rules.

A rule is a triple (P, Q, x). P is the set of positive literals, Q the set of negative
literals and x the value. The rule applies to a coalition S if P is a subset of S and Q does
not meet S. The value v(S) is the sum of x over the rules that apply to S. P must be nonempty
and disjoint from Q, so that no rule applies to the empty coalition and v(empty set) = 0.
Players are 0 to n - 1. Values may be ints or Fractions, and the indices come out exact.
"""

from fractions import Fraction
from itertools import combinations
from math import factorial

Rule = tuple[frozenset, frozenset, object]


def make_rule(pos, neg, x) -> Rule:
    """Build a rule and check that it is valid."""
    P, Q = frozenset(pos), frozenset(neg)
    if not P:
        raise ValueError("a rule needs at least one positive literal")
    if P & Q:
        raise ValueError("a player cannot be both a positive and a negative literal")
    return (P, Q, x)


def value(rules: list[Rule], S) -> object:
    """v(S): the sum of the values of the rules that apply to S."""
    S = frozenset(S)
    total = 0  # @line L1
    for P, Q, x in rules:  # @line L2
        if P <= S and not (Q & S):  # @line L3
            total += x
    return total  # @line L4


def shapley(rules: list[Rule], n: int) -> list[Fraction]:
    """The Shapley value of every player, in time linear in the size of the rules."""
    phi = [Fraction(0)] * n  # @line L5
    for P, Q, x in rules:  # @line L6
        a, b = len(P), len(Q)
        for i in P:  # @line L7
            phi[i] += Fraction(x) * factorial(a - 1) * factorial(b) / factorial(a + b)  # @line L8
        for j in Q:  # @line L9
            phi[j] -= Fraction(x) * factorial(a) * factorial(b - 1) / factorial(a + b)  # @line L10
    return phi  # @line L11


def banzhaf(rules: list[Rule], n: int) -> list[Fraction]:
    """The raw Banzhaf value of every player: the mean of v(S + i) - v(S) over the 2^(n-1) sets S."""
    beta = [Fraction(0)] * n  # @line L12
    for P, Q, x in rules:  # @line L13
        share = Fraction(x) / 2 ** (len(P) + len(Q) - 1)  # @line L14
        for i in P:  # @line L15
            beta[i] += share
        for j in Q:  # @line L16
            beta[j] -= share
    return beta  # @line L17


def from_game(n: int, v) -> list[Rule]:
    """Rules with no negative literals for any game v, from its Harsanyi dividends.

    The dividend of T is the sum over S in T of (-1)^(|T| - |S|) v(S). The game is the sum of
    dividend(T) times the unanimity game of T, so the rule (T, empty set, dividend(T)) for each
    nonempty T with a nonzero dividend gives back v. The output can have 2^n - 1 rules.
    """
    rules = []
    for r in range(1, n + 1):
        for T in combinations(range(n), r):
            d = 0
            for k in range(r + 1):
                for S in combinations(T, k):
                    d += (-1) ** (r - k) * v(frozenset(S))
            if d != 0:
                rules.append(make_rule(T, (), d))
    return rules
test_marginal_contribution_nets.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/marginal-contribution-nets/. The authors are listed in prov/J0TAYV.jsonl.

import random
from fractions import Fraction
from itertools import combinations
from math import factorial

import pytest

from marginal_contribution_nets import banzhaf, from_game, make_rule, shapley, value


def all_sets(n):
    for r in range(n + 1):
        for S in combinations(range(n), r):
            yield frozenset(S)


def brute_shapley(n, v):
    phi = []
    for i in range(n):
        t = Fraction(0)
        for S in all_sets(n):
            if i in S:
                continue
            s = len(S)
            t += Fraction(factorial(s) * factorial(n - 1 - s), factorial(n)) * (v(S | {i}) - v(S))
        phi.append(t)
    return phi


def brute_banzhaf(n, v):
    out = []
    for i in range(n):
        t = sum(v(S | {i}) - v(S) for S in all_sets(n) if i not in S)
        out.append(Fraction(t, 2 ** (n - 1)))
    return out


def random_rules(rng, n, count):
    rules = []
    for _ in range(count):
        players = list(range(n))
        rng.shuffle(players)
        a = rng.randint(1, n)
        b = rng.randint(0, n - a)
        rules.append(make_rule(players[:a], players[a:a + b], rng.randint(-6, 9)))
    return rules


def test_example_game():
    # v(12) = 4, v(13) = 2, v(123) = 6 (players 0, 1, 2 here): two rules.
    rules = [make_rule({0, 1}, (), 4), make_rule({0, 2}, (), 2)]
    assert [value(rules, S) for S in ({0, 1}, {0, 2}, {1, 2}, {0, 1, 2})] == [4, 2, 0, 6]
    assert shapley(rules, 3) == [3, 2, 1]
    assert banzhaf(rules, 3) == [3, 2, 1]


def test_random_nets_against_enumeration():
    rng = random.Random(2005)
    for _ in range(40):
        n = rng.randint(1, 7)
        rules = random_rules(rng, n, rng.randint(0, 6))
        v = lambda S, rules=rules: value(rules, S)
        assert v(frozenset()) == 0
        assert shapley(rules, n) == brute_shapley(n, v)
        assert banzhaf(rules, n) == brute_banzhaf(n, v)
        assert sum(shapley(rules, n)) == v(frozenset(range(n)))


def test_round_trip_from_game():
    rng = random.Random(4)
    for _ in range(15):
        n = rng.randint(1, 6)
        table = {S: (rng.randint(-5, 10) if S else 0) for S in all_sets(n)}
        rules = from_game(n, table.__getitem__)
        assert all(not Q for _, Q, _ in rules)
        for S in all_sets(n):
            assert value(rules, S) == table[S]
        assert shapley(rules, n) == brute_shapley(n, table.__getitem__)


def test_or_game_is_small_with_negations():
    k = 6
    v = lambda S: 1 if S else 0
    # Without negative literals the dividends give 2^k - 1 rules.
    assert len(from_game(k, v)) == 2 ** k - 1
    # With negative literals, k rules: player i counts if no lower player is present.
    rules = [make_rule({i}, range(i), 1) for i in range(k)]
    for S in all_sets(k):
        assert value(rules, S) == v(S)
    assert shapley(rules, k) == [Fraction(1, k)] * k


def test_graph_game():
    # Edge weights; v(S) is the weight of the edges with both ends in S.
    edges = {(0, 1): 3, (1, 2): 5, (0, 3): -2, (2, 3): 4}
    rules = [make_rule(e, (), w) for e, w in edges.items()]
    expect = [Fraction(0)] * 4
    for (a, b), w in edges.items():
        expect[a] += Fraction(w, 2)
        expect[b] += Fraction(w, 2)
    assert shapley(rules, 4) == expect


def test_fraction_values():
    rules = [make_rule({0}, {1}, Fraction(1, 3)), make_rule({1, 2}, (), Fraction(5, 2))]
    v = lambda S: value(rules, S)
    assert shapley(rules, 3) == brute_shapley(3, v)
    assert banzhaf(rules, 3) == brute_banzhaf(3, v)


def test_invalid_rules():
    with pytest.raises(ValueError):
        make_rule((), {0}, 1)
    with pytest.raises(ValueError):
        make_rule({0, 1}, {1}, 1)

History

Ieong and Shoham (2005) introduced marginal contribution nets at the ACM Conference on Electronic Commerce, as a representation that is both expressive and fast for the Shapley value. They proved that the Shapley value takes linear time in the size of the net and studied the core through the treewidth of the interaction graph. Their work built on the graph games of Deng and Papadimitriou (1994), which are nets whose rules have two players. The textbooks of Shoham and Leyton-Brown (2009) and of Chalkiadakis, Elkind and Wooldridge (2011) cover MC-nets among the compact representations of coalitional games.

References

  1. Samuel Ieong and Yoav Shoham, Marginal contribution nets: a compact representation scheme for coalitional games, Proceedings of the 6th ACM Conference on Electronic Commerce (EC 2005), 193-202, the rules with conjunctions of literals, the Shapley value in time linear in the size of the net, and the core algorithms by tree decomposition
  2. Xiaotie Deng and Christos H. Papadimitriou, On the complexity of cooperative solution concepts, Mathematics of Operations Research 19(2) (1994), 257-266, the games on weighted graphs, whose Shapley value is half the weight of the edges at each node
  3. Georgios Chalkiadakis, Edith Elkind and Michael Wooldridge, Computational Aspects of Cooperative Game Theory, Morgan and Claypool, 2011, Chapter 3, Representations and algorithms (induced subgraph games and marginal contribution nets)
  4. Yoav Shoham and Kevin Leyton-Brown, Multiagent Systems, Algorithmic, Game-Theoretic, and Logical Foundations, Cambridge University Press, 2009, Section 12.3.5, Marginal contribution nets

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.banzhaf
  • a full proof of time.shapley
  • a full proof of time.value
  • a full proof of space.rules
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/J0TAYV/text.yaml