"""Count strict regular equilibria of five-player binary games with three factored rows. Run python3 verify_two_rows.py game.json. Coordinates are probabilities of action one. The JSON gives the first three rows' interior thresholds over a common denominator and the last two rows' integer corner payoff differences. The corner order is lexicographic in the four opponent bits, players ascending. Only Python's standard library is required (3.9+). """ import argparse import json from fractions import Fraction as F from functools import lru_cache from itertools import permutations, product from math import gcd, isqrt, lcm, prod from pathlib import Path def sign(x): if isinstance(x, Quadratic): if not x.b or sign(x.a) == sign(x.b): return sign(x.a) or sign(x.b) if not x.a: return sign(x.b) return sign(x.a) * sign(x.a*x.a - x.d*x.b*x.b) return (x > 0) - (x < 0) class Quadratic: """a + b*sqrt(d), where d is a positive nonsquare integer.""" def __init__(self, a, b, d): self.a, self.b, self.d = a, b, d def parts(self, other): if isinstance(other, Quadratic): assert self.d == other.d return other.a, other.b return other, 0 def __add__(self, other): c, e = self.parts(other) return Quadratic(self.a+c, self.b+e, self.d) __radd__ = __add__ def __neg__(self): return Quadratic(-self.a, -self.b, self.d) def __sub__(self, other): return self + (-other) def __rsub__(self, other): return (-self) + other def __mul__(self, other): c, e = self.parts(other) return Quadratic(self.a*c + self.d*self.b*e, self.a*e + self.b*c, self.d) __rmul__ = __mul__ def reciprocal(self): norm = self.a*self.a - self.d*self.b*self.b return Quadratic(self.a/norm, -self.b/norm, self.d) def __truediv__(self, other): if isinstance(other, Quadratic): return self * other.reciprocal() return Quadratic(self.a/other, self.b/other, self.d) def __rtruediv__(self, other): return other*self.reciprocal() def simple_roots(a, b, c): """Simple real roots of a*x*x+b*x+c, including the linear case.""" scale = lcm(a.denominator, b.denominator, c.denominator) a, b, c = (int(t*scale) for t in (a,b,c)) if a == 0: return [] if b == 0 else [F(-c,b)] common = gcd(gcd(abs(a), abs(b)), abs(c)) a, b, c = a//common, b//common, c//common disc = b*b-4*a*c if disc <= 0: return [] root = isqrt(disc) if root*root == disc: return [F(-b-root,2*a), F(-b+root,2*a)] return [Quadratic(F(-b,2*a), F(s,2*a), disc) for s in (-1,1)] def inside(x): return sign(x) > 0 and sign(1-x) > 0 def solutions(polynomials): """Return the coordinates and Jacobian sign of the transverse unit-cube roots.""" if not polynomials: yield (), 1 elif len(polynomials) == 1: a, b = polynomials[0] if b and inside(x := -a/b): yield (x,), sign(b) else: (a,b,c,d), (e,f,g,h) = polynomials for x in simple_roots(b*h-f*d, a*h+b*g-e*d-f*c, a*g-e*c): if not inside(x): continue if sign(c+d*x): y = -(a+b*x)/(c+d*x) elif sign(g+h*x): y = -(e+f*x)/(g+h*x) else: continue if inside(y): assert sign(a+b*x+c*y+d*x*y) == sign(e+f*x+g*y+h*x*y) == 0 jac = sign((b+d*y)*(g+h*x)-(c+d*x)*(f+h*y)) if jac: yield (x,y), jac def restrict(row_values, profile, free): table = [] for bits in product((F(0),F(1)), repeat=len(free)): profile.update(zip(free,bits)) table.append(row_values(tuple(profile[j] for j in range(5)))) if len(free) == 1: return table[0], table[1]-table[0] a, v, u, w = table return a, u-a, v-a, w-u-v+a def linear_interpolant(i, corners): opp = [j for j in range(5) if j != i] bits = tuple(product((0,1), repeat=4)) def evaluate(profile): return sum(value*prod(profile[j] if b else 1-profile[j] for j,b in zip(opp,corner)) for corner,value in zip(bits,corners)) return evaluate def permutation_sign(columns): return (-1)**sum(a > b for i,a in enumerate(columns) for b in columns[i+1:]) def verify(data): denominator = data['threshold_denominator'] if not isinstance(denominator, int) or denominator <= 0: raise ValueError('The threshold denominator must be a positive integer.') ts = [[F(v,denominator) for v in row] for row in data['thresholds']] if len(ts)!=3 or any(len(row)!=5 for row in ts): raise ValueError('Expected three rows of five thresholds.') for j in range(5): vals = [ts[i][j] for i in range(3) if i!=j] if len(vals)!=len(set(vals)) or not all(inside(x) for x in vals): raise ValueError('Thresholds in each opponent column must be distinct and interior.') rows = data['corner_differences'] if len(rows)!=2 or any(len(row)!=16 or not all(isinstance(v,int) for v in row) for row in rows): raise ValueError('Expected two sets of sixteen integer corner differences.') evaluate = {i: linear_interpolant(i,rows[i-3]) for i in (3,4)} rational_evaluate = {i: lru_cache(maxsize=None)(evaluate[i]) for i in (3,4)} counts, indices = [0]*6, [0]*6 for state in product((0,1,None), repeat=5): mixed = tuple(i for i,v in enumerate(state) if v is None) old = tuple(i for i in mixed if i<3) new = tuple(i for i in mixed if i>=3) for assigned in permutations(mixed,len(old)): if any(i==j for i,j in zip(old,assigned)): continue free = tuple(j for j in mixed if j not in assigned) if any(all(i==j for j in free) for i in new): continue profile = {i:F(v) for i,v in enumerate(state) if v is not None} profile.update({j:ts[i][j] for i,j in zip(old,assigned)}) polys = [restrict(rational_evaluate[i],profile,free) for i in new] for coordinates,new_jac in solutions(polys): profile.update(zip(free,coordinates)) pure_ok = True for i in range(5): if i in mixed: continue if i < 3: value = prod(profile[j]-ts[i][j] for j in range(5) if j!=i) else: value = evaluate[i](tuple(profile[j] for j in range(5))) if sign(value) != 2*state[i]-1: pure_ok = False break if not pure_ok: continue # Each old mixing row must have exactly one zero factor. Its # sole nonzero active derivative is then in its assigned column. old_jac = prod(sign(prod(profile[k]-ts[i][k] for k in range(5) if k not in (i,j))) for i,j in zip(old,assigned)) if not old_jac: continue size = len(mixed) counts[size] += 1 indices[size] += (-1)**size*permutation_sign(assigned+free)*old_jac*new_jac return counts, indices if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('games', nargs='+', type=Path) for path in parser.parse_args().games: counts, indices = verify(json.loads(path.read_text())) print(f'{path.name}: {sum(counts)} strict regular equilibria, by number of mixers {counts}') print(f'Index sum {sum(indices)}, by number of mixers {indices}')