Esempio n. 1
0
 def test_initial_strategy(self):
     """
     Starts by cooperating
     """
     P1 = axelrod.Grudger()
     P2 = axelrod.Player()
     self.assertEqual(P1.strategy(P2), 'C')
Esempio n. 2
0
 def test_vs_tit_for_tat(self):
     """
     Will keep nasty strategies happy if it can
     """
     P1 = axelrod.MindReader()
     P2 = axelrod.Grudger()
     self.assertEqual(P1.strategy(P2), 'C')
def tscizzle_strategies():
    """The list of strategies used in @tscizzle's Morality Metrics paper."""

    strategies = [
        axelrod.Cooperator(),
        axelrod.Defector(),
        axelrod.Eatherley(),
        axelrod.Champion(),
        axelrod.GTFT(p=0.1),
        axelrod.GTFT(p=0.3),
        axelrod.GoByMajority(soft=True),
        axelrod.GoByMajority(soft=False),
        axelrod.TitFor2Tats(),
        axelrod.Random(0.8),
        axelrod.Random(0.5),
        axelrod.Random(0.2),
        axelrod.WinStayLoseShift(),  # Pavlov
        axelrod.TitForTat(),
        axelrod.TwoTitsForTat(),
        axelrod.Grudger(),  # Friedman
        axelrod.Tester(),
        axelrod.SuspiciousTitForTat(),
        axelrod.Joss(0.9),
        axelrod.Joss(0.7),
    ]
    return strategies
Esempio n. 4
0
 def test_rounds(self):
     self.versus_test(
         axl.Grudger(),
         axl.SuspiciousTitForTat(),
         [C] + [D] * 9,
         [D, C] + [D] * 8,
     )
Esempio n. 5
0
 def test_vs_grudger(self):
     """
     Will keep nasty strategies happy if it can
     """
     p1 = axelrod.MindReader()
     p2 = axelrod.Grudger()
     self.assertEqual(p1.strategy(p2), C)
Esempio n. 6
0
    def test_tournament(self):
        """Test tournament."""

        outcome = [('Cooperator', [1800, 1800, 1800, 1800, 1800]),
                   ('Defector', [1612, 1612, 1612, 1612, 1612]),
                   ('Go By Majority', [1999, 1999, 1999, 1999, 1999]),
                   ('Grudger', [1999, 1999, 1999, 1999, 1999]),
                   ('Tit For Tat', [1999, 1999, 1999, 1999, 1999])]

        outcome.sort()

        P1 = axelrod.Cooperator()
        P2 = axelrod.TitForTat()
        P3 = axelrod.Defector()
        P4 = axelrod.Grudger()
        P5 = axelrod.GoByMajority()
        tournament = axelrod.Tournament(name='test',
                                        players=[P1, P2, P3, P4, P5],
                                        game=self.game,
                                        turns=200,
                                        repetitions=5)
        names = [str(p) for p in tournament.players]
        results = tournament.play().results
        scores = [[
            sum([r[i] for ir, r in enumerate(res) if ir != ires])
            for i in range(5)
        ] for ires, res in enumerate(results)]
        self.assertEqual(sorted(zip(names, scores)), outcome)
def sp_strategies():
    """The list of strategies used in Stewart and Plotkin's 2012 tournament."""

    strategies = [
        axelrod.Cooperator(),  # ALLC
        axelrod.Defector(),  # ALLD
        axelrod.GTFT(),
        axelrod.GoByMajority(soft=False),  # HARD_MAJO
        #axelrod.GoByMajority(soft=True), # SOFT_MAJO
        axelrod.TitFor2Tats(),  # TFT2
        axelrod.HardTitFor2Tats(),  # HARD_TFT2
        axelrod.Random(),  # RANDOM
        axelrod.WinStayLoseShift(),  # WSLS
        axelrod.TitForTat(),
        axelrod.HardTitForTat(),  # HARD_TFT
        axelrod.Grudger(),  # GRIM
        axelrod.Joss(),  # HARD_JOSS
        axelrod.ZDGTFT2(),
        axelrod.ZDExtort2(),
        axelrod.Prober(),
        axelrod.Prober2(),
        axelrod.Prober3(),
        axelrod.HardProber(),
        axelrod.Calculator(),
    ]
    return strategies
Esempio n. 8
0
 def test_simulate_matches(self):
     """
     Simulates a number of matches
     """
     P1 = axelrod.MindReader()
     P2 = axelrod.Grudger()
     P1.simulate_match(P2, 'C', 4)
     self.assertEqual(P2.history, ['C', 'C', 'C', 'C'])
Esempio n. 9
0
 def test_simulate_matches(self):
     """
     Simulates a number of matches
     """
     p1 = axelrod.MindReader()
     p2 = axelrod.Grudger()
     simulate_match(p1, p2, C, 4)
     self.assertEqual(p2.history, [C, C, C, C])
Esempio n. 10
0
    def test_vs_grudger(self):
        """ Will force even Grudger to forget its grudges"""

        P1 = axelrod.MindController()
        P2 = axelrod.Grudger()
        P1.history = [D, D, D, D]
        self.assertEqual(P1.strategy(P2), D)
        self.assertEqual(P2.strategy(P1), C)
Esempio n. 11
0
    def test_vs_grudger(self):
        """ Will force even Grudger to forget its grudges"""

        p1 = axl.MindController()
        p2 = axl.Grudger()
        for _ in range(4):
            p1.history.append(D, C)
            p2.history.append(C, D)
        self.assertEqual(p1.strategy(p2), D)
        self.assertEqual(p2.strategy(p1), C)
Esempio n. 12
0
 def test_history_is_same(self):
     """
     Checks that the history is not altered by the player
     """
     P1 = axelrod.MindReader()
     P2 = axelrod.Grudger()
     P1.history = ['C', 'C']
     P2.history = ['C', 'D']
     P1.strategy(P2)
     self.assertEqual(P1.history, ['C', 'C'])
     self.assertEqual(P2.history, ['C', 'D'])
Esempio n. 13
0
 def test_round_robin_cooperator_v_titfortat_v_defector_v_grudger(self):
     """
     Test round robin: tit for tat does a lot better this time around
     """
     P1 = axelrod.Cooperator()
     P2 = axelrod.TitForTat()
     P3 = axelrod.Defector()
     P4 = axelrod.Grudger()
     tournament = axelrod.Axelrod(P1, P2, P3, P4)
     tournament.round_robin(turns=10)
     self.assertEqual([(str(player), player.score) for player in sorted(tournament.players, key=lambda x: x.score)], [('Defector', 72), ('Tit For Tat', 81), ('Grudger', 81), ('Cooperator', 90)])
Esempio n. 14
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(),
        ]

        turns = 1000
        tournament = axl.Tournament(players,
                                    turns=turns,
                                    repetitions=1,
                                    seed=75)
        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)
Esempio n. 15
0
 def test_round_robin_cooperator_v_titfortat_v_defector_v_grudger_v_go_by_majority(self):
     """
     Test round robin: Tit for tat now wins
     """
     P1 = axelrod.Cooperator()
     P2 = axelrod.TitForTat()
     P3 = axelrod.Defector()
     P4 = axelrod.Grudger()
     P5 = axelrod.GoByMajority()
     tournament = axelrod.Axelrod(P1, P2, P3, P4, P5)
     tournament.round_robin(turns=10)
     self.assertEqual([(str(player), player.score) for player in sorted(tournament.players, key=lambda x: x.score)], [('Tit For Tat', 101), ('Grudger', 101), ('Go By Majority', 101), ('Defector', 108), ('Cooperator', 110)])
Esempio n. 16
0
 def test_strategy(self):
     """
     If opponent defects at any point then the player will defect forever
     """
     P1 = axelrod.Grudger()
     P2 = axelrod.Player()
     P1.history = ['C', 'D', 'D', 'D']
     P2.history = ['C', 'C', 'C', 'C']
     self.assertEqual(P1.strategy(P2), 'C')
     P1.history = ['C', 'C', 'D', 'D', 'D']
     P2.history = ['C', 'D', 'C', 'C', 'C']
     self.assertEqual(P1.strategy(P2), 'D')
Esempio n. 17
0
 def test_history_is_same(self):
     """
     Checks that the history is not altered by the player
     """
     p1 = axelrod.MindReader()
     p2 = axelrod.Grudger()
     p1.history.append(C, C)
     p1.history.append(C, D)
     p2.history.append(C, C)
     p2.history.append(D, C)
     p1.strategy(p2)
     self.assertEqual(p1.history, [C, C])
     self.assertEqual(p2.history, [C, D])
Esempio n. 18
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)
Esempio n. 19
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)
Esempio n. 20
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)
Esempio n. 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])]))
Esempio n. 22
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()
Esempio n. 23
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()
Esempio n. 24
0
    def test_strategy(self):
        # Play against opponents
        actions = [(C, D), (D, C), (C, C), (C, C), (C, D), (D, D)]
        self.versus_test(axelrod.Random(), expected_actions=actions, seed=0)

        actions = [(C, C), (C, C), (C, D), (D, C), (C, D), (D, D)]
        self.versus_test(axelrod.Random(), expected_actions=actions, seed=1)

        actions = [(C, C), (C, D), (D, C), (C, D), (D, C)]
        self.versus_test(axelrod.Alternator(), expected_actions=actions)

        actions = [(C, C) * 50, (D, C), (C, C) * 5]
        self.versus_test(axelrod.Cooperator(), expected_actions=actions)

        actions = [(C, D), (D, D) * 49, (D, D) * 6]
        self.versus_test(axelrod.Defector(), expected_actions=actions)

        actions = [(C, C) * 50, (D, C), (C, C) * 5]
        self.versus_test(axelrod.Grumpy(), expected_actions=actions)

        actions = [(C, C) * 50, (D, C), (C, D) * 5]
        self.versus_test(axelrod.Grudger(), expected_actions=actions)
Esempio n. 25
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
Esempio n. 26
0
    def setUpClass(cls):
        cls.game = axelrod.Game()
        cls.players = [
            axelrod.Cooperator(),
            axelrod.TitForTat(),
            axelrod.Defector(),
            axelrod.Grudger(),
            axelrod.GoByMajority()
        ]
        cls.test_name = 'test'
        cls.test_repetitions = 5

        cls.expected_payoff = [[600, 600, 0, 600, 600],
                               [600, 600, 199, 600, 600],
                               [1000, 204, 200.0, 204, 204],
                               [600, 600, 199, 600.0, 600],
                               [600, 600, 199, 600, 600]]

        cls.expected_cooperation = [[200, 200, 200, 200, 200],
                                    [200, 200, 1, 200, 200],
                                    [0.0, 0.0, 0.0, 0.0, 0.0],
                                    [200, 200, 1, 200, 200],
                                    [200, 200, 1, 200, 200]]
Esempio n. 27
0
                #  return D if previous 3 times of opponent are C then return C
                if len(self.history) > 2:
                    if list(opponent.history)[-2] == D and list(opponent.history)[-1] == D:
                        return D
                    elif list(opponent.history)[-3:len(self.history)] ==[C, C, C]:
                        return C
                return C
        return C

#==============================================================================
# Tournament Running
#==============================================================================

# Store strategies that we need to test for the tornament into players
players = [IDoWhatIWant(), axl.Random(), axl.TitForTat(), axl.Defector(), axl.BackStabber(),
           axl.FirstByDavis(), axl.Grudger(), axl.Gambler(), axl.EvolvedLookerUp2_2_2(),
           axl.Cooperator()]

# Setting tournament with 200 turns and repetitions with 20
tournament = axl.Tournament(players, turns = 200, repetitions = 20)
# Run the tournament and save the result into results
results = tournament.play()
# Output the rank of choosen strategies
results.ranked_names

# Save results into csv file
results.write_summary('Milestone_3_result.csv')

# Save all results plots
plot = axl.Plot(results)
axl.Plot.save_all_plots(plot, 'Milestone_3', filetype = 'png')
Esempio n. 28
0
# Include a list of parametrized strategies

#### ORDER MUST BE THE SAME AS FIRSTEN_STR TYPE
firstgen_str_text = [   "Cooperator", "Alternator", "TitForTat", "TidemanAndChieruzzi", "Nydegger", "Grofman",
                        "Shubik", "SteinAndRapoport", "Grudger", "Davis", "RevisedDowning", "Feld", "Joss","Tullock", "Random" ]

firstgen_str_type = [       axl.Cooperator(),   
                            axl.Alternator(),
                            axl.TitForTat(),
                            axl.FirstByTidemanAndChieruzzi(),
                            axl.FirstByNydegger(),
                            axl.FirstByGrofman(),
                            axl.FirstByShubik(),
                            axl.FirstBySteinAndRapoport(),
                            axl.Grudger(),
                            axl.FirstByDavis(),
                            axl.RevisedDowning(),
                            axl.FirstByFeld(),
                            axl.FirstByJoss(),
                            axl.FirstByTullock(),
                            axl.Random() ]
#### ORDER MUST BE THE SAME AS FISTGEN STR STR(TEXT)
secondgen_str_text = [  "Champion", "Eatherley", "Tester", "Tranquilizer", "SecGrofman", "Kluepfel", "Borufsen", "Cave",
                        "WmAdams", "GraaskampKatzen", "Weiner", "Harrington", "SecTidemanAndChieruzzi", "Getzler", "Leyvraz", "White", "Black",
                        "RichardHufford", "Yamachi", "Colbert", "Mikkelson", "Rowsam", "Appold"]

secondgen_str_text_a = [  "Champion", "Eatherley", "Tester", "Tranquilizer", "SecGrofman", "Kluepfel", "Borufsen", "Cave",
                        "WmAdams", "GraaskampKatzen", "Weiner", "Harrington", "SecTidemanAndChieruzzi", "Getzler", "Leyvraz", "White", "Black",
                        "RichardHufford", "Yamachi", "Colbert", "Mikkelson", "Rowsam", "Appold", "Alternator"]
Esempio n. 29
0
# -------- CELL 1 --------
# The ! means 'run this as a bash script' 
! pip install axelrod
! pip install axelrod-dojo
! wget https://raw.githubusercontent.com/GitToby/FinalYearProject/master/code/full_analysis.py

# -------- CELL 2 --------
import axelrod as axl
import full_analysis as fa

run = fa.NewAnalysisRun(population_size=40)

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

run.start()
Esempio n. 30
0
import os
import time

import axelrod as axl
import axelrod_dojo as axl_dojo
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

C, D = axl.Action

interesting_opponents = [axl.TitForTat(), axl.Alternator(), axl.Grudger(), axl.Random(), axl.EvolvedFSM16(),
                         axl.CollectiveStrategy()]
col_names = ["generation", "mean_score", "standard_deviation", "best_score", "sequence"]


def runGeneticAlgo(opponent, population_size=150, number_of_game_turns=200, cycle_length=200, generations=250,
                   mutation_probability=0.1, mutation_potency=1, reset_file=True):
    cycler_class = axl_dojo.CyclerParams
    cycler_objective = axl_dojo.prepare_objective(name="score", turns=number_of_game_turns, repetitions=1)
    cycler_kwargs = {
        "sequence_length": cycle_length,
        "mutation_probability": mutation_probability,
        "mutation_potency": mutation_potency
    }

    output_file_name = "data/" + str(opponent).replace(" ", "_") + ".csv"
    try:
        if reset_file and os.path.isfile(output_file_name):
            os.remove(output_file_name)
    finally: