def test_cache_update_required(self, p): assume(0 < p < 1) p1, p2 = axelrod.Cooperator(), axelrod.Cooperator() match = axelrod.Match((p1, p2), 5, noise=p) self.assertFalse(match._cache_update_required) cache = DeterministicCache() cache.mutable = False match = axelrod.Match((p1, p2), 5, deterministic_cache=cache) self.assertFalse(match._cache_update_required) match = axelrod.Match((p1, p2), 5) self.assertTrue(match._cache_update_required) p1 = axelrod.Random() match = axelrod.Match((p1, p2), 5) self.assertFalse(match._cache_update_required)
def test_three_players_with_mutation(self): p1 = axelrod.Cooperator() p2 = axelrod.Random() p3 = axelrod.Defector() players = [p1, p2, p3] mp = MoranProcess(players, mutation_rate=0.2) self.assertDictEqual( mp.mutation_targets, {str(p1): [p3, p2], str(p2): [p1, p3], str(p3): [p1, p2]}, ) # Test that mutation causes the population to alternate between # fixations counters = [Counter({"Cooperator": 3}), Counter({"Defector": 3})] for counter in counters: for _ in itertools.takewhile( lambda x: x.population_distribution() != counter, mp ): pass self.assertEqual(mp.population_distribution(), counter)
def test_clone(self): """Tests player cloning.""" player1 = axelrod.Random(p=0.75) # 0.5 is the default player2 = player1.clone() turns = 50 for op in [ axelrod.Cooperator(), axelrod.Defector(), axelrod.TitForTat() ]: player1.reset() player2.reset() seed = random.randint(0, 10**6) 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)
def test_reduction_to_TFT(self): player = self.player(p=0) opponent = axelrod.Random() test_responses(self, player, opponent, [C], [C], [C], seed=1, attrs={'probing': False}) test_responses(self, player, opponent, [D], [C], [D], attrs={'probing': False}) test_responses(self, player, opponent, [C], [C, D], [D, C], attrs={'probing': False}) test_responses(self, player, opponent, [D], [C, D], [D, D], attrs={'probing': False})
def test_reset_history(self): """Make sure resetting works correctly.""" if self.player.name == "Human": return p = self.player() p_clone = p.clone() player2 = axelrod.Random() for _ in range(10): p.play(player2) p.reset() self.assertEqual(len(p.history), 0) self.assertEqual(self.player().cooperations, 0) self.assertEqual(self.player().defections, 0) self.assertEqual(self.player().state_distribution, dict()) for k, v in p_clone.__dict__.items(): try: self.assertEqual(v, getattr(p_clone, k)) except ValueError: self.assertTrue(np.array_equal(v, getattr(p_clone, k)))
def test_retaliation_until_apology(self): """Tests the RetaliateUntilApologyTransformer.""" TFT = RetaliateUntilApologyTransformer()(axelrod.Cooperator) p1 = TFT() p2 = axelrod.Cooperator() p1.play(p2) p1.play(p2) self.assertEqual(p1.history, [C, C]) p1 = TFT() p2 = axelrod.Defector() p1.play(p2) p1.play(p2) self.assertEqual(p1.history, [C, D]) random.seed(12) p1 = TFT() p2 = axelrod.Random() for _ in range(5): p1.play(p2) self.assertEqual(p1.history, [C, C, D, D, C])
def __init__(self, strategy, opponents=None, number_of_opponents=50): """ Parameters ---------- strategy : class or instance A class that must be descended from axelrod.Player or an instance of axelrod.Player. opponents : list of instances A list that contains a list of opponents Default: A spectrum of Random players number_of_opponents: int The number of Random opponents Default: 50 """ self.strategy = strategy if opponents is None: self.opponents = [axl.Random(p) for p in np.linspace(0, 1, number_of_opponents)] else: self.opponents = opponents
def test_strategy(self): player = self.player() # Test against cyclers for opponent in [ axl.CyclerCCD(), axl.CyclerCCCD(), axl.CyclerCCCCCD(), axl.Alternator(), ]: player.reset() match = Match((player, opponent), turns=50) match.play() self.assertEqual(player.history[-1], D) # Test against non-cyclers and cooperators for opponent in [ axl.Random(), axl.AntiCycler(), axl.DoubleCrosser(), axl.Cooperator(), ]: player.reset() match = Match((player, opponent), turns=50, seed=43) match.play() self.assertEqual(player.history[-1], C)
def test_seeding_equality(self, seed): """Tests that a tournament with a given seed will return the same results each time. This specifically checks when running using multiple cores so as to confirm that https://github.com/Axelrod-Python/Axelrod/issues/1277 is fixed.""" rng = axl.RandomGenerator(seed=seed) players = [axl.Random(rng.random()) for _ in range(8)] tournament1 = axl.Tournament(name=self.test_name, players=players, game=self.game, turns=10, repetitions=100, seed=seed) tournament2 = axl.Tournament(name=self.test_name, players=players, game=self.game, turns=10, repetitions=100, seed=seed) for _ in range(4): results1 = tournament1.play(processes=2) results2 = tournament2.play(processes=2) self.assertEqual(results1.ranked_names, results2.ranked_names)
import axelrod as axl players = (axl.Cooperator(), axl.Random()) #players = ( axl.Cooperator(), axl.Alternator()) match = axl.Match(players, turns=1) results = match.play() print(results) listx = list(results[0]) if len(listx) == 2: akokuw = listx[0] bkokuw = listx[1] akoku = str(akokuw).strip() bkoku = str(bkokuw).strip() #print(str(akoku) == 'C') #print(bkoku) scores = match.scores() scoresx = list(scores[0]) if len(scoresx) == 2: ascore = scoresx[0] bscore = scoresx[1] if akoku == 'C' and bkoku == 'C': #協力協力 ascore = 10 bscore = 10 elif akoku == 'C' and bkoku == 'D': #協力裏切り ascore = 1 bscore = 11
preventing it from being recomputed if it is called multiple times with the same arguments.""" return _coconut.functools.lru_cache(maxsize, *args, **kwargs) _coconut_MatchError, _coconut_count, _coconut_enumerate, _coconut_makedata, _coconut_map, _coconut_reversed, _coconut_starmap, _coconut_tee, _coconut_zip, TYPE_CHECKING, reduce, takewhile, dropwhile = MatchError, count, enumerate, makedata, map, reversed, starmap, tee, zip, False, _coconut.functools.reduce, _coconut.itertools.takewhile, _coconut.itertools.dropwhile # Compiled Coconut: ----------------------------------------------------------- import axelrod as axl import nashpy as nash import random policyDict = { 'Cooperator': axl.Cooperator(), 'Defector': axl.Defector(), 'Random': axl.Random() } # vPol :: vertex -> policy #"""parameters for a PD game, which is the only we'll be trying. Could be generalized to other games""" class pdGameParams(_coconut.collections.namedtuple("pdGameParams", "alpha")): __slots__ = () __ne__ = _coconut.object.__ne__ def __eq__(self, other): return self.__class__ is other.__class__ and _coconut.tuple.__eq__( self, other) def __hash__(self):
def test_vs_random(self): # We can also test against random strategies actions = [(C, D), (D, C), (C, C), (C, D), (D, D)] self.versus_test(axl.Random(), expected_actions=actions, seed=17)
def test_vs_random2(self): actions = [(C, C), (C, C), (C, C), (C, C)] self.versus_test(axl.Random(), expected_actions=actions, seed=3)
def test_random_defection(self): # Random defection player = self.player(0.4) opponent = axelrod.Random() test_responses(self, player, opponent, [C], [C], [D], random_seed=1)
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"] secondgen_str_type = [ axl.SecondByChampion(), axl.SecondByEatherley(), axl.SecondByTester(), axl.SecondByTranquilizer(), axl.SecondByGrofman(), axl.SecondByKluepfel(),
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:
def test_strategy(self): # Test TitForTat behavior in first 15 turns opponent = axelrod.Cooperator() actions = list([(C, C)]) * 15 self.versus_test(opponent, expected_actions=actions) opponent = axelrod.Defector() actions = [(C, D)] + list([(D, D)]) * 14 self.versus_test(opponent, expected_actions=actions) opponent = axelrod.Alternator() actions = [(C, C)] + [(C, D), (D, C)] * 7 self.versus_test(opponent, expected_actions=actions) opponent_actions = [C, D, D, C, D, C, C, D, C, D, D, C, C, D, D] opponent = axelrod.MockPlayer(actions=opponent_actions) mem_actions = [C, C, D, D, C, D, C, C, D, C, D, D, C, C, D] actions = list(zip(mem_actions, opponent_actions)) self.versus_test(opponent, expected_actions=actions) opponent = axelrod.Random() actions = [(C, D), (D, D), (D, C), (C, C), (C, D), (D, C)] self.versus_test(opponent, expected_actions=actions, seed=0) # Test net-cooperation-score (NCS) based decisions in subsequent turns opponent = axelrod.Cooperator() actions = [(C, C)] * 15 + [(C, C)] self.versus_test( opponent, expected_actions=actions, seed=1, init_kwargs={"memory": [D] * 5 + [C] * 10}, ) opponent = axelrod.Cooperator() actions = [(C, C)] * 15 + [(C, C)] self.versus_test( opponent, expected_actions=actions, seed=1, init_kwargs={"memory": [D] * 4 + [C] * 11}, ) # Test alternative starting strategies opponent = axelrod.Cooperator() actions = list([(D, C)]) * 15 self.versus_test( opponent, expected_actions=actions, init_kwargs={"start_strategy": axelrod.Defector}, ) opponent = axelrod.Cooperator() actions = list([(C, C)]) * 15 self.versus_test( opponent, expected_actions=actions, init_kwargs={"start_strategy": axelrod.Cooperator}, ) opponent = axelrod.Cooperator() actions = [(C, C)] + list([(D, C), (C, C)]) * 7 self.versus_test( opponent, expected_actions=actions, init_kwargs={"start_strategy": axelrod.Alternator}, ) opponent = axelrod.Defector() actions = [(C, D)] * 7 + [(D, D)] self.versus_test( opponent, expected_actions=actions, seed=4, init_kwargs={ "memory": [C] * 12, "start_strategy": axelrod.Defector, "start_strategy_duration": 0, }, )
# After third round, if previous 2 times of opponent are D then # 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)
def test_representation(self): P1 = axelrod.Random() self.assertEqual(str(P1), 'Random')
def test_strategy(self): # Build an opponent that will cooperate the first 36 turns and # defect on the 37th turn opponent_actions = [C] * 36 + [D] + [C] * 100 Defect37 = axelrod.MockPlayer(actions=opponent_actions) # Activate the Fair-weather flag actions = [(C, C)] * 36 + [(D, D)] + [(C, C)] * 100 self.versus_test(Defect37, expected_actions=actions, attrs={"mode": "Fair-weather"}) # Defect on 37th turn to activate Fair-weather, then later defect to # exit Fair-weather opponent_actions = [C] * 36 + [D] + [C] * 100 + [D] + [C] * 4 Defect37_big = axelrod.MockPlayer(actions=opponent_actions) actions = [(C, C)] * 36 + [(D, D)] + [(C, C)] * 100 actions += [(C, D)] #Immediately exit Fair-weather actions += [(D, C), (C, C), (D, C), (C, C)] self.versus_test(Defect37_big, expected_actions=actions, seed=2, attrs={"mode": "Normal"}) actions = [(C, C)] * 36 + [(D, D)] + [(C, C)] * 100 actions += [(C, D)] #Immediately exit Fair-weather actions += [(D, C), (C, C), (C, C), (C, C)] self.versus_test(Defect37_big, expected_actions=actions, seed=1, attrs={"mode": "Normal"}) # Opponent defects on 1st turn opponent_actions = [D] + [C] * 46 Defect1 = axelrod.MockPlayer(actions=opponent_actions) # Tit-for-Tat on the first, but no streaks, no Fair-weather flag. actions = [(C, D), (D, C)] + [(C, C)] * 34 + [(D, C)] # Two cooperations scheduled after the 37-turn defection actions += [(C, C)] * 2 # TFT twice, then random number yields a DCC combo. actions += [(C, C)] * 2 actions += [(D, C), (C, C), (C, C)] # Don't draw next random number until now. Again DCC. actions += [(D, C), (C, C), (C, C)] self.versus_test(Defect1, expected_actions=actions, seed=2) # Defection on turn 37 by opponent doesn't have an effect here opponent_actions = [D] + [C] * 35 + [D] + [C] * 10 Defect1_37 = axelrod.MockPlayer(actions=opponent_actions) actions = [(C, D), (D, C)] + [(C, C)] * 34 + [(D, D)] actions += [(C, C)] * 2 actions += [(C, C)] * 2 actions += [(D, C), (C, C), (C, C)] actions += [(D, C), (C, C), (C, C)] self.versus_test(Defect1_37, expected_actions=actions, seed=2) # However a defect on turn 38 would be considered a burn. opponent_actions = [D] + [C] * 36 + [D] + [C] * 9 Defect1_38 = axelrod.MockPlayer(actions=opponent_actions) # Tit-for-Tat on the first, but no streaks, no Fair-weather flag. actions = [(C, D), (D, C)] + [(C, C)] * 34 + [(D, C)] # Two cooperations scheduled after the 37-turn defection actions += [(C, D), (C, C)] # TFT from then on, since burned actions += [(C, C)] * 8 self.versus_test(Defect1_38, expected_actions=actions, seed=2, attrs={"burned": True}) # Use alternator to test parity flags. actions = [(C, C), (C, D)] # Even streak is set to 2, one for the opponent's defect and one for # our defect. actions += [(D, C)] actions += [(C, D)] # Even streak is increased two more. actions += [(D, C)] actions += [(C, D)] # Opponent's defect increments even streak to 5, so we cooperate. actions += [(C, C)] actions += [(C, D), (D, C), (C, D), (D, C), (C, D)] # Another 5 streak actions += [(C, C)] # Repeat actions += [(C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] * 3 # Repeat. Notice that the last turn is the 37th move, but we do not # defect. actions += [(C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] self.versus_test(axelrod.Alternator(), expected_actions=actions) # Test for parity limit shortening. opponent_actions = [D, C] * 1000 AsyncAlternator = axelrod.MockPlayer(actions=opponent_actions) actions = [(C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] * 6 # Defect on 37th move actions += [(D, D)] actions += [(C, C)] # This triggers the burned flag. We should just Tit-for-Tat from here. actions += [(C, D)] actions += [(D, C), (C, D), (D, C), (C, D), (C, C)] # This is the seventh time we've hit the limit. So do it once more. actions += [(C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] # Now hit the limit sooner actions += [(C, D), (D, C), (C, D), (C, C)] * 5 self.versus_test(AsyncAlternator, expected_actions=actions, attrs={"parity_limit": 3}) # Use a Defector to test the 20-defect streak actions = [(C, D), (D, D), (D, D), (D, D), (D, D)] # Now the two parity flags are used actions += [(C, D), (C, D)] # Repeat actions += [(D, D), (D, D), (D, D), (D, D), (C, D), (C, D)] * 2 actions += [(D, D), (D, D)] # 20 D have passed (first isn't record) actions += [(D, D)] * 100 # The defect streak will always be detected from here on, because it # doesn't reset. This logic comes before parity streaks or the turn- # based logic. self.versus_test(axelrod.Defector(), expected_actions=actions, attrs={"recorded_defects": 119}) # Detect random expected_actions = [(C, D), (D, C), (C, D), (D, C), (C, D), (C, D), (D, D), (D, C), (C, D), (D, C), (C, C), (C, D), (D, D), (D, C), (C, D), (D, D), (D, C), (C, C), (C, D), (D, C), (C, D), (D, D), (D, C), (C, D), (D, D), (D, D), (C, D), (D, C), (C, C)] # Enter defect mode. expected_actions += [(D, C)] random.seed(10) player = self.player() match = axelrod.Match((player, axelrod.Random()), turns=len(expected_actions)) # The history matrix will be [[0, 2], [5, 6], [3, 6], [4, 2]] actions = match.play() self.assertEqual(actions, expected_actions) self.assertAlmostEqual(player.calculate_chi_squared( len(expected_actions)), 2.395, places=3) # Come back out of defect mode opponent_actions = [ D, C, D, C, D, D, D, C, D, C, C, D, D, C, D, D, C, C, D, C, D, D, C, D, D, D, D, C, C, C ] opponent_actions += [D] * 16 Rand_Then_Def = axelrod.MockPlayer(actions=opponent_actions) actions = [(C, D), (D, C), (C, D), (D, C), (C, D), (C, D), (D, D), (D, C), (C, D), (D, C), (C, C), (C, D), (D, D), (D, C), (C, D), (D, D), (D, C), (C, C), (C, D), (D, C), (C, D), (D, D), (D, C), (C, D), (D, D), (D, D), (C, D), (D, C), (C, C)] actions += [(D, C)] # Enter defect mode. actions += [(D, D)] * 14 # Mutual defect for a while, then exit Defect mode with two coops actions += [(C, D)] * 2 self.versus_test(Rand_Then_Def, expected_actions=actions, seed=10, attrs={ "mode": "Normal", "was_defective": True })
def test_strategy(self): actions = [(C, C)] * 100 # Cooperate forever self.versus_test(axelrod.Cooperator(), expected_actions=actions) # Since never two in a row, will respond in kind with 70% if # coop and 60% otherwise, after first couple actions = [ (C, C), (C, D), # Views first three as the same. # A random gets used in each of the first two. (D, C), (D, D), (C, C), (C, D) ] self.versus_test(axelrod.Alternator(), expected_actions=actions, seed=1) actions = [(C, C), (C, D), (C, C), (D, D), (D, C), (C, D)] self.versus_test(axelrod.Alternator(), expected_actions=actions, seed=2) actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] self.versus_test(axelrod.Alternator(), expected_actions=actions, seed=3) # Now we have to test the detect-random logic, which doesn't pick up # until after 26 turns. So we need a big sample. actions = [ (C, D), (D, D), (D, D), (D, D), (D, D), (D, C), (C, C), (C, D), (C, C), (D, D), (D, C), (C, C), (C, D), (D, D), (C, D), (D, D), (D, C), (C, C), (D, C), (C, C), (C, D), (D, D), (D, C), (C, D), (D, C), (C, C), (C, D), # Success detect random opponent for remaining turns. (D, D), (D, D), (D, D), (D, C), (D, D), (D, C), (D, D), (D, C), (D, D), (D, C), (D, C), (D, D), (D, D), (D, C), (D, C), (D, C), (D, C), (D, D), (D, C), (D, C), (D, C), (D, C), (D, D) ] self.versus_test(axelrod.Random(0.5), expected_actions=actions, seed=10)
def test_strategy(self): # TitForTat test_strategy init_kwargs = {"N": 1, "M": 1} actions = [(C, C), (C, D), (D, C), (C, D), (D, C)] self.versus_test( axl.Alternator(), expected_actions=actions, init_kwargs=init_kwargs ) actions = [(C, C), (C, C), (C, C), (C, C), (C, C)] self.versus_test( axl.Cooperator(), expected_actions=actions, init_kwargs=init_kwargs ) actions = [(C, D), (D, D), (D, D), (D, D), (D, D)] self.versus_test( axl.Defector(), expected_actions=actions, init_kwargs=init_kwargs ) actions = [(C, C), (C, D), (D, C), (C, D), (D, C)] self.versus_test( axl.Alternator(), expected_actions=actions, match_attributes={"length": float("inf")}, init_kwargs=init_kwargs, ) actions = [(C, D), (D, D), (D, C), (C, C), (C, D)] self.versus_test( axl.Random(), expected_actions=actions, seed=0, init_kwargs=init_kwargs ) actions = [(C, C), (C, D), (D, D), (D, C)] self.versus_test( axl.Random(), expected_actions=actions, seed=1, init_kwargs=init_kwargs ) opponent = axl.MockPlayer(actions=[C, D]) actions = [(C, C), (C, D), (D, C), (C, D)] self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) opponent = axl.MockPlayer(actions=[C, C, D, D, C, D]) actions = [(C, C), (C, C), (C, D), (D, D), (D, C), (C, D)] self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) # TitFor2Tats test_strategy init_kwargs = {"N": 1, "M": 2} opponent = axl.MockPlayer(actions=[D, D, D, C, C]) actions = [(C, D), (C, D), (D, D), (D, C), (C, C), (C, D)] self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) # TwoTitsForTat test_strategy init_kwargs = {"N": 2, "M": 1} opponent = axl.MockPlayer(actions=[D, C, C, D, C]) actions = [(C, D), (D, C), (D, C), (C, D), (D, C)] self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) actions = [(C, C), (C, C)] self.versus_test( opponent=axl.Cooperator(), expected_actions=actions, init_kwargs=init_kwargs, ) actions = [(C, D), (D, D), (D, D)] self.versus_test( opponent=axl.Defector(), expected_actions=actions, init_kwargs=init_kwargs, ) # Cooperator test_strategy actions = [(C, C)] + [(C, D), (C, C)] * 9 self.versus_test( opponent=axl.Alternator(), expected_actions=actions, init_kwargs={"N": 0, "M": 1}, ) self.versus_test( opponent=axl.Alternator(), expected_actions=actions, init_kwargs={"N": 0, "M": 5}, ) self.versus_test( opponent=axl.Alternator(), expected_actions=actions, init_kwargs={"N": 0, "M": 0}, ) # Defector test_strategy actions = [(D, C)] + [(D, D), (D, C)] * 9 self.versus_test( opponent=axl.Alternator(), expected_actions=actions, init_kwargs={"N": 1, "M": 0}, ) self.versus_test( opponent=axl.Alternator(), expected_actions=actions, init_kwargs={"N": 5, "M": 0}, ) # Default init args actions = [(C, C), (C, D), (C, D), (D, C), (D, C), (D, D), (C, C)] opponent = axl.MockPlayer(actions=[acts[1] for acts in actions]) self.versus_test(opponent=opponent, expected_actions=actions)
def test_deterministic_classification(self): """Test classification when p is 0 or 1""" for p in [0, 1]: player = axelrod.Random(p=p) self.assertFalse(player.classifier['stochastic'])
def test_init(self): player = axl.TitForTat() fingerprint = axl.TransitiveFingerprint(strategy=player) self.assertEqual(fingerprint.strategy, player) self.assertEqual(fingerprint.opponents, [axl.Random(p) for p in np.linspace(0, 1, 50)])
import axelrod as axl players = [s() for s in axl.strategies if "length" not in s.classifier["makes_use_of"]] parameterized_players = [axl.Random(0.1), axl.Random(0.3), axl.Random(0.7), axl.Random(0.9), axl.GTFT(0.1), axl.GTFT(0.3), axl.GTFT(0.7), axl.GTFT(0.9)] players += parameterized_players players.sort(key=lambda p:p.__repr__())
# The list of agents playing in the Axelrod's first tournament, except Graaskamp axl_first_players = [ axl.TitForTat(), axl.TidemanAndChieruzzi(), axl.Nydegger(), axl.Grofman(), axl.Shubik(), axl.SteinAndRapoport(), axl.Grudger(), axl.Davis(), axl.RevisedDowning(), axl.Feld(), axl.Joss(), axl.Tullock(), axl.UnnamedStrategy(), axl.Random() ] # The list of agents playing in the Axelrod's second tournament. Incomplete axl_second_players = [ axl.Black(), axl.Borufsen(), axl.Cave(), axl.Champion(), axl.Colbert(), axl.Eatherley(), axl.Getzler(), axl.Gladstein(), axl.GoByMajority(), axl.GraaskampKatzen(), axl.Harrington(),
# -------- 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()
oppScore = [] selfAvgList = [] oppAvgList = [] avgScore = [] oppAvgScore = [] evolveCode = [0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0,\ 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0] # For final experiments singEvolveCode = [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1,\ 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0] # strategies = [axelrod.Cooperator(), axelrod.Defector()] # strategies = [axelrod.TitFor2Tats(), axelrod.SuspiciousTitForTat(), axelrod.TitForTat(), axelrod.Prober()] strategies = [axelrod.Cooperator(), axelrod.Defector(), axelrod.CyclerCCD(),axelrod.HardTitForTat(),\ axelrod.TitFor2Tats(), axelrod.SuspiciousTitForTat(), axelrod.Random(), axelrod.TitForTat(), axelrod.Prober()] learner = axelrod.LearnerAxel(memory_depth=2, exploreProb=0.1, learnerType=2) multAxel = axelrod.EvolveAxel(3, evolveCode, 'MULT') singAxel = axelrod.EvolveAxel(3, evolveCode, 'SING') ply = learner # print ply for p in strategies: print "Currently playing against strategy:", p for turn in range(numTurns): ply.play(p) selfList = map(ScoreMatrix, zip(ply.history, p.history)) oppList = map(ScoreMatrix, zip(p.history, ply.history))
def test_retaliation_until_apology_stochastic(self): TFT = RetaliateUntilApologyTransformer()(axl.Cooperator) p1 = TFT() p2 = axl.Random() self.versus_test(p1, p2, [C, C, D, D, C], [C, D, D, C, D], seed=1)
def test_stochastic(self): self.assertTrue(axelrod.Random().stochastic)