Exemple #1
0
def test_stability():
    """Test that StableRoommates can recognise whether a matching is stable."""

    players = [Player("A"), Player("B"), Player("C"), Player("D")]
    a, b, c, d = players

    a.set_prefs([b, c, d])
    b.set_prefs([c, d, a])
    c.set_prefs([d, b, a])
    d.set_prefs([a, b, c])

    game = StableRoommates(players)

    matching = game.solve()
    assert game.check_stability()

    a, b, c, d = game.players

    matching[a] = c
    matching[b] = d
    matching[c] = a
    matching[d] = b

    assert not game.check_stability()

    matching[a] = None
    matching[c] = None
    assert not game.check_stability()
def test_check_stability():
    """ Test that StableMarriage can recognise whether a matching is stable. """

    from matching import Player

    suitors = [Player("A"), Player("B")]
    reviewers = [Player("X"), Player("Y")]

    (a, b), (x, y) = suitors, reviewers

    a.set_prefs(reviewers)
    b.set_prefs(reviewers[::-1])

    x.set_prefs(suitors)
    y.set_prefs(suitors[::-1])

    game = StableMarriage(suitors, reviewers)

    matching = game.solve()
    assert game.check_stability()

    (a, b), (x, y) = game.suitors, game.reviewers
    matching[a] = y
    matching[b] = x

    assert not game.check_stability()
Exemple #3
0
def test_match(name, pref_names):
    """ Check that a player can match to another player correctly. """

    player = Player(name)
    other = Player(pref_names[0])

    player.match(other)
    assert player.matching == other
Exemple #4
0
def test_get_favourite(name, pref_names):
    """ Check the correct player is returned as the favourite of a player. """

    player = Player(name)
    others = [Player(other) for other in pref_names]

    player.set_prefs(others)
    favourite = others[0]
    assert player.get_favourite() == favourite
Exemple #5
0
def test_unmatch(name, pref_names):
    """ Check that a player can unmatch from another player correctly. """

    player = Player(name)
    other = Player(pref_names[0])

    player.matching = other
    player.unmatch()
    assert player.matching is None
Exemple #6
0
def test_set_prefs(name, pref_names):
    """ Verify a Player can set its preferences correctly. """

    player = Player(name)
    others = [Player(other) for other in pref_names]

    player.set_prefs(others)
    assert player.prefs == others
    assert player._original_prefs == others
Exemple #7
0
def test_prefers(name, pref_names):
    """Test that a comparison of preference between two other players can be
    found for a player."""

    player = Player(name)
    others = [Player(other) for other in pref_names]

    player.set_prefs(others)
    for i, other in enumerate(others[:-1]):
        assert player.prefers(other, others[i + 1])
Exemple #8
0
def test_trivial_case():
    """ Verify that a matching is given when there are only two players. """

    p1, p2 = players = [Player(1), Player(2)]

    p1.set_prefs([p2])
    p2.set_prefs([p1])

    matching = stable_roommates(players)
    assert matching == {p1: p2, p2: p1}
Exemple #9
0
def _make_instances(suitor_prefs, reviewer_prefs):
    """ Create ``Player`` instances for the names in each dictionary. """

    suitor_dict, reviewer_dict = {}, {}
    for suitor_name in suitor_prefs:
        suitor = Player(name=suitor_name)
        suitor_dict[suitor_name] = suitor
    for reviewer_name in reviewer_prefs:
        reviewer = Player(name=reviewer_name)
        reviewer_dict[reviewer_name] = reviewer

    return suitor_dict, reviewer_dict
Exemple #10
0
def test_match_pair(name, pref_names):
    """ Verify that two players can be matched to one another. """

    others = [Player(other) for other in pref_names]

    for other in others:
        player = Player(name)
        other.set_prefs([player])
        player.set_prefs(others)

        _match_pair(player, other)
        assert player.matching == other
        assert other.matching == player
Exemple #11
0
def test_delete_pair(name, pref_names):
    """ Verify that two players can forget each other. """

    others = [Player(other) for other in pref_names]

    for other in others:
        player = Player(name)
        other.set_prefs([player])
        player.set_prefs(others)

        _delete_pair(player, other)
        assert player.prefs == [o for o in others if o != other]
        assert other.prefs == []
Exemple #12
0
def test_forget(name, pref_names):
    """ Test that a player can forget somebody. """

    player = Player(name)
    others = [Player(other) for other in pref_names]

    player.set_prefs(others)
    for i, other in enumerate(others[:-1]):
        player.forget(other)
        assert player.prefs == others[i + 1:]

    player.forget(others[-1])
    assert player.prefs == []
    assert player._original_prefs == others
Exemple #13
0
def make_players(player_names, seed):
    """ Given some names, make a valid set each of suitors and reviewers. """

    np.random.seed(seed)
    suitor_names, reviewer_names = player_names
    suitors = [Player(name) for name in suitor_names]
    reviewers = [Player(name) for name in reviewer_names]

    for suitor in suitors:
        suitor.set_prefs(np.random.permutation(reviewers).tolist())
    for reviewer in reviewers:
        reviewer.set_prefs(np.random.permutation(suitors).tolist())

    return suitors, reviewers
Exemple #14
0
def test_get_successors(name, pref_names):
    """Test that the correct successors to another player in a player's
    preference list are found."""

    player = Player(name)
    others = [Player(other) for other in pref_names]

    player.set_prefs(others)
    player.matching = others[0]
    if len(player._original_prefs) > 1:
        successors = others[1:]
        assert player.get_successors() == successors
    else:
        assert player.get_successors() == []
Exemple #15
0
def test_example_in_issue():
    """Verify that the matching found is consistent with the example provided
    in #64."""

    players = [
        Player(name)
        for name in ("charlie", "peter", "elise", "paul", "kelly", "sam")
    ]
    charlie, peter, elise, paul, kelly, sam = players

    charlie.set_prefs([peter, paul, sam, kelly, elise])
    peter.set_prefs([kelly, elise, sam, paul, charlie])
    elise.set_prefs([peter, sam, kelly, charlie, paul])
    paul.set_prefs([elise, charlie, sam, peter, kelly])
    kelly.set_prefs([peter, charlie, sam, elise, paul])
    sam.set_prefs([charlie, paul, kelly, elise, peter])

    matching = stable_roommates(players)
    assert matching == {
        charlie: sam,
        peter: kelly,
        elise: paul,
        paul: elise,
        kelly: peter,
        sam: charlie,
    }
Exemple #16
0
def test_check_if_match_unacceptable(name, pref_names):
    """ Test that the acceptability of a match is caught correctly. """

    player = Player(name)
    others = [Player(other) for other in pref_names]

    message = player.unmatched_message()
    assert player.check_if_match_is_unacceptable() == message

    player.set_prefs(others[:-1])
    player.match(others[-1])
    message = player.not_in_preferences_message(others[-1])
    assert player.check_if_match_is_unacceptable() == message

    player.set_prefs(others)
    assert player.check_if_match_is_unacceptable() is None
Exemple #17
0
def test_init(name):
    """ Make an instance of Player and check their attributes are correct. """

    player = Player(name)

    assert player.name == name
    assert player.prefs is None
    assert player._original_prefs is None
    assert player.matching is None
Exemple #18
0
def test_check_inputs_player_prefs_unique(name, other_names, clean):
    """ Test that a game can verify its players have unique preferences. """

    player = Player(name)
    others = [Player(other) for other in other_names]
    player.set_prefs(others + others[:1])

    game = DummyGame(clean)
    game.players = [player]

    with warnings.catch_warnings(record=True) as w:
        game._check_inputs_player_prefs_unique("players")

        message = w[-1].message
        assert isinstance(message, PreferencesChangedWarning)
        assert str(message).startswith(name)
        assert others[0].name in str(message)
        if clean:
            assert player.pref_names == other_names
Exemple #19
0
def make_players(player_names, seed):
    """ Given some names, make a valid set of players. """

    np.random.seed(seed)
    players = [Player(name) for name in player_names]

    for player in players:
        player.set_prefs(
            np.random.permutation([p for p in players
                                   if p != player]).tolist())

    return players
Exemple #20
0
        def getPreference(self, apps, sortedApps):

            preferenceList = []

            for app in apps:
                pref = []

                for sApp in sortedApps:

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Sheep" and sApp.getClassName() == "Devil":
                        pref.append(sApp.getName())

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Rabit" and sApp.getClassName() == "Sheeo":
                        pref.append(sApp.getName())

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Devil" and sApp.getClassName() == "Devil":
                        pref.append(sApp.getName())

                for sApp in sortedApps:

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Sheep" and sApp.getClassName() == "Rabit":
                        pref.append(sApp.getName())

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Rabit" and sApp.getClassName() == "Rabit":
                        pref.append(sApp.getName())

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Devil" and sApp.getClassName() == "Sheep":
                        pref.append(sApp.getName())

                for sApp in sortedApps:

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Sheep" and sApp.getClassName() == "Sheep":
                        pref.append(sApp.getName())

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Rabit" and sApp.getClassName() == "Devil":
                        pref.append(sApp.getName())

                    if app.getName() != sApp.getName() \
                      and app.getClassName() == "Devil" and sApp.getClassName() == "Rabit":
                        pref.append(sApp.getName())

                preferenceList.append(
                    Player(name=app.getName(), pref_names=pref))

            return preferenceList
Exemple #21
0
def test_check_stability():
    """ Test that StableMarriage can recognise whether a matching is stable. """

    from matching import Player

    suitors = [Player("A"), Player("B")]
    reviewers = [Player(1), Player(2)]

    suitors[0].set_prefs(reviewers)
    suitors[1].set_prefs(reviewers[::-1])

    reviewers[0].set_prefs(suitors)
    reviewers[1].set_prefs(suitors[::-1])

    game = StableMarriage(suitors, reviewers)

    matching = game.solve()
    assert game.check_stability()

    (s_a, s_b), (r_1, r_2) = game.suitors, game.reviewers
    matching[s_a] = r_2
    matching[s_b] = r_1

    assert not game.check_stability()
Exemple #22
0
def _make_players(player_prefs):
    """Make a set of ``Player`` instances from the dictionary given. Add their
    preferences."""

    player_dict = {}
    for player_name in player_prefs:
        player = Player(name=player_name)
        player_dict[player_name] = player

    for player_name, player in player_dict.items():
        prefs = [player_dict[name] for name in player_prefs[player_name]]
        player.set_prefs(prefs)

    players = list(player_dict.values())

    return players
Exemple #23
0
def test_original_paper():
    """Verify that the matching found is consistent with the example in the
    original paper."""

    players = [Player(name) for name in ("A", "B", "C", "D", "E", "F")]
    a, b, c, d, e, f = players

    a.set_prefs([d, f, b, e, c])
    b.set_prefs([f, c, e, a, d])
    c.set_prefs([d, e, a, f, b])
    d.set_prefs([b, f, e, a, c])
    e.set_prefs([d, b, c, f, a])
    f.set_prefs([e, a, d, b, c])

    matching = stable_roommates(players)
    assert matching == {a: f, b: c, c: b, d: e, e: d, f: a}
Exemple #24
0
def players(draw, **kwargs):
    """ A strategy for making a set of players. """

    preferences = draw(connections(**kwargs))

    players_ = [Player(name) for name in preferences]
    for player in players_:
        names = preferences[player.name]
        prefs = []
        for name in names:
            for other in players_:
                if other.name == name:
                    prefs.append(other)
                    break

        player.set_prefs(prefs)

    return players_
Exemple #25
0
def test_pride_and_prejudice():
    """ Verify that the matching found is consistent with the one adapted from
    Jane Austen's Pride and Prejudice. Also used in
    `docs/discussion/stable_marriage/example.rst`. """

    suitors = [
        Player(name="Bingley"),
        Player(name="Collins"),
        Player(name="Darcy"),
        Player(name="Wickham"),
    ]

    reviewers = [
        Player(name="Charlotte"),
        Player(name="Elizabeth"),
        Player(name="Jane"),
        Player(name="Lydia"),
    ]

    bingley, collins, darcy, wickham = suitors
    charlotte, elizabeth, jane, lydia = reviewers

    bingley.set_prefs([jane, elizabeth, lydia, charlotte])
    collins.set_prefs([jane, elizabeth, lydia, charlotte])
    darcy.set_prefs([elizabeth, jane, charlotte, lydia])
    wickham.set_prefs([lydia, jane, elizabeth, charlotte])

    charlotte.set_prefs([bingley, darcy, collins, wickham])
    elizabeth.set_prefs([wickham, darcy, bingley, collins])
    jane.set_prefs([bingley, wickham, darcy, collins])
    lydia.set_prefs([bingley, wickham, darcy, collins])

    matching = stable_marriage(suitors, reviewers)
    assert matching == {
        bingley: jane,
        collins: charlotte,
        darcy: elizabeth,
        wickham: lydia,
    }
Exemple #26
0
def whisker(benchmarks):
	players = [Player(x) for x in benchmarks]

	(sens_whiskers, cont_whiskers) = get_whiskers()
	whiskers = dict((x, (float(sens_whiskers[x.name.split('.')[1]]), float(cont_whiskers[x.name.split('.')[1]]))) for x in players)
	prefs = dict()

	for bench in players:
		if whiskers[bench][0] < clos:
			bench.prefs = list(map(lambda x: x[0],
							sorted([x for x in whiskers.items() if x[0] != bench], reverse = True,
							key = lambda x: x[1][1])))
		else:
			bench.prefs = list(map(lambda x: x[0],
							sorted([x for x in whiskers.items() if x[1][1] < clos and x[0] != bench], reverse = True,
							key = lambda x: x[1][1])))
			bench.prefs += list(map(lambda x: x[0],
							sorted([x for x in whiskers.items() if x[1][1] >= clos and x[0] != bench],
							key = lambda x: x[1][1])))
	return players_to_str(stable_roommates(players))
Exemple #27
0
def oracle(benchmarks, mode = 'real'):
	players = [Player(x) for x in benchmarks]

	window = dict()
	if mode == 'real': use_grid = grid
	elif mode == 'pred':
		use_grid = generate_grid()
		read_grid(use_grid, 'pred_grid')
	for bench1 in players:
		window[bench1] = dict()
		for bench2 in set(players).difference([bench1]):
			try:
				window[bench1][bench2] = use_grid[bench1.name.split('.')[1]][bench2.name.split('.')[1]]
			except:
				window[bench1][bench2] = 0
		bench1.prefs = list(map(lambda x: x[0],
						sorted([x for x in window[bench1].items() if float(x[1]) < clos], reverse = True,
						key = itemgetter(1))))
		bench1.prefs += list(map(lambda x: x[0],
						sorted([x for x in window[bench1].items() if float(x[1]) >= clos],
						key = itemgetter(1))))
	return players_to_str(stable_roommates(players))
Exemple #28
0
def test_readme_example():
    """ Verify the example used in the repo README. """

    suitors = [Player(name="A"), Player(name="B"), Player(name="C")]
    reviewers = [Player(name="D"), Player(name="E"), Player(name="F")]
    (A, B, C), (D, E, F) = suitors, reviewers

    A.set_prefs([D, E, F])
    B.set_prefs([D, F, E])
    C.set_prefs([F, D, E])

    D.set_prefs([B, C, A])
    E.set_prefs([A, C, B])
    F.set_prefs([C, B, A])

    matching = stable_marriage(suitors, reviewers)
    assert matching == {A: E, B: D, C: F}
Exemple #29
0
def test_check_inputs_player_prefs_all_in_party(player_others, clean):
    """ " Test that a game can verify its players have only got preferences in
    the correct party."""

    player, others = player_others

    outsider = Player("foo")
    player.set_prefs([outsider])

    game = DummyGame(clean)
    game.players = [player]
    game.others = others

    with warnings.catch_warnings(record=True) as w:
        game._check_inputs_player_prefs_all_in_party("players", "others")

        message = w[-1].message
        assert isinstance(message, PreferencesChangedWarning)
        assert str(message).startswith(player.name)
        assert "non-other" in str(message)
        assert outsider.name in str(message)
        if clean:
            assert outsider not in player.prefs
Exemple #30
0
def test_examples_in_issue_124():
    """Verify that the matching is consistent with the examples provided in
    #124."""

    a, b, c, d = players = [Player(name) for name in ("a", "b", "c", "d")]

    a.set_prefs([b, c, d])
    b.set_prefs([a, c, d])
    c.set_prefs([a, b, d])
    d.set_prefs([a, b, c])

    matching = stable_roommates(players)
    assert matching == {a: b, b: a, c: d, d: c}

    for player in players:
        player._unmatch()

    a.set_prefs([b, c, d])
    b.set_prefs([a, c, d])
    c.set_prefs([d, b, a])
    d.set_prefs([c, b, a])

    matching = stable_roommates(players)
    assert matching == {a: b, b: a, c: d, d: c}