|
| 1 | +"""Utilities used by various strategies""" |
| 2 | +import functools |
| 3 | +import collections |
| 4 | +import itertools |
| 5 | + |
| 6 | +from axelrod import RoundRobin, update_history |
| 7 | +from axelrod import Actions |
| 8 | + |
| 9 | +from axelrod.strategies.cycler import Cycler |
| 10 | + |
| 11 | +C, D = Actions.C, Actions.D |
| 12 | + |
| 13 | +def detect_cycle(history, min_size=1, offset=0): |
| 14 | + """Detects cycles in the sequence history. |
| 15 | +
|
| 16 | + Mainly used by hunter strategies. |
| 17 | +
|
| 18 | + Parameters |
| 19 | +
|
| 20 | + history: sequence of C and D |
| 21 | + The sequence to look for cycles within |
| 22 | + min_size: int, 1 |
| 23 | + The minimum length of the cycle |
| 24 | + offset: int, 0 |
| 25 | + The amount of history to skip initially |
| 26 | + """ |
| 27 | + history_tail = history[-offset:] |
| 28 | + for i in range(min_size, len(history_tail) // 2): |
| 29 | + cycle = tuple(history_tail[:i]) |
| 30 | + for j, elem in enumerate(history_tail): |
| 31 | + if elem != cycle[j % len(cycle)]: |
| 32 | + break |
| 33 | + if j == len(history_tail) - 1: |
| 34 | + # We made it to the end, is the cycle itself a cycle? |
| 35 | + # I.E. CCC is not ok as cycle if min_size is really 2 |
| 36 | + # Since this is the same as C |
| 37 | + return cycle |
| 38 | + return None |
| 39 | + |
| 40 | + |
| 41 | +def limited_simulate_play(player_1, player_2, h1): |
| 42 | + """Here we want to replay player_1's history to player_2, allowing |
| 43 | + player_2's strategy method to set any internal variables as needed. If you |
| 44 | + need a more complete simulation, see `simulate_play` in player.py. This |
| 45 | + function is specifically designed for the needs of MindReader.""" |
| 46 | + h2 = player_2.strategy(player_1) |
| 47 | + update_history(player_1, h1) |
| 48 | + update_history(player_2, h2) |
| 49 | + |
| 50 | +def simulate_match(player_1, player_2, strategy, rounds=10): |
| 51 | + """Simulates a number of matches.""" |
| 52 | + for match in range(rounds): |
| 53 | + limited_simulate_play(player_1, player_2, strategy) |
| 54 | + |
| 55 | +def look_ahead(player_1, player_2, game, rounds=10): |
| 56 | + """Looks ahead for `rounds` and selects the next strategy appropriately.""" |
| 57 | + results = [] |
| 58 | + |
| 59 | + # Simulate plays for `rounds` rounds |
| 60 | + strategies = [C, D] |
| 61 | + for strategy in strategies: |
| 62 | + # Instead of a deepcopy, create a new opponent and play out the history |
| 63 | + opponent_ = player_2.clone() |
| 64 | + player_ = Cycler(strategy) # Either cooperator or defector |
| 65 | + for h1 in player_1.history: |
| 66 | + limited_simulate_play(player_, opponent_, h1) |
| 67 | + |
| 68 | + round_robin = RoundRobin(players=[player_, opponent_], game=game, |
| 69 | + turns=rounds) |
| 70 | + simulate_match(player_, opponent_, strategy, rounds) |
| 71 | + results.append(round_robin._calculate_scores(player_, opponent_)[0]) |
| 72 | + |
| 73 | + return strategies[results.index(max(results))] |
| 74 | + |
| 75 | + |
| 76 | +class Memoized(object): |
| 77 | + """Decorator. Caches a function's return value each time it is called. |
| 78 | + If called later with the same arguments, the cached value is returned |
| 79 | + (not reevaluated). From: |
| 80 | + https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize |
| 81 | + """ |
| 82 | + def __init__(self, func): |
| 83 | + self.func = func |
| 84 | + self.cache = {} |
| 85 | + |
| 86 | + def __call__(self, *args): |
| 87 | + if not isinstance(args, collections.Hashable): |
| 88 | + # uncacheable. a list, for instance. |
| 89 | + # better to not cache than blow up. |
| 90 | + return self.func(*args) |
| 91 | + if args in self.cache: |
| 92 | + return self.cache[args] |
| 93 | + else: |
| 94 | + value = self.func(*args) |
| 95 | + self.cache[args] = value |
| 96 | + return value |
| 97 | + |
| 98 | + def __repr__(self): |
| 99 | + """Return the function's docstring.""" |
| 100 | + return self.func.__doc__ |
| 101 | + |
| 102 | + def __get__(self, obj, objtype): |
| 103 | + """Support instance methods.""" |
| 104 | + return functools.partial(self.__call__, obj) |
| 105 | + |
| 106 | + |
| 107 | +@Memoized |
| 108 | +def recursive_thue_morse(n): |
| 109 | + """The recursive definition of the Thue-Morse sequence. The first few terms |
| 110 | + of the Thue-Morse sequence are: |
| 111 | + 0 1 1 0 1 0 0 1 1 0 0 1 0 1 1 0 . . .""" |
| 112 | + |
| 113 | + if n == 0: |
| 114 | + return 0 |
| 115 | + if n % 2 == 0: |
| 116 | + return recursive_thue_morse(n / 2) |
| 117 | + if n % 2 == 1: |
| 118 | + return 1 - recursive_thue_morse((n - 1) / 2) |
| 119 | + |
| 120 | + |
| 121 | +def thue_morse_generator(start=0): |
| 122 | + """A generator for the Thue-Morse sequence.""" |
| 123 | + |
| 124 | + for n in itertools.count(start): |
| 125 | + yield recursive_thue_morse(n) |
0 commit comments