Пример #1
0
def test_sorted_strategy_loading(_):
    with open('test/hard_nash_game_1.json') as f:
        _, serial = gameio.read_basegame(json.load(f))
    assert utils.is_sorted(serial.role_names), \
        "loaded json game didn't have sorted roles"
    assert all(utils.is_sorted(strats) for strats in serial.strat_names), \
        "loaded json game didn't have sorted strategies"
Пример #2
0
def test_serialize_copy_role_lengths():
    """Test role lengths"""
    game = full_game(['a', 'b'], [1, 1], [['1', '2'], ['3', '4', '5']])
    matg = matgame.matgame_copy(game)
    expected = matgame.matgame_names(['a', 'b'], [['1', '2'], ['3', '4', '5']],
                                     np.zeros((2, 3, 2)))
    assert utils.is_sorted(matg.role_names)
    assert matg == expected

    game = full_game(['a', 'b'], [2, 1], [['1', '2'], ['3', '4', '5']])
    matg = matgame.matgame_copy(game)
    expected = matgame.matgame_names(['ap0', 'ap1', 'bp0'],
                                     [['1', '2'], ['1', '2'], ['3', '4', '5']],
                                     np.zeros((2, 2, 3, 3)))
    assert utils.is_sorted(matg.role_names)
    assert matg == expected
Пример #3
0
def verify_trace_json(game, traces):
    """Verify traced json"""
    for trace in traces:
        for point in trace:
            assert point.keys() == {'regret', 'equilibrium', 't'}
            game.mixture_from_json(point['equilibrium'])
        assert utils.is_sorted(trace, key=lambda t: t['t'])
Пример #4
0
def verify_trace_json(game, traces):
    """Verify traced json"""
    for trace in traces:
        for point in trace:
            assert point.keys() == {"regret", "equilibrium", "t"}
            game.mixture_from_json(point["equilibrium"])
        assert utils.is_sorted(trace, key=lambda t: t["t"])
Пример #5
0
def test_serialize_copy_role_lengths_natural():
    """Test natural role lengths"""
    game = full_game(['q', 'qq'], [2, 1], [['1', '2'], ['3', '4', '5']])
    matg = matgame.matgame_copy(game)
    expected = matgame.matgame_names(['qp0', 'qp1', 'qqp0'],
                                     [['1', '2'], ['1', '2'], ['3', '4', '5']],
                                     np.zeros((2, 2, 3, 3)))
    assert utils.is_sorted(matg.role_names)
    assert matg == expected
Пример #6
0
def test_serialize_copy_role_lengths():
    """Test role lengths"""
    game = full_game(
        ['a', 'b'], [1, 1], [['1', '2'], ['3', '4', '5']])
    matg = matgame.matgame_copy(game)
    expected = matgame.matgame_names(
        ['a', 'b'], [['1', '2'], ['3', '4', '5']], np.zeros((2, 3, 2)))
    assert utils.is_sorted(matg.role_names)
    assert matg == expected

    game = full_game(
        ['a', 'b'], [2, 1], [['1', '2'], ['3', '4', '5']])
    matg = matgame.matgame_copy(game)
    expected = matgame.matgame_names(
        ['ap0', 'ap1', 'bp0'], [['1', '2'], ['1', '2'], ['3', '4', '5']],
        np.zeros((2, 2, 3, 3)))
    assert utils.is_sorted(matg.role_names)
    assert matg == expected
Пример #7
0
def test_random_serialize_copy_role_lengths(_):
    """Test serialization copy"""
    num_roles = random.randint(2, 3)
    roles = random_names(num_roles)
    strats = tuple(
        random_names(random.randint(2, 3)) for _ in range(num_roles))
    players = [random.randint(1, 3) for _ in range(num_roles)]
    game = full_game(roles, players, strats)
    matg = matgame.matgame_copy(game)
    assert utils.is_sorted(matg.role_names)
Пример #8
0
def test_random_serialize_copy_role_lengths(_):
    """Test serialization copy"""
    num_roles = random.randint(2, 3)
    roles = random_names(num_roles)
    strats = tuple(random_names(random.randint(2, 3))
                   for _ in range(num_roles))
    players = [random.randint(1, 3) for _ in range(num_roles)]
    game = full_game(roles, players, strats)
    matg = matgame.matgame_copy(game)
    assert utils.is_sorted(matg.role_names)
Пример #9
0
def test_serialize_copy_role_lengths_natural():
    """Test natural role lengths"""
    game = full_game(
        ['q', 'qq'], [2, 1], [['1', '2'], ['3', '4', '5']])
    matg = matgame.matgame_copy(game)
    expected = matgame.matgame_names(
        ['qp0', 'qp1', 'qqp0'], [['1', '2'], ['1', '2'], ['3', '4', '5']],
        np.zeros((2, 2, 3, 3)))
    assert utils.is_sorted(matg.role_names)
    assert matg == expected
Пример #10
0
def matgame_copy(copy_game):
    """Copy a matrix game from an existing game

    Parameters
    ----------
    copy_game : RsGame
        Game to copy payoff data out of. This game must be complete.
    """
    utils.check(copy_game.is_complete(), 'can only copy complete games')

    if hasattr(copy_game, 'payoff_matrix'):
        return matgame_replace(copy_game, copy_game.payoff_matrix())

    # Get payoff matrix
    num_role_strats = copy_game.num_role_strats.repeat(
        copy_game.num_role_players)
    shape = tuple(num_role_strats) + (num_role_strats.size,)
    payoff_matrix = np.empty(shape, float)
    offset = copy_game.role_starts.repeat(copy_game.num_role_players)
    for profile, payoffs in zip(copy_game.profiles(), copy_game.payoffs()):
        inds = itertools.product(*[
            set(itertools.permutations(np.arange(s.size).repeat(s))) for s
            in np.split(profile, copy_game.role_starts[1:])])
        for nested in inds:
            ind = tuple(itertools.chain.from_iterable(nested))
            payoff_matrix[ind] = payoffs[ind + offset]

    # Get role names
    if np.all(copy_game.num_role_players == 1):
        roles = copy_game.role_names
        strats = copy_game.strat_names
    else:
        # When we expand names, we need to make sure they stay sorted
        if utils.is_sorted(r + 'p' for r in copy_game.role_names):
            # We can naively append player numbers
            role_names = copy_game.role_names
        else:
            # We have to prefix to preserve role order
            maxlen = max(map(len, copy_game.role_names))
            role_names = (
                p + '_' * (maxlen - len(r)) + r for r, p
                in zip(copy_game.role_names,
                       utils.prefix_strings('', copy_game.num_roles)))
        roles = tuple(itertools.chain.from_iterable(
            (r + s for s in utils.prefix_strings('p', p))
            for r, p in zip(role_names, copy_game.num_role_players)))
        strats = tuple(itertools.chain.from_iterable(
            itertools.repeat(s, p) for s, p
            in zip(copy_game.strat_names, copy_game.num_role_players)))
    return _MatrixGame(roles, strats, payoff_matrix)
Пример #11
0
def _normalize(role_names, strat_names, matrix):
    """Take gambit data and make it comply with gameanalysis standards"""
    num_roles = len(role_names)

    # Sort role names
    if not utils.is_sorted(role_names, strict=True):
        warnings.warn(
            "gambit player names aren't strictly sorted; modifying to comply "
            'with gameanalysis standards')
        _dedup(role_names)
        if not utils.is_sorted(role_names):
            order = sorted(range(num_roles), key=lambda i: role_names[i])
            role_names = [role_names[i] for i in order]
            strat_names = [strat_names[i] for i in order]
            shape = tuple(order) + (num_roles,)
            matrix = np.transpose(matrix, shape)[..., order]

    # Sort strat names
    if not all(utils.is_sorted(strats, strict=True) for strats in strat_names):
        warnings.warn(
            "gambit strategy names aren't strictly sorted; modifying to "
            'comply with gameanalysis standards')
        new_strats = []
        for role, strats in enumerate(strat_names):
            if not utils.is_sorted(strats, strict=True):
                _dedup(strats)
                if not utils.is_sorted(strats):
                    strats, order = zip(
                        *sorted((s, i) for i, s in enumerate(strats)))
                    shuffle = [slice(None)] * (num_roles + 1)
                    shuffle[role] = order
                    matrix = matrix[shuffle]
            new_strats.append(strats)
        strat_names = new_strats

    return matgame.matgame_names(role_names, strat_names, matrix)
Пример #12
0
def _normalize(role_names, strat_names, matrix):
    """Take gambit data and make it comply with gameanalysis standards"""
    num_roles = len(role_names)

    # Sort role names
    if not utils.is_sorted(role_names, strict=True):
        warnings.warn(
            "gambit player names aren't strictly sorted; modifying to comply "
            'with gameanalysis standards')
        _dedup(role_names)
        if not utils.is_sorted(role_names):
            order = sorted(range(num_roles), key=lambda i: role_names[i])
            role_names = [role_names[i] for i in order]
            strat_names = [strat_names[i] for i in order]
            shape = tuple(order) + (num_roles, )
            matrix = np.transpose(matrix, shape)[..., order]

    # Sort strat names
    if not all(utils.is_sorted(strats, strict=True) for strats in strat_names):
        warnings.warn(
            "gambit strategy names aren't strictly sorted; modifying to "
            'comply with gameanalysis standards')
        new_strats = []
        for role, strats in enumerate(strat_names):
            if not utils.is_sorted(strats, strict=True):
                _dedup(strats)
                if not utils.is_sorted(strats):
                    strats, order = zip(*sorted(
                        (s, i) for i, s in enumerate(strats)))
                    shuffle = [slice(None)] * (num_roles + 1)
                    shuffle[role] = order
                    matrix = matrix[shuffle]
            new_strats.append(strats)
        strat_names = new_strats

    return matgame.matgame_names(role_names, strat_names, matrix)
Пример #13
0
def test_prefix_strings_test():
    assert utils.is_sorted(utils.prefix_strings('', 13))
Пример #14
0
def test_prefix_strings():
    """Test prefix strings returns sorted lists"""
    assert utils.is_sorted(utils.prefix_strings('', 13))
Пример #15
0
def test_is_sorted():
    """Test is_sorted"""
    assert utils.is_sorted([])
    assert utils.is_sorted([0])
    assert utils.is_sorted([[0], [1], [2]], key=lambda x: x[0])
    assert utils.is_sorted([3, 4])
    assert utils.is_sorted([3, 4], strict=True)
    assert not utils.is_sorted([3, 4], reverse=True)
    assert not utils.is_sorted([3, 4], reverse=True, strict=True)
    assert utils.is_sorted([4, 3], reverse=True)
    assert utils.is_sorted([4, 3], reverse=True, strict=True)
    assert utils.is_sorted([3, 4, 4, 5])
    assert not utils.is_sorted([3, 4, 4, 5], strict=True)
    assert utils.is_sorted([5, 4, 4, 3], reverse=True)
    assert not utils.is_sorted([5, 4, 4, 3], reverse=True, strict=True)
Пример #16
0
def test_prefix_strings():
    """Test prefix strings returns sorted lists"""
    assert utils.is_sorted(utils.prefix_strings('', 13))
Пример #17
0
def test_is_sorted():
    """Test is_sorted"""
    assert utils.is_sorted([])
    assert utils.is_sorted([0])
    assert utils.is_sorted([[0], [1], [2]], key=lambda x: x[0])
    assert utils.is_sorted([3, 4])
    assert utils.is_sorted([3, 4], strict=True)
    assert not utils.is_sorted([3, 4], reverse=True)
    assert not utils.is_sorted([3, 4], reverse=True, strict=True)
    assert utils.is_sorted([4, 3], reverse=True)
    assert utils.is_sorted([4, 3], reverse=True, strict=True)
    assert utils.is_sorted([3, 4, 4, 5])
    assert not utils.is_sorted([3, 4, 4, 5], strict=True)
    assert utils.is_sorted([5, 4, 4, 3], reverse=True)
    assert not utils.is_sorted([5, 4, 4, 3], reverse=True, strict=True)
Пример #18
0
def test_is_sorted():
    assert utils.is_sorted([])
    assert utils.is_sorted([0])
    assert not utils.is_sorted([3, 4], reverse=True)