Пример #1
0
 def test_stochastic_outcomes(self):
     for seed, expected in zip(range(2),
                               [[0, 1, 0, 1, 0], [0, 0, 0, 1, 1]]):
         axl.seed(seed)
         player = axl.TitForTat()
         opponent = axl.Defector()
         expected_fixation_probabilities = expected
         fixation_probabilities = utils.objective_moran_win(player,
                                                            opponent,
                                                            turns=3,
                                                            repetitions=5,
                                                            noise=0)
         self.assertEqual(fixation_probabilities,
                          expected_fixation_probabilities)
Пример #2
0
    def setUpClass(cls):
        cls.test_key = (axl.TitForTat(), axl.Defector())
        cls.test_value = [(C, D), (D, D), (D, D)]
        save_path = pathlib.Path("test_outputs/test_cache_save.txt")
        cls.test_save_file = axl_filename(save_path)
        load_path = pathlib.Path("test_outputs/test_cache_load.txt")
        cls.test_load_file = axl_filename(load_path)
        test_data_to_pickle = {
            ("Tit For Tat", "Defector"): [(C, D), (D, D), (D, D)]
        }
        cls.test_pickle = pickle.dumps(test_data_to_pickle)

        with open(cls.test_load_file, "wb") as f:
            f.write(cls.test_pickle)
Пример #3
0
    def test_strategy(self):
        axelrod.seed(0)
        vector = [random.random() for _ in range(16)]

        actions = [(C, C), (C, C), (D, D), (D, C), (C, C), (C, D), (C, C)]
        self.versus_test(opponent=axelrod.CyclerCCD(),
                         expected_actions=actions, seed=0,
                         init_kwargs={'sixteen_vector': vector})

        actions = [(C, C), (C, C), (C, D), (D, C), (C, C), (C, D), (C, C)]
        self.versus_test(opponent=axelrod.CyclerCCD(),
                         expected_actions=actions, seed=1,
                         init_kwargs={'sixteen_vector': vector})

        actions = [(C, C), (C, C), (D, C), (D, D), (C, D), (C, C), (D, C)]
        self.versus_test(opponent=axelrod.TitForTat(),
                         expected_actions=actions, seed=0,
                         init_kwargs={'sixteen_vector': vector})

        actions = [(C, C), (C, C), (C, C), (D, C), (D, D), (C, D), (C, C)]
        self.versus_test(opponent=axelrod.TitForTat(),
                         expected_actions=actions, seed=1,
                         init_kwargs={'sixteen_vector': vector})
Пример #4
0
    def test_fingeprint_explicit_probe(self):
        af = AshlockFingerprint(axl.TitForTat(), probe=axl.Random(p=0.1))
        af.fingerprint(turns=10, repetitions=2, step=0.5, progress_bar=False)

        probes = af.spatial_tournament.players[1:]
        self.assertEqual(
            str(probes[0]), "Joss-Ann Random: 0.1: (0.0, 0.0)"
        )  # x + y < 1
        self.assertEqual(
            str(probes[2]), "Dual Joss-Ann Random: 0.1: (1.0, 0.0)"
        )  # x + y = 1
        self.assertEqual(
            str(probes[8]), "Dual Joss-Ann Random: 0.1: (0.0, 0.0)"
        )  # x + y > 1
Пример #5
0
    def test_final_score_per_turn(self):
        turns = 3
        player1 = axelrod.TitForTat()
        player2 = axelrod.Defector()

        match = axelrod.Match((player1, player2), turns)
        self.assertEqual(match.final_score_per_turn(), None)
        match.play()
        self.assertEqual(match.final_score_per_turn(), (2/float(turns), 7/float(turns)))

        match = axelrod.Match((player2, player1), turns)
        self.assertEqual(match.final_score_per_turn(), None)
        match.play()
        self.assertEqual(match.final_score_per_turn(), (7/float(turns), 2/float(turns)))
Пример #6
0
    def test_strategies_without_countermeasures_return_their_strategy(self):
        tft = axl.TitForTat()
        inspector = axl.Alternator()
        match = axl.Match((tft, inspector), turns=1)
        match.play()
        self.assertEqual(tft.history, [C])
        self.assertEqual(inspect_strategy(inspector=inspector, opponent=tft),
                         C)

        match = axl.Match((tft, inspector), turns=2)
        match.play()
        self.assertEqual(tft.history, [C, C])
        self.assertEqual(inspect_strategy(inspector=inspector, opponent=tft),
                         D)
        self.assertEqual(tft.strategy(inspector), D)
Пример #7
0
    def test_strategy(self):
        self.versus_test(
            opponent=axl.TitForTat(),
            expected_actions=[(C, C), (D, C), (C, D)] + [(C, C)] * 15,
        )

        self.versus_test(
            opponent=axl.Cooperator(),
            expected_actions=[(C, C), (D, C), (C, C), (C, C)] + [(D, C)] * 15,
        )

        self.versus_test(
            opponent=axl.Defector(),
            expected_actions=[(C, D), (D, D), (C, D), (C, D)] + [(D, D)] * 15,
        )
Пример #8
0
def init_players():
    players = [
        #axl.Cooperator(),
        #axl.Defector(),
        #axl.Random(),
        #axl.WinStayLoseShift(),
        axl.TitForTat(),
        #axl.GTFT(),
        #axl.ZDExtortion(),
        #axl.ZDExtort2(),
        #axl.ZDGTFT2(),
        axl.ZDSet2(),
    ]

    return players
Пример #9
0
 def setUpClass(cls):
     players = [axl.Alternator(), axl.TitForTat()]
     tournament = axl.Tournament(players)
     cls.results = tournament.play()
     cls.data = TournamentResultsSerializer(cls.results).data
     cls.expected_keys = [
         'filename', 'num_interactions', 'players', 'repetitions',
         'nplayers', 'match_lengths', 'wins', 'scores', 'normalised_scores',
         'payoffs', 'score_diffs', 'cooperation', 'normalised_cooperation',
         'initial_cooperation_count', 'good_partner_matrix', 'total_interactions',
         'good_partner_rating', 'ranking', 'ranked_names', 'payoff_matrix',
         'payoff_stddevs', 'payoff_diffs_means', 'vengeful_cooperation',
         'cooperating_rating', 'initial_cooperation_rate', 'eigenjesus_rating',
         'eigenmoses_rating', 'wins',
     ]
Пример #10
0
 def test_clone(self):
     """Tests player cloning."""
     player1 = axl.Random(p=0.75)  # 0.5 is the default
     player2 = player1.clone()
     turns = 50
     for op in [axl.Cooperator(), axl.Defector(), axl.TitForTat()]:
         player1.reset()
         player2.reset()
         seed = random.randint(0, 10 ** 6)
         for p in [player1, player2]:
             axl.seed(seed)
             m = axl.Match((p, op), turns=turns)
             m.play()
         self.assertEqual(len(player1.history), turns)
         self.assertEqual(player1.history, player2.history)
Пример #11
0
    def test_init_from_resulsetfromfile(self):
        tmp_file = tempfile.NamedTemporaryFile(mode='w', delete=False)
        tournament = axelrod.Tournament(
            players=[axelrod.Cooperator(),
                     axelrod.TitForTat(),
                     axelrod.Defector()],
            turns=2,
            repetitions=2)
        tournament.play(filename=tmp_file.name, progress_bar=False)
        tmp_file.close()
        rs = axelrod.ResultSetFromFile(tmp_file.name)

        plot = axelrod.Plot(rs)
        self.assertEqual(plot.result_set, rs)
        self.assertEqual(matplotlib_installed, plot.matplotlib_installed)
Пример #12
0
    def test_dual_tft_transformer(self):
        """Tests that DualTransformer produces the opposite results when faced
        with the same opponent history.
        """
        p1 = axelrod.TitForTat()
        p2 = DualTransformer()(axelrod.TitForTat)()
        p3 = axelrod.CyclerCCD()  # Cycles 'CCD'

        for _ in range(10):
            p1.play(p3)

        p3.reset()
        for _ in range(10):
            p2.play(p3)

        self.assertEqual(p1.history, [flip_action(x) for x in p2.history])
Пример #13
0
    def test_example(self):
        run = fa.NewAnalysisRun()
        run.save_file_prefix = "example-"

        run.add_opponent(axl.TitForTat())
        run.add_opponent(axl.Random())
        run.add_opponent(axl.Grudger())

        # must have 12 opponents; 10 Randoms and the other 2
        self.assertEqual(len(run.opponent_list), 12)
        run.start()

        import glob
        all_files = glob.glob("./output/*.csv")
        # assert all files were created
        self.assertEqual(len(all_files), 12)
Пример #14
0
 def test_play_single_interaction(self):
     players = [
         axelrod.Alternator(),
         axelrod.Defector(),
         axelrod.TitForTat()
     ]
     rr = axelrod.RoundRobin(players=players, game=self.game, turns=20)
     player1 = players[0]
     player2 = players[2]
     classes = (player1.__class__, player2.__class__)
     scores, cooperation_rates = (rr._play_single_interaction(
         player1, player2, classes))
     expected_scores = (53, 48)
     expected_cooperation_rates = (10, 11)
     self.assertEqual(expected_scores, scores)
     self.assertEqual(expected_cooperation_rates, cooperation_rates)
Пример #15
0
    def test_particular_tournament(self):
        """A test for a tournament that has caused failures during some bug
        fixing"""
        players = [axelrod.Cooperator(), axelrod.Defector(),
                   axelrod.TitForTat(), axelrod.Grudger()]
        edges = [(0, 2), (0, 3), (1, 2), (1, 3)]
        tournament = axelrod.SpatialTournament(players, edges=edges)
        results = tournament.play(progress_bar=False)
        expected_ranked_names = ['Cooperator', 'Tit For Tat',
                                 'Grudger', 'Defector']
        self.assertEqual(results.ranked_names, expected_ranked_names)

        # Check that this tournament runs with noise
        tournament = axelrod.SpatialTournament(players, edges=edges, noise=.5)
        results = tournament.play(progress_bar=False)
        self.assertIsInstance(results, axelrod.ResultSet)
Пример #16
0
    def test_specific_set_of_results(self):
        """
        This tests specific reported results as discussed in
        https://github.com/Axelrod-Python/Axelrod/issues/1294

        The results there used a version of mistrust with a bug that corresponds
        to a memory one player that start by defecting and only cooperates if
        both players cooperated in the previous round.
        """
        mistrust_with_bug = axl.MemoryOnePlayer(
            initial=D,
            four_vector=(1, 0, 0, 0),
        )
        players = [
            self.player(),
            axl.TitForTat(),
            axl.GoByMajority(),
            axl.Grudger(),
            axl.WinStayLoseShift(),
            axl.Prober(),
            axl.Defector(),
            mistrust_with_bug,
            axl.Cooperator(),
            axl.CyclerCCD(),
            axl.CyclerDDC(),
        ]
        axl.seed(1)
        tournament = axl.Tournament(players, turns=1000, repetitions=1)
        results = tournament.play(progress_bar=False)
        scores = [
            round(average_score_per_turn * 1000, 1)
            for average_score_per_turn in results.payoff_matrix[0]
        ]
        expected_scores = [
            3000.0,
            3000.0,
            3000.0,
            3000.0,
            3000.0,
            2999.0,
            983.0,
            983.0,
            3000.0,
            3596.0,
            2302.0,
        ]
        self.assertEqual(scores, expected_scores)
Пример #17
0
    def test_init(self):
        players = axelrod.Cooperator(), axelrod.Defector()
        mp = MoranProcess(players)
        self.assertEqual(mp.turns, axelrod.DEFAULT_TURNS)
        self.assertIsNone(mp.prob_end)
        self.assertIsNone(mp.game)
        self.assertEqual(mp.noise, 0)
        self.assertEqual(mp.initial_players, players)
        self.assertEqual(mp.players, list(players))
        self.assertEqual(mp.populations,
                         [Counter({
                             "Cooperator": 1,
                             "Defector": 1
                         })])
        self.assertIsNone(mp.winning_strategy_name)
        self.assertEqual(mp.mutation_rate, 0)
        self.assertEqual(mp.mode, "bd")
        self.assertEqual(mp.deterministic_cache, axelrod.DeterministicCache())
        self.assertEqual(mp.mutation_targets, {
            "Cooperator": [players[1]],
            "Defector": [players[0]]
        })
        self.assertEqual(mp.interaction_graph._edges, [(0, 1), (1, 0)])
        self.assertEqual(mp.reproduction_graph._edges, [(0, 1), (1, 0), (0, 0),
                                                        (1, 1)])
        self.assertEqual(mp.fitness_transformation, None)
        self.assertEqual(mp.locations, [0, 1])
        self.assertEqual(mp.index, {0: 0, 1: 1})

        # Test non default graph cases
        players = axelrod.Cooperator(), axelrod.Defector(), axelrod.TitForTat()
        edges = [(0, 1), (2, 0), (1, 2)]
        graph = axelrod.graph.Graph(edges, directed=True)
        mp = MoranProcess(players, interaction_graph=graph)
        self.assertEqual(mp.interaction_graph._edges, [(0, 1), (2, 0), (1, 2)])
        self.assertEqual(
            sorted(mp.reproduction_graph._edges),
            sorted([(0, 1), (2, 0), (1, 2), (0, 0), (1, 1), (2, 2)]),
        )

        mp = MoranProcess(players,
                          interaction_graph=graph,
                          reproduction_graph=graph)
        self.assertEqual(mp.interaction_graph._edges, [(0, 1), (2, 0), (1, 2)])
        self.assertEqual(mp.reproduction_graph._edges, [(0, 1), (2, 0),
                                                        (1, 2)])
Пример #18
0
    def setUpClass(cls):
        cls.filename = "test_outputs/test_results.csv"

        cls.players = [axelrod.Alternator(), axelrod.TitForTat(), axelrod.Defector()]
        cls.repetitions = 3
        cls.turns = 5

        cls.test_result_set = axelrod.ResultSet(
            cls.filename, cls.players, cls.repetitions, progress_bar=False
        )

        cls.test_result_set = axelrod.ResultSet(
            cls.filename, cls.players, cls.repetitions, progress_bar=False
        )
        cls.expected_boxplot_dataset = [
            [(17 / 5 + 9 / 5) / 2 for _ in range(3)],
            [(13 / 5 + 4 / 5) / 2 for _ in range(3)],
            [3 / 2 for _ in range(3)],
        ]
        cls.expected_boxplot_xticks_locations = [1, 2, 3, 4]
        cls.expected_boxplot_xticks_labels = ["Defector", "Tit For Tat", "Alternator"]

        cls.expected_lengthplot_dataset = [
            [cls.turns for _ in range(3)],
            [cls.turns for _ in range(3)],
            [cls.turns for _ in range(3)],
        ]

        cls.expected_payoff_dataset = [
            [0, mean([9 / 5 for _ in range(3)]), mean([17 / 5 for _ in range(3)])],
            [mean([4 / 5 for _ in range(3)]), 0, mean([13 / 5 for _ in range(3)])],
            [mean([2 / 5 for _ in range(3)]), mean([13 / 5 for _ in range(3)]), 0],
        ]
        cls.expected_winplot_dataset = (
            [[2, 2, 2], [0, 0, 0], [0, 0, 0]],
            ["Defector", "Tit For Tat", "Alternator"],
        )

        cls.expected_sdvplot_dataset = (
            [
                [3, 3, 3, 1, 1, 1, 0, 0, 0],
                [0, 0, 0, 0, 0, 0, -1, -1, -1],
                [0, 0, 0, 0, 0, 0, -3, -3, -3],
            ],
            ["Defector", "Tit For Tat", "Alternator"],
        )
Пример #19
0
 def test_update_matrices(self):
     players = [
         axelrod.Alternator(),
         axelrod.Defector(),
         axelrod.TitForTat()
     ]
     rr = axelrod.RoundRobin(players=players, game=self.game, turns=20)
     scores = (53, 48)
     cooperation_rates = (0.5, 0.55)
     payoffs = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
     cooperation = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
     rr._update_matrices(0, 2, scores, payoffs, cooperation_rates,
                         cooperation)
     expected_payoffs = [[0, 0, 53], [0, 0, 0], [48, 0, 0]]
     expected_cooperation = [[0, 0, 0.5], [0, 0, 0], [0.55, 0, 0]]
     self.assertEqual(expected_payoffs, payoffs)
     self.assertEqual(expected_cooperation, cooperation)
Пример #20
0
def playWithFixed(TD, DP, MC):
    C = axl.Cooperator()
    D = axl.Defector()
    TFT = axl.TitForTat()
    BUL = axl.Bully()
    PAV = Pavlov()
    APAV = axl.APavlov2011()

    for learner in [TD,DP,MC]:
        players = [C, D, TFT, BUL, PAV, APAV, learner]
        tournament = axl.Tournament(players, turns=10000)
        results = tournament.play()

        title = learner.name + " VS Fixed Strategy Players"
        plot = axl.Plot(results)
        p = plot.boxplot(title)
        p.savefig(learner.name)
Пример #21
0
 def test_tournament(self):
     """
     Test tournament
     """
     P1 = axelrod.Cooperator()
     P2 = axelrod.TitForTat()
     P3 = axelrod.Defector()
     P4 = axelrod.Grudger()
     P5 = axelrod.GoByMajority()
     tournament = axelrod.Axelrod(P1, P2, P3, P4, P5)
     results = tournament.tournament(turns=200, repetitions=5)
     self.assertEqual(sorted([(str(player), results[player]) for player in sorted(results.keys())]), sorted([
    ('Tit For Tat', [2001, 2001, 2001, 2001, 2001]),
    ('Cooperator', [2200, 2200, 2200, 2200, 2200]),
    ('Defector', [2388, 2388, 2388, 2388, 2388]),
    ('Grudger', [2001, 2001, 2001, 2001, 2001]),
    ('Go By Majority', [2001, 2001, 2001, 2001, 2001])]))
Пример #22
0
    def setUpClass(cls):
        cls.players = (axelrod.Alternator(), axelrod.TitForTat(), axelrod.Defector())
        cls.turns = 5
        cls.matches = {
                        (0,1): [axelrod.Match((cls.players[0], cls.players[1]),
                        turns=cls.turns) for _ in range(3)],
                        (0,2): [axelrod.Match((cls.players[0], cls.players[2]),
                        turns=cls.turns) for _ in range(3)],
                        (1,2): [axelrod.Match((cls.players[1], cls.players[2]),
                        turns=cls.turns) for _ in range(3)]}
                          # This would not actually be a round robin tournament
                           # (no cloned matches)

        cls.interactions = {}
        for index_pair, matches in cls.matches.items():
            for match in matches:
                match.play()
                try:
                    cls.interactions[index_pair].append(match.result)
                except KeyError:
                    cls.interactions[index_pair] = [match.result]

        cls.test_result_set = axelrod.ResultSet(cls.players, cls.interactions)
        cls.expected_boxplot_dataset = [
               [(17.0 / 5 + 9.0 / 5) / 2 for _ in range(3)],
               [(13.0 / 5 + 4.0 / 5) / 2 for _ in range(3)],
               [3.0 / 2 for _ in range(3)]
               ]
        cls.expected_boxplot_xticks_locations = [1, 2, 3, 4]
        cls.expected_boxplot_xticks_labels = ['Defector', 'Tit For Tat', 'Alternator']

        cls.expected_lengthplot_dataset = [
               [cls.turns for _ in range(3)],
               [cls.turns for _ in range(3)],
               [cls.turns for _ in range(3)],
               ]

        cls.expected_payoff_dataset = [
            [0, mean([9/5.0 for _ in range(3)]), mean([17/5.0 for _ in range(3)])],
            [mean([4/5.0 for _ in range(3)]), 0, mean([13/5.0 for _ in range(3)])],
            [mean([2/5.0 for _ in range(3)]), mean([13/5.0 for _ in range(3)]), 0]
        ]
        cls.expected_winplot_dataset = ([[2, 2, 2], [0, 0, 0], [0, 0, 0]],
                                        ['Defector', 'Tit For Tat', 'Alternator'])
Пример #23
0
    def test_winner(self):
        player1 = axelrod.TitForTat()
        player2 = axelrod.Defector()

        match = axelrod.Match((player1, player2), 3)
        self.assertEqual(match.winner(), None)
        match.play()
        self.assertEqual(match.winner(), player2)

        match = axelrod.Match((player2, player1), 3)
        self.assertEqual(match.winner(), None)
        match.play()
        self.assertEqual(match.winner(), player2)

        player1 = axelrod.Defector()
        match = axelrod.Match((player1, player2), 3)
        self.assertEqual(match.winner(), None)
        match.play()
        self.assertEqual(match.winner(), False)
Пример #24
0
    def setUpClass(cls):
        cls.game = axelrod.Game()
        cls.players = [
            axelrod.Cooperator(),
            axelrod.TitForTat(),
            axelrod.Defector(),
            axelrod.Grudger(),
            axelrod.GoByMajority()]
        cls.player_names = [str(p) for p in cls.players]
        cls.test_name = 'test'
        cls.test_repetitions = 5

        cls.expected_outcome = [
            ('Cooperator', [180, 180, 180, 180, 180]),
            ('Defector', [172, 172, 172, 172, 172]),
            ('Grudger', [199, 199, 199, 199, 199]),
            ('Soft Go By Majority', [199, 199, 199, 199, 199]),
            ('Tit For Tat', [199, 199, 199, 199, 199])]
        cls.expected_outcome.sort()
Пример #25
0
 def test_pair_of_players(self):
     players = [
         axelrod.Cooperator(),
         axelrod.Defector(),
         axelrod.TitForTat()
     ]
     rr = axelrod.RoundRobin(players=players, game=self.game, turns=20)
     player1, player2, key = rr._pair_of_players(0, 2)
     self.assertEqual(player1.name, 'Cooperator')
     self.assertEqual(player2.name, 'Tit For Tat')
     self.assertEqual(key[0], axelrod.Cooperator)
     self.assertEqual(key[1], axelrod.TitForTat)
     player1, player2, key = rr._pair_of_players(0, 0)
     self.assertEqual(player1.name, player2.name)
     self.assertEqual(key[0], key[1])
     self.assertNotEqual(player1, player2)
     # Check that the two player instances are wholly independent
     player1.name = 'player 1'
     player2.name = 'player 2'
     self.assertNotEqual(player1.name, player2.name)
Пример #26
0
class TestResultSetFromFile(unittest.TestCase):
    tournament = axelrod.Tournament(players=[
        axelrod.Cooperator(),
        axelrod.TitForTat(),
        axelrod.Defector()
    ],
                                    turns=2,
                                    repetitions=2)
    tmp_file = tempfile.NamedTemporaryFile(mode='w', delete=False)
    tournament.play(filename=tmp_file.name)
    tmp_file.close()

    def test_init(self):
        rs = axelrod.ResultSetFromFile(self.tmp_file.name)
        players = ['Cooperator', 'Tit For Tat', 'Defector']
        self.assertEqual(rs.players, players)
        self.assertEqual(rs.nplayers, len(players))
        self.assertEqual(rs.nrepetitions, 2)

        expected_interactions = [{
            (0, 1): [('C', 'C'), ('C', 'C')],
            (1, 2): [('C', 'D'), ('D', 'D')],
            (0, 0): [('C', 'C'), ('C', 'C')],
            (2, 2): [('D', 'D'), ('D', 'D')],
            (0, 2): [('C', 'D'), ('C', 'D')],
            (1, 1): [('C', 'C'), ('C', 'C')]
        }, {
            (0, 1): [('C', 'C'), ('C', 'C')],
            (1, 2): [('C', 'D'), ('D', 'D')],
            (0, 0): [('C', 'C'), ('C', 'C')],
            (2, 2): [('D', 'D'), ('D', 'D')],
            (0, 2): [('C', 'D'), ('C', 'D')],
            (1, 1): [('C', 'C'), ('C', 'C')]
        }]
        self.assertEqual(rs.interactions, expected_interactions)

    def test_string_to_interactions(self):
        rs = axelrod.ResultSetFromFile(self.tmp_file.name)
        string = 'CDCDDD'
        interactions = [('C', 'D'), ('C', 'D'), ('D', 'D')]
        self.assertEqual(rs._string_to_interactions(string), interactions)
Пример #27
0
    def setUpClass(cls):
        cls.game = axelrod.Game()
        cls.players = [
            axelrod.Cooperator(),
            axelrod.TitForTat(),
            axelrod.Defector(),
            axelrod.Grudger(),
            axelrod.GoByMajority(),
        ]
        cls.player_names = [str(p) for p in cls.players]
        cls.test_name = "test"
        cls.test_repetitions = 3

        cls.expected_outcome = [
            ("Cooperator", [45, 45, 45]),
            ("Defector", [52, 52, 52]),
            ("Grudger", [49, 49, 49]),
            ("Soft Go By Majority", [49, 49, 49]),
            ("Tit For Tat", [49, 49, 49]),
        ]
        cls.expected_outcome.sort()
Пример #28
0
    def test_clone(self, seed):
        # Test that the cloned player produces identical play
        player1 = self.player()
        player2 = player1.clone()
        self.assertEqual(len(player2.history), 0)
        self.assertEqual(player2.cooperations, 0)
        self.assertEqual(player2.defections, 0)
        self.assertEqual(player2.state_distribution, {})
        self.assertEqual(player2.classifier, player1.classifier)
        self.assertEqual(player2.match_attributes, player1.match_attributes)

        turns = 10
        for op in [
                axl.Cooperator(),
                axl.Defector(),
                axl.TitForTat(),
        ]:
            for p in [player1, player2]:
                match = axl.Match((p, op), turns=turns, reset=True, seed=seed)
                match.play()
            self.assertEqual(len(player1.history), turns)
            self.assertEqual(player1.history, player2.history)
Пример #29
0
def main():
    strategies = [
        axelrod.Cooperator(),
        axelrod.Defector(),
        axelrod.Random(0.4),
        axelrod.Random(0.5),
        axelrod.Random(0.9),
        axelrod.Alternator(),
        axelrod.TitForTat(),
        axelrod.GTFT(),
        axelrod.WinStayLoseShift(),
        axelrod.ZDGTFT2(),
        axelrod.ZDExtort2(),
        axelrod.TitFor2Tats(),
        axelrod.TwoTitsForTat(),
        axelrod.CyclerCCD(),
        axelrod.CyclerCCCD(),
        axelrod.CyclerCCCCCD(),
        axelrod.HardTitForTat(),
        axelrod.AntiCycler(),
        axelrod.Grudger()
    ]

    for opponent in strategies:
        data_dict, test_results, estimate = infer_depth(opponent)

        print opponent
        print "-" * len(str(opponent))
        print "Collected Data"
        print_dict(data_dict)
        C_count = sum(v[0] for (k, v) in data_dict.items())
        D_count = sum(v[1] for (k, v) in data_dict.items())
        print "C count, D count: %s, %s" % (C_count, D_count)
        print "\nFisher Exact Tests"
        print_dict(test_results)
        print "\nEstimated Memory One Probabilities"
        print_dict(estimate)
        print
Пример #30
0
    def test_tft_fingerprint(self):
        axl.seed(0)  # Fingerprinting is a random process.
        test_data = {
            Point(x=0.0, y=0.0): 3.000,
            Point(x=0.0, y=0.25): 1.820,
            Point(x=0.0, y=0.5): 1.130,
            Point(x=0.0, y=0.75): 1.050,
            Point(x=0.0, y=1.0): 0.980,
            Point(x=0.25, y=0.0): 3.000,
            Point(x=0.25, y=0.25): 2.440,
            Point(x=0.25, y=0.5): 1.770,
            Point(x=0.25, y=0.75): 1.700,
            Point(x=0.25, y=1.0): 1.490,
            Point(x=0.5, y=0.0): 3.000,
            Point(x=0.5, y=0.25): 2.580,
            Point(x=0.5, y=0.5): 2.220,
            Point(x=0.5, y=0.75): 2.000,
            Point(x=0.5, y=1.0): 1.940,
            Point(x=0.75, y=0.0): 3.000,
            Point(x=0.75, y=0.25): 2.730,
            Point(x=0.75, y=0.5): 2.290,
            Point(x=0.75, y=0.75): 2.310,
            Point(x=0.75, y=1.0): 2.130,
            Point(x=1.0, y=0.0): 3.000,
            Point(x=1.0, y=0.25): 2.790,
            Point(x=1.0, y=0.5): 2.480,
            Point(x=1.0, y=0.75): 2.310,
            Point(x=1.0, y=1.0): 2.180,
        }

        af = axl.AshlockFingerprint(axl.TitForTat(), axl.TitForTat)
        data = af.fingerprint(turns=50,
                              repetitions=2,
                              step=0.25,
                              progress_bar=False)

        for key, value in data.items():
            self.assertAlmostEqual(value, test_data[key], places=2)