Esempio n. 1
0
class TestPlayer_2opponents:
    """Test the methods of Player with two opponent players"""
    def setUp(self):
        """Setup a Player instance"""
        payoffs_2opponents = [[[3, 6], [4, 2]], [[1, 0], [5, 7]]]
        self.player = Player(payoffs_2opponents)

    def test_payoff_vector_against_pure(self):
        assert_array_equal(self.player.payoff_vector((0, 1)), [6, 0])

    def test_is_best_response_against_pure(self):
        ok_(not self.player.is_best_response(0, (1, 0)))

    def test_best_response_against_pure(self):
        eq_(self.player.best_response((1, 1)), 1)

    def test_best_response_list_when_tie(self):
        """
        best_response against a mixed action profile with
        tie_breaking=False
        """
        assert_array_equal(
            sorted(
                self.player.best_response(([3 / 7, 4 / 7], [1 / 2, 1 / 2]),
                                          tie_breaking=False)), sorted([0, 1]))
Esempio n. 2
0
    def __init__(self, payoff_matrix, N):
        A = np.asarray(payoff_matrix)
        if A.ndim != 2 or A.shape[0] != A.shape[1]:
            raise ValueError('payoff matrix must be square')
        self.num_actions = A.shape[0]  # Number of actions
        self.N = N  # Number of players

        self.player = Player(A)  # "Representative player"
        self.tie_breaking = 'smallest'

        # Current action distribution
        self.current_action_dist = np.zeros(self.num_actions, dtype=int)
        self.current_action_dist[0] = self.N  # Initialization
Esempio n. 3
0
class TestPlayer_0opponents:
    """Test for degenerate Player with no opponent player"""
    def setUp(self):
        """Setup a Player instance"""
        payoffs = [0, 1]
        self.player = Player(payoffs)

    def test_payoff_vector(self):
        """Degenerate player: payoff_vector"""
        assert_array_equal(self.player.payoff_vector(None), [0, 1])

    def test_is_best_response(self):
        """Degenerate player: is_best_response"""
        ok_(self.player.is_best_response(1, None))

    def test_best_response(self):
        """Degenerate player: best_response"""
        eq_(self.player.best_response(None), 1)
Esempio n. 4
0
    def __init__(self, payoff_matrix, N):
        A = np.asarray(payoff_matrix)
        if A.ndim != 2 or A.shape[0] != A.shape[1]:
            raise ValueError("payoff matrix must be square")
        self.num_actions = A.shape[0]  # Number of actions
        self.N = N  # Number of players

        self.player = Player(A)  # "Representative player"
        self.tie_breaking = "smallest"

        # Current action distribution
        self.current_action_dist = np.zeros(self.num_actions, dtype=int)
        self.current_action_dist[0] = self.N  # Initialization
Esempio n. 5
0
class TestPlayer_1opponent:
    """Test the methods of Player with one opponent player"""
    def setUp(self):
        """Setup a Player instance"""
        coordination_game_matrix = [[4, 0], [3, 2]]
        self.player = Player(coordination_game_matrix)

    def test_best_response_against_pure(self):
        eq_(self.player.best_response(1), 1)

    def test_best_response_against_mixed(self):
        eq_(self.player.best_response([1 / 2, 1 / 2]), 1)

    def test_best_response_list_when_tie(self):
        """best_response with tie_breaking=False"""
        assert_array_equal(
            sorted(
                self.player.best_response([2 / 3, 1 / 3], tie_breaking=False)),
            sorted([0, 1]))

    def test_best_response_with_random_tie_breaking(self):
        """best_response with tie_breaking='random'"""
        ok_(
            self.player.best_response([2 / 3, 1 /
                                       3], tie_breaking='random') in [0, 1])

    def test_best_response_with_smallest_tie_breaking(self):
        """best_response with tie_breaking='smallest' (default)"""
        eq_(self.player.best_response([2 / 3, 1 / 3]), 0)

    def test_best_response_with_payoff_perturbation(self):
        """best_response with payoff_perturbation"""
        eq_(
            self.player.best_response([2 / 3, 1 / 3],
                                      payoff_perturbation=[0, 0.1]), 1)

    def test_is_best_response_against_pure(self):
        ok_(self.player.is_best_response(0, 0))

    def test_is_best_response_against_mixed(self):
        ok_(self.player.is_best_response([1 / 2, 1 / 2], [2 / 3, 1 / 3]))
Esempio n. 6
0
    def __init__(self, payoff_matrix, adj_matrix):
        self.adj_matrix = sparse.csr_matrix(adj_matrix)
        M, N = self.adj_matrix.shape
        if N != M:
            raise ValueError('adjacency matrix must be square')
        self.N = N  # Number of players

        A = np.asarray(payoff_matrix)
        if A.ndim != 2 or A.shape[0] != A.shape[1]:
            raise ValueError('payoff matrix must be square')
        self.num_actions = A.shape[0]  # Number of actions

        self.players = [Player(A) for i in range(self.N)]
        self.tie_breaking = 'smallest'

        init_actions = np.zeros(self.N, dtype=int)
        self.current_actions_mixed = sparse.csr_matrix(
            (np.ones(self.N, dtype=int), init_actions, np.arange(self.N + 1)),
            shape=(self.N, self.num_actions))
        self._current_actions = self.current_actions_mixed.indices.view()
Esempio n. 7
0
 def setUp(self):
     """Setup a Player instance"""
     payoffs_2opponents = [[[3, 6], [4, 2]], [[1, 0], [5, 7]]]
     self.player = Player(payoffs_2opponents)
Esempio n. 8
0
def test_normalformgame_invalid_input_players_num_inconsistent():
    p0 = Player(np.zeros((2, 2, 2)))
    p1 = Player(np.zeros((2, 2, 2)))
    g = NormalFormGame([p0, p1])
Esempio n. 9
0
 def setUp(self):
     """Setup a Player instance"""
     coordination_game_matrix = [[4, 0], [3, 2]]
     self.player = Player(coordination_game_matrix)
Esempio n. 10
0
 def setUp(self):
     """Setup a Player instance"""
     payoffs = [0, 1]
     self.player = Player(payoffs)
Esempio n. 11
0
 def setUp(self):
     """Setup a NormalFormGame instance"""
     payoffs_2opponents = [[[3, 6], [4, 2]], [[1, 0], [5, 7]]]
     player = Player(payoffs_2opponents)
     self.g = NormalFormGame([player for i in range(3)])
Esempio n. 12
0
class BRD(object):
    def __init__(self, payoff_matrix, N):
        A = np.asarray(payoff_matrix)
        if A.ndim != 2 or A.shape[0] != A.shape[1]:
            raise ValueError("payoff matrix must be square")
        self.num_actions = A.shape[0]  # Number of actions
        self.N = N  # Number of players

        self.player = Player(A)  # "Representative player"
        self.tie_breaking = "smallest"

        # Current action distribution
        self.current_action_dist = np.zeros(self.num_actions, dtype=int)
        self.current_action_dist[0] = self.N  # Initialization

    def set_init_action_dist(self, init_action_dist=None):
        """
        Set the attribute `current_action_dist` to `init_action_dist`.

        Parameters
        ----------
        init_action_dist : array_like(float, ndim=1),
                           optional(default=None)
            Array containing the initial action distribution. If not
            supplied, randomly chosen uniformly over the set of possible
            action distributions.

        """
        if init_action_dist is None:  # Randomly choose an action distribution
            cutoffs = np.empty(self.num_actions, dtype=int)
            cutoffs[-1] = self.N + self.num_actions - 1
            cutoffs[:-1] = np.random.choice(self.N + self.num_actions - 1, self.num_actions - 1, replace=False)
            cutoffs[:-1].sort()
            cutoffs[1:] -= cutoffs[:-1] + 1
            init_action_dist = cutoffs
        self.current_action_dist[:] = init_action_dist

    def play(self, current_action):
        self.current_action_dist[current_action] -= 1
        opponent_action_dist = self.current_action_dist
        next_action = self.player.best_response(opponent_action_dist, tie_breaking=self.tie_breaking)
        self.current_action_dist[next_action] += 1

    def simulate(self, ts_length, init_action_dist=None):
        action_dist_sequence = np.empty((ts_length, self.num_actions), dtype=int)
        action_dist_sequence_iter = self.simulate_iter(ts_length, init_action_dist=init_action_dist)

        for t, action_dist in enumerate(action_dist_sequence_iter):
            action_dist_sequence[t] = action_dist

        return action_dist_sequence

    def simulate_iter(self, ts_length, init_action_dist=None):
        self.set_init_action_dist(init_action_dist=init_action_dist)

        # Sequence of randomly chosen players to revise
        player_ind_sequence = np.random.randint(self.N, size=ts_length)

        for t in range(ts_length):
            yield self.current_action_dist
            action = np.searchsorted(
                self.current_action_dist.cumsum(), player_ind_sequence[t], side="right"
            )  # Action the revising player is playing
            self.play(current_action=action)

    def replicate(self, T, num_reps, init_action_dist=None):
        out = np.empty((num_reps, self.num_actions), dtype=int)

        for j in range(num_reps):
            action_dist_sequence_iter = self.simulate_iter(T + 1, init_action_dist=init_action_dist)
            for action_dist in action_dist_sequence_iter:
                x = action_dist
            out[j] = x

        return out
Esempio n. 13
0
class BRD(object):
    def __init__(self, payoff_matrix, N):
        A = np.asarray(payoff_matrix)
        if A.ndim != 2 or A.shape[0] != A.shape[1]:
            raise ValueError('payoff matrix must be square')
        self.num_actions = A.shape[0]  # Number of actions
        self.N = N  # Number of players

        self.player = Player(A)  # "Representative player"
        self.tie_breaking = 'smallest'

        # Current action distribution
        self.current_action_dist = np.zeros(self.num_actions, dtype=int)
        self.current_action_dist[0] = self.N  # Initialization

    def set_init_action_dist(self, init_action_dist=None):
        """
        Set the attribute `current_action_dist` to `init_action_dist`.

        Parameters
        ----------
        init_action_dist : array_like(float, ndim=1),
                           optional(default=None)
            Array containing the initial action distribution. If not
            supplied, randomly chosen uniformly over the set of possible
            action distributions.

        """
        if init_action_dist is None:  # Randomly choose an action distribution
            cutoffs = np.empty(self.num_actions, dtype=int)
            cutoffs[-1] = self.N + self.num_actions - 1
            cutoffs[:-1] = np.random.choice(self.N+self.num_actions-1,
                                            self.num_actions-1, replace=False)
            cutoffs[:-1].sort()
            cutoffs[1:] -= cutoffs[:-1] + 1
            init_action_dist = cutoffs
        self.current_action_dist[:] = init_action_dist

    def play(self, current_action):
        self.current_action_dist[current_action] -= 1
        opponent_action_dist = self.current_action_dist
        next_action = self.player.best_response(opponent_action_dist,
                                                tie_breaking=self.tie_breaking)
        self.current_action_dist[next_action] += 1

    def simulate(self, ts_length, init_action_dist=None):
        action_dist_sequence = \
            np.empty((ts_length, self.num_actions), dtype=int)
        action_dist_sequence_iter = \
            self.simulate_iter(ts_length, init_action_dist=init_action_dist)

        for t, action_dist in enumerate(action_dist_sequence_iter):
            action_dist_sequence[t] = action_dist

        return action_dist_sequence

    def simulate_iter(self, ts_length, init_action_dist=None):
        self.set_init_action_dist(init_action_dist=init_action_dist)

        # Sequence of randomly chosen players to revise
        player_ind_sequence = np.random.randint(self.N, size=ts_length)

        for t in range(ts_length):
            yield self.current_action_dist
            action = np.searchsorted(
                self.current_action_dist.cumsum(), player_ind_sequence[t],
                side='right'
            )  # Action the revising player is playing
            self.play(current_action=action)

    def replicate(self, T, num_reps, init_action_dist=None):
        out = np.empty((num_reps, self.num_actions), dtype=int)

        for j in range(num_reps):
            action_dist_sequence_iter = \
                self.simulate_iter(T+1, init_action_dist=init_action_dist)
            for action_dist in action_dist_sequence_iter:
                x = action_dist
            out[j] = x

        return out