forked from egtaonline/gameanalysis
/
RandomGames.py
executable file
·449 lines (370 loc) · 14.9 KB
/
RandomGames.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#! /usr/bin/env python2.7
import GameIO as IO
from BasicFunctions import leading_zeros
from RoleSymmetricGame import Game, SampleGame, PayoffData, Profile
from functools import partial
from itertools import combinations
from bisect import bisect
from numpy.random import uniform as U, normal, multivariate_normal, beta, gumbel
from random import choice
from numpy import array, arange, zeros, fill_diagonal, cumsum
def __make_asymmetric_game(N, S):
"""
N: number of players
S: number of strategies
"""
roles = ["r" + leading_zeros(i,N) for i in range(N)]
players = {r:1 for r in roles}
strategies = {r:["s"+leading_zeros(i,S) for i in range(S)] for r in roles}
return Game(roles, players, strategies)
def __make_symmetric_game(N, S):
"""
N: number of players
S: number of strategies
"""
roles = ["All"]
players = {"All":N}
strategies = {"All":["s" + leading_zeros(i,S) for i in range(S)]}
return Game(roles, players, strategies)
def independent_game(N, S, dstr=partial(U,-1,1)):
"""
All payoff values drawn independently according to specified distribution.
N: number of players
S: number of strategies
dstr: distribution from which payoff values are independently drawn
"""
g = __make_asymmetric_game(N, S)
for prof in g.allProfiles():
g.addProfile({r:[PayoffData(prof[r].keys()[0], 1, dstr())] \
for r in prof})
return g
def covariant_game(N, S, mean_func=lambda:0, var=1, covar_func=partial(U,0,1)):
"""
Payoff values for each profile drawn according to multivariate normal.
The multivariate normal for each profile has a constant mean-vector with
value drawn from mean_func, constant variance=var, and equal covariance
between all pairs of players, drawn from covar_func.
N: number of players
S: number of strategies
mean_func: distribution from which mean payoff for each profile is drawn
var: diagonal entries of covariance matrix
covar_func: distribution from which the value of the off-diagonal
covariance matrix entries for each profile is drawn
Both mean_func and covar_func should be numpy-style random number generators
that can return an array.
"""
g = __make_asymmetric_game(N, S)
mean = zeros(S)
covar = zeros([S,S])
for prof in g.allProfiles():
mean.fill(mean_func())
payoffs = multivariate_normal(mean, covar)
covar.fill(covar_func())
fill_diagonal(covar, var)
g.addProfile({r:[PayoffData(prof[r].keys()[0], 1, payoffs[i])] \
for i,r in enumerate(g.roles)})
return g
def uniform_zero_sum_game(S, min_val=-1, max_val=1):
"""
2-player zero-sum game; player 1 payoffs drawn from a uniform distribution.
S: number of strategies
min_val: minimum for the uniform distribution
max_val: maximum for the uniform distribution
"""
g = __make_asymmetric_game(2, S)
for prof in g.allProfiles():
row_strat = prof["r0"].keys()[0]
row_val = U(min_val, max_val)
col_strat = prof["r1"].keys()[0]
p = {"r0":[PayoffData(row_strat, 1, row_val)], \
"r1":[PayoffData(col_strat, 1, -row_val)]}
g.addProfile(p)
return g
def uniform_symmetric_game(N, S, min_val=-1, max_val=1):
"""
Symmetric game with each payoff value drawn from a uniform distribution.
N: number of players
S: number of strategies
min_val: minimum for the uniform distribution
max_val: maximum for the uniform distribution
"""
g = __make_symmetric_game(N, S)
for prof in g.allProfiles():
payoffs = []
for strat, count in prof["All"].items():
payoffs.append(PayoffData(strat, count, U(min_val, max_val)))
g.addProfile({"All":payoffs})
return g
def sym_2p2s_game(a=0, b=1, c=2, d=3, min_val=-1, max_val=1):
"""
Create a symmetric 2-player 2-strategy game of the specified form.
Four payoff values get drawn from U(min_val, max_val), and then are assigned
to profiles in order from smallest to largest according to the order
parameters as follows:
| s0 | s1 |
---|-----|-----|
s0 | a,a | b,c |
s1 | c,b | d,d |
---|-----|-----|
So a=2,b=0,c=3,d=1 gives a prisoners' dilemma; a=0,b=3,c=1,d=2 gives a game
of chicken.
"""
g = __make_symmetric_game(2, 2)
payoffs = sorted(U(min_val, max_val, 4))
g.addProfile({"All":[PayoffData(g.strategies["All"][0], 2, payoffs[a])]})
g.addProfile({"All":[PayoffData(g.strategies["All"][0], 1, payoffs[b]), \
PayoffData(g.strategies["All"][1], 1, payoffs[c])]})
g.addProfile({"All":[PayoffData(g.strategies["All"][1], 2, payoffs[d])]})
return g
def congestion_game(N, facilities, required):
"""
Generates random congestion games with N players and nCr(f,r) strategies.
Congestion games are symmetric, so all players belong to role All. Each
strategy is a subset of size #required among the size #facilities set of
available facilities. Payoffs for each strategy are summed over facilities.
Each facility's payoff consists of three components:
-constant ~ U[0,#facilities]
-linear congestion cost ~ U[-#required,0]
-quadratic congestion cost ~ U[-1,0]
"""
roles = ["All"]
players = {"All":N}
strategies = {'+'.join(["f"+str(f) for f in strat]):strat for strat in \
combinations(range(facilities), required)}
facility_values = [array([U(facilities), U(-required), U(-1)]) for __ in \
range(facilities)]
g = Game(roles, players, {"All":strategies.keys()})
for prof in g.allProfiles():
payoffs = []
useage = [0]*facilities
for strat, count in prof["All"].items():
for facility in strategies[strat]:
useage[facility] += count
for strat, count in prof["All"].items():
payoffs.append(PayoffData(strat, count, [sum(useage[f]**arange(3) \
* facility_values[f]) for f in strategies[strat]]))
g.addProfile({"All":payoffs})
return g
def local_effect_game(N, S):
"""
Generates random congestion games with N players and S strategies.
Local effect games are symmetric, so all players belong to role All. Each
strategy corresponds to a node in the G(N,2/S) local effect graph. Payoffs
for each strategy consist of constant terms for each strategy, and
interaction terms for the number of players choosing that strategy and each
neighboring strategy.
The one-strategy terms are drawn as follows:
-constant ~ U[-N-S,N+S]
-linear ~ U[-N,0]
The neighbor strategy terms are drawn as follows:
-linear ~ U[-S,S]
-quadratic ~ U[-1,1]
"""
g = __make_symmetric_game(N, S)
strategies = g.strategies["All"]
local_effects = {s:{} for s in strategies}
for s in strategies:
for d in strategies:
if s == d:
local_effects[s][d] = [U(-N-S,N+S),U(-N,0)]
elif U(0,S) > 2:
local_effects[s][d] = [U(-S,S),U(-1,1)]
for prof in g.allProfiles():
payoffs = []
for strat, count in prof["All"].items():
value = local_effects[strat][strat][0] + \
local_effects[strat][strat][1] * count
for neighbor in local_effects[strat]:
if neighbor not in prof["All"]:
continue
nc = prof["All"][neighbor]
value += local_effects[strat][neighbor][0] * count
value += local_effects[strat][neighbor][1] * count**2
payoffs.append(PayoffData(strat, count, value))
g.addProfile({"All":payoffs})
return g
def polymatrix_game(N, S, matrix_game=partial(independent_game,2)):
"""
Creates a polymatrix game using the specified 2-player matrix game function.
Each player's payoff in each profile is a sum over independent games played
against each opponent. Each pair of players plays an instance of the
specified random 2-player matrix game.
N: number of players
S: number of strategies
matrix_game: a function of one argument (S) that returns 2-player,
S-strategy games.
"""
g = __make_asymmetric_game(N, S)
matrices = {pair : matrix_game(S) for pair in combinations(g.roles, 2)}
for prof in g.allProfiles():
payoffs = {r:0 for r in g.roles}
for role in g.roles:
role_strat = prof[role].keys()[0]
for other in g.roles:
if role < other:
m = matrices[(role, other)]
p0 = sorted(m.players.keys())[0]
p1 = sorted(m.players.keys())[1]
elif role > other:
m = matrices[(other, role)]
p0 = sorted(m.players.keys())[1]
p1 = sorted(m.players.keys())[0]
else:
continue
other_strat = prof[other].keys()[0]
s0 = m.strategies[p0][g.strategies[role].index(role_strat)]
s1 = m.strategies[p1][g.strategies[other].index(other_strat)]
m_prof = Profile({p0:{s0:1},p1:{s1:1}})
payoffs[role] += m.getPayoff(m_prof, p0, s0)
g.addProfile({r:[PayoffData(prof[r].keys()[0], 1, payoffs[r])] \
for r in g.roles})
return g
game_functions = filter(lambda k: k.endswith("game") and not \
k.startswith("__"), globals().keys())
def add_noise(game, model, spread, samples):
"""
Generate sample game with random noise added to each payoff.
game: a RSG.Game or RSG.SampleGame
model: a 2-parameter function that generates mean-zero noise
spread, samples: the parameters passed to the noise function
"""
sg = SampleGame(game.roles, game.players, game.strategies)
for prof in game.knownProfiles():
sg.addProfile({r:[PayoffData(s, prof[r][s], game.getPayoff(prof,r,s) + \
model(spread, samples)) for s in prof[r]] for r in game.roles})
return sg
def gaussian_mixture_noise(max_stdev, samples, modes=2, spread_mult=2):
"""
Generate Gaussian mixture noise to add to one payoff in a game.
max_stdev: maximum standard deviation for the mixed distributions (also
affects how widely the mixed distributions are spaced)
samples: numer of samples to take of every profile
modes: number of Gaussians to mix
spread_mult: multiplier for the spread of the Gaussians. Distance between
the mean and the nearest distribution is drawn from
N(0,max_stdev*spread_mult).
"""
multipliers = arange(float(modes)) - float(modes-1)/2
offset = normal(0, max_stdev * spread_mult)
stdev = beta(2,1) * max_stdev
return [normal(choice(multipliers)*offset, stdev) for _ in range(samples)]
eq_var_normal_noise = partial(normal, 0)
normal_noise = partial(gaussian_mixture_noise, modes=1)
bimodal_noise = partial(gaussian_mixture_noise, modes=2)
def nonzero_gaussian_noise(max_stdev, samples, prob_pos=0.5, spread_mult=1):
"""
Generate Noise from a normal distribution centered up to one stdev from 0.
With prob_pos=0.5, this implements the previous buggy output of
bimodal_noise.
max_stdev: maximum standard deviation for the mixed distributions (also
affects how widely the mixed distributions are spaced)
samples: numer of samples to take of every profile
prob_pos: the probability that the noise mean for any payoff will be >0.
spread_mult: multiplier for the spread of the Gaussians. Distance between
the mean and the mean of the distribution is drawn from
N(0,max_stdev*spread_mult).
"""
offset = normal(0, max_stdev)*(1 if U(0,1) < prob_pos else -1)*spread_mult
stdev = beta(2,1) * max_stdev
return normal(offset, stdev, samples)
def uniform_noise(max_half_width, samples):
"""
Generate uniform random noise to add to one payoff in a game.
max_range: maximum half-width of the uniform distribution
samples: numer of samples to take of every profile
"""
hw = beta(2,1) * max_half_width
return U(-hw, hw, samples)
def gumbel_noise(scale, samples, flip_prob=0.5):
"""
Generate random noise according to a gumbel distribution.
Gumbel distributions are skewed, so the default setting of the flip_prob
parameter makes it equally likely to be skewed positive or negative
"""
location = -0.5772*scale
multiplier = -1 if (U(0,1) < flip_prob) else 1
return multiplier * gumbel(location, scale, samples)
def mix_models(models, rates, spread, samples):
"""
Generate SampleGame with noise drawn from several models.
models: a list of 2-parameter noise functions to draw from
rates: the probabilites with which a payoff will be drawn from each model
spread, samples: the parameters passed to the noise functions
"""
cum_rates = cumsum(rates)
m = models[bisect(cum_rates, U(0,1))]
return m(spread, samples)
n80b20_noise = partial(mix_models, [normal_noise, bimodal_noise], [.8,.2])
n60b40_noise = partial(mix_models, [normal_noise, bimodal_noise], [.6,.4])
n40b60_noise = partial(mix_models, [normal_noise, bimodal_noise], [.4,.6])
n20b80_noise = partial(mix_models, [normal_noise, bimodal_noise], [.2,.8])
equal_mix_noise = partial(mix_models, [normal_noise, bimodal_noise, \
uniform_noise, gumbel_noise], [.25]*4)
mostly_normal_noise = partial(mix_models, [normal_noise, bimodal_noise, \
gumbel_noise], [.8,.1,.1])
noise_functions = filter(lambda k: k.endswith("_noise") and not \
k.startswith("add_"), globals().keys())
def rescale_payoffs(game, min_payoff=0, max_payoff=100):
"""
Rescale game's payoffs to be in the range [min_payoff, max_payoff].
Modifies game.values in-place.
"""
game.makeArrays()
min_val = game.values.min()
max_val = game.values.max()
game.values -= min_val
game.values *= (max_payoff - min_payoff)
game.values /= (max_val - min_val)
game.values += min_payoff
def parse_args():
parser = IO.io_parser(description="Generate random games.")
parser.add_argument("type", choices=["uZS", "uSym", "CG", "LEG"], help= \
"Type of random game to generate. uZS = uniform zero sum. " +\
"uSym = uniform symmetric. CG = congestion game.")
parser.add_argument("count", type=int, help="Number of random games " +\
"to create.")
parser.add_argument("-noise", choices=["none", "normal", \
"gauss_mix"], default="None", help="Noise function.")
parser.add_argument("-noise_args", nargs="*", default=[], \
help="Arguments to be passed to the noise function.")
parser.add_argument("-game_args", nargs="*", default=[], \
help="Additional arguments for game generator function.")
assert "-input" not in IO.sys.argv, "no input JSON required"
IO.sys.argv = IO.sys.argv[:3] + ["-input", None] + IO.sys.argv[3:]
return parser.parse_args()
def main():
args = parse_args()
if args.type == "uZS":
game_func = uniform_zero_sum_game
assert len(args.game_args) == 1, "game_args must specify strategy count"
elif args.type == "uSym":
game_func = uniform_symmetric_game
assert len(args.game_args) == 2, "game_args must specify player and "+\
"strategy counts"
elif args.type == "CG":
game_func = congestion_game
assert len(args.game_args) == 3, "game_args must specify player, "+\
"facility, and required facility counts"
elif args.type == "LEG":
game_func = local_effect_game
assert len(args.game_args) == 2, "game_args must specify player and "+\
"strategy counts"
game_args = map(int, args.game_args)
games = [game_func(*game_args) for __ in range(args.count)]
if args.noise == "normal":
assert len(args.noise_args) == 2, "noise_args must specify stdev "+\
"and sample count"
noise_args = [float(args.noise_args[0]), int(args.noise_args[1])]
games = map(lambda g: normal_noise(g, *noise_args), games)
elif args.noise == "gauss_mix":
assert len(args.noise_args) == 3, "noise_args must specify max "+\
"stdev, sample count, and number of modes"
noise_args = [float(args.noise_args[0]), int(args.noise_args[1]), \
int(args.noise_args[2])]
games = map(lambda g: gaussian_mixture_noise(g, *noise_args), games)
if len(games) == 1:
print IO.to_JSON_str(games[0])
else:
print IO.to_JSON_str(games)
if __name__ == "__main__":
main()