Example #1
0
    def test_score_with_weights(self):
        axl.seed(0)
        opponents_information = [utils.PlayerInfo(s, {})
                                 for s in axl.demo_strategies]
        objective = utils.prepare_objective()
        params = DummyParams()
        score = utils.score_params(params,
                                   objective=objective,
                                   opponents_information=opponents_information,
                                   # All weight on Coop
                                   weights=[1, 0, 0, 0, 0])
        expected_score = 3
        self.assertEqual(score, expected_score)

        score = utils.score_params(params,
                                   objective=objective,
                                   opponents_information=opponents_information,
                                   # Shared weight between Coop and Def
                                   weights=[2, 2, 0, 0, 0])
        expected_score = 1.5
        self.assertEqual(score, expected_score)

        score = utils.score_params(params,
                                   objective=objective,
                                   opponents_information=opponents_information,
                                   # Shared weight between Coop and Def
                                   weights=[2, -.5, 0, 0, 0])
        expected_score = 4.0
        self.assertEqual(score, expected_score)
Example #2
0
    def test_score_with_particular_players(self):
        """
        These are players that are known to be difficult to pickle
        """
        name = "score"
        turns = 10
        noise = 0
        repetitions = 5
        num_states = 2
        opponents = [axl.ThueMorse(),
                     axl.MetaHunter(),
                     axl.BackStabber(),
                     axl.Alexei()]
        size = 10

        objective = dojo.prepare_objective(name=name,
                                           turns=turns,
                                           noise=noise,
                                           repetitions=repetitions)

        population = dojo.Population(params_class=dojo.FSMParams,
                                     params_kwargs={"num_states": num_states},
                                     size=size,
                                     objective=objective,
                                     output_filename=self.temporary_file.name,
                                     opponents=opponents,
                                     bottleneck=2,
                                     mutation_probability = .01,
                                     processes=0)

        generations = 4
        axl.seed(0)
        population.run(generations, print_output=False)
        self.assertEqual(population.generation, 4)
    def test_pso_with_gambler(self):
        name = "score"
        turns = 50
        noise = 0
        repetitions = 5
        num_plays = 1
        num_op_plays = 1
        num_op_start_plays = 1
        params_kwargs = {"plays": num_plays,
                         "op_plays": num_op_plays,
                         "op_start_plays": num_op_start_plays}
        population = 10
        generations = 100
        opponents = [axl.Cooperator() for _ in range(5)]

        objective = dojo.prepare_objective(name=name,
                                           turns=turns,
                                           noise=noise,
                                           repetitions=repetitions)

        pso = dojo.PSO(dojo.GamblerParams, params_kwargs, objective=objective, debug=False,
                  opponents=opponents, population=population, generations=generations)

        axl.seed(0)
        opt_vector, opt_objective_value = pso.swarm()

        self.assertTrue(np.allclose(opt_vector, np.array([[0. , 0. , 0.36158016,
                                                           0.35863128, 0. , 1.,
                                                           0.72670793, 0.67951873]])))
        self.assertEqual(abs(opt_objective_value), 4.96)
Example #4
0
 def test_strategy(self):
     player = self.player()
     # Test against cyclers
     for opponent in [
         axelrod.CyclerCCD(),
         axelrod.CyclerCCCD(),
         axelrod.CyclerCCCCCD(),
         axelrod.Alternator(),
     ]:
         player.reset()
         for i in range(50):
             player.play(opponent)
         self.assertEqual(player.history[-1], D)
     # Test against non-cyclers and cooperators
     axelrod.seed(43)
     for opponent in [
         axelrod.Random(),
         axelrod.AntiCycler(),
         axelrod.DoubleCrosser(),
         axelrod.Cooperator(),
     ]:
         player.reset()
         for i in range(50):
             player.play(opponent)
         self.assertEqual(player.history[-1], C)
Example #5
0
    def test_score_with_particular_players(self):
        name = "score"
        turns = 10
        noise = 0
        repetitions = 5
        num_states = 2
        opponents = [s() for s in axl.basic_strategies]
        size = 10

        objective = dojo.prepare_objective(name=name,
                                           turns=turns,
                                           noise=noise,
                                           repetitions=repetitions)

        population = dojo.Population(params_class=dojo.HMMParams,
                                     params_kwargs={"num_states": num_states},
                                     size=size,
                                     objective=objective,
                                     output_filename=self.temporary_file.name,
                                     opponents=opponents,
                                     bottleneck=2,
                                     mutation_probability = .01,
                                     processes=0)

        generations = 4
        axl.seed(0)
        population.run(generations, print_output=False)
        self.assertEqual(population.generation, 4)
Example #6
0
 def test_return_values(self):
     self.assertEqual(random_choice(1), C)
     self.assertEqual(random_choice(0), D)
     seed(1)
     self.assertEqual(random_choice(), C)
     seed(2)
     self.assertEqual(random_choice(), D)
Example #7
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},
        )
Example #8
0
def write_winner(outfilename, names_inv,
                 N, i, j, repetitions, n=1):
    """
    Write the winner of a Moran process to file
    """

    initial_population = build_population(players, i, j, [n, N-n])

    s1 = str(players[i].clone())
    s2 = str(players[j].clone())

    # Pull out just the interaction we need
    outcomes = dict()
    for pair in [(s1, s1), (s1, s2), (s2, s1), (s2, s2)]:
        outcomes[pair] = match_outcomes[pair]

    mp = ApproximateMoranProcess(initial_population, cached_outcomes=outcomes)

    data = {i: 0, j: 0}
    for seed in range(repetitions):
        axl.seed(seed)
        mp.reset()
        mp.play()
        winner_name = mp.winning_strategy_name
        data[names_inv[winner_name]] += 1

    path = Path("../data")
    path = path / outfilename
    with path.open('a') as f:
        outputfile = csv.writer(f)
        for winner, count in data.items():
            outputfile.writerow([i, j, winner, count])
 def test_creation_seqLen(self):
     axl.seed(0)
     test_length = 10
     self.instance = CyclerParams(sequence_length=test_length)
     self.assertEqual(self.instance.sequence, [D, C, C, D, C, C, C, C, C, C])
     self.assertEqual(self.instance.sequence_length, test_length)
     self.assertEqual(len(self.instance.sequence), test_length)
Example #10
0
 def test_asymmetry(self):
     """Asymmetry in interaction and reproduction should sometimes
     produce different results."""
     seeds = [(1, True), (21, False)]
     players = []
     N = 6
     graph1 = axelrod.graph.cycle(N)
     graph2 = axelrod.graph.complete_graph(N)
     for _ in range(N // 2):
         players.append(axelrod.Cooperator())
     for _ in range(N // 2):
         players.append(axelrod.Defector())
     for seed, outcome in seeds:
         axelrod.seed(seed)
         mp = MoranProcess(
             players, interaction_graph=graph1, reproduction_graph=graph2
         )
         mp.play()
         winner = mp.winning_strategy_name
         axelrod.seed(seed)
         mp = MoranProcess(
             players, interaction_graph=graph2, reproduction_graph=graph1
         )
         mp.play()
         winner2 = mp.winning_strategy_name
         self.assertEqual((winner == winner2), outcome)
Example #11
0
    def test_complete_tournament(self, strategies, prob_end, seed, reps):
        """
        A test to check that a spatial tournament on the complete graph
        gives the same results as the round robin.
        """
        players = [s() for s in strategies]

        # create a prob end round robin tournament
        tournament = axelrod.Tournament(players, prob_end=prob_end, repetitions=reps)
        axelrod.seed(seed)
        results = tournament.play(progress_bar=False)

        # create a complete spatial tournament
        # edges
        edges = [(i, j) for i in range(len(players)) for j in range(i, len(players))]

        spatial_tournament = axelrod.Tournament(
            players, prob_end=prob_end, repetitions=reps, edges=edges
        )
        axelrod.seed(seed)
        spatial_results = spatial_tournament.play(progress_bar=False)
        self.assertEqual(results.match_lengths, spatial_results.match_lengths)
        self.assertEqual(results.ranked_names, spatial_results.ranked_names)
        self.assertEqual(results.wins, spatial_results.wins)
        self.assertEqual(results.scores, spatial_results.scores)
        self.assertEqual(results.cooperation, spatial_results.cooperation)
    def test_pso_with_fsm(self):
        name = "score"
        turns = 10
        noise = 0
        repetitions = 5
        num_states = 4
        params_kwargs = {"num_states": num_states}
        population = 10
        generations = 100
        opponents = [axl.Defector() for _ in range(5)]

        objective = dojo.prepare_objective(name=name,
                                           turns=turns,
                                           noise=noise,
                                           repetitions=repetitions)

        pso = PSO(FSMParams, params_kwargs, objective=objective, debug=False,
                  opponents=opponents, population=population, generations=generations)

        axl.seed(0)
        opt_vector, opt_objective_value = pso.swarm()

        self.assertTrue(np.allclose(opt_vector, np.array([0.0187898, 0.6176355,
                                                          0.61209572, 0.616934,
                                                          0.94374808, 0.6818203,
                                                          0.3595079, 0.43703195,
                                                          0.6976312, 0.06022547,
                                                          0.66676672, 0.67063787,
                                                          0.21038256, 0.1289263,
                                                          0.31542835, 0.36371077,
                                                          0.57019677])))
        self.assertEqual(abs(opt_objective_value), 1)
Example #13
0
    def test_makes_use_of_filtering(self, seed_, strategies):
        """
        Test equivalent filtering using two approaches.

        This needs to be seeded as some players classification is random.
        """
        classifiers = [["game"], ["length"], ["game", "length"]]

        for classifier in classifiers:
            seed(seed_)
            comprehension = set(
                [
                    s
                    for s in strategies
                    if set(classifier).issubset(set(s().classifier["makes_use_of"]))
                ]
            )

            seed(seed_)
            filterset = {"makes_use_of": classifier}
            filtered = set(filtered_strategies(filterset, strategies=strategies))

            self.assertEqual(
                comprehension, filtered, msg="classifier: {}".format(classifier)
            )
Example #14
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)
Example #15
0
    def test_majority_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.940,
            Point(x=0.0, y=0.5): 1.130,
            Point(x=0.0, y=0.75): 1.030,
            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.130,
            Point(x=0.25, y=0.5): 1.940,
            Point(x=0.25, y=0.75): 2.060,
            Point(x=0.25, y=1.0): 1.940,
            Point(x=0.5, y=0.0): 3.000,
            Point(x=0.5, y=0.25): 2.300,
            Point(x=0.5, y=0.5): 2.250,
            Point(x=0.5, y=0.75): 2.420,
            Point(x=0.5, y=1.0): 2.690,
            Point(x=0.75, y=0.0): 3.000,
            Point(x=0.75, y=0.25): 2.400,
            Point(x=0.75, y=0.5): 2.010,
            Point(x=0.75, y=0.75): 2.390,
            Point(x=0.75, y=1.0): 2.520,
            Point(x=1.0, y=0.0): 3.000,
            Point(x=1.0, y=0.25): 2.360,
            Point(x=1.0, y=0.5): 1.740,
            Point(x=1.0, y=0.75): 2.260,
            Point(x=1.0, y=1.0): 2.260,
        }

        af = axl.AshlockFingerprint(axl.GoByMajority, 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)
Example #16
0
    def test_clone(self, seed):
        # Test that the cloned player produces identical play
        player1 = self.player()
        if player1.name in ["Darwin", "Human"]:
            # Known exceptions
            return
        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 = 50
        r = random.random()
        for op in [
            axelrod.Cooperator(),
            axelrod.Defector(),
            axelrod.TitForTat(),
            axelrod.Random(p=r),
        ]:
            player1.reset()
            player2.reset()
            for p in [player1, player2]:
                axelrod.seed(seed)
                m = axelrod.Match((p, op), turns=turns)
                m.play()
            self.assertEqual(len(player1.history), turns)
            self.assertEqual(player1.history, player2.history)
Example #17
0
    def test_wsls_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.710,
            Point(x=0.0, y=0.5): 1.440,
            Point(x=0.0, y=0.75): 1.080,
            Point(x=0.0, y=1.0): 0.500,
            Point(x=0.25, y=0.0): 3.000,
            Point(x=0.25, y=0.25): 2.280,
            Point(x=0.25, y=0.5): 1.670,
            Point(x=0.25, y=0.75): 1.490,
            Point(x=0.25, y=1.0): 0.770,
            Point(x=0.5, y=0.0): 3.000,
            Point(x=0.5, y=0.25): 2.740,
            Point(x=0.5, y=0.5): 2.240,
            Point(x=0.5, y=0.75): 1.730,
            Point(x=0.5, y=1.0): 1.000,
            Point(x=0.75, y=0.0): 3.000,
            Point(x=0.75, y=0.25): 3.520,
            Point(x=0.75, y=0.5): 2.830,
            Point(x=0.75, y=0.75): 1.750,
            Point(x=0.75, y=1.0): 1.250,
            Point(x=1.0, y=0.0): 3.000,
            Point(x=1.0, y=0.25): 4.440,
            Point(x=1.0, y=0.5): 4.410,
            Point(x=1.0, y=0.75): 4.440,
            Point(x=1.0, y=1.0): 1.300,
        }
        af = axl.AshlockFingerprint(axl.WinStayLoseShift(), 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)
Example #18
0
def simulated_fixation(strategy_pair, N, i=1, repetitions=10,
                       cachefile=None):
    """Run an approximate Moran process and obtain the fixation probabilities"""
    if cachefile is None:
        cachefile = "../data/outcomes.csv"

    cache = generate_cache.read_csv(cachefile)
    for k, v in cache.items():
        cache[k] = axl.Pdf(v)

    players = []
    for _ in range(i):
        players.append(strategy_pair[0])
    for _ in range(N - i):
        players.append(strategy_pair[1])
    mp = axl.ApproximateMoranProcess(players, cached_outcomes=cache)

    win_count = 0
    for seed in range(repetitions):
        axl.seed(seed)
        mp.reset()
        mp.play()
        if mp.winning_strategy_name == str(players[0]):
            win_count += 1

    return win_count / repetitions
Example #19
0
    def test_population_init_with_given_rate(self):
        name = "score"
        turns = 10
        noise = 0
        repetitions = 5
        num_states = 2
        opponents = [s() for s in axl.demo_strategies]
        size = 10

        objective = dojo.prepare_objective(name=name,
                                           turns=turns,
                                           noise=noise,
                                           repetitions=repetitions)

        population = dojo.Population(params_class=dojo.FSMParams,
                                     params_kwargs={"num_states": num_states,
                                                    "mutation_probability": .5},
                                     size=size,
                                     objective=objective,
                                     output_filename=self.temporary_file.name,
                                     opponents=opponents,
                                     bottleneck=2,
                                     mutation_probability = .01,
                                     processes=1)

        for p in population.population:
            self.assertEqual(p.mutation_probability, .5)
        generations = 1
        axl.seed(0)
        population.run(generations, print_output=False)
        self.assertEqual(population.generation, 1)
Example #20
0
    def test_strategy(self):
        """
        Test that the strategy gives expected behaviour
        """

        axelrod.seed(8)
        opponent = axelrod.Cooperator()
        player = axelrod.WorseAndWorse()
        match = axelrod.Match((opponent, player), turns=10)
        self.assertEqual(match.play(), [('C', 'C'),
                                        ('C', 'C'),
                                        ('C', 'C'),
                                        ('C', 'C'),
                                        ('C', 'C'),
                                        ('C', 'C'),
                                        ('C', 'D'),
                                        ('C', 'C'),
                                        ('C', 'C'),
                                        ('C', 'C')])

        # Test that behaviour does not depend on opponent
        opponent = axelrod.Defector()
        player = axelrod.WorseAndWorse()
        axelrod.seed(8)
        match = axelrod.Match((opponent, player), turns=10)
        self.assertEqual(match.play(), [('D', 'C'),
                                        ('D', 'C'),
                                        ('D', 'C'),
                                        ('D', 'C'),
                                        ('D', 'C'),
                                        ('D', 'C'),
                                        ('D', 'D'),
                                        ('D', 'C'),
                                        ('D', 'C'),
                                        ('D', 'C')])
Example #21
0
def test_responses(test_class, P1, P2, history_1, history_2, responses,
                   random_seed=None, attrs=None):
    """
    Test responses to arbitrary histories. Used for the following tests
    in TestPlayer: first_play_test, markov_test, and responses_test.
    Works for arbitrary players as well. Input response_lists is a list of
    lists, each of which consists of a list for the history of player 1, a
    list for the history of player 2, and a list for the subsequent moves
    by player one to test.
    """

    if random_seed:
        axelrod.seed(random_seed)
    # Force the histories, In case either history is impossible or if some
    # internal state needs to be set, actually submit to moves to the strategy
    # method. Still need to append history manually.
    for h1, h2 in zip(history_1, history_2):
        simulate_play(P1, P2, h1, h2)
    # Run the tests
    for response in responses:
        s1, s2 = simulate_play(P1, P2)
        test_class.assertEqual(s1, response)
    if attrs:
        for attr, value in attrs.items():
            test_class.assertEqual(getattr(P1, attr), value)
Example #22
0
 def test_self_interaction_for_random_strategies(self):
     # Based on https://github.com/Axelrod-Python/Axelrod/issues/670
     axelrod.seed(0)
     players = [s() for s in axelrod.demo_strategies]
     tournament = axelrod.Tournament(players, repetitions=2, turns=5)
     results = tournament.play(progress_bar=False)
     self.assertEqual(results.payoff_diffs_means[-1][-1], 1.0)
    def test_generations(self):
        temporary_file = tempfile.NamedTemporaryFile()

        params_kwargs = {"plays": 1, "op_plays": 1, "op_start_plays": 2}
        population = dojo.Population(params_class=dojo.GamblerParams,
                                     params_kwargs=params_kwargs,
                                     size=self.size,
                                     objective=self.objective,
                                     output_filename=temporary_file.name,
                                     opponents=self.opponents,
                                     bottleneck=2,
                                     mutation_probability=.01,
                                     processes=1)

        generations = 4
        axl.seed(0)
        population.run(generations, print_output=False)
        self.assertEqual(population.generation, generations)

        results = []
        with open(temporary_file.name, "r") as f:
            reader = csv.reader(f)
            for row in reader:
                results.append(row)

        self.assertEqual(population.generation, len(results))
Example #24
0
    def test_seed(self):
        """Test that numpy seeds the sample properly"""

        for s in range(10):
            seed(s)
            sample = self.pdf.sample()
            seed(s)
            self.assertEqual(sample, self.pdf.sample())
Example #25
0
 def test_different_game(self):
     # Possible for Cooperator to become fixed when using a different game
     p1, p2 = axelrod.Cooperator(), axelrod.Defector()
     axelrod.seed(0)
     game = axelrod.Game(r=4, p=2, s=1, t=6)
     mp = MoranProcess((p1, p2), turns=5, game=game)
     populations = mp.play()
     self.assertEqual(mp.winning_strategy_name, str(p1))
Example #26
0
    def test_plot_data(self):
        axl.seed(0)  # Fingerprinting is a random process.
        af = AshlockFingerprint(axl.Cooperator())
        af.fingerprint(turns=5, repetitions=3, step=0.5, progress_bar=False)

        reshaped_data = np.array([[0.0, 0.0, 0.0], [2.0, 1.0, 2.0], [3.0, 3.0, 3.0]])
        plotted_data = af.plot().gca().images[0].get_array()
        np.testing.assert_allclose(plotted_data, reshaped_data)
Example #27
0
 def test_reset(self):
     axl.seed(0)
     player = axl.Stalker()
     m = axl.Match((player, axl.Alternator()))
     m.play()
     self.assertNotEqual(player.current_score, 0)
     player.reset()
     self.assertEqual(player.current_score, 0)
def run_tournament(filename, players,
                   seed=seed, turns=turns, repetitions=repetitions):
    try:
        os.remove(filename)
    except FileNotFoundError:
        pass
    axl.seed(seed)
    tournament = axl.Tournament(players, turns=turns, repetitions=repetitions)
    tournament.play(processes=0, filename=filename, build_results=False)
Example #29
0
 def test_three_players(self):
     players = [axelrod.Cooperator(), axelrod.Cooperator(), axelrod.Defector()]
     axelrod.seed(11)
     mp = MoranProcess(players)
     populations = mp.play()
     self.assertEqual(len(mp), 7)
     self.assertEqual(len(populations), 7)
     self.assertEqual(populations, mp.populations)
     self.assertEqual(mp.winning_strategy_name, str(axelrod.Defector()))
Example #30
0
 def test_sample_length(self):
     for seed, prob_end, expected_length in [
         (0, 0.5, 3),
         (1, 0.5, 1),
         (2, 0.6, 4),
         (3, 0.4, 1),
     ]:
         axelrod.seed(seed)
         self.assertEqual(axelrod.match.sample_length(prob_end), expected_length)
Example #31
0
 def test_sample_length(self):
     for seed, prob_end, expected_length in [
         (0, 0.5, 3),
         (1, 0.5, 1),
         (2, 0.6, 4),
         (3, 0.4, 1),
     ]:
         axl.seed(seed)
         self.assertEqual(axl.match.sample_length(prob_end),
                          expected_length)
Example #32
0
    def test_sample(self):
        """Test that sample maps to correct domain"""
        all_samples = []

        axl.seed(0)
        for sample in range(100):
            all_samples.append(self.pdf.sample())

        self.assertEqual(len(all_samples), 100)
        self.assertEqual(set(all_samples), set(self.observations))
Example #33
0
 def test_four_players(self):
     players = [axl.Cooperator() for _ in range(3)]
     players.append(axl.Defector())
     axl.seed(29)
     mp = axl.MoranProcess(players)
     populations = mp.play()
     self.assertEqual(len(mp), 9)
     self.assertEqual(len(populations), 9)
     self.assertEqual(populations, mp.populations)
     self.assertEqual(mp.winning_strategy_name, str(axl.Defector()))
 def test_serialization_csv(self):
     """Serializing and deserializing should return the original player."""
     seed(0)
     player = self.player()
     serialized = player.serialize_parameters()
     s = "0, 1, {}, 3".format(serialized)
     s2 = s.split(',')[2]
     deserialized_player = player.__class__.deserialize_parameters(s2)
     self.assertEqual(player, deserialized_player)
     self.assertEqual(deserialized_player, deserialized_player.clone())
Example #35
0
    def test_randomize(self):
        num_states = 2
        rows = [[0, C, 1, D], [0, D, 0, D], [1, C, 1, C], [1, D, 1, D]]
        fsm_params = FSMParams(num_states=num_states, rows=rows)

        axl.seed(5)
        fsm_params.randomize()
        self.assertNotEqual(rows, fsm_params.rows)
        self.assertNotEqual(C, fsm_params.initial_action)
        self.assertNotEqual(0, fsm_params.initial_state)
Example #36
0
    def test_crossover_odd_length(self):
        cycle1 = "C" * 7
        cycle2 = "D" * 7
        cross_cycle = "CDDDDDD"

        player1 = self.player_class(cycle=cycle1)
        player2 = self.player_class(cycle=cycle2)
        axl.seed(3)
        crossed = player1.crossover(player2)
        self.assertEqual(cross_cycle, crossed.cycle)
Example #37
0
    def test_outcome_repeats_stochastic(self, strategies, turns, seed):
        """a test to check that if a seed is set stochastic strategies give the
        same result"""
        results = []
        for _ in range(3):
            axl.seed(seed)
            players = [s() for s in strategies]
            results.append(axl.Match(players, turns).play())

        self.assertEqual(results[0], results[1])
        self.assertEqual(results[1], results[2])
Example #38
0
 def test_death_birth(self):
     """Two player death-birth should fixate after one round."""
     p1, p2 = axl.Cooperator(), axl.Defector()
     seeds = range(0, 20)
     for seed in seeds:
         axl.seed(seed)
         mp = axl.MoranProcess((p1, p2), mode="db")
         mp.play()
     self.assertIsNotNone(mp.winning_strategy_name)
     # Number of populations is 2: the original and the one after the first round.
     self.assertEqual(len(mp.populations), 2)
Example #39
0
    def test_crossover_dictionaries(self):
        dict1 = {'1': 1, '2': 2, '3': 3}
        dict2 = {'1': 'a', '2': 'b', '3': 'c'}

        axl.seed(0)
        crossed = crossover_dictionaries(dict1, dict2)
        self.assertEqual(crossed, {'1': 1, '2': 'b', '3': 'c'})

        axl.seed(1)
        crossed = crossover_dictionaries(dict1, dict2)
        self.assertEqual(crossed, dict2)
Example #40
0
 def test_score(self):
     axl.seed(0)
     opponents_information = [
         utils.PlayerInfo(s, {}) for s in axl.demo_strategies
     ]
     objective = utils.prepare_objective()
     score = utils.score_player(axl.Cooperator(),
                                objective=objective,
                                opponents_information=opponents_information)
     expected_score = 2.0949
     self.assertEqual(score, expected_score)
Example #41
0
 def test_init_without_default_rows(self):
     """
     Check that by default have random rows.
     """
     num_states = 2
     rows = []
     for seed in range(2):
         axl.seed(seed)
         fsm_params = FSMParams(num_states=num_states)
         rows.append(fsm_params.rows)
     self.assertNotEqual(*rows)
Example #42
0
 def test_atomic_mutation_fsm(self):
     axelrod.seed(12)
     players = [axelrod.EvolvableFSMPlayer(num_states=2, initial_state=1, initial_action=C)
                for _ in range(5)]
     mp = MoranProcess(players, turns=10, mutation_method="atomic")
     population = mp.play()
     self.assertEqual(
         mp.winning_strategy_name,
         'EvolvableFSMPlayer: ((0, C, 1, D), (0, D, 1, C), (1, C, 0, D), (1, D, 1, C)), 1, C, 2, 0.1')
     self.assertEqual(len(mp.populations), 31)
     self.assertTrue(mp.fixated)
Example #43
0
    def test_crossover_lists(self):
        list1 = [[0, C, 1, D], [0, D, 0, D], [1, C, 1, C], [1, D, 1, D]]
        list2 = [[0, D, 1, C], [0, C, 0, C], [1, D, 1, D], [1, C, 1, C]]

        axl.seed(0)
        crossed = crossover_lists(list1, list2)
        self.assertEqual(crossed, list1[:3] + list2[3:])

        axl.seed(1)
        crossed = crossover_lists(list1, list2)
        self.assertEqual(crossed, list1[:1] + list2[1:])
Example #44
0
 def test_atomic_mutation_cycler(self):
     axl.seed(10)
     cycle_length = 5
     players = [
         axl.EvolvableCycler(cycle_length=cycle_length) for _ in range(5)
     ]
     mp = axl.MoranProcess(players, turns=10, mutation_method="atomic")
     population = mp.play()
     self.assertEqual(mp.winning_strategy_name,
                      'EvolvableCycler: CDCDD, 5, 0.2, 1')
     self.assertEqual(len(mp.populations), 19)
     self.assertTrue(mp.fixated)
def test_result_from_numerical_experiments():
    axl.seed(2933)
    opponents = [np.random.random(4) for _ in range(1)]

    solution_set = opt_mo.reactive_best_response.get_candidate_reactive_best_responses(
        opponents)
    solution = opt_mo.reactive_best_response.get_argmax(
        opponents, solution_set)

    assert len(solution_set) == len(
        set([0, 0.13036776235395545, 0.4267968584197451, 1]))
    assert np.allclose(solution, (0, 0.4267968584197451, 2.6546912335393573))
Example #46
0
    def test_reset_history_and_attributes(self):
        """Make sure resetting works correctly."""
        player = self.player()
        clone = player.clone()
        opponent = axelrod.Random()

        for seed in range(10):
            axelrod.seed(seed)
            player.play(opponent)

        player.reset()
        self.assertEqual(player, clone)
Example #47
0
 def equality_of_players_test(self, p1, p2, seed, opponent):
     a1 = opponent()
     a2 = opponent()
     self.assertEqual(p1, p2)
     for player, op in [(p1, a1), (p2, a2)]:
         axl.seed(seed)
         for _ in range(10):
             simultaneous_play(player, op)
     self.assertEqual(p1, p2)
     p1 = pickle.loads(pickle.dumps(p1))
     p2 = pickle.loads(pickle.dumps(p2))
     self.assertEqual(p1, p2)
Example #48
0
    def test_score_with_sample_count_and_weights(self):
        name = "score"
        turns = 10
        noise = 0
        repetitions = 5
        num_states = 2
        opponents = [s() for s in axl.demo_strategies]
        size = 10

        objective = dojo.prepare_objective(name=name,
                                           turns=turns,
                                           noise=noise,
                                           repetitions=repetitions)

        population = dojo.Population(
            params_class=dojo.FSMParams,
            params_kwargs={"num_states": num_states},
            size=size,
            objective=objective,
            output_filename=self.temporary_file.name,
            opponents=opponents,
            sample_count=2,  # Randomly sample 2 opponents at each step
            weights=[5, 1, 1, 1, 1],
            bottleneck=2,
            mutation_probability=.01,
            processes=1)

        generations = 4
        axl.seed(0)
        population.run(generations, print_output=False)
        self.assertEqual(population.generation, 4)

        # Manually read from tempo file to find best strategy
        best_score, best_params = 0, None
        with open(self.temporary_file.name, "r") as f:
            reader = csv.reader(f)
            for row in reader:
                _, mean_score, sd_score, max_score, arg_max = row
                if float(max_score) > best_score:
                    best_score = float(max_score)
                    best_params = arg_max

        # Test the load params function
        for num in range(1, 4 + 1):
            best = dojo.load_params(params_class=dojo.FSMParams,
                                    filename=self.temporary_file.name,
                                    num=num)
            self.assertEqual(len(best), num)

            for parameters in best:
                self.assertIsInstance(parameters, dojo.FSMParams)

            self.assertEqual(best[0].__repr__(), best_params)
Example #49
0
    def test_set_seed(self):
        """Test that numpy and stdlib random seed is set by axelrod seed"""

        numpy_random_numbers = []
        stdlib_random_numbers = []
        for _ in range(2):
            seed(0)
            numpy_random_numbers.append(numpy.random.random())
            stdlib_random_numbers.append(random.random())

        self.assertEqual(numpy_random_numbers[0], numpy_random_numbers[1])
        self.assertEqual(stdlib_random_numbers[0], stdlib_random_numbers[1])
Example #50
0
    def test_add_noise(self):
        axelrod.seed(1)
        noise = 0.2
        s1, s2 = C, C
        noisy_s1, noisy_s2 = self.player()._add_noise(noise, s1, s2)
        self.assertEqual(noisy_s1, D)
        self.assertEqual(noisy_s2, C)

        noise = 0.9
        noisy_s1, noisy_s2 = self.player()._add_noise(noise, s1, s2)
        self.assertEqual(noisy_s1, D)
        self.assertEqual(noisy_s2, D)
Example #51
0
 def test_mutate_variations(self):
     """Generate many variations to test that mutate produces different strategies."""
     if not self.init_parameters:
         return
     axl.seed(100)
     variants_produced = False
     for _ in range(2, 400):
         player = self.player()
         mutant = player.mutate()
         if player != mutant:
             variants_produced = True
     self.assertTrue(variants_produced)
Example #52
0
    def test_output_from_literature(self):
        """
        This strategy is not fully described in the literature, however the
        scores for the strategy against a set of opponents is reported

        Bruno Beaufils, Jean-Paul Delahaye, Philippe Mathie
        "Our Meeting With Gradual: A Good Strategy For The Iterated Prisoner's
        Dilemma" Proc. Artif. Life 1996

        This test just ensures that the strategy is as was originally defined.

        See https://github.com/Axelrod-Python/Axelrod/issues/1294 for another
        discussion of this.
        """
        players = [
            axl.Cooperator(),
            axl.Defector(),
            axl.Random(),
            axl.TitForTat(),
            axl.Grudger(),
            axl.CyclerDDC(),
            axl.CyclerCCD(),
            axl.GoByMajority(),
            axl.SuspiciousTitForTat(),
            axl.Prober(),
            self.player(),
            axl.WinStayLoseShift(),
        ]

        axl.seed(1)
        turns = 1000
        tournament = axl.Tournament(players, turns=turns, 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[-2]
        ]
        expected_scores = [
            3000.0,
            915.0,
            2763.0,
            3000.0,
            3000.0,
            2219.0,
            3472.0,
            3000.0,
            2996.0,
            2999.0,
            3000.0,
            3000.0,
        ]
        self.assertEqual(scores, expected_scores)
Example #53
0
 def test_noisy_match(self):
     axl.seed(0)
     player = axl.Cooperator()
     opponent = axl.Defector()
     scores = utils.objective_score(player,
                                    opponent,
                                    turns=2,
                                    repetitions=3,
                                    noise=.8)
     # Stochastic so more repetitions are run
     self.assertEqual(len(scores), 3)
     # Cooperator should score 0 but noise implies it scores more
     self.assertNotEqual(max(scores), 0)
Example #54
0
 def test_constant_fitness_case(self):
     # Scores between an Alternator and Defector will be: (1,  6)
     axelrod.seed(0)
     players = (axelrod.Alternator(), axelrod.Alternator(),
                axelrod.Defector(), axelrod.Defector())
     mp = MoranProcess(players, turns=2)
     winners = []
     for _ in range(100):
         mp.play()
         winners.append(mp.winning_strategy_name)
         mp.reset()
     winners = Counter(winners)
     self.assertEqual(winners["Defector"], 88)
Example #55
0
 def test_three_players(self):
     players = [
         axelrod.Cooperator(),
         axelrod.Cooperator(),
         axelrod.Defector()
     ]
     axelrod.seed(11)
     mp = MoranProcess(players)
     populations = mp.play()
     self.assertEqual(len(mp), 7)
     self.assertEqual(len(populations), 7)
     self.assertEqual(populations, mp.populations)
     self.assertEqual(mp.winning_strategy_name, str(axelrod.Defector()))
Example #56
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)
Example #57
0
    def versus_test(self, opponent, expected_actions,
                    noise=None, seed=None, turns=10,
                    match_attributes=None, attrs=None,
                    init_kwargs=None):
        """
        Tests a sequence of outcomes for two given players.

        Parameters:
        -----------

        opponent: Player or list
            An instance of a player OR a sequence of actions. If a sequence of
            actions is passed, a Mock Player is created that cycles over that
            sequence.
        expected_actions: List
            The expected outcomes of the match (list of tuples of actions).
        noise: float
            Any noise to be passed to a match
        seed: int
            The random seed to be used
        length: int
            The length of the game. If `opponent` is a sequence of actions then
            the length is taken to be the length of the sequence.
        match_attributes: dict
            The match attributes to be passed to the players.  For example,
            `{length:-1}` implies that the players do not know the length of the
            match.
        attrs: dict
            Dictionary of internal attributes to check at the end of all plays
            in player
        init_kwargs: dict
            A dictionary of keyword arguments to instantiate player with
        """

        turns = len(expected_actions)
        if init_kwargs is None:
            init_kwargs = dict()

        if seed is not None:
            axelrod.seed(seed)

        player = self.player(**init_kwargs)

        match = axelrod.Match((player, opponent), turns=turns, noise=noise,
                              match_attributes=match_attributes)
        self.assertEqual(match.play(), expected_actions)

        if attrs:
            player = match.players[0]
            for attr, value in attrs.items():
                self.assertEqual(getattr(player, attr), value)
def main(index,
         players=players,
         processes=None,
         seed=1,
         turns=200,
         repetitions=10000,
         noise=0):
    """
    index of the player in question
    """
    edges = [(index, j) for j, _ in enumerate(players)]
    assert (index, index) in edges
    assert len(edges) == len(players)

    if processes is None:
        processes = multiprocessing.cpu_count()

    prefix = "{}_{}_{}_{}".format(seed, int(100 * noise), repetitions,
                                  abbreviations[str(players[index])])
    interactions_filename = "../data/cooperation_{}_interactions.csv".format(
        prefix)
    output_filename = "../data/cooperation_{}_array.gz".format(prefix)

    # Deleting the file if it exists
    try:
        os.remove(interactions_filename)
    except OSError:
        pass

    axl.seed(seed)  # Setting a seed
    assert axl.__version__ == "2.9.0"
    print("Axelrod version", axl.__version__)
    print(len(players), "Players")
    print("Seed", seed)
    print("Repetitions", repetitions)
    print("Noise", noise)
    print("Player", players[index])

    tournament = axl.SpatialTournament(players,
                                       edges=edges,
                                       turns=turns,
                                       repetitions=repetitions,
                                       noise=noise)

    tournament.play(filename=interactions_filename,
                    processes=processes,
                    build_results=False,
                    progress_bar=False)

    matrix = obtain_cooperation_matrix(interactions_filename)
    np.savetxt(fname=output_filename, X=matrix, delimiter=",")
Example #59
0
    def test_complete_tournament(self, strategies, turns, repetitions, noise,
                                 seed):
        """
        A test to check that a spatial tournament on the complete multigraph
        gives the same results as the round robin.
        """

        players = [s() for s in strategies]
        # edges
        edges = []
        for i in range(0, len(players)):
            for j in range(i, len(players)):
                edges.append((i, j))

        # create a round robin tournament
        tournament = axelrod.Tournament(players,
                                        repetitions=repetitions,
                                        turns=turns,
                                        noise=noise)
        # create a complete spatial tournament
        spatial_tournament = axelrod.Tournament(players,
                                                repetitions=repetitions,
                                                turns=turns,
                                                noise=noise,
                                                edges=edges)

        axelrod.seed(seed)
        results = tournament.play(progress_bar=False)
        axelrod.seed(seed)
        spatial_results = spatial_tournament.play(progress_bar=False)

        self.assertEqual(results.ranked_names, spatial_results.ranked_names)
        self.assertEqual(results.num_players, spatial_results.num_players)
        self.assertEqual(results.repetitions, spatial_results.repetitions)
        self.assertEqual(results.payoff_diffs_means,
                         spatial_results.payoff_diffs_means)
        self.assertEqual(results.payoff_matrix, spatial_results.payoff_matrix)
        self.assertEqual(results.payoff_stddevs,
                         spatial_results.payoff_stddevs)
        self.assertEqual(results.payoffs, spatial_results.payoffs)
        self.assertEqual(results.cooperating_rating,
                         spatial_results.cooperating_rating)
        self.assertEqual(results.cooperation, spatial_results.cooperation)
        self.assertEqual(results.normalised_cooperation,
                         spatial_results.normalised_cooperation)
        self.assertEqual(results.normalised_scores,
                         spatial_results.normalised_scores)
        self.assertEqual(results.good_partner_matrix,
                         spatial_results.good_partner_matrix)
        self.assertEqual(results.good_partner_rating,
                         spatial_results.good_partner_rating)
Example #60
0
 def test_matches_have_different_length(self):
     """
     A match between two players should have variable length across the
     repetitions
     """
     p1 = axelrod.Cooperator()
     p2 = axelrod.Cooperator()
     p3 = axelrod.Cooperator()
     players = [p1, p2, p3]
     axelrod.seed(0)
     tournament = axelrod.Tournament(players, prob_end=.5, repetitions=2)
     results = tournament.play(progress_bar=False)
     # Check that match length are different across the repetitions
     self.assertNotEqual(results.match_lengths[0], results.match_lengths[1])