def test_lemke_howson_enumeration(self): """Test for the enumeration of equilibrium using Lemke Howson""" A = np.array([[3, 1], [0, 2]]) B = np.array([[2, 1], [0, 3]]) g = nash.Game(A, B) expected_equilibria = [(np.array([1, 0]), np.array([1, 0])), (np.array([0, 1]), np.array([0, 1]))] * 2 equilibria = g.lemke_howson_enumeration() for equilibrium, expected_equilibrium in zip(equilibria, expected_equilibria): for strategy, expected_strategy in zip(equilibrium, expected_equilibrium): self.assertTrue(all(np.isclose(strategy, expected_strategy))) A = np.array([[3, 1], [1, 3]]) B = np.array([[1, 3], [3, 1]]) g = nash.Game(A, B) expected_equilibria = [(np.array([1 / 2, 1 / 2 ]), np.array([1 / 2, 1 / 2]))] * 4 equilibria = g.lemke_howson_enumeration() for equilibrium, expected_equilibrium in zip(equilibria, expected_equilibria): for strategy, expected_strategy in zip(equilibrium, expected_equilibrium): self.assertTrue(all(np.isclose(strategy, expected_strategy)))
def test_bi_matrix_init(self, A, B): """Test that can create a bi matrix game""" g = nash.Game(A, B) self.assertEqual(g.payoff_matrices, (A, B)) if np.array_equal(A, -B): # Check if A or B are non zero self.assertTrue(g.zero_sum) else: self.assertFalse(g.zero_sum) # Can also init with lists A = A.tolist() B = B.tolist() g = nash.Game(A, B) self.assertTrue(np.array_equal(g.payoff_matrices[0], np.asarray(A))) self.assertTrue(np.array_equal(g.payoff_matrices[1], np.asarray(B)))
def test_bi_matrix_init(self): """Test that can create a bi matrix game""" A = np.array([[1, 2], [2, 1]]) B = np.array([[2, 1], [1, 2]]) g = nash.Game(A, B) self.assertEqual(g.payoff_matrices, (A, B)) self.assertFalse(g.zero_sum) # Can also init with lists A = [[1, 2], [2, 1]] B = [[2, 1], [1, 2]] g = nash.Game(A, B) self.assertTrue(np.array_equal(g.payoff_matrices[0], np.asarray(A))) self.assertTrue(np.array_equal(g.payoff_matrices[1], np.asarray(B))) self.assertFalse(g.zero_sum)
def test_zero_sum_game_init(self, A): """Test that can create a zero sum game""" g = nash.Game(A) self.assertTrue(np.array_equal(g.payoff_matrices[0], A)) self.assertTrue( np.array_equal(g.payoff_matrices[0], -g.payoff_matrices[1])) self.assertTrue(g.zero_sum) # Can also init with lists A = A.tolist() g = nash.Game(A) self.assertTrue(np.array_equal(g.payoff_matrices[0], np.asarray(A))) self.assertTrue( np.array_equal(g.payoff_matrices[0], -g.payoff_matrices[1])) self.assertTrue(g.zero_sum)
def __find_nash_equilibrium(self): # set up a game game = nash.Game(self.__Firm_1_payoffs, self.__Firm_2_payoffs) # find nash equilibrium strategy nash_equilibrium = list(game.support_enumeration()) # Firm 1 nash equilibrium strategy Firm_1_nash_equilibrium = nash_equilibrium[0][0] # Firm 2 nash equilibrium strategy Firm_2_nash_equilibrium = nash_equilibrium[0][1] # Get the number of nash equilibrium strategy for Firm 1 Firm_1_ne_strategy = np.where(Firm_1_nash_equilibrium == 1)[0][0] # Get the number of nash equilibrium strategy for Firm 2 Firm_2_ne_strategy = np.where(Firm_2_nash_equilibrium == 1)[0][0] # Determine payoffs for chosen strategies: Firm_1_ne_payoff = self.__Firm_1_payoffs[ Firm_1_ne_strategy][Firm_2_ne_strategy] Firm_2_ne_payoff = self.__Firm_2_payoffs[ Firm_1_ne_strategy][Firm_2_ne_strategy] # Print results: if Firm_1_ne_strategy == 0: print 'Nash equilibrium strategy for Firm 1 is Aggressive.\ Payoff is', Firm_1_ne_payoff else: print 'Nash equilibrium strategy for Firm 1 is Passive.\ Payoff is', Firm_1_ne_payoff if Firm_2_ne_strategy == 0: print 'Nash equilibrium strategy for Firm 2 is Aggressive.\ Payoff is', Firm_2_ne_payoff else: print 'Nash equilibrium strategy for Firm 2 is Passive.\ Payoff is', Firm_2_ne_payoff
def test_solve_indifference(self): """Test solve indifference""" A = np.array([[0, 1, -1], [1, 0, 1], [-1, 1, 0]]) g = nash.Game(A) rows = [0, 1] columns = [0, 1] self.assertTrue( np.array_equal(g.solve_indifference(A, rows, columns), np.array([0.5, 0.5, 0.]))) rows = [1, 2] columns = [0, 1] self.assertTrue( all( np.isclose(g.solve_indifference(A, rows, columns), np.array([1 / 3, 2 / 3, 0.])))) rows = [0, 2] columns = [0, 1] self.assertTrue( np.array_equal(g.solve_indifference(A, rows, columns), np.array([0., 1.0, 0.]))) rows = [0, 1, 2] columns = [0, 1, 2] self.assertTrue( all( np.isclose(g.solve_indifference(A, rows, columns), np.array([0.2, 0.6, 0.2]))))
def test_is_ne(self): """Test if is ne""" A = np.array([[2, 1], [0, 2]]) B = np.array([[2, 0], [1, 2]]) g = nash.Game(A, B) strategy_pair = np.array([1, 0]), np.array([1, 0]) support_pair = [0], [0] self.assertTrue(g.is_ne(strategy_pair, support_pair)) strategy_pair = np.array([1 / 3, 2 / 3]), np.array([1 / 3, 2 / 3]) support_pair = [0, 1], [0, 1] self.assertTrue(g.is_ne(strategy_pair, support_pair)) strategy_pair = np.array([0, 1]), np.array([1, 0]) support_pair = [1], [0] self.assertFalse(g.is_ne(strategy_pair, support_pair)) strategy_pair = np.array([1, 0]), np.array([0, 1]) support_pair = [0], [1] self.assertFalse(g.is_ne(strategy_pair, support_pair)) A = np.array([[1, -1], [-1, 1]]) g = nash.Game(A) strategy_pair = np.array([1 / 2, 1 / 2]), np.array([1 / 2, 1 / 2]) support_pair = [0, 1], [0, 1] self.assertTrue(g.is_ne(strategy_pair, support_pair)) A = np.array([[0, 1, -1], [-1, 0, 1], [1, -1, 0]]) g = nash.Game(A) strategy_pair = (np.array([1 / 3, 1 / 3, 1 / 3]), np.array([1 / 3, 1 / 3, 1 / 3])) support_pair = [0, 1, 2], [0, 1, 2] self.assertTrue(g.is_ne(strategy_pair, support_pair)) strategy_pair = (np.array([1, 0, 0]), np.array([1, 0, 0])) support_pair = [0], [0] self.assertFalse(g.is_ne(strategy_pair, support_pair)) A = np.array([[160, 205, 44], [175, 180, 45], [201, 204, 50], [120, 207, 49]]) B = np.array([[2, 2, 2], [1, 0, 0], [3, 4, 1], [4, 1, 2]]) g = nash.Game(A, B) self.assertTrue( g.is_ne((np.array( (0, 0, 3 / 4, 1 / 4)), np.array((1 / 28, 27 / 28, 0))), (np.array([2, 3]), np.array([0, 1]))))
def test_vertex_enumeration_for_bi_matrix(self): """Test for the equilibria calculation using vertex enumeration""" A = np.array([[160, 205, 44], [175, 180, 45], [201, 204, 50], [120, 207, 49]]) B = np.array([[2, 2, 2], [1, 0, 0], [3, 4, 1], [4, 1, 2]]) g = nash.Game(A, B) expected_equilibria = [(np.array([0, 0, 3 / 4, 1 / 4]), np.array([1 / 28, 27 / 28, 0]))] for obtained, expected in zip(g.vertex_enumeration(), expected_equilibria): for s1, s2 in zip(obtained, expected): self.assertTrue(all(np.isclose(s1, s2)), msg="obtained: {} !=expected: {}".format( obtained, expected)) A = np.array([[1, 0], [-2, 3]]) B = np.array([[3, 2], [-1, 0]]) g = nash.Game(A, B) expected_equilibria = [(np.array([1, 0]), np.array([1, 0])), (np.array([0, 1]), np.array([0, 1])), (np.array([1 / 2, 1 / 2]), np.array([1 / 2, 1 / 2]))] for obtained, expected in zip(g.vertex_enumeration(), expected_equilibria): for s1, s2 in zip(obtained, expected): self.assertTrue(all(np.isclose(s1, s2)), msg="obtained: {} !=expected: {}".format( obtained, expected)) A = np.array([[2, 1], [0, 2]]) B = np.array([[2, 0], [1, 2]]) g = nash.Game(A, B) expected_equilibria = [(np.array([1, 0]), np.array([1, 0])), (np.array([0, 1]), np.array([0, 1])), (np.array([1 / 3, 2 / 3]), np.array([1 / 3, 2 / 3]))] for obtained, expected in zip(g.vertex_enumeration(), expected_equilibria): for s1, s2 in zip(obtained, expected): self.assertTrue(all(np.isclose(s1, s2)), msg="obtained: {} !=expected: {}".format( obtained, expected))
def find_snash(self): g = nash.Game(self.game, np.transpose(self.game)) eqs = list(g.support_enumeration()) sym = [] for eq in eqs: if self.symmetric(eq): sym += [eq] return sym
def test_lemke_howson_for_bi_matrix(self): """Test for the equilibria calculation using lemke howson""" A = np.array([[160, 205, 44], [175, 180, 45], [201, 204, 50], [120, 207, 49]]) B = np.array([[2, 2, 2], [1, 0, 0], [3, 4, 1], [4, 1, 2]]) g = nash.Game(A, B) expected_equilibria = (np.array([0, 0, 3 / 4, 1 / 4]), np.array([1 / 28, 27 / 28, 0])) equilibria = g.lemke_howson(initial_dropped_label=4) for eq, expected in zip(equilibria, expected_equilibria): self.assertTrue(all(np.isclose(eq, expected)))
def get_nash_game(graph, state, poss_choices, weights): choices1 = poss_choices[0] choices2 = poss_choices[1] arr = np.zeros((len(choices1), len(choices2))) for i in range(len(choices1)): c1 = choices1[i] for j in range(len(choices2)): c2 = choices2[j] result_state = choice_result([c1, c2], state) arr[i][j] = graph.node[str(result_state)]['value'] return nash.Game(arr)
def test_zero_sum_repr(self): """Test that can create a bi matrix game""" A = np.array([[1, -1], [-1, 1]]) g = nash.Game(A) string_repr = """Zero sum game with payoff matrices: Row player: [[ 1 -1] [-1 1]] Column player: [[-1 1] [ 1 -1]]""" self.assertEqual(g.__repr__(), string_repr)
def test_property_support_enumeration(self, A, B): """Property based test for the equilibria calculation""" g = nash.Game(A, B) for equilibrium in g.support_enumeration(): for i, s in enumerate(equilibrium): # Test that have a probability vector (subject to numerical # error) self.assertAlmostEqual(s.sum(), 1) # Test that it is of the correct size self.assertEqual(s.size, [3, 4][i]) # Test that it is non negative self.assertTrue(all(s >= 0))
def test_obey_support(self): """Test for obey support""" A = np.array([[2, 1], [0, 2]]) B = np.array([[2, 0], [1, 2]]) g = nash.Game(A, B) self.assertFalse(g.obey_support(False, np.array([0, 1]))) self.assertFalse(g.obey_support(np.array([1, 0]), np.array([0, 1]))) self.assertFalse(g.obey_support(np.array([0, .5]), np.array([0]))) self.assertFalse(g.obey_support(np.array([.5, 0]), np.array([1]))) self.assertTrue(g.obey_support(np.array([1, 0]), np.array([0]))) self.assertTrue(g.obey_support(np.array([0, .5]), np.array([1]))) self.assertTrue(g.obey_support(np.array([.5, 0]), np.array([0]))) self.assertTrue(g.obey_support(np.array([.5, .5]), np.array([0, 1])))
def test_particular_lemke_howson_raises_warning(self): """ This is a degenerate game so the algorithm fails. This was raised in https://github.com/drvinceknight/Nashpy/issues/35 """ A = np.array([[-1, -1, -1], [0, 0, 0], [-1, -1, -10000]]) B = np.array([[-1, -1, -1], [0, 0, 0], [-1, -1, -10000]]) game = nash.Game(A, B) with warnings.catch_warnings(record=True) as w: eqs = game.lemke_howson(initial_dropped_label=0) self.assertEqual(len(eqs[0]), 2) self.assertEqual(len(eqs[1]), 4) self.assertGreater(len(w), 0) self.assertEqual(w[-1].category, RuntimeWarning)
def test_bi_matrix_repr(self): """Test that can create a bi matrix game""" A = np.array([[1, 2], [2, 1]]) B = np.array([[2, 1], [1, 2]]) g = nash.Game(A, B) string_repr = """Bi matrix game with payoff matrices: Row player: [[1 2] [2 1]] Column player: [[2 1] [1 2]]""" self.assertEqual(g.__repr__(), string_repr)
def test_potential_supports(self): """Test for the enumeration of potential supports""" A = np.array([[1, 0], [-2, 3]]) B = np.array([[3, 2], [-1, 0]]) g = nash.Game(A, B) self.assertEqual(list(g.potential_support_pairs()), [((0, ), (0, )), ((0, ), (1, )), ((1, ), (0, )), ((1, ), (1, )), ((0, 1), (0, 1))]) A = np.array([[1, 0, 2], [-2, 3, 9]]) B = np.array([[3, 2, 1], [-1, 0, 2]]) g = nash.Game(A, B) self.assertEqual(list(g.potential_support_pairs()), [((0, ), (0, )), ((0, ), (1, )), ((0, ), (2, )), ((1, ), (0, )), ((1, ), (1, )), ((1, ), (2, )), ((0, 1), (0, 1)), ((0, 1), (0, 2)), ((0, 1), (1, 2))]) A = np.array([[1, 0], [-2, 3], [2, 1]]) B = np.array([[3, 2], [-1, 0], [5, 2]]) g = nash.Game(B, A) self.assertEqual(list(g.potential_support_pairs()), [((0, ), (0, )), ((0, ), (1, )), ((1, ), (0, )), ((1, ), (1, )), ((2, ), (0, )), ((2, ), (1, )), ((0, 1), (0, 1)), ((0, 2), (0, 1)), ((1, 2), (0, 1))])
def test_get_item(self): """Test solve indifference""" A = np.array([[1, -1], [-1, 1]]) g = nash.Game(A) row_strategy = [0, 1] column_strategy = [1, 0] self.assertTrue( np.array_equal(g[row_strategy, column_strategy], np.array( (-1, 1)))) row_strategy = [1 / 2, 1 / 2] column_strategy = [1 / 2, 1 / 2] self.assertTrue( np.array_equal(g[row_strategy, column_strategy], np.array((0, 0))))
def get_nash_game_recur(graph, state, poss_choices=None, weights=default_weights): n_players = 2 if poss_choices is None: poss_choices = [possible_choices(state, i) for i in range(n_players)] choices1 = poss_choices[0] choices2 = poss_choices[1] arr = np.zeros((len(choices1), len(choices2))) for i in range(len(choices1)): c1 = choices1[i] for j in range(len(choices2)): c2 = choices2[j] result_state = choice_result([c1, c2], state) _, poss_c = possible_results(result_state) arr[i][j] = get_nash_value_recur(graph, result_state, poss_c, weights) return nash.Game(arr)
def test_indifference_strategies(self): """Test for the enumeration of potential supports""" A = np.array([[2, 1], [0, 2]]) B = np.array([[2, 0], [1, 2]]) g = nash.Game(A, B) expected_indifference = [(np.array([1, 0]), np.array([1, 0])), (np.array([1, 0]), np.array([0, 1])), (np.array([0, 1]), np.array([1, 0])), (np.array([0, 1]), np.array([0, 1])), (np.array([1 / 3, 2 / 3]), np.array([1 / 3, 2 / 3]))] obtained_indifference = [ out[:2] for out in g.indifference_strategies() ] self.assertEqual(len(obtained_indifference), len(expected_indifference)) for obtained, expected in zip(obtained_indifference, expected_indifference): self.assertTrue(np.array_equal(obtained, expected), msg="obtained: {} !=expected: {}".format( obtained, expected))
def call(self): array1 = [] array2 = [] for i in range(0, 4): if self.isNum(self.entryName[i * 2].get()) == False or self.isNum( self.entryName[i * 2 + 1].get()) == False: tkinter.messagebox.showerror("Error", "输入不合法!") return array1.append(int(self.entryName[i * 2].get())) array2.append(int(self.entryName[i * 2 + 1].get())) A = np.array([array1[0:2], array1[2:4]]) B = np.array([array2[0:2], array2[2:4]]) rps = nash.Game(A, B) # print(rps) eqs = rps.support_enumeration() # print(list(eqs)) label = tkinter.Label(root, text='计算结果:', justify=tkinter.RIGHT, width=80) label.place(x=10, y=140, width=80, height=20) text2 = tkinter.Text(root, height=20, width=50) set_precision = 4 cnt = 1 for ans in eqs: tmp = '策略' + str(cnt) + ': ' + '(' + '(' + str( round(ans[0][0], set_precision)) + ',' + str( round(ans[0][1], set_precision)) + ')' + ' , ' tmp += '(' + str(round(ans[1][0], set_precision)) + ',' + str( round(ans[1][1], set_precision)) + ')' + ')' tmp += '\n' # print (tmp) text2.insert('end', tmp) cnt += 1 text2.place(x=10, y=160)
def find_nash(self): g = nash.Game(self.game, np.transpose(self.game)) return list(g.support_enumeration())
#Nash Equilibrium--In the Nash Equilibrium, each player's strategy is optimal when considering the decisions of other players Read more: Nash Equilibrium https://www.investopedia.com/terms/n/nash-equilibrium.asp#ixzz4ySuAWtbx Follow us: Investopedia on Facebook#NashPy library is included in SciPy. This is a library for simple 2 player games. #Example 1 >>> import nash >>> A = [[1, 2], [3, 0]] >>> B = [[0, 2], [3, 1]] >>> battle_of_the_sexes = nash.Game(A, B) >>> for eq in battle_of_the_sexes.support_enumeration(): ... print(eq) (array([ 1., 0.]), array([ 0., 1.])) (array([ 0., 1.]), array([ 1., 0.])) (array([ 0.5, 0.5]), array([ 0.5, 0.5])) >>> battle_of_the_sexes[[0, 1], [1, 0]] array([3, 3]) #Example 2 >>> import nash >>> A = [[1, 2], [3, 0]] >>> B = [[4, 2], [9, 8]] >>> battle_of_the_sexes = nash.Game(A, B) >>> for eq in battle_of_the_sexes.support_enumeration(): ... print(eq) ... (array([ 0., 1.]), array([ 1., 0.])) >>> battle_of_the_sexes[[0, 1], [1, 0]] array([3, 9])
closest_vector = v return closest_vector def rand_game(i): return np.array([[random.randint(-i, i), random.randint(-i, i)], [random.randint(-i, i), random.randint(-i, i)]]) for _ in range(NUM_TESTS): #game = rand_game(5) n = nash.Game(game, np.transpose(game)) print(n) equilibria = [np.asarray(x) for x in n.support_enumeration()] print("Equilibria:") for x in equilibria: print(x) for p_name, p in tests: #game = np.array([[2, 0],[3, 1]], dtype=np.float) parameters = { "game": game, "w": 0.1, "model_type": p,
def solveGame(U_crash_y=-100, U_crash_x=-100, U_time=1., NY=20, NX=20): V = np.zeros((NY, NX, 2)) #vals as pairs in 3rd dim S = np.zeros((NY, NX, 2)) #strategies at each point, as yield probs #successful passing end states [y,x,player_to_reward Y=0] Y = 0 X = 1 for x in range(1, NX): #Y has won V[0, x, Y] = 0. V[0, x, X] = -U_time * (x / 2.) for x in range(2, NX): V[1, x, Y] = 0. V[1, x, X] = -U_time * ((x - 1) / 2.) for y in range(1, NY): #X has won V[y, 0, X] = 0. V[y, 0, Y] = -U_time * (y / 2.) for y in range(2, NY): V[y, 1, X] = 0. V[y, 1, Y] = -U_time * ((y - 1) / 2.) #crash end states -- overwrite V[0, 0, Y] = U_crash_y V[0, 0, X] = U_crash_x V[1, 1, Y] = U_crash_y V[1, 1, X] = U_crash_x #recursively compute optimal strategies and game values for x in range(2, NX): for y in range(2, NY): print("--" + str(y) + "_" + str(x)) Y = [[0, 0], [0, 0]] X = [[0, 0], [0, 0]] #pdb.set_trace() #make subgame payoff matrix. Actions: move-1, move-2 for ay in [1, 2]: #action me, action u for ax in [1, 2]: y_next = y - ay x_next = x - ax val_y = V[y_next, x_next, 0] val_x = V[y_next, x_next, 1] Y[ay - 1][ax - 1] = val_y - 1 #each tick pays 1 second X[ay - 1][ax - 1] = val_x - 1 # print(Y) # print(X) # if y==2 \u-nd x==7: # pdb.set_trace() #compute the nashes - pynash G = nash.Game(Y, X) eqs = G.support_enumeration() #question one: is there at least one symetric equilibrium? b_exists_sym_eq = False eq_list = [] for eq in eqs: eq_list.append(eq) for eq in eq_list: #pdb.set_trace() b_sym = np.abs(eq[0][0] - eq[1][0]) < 0.0001 #symetric if b_sym: b_exists_sym_eq = True #pdb.set_trace() #throw away any dominated ones eq_best = 0 vY_best = -999 #vals of both players at single best known equilibrium vX_best = -999 # pdb.set_trace() for eq in eq_list: b_sym = np.abs( eq[0][0] - eq[1][0]) < 0.0001 #real number equality is uncomputable! #how do we know what floating point #is being used by the other player !? #if b_exists_sym_eq and not b_sym: # continue #discard asym equilibria if there exist sym ones (vY, vX) = G[eq[0], eq[1]] #values to players #b_dom = ( vY<vY_best and vX < vX_best ) #is it dominated? #HACK HACK HACK #if not b_dom: #assume for now that there is only one of these! if b_sym: #assume for now that there is only one of these! eq_best = eq #TODO metatrategy convergence is more than one vY_best = vY vX_best = vX #then meta-strategy convergence... TODO #pdb.set_trace() print("best", eq_best) #log results S[y, x, 0] = eq_best[0][0] #yield probs -> strategy S[y, x, 1] = eq_best[1][0] V[y, x, 0] = vY_best V[y, x, 1] = vX_best return (V, S)
def plot_matrix_pair(A, B, subplot_base=121, norm_max=1, norm_min=-1, colour='grey', plot_poly=True, cfill=False, save_str="", offset_watermark=False): '''Plots a game A vs B to the screen. Polytope Vertacies: 0:cyan, 1:magenta, 2:black, 3:blue''' # Create [0,1]^2 plane: x_range, y_range = [np.arange(0, 1.1, 0.01)] * 2 x_grid, y_grid = np.meshgrid(x_range, y_range) polytope_eqns = get_polytope_vertex_eqns(A,B) game = nash.Game(A, B) eqlbria = list(game.support_enumeration()) num_eqs = len(eqlbria) # Build the Data for row player: row_Z = get_utility_plane(x_grid, y_grid, A) # Build the Data for col player: col_Z = get_utility_plane(x_grid, y_grid, B) #PLOTS plt.rcParams['axes.facecolor'] = colour #Row: P = {x \in R | x>=0, xB<=1} plt.subplot(subplot_base) if cfill: plt.contourf(x_grid, y_grid, row_Z, 15, cmap='RdYlGn') # Norm is for the coloured lines else: plt.contour(x_grid, y_grid, row_Z, cmap='RdYlGn', norm=mpl.colors.Normalize(vmin=norm_min, vmax=norm_max)) # Norm is for the coloured lines if plot_poly: plt.plot(x_range,[1,1]+[0]*(len(x_range)-2),'c-',x_range,[0.01]*len(x_range),'m-') plt.plot(x_range,polytope_eqns[2](x_range),'k-',x_range,polytope_eqns[3](x_range),'b-') plt.colorbar() eqs = ",".join(["{:.1f}".format(eqlbria[n][0][0]) for n in range(num_eqs)]) plt.title("$u_r$ plane | eq@$x="+eqs+"$") plt.xlabel("$x$ for $\sigma_r=(x,1-x)$") plt.ylabel("$y$ for $\sigma_c=(y,1-y)$") plt.xlim(0,1) plt.ylim(0,1) if offset_watermark: plt.text(0.66, 0.66,'$u_r$', horizontalalignment='center',verticalalignment='center', color='grey', fontsize=40, alpha=0.4) else: plt.text(0.5, 0.5,'$u_r$', horizontalalignment='center',verticalalignment='center', color='grey', fontsize=40, alpha=0.4) #Col: Q = {y \in R | Ay<=1, y>=0} plt.subplot(subplot_base+1) if cfill: plt.contourf(x_grid, y_grid, col_Z, 15, cmap='RdYlGn') # Norm is for the coloured lines else: plt.contour(x_grid, y_grid, col_Z, cmap='RdYlGn', norm=mpl.colors.Normalize(vmin=norm_min, vmax=norm_max)) # Norm is for the coloured lines if plot_poly: plt.plot(x_range,[1,1]+[0]*(len(x_range)-2),'k-',x_range,[0.01]*len(x_range),'b-') plt.plot(x_range,polytope_eqns[0](x_range),'c-',x_range,polytope_eqns[1](x_range),'m-') plt.colorbar() eqs = ",".join(["{:.1f}".format(eqlbria[n][1][0]) for n in range(num_eqs)]) plt.title("$u_c$ plane | eq@$y="+eqs+"$") plt.xlabel("$x$ for $\sigma_r=(x,1-x)$") plt.ylabel("$y$ for $\sigma_c=(y,1-y)$") plt.xlim(0,1) plt.ylim(0,1) if offset_watermark: plt.text(0.66, 0.66,'$u_c$', horizontalalignment='center',verticalalignment='center', color='grey', fontsize=40, alpha=0.4) else: plt.text(0.5, 0.5,'$u_c$', horizontalalignment='center',verticalalignment='center', color='grey', fontsize=40, alpha=0.4) plt.tight_layout() if not save_str == "": plt.savefig("img/"+save_str)
def test_zero_sum_property_from_bi_matrix(self, A): """Test that can create a zero sum game""" B = -A g = nash.Game(A, B) self.assertTrue(g.zero_sum)
def test_zero_sum_property_from_bi_matrix(self): """Test that can create a zero sum game""" A = np.array([[1, 2], [2, 1]]) B = -A g = nash.Game(A, B) self.assertTrue(g.zero_sum)
#!/usr/bin/env python __author__ = 'joon' import nash import numpy as np p = np.array([[4.0, 6.6, 15.0, 22.2, 16.7, 9.9], [2.5, 2.3, 11.6, 18.5, 7.2, 4.9], [5.8, 7.6, 4.6, 23.6, 16.6, 9.1], [0.4, 0.8, 8.6, 5.8, 3.1, 1.4], [2.6, 2.2, 11.8, 18.1, 3.4, 4.3], [0.7, 0.9, 5.2, 9.5, 3.2, 2.0]]) minimaxgame = nash.Game(-p) eq = [e for e in minimaxgame.vertex_enumeration()] roweq = eq[0][0] coleq = eq[0][1] value = np.dot(roweq, np.dot(p, coleq)) print("Value of the game (privacy guarantee for U): %2.1f" % value) print("U's optimal strategy: {}".format(roweq)) print("R's optimal strategy: {}".format(coleq))