From 562be023ef93fbe7a8e02c137b7b628cc25e42bc Mon Sep 17 00:00:00 2001 From: Vince Knight Date: Wed, 8 Apr 2020 09:38:49 +0100 Subject: [PATCH] Revert "Run black on all files" This reverts commit 6e31d2ada55ecb647a4430cf801669e1444a448a. --- .../compute_finite_state_machine_memory.py | 33 ++- axelrod/evolvable_player.py | 3 +- axelrod/graph.py | 3 +- axelrod/moran.py | 6 +- axelrod/strategies/adaptor.py | 20 +- axelrod/strategies/ann.py | 73 ++--- axelrod/strategies/axelrod_first.py | 52 +--- axelrod/strategies/axelrod_second.py | 6 +- axelrod/strategies/calculator.py | 3 +- axelrod/strategies/cycler.py | 20 +- axelrod/strategies/finite_state_machines.py | 147 +++++----- axelrod/strategies/gambler.py | 18 +- axelrod/strategies/grudger.py | 2 +- axelrod/strategies/hmm.py | 123 ++------- axelrod/strategies/lookerup.py | 43 +-- axelrod/strategies/prober.py | 2 +- axelrod/strategies/revised_downing.py | 2 +- axelrod/strategies/shortmem.py | 2 +- axelrod/strategy_transformers.py | 4 +- axelrod/tests/property.py | 9 +- axelrod/tests/strategies/test_adaptor.py | 32 ++- axelrod/tests/strategies/test_ann.py | 13 +- axelrod/tests/strategies/test_apavlov.py | 8 +- .../tests/strategies/test_axelrod_first.py | 11 +- .../tests/strategies/test_axelrod_second.py | 254 ++++++++---------- axelrod/tests/strategies/test_backstabber.py | 8 +- .../tests/strategies/test_bush_mosteller.py | 5 +- axelrod/tests/strategies/test_calculator.py | 4 +- axelrod/tests/strategies/test_cooperator.py | 8 +- axelrod/tests/strategies/test_darwin.py | 8 +- axelrod/tests/strategies/test_doubler.py | 4 +- .../tests/strategies/test_evolvable_player.py | 14 +- .../strategies/test_finite_state_machines.py | 32 ++- axelrod/tests/strategies/test_forgiver.py | 5 +- axelrod/tests/strategies/test_gambler.py | 44 +-- axelrod/tests/strategies/test_geller.py | 16 +- axelrod/tests/strategies/test_grudger.py | 2 +- axelrod/tests/strategies/test_headsup.py | 21 +- axelrod/tests/strategies/test_hunter.py | 8 +- axelrod/tests/strategies/test_negation.py | 12 +- axelrod/tests/strategies/test_prober.py | 20 +- .../tests/strategies/test_revised_downing.py | 1 - axelrod/tests/strategies/test_selfsteem.py | 8 +- axelrod/tests/strategies/test_shortmem.py | 2 +- axelrod/tests/strategies/test_verybad.py | 4 +- .../tests/strategies/test_worse_and_worse.py | 4 +- .../tests/strategies/test_zero_determinant.py | 48 +++- ...est_compute_finite_state_machine_memory.py | 22 +- axelrod/tests/unit/test_ecosystem.py | 4 +- axelrod/tests/unit/test_eigen.py | 1 + axelrod/tests/unit/test_fingerprint.py | 4 +- axelrod/tests/unit/test_graph.py | 87 +++--- axelrod/tests/unit/test_history.py | 13 +- axelrod/tests/unit/test_interaction_utils.py | 46 +--- axelrod/tests/unit/test_match.py | 18 +- axelrod/tests/unit/test_mock_player.py | 1 + axelrod/tests/unit/test_moran.py | 30 +-- axelrod/tests/unit/test_pickling.py | 31 +-- axelrod/tests/unit/test_property.py | 4 +- axelrod/tournament.py | 10 +- 60 files changed, 676 insertions(+), 762 deletions(-) diff --git a/axelrod/compute_finite_state_machine_memory.py b/axelrod/compute_finite_state_machine_memory.py index 366ab45a3..0f83d3494 100644 --- a/axelrod/compute_finite_state_machine_memory.py +++ b/axelrod/compute_finite_state_machine_memory.py @@ -47,7 +47,10 @@ def __hash__(self): def __eq__(self, other_memit) -> bool: """In action and out actions are the same.""" - return self.in_act == other_memit.in_act and self.out_act == other_memit.out_act + return ( + self.in_act == other_memit.in_act + and self.out_act == other_memit.out_act + ) def __lt__(self, other_memit) -> bool: return repr(self) < repr(other_memit) @@ -107,10 +110,9 @@ def get_accessible_transitions( accessible_transitions = dict() for trans in transition_iterator(transitions): if trans.state in accessible_states: - accessible_transitions[(trans.state, trans.last_opponent_action)] = ( - trans.next_state, - trans.next_action, - ) + accessible_transitions[ + (trans.state, trans.last_opponent_action) + ] = (trans.next_state, trans.next_action) return accessible_transitions @@ -177,7 +179,9 @@ def get_memory_from_transitions( transitions = get_accessible_transitions(transitions, initial_state) # Get the incoming actions for each state. - incoming_action_by_state = defaultdict(set) # type: DefaultDict[int, Set[Action]] + incoming_action_by_state = defaultdict( + set + ) # type: DefaultDict[int, Set[Action]] for trans in transition_iterator(transitions): incoming_action_by_state[trans.next_state].add(trans.next_action) @@ -189,17 +193,23 @@ def get_memory_from_transitions( # That is to say that the opponent could do anything for out_action in all_actions: # More recent in action history - starting_node = Memit(trans.next_action, trans.next_state, out_action) + starting_node = Memit( + trans.next_action, trans.next_state, out_action + ) # All incoming paths to current state for in_action in incoming_action_by_state[trans.state]: # Less recent in action history - ending_node = Memit(in_action, trans.state, trans.last_opponent_action) + ending_node = Memit( + in_action, trans.state, trans.last_opponent_action + ) memit_edges[starting_node].add(ending_node) all_memits = list(memit_edges.keys()) pair_nodes = set() - pair_edges = defaultdict(set) # type: DefaultDict[MemitPair, Set[MemitPair]] + pair_edges = defaultdict( + set + ) # type: DefaultDict[MemitPair, Set[MemitPair]] # Loop through all pairs of memits. for x, y in [(x, y) for x in all_memits for y in all_memits]: if x == y and x.state == y.state: @@ -226,7 +236,9 @@ def get_memory_from_transitions( next_action_by_memit = dict() for trans in transition_iterator(transitions): for in_action in incoming_action_by_state[trans.state]: - memit_key = Memit(in_action, trans.state, trans.last_opponent_action) + memit_key = Memit( + in_action, trans.state, trans.last_opponent_action + ) next_action_by_memit[memit_key] = trans.next_action # Calculate the longest path. @@ -251,3 +263,4 @@ def get_memory_from_transitions( if len(next_action_set) == 1: return 0 return 1 + diff --git a/axelrod/evolvable_player.py b/axelrod/evolvable_player.py index 2c45b070e..e80da1c69 100644 --- a/axelrod/evolvable_player.py +++ b/axelrod/evolvable_player.py @@ -7,7 +7,6 @@ class InsufficientParametersError(Exception): """Error indicating that insufficient parameters were specified to initialize an Evolvable Player.""" - def __init__(self, *args): super().__init__(*args) @@ -39,7 +38,7 @@ def create_new(self, **kwargs): def serialize_parameters(self): """Serialize parameters.""" pickled = dumps(self.init_kwargs) # bytes - s = base64.b64encode(pickled).decode("utf8") # string + s = base64.b64encode(pickled).decode('utf8') # string return s @classmethod diff --git a/axelrod/graph.py b/axelrod/graph.py index 48308a656..9f41bde4d 100644 --- a/axelrod/graph.py +++ b/axelrod/graph.py @@ -155,7 +155,8 @@ def attached_complete_graphs(length, loops=True, directed=False): for cluster in range(2): for i in range(length): for j in range(i + 1, length): - edges.append(("{}:{}".format(cluster, i), "{}:{}".format(cluster, j))) + edges.append(("{}:{}".format(cluster, i), + "{}:{}".format(cluster, j))) # Attach at one node edges.append(("0:0", "1:0")) graph = Graph(directed=directed, edges=edges) diff --git a/axelrod/moran.py b/axelrod/moran.py index c1b356f53..1c0bdc487 100644 --- a/axelrod/moran.py +++ b/axelrod/moran.py @@ -57,7 +57,7 @@ def __init__( reproduction_graph: Graph = None, fitness_transformation: Callable = None, mutation_method="transition", - stop_on_fixation=True, + stop_on_fixation=True ) -> None: """ An agent based Moran process class. In each round, each player plays a @@ -193,9 +193,7 @@ def mutate(self, index: int) -> Player: if self.mutation_method == "atomic": if not issubclass(self.players[index].__class__, EvolvablePlayer): - raise TypeError( - "Player is not evolvable. Use a subclass of EvolvablePlayer." - ) + raise TypeError("Player is not evolvable. Use a subclass of EvolvablePlayer.") return self.players[index].mutate() # Assuming mutation_method == "transition" diff --git a/axelrod/strategies/adaptor.py b/axelrod/strategies/adaptor.py index 62407d60a..2648b2704 100644 --- a/axelrod/strategies/adaptor.py +++ b/axelrod/strategies/adaptor.py @@ -39,13 +39,12 @@ class AbstractAdaptor(Player): "manipulates_state": False, } - def __init__( - self, delta: Dict[Tuple[Action, Action], float], perr: float = 0.01 - ) -> None: + def __init__(self, delta: Dict[Tuple[Action, Action], float], + perr: float = 0.01) -> None: super().__init__() self.perr = perr self.delta = delta - self.s = 0.0 + self.s = 0. def strategy(self, opponent: Player) -> Action: if self.history: @@ -55,8 +54,7 @@ def strategy(self, opponent: Player) -> Action: # Compute probability of Cooperation p = self.perr + (1.0 - 2 * self.perr) * ( - heaviside(self.s + 1, 1) - heaviside(self.s - 1, 1) - ) + heaviside(self.s + 1, 1) - heaviside(self.s - 1, 1)) # Draw action action = random_choice(p) return action @@ -76,10 +74,10 @@ class AdaptorBrief(AbstractAdaptor): def __init__(self) -> None: delta = { - (C, C): 0.0, # R + (C, C): 0., # R (C, D): -1.001505, # S - (D, C): 0.992107, # T - (D, D): -0.638734, # P + (D, C): 0.992107, # T + (D, D): -0.638734 # P } super().__init__(delta=delta) @@ -98,9 +96,9 @@ class AdaptorLong(AbstractAdaptor): def __init__(self) -> None: delta = { - (C, C): 0.0, # R + (C, C): 0., # R (C, D): 1.888159, # S (D, C): 1.858883, # T - (D, D): -0.995703, # P + (D, D): -0.995703 # P } super().__init__(delta=delta) diff --git a/axelrod/strategies/ann.py b/axelrod/strategies/ann.py index a5c9bd6f5..2d3a1bc85 100644 --- a/axelrod/strategies/ann.py +++ b/axelrod/strategies/ann.py @@ -3,11 +3,7 @@ import numpy.random as random from axelrod.action import Action from axelrod.load_data_ import load_weights -from axelrod.evolvable_player import ( - EvolvablePlayer, - InsufficientParametersError, - crossover_lists, -) +from axelrod.evolvable_player import EvolvablePlayer, InsufficientParametersError, crossover_lists from axelrod.player import Player @@ -195,7 +191,8 @@ class ANN(Player): } def __init__( - self, num_features: int, num_hidden: int, weights: List[float] = None + self, num_features: int, num_hidden: int, + weights: List[float] = None ) -> None: super().__init__() self.num_features = num_features @@ -225,28 +222,20 @@ def strategy(self, opponent: Player) -> Action: class EvolvableANN(ANN, EvolvablePlayer): """Evolvable version of ANN.""" - name = "EvolvableANN" def __init__( - self, - num_features: int, - num_hidden: int, + self, num_features: int, num_hidden: int, weights: List[float] = None, mutation_probability: float = None, mutation_distance: int = 5, ) -> None: - ( - num_features, - num_hidden, - weights, - mutation_probability, - ) = self._normalize_parameters( - num_features, num_hidden, weights, mutation_probability - ) - ANN.__init__( - self, num_features=num_features, num_hidden=num_hidden, weights=weights - ) + num_features, num_hidden, weights, mutation_probability = self._normalize_parameters( + num_features, num_hidden, weights, mutation_probability) + ANN.__init__(self, + num_features=num_features, + num_hidden=num_hidden, + weights=weights) EvolvablePlayer.__init__(self) self.mutation_probability = mutation_probability self.mutation_distance = mutation_distance @@ -254,28 +243,22 @@ def __init__( num_features=num_features, num_hidden=num_hidden, weights=weights, - mutation_probability=mutation_probability, - ) + mutation_probability=mutation_probability) @classmethod - def _normalize_parameters( - cls, num_features=None, num_hidden=None, weights=None, mutation_probability=None - ): + def _normalize_parameters(cls, num_features=None, num_hidden=None, weights=None, mutation_probability=None): if not (num_features and num_hidden): - raise InsufficientParametersError( - "Insufficient Parameters to instantiate EvolvableANN" - ) + raise InsufficientParametersError("Insufficient Parameters to instantiate EvolvableANN") size = num_weights(num_features, num_hidden) if not weights: weights = [random.uniform(-1, 1) for _ in range(size)] if mutation_probability is None: - mutation_probability = 10.0 / size + mutation_probability = 10. / size return num_features, num_hidden, weights, mutation_probability @staticmethod - def mutate_weights( - weights, num_features, num_hidden, mutation_probability, mutation_distance - ): + def mutate_weights(weights, num_features, num_hidden, mutation_probability, + mutation_distance): size = num_weights(num_features, num_hidden) randoms = random.random(size) for i, r in enumerate(randoms): @@ -286,12 +269,8 @@ def mutate_weights( def mutate(self): weights = self.mutate_weights( - self.weights, - self.num_features, - self.num_hidden, - self.mutation_probability, - self.mutation_distance, - ) + self.weights, self.num_features, self.num_hidden, + self.mutation_probability, self.mutation_distance) return self.create_new(weights=weights) def crossover(self, other): @@ -319,8 +298,9 @@ class EvolvedANN(ANN): def __init__(self) -> None: num_features, num_hidden, weights = nn_weights["Evolved ANN"] super().__init__( - num_features=num_features, num_hidden=num_hidden, weights=weights - ) + num_features=num_features, + num_hidden=num_hidden, + weights=weights) class EvolvedANN5(ANN): @@ -341,8 +321,9 @@ class EvolvedANN5(ANN): def __init__(self) -> None: num_features, num_hidden, weights = nn_weights["Evolved ANN 5"] super().__init__( - num_features=num_features, num_hidden=num_hidden, weights=weights - ) + num_features=num_features, + num_hidden=num_hidden, + weights=weights) class EvolvedANNNoise05(ANN): @@ -363,5 +344,7 @@ class EvolvedANNNoise05(ANN): def __init__(self) -> None: num_features, num_hidden, weights = nn_weights["Evolved ANN 5 Noise 05"] super().__init__( - num_features=num_features, num_hidden=num_hidden, weights=weights - ) + num_features=num_features, + num_hidden=num_hidden, + weights=weights) + diff --git a/axelrod/strategies/axelrod_first.py b/axelrod/strategies/axelrod_first.py index 8aa61a727..f9dab0b94 100644 --- a/axelrod/strategies/axelrod_first.py +++ b/axelrod/strategies/axelrod_first.py @@ -69,7 +69,7 @@ def strategy(self, opponent: Player) -> Action: opponent ever plays D.""" if len(self.history) < self._rounds_to_cooperate: return C - if opponent.defections > 0: #  Implement Grudger + if opponent.defections > 0: # Implement Grudger return D return C @@ -266,14 +266,12 @@ def strategy(self, opponent: Player) -> Action: # Adding 1 to cooperations for assumption that first opponent move # being a response to a cooperation. See docstring for more # information. - alpha = self.number_opponent_cooperations_in_response_to_C / ( - self.cooperations + 1 - ) + alpha = (self.number_opponent_cooperations_in_response_to_C / + (self.cooperations + 1)) # Adding 2 to defections on the assumption that the first two # moves are defections, which may not be true in a noisy match - beta = self.number_opponent_cooperations_in_response_to_D / max( - self.defections, 2 - ) + beta = (self.number_opponent_cooperations_in_response_to_D / + max(self.defections, 2)) R, P, S, T = self.match_attributes["game"].RPST() expected_value_of_cooperating = alpha * R + (1 - alpha) * S @@ -442,13 +440,10 @@ def strategy(self, opponent: Player) -> Action: if self.opponent_is_random: return D - if ( - all( - opponent.history[i] == self.history[i - 1] - for i in range(1, len(self.history)) - ) - or opponent.history == self.history - ): + if all( + opponent.history[i] == self.history[i - 1] + for i in range(1, len(self.history)) + ) or opponent.history == self.history: # Check if opponent plays Tit for Tat or a clone of itself. if opponent.history[-1] == D: return D @@ -490,7 +485,6 @@ class FirstByGrofman(Player): "manipulates_source": False, "manipulates_state": False, } - def strategy(self, opponent: Player) -> Action: if len(self.history) == 0 or self.history[-1] == opponent.history[-1]: return C @@ -594,27 +588,7 @@ class FirstByNydegger(Player): } def __init__(self) -> None: - self.As = [ - 1, - 6, - 7, - 17, - 22, - 23, - 26, - 29, - 30, - 31, - 33, - 38, - 39, - 45, - 49, - 54, - 55, - 58, - 61, - ] + self.As = [1, 6, 7, 17, 22, 23, 26, 29, 30, 31, 33, 38, 39, 45, 49, 54, 55, 58, 61] self.score_map = {(C, C): 0, (C, D): 2, (D, C): 1, (D, D): 3} super().__init__() @@ -1029,10 +1003,8 @@ def strategy(self, opponent: Player) -> Action: std_deviation = (N ** (1 / 2)) / 2 lower = N / 2 - 3 * std_deviation upper = N / 2 + 3 * std_deviation - if ( - self.remembered_number_of_opponent_defectioons <= lower - or self.remembered_number_of_opponent_defectioons >= upper - ): + if (self.remembered_number_of_opponent_defectioons <= lower or + self.remembered_number_of_opponent_defectioons >= upper): # Opponent deserves a fresh start self.last_fresh_start = current_round self._fresh_start() diff --git a/axelrod/strategies/axelrod_second.py b/axelrod/strategies/axelrod_second.py index 1125c6804..50e4e18ee 100644 --- a/axelrod/strategies/axelrod_second.py +++ b/axelrod/strategies/axelrod_second.py @@ -61,7 +61,6 @@ def strategy(self, opponent: Player) -> Action: return D return C - class SecondByEatherley(Player): """ Strategy submitted to Axelrod's second tournament by Graham Eatherley. @@ -2127,7 +2126,6 @@ def strategy(self, opponent: Player) -> Action: # Calculate the probability that the opponent cooperated last turn given # what we know two turns ago. - prob_coop = ( - self.opp_c_after_x[us_two_turns_ago] / self.total_num_of_x[us_two_turns_ago] - ) + prob_coop = self.opp_c_after_x[us_two_turns_ago] / self.total_num_of_x[ + us_two_turns_ago] return random_choice(prob_coop) diff --git a/axelrod/strategies/calculator.py b/axelrod/strategies/calculator.py index eaec5e421..8ac9b59d0 100644 --- a/axelrod/strategies/calculator.py +++ b/axelrod/strategies/calculator.py @@ -36,7 +36,8 @@ def __init__(self) -> None: def strategy(self, opponent: Player) -> Action: turn = len(self.history) if turn > 0: - self.joss_instance.history.append(self.history[-1], opponent.history[-1]) + self.joss_instance.history.append(self.history[-1], + opponent.history[-1]) if turn == 20: self.cycle = detect_cycle(opponent.history) return self.extended_strategy(opponent) diff --git a/axelrod/strategies/cycler.py b/axelrod/strategies/cycler.py index 37abecac2..509141717 100644 --- a/axelrod/strategies/cycler.py +++ b/axelrod/strategies/cycler.py @@ -4,11 +4,7 @@ from typing import List, Tuple from axelrod.action import Action, actions_to_str, str_to_actions -from axelrod.evolvable_player import ( - EvolvablePlayer, - InsufficientParametersError, - crossover_lists, -) +from axelrod.evolvable_player import EvolvablePlayer, InsufficientParametersError, crossover_lists from axelrod.player import Player C, D = Action.C, Action.D @@ -113,14 +109,16 @@ def __init__( cycle: str = None, cycle_length: int = None, mutation_probability: float = 0.2, - mutation_potency: int = 1, + mutation_potency: int = 1 ) -> None: cycle, cycle_length = self._normalize_parameters(cycle, cycle_length) # The following __init__ sets self.cycle = cycle Cycler.__init__(self, cycle=cycle) EvolvablePlayer.__init__(self) # Overwrite init_kwargs in the case that we generated a new cycle from cycle_length - self.overwrite_init_kwargs(cycle=cycle, cycle_length=cycle_length) + self.overwrite_init_kwargs( + cycle=cycle, + cycle_length=cycle_length) self.mutation_probability = mutation_probability self.mutation_potency = mutation_potency @@ -129,9 +127,7 @@ def _normalize_parameters(cls, cycle=None, cycle_length=None) -> Tuple[str, int] """Compute other parameters from those that may be missing, to ensure proper cloning.""" if not cycle: if not cycle_length: - raise InsufficientParametersError( - "Insufficient Parameters to instantiate EvolvableCycler" - ) + raise InsufficientParametersError("Insufficient Parameters to instantiate EvolvableCycler") cycle = cls._generate_random_cycle(cycle_length) cycle_length = len(cycle) return cycle, cycle_length @@ -151,9 +147,7 @@ def mutate(self) -> EvolvablePlayer: mutated_sequence = list(str_to_actions(self.cycle)) for _ in range(self.mutation_potency): index_to_change = random.randint(0, len(mutated_sequence) - 1) - mutated_sequence[index_to_change] = mutated_sequence[ - index_to_change - ].flip() + mutated_sequence[index_to_change] = mutated_sequence[index_to_change].flip() cycle = actions_to_str(mutated_sequence) else: cycle = self.cycle diff --git a/axelrod/strategies/finite_state_machines.py b/axelrod/strategies/finite_state_machines.py index 59cdad38b..e7bdd7f63 100644 --- a/axelrod/strategies/finite_state_machines.py +++ b/axelrod/strategies/finite_state_machines.py @@ -4,11 +4,7 @@ import numpy.random as random from numpy.random import choice from axelrod.action import Action -from axelrod.evolvable_player import ( - EvolvablePlayer, - InsufficientParametersError, - copy_lists, -) +from axelrod.evolvable_player import EvolvablePlayer, InsufficientParametersError, copy_lists from axelrod.player import Player C, D = Action.C, Action.D @@ -42,7 +38,9 @@ def __init__(self, transitions: tuple, initial_state: int) -> None: self._raise_error_for_bad_input() def _raise_error_for_bad_input(self): - callable_states = set(pair[0] for pair in self._state_transitions.values()) + callable_states = set( + pair[0] for pair in self._state_transitions.values() + ) callable_states.add(self._state) for state in callable_states: self._raise_error_for_bad_state(state) @@ -113,7 +111,7 @@ def __init__( self, transitions: Tuple[Transition, ...] = ((1, C, 1, C), (1, D, 1, D)), initial_state: int = 1, - initial_action: Action = C, + initial_action: Action = C ) -> None: super().__init__() self.initial_state = initial_state @@ -152,33 +150,23 @@ def __init__( ) -> None: """If transitions, initial_state, and initial_action are None then generate random parameters using num_states.""" - ( - transitions, - initial_state, - initial_action, - num_states, - ) = self._normalize_parameters( - transitions, initial_state, initial_action, num_states - ) + transitions, initial_state, initial_action, num_states = self._normalize_parameters( + transitions, initial_state, initial_action, num_states) FSMPlayer.__init__( self, transitions=transitions, initial_state=initial_state, - initial_action=initial_action, - ) + initial_action=initial_action) EvolvablePlayer.__init__(self) self.mutation_probability = mutation_probability self.overwrite_init_kwargs( transitions=transitions, initial_state=initial_state, initial_action=initial_action, - num_states=self.num_states, - ) + num_states=self.num_states) @classmethod - def normalize_transitions( - cls, transitions: Sequence[Sequence] - ) -> Tuple[Tuple[Any, ...], ...]: + def normalize_transitions(cls, transitions: Sequence[Sequence]) -> Tuple[Tuple[Any, ...], ...]: """Translate a list of lists to a tuple of tuples.""" normalized = [] for t in transitions: @@ -186,22 +174,11 @@ def normalize_transitions( return tuple(normalized) @classmethod - def _normalize_parameters( - cls, - transitions: Tuple = None, - initial_state: int = None, - initial_action: Action = None, - num_states: int = None, - ) -> Tuple[Tuple, int, Action, int]: - if not ( - (transitions is not None) - and (initial_state is not None) - and (initial_action is not None) - ): + def _normalize_parameters(cls, transitions: Tuple = None, initial_state: int = None, initial_action: Action = None, + num_states: int = None) -> Tuple[Tuple, int, Action, int]: + if not ((transitions is not None) and (initial_state is not None) and (initial_action is not None)): if not num_states: - raise InsufficientParametersError( - "Insufficient Parameters to instantiate EvolvableFSMPlayer" - ) + raise InsufficientParametersError("Insufficient Parameters to instantiate EvolvableFSMPlayer") transitions, initial_state, initial_action = cls.random_params(num_states) transitions = cls.normalize_transitions(transitions) num_states = len(transitions) // 2 @@ -212,9 +189,7 @@ def num_states(self) -> int: return self.fsm.num_states() @classmethod - def random_params( - cls, num_states: int - ) -> Tuple[Tuple[Transition, ...], int, Action]: + def random_params(cls, num_states: int) -> Tuple[Tuple[Transition, ...], int, Action]: rows = [] for j in range(num_states): for action in actions: @@ -255,9 +230,7 @@ def mutate(self): if random.random() < self.mutation_probability / (10 * self.num_states): initial_state = randrange(self.num_states) try: - transitions = self.mutate_rows( - self.fsm.transitions(), self.mutation_probability - ) + transitions = self.mutate_rows(self.fsm.transitions(), self.mutation_probability) self.fsm = SimpleFSM(transitions, self.initial_state) except ValueError: # If the FSM is malformed, try again. @@ -279,9 +252,7 @@ def crossover_rows(rows1, rows2): def crossover(self, other): if other.__class__ != self.__class__: raise TypeError("Crossover must be between the same player classes.") - transitions = self.crossover_rows( - self.fsm.transitions(), other.fsm.transitions() - ) + transitions = self.crossover_rows(self.fsm.transitions(), other.fsm.transitions()) transitions = self.normalize_transitions(transitions) return self.create_new(transitions=transitions) @@ -299,26 +270,22 @@ def receive_vector(self, vector): Finally, a probability to determine the player's first move. """ num_states = self.fsm.num_states() - state_scale = vector[: num_states * 2] + state_scale = vector[:num_states * 2] next_states = [int(s * (num_states - 1)) for s in state_scale] - actions = vector[num_states * 2 : -1] + actions = vector[num_states * 2: -1] self.initial_action = C if round(vector[-1]) == 0 else D self.initial_state = 1 transitions = [] - for i, (initial_state, action) in enumerate( - itertools.product(range(num_states), [C, D]) - ): + for i, (initial_state, action) in enumerate(itertools.product(range(num_states), [C, D])): next_action = C if round(actions[i]) == 0 else D transitions.append([initial_state, action, next_states[i], next_action]) transitions = self.normalize_transitions(transitions) self.fsm = SimpleFSM(transitions, self.initial_state) - self.overwrite_init_kwargs( - transitions=transitions, - initial_state=self.initial_state, - initial_action=self.initial_action, - ) + self.overwrite_init_kwargs(transitions=transitions, + initial_state=self.initial_state, + initial_action=self.initial_action) def create_vector_bounds(self): """Creates the bounds for the decision variables.""" @@ -361,7 +328,9 @@ def __init__(self) -> None: (3, D, 1, D), ) - super().__init__(transitions=transitions, initial_state=1, initial_action=D) + super().__init__( + transitions=transitions, initial_state=1, initial_action=D + ) class Fortress4(FSMPlayer): @@ -400,7 +369,9 @@ def __init__(self) -> None: (4, D, 1, D), ) - super().__init__(transitions=transitions, initial_state=1, initial_action=D) + super().__init__( + transitions=transitions, initial_state=1, initial_action=D + ) class Predator(FSMPlayer): @@ -446,7 +417,9 @@ def __init__(self) -> None: (8, D, 6, D), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) class Pun1(FSMPlayer): @@ -471,7 +444,9 @@ class Pun1(FSMPlayer): def __init__(self) -> None: transitions = ((1, C, 2, C), (1, D, 2, C), (2, C, 1, C), (2, D, 1, D)) - super().__init__(transitions=transitions, initial_state=1, initial_action=D) + super().__init__( + transitions=transitions, initial_state=1, initial_action=D + ) class Raider(FSMPlayer): @@ -507,7 +482,9 @@ def __init__(self) -> None: (3, D, 1, C), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=D) + super().__init__( + transitions=transitions, initial_state=0, initial_action=D + ) class Ripoff(FSMPlayer): @@ -540,7 +517,9 @@ def __init__(self) -> None: (3, D, 3, D), ) - super().__init__(transitions=transitions, initial_state=1, initial_action=D) + super().__init__( + transitions=transitions, initial_state=1, initial_action=D + ) class UsuallyCooperates(FSMPlayer): @@ -566,7 +545,9 @@ class UsuallyCooperates(FSMPlayer): def __init__(self) -> None: transitions = ((1, C, 1, C), (1, D, 2, C), (2, C, 1, D), (2, D, 1, C)) - super().__init__(transitions=transitions, initial_state=1, initial_action=C) + super().__init__( + transitions=transitions, initial_state=1, initial_action=C + ) class UsuallyDefects(FSMPlayer): @@ -592,7 +573,9 @@ class UsuallyDefects(FSMPlayer): def __init__(self) -> None: transitions = ((1, C, 2, D), (1, D, 1, D), (2, C, 1, D), (2, D, 1, C)) - super().__init__(transitions=transitions, initial_state=1, initial_action=D) + super().__init__( + transitions=transitions, initial_state=1, initial_action=D + ) class SolutionB1(FSMPlayer): @@ -625,7 +608,9 @@ def __init__(self) -> None: (3, D, 3, C), ) - super().__init__(transitions=transitions, initial_state=1, initial_action=D) + super().__init__( + transitions=transitions, initial_state=1, initial_action=D + ) class SolutionB5(FSMPlayer): @@ -665,7 +650,9 @@ def __init__(self) -> None: (6, D, 5, D), ) - super().__init__(transitions=transitions, initial_state=1, initial_action=D) + super().__init__( + transitions=transitions, initial_state=1, initial_action=D + ) class Thumper(FSMPlayer): @@ -691,7 +678,9 @@ class Thumper(FSMPlayer): def __init__(self) -> None: transitions = ((1, C, 1, C), (1, D, 2, D), (2, C, 1, D), (2, D, 1, D)) - super().__init__(transitions=transitions, initial_state=1, initial_action=C) + super().__init__( + transitions=transitions, initial_state=1, initial_action=C + ) class EvolvedFSM4(FSMPlayer): @@ -726,7 +715,9 @@ def __init__(self) -> None: (3, D, 1, D), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) class EvolvedFSM16(FSMPlayer): @@ -782,7 +773,9 @@ def __init__(self) -> None: (15, D, 2, C), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) class EvolvedFSM16Noise05(FSMPlayer): @@ -838,7 +831,9 @@ def __init__(self) -> None: (15, D, 11, C), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) # Strategies trained with Moran process objectives @@ -900,7 +895,9 @@ def __init__(self) -> None: (15, D, 5, C), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) class TF2(FSMPlayer): @@ -955,7 +952,9 @@ def __init__(self) -> None: (15, D, 11, D), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) class TF3(FSMPlayer): @@ -998,4 +997,6 @@ def __init__(self) -> None: (7, D, 5, C), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) diff --git a/axelrod/strategies/gambler.py b/axelrod/strategies/gambler.py index 847db5806..f127ce0f4 100644 --- a/axelrod/strategies/gambler.py +++ b/axelrod/strategies/gambler.py @@ -13,13 +13,7 @@ from axelrod.random_ import random_choice -from .lookerup import ( - EvolvableLookerUp, - LookupTable, - LookerUp, - Plays, - create_lookup_table_keys, -) +from .lookerup import EvolvableLookerUp, LookupTable, LookerUp, Plays, create_lookup_table_keys C, D = Action.C, Action.D tables = load_pso_tables("pso_gambler.csv", directory="data") @@ -62,7 +56,7 @@ def __init__( initial_actions: tuple = None, pattern: Any = None, # pattern is str or tuple of Actions. parameters: Plays = None, - mutation_probability: float = None, + mutation_probability: float = None ) -> None: EvolvableLookerUp.__init__( self, @@ -70,7 +64,7 @@ def __init__( initial_actions=initial_actions, pattern=pattern, parameters=parameters, - mutation_probability=mutation_probability, + mutation_probability=mutation_probability ) self.pattern = list(self.pattern) Gambler.__init__( @@ -78,7 +72,7 @@ def __init__( lookup_dict=self.lookup_dict, initial_actions=self.initial_actions, pattern=self.pattern, - parameters=self.parameters, + parameters=self.parameters ) self.overwrite_init_kwargs( lookup_dict=self.lookup_dict, @@ -109,9 +103,7 @@ def receive_vector(self, vector): """Receives a vector and updates the player's pattern. Ignores extra parameters.""" self.pattern = vector self_depth, op_depth, op_openings_depth = self.parameters - self._lookup = LookupTable.from_pattern( - self.pattern, self_depth, op_depth, op_openings_depth - ) + self._lookup = LookupTable.from_pattern(self.pattern, self_depth, op_depth, op_openings_depth) def create_vector_bounds(self): """Creates the bounds for the decision variables. Ignores extra parameters.""" diff --git a/axelrod/strategies/grudger.py b/axelrod/strategies/grudger.py index 1473b8def..61215bb9a 100644 --- a/axelrod/strategies/grudger.py +++ b/axelrod/strategies/grudger.py @@ -23,7 +23,7 @@ class Grudger(Player): name = "Grudger" classifier = { - "memory_depth": float("inf"), + "memory_depth": float('inf'), "stochastic": False, "makes_use_of": set(), "long_run_time": False, diff --git a/axelrod/strategies/hmm.py b/axelrod/strategies/hmm.py index b88d2b6ff..8ae2ed811 100644 --- a/axelrod/strategies/hmm.py +++ b/axelrod/strategies/hmm.py @@ -3,12 +3,7 @@ from numpy.random import choice from axelrod.action import Action -from axelrod.evolvable_player import ( - EvolvablePlayer, - InsufficientParametersError, - copy_lists, - crossover_lists, -) +from axelrod.evolvable_player import EvolvablePlayer, InsufficientParametersError, copy_lists, crossover_lists from axelrod.player import Player from axelrod.random_ import random_choice, random_vector @@ -152,7 +147,7 @@ def __init__( transitions_D=None, emission_probabilities=None, initial_state=0, - initial_action=C, + initial_action=C ) -> None: super().__init__() if not transitions_C: @@ -163,10 +158,7 @@ def __init__( self.initial_state = initial_state self.initial_action = initial_action self.hmm = SimpleHMM( - copy_lists(transitions_C), - copy_lists(transitions_D), - list(emission_probabilities), - initial_state, + copy_lists(transitions_C), copy_lists(transitions_D), list(emission_probabilities), initial_state ) assert self.hmm.is_well_formed() self.state = self.hmm.state @@ -197,7 +189,6 @@ def strategy(self, opponent: Player) -> Action: class EvolvableHMMPlayer(HMMPlayer, EvolvablePlayer): """Evolvable version of HMMPlayer.""" - name = "EvolvableHMMPlayer" def __init__( @@ -208,34 +199,17 @@ def __init__( initial_state=0, initial_action=C, num_states=None, - mutation_probability=None, + mutation_probability=None ) -> None: - ( - transitions_C, - transitions_D, - emission_probabilities, - initial_state, - initial_action, - num_states, - mutation_probability, - ) = self._normalize_parameters( - transitions_C, - transitions_D, - emission_probabilities, - initial_state, - initial_action, - num_states, - mutation_probability, - ) + transitions_C, transitions_D, emission_probabilities, initial_state, initial_action, num_states, mutation_probability = self._normalize_parameters( + transitions_C, transitions_D, emission_probabilities, initial_state, initial_action, num_states, mutation_probability) self.mutation_probability = mutation_probability - HMMPlayer.__init__( - self, - transitions_C=transitions_C, - transitions_D=transitions_D, - emission_probabilities=emission_probabilities, - initial_state=initial_state, - initial_action=initial_action, - ) + HMMPlayer.__init__(self, + transitions_C=transitions_C, + transitions_D=transitions_D, + emission_probabilities=emission_probabilities, + initial_state=initial_state, + initial_action=initial_action) EvolvablePlayer.__init__(self) self.overwrite_init_kwargs( transitions_C=transitions_C, @@ -244,38 +218,17 @@ def __init__( initial_state=initial_state, initial_action=initial_action, num_states=num_states, - mutation_probability=mutation_probability, + mutation_probability=mutation_probability ) @classmethod - def _normalize_parameters( - cls, - transitions_C=None, - transitions_D=None, - emission_probabilities=None, - initial_state=None, - initial_action=None, - num_states=None, - mutation_probability=None, - ): - if not ( - transitions_C - and transitions_D - and emission_probabilities - and (initial_state is not None) - and (initial_action is not None) - ): + def _normalize_parameters(cls, transitions_C=None, transitions_D=None, emission_probabilities=None, + initial_state=None, initial_action=None, num_states=None, mutation_probability=None): + if not (transitions_C and transitions_D and emission_probabilities and (initial_state is not None) and (initial_action is not None)): if not num_states: - raise InsufficientParametersError( - "Insufficient Parameters to instantiate EvolvableHMMPlayer" - ) - ( - transitions_C, - transitions_D, - emission_probabilities, - initial_state, - initial_action, - ) = cls.random_params(num_states) + raise InsufficientParametersError("Insufficient Parameters to instantiate EvolvableHMMPlayer") + transitions_C, transitions_D, emission_probabilities, initial_state, initial_action = cls.random_params( + num_states) # Normalize types of various matrices for m in [transitions_C, transitions_D]: for i in range(len(m)): @@ -286,15 +239,7 @@ def _normalize_parameters( mutation_probability = 10 / (num_states ** 2) else: mutation_probability = mutation_probability - return ( - transitions_C, - transitions_D, - emission_probabilities, - initial_state, - initial_action, - num_states, - mutation_probability, - ) + return transitions_C, transitions_D, emission_probabilities, initial_state, initial_action, num_states, mutation_probability @classmethod def random_params(cls, num_states): @@ -307,13 +252,7 @@ def random_params(cls, num_states): emission_probabilities.append(random.random()) initial_state = randrange(num_states) initial_action = C - return ( - transitions_C, - transitions_D, - emission_probabilities, - initial_state, - initial_action, - ) + return transitions_C, transitions_D, emission_probabilities, initial_state, initial_action @property def num_states(self): @@ -328,14 +267,11 @@ def mutate_rows(rows, mutation_probability): def mutate(self): transitions_C = self.mutate_rows( - self.hmm.transitions_C, self.mutation_probability - ) + self.hmm.transitions_C, self.mutation_probability) transitions_D = self.mutate_rows( - self.hmm.transitions_D, self.mutation_probability - ) + self.hmm.transitions_D, self.mutation_probability) emission_probabilities = mutate_row( - self.hmm.emission_probabilities, self.mutation_probability - ) + self.hmm.emission_probabilities, self.mutation_probability) initial_action = self.initial_action if random.random() < self.mutation_probability / 10: initial_action = self.initial_action.flip() @@ -356,12 +292,11 @@ def crossover(self, other): transitions_C = crossover_lists(self.hmm.transitions_C, other.hmm.transitions_C) transitions_D = crossover_lists(self.hmm.transitions_D, other.hmm.transitions_D) emission_probabilities = crossover_lists( - self.hmm.emission_probabilities, other.hmm.emission_probabilities - ) + self.hmm.emission_probabilities, other.hmm.emission_probabilities) return self.create_new( transitions_C=transitions_C, transitions_D=transitions_D, - emission_probabilities=emission_probabilities, + emission_probabilities=emission_probabilities ) def receive_vector(self, vector): @@ -378,12 +313,12 @@ class with self.num_states. entry is the initial_action. """ - assert len(vector) == 2 * self.num_states ** 2 + self.num_states + 1 + assert(len(vector) == 2 * self.num_states ** 2 + self.num_states + 1) def deserialize(vector): matrix = [] for i in range(self.num_states): - row = vector[self.num_states * i : self.num_states * (i + 1)] + row = vector[self.num_states * i: self.num_states * (i + 1)] row = normalize_vector(row) matrix.append(row) return matrix @@ -396,7 +331,7 @@ def deserialize(vector): deserialize(vector[0:break_tc]), deserialize(vector[break_tc:break_td]), normalize_vector(vector[break_td:break_ep]), - initial_state, + initial_state ) self.initial_action = C if round(vector[-1]) == 0 else D self.initial_state = initial_state diff --git a/axelrod/strategies/lookerup.py b/axelrod/strategies/lookerup.py index 66a71fbf6..b66d06293 100644 --- a/axelrod/strategies/lookerup.py +++ b/axelrod/strategies/lookerup.py @@ -6,11 +6,7 @@ from numpy.random import choice from axelrod.action import Action, actions_to_str, str_to_actions -from axelrod.evolvable_player import ( - EvolvablePlayer, - InsufficientParametersError, - crossover_dictionaries, -) +from axelrod.evolvable_player import EvolvablePlayer, InsufficientParametersError, crossover_dictionaries from axelrod.player import Player @@ -323,7 +319,7 @@ def __init__( lookup_dict: dict = None, initial_actions: tuple = None, pattern: Any = None, # pattern is str or tuple of Action's. - parameters: Plays = None, + parameters: Plays = None ) -> None: super().__init__() @@ -408,15 +404,9 @@ def __init__( initial_actions: tuple = None, pattern: Any = None, # pattern is str or tuple of Action's. parameters: Plays = None, - mutation_probability: float = None, + mutation_probability: float = None ) -> None: - ( - lookup_dict, - initial_actions, - pattern, - parameters, - mutation_probability, - ) = self._normalize_parameters( + lookup_dict, initial_actions, pattern, parameters, mutation_probability = self._normalize_parameters( lookup_dict, initial_actions, pattern, parameters, mutation_probability ) LookerUp.__init__( @@ -437,24 +427,14 @@ def __init__( ) @classmethod - def _normalize_parameters( - cls, - lookup_dict=None, - initial_actions=None, - pattern=None, - parameters=None, - mutation_probability=None, - ): + def _normalize_parameters(cls, lookup_dict=None, initial_actions=None, pattern=None, parameters=None, + mutation_probability=None): if lookup_dict and initial_actions: # Compute the associated pattern and parameters # Map the table keys to namedTuple Plays lookup_table = cls._get_lookup_table(lookup_dict, pattern, parameters) lookup_dict = lookup_table.dictionary - parameters = ( - lookup_table.player_depth, - lookup_table.op_depth, - lookup_table.op_openings_depth, - ) + parameters = (lookup_table.player_depth, lookup_table.op_depth, lookup_table.op_openings_depth) pattern = tuple(v for k, v in sorted(lookup_dict.items())) elif pattern and parameters and initial_actions: # Compute the associated lookup table @@ -470,9 +450,7 @@ def _normalize_parameters( num_actions = max([plays, op_plays, op_start_plays]) initial_actions = tuple([choice((C, D)) for _ in range(num_actions)]) else: - raise InsufficientParametersError( - "Insufficient Parameters to instantiate EvolvableLookerUp" - ) + raise InsufficientParametersError("Insufficient Parameters to instantiate EvolvableLookerUp") # Normalize pattern if isinstance(pattern, str): pattern = str_to_actions(pattern) @@ -480,7 +458,7 @@ def _normalize_parameters( if mutation_probability is None: plays, op_plays, op_start_plays = parameters keys = create_lookup_table_keys(plays, op_plays, op_start_plays) - mutation_probability = 2.0 / len(keys) + mutation_probability = 2. / len(keys) return lookup_dict, initial_actions, pattern, parameters, mutation_probability @classmethod @@ -517,7 +495,8 @@ def mutate(self): if r < self.mutation_probability: initial_actions[i] = initial_actions[i].flip() return self.create_new( - lookup_dict=lookup_dict, initial_actions=tuple(initial_actions), + lookup_dict=lookup_dict, + initial_actions=tuple(initial_actions), ) def crossover(self, other): diff --git a/axelrod/strategies/prober.py b/axelrod/strategies/prober.py index 79a41971a..96940a1fc 100644 --- a/axelrod/strategies/prober.py +++ b/axelrod/strategies/prober.py @@ -84,7 +84,7 @@ def strategy(self, opponent: Player) -> Action: return self.initial_actions[hist_size] if D not in opponent.history[:init_size]: return D - return opponent.history[-1] # TFT + return opponent.history[-1] # TFT class Prober(Player): diff --git a/axelrod/strategies/revised_downing.py b/axelrod/strategies/revised_downing.py index f3e290fd0..2304af708 100644 --- a/axelrod/strategies/revised_downing.py +++ b/axelrod/strategies/revised_downing.py @@ -7,7 +7,6 @@ C, D = Action.C, Action.D - class RevisedDowning(Player): """ Strategy submitted to Axelrod's second tournament by Leslie Downing. @@ -73,3 +72,4 @@ def strategy(self, opponent: Player) -> Action: else: move = D return move + diff --git a/axelrod/strategies/shortmem.py b/axelrod/strategies/shortmem.py index ae4476cd7..23bf7c523 100644 --- a/axelrod/strategies/shortmem.py +++ b/axelrod/strategies/shortmem.py @@ -22,7 +22,7 @@ class ShortMem(Player): name = "ShortMem" classifier = { - "memory_depth": float("inf"), + "memory_depth": float('inf'), "stochastic": False, "makes_use_of": set(), "long_run_time": False, diff --git a/axelrod/strategy_transformers.py b/axelrod/strategy_transformers.py index a4217746c..6d50d77c2 100644 --- a/axelrod/strategy_transformers.py +++ b/axelrod/strategy_transformers.py @@ -535,7 +535,9 @@ def mixed_wrapper(player, opponent, action, probability, m_player): probability = [probability] # If a probability distribution, players is passed - if isinstance(probability, Iterable) and isinstance(m_player, Iterable): + if isinstance(probability, Iterable) and isinstance( + m_player, Iterable + ): mutate_prob = sum(probability) # Prob of mutation if mutate_prob > 0: # Distribution of choice of mutation: diff --git a/axelrod/tests/property.py b/axelrod/tests/property.py index 78b61a09b..95d08e2b8 100644 --- a/axelrod/tests/property.py +++ b/axelrod/tests/property.py @@ -10,10 +10,7 @@ @composite def strategy_lists( - draw, - strategies=axl.short_run_time_strategies, - min_size=1, - max_size=len(axl.strategies), + draw, strategies=axl.short_run_time_strategies, min_size=1, max_size=len(axl.strategies) ): """ A hypothesis decorator to return a list of strategies @@ -111,9 +108,7 @@ def tournaments( repetitions = draw(integers(min_value=min_repetitions, max_value=max_repetitions)) noise = draw(floats(min_value=min_noise, max_value=max_noise)) - tournament = axl.Tournament( - players, turns=turns, repetitions=repetitions, noise=noise - ) + tournament = axl.Tournament(players, turns=turns, repetitions=repetitions, noise=noise) return tournament diff --git a/axelrod/tests/strategies/test_adaptor.py b/axelrod/tests/strategies/test_adaptor.py index fe112429a..740fdb252 100644 --- a/axelrod/tests/strategies/test_adaptor.py +++ b/axelrod/tests/strategies/test_adaptor.py @@ -25,11 +25,15 @@ class TestAdaptorBrief(TestPlayer): def test_strategy(self): # No error. actions = [(C, C), (C, C), (C, C), (C, C)] - self.versus_test(opponent=axl.AdaptorBrief(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.AdaptorBrief(), expected_actions=actions, seed=0 + ) # Error corrected. actions = [(C, C), (C, D), (D, C), (C, C)] - self.versus_test(opponent=axl.AdaptorBrief(), expected_actions=actions, seed=22) + self.versus_test( + opponent=axl.AdaptorBrief(), expected_actions=actions, seed=22 + ) # Error corrected, example 2 actions = [(D, C), (C, D), (D, C), (C, D), (C, C)] @@ -39,11 +43,15 @@ def test_strategy(self): # Versus Cooperator actions = [(C, C)] * 8 - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=0 + ) # Versus Defector actions = [(C, D), (D, D), (D, D), (D, D), (D, D), (D, D), (D, D)] - self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Defector(), expected_actions=actions, seed=0 + ) class TestAdaptorLong(TestPlayer): @@ -62,16 +70,24 @@ class TestAdaptorLong(TestPlayer): def test_strategy(self): # No error. actions = [(C, C), (C, C), (C, C), (C, C)] - self.versus_test(opponent=axl.AdaptorLong(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.AdaptorLong(), expected_actions=actions, seed=0 + ) # Error corrected. actions = [(C, C), (C, D), (D, D), (C, C), (C, C)] - self.versus_test(opponent=axl.AdaptorLong(), expected_actions=actions, seed=22) + self.versus_test( + opponent=axl.AdaptorLong(), expected_actions=actions, seed=22 + ) # Versus Cooperator actions = [(C, C)] * 8 - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=0 + ) # Versus Defector actions = [(C, D), (D, D), (C, D), (D, D), (D, D), (C, D), (D, D)] - self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Defector(), expected_actions=actions, seed=0 + ) diff --git a/axelrod/tests/strategies/test_ann.py b/axelrod/tests/strategies/test_ann.py index cbfb5e81b..3a63d2131 100644 --- a/axelrod/tests/strategies/test_ann.py +++ b/axelrod/tests/strategies/test_ann.py @@ -19,7 +19,6 @@ class TestSplitWeights(unittest.TestCase): def test_split_weights(self): with self.assertRaises(ValueError): split_weights([0] * 20, 12, 10) - # Doesn't Raise split_weights([0] * 70, 5, 10) split_weights([0] * 12, 10, 1) @@ -101,12 +100,13 @@ class TestEvolvableANN(unittest.TestCase): def test_normalized_parameters(self): # Must specify at least one of cycle or cycle_length self.assertRaises( - InsufficientParametersError, self.player_class._normalize_parameters + InsufficientParametersError, + self.player_class._normalize_parameters ) self.assertRaises( InsufficientParametersError, self.player_class._normalize_parameters, - weights=nn_weights["Evolved ANN 5"][2], + weights=nn_weights["Evolved ANN 5"][2] ) @@ -126,13 +126,16 @@ class TestEvolvableANN3(TestEvolvablePlayer): init_parameters = { "num_features": nn_weights["Evolved ANN 5"][0], "num_hidden": nn_weights["Evolved ANN 5"][1], - "weights": nn_weights["Evolved ANN 5"][2], + "weights": nn_weights["Evolved ANN 5"][2] } # Substitute EvolvableANN as a regular EvolvedANN5. EvolvableANNPlayerWithDefault = PartialClass( - axl.EvolvableANN, num_features=num_features, num_hidden=num_hidden, weights=weights + axl.EvolvableANN, + num_features=num_features, + num_hidden=num_hidden, + weights=weights ) diff --git a/axelrod/tests/strategies/test_apavlov.py b/axelrod/tests/strategies/test_apavlov.py index 7396dbc23..e720dce56 100644 --- a/axelrod/tests/strategies/test_apavlov.py +++ b/axelrod/tests/strategies/test_apavlov.py @@ -37,7 +37,9 @@ def test_strategy(self): actions = [(C, D)] + [(D, D)] * 6 self.versus_test( - axl.Defector(), expected_actions=actions, attrs={"opponent_class": "ALLD"}, + axl.Defector(), + expected_actions=actions, + attrs={"opponent_class": "ALLD"}, ) opponent = axl.MockPlayer(actions=[D, C, D, C, D, C]) @@ -107,7 +109,9 @@ def test_strategy(self): actions = [(C, D)] + [(D, D)] * 9 self.versus_test( - axl.Defector(), expected_actions=actions, attrs={"opponent_class": "ALLD"}, + axl.Defector(), + expected_actions=actions, + attrs={"opponent_class": "ALLD"}, ) opponent = axl.MockPlayer(actions=[C, D, D, D, D, D, D]) diff --git a/axelrod/tests/strategies/test_axelrod_first.py b/axelrod/tests/strategies/test_axelrod_first.py index c5b2cbf7f..35ee2d5f4 100644 --- a/axelrod/tests/strategies/test_axelrod_first.py +++ b/axelrod/tests/strategies/test_axelrod_first.py @@ -168,7 +168,9 @@ def test_strategy(self): # Against defector actions = [(C, D)] + [(D, D)] * 55 # 56 turns - self.versus_test(axl.Defector(), expected_actions=actions, attrs=expected_attrs) + self.versus_test( + axl.Defector(), expected_actions=actions, attrs=expected_attrs + ) # Against cooperator actions = [(C, C)] * 50 + [(D, C)] + [(C, C)] * 5 @@ -567,11 +569,8 @@ def test_strategy(self): # Cooperator Test does noot defect if game length is unknown opponent = axl.Cooperator() actions = [(C, C), (C, C), (C, C), (C, C)] - self.versus_test( - opponent, - expected_actions=actions, - match_attributes={"length": float("inf")}, - ) + self.versus_test(opponent, expected_actions=actions, + match_attributes={"length": float("inf")}) # Defector Test opponent = axl.Defector() diff --git a/axelrod/tests/strategies/test_axelrod_second.py b/axelrod/tests/strategies/test_axelrod_second.py index b889347bc..7c9122d8d 100644 --- a/axelrod/tests/strategies/test_axelrod_second.py +++ b/axelrod/tests/strategies/test_axelrod_second.py @@ -1116,7 +1116,9 @@ def test_strategy(self): # doesn't reset. This logic comes before parity streaks or the turn- # based logic. self.versus_test( - axl.Defector(), expected_actions=actions, attrs={"recorded_defects": 119}, + axl.Defector(), + expected_actions=actions, + attrs={"recorded_defects": 119}, ) # Detect random @@ -1404,7 +1406,9 @@ def test_strategy(self): (D, C), (C, D), ] - self.versus_test(axl.SuspiciousTitForTat(), expected_actions=actions, seed=1) + self.versus_test( + axl.SuspiciousTitForTat(), expected_actions=actions, seed=1 + ) actions = [(C, C), (C, D), (D, C)] + [(D, D), (C, C)] * 3 self.versus_test(axl.Alternator(), expected_actions=actions, seed=2) @@ -1757,19 +1761,29 @@ def test_strategy(self): ) actions = [(C, D), (C, D), (C, D), (C, D)] - self.versus_test(axl.Defector(), expected_actions=actions, attrs={"credit": 1}) + self.versus_test( + axl.Defector(), expected_actions=actions, attrs={"credit": 1} + ) # Defect then reset to 4 actions += [(D, D)] - self.versus_test(axl.Defector(), expected_actions=actions, attrs={"credit": 4}) + self.versus_test( + axl.Defector(), expected_actions=actions, attrs={"credit": 4} + ) # Repeat actions += [(C, D), (D, D)] * 2 - self.versus_test(axl.Defector(), expected_actions=actions, attrs={"credit": 4}) + self.versus_test( + axl.Defector(), expected_actions=actions, attrs={"credit": 4} + ) # With ten turns passed, keep defecting now actions += [(C, D), (D, D)] - self.versus_test(axl.Defector(), expected_actions=actions, attrs={"credit": 0}) + self.versus_test( + axl.Defector(), expected_actions=actions, attrs={"credit": 0} + ) # With ten turns passed, keep defecting now actions += [(D, D)] * 30 - self.versus_test(axl.Defector(), expected_actions=actions, attrs={"credit": -7}) + self.versus_test( + axl.Defector(), expected_actions=actions, attrs={"credit": -7} + ) actions = [(C, D), (C, D), (C, C)] self.versus_test( @@ -1803,7 +1817,6 @@ def test_strategy(self): ) # Still Cooperate, because Defect rate is low - class TestRowsam(TestPlayer): name = "Second by Rowsam" player = axl.SecondByRowsam @@ -1825,16 +1838,12 @@ def test_strategy(self): # Against a Defector should eventually enter Defect mode actions = [(C, D)] * 5 actions += [(D, D), (C, D), (D, D)] # Do a Coop-Def cycle - self.versus_test( - axl.Defector(), expected_actions=actions, attrs={"distrust_points": 5} - ) + self.versus_test(axl.Defector(), expected_actions=actions, attrs={ + "distrust_points": 5}) actions += [(C, D)] * 3 # Continue for now actions += [(D, D)] * 100 # Now Defect mode - self.versus_test( - axl.Defector(), - expected_actions=actions, - attrs={"distrust_points": 10, "mode": "Defect"}, - ) + self.versus_test(axl.Defector(), expected_actions=actions, attrs={ + "distrust_points": 10, "mode": "Defect"}) # Test specific score scenarios # 5 Defects @@ -1842,11 +1851,8 @@ def test_strategy(self): custom_opponent = axl.MockPlayer(actions=opponent_actions) actions = [(C, D)] * 5 actions += [(D, C)] - self.versus_test( - custom_opponent, - expected_actions=actions, - attrs={"distrust_points": 5, "current_score": 0}, - ) + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 5, "current_score": 0}) # 3 Defects opponent_actions = [D] * 3 + [C] * 100 @@ -1854,11 +1860,8 @@ def test_strategy(self): actions = [(C, D)] * 3 actions += [(C, C)] * 2 actions += [(D, C)] - self.versus_test( - custom_opponent, - expected_actions=actions, - attrs={"distrust_points": 3, "current_score": 6}, - ) + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 3, "current_score": 6}) # 2 Defects opponent_actions = [D] * 2 + [C] * 100 @@ -1866,11 +1869,8 @@ def test_strategy(self): actions = [(C, D)] * 2 actions += [(C, C)] * 3 actions += [(D, C)] - self.versus_test( - custom_opponent, - expected_actions=actions, - attrs={"distrust_points": 2, "current_score": 9}, - ) + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 2, "current_score": 9}) # 1 Defect opponent_actions = [D] * 1 + [C] * 100 @@ -1878,11 +1878,8 @@ def test_strategy(self): actions = [(C, D)] * 1 actions += [(C, C)] * 4 actions += [(D, C)] - self.versus_test( - custom_opponent, - expected_actions=actions, - attrs={"distrust_points": 1, "current_score": 12}, - ) + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 1, "current_score": 12}) # Test that some distrust_points wear off. opponent_actions = [D] * 3 + [C] * 100 @@ -1890,38 +1887,27 @@ def test_strategy(self): actions = [(C, D)] * 3 actions += [(C, C)] * 2 actions += [(D, C)] - self.versus_test( - custom_opponent, - expected_actions=actions, - attrs={"distrust_points": 3, "current_score": 6}, - ) + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 3, "current_score": 6}) custom_opponent = axl.MockPlayer(actions=opponent_actions) actions += [(C, C), (D, C)] # Complete Coop-Def cycle actions += [(C, C)] * 3 actions += [(D, C)] - self.versus_test( - custom_opponent, - expected_actions=actions, - attrs={"distrust_points": 4, "current_score": 28}, - ) + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 4, "current_score": 28}) custom_opponent = axl.MockPlayer(actions=opponent_actions) actions += [(C, C), (D, C)] # Complete Coop-Def cycle actions += [(C, C)] * 4 # No defect or cycle this time. - self.versus_test( - custom_opponent, - expected_actions=actions, - attrs={"distrust_points": 3, "current_score": 50}, - ) # One point wears off. + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 3, "current_score": 50}) # One point wears off. custom_opponent = axl.MockPlayer(actions=opponent_actions) actions += [(C, C)] * 18 - self.versus_test( - custom_opponent, expected_actions=actions, attrs={"distrust_points": 2} - ) # Second point wears off + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 2}) # Second point wears off custom_opponent = axl.MockPlayer(actions=opponent_actions) actions += [(C, C)] * 18 - self.versus_test( - custom_opponent, expected_actions=actions, attrs={"distrust_points": 2} - ) # But no more + self.versus_test(custom_opponent, expected_actions=actions, attrs={ + "distrust_points": 2}) # But no more class TestAppold(TestPlayer): @@ -1953,39 +1939,36 @@ def test_strategy(self): # Then defect most of the time, depending on the random number. We # don't defect 100% of the time, because of the way that initialize # opp_c_after_x. - actions += [ - (D, D), - (C, D), - (D, D), - (D, D), # C can never be two moves after a C. - (D, D), - (D, D), - (D, D), - (D, D), - (D, D), - (D, D), - (C, D), - (C, D), - (D, D), - (D, D), - (D, D), - (D, D), - (D, D), - (C, D), - (D, D), - (D, D), - (D, D), - (D, D), - (D, D), - (D, D), - (C, D), - (C, D), - (D, D), - (D, D), - ] - self.versus_test( - opponent, expected_actions=actions, seed=1, attrs={"first_opp_def": True} - ) + actions += [(D, D), + (C, D), + (D, D), + (D, D), # C can never be two moves after a C. + (D, D), + (D, D), + (D, D), + (D, D), + (D, D), + (D, D), + (C, D), + (C, D), + (D, D), + (D, D), + (D, D), + (D, D), + (D, D), + (C, D), + (D, D), + (D, D), + (D, D), + (D, D), + (D, D), + (D, D), + (C, D), + (C, D), + (D, D), + (D, D)] + self.versus_test(opponent, expected_actions=actions, seed=1, + attrs={"first_opp_def": True}) # An opponent who defects for a long time, then tries cooperating opponent_actions = [C] * 30 + [D] + [C] * 10 @@ -2002,60 +1985,51 @@ def test_strategy(self): # First three opponent actions get counted as reactions to C. Fourth # action will get counted on next turn. actions = [(C, D), (C, C), (C, D), (C, C)] - self.versus_test( - opponent, - expected_actions=actions, - attrs={"opp_c_after_x": {C: 1, D: 1}, "total_num_of_x": {C: 3, D: 1}}, - ) + self.versus_test(opponent, expected_actions=actions, + attrs={"opp_c_after_x": {C: 1, D: 1}, + "total_num_of_x": {C: 3, D: 1}}) # Will cooperate 50% of the time actions += [(C, D)] - self.versus_test( - opponent, - expected_actions=actions, - attrs={ - "opp_c_after_x": {C: 2, D: 1}, - "total_num_of_x": {C: 4, D: 1}, - "first_opp_def": False, - }, - seed=100, - ) + self.versus_test(opponent, expected_actions=actions, + attrs={"opp_c_after_x": {C: 2, D: 1}, + "total_num_of_x": {C: 4, D: 1}, + "first_opp_def": False}, seed=100) # Always cooperate, because we forgive the first defect actions += [(C, C)] - self.versus_test( - opponent, expected_actions=actions, attrs={"first_opp_def": True}, seed=100 - ) + self.versus_test(opponent, expected_actions=actions, + attrs={"first_opp_def": True}, seed=100) # Against a random opponent, will respond mostly randomly too. - actions = [ - (C, C), - (C, C), - (C, D), - (C, C), - (C, C), - (C, D), - (C, C), - (C, C), - (C, C), - (D, C), - (C, D), - (D, D), - (C, D), - (C, D), - (C, C), - (C, C), - (D, C), - (C, D), - (D, D), - (C, C), - (C, D), - (C, C), - (C, C), - (C, D), - (D, C), - (C, D), - (D, D), - (C, D), - (C, C), - (D, C), - ] + actions = [(C, C), + (C, C), + (C, D), + (C, C), + (C, C), + (C, D), + (C, C), + (C, C), + (C, C), + (D, C), + (C, D), + (D, D), + (C, D), + (C, D), + (C, C), + (C, C), + (D, C), + (C, D), + (D, D), + (C, C), + (C, D), + (C, C), + (C, C), + (C, D), + (D, C), + (C, D), + (D, D), + (C, D), + (C, C), + (D, C)] self.versus_test(axl.Random(0.5), expected_actions=actions, seed=7) + + diff --git a/axelrod/tests/strategies/test_backstabber.py b/axelrod/tests/strategies/test_backstabber.py index 54638352f..1f580c9cf 100644 --- a/axelrod/tests/strategies/test_backstabber.py +++ b/axelrod/tests/strategies/test_backstabber.py @@ -45,7 +45,9 @@ def test_defects_on_last_two_rounds_by_match_len(self): ) actions = [(C, C)] * 10 + [(D, C), (D, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, match_attributes={"length": 12}, + axl.Cooperator(), + expected_actions=actions, + match_attributes={"length": 12}, ) # Test that exceeds tournament length. actions = [(C, C)] * 198 + [(D, C), (D, C), (C, C), (C, C)] @@ -57,7 +59,9 @@ def test_defects_on_last_two_rounds_by_match_len(self): # But only if the tournament is known. actions = [(C, C)] * 202 self.versus_test( - axl.Cooperator(), expected_actions=actions, match_attributes={"length": -1}, + axl.Cooperator(), + expected_actions=actions, + match_attributes={"length": -1}, ) diff --git a/axelrod/tests/strategies/test_bush_mosteller.py b/axelrod/tests/strategies/test_bush_mosteller.py index 7159478c8..2cc881a57 100644 --- a/axelrod/tests/strategies/test_bush_mosteller.py +++ b/axelrod/tests/strategies/test_bush_mosteller.py @@ -22,7 +22,10 @@ class TestBushMostellar(TestPlayer): def test_strategy(self): actions = [(C, C), (D, C), (D, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, attrs={"_stimulus": 1}, seed=1, + axl.Cooperator(), + expected_actions=actions, + attrs={"_stimulus": 1}, + seed=1, ) # Making sure probabilities changes following payoffs diff --git a/axelrod/tests/strategies/test_calculator.py b/axelrod/tests/strategies/test_calculator.py index c70c13af2..3b2dc66c8 100644 --- a/axelrod/tests/strategies/test_calculator.py +++ b/axelrod/tests/strategies/test_calculator.py @@ -35,7 +35,9 @@ def test_twenty_rounds_joss_then_defects_for_cyclers(self): self.versus_test( axl.Alternator(), expected_actions=twenty_test_actions, seed=seed ) - self.versus_test(axl.Alternator(), expected_actions=expected_actions, seed=seed) + self.versus_test( + axl.Alternator(), expected_actions=expected_actions, seed=seed + ) def test_twenty_rounds_joss_then_tit_for_tat_for_non_cyclers(self): """Uses axelrod.strategies.axelrod_first.Joss strategy for first 20 rounds""" diff --git a/axelrod/tests/strategies/test_cooperator.py b/axelrod/tests/strategies/test_cooperator.py index bd2c2dee2..aca2290ae 100644 --- a/axelrod/tests/strategies/test_cooperator.py +++ b/axelrod/tests/strategies/test_cooperator.py @@ -46,7 +46,8 @@ def test_strategy(self): opponent_actions = [C, C, C, C, D, D] expected_actions = [(C, C), (C, C), (C, C), (D, C), (D, D), (C, D)] self.versus_test( - axl.MockPlayer(actions=opponent_actions), expected_actions=expected_actions, + axl.MockPlayer(actions=opponent_actions), + expected_actions=expected_actions, ) opponent_actions = [C, C, C, C] + [D, D] + [C] * 10 @@ -54,7 +55,8 @@ def test_strategy(self): [(C, C), (C, C), (C, C), (D, C)] + [(D, D), (C, D)] + [(C, C)] * 10 ) self.versus_test( - axl.MockPlayer(actions=opponent_actions), expected_actions=expected_actions, + axl.MockPlayer(actions=opponent_actions), + expected_actions=expected_actions, ) def test_cooperates_in_first_three_rounds(self): @@ -66,7 +68,7 @@ def test_cooperates_in_first_three_rounds(self): self.versus_test(axl.Alternator(), expected_actions=against_alternator) def test_defects_after_three_rounds_if_opponent_only_cooperated_in_max_history_depth_ten( - self, + self ): against_cooperator = [(C, C)] * 3 + [(D, C)] * 20 self.versus_test(axl.Cooperator(), expected_actions=against_cooperator) diff --git a/axelrod/tests/strategies/test_darwin.py b/axelrod/tests/strategies/test_darwin.py index cd409b433..8aa0b6391 100644 --- a/axelrod/tests/strategies/test_darwin.py +++ b/axelrod/tests/strategies/test_darwin.py @@ -45,7 +45,9 @@ def test_strategy(self): p1.reset() self.versus_test( - axl.Cooperator(), expected_actions=[(C, C)] * 5, attrs={"genome": [C] * 5}, + axl.Cooperator(), + expected_actions=[(C, C)] * 5, + attrs={"genome": [C] * 5}, ) expected_genome = [D] * 4 + [C] @@ -67,7 +69,9 @@ def test_against_geller_and_mindreader(self): ) self.versus_test( - axl.MindReader(), expected_actions=[(C, D)] * 2, attrs={"genome": [D, C]}, + axl.MindReader(), + expected_actions=[(C, D)] * 2, + attrs={"genome": [D, C]}, ) def test_reset_history_and_attributes(self): diff --git a/axelrod/tests/strategies/test_doubler.py b/axelrod/tests/strategies/test_doubler.py index a02f42695..e3d436302 100644 --- a/axelrod/tests/strategies/test_doubler.py +++ b/axelrod/tests/strategies/test_doubler.py @@ -22,7 +22,7 @@ class TestDoubler(TestPlayer): } def test_defects_if_opponent_last_play_is_D_and_defections_gt_two_times_cooperations( - self, + self ): opponent_plays = [C] * 7 + [D] * 4 + [C] actions = [(C, C)] * 7 + [(C, D)] * 4 + [(D, C)] @@ -31,7 +31,7 @@ def test_defects_if_opponent_last_play_is_D_and_defections_gt_two_times_cooperat ) def test_defects_if_opponent_last_play_D_and_defections_equal_two_times_cooperations( - self, + self ): opponent_plays = [C] * 8 + [D] * 4 + [C] actions = [(C, C)] * 8 + [(C, D)] * 4 + [(D, C)] diff --git a/axelrod/tests/strategies/test_evolvable_player.py b/axelrod/tests/strategies/test_evolvable_player.py index b7d1aef5f..ccb6ac37d 100644 --- a/axelrod/tests/strategies/test_evolvable_player.py +++ b/axelrod/tests/strategies/test_evolvable_player.py @@ -11,8 +11,10 @@ def PartialClass(cls, **kwargs): + class PartialedClass(cls): - __init__ = functools.partialmethod(cls.__init__, **kwargs) + __init__ = functools.partialmethod( + cls.__init__, **kwargs) return PartialedClass @@ -143,7 +145,7 @@ def test_serialization_csv(self): player = self.player() serialized = player.serialize_parameters() s = "0, 1, {}, 3".format(serialized) - s2 = s.split(",")[2] + s2 = s.split(',')[2] deserialized_player = player.__class__.deserialize_parameters(s2) self.assertEqual(player, deserialized_player) self.assertEqual(deserialized_player, deserialized_player.clone()) @@ -179,6 +181,7 @@ def test_behavior(self): class TestUtilityFunctions(unittest.TestCase): + def test_copy_lists(self): l1 = [list(range(10)), list(range(20))] l2 = copy_lists(l1) @@ -197,13 +200,14 @@ def test_crossover_lists(self): self.assertEqual(crossed, list1[:1] + list2[1:]) def test_crossover_dictionaries(self): - dict1 = {"1": 1, "2": 2, "3": 3} - dict2 = {"1": "a", "2": "b", "3": "c"} + 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"}) + self.assertEqual(crossed, {'1': 1, '2': 'b', '3': 'c'}) axl.seed(1) crossed = crossover_dictionaries(dict1, dict2) self.assertEqual(crossed, dict2) + diff --git a/axelrod/tests/strategies/test_finite_state_machines.py b/axelrod/tests/strategies/test_finite_state_machines.py index c58a340e5..12fe52e5d 100644 --- a/axelrod/tests/strategies/test_finite_state_machines.py +++ b/axelrod/tests/strategies/test_finite_state_machines.py @@ -7,11 +7,7 @@ import axelrod as axl from axelrod.compute_finite_state_machine_memory import get_memory_from_transitions from axelrod.evolvable_player import InsufficientParametersError -from axelrod.strategies.finite_state_machines import ( - EvolvableFSMPlayer, - FSMPlayer, - SimpleFSM, -) +from axelrod.strategies.finite_state_machines import EvolvableFSMPlayer, FSMPlayer, SimpleFSM from .test_player import TestPlayer from .test_evolvable_player import PartialClass, TestEvolvablePlayer @@ -165,7 +161,9 @@ def test_wsls(self): } expected = [(C, C), (C, D), (D, C), (D, D)] * 3 self.versus_test( - axl.Alternator(), expected_actions=expected, init_kwargs=wsls_init_kwargs, + axl.Alternator(), + expected_actions=expected, + init_kwargs=wsls_init_kwargs, ) @@ -214,7 +212,8 @@ def transitions_test(self, state_and_action): ) self.versus_test( - axl.MockPlayer(actions=opponent_actions), expected_actions=expected_actions, + axl.MockPlayer(actions=opponent_actions), + expected_actions=expected_actions, ) def verify_against_finite_state_machine( @@ -279,10 +278,7 @@ def test_memory(self): Test the memory depth using implemented algorithm """ transitions = self.player().fsm._state_transitions - self.assertEqual( - get_memory_from_transitions(transitions), - self.expected_classifier["memory_depth"], - ) + self.assertEqual(get_memory_from_transitions(transitions), self.expected_classifier["memory_depth"]) class TestFortress3(TestFSMPlayer): @@ -1053,18 +1049,21 @@ class TestEvolvableFSMPlayer(unittest.TestCase): def test_normalized_parameters(self): self.assertRaises( - InsufficientParametersError, self.player_class._normalize_parameters + InsufficientParametersError, + self.player_class._normalize_parameters ) self.assertRaises( InsufficientParametersError, self.player_class._normalize_parameters, - transitions=[[0, C, 1, D], [0, D, 0, D], [1, C, 1, C], [1, D, 1, D]], + transitions=[[0, C, 1, D], [0, D, 0, D], [1, C, 1, C], [1, D, 1, D]] ) def test_init(self): transitions = [[0, C, 1, D], [0, D, 0, D], [1, C, 1, C], [1, D, 1, D]] player = axl.EvolvableFSMPlayer( - transitions=transitions, initial_action=D, initial_state=1 + transitions=transitions, + initial_action=D, + initial_state=1 ) self.assertEqual(player.num_states, 2) self.assertEqual(player.fsm.transitions(), transitions) @@ -1115,7 +1114,7 @@ class TestEvolvableFSMPlayer4(TestEvolvablePlayer): init_parameters = { "transitions": ((1, C, 1, C), (1, D, 2, D), (2, C, 2, D), (2, D, 1, C)), "initial_state": 1, - "initial_action": C, + "initial_action": C } @@ -1124,8 +1123,7 @@ class TestEvolvableFSMPlayer4(TestEvolvablePlayer): EvolvableFSMPlayer, transitions=((1, C, 1, C), (1, D, 1, D)), initial_state=1, - initial_action=C, -) + initial_action=C) class EvolvableFSMAsFSM(TestFSMPlayer): diff --git a/axelrod/tests/strategies/test_forgiver.py b/axelrod/tests/strategies/test_forgiver.py index d5387b663..e83b86d76 100644 --- a/axelrod/tests/strategies/test_forgiver.py +++ b/axelrod/tests/strategies/test_forgiver.py @@ -28,7 +28,7 @@ def test_strategy(self): self.versus_test(axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 10) def test_cooperates_if_opponent_defections_is_ten_pct_and_defects_if_opponent_defections_gt_ten_pct( - self, + self ): final_action_lowers_defections_to_ten_percent = [D] + [C] * 9 expected = [(C, D)] + [(D, C)] * 9 @@ -97,5 +97,6 @@ def test_reverts_to_cooperator_if_defections_become_le_ten_percent(self): maintain_ten_pct = defections_at_ten_pct + ([C] * 9 + [D]) * 3 now_cooperates = tft + ([(C, C)] * 9 + [(C, D)]) * 3 self.versus_test( - axl.MockPlayer(actions=maintain_ten_pct), expected_actions=now_cooperates, + axl.MockPlayer(actions=maintain_ten_pct), + expected_actions=now_cooperates, ) diff --git a/axelrod/tests/strategies/test_gambler.py b/axelrod/tests/strategies/test_gambler.py index c91452ce2..4a3b3c5fb 100755 --- a/axelrod/tests/strategies/test_gambler.py +++ b/axelrod/tests/strategies/test_gambler.py @@ -131,7 +131,9 @@ def test_cooperate_forever(self): seed = 2 opponent = [D] * 3 + [C] * 10 expected = [(C, D), (D, D), (D, D)] + [(C, C)] * 10 - self.versus_test(axl.MockPlayer(opponent), expected_actions=expected, seed=seed) + self.versus_test( + axl.MockPlayer(opponent), expected_actions=expected, seed=seed + ) def test_defect_forever(self): seed = 2 @@ -400,7 +402,9 @@ def test_vs_DCDDC(self): new_seed = 3 expected[8] = (D, D) self.versus_test( - axl.MockPlayer(opponent_actions), expected_actions=expected, seed=new_seed, + axl.MockPlayer(opponent_actions), + expected_actions=expected, + seed=new_seed, ) new_seed = 2 @@ -493,13 +497,14 @@ def test_vs_alternator(self): class TestEvolvableGambler(unittest.TestCase): + def test_receive_vector(self): plays, op_plays, op_start_plays = 1, 1, 1 - player = axl.EvolvableGambler(parameters=(plays, op_plays, op_start_plays)) + player = axl.EvolvableGambler( + parameters=(plays, op_plays, op_start_plays)) - self.assertRaises( - AttributeError, axl.EvolvableGambler.__getattribute__, *[player, "vector"] - ) + self.assertRaises(AttributeError, axl.EvolvableGambler.__getattribute__, + *[player, 'vector']) vector = [random.random() for _ in range(8)] player.receive_vector(vector) @@ -507,19 +512,20 @@ def test_receive_vector(self): def test_vector_to_instance(self): plays, op_plays, op_start_plays = 1, 1, 1 - player = axl.EvolvableGambler(parameters=(plays, op_plays, op_start_plays)) + player = axl.EvolvableGambler( + parameters=(plays, op_plays, op_start_plays)) vector = [random.random() for _ in range(8)] player.receive_vector(vector) - keys = create_lookup_table_keys( - player_depth=plays, op_depth=op_plays, op_openings_depth=op_start_plays - ) + keys = create_lookup_table_keys(player_depth=plays, op_depth=op_plays, + op_openings_depth=op_start_plays) action_dict = dict(zip(keys, vector)) self.assertEqual(player._lookup.dictionary, action_dict) def test_create_vector_bounds(self): plays, op_plays, op_start_plays = 1, 1, 1 - player = axl.EvolvableGambler(parameters=(plays, op_plays, op_start_plays)) + player = axl.EvolvableGambler( + parameters=(plays, op_plays, op_start_plays)) lb, ub = player.create_vector_bounds() self.assertIsInstance(lb, list) self.assertIsInstance(ub, list) @@ -536,7 +542,8 @@ class TestEvolvableGambler2(TestEvolvablePlayer): player_class = axl.EvolvableGambler parent_class = axl.Gambler parent_kwargs = ["lookup_dict"] - init_parameters = {"parameters": (1, 1, 1), "initial_actions": (C,)} + init_parameters = {"parameters": (1, 1, 1), + "initial_actions": (C,)} class TestEvolvableGambler3(TestEvolvablePlayer): @@ -544,7 +551,8 @@ class TestEvolvableGambler3(TestEvolvablePlayer): player_class = axl.EvolvableGambler parent_class = axl.Gambler parent_kwargs = ["lookup_dict"] - init_parameters = {"parameters": (3, 2, 1), "initial_actions": (C, C, C,)} + init_parameters = {"parameters": (3, 2, 1), + "initial_actions": (C, C, C,)} class TestEvolvableGambler4(TestEvolvablePlayer): @@ -552,11 +560,9 @@ class TestEvolvableGambler4(TestEvolvablePlayer): player_class = axl.EvolvableGambler parent_class = axl.Gambler parent_kwargs = ["lookup_dict"] - init_parameters = { - "parameters": (2, 2, 2), - "pattern": [random.random() for _ in range(64)], - "initial_actions": (C, C,), - } + init_parameters = {"parameters": (2, 2, 2), + "pattern": [random.random() for _ in range(64)], + "initial_actions": (C, C,)} # Substitute EvolvableHMMPlayer as a regular HMMPlayer. @@ -564,7 +570,7 @@ class TestEvolvableGambler4(TestEvolvablePlayer): axl.EvolvableGambler, pattern=tables[("PSO Gambler 2_2_2", 2, 2, 2)], parameters=(2, 2, 2), - initial_actions=(C, C,), + initial_actions=(C, C,) ) diff --git a/axelrod/tests/strategies/test_geller.py b/axelrod/tests/strategies/test_geller.py index 2c2e9e0f2..e2b7bdf67 100644 --- a/axelrod/tests/strategies/test_geller.py +++ b/axelrod/tests/strategies/test_geller.py @@ -50,8 +50,12 @@ def test_strategy_against_lookerup_players(self): Regression test for a bug discussed in https://github.com/Axelrod-Python/Axelrod/issues/1185 """ - self.versus_test(axl.EvolvedLookerUp1_1_1(), expected_actions=[(C, C), (C, C)]) - self.versus_test(axl.EvolvedLookerUp2_2_2(), expected_actions=[(C, C), (C, C)]) + self.versus_test( + axl.EvolvedLookerUp1_1_1(), expected_actions=[(C, C), (C, C)] + ) + self.versus_test( + axl.EvolvedLookerUp2_2_2(), expected_actions=[(C, C), (C, C)] + ) def test_returns_foil_inspection_strategy_of_opponent(self): self.versus_test( @@ -92,7 +96,9 @@ def test_returns_foil_inspection_strategy_of_opponent(self): self.versus_test(axl.Darwin(), expected_actions=[(C, C), (C, C), (C, C)]) - self.versus_test(axl.MindReader(), expected_actions=[(D, D), (D, D), (D, D)]) + self.versus_test( + axl.MindReader(), expected_actions=[(D, D), (D, D), (D, D)] + ) class TestGellerDefector(TestGeller): @@ -121,4 +127,6 @@ def test_returns_foil_inspection_strategy_of_opponent(self): self.versus_test(axl.Darwin(), expected_actions=[(C, C), (C, C), (C, C)]) - self.versus_test(axl.MindReader(), expected_actions=[(D, D), (D, D), (D, D)]) + self.versus_test( + axl.MindReader(), expected_actions=[(D, D), (D, D), (D, D)] + ) diff --git a/axelrod/tests/strategies/test_grudger.py b/axelrod/tests/strategies/test_grudger.py index 7b5fc1970..79194b5d8 100644 --- a/axelrod/tests/strategies/test_grudger.py +++ b/axelrod/tests/strategies/test_grudger.py @@ -12,7 +12,7 @@ class TestGrudger(TestPlayer): name = "Grudger" player = axl.Grudger expected_classifier = { - "memory_depth": float("inf"), + "memory_depth": float('inf'), "stochastic": False, "makes_use_of": set(), "long_run_time": False, diff --git a/axelrod/tests/strategies/test_headsup.py b/axelrod/tests/strategies/test_headsup.py index ae99242c4..9b9282724 100644 --- a/axelrod/tests/strategies/test_headsup.py +++ b/axelrod/tests/strategies/test_headsup.py @@ -54,7 +54,11 @@ class TestZDGTFT2vsBully(TestMatch): def test_rounds(self): self.versus_test( - axl.ZDGTFT2(), axl.Bully(), [C, D, D, C, C, C], [D, D, C, C, D, D], seed=2, + axl.ZDGTFT2(), + axl.Bully(), + [C, D, D, C, C, C], + [D, D, C, C, D, D], + seed=2, ) @@ -76,7 +80,10 @@ class FoolMeOncevsBully(TestMatch): def test_rounds(self): self.versus_test( - axl.FoolMeOnce(), axl.Bully(), [C, C, D, D, D, D], [D, D, D, C, C, C], + axl.FoolMeOnce(), + axl.Bully(), + [C, C, D, D, D, D], + [D, D, D, C, C, C], ) @@ -94,7 +101,10 @@ class GrudgervsSTFT(TestMatch): def test_rounds(self): self.versus_test( - axl.Grudger(), axl.SuspiciousTitForTat(), [C] + [D] * 9, [D, C] + [D] * 8, + axl.Grudger(), + axl.SuspiciousTitForTat(), + [C] + [D] * 9, + [D, C] + [D] * 8, ) @@ -103,5 +113,8 @@ class TestWSLSvsBully(TestMatch): def test_rounds(self): self.versus_test( - axl.WinStayLoseShift(), axl.Bully(), [C, D, C, C, D], [D, D, C, D, D], + axl.WinStayLoseShift(), + axl.Bully(), + [C, D, C, C, D], + [D, D, C, D, D], ) diff --git a/axelrod/tests/strategies/test_hunter.py b/axelrod/tests/strategies/test_hunter.py index b747687cc..7c2912494 100644 --- a/axelrod/tests/strategies/test_hunter.py +++ b/axelrod/tests/strategies/test_hunter.py @@ -93,12 +93,16 @@ class TestAlternatorHunter(TestPlayer): def test_strategy(self): actions = [(C, C), (C, D)] * 3 + [(D, C), (D, D)] * 5 self.versus_test( - opponent=axl.Alternator(), expected_actions=actions, attrs={"is_alt": True}, + opponent=axl.Alternator(), + expected_actions=actions, + attrs={"is_alt": True}, ) actions = [(C, D)] * 14 self.versus_test( - opponent=axl.Defector(), expected_actions=actions, attrs={"is_alt": False}, + opponent=axl.Defector(), + expected_actions=actions, + attrs={"is_alt": False}, ) def test_reset_attr(self): diff --git a/axelrod/tests/strategies/test_negation.py b/axelrod/tests/strategies/test_negation.py index 601816cd8..8c7542aaa 100644 --- a/axelrod/tests/strategies/test_negation.py +++ b/axelrod/tests/strategies/test_negation.py @@ -24,10 +24,16 @@ class TestNegation(TestPlayer): def test_strategy(self): # First move is random. actions = [(C, C), (D, D), (C, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=1) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=1 + ) actions = [(D, C), (D, D), (C, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, C), (D, C), (D, C)] - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=1) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=1 + ) actions = [(D, D), (C, D), (C, D)] self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=2) diff --git a/axelrod/tests/strategies/test_prober.py b/axelrod/tests/strategies/test_prober.py index 6a64cd9f5..771e0115a 100644 --- a/axelrod/tests/strategies/test_prober.py +++ b/axelrod/tests/strategies/test_prober.py @@ -288,21 +288,29 @@ def test_strategy(self): def test_random_defection(self): # Unprovoked defection with small probability actions = [(C, C), (D, C), (D, C), (C, C), (C, C)] - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=2 + ) actions = [(C, C), (C, C), (C, C), (C, C), (D, C)] - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=5) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=5 + ) # Always defect when p is 1 actions = [(C, C), (D, C), (D, C), (D, C), (D, C)] self.versus_test( - opponent=axl.Cooperator(), expected_actions=actions, init_kwargs={"p": 1}, + opponent=axl.Cooperator(), + expected_actions=actions, + init_kwargs={"p": 1}, ) def test_reduction_to_TFT(self): actions = [(C, C), (C, D), (D, C), (C, D), (D, C)] self.versus_test( - opponent=axl.Alternator(), expected_actions=actions, init_kwargs={"p": 0}, + opponent=axl.Alternator(), + expected_actions=actions, + init_kwargs={"p": 0}, ) @@ -324,7 +332,9 @@ def test_strategy(self): # Always retaliate a defection actions = [(C, D)] + [(D, D)] * 10 self.versus_test( - opponent=axl.Defector(), expected_actions=actions, attrs={"probing": False}, + opponent=axl.Defector(), + expected_actions=actions, + attrs={"probing": False}, ) def test_random_defection(self): diff --git a/axelrod/tests/strategies/test_revised_downing.py b/axelrod/tests/strategies/test_revised_downing.py index a97db8e63..b46f6fdcc 100644 --- a/axelrod/tests/strategies/test_revised_downing.py +++ b/axelrod/tests/strategies/test_revised_downing.py @@ -4,7 +4,6 @@ C, D = axl.Action.C, axl.Action.D - class TestRevisedDowning(TestPlayer): name = "Revised Downing" diff --git a/axelrod/tests/strategies/test_selfsteem.py b/axelrod/tests/strategies/test_selfsteem.py index 0799b8cf9..c0d9ec84c 100644 --- a/axelrod/tests/strategies/test_selfsteem.py +++ b/axelrod/tests/strategies/test_selfsteem.py @@ -32,7 +32,9 @@ def test_strategy(self): # Check for f < -0.95, cooperate actions = [(D, C), (C, C), (D, C), (D, C), (C, C), (D, C), (C, C), (C, C)] - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=0 + ) actions = [(D, D)] + [(D, D)] * 5 + [(D, D), (C, D), (C, D)] self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=0) @@ -44,7 +46,9 @@ def test_strategy(self): + [(D, C), (D, C)] + [(C, C)] * 7 ) - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=6) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=6 + ) actions = ( [(D, D)] * 7 diff --git a/axelrod/tests/strategies/test_shortmem.py b/axelrod/tests/strategies/test_shortmem.py index 9f7af797f..48dcd0138 100644 --- a/axelrod/tests/strategies/test_shortmem.py +++ b/axelrod/tests/strategies/test_shortmem.py @@ -12,7 +12,7 @@ class TestShortMem(TestPlayer): name = "ShortMem" player = axl.ShortMem expected_classifier = { - "memory_depth": float("inf"), + "memory_depth": float('inf'), "stochastic": False, "makes_use_of": set(), "inspects_source": False, diff --git a/axelrod/tests/strategies/test_verybad.py b/axelrod/tests/strategies/test_verybad.py index 6c31ad2a2..b67545e97 100644 --- a/axelrod/tests/strategies/test_verybad.py +++ b/axelrod/tests/strategies/test_verybad.py @@ -23,7 +23,9 @@ class TestVeryBad(TestPlayer): def test_strategy(self): # axelrod.Defector - # cooperates for the first three, defects for the rest P(C) < .5 - self.versus_test(axl.Defector(), expected_actions=([(C, D)] * 3 + [(D, D)] * 7)) + self.versus_test( + axl.Defector(), expected_actions=([(C, D)] * 3 + [(D, D)] * 7) + ) # axelrod.Cooperator - # cooperate for all, P(C) == 1 diff --git a/axelrod/tests/strategies/test_worse_and_worse.py b/axelrod/tests/strategies/test_worse_and_worse.py index febaee4e2..a402a5e15 100644 --- a/axelrod/tests/strategies/test_worse_and_worse.py +++ b/axelrod/tests/strategies/test_worse_and_worse.py @@ -151,5 +151,7 @@ def test_strategy(self): # stochastic behaviour, given a seed actions = [(C, C), (C, D), (C, C), (D, D), (C, C), (D, C)] self.versus_test( - axl.MockPlayer(actions=[C, D, C, D, C]), expected_actions=actions, seed=8, + axl.MockPlayer(actions=[C, D, C, D, C]), + expected_actions=actions, + seed=8, ) diff --git a/axelrod/tests/strategies/test_zero_determinant.py b/axelrod/tests/strategies/test_zero_determinant.py index ab99bef66..615ca27fd 100644 --- a/axelrod/tests/strategies/test_zero_determinant.py +++ b/axelrod/tests/strategies/test_zero_determinant.py @@ -37,7 +37,9 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (C, D), (D, C), (D, D), (D, C), (D, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=3) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=3 + ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=6) @@ -68,10 +70,14 @@ def test_receive_match_attributes(self): def test_strategy(self): actions = [(C, C), (D, D), (D, C), (D, D), (D, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, C), (C, D), (C, C), (C, D), (D, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=31) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=31 + ) actions = [(C, D), (D, C), (D, D), (D, C), (C, D), (C, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=2) @@ -105,7 +111,9 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (D, D), (D, C), (D, D), (D, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) @@ -136,7 +144,9 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (C, D), (D, C), (D, D), (D, C), (D, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=3) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=3 + ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] @@ -163,7 +173,9 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (D, D), (D, C), (D, D), (D, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) @@ -190,10 +202,14 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (C, D), (D, C), (D, D), (C, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, C), (C, D), (C, C), (C, D), (C, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=31) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=31 + ) actions = [(C, D), (D, C), (D, D), (C, C), (C, D), (C, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=2) @@ -226,10 +242,14 @@ def test_receive_match_attributes(self): def test_strategy(self): actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, C), (C, D), (C, C), (C, D), (C, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=31) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=31 + ) actions = [(C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=2) @@ -258,7 +278,9 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (D, D), (D, C), (D, D), (D, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) @@ -289,7 +311,9 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (D, D), (D, C), (C, D), (C, C), (D, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=2 + ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) diff --git a/axelrod/tests/unit/test_compute_finite_state_machine_memory.py b/axelrod/tests/unit/test_compute_finite_state_machine_memory.py index 4e3810cff..82e828676 100644 --- a/axelrod/tests/unit/test_compute_finite_state_machine_memory.py +++ b/axelrod/tests/unit/test_compute_finite_state_machine_memory.py @@ -98,7 +98,7 @@ def test_three_state_tft(self): (1, C, 2, C), (1, D, 0, D), (2, C, 0, C), - (2, D, 2, D), + (2, D, 2, D) ) trans_dict = self.transitions_to_dict(transitions) @@ -271,7 +271,9 @@ def test_disconnected_graph(self): ) trans_dict = self.transitions_to_dict(transitions) - self.assertEqual(get_memory_from_transitions(trans_dict, initial_state=1), 2) + self.assertEqual( + get_memory_from_transitions(trans_dict, initial_state=1), 2 + ) def test_transient_state(self): """Test a setup where we a transient state (no incoming transitions) @@ -295,9 +297,13 @@ def test_transient_state(self): trans_dict = self.transitions_to_dict(transitions) # If starting in state 4, then treat like Cooperator - self.assertEqual(get_memory_from_transitions(trans_dict, initial_state=4), 0) + self.assertEqual( + get_memory_from_transitions(trans_dict, initial_state=4), 0 + ) # Start in state 1, then a Fortress3. - self.assertEqual(get_memory_from_transitions(trans_dict, initial_state=1), 2) + self.assertEqual( + get_memory_from_transitions(trans_dict, initial_state=1), 2 + ) def test_infinite_memory_transient_state(self): """A transient state at 0, which goes into either a Cooperator or a TFT. @@ -316,10 +322,13 @@ def test_infinite_memory_transient_state(self): trans_dict = self.transitions_to_dict(transitions) self.assertEqual( - get_memory_from_transitions(trans_dict, initial_state=0), float("inf"), + get_memory_from_transitions(trans_dict, initial_state=0), + float("inf"), ) - self.assertEqual(get_memory_from_transitions(trans_dict, initial_state=2), 1) + self.assertEqual( + get_memory_from_transitions(trans_dict, initial_state=2), 1 + ) def test_evolved_fsm_4(self): """This should be infinite memory because the C/D self-loop at state 2 @@ -338,3 +347,4 @@ def test_evolved_fsm_4(self): trans_dict = self.transitions_to_dict(transitions) self.assertEqual(get_memory_from_transitions(trans_dict), float("inf")) + diff --git a/axelrod/tests/unit/test_ecosystem.py b/axelrod/tests/unit/test_ecosystem.py index ca49fe300..92098ba17 100644 --- a/axelrod/tests/unit/test_ecosystem.py +++ b/axelrod/tests/unit/test_ecosystem.py @@ -37,7 +37,9 @@ def test_default_population_sizes(self): self.assertEqual(list(set(pops[0])), [0.25]) def test_non_default_population_sizes(self): - eco = axl.Ecosystem(self.res_cooperators, population=[0.7, 0.25, 0.03, 0.02]) + eco = axl.Ecosystem( + self.res_cooperators, population=[0.7, 0.25, 0.03, 0.02] + ) pops = eco.population_sizes self.assertEqual(eco.num_players, 4) self.assertEqual(len(pops), 1) diff --git a/axelrod/tests/unit/test_eigen.py b/axelrod/tests/unit/test_eigen.py index eb3f8f379..36f0bf5b9 100644 --- a/axelrod/tests/unit/test_eigen.py +++ b/axelrod/tests/unit/test_eigen.py @@ -8,6 +8,7 @@ from axelrod.eigen import _normalise, principal_eigenvector + class FunctionCases(unittest.TestCase): def test_identity_matrices(self): for size in range(2, 6): diff --git a/axelrod/tests/unit/test_fingerprint.py b/axelrod/tests/unit/test_fingerprint.py index 841055363..f60a93e7a 100644 --- a/axelrod/tests/unit/test_fingerprint.py +++ b/axelrod/tests/unit/test_fingerprint.py @@ -445,7 +445,9 @@ def test_serial_fingerprint(self): tf = TransitiveFingerprint(strategy) path = pathlib.Path("test_outputs/test_fingerprint.csv") tf.fingerprint( - repetitions=1, progress_bar=False, filename=axl_filename(path), + repetitions=1, + progress_bar=False, + filename=axl_filename(path), ) self.assertEqual(tf.data.shape, (50, 50)) diff --git a/axelrod/tests/unit/test_graph.py b/axelrod/tests/unit/test_graph.py index b9c79b241..1e0666ee6 100644 --- a/axelrod/tests/unit/test_graph.py +++ b/axelrod/tests/unit/test_graph.py @@ -247,70 +247,59 @@ def test_size_4_with_loops(self): class TestAttachedComplete(unittest.TestCase): def test_size_2(self): g = axl.graph.attached_complete_graphs(2, loops=False) - self.assertEqual(g.vertices, ["0:0", "0:1", "1:0", "1:1"]) + self.assertEqual(g.vertices, ['0:0', '0:1', '1:0', '1:1']) self.assertEqual( g.edges, - [ - ("0:0", "0:1"), - ("0:1", "0:0"), - ("1:0", "1:1"), - ("1:1", "1:0"), - ("0:0", "1:0"), - ("1:0", "0:0"), - ], + [('0:0', '0:1'), ('0:1', '0:0'), ('1:0', '1:1'), ('1:1', '1:0'), ('0:0', '1:0'), ('1:0', '0:0')] ) self.assertEqual(g.directed, False) def test_size_3(self): g = axl.graph.attached_complete_graphs(3, loops=False) - self.assertEqual(g.vertices, ["0:0", "0:1", "0:2", "1:0", "1:1", "1:2"]) + self.assertEqual(g.vertices, ['0:0', '0:1', '0:2', '1:0', '1:1', '1:2']) self.assertEqual( g.edges, - [ - ("0:0", "0:1"), - ("0:1", "0:0"), - ("0:0", "0:2"), - ("0:2", "0:0"), - ("0:1", "0:2"), - ("0:2", "0:1"), - ("1:0", "1:1"), - ("1:1", "1:0"), - ("1:0", "1:2"), - ("1:2", "1:0"), - ("1:1", "1:2"), - ("1:2", "1:1"), - ("0:0", "1:0"), - ("1:0", "0:0"), - ], + [('0:0', '0:1'), + ('0:1', '0:0'), + ('0:0', '0:2'), + ('0:2', '0:0'), + ('0:1', '0:2'), + ('0:2', '0:1'), + ('1:0', '1:1'), + ('1:1', '1:0'), + ('1:0', '1:2'), + ('1:2', '1:0'), + ('1:1', '1:2'), + ('1:2', '1:1'), + ('0:0', '1:0'), + ('1:0', '0:0')] ) self.assertEqual(g.directed, False) def test_size_3_with_loops(self): g = axl.graph.attached_complete_graphs(3, loops=True) - self.assertEqual(g.vertices, ["0:0", "0:1", "0:2", "1:0", "1:1", "1:2"]) + self.assertEqual(g.vertices, ['0:0', '0:1', '0:2', '1:0', '1:1', '1:2']) self.assertEqual( g.edges, - [ - ("0:0", "0:1"), - ("0:1", "0:0"), - ("0:0", "0:2"), - ("0:2", "0:0"), - ("0:1", "0:2"), - ("0:2", "0:1"), - ("1:0", "1:1"), - ("1:1", "1:0"), - ("1:0", "1:2"), - ("1:2", "1:0"), - ("1:1", "1:2"), - ("1:2", "1:1"), - ("0:0", "1:0"), - ("1:0", "0:0"), - ("0:0", "0:0"), - ("0:1", "0:1"), - ("0:2", "0:2"), - ("1:0", "1:0"), - ("1:1", "1:1"), - ("1:2", "1:2"), - ], + [('0:0', '0:1'), + ('0:1', '0:0'), + ('0:0', '0:2'), + ('0:2', '0:0'), + ('0:1', '0:2'), + ('0:2', '0:1'), + ('1:0', '1:1'), + ('1:1', '1:0'), + ('1:0', '1:2'), + ('1:2', '1:0'), + ('1:1', '1:2'), + ('1:2', '1:1'), + ('0:0', '1:0'), + ('1:0', '0:0'), + ('0:0', '0:0'), + ('0:1', '0:1'), + ('0:2', '0:2'), + ('1:0', '1:0'), + ('1:1', '1:1'), + ('1:2', '1:2')] ) self.assertEqual(g.directed, False) diff --git a/axelrod/tests/unit/test_history.py b/axelrod/tests/unit/test_history.py index 747627157..7c517958b 100644 --- a/axelrod/tests/unit/test_history.py +++ b/axelrod/tests/unit/test_history.py @@ -84,7 +84,8 @@ def test_flip_plays(self): self.assertEqual(flipped_history, [D, C, D, C, D]) self.assertEqual(flipped_history.cooperations, 2) self.assertEqual(flipped_history.defections, 3) - self.assertEqual(flipped_history.state_distribution, new_distribution) + self.assertEqual(flipped_history.state_distribution, + new_distribution) # Flip operation is idempotent flipped_flipped_history = flipped_history.flip_plays() @@ -94,6 +95,7 @@ def test_flip_plays(self): class TestLimitedHistory(unittest.TestCase): + def test_memory_depth(self): h = LimitedHistory(memory_depth=3) h.append(C, C) @@ -104,9 +106,8 @@ def test_memory_depth(self): self.assertEqual(len(h), 3) self.assertEqual(h.cooperations, 2) self.assertEqual(h.defections, 1) - self.assertEqual( - h.state_distribution, Counter({(C, C): 1, (D, D): 1, (C, D): 1}) - ) + self.assertEqual(h.state_distribution, + Counter({(C, C): 1, (D, D): 1, (C, D): 1})) h.append(D, C) self.assertEqual(len(h), 3) self.assertEqual(h._plays, [D, C, D]) @@ -114,5 +115,5 @@ def test_memory_depth(self): self.assertEqual(h.cooperations, 1) self.assertEqual(h.defections, 2) self.assertEqual( - h.state_distribution, Counter({(D, D): 1, (C, D): 1, (D, C): 1, (C, C): 0}) - ) + h.state_distribution, + Counter({(D, D): 1, (C, D): 1, (D, C): 1, (C, C): 0})) diff --git a/axelrod/tests/unit/test_interaction_utils.py b/axelrod/tests/unit/test_interaction_utils.py index 953d3f363..2e1d2c5e1 100644 --- a/axelrod/tests/unit/test_interaction_utils.py +++ b/axelrod/tests/unit/test_interaction_utils.py @@ -49,17 +49,14 @@ def test_compute_scores(self): def test_compute_final_score(self): for inter, final_score in zip(self.interactions, self.final_scores): - self.assertEqual( - final_score, axl.interaction_utils.compute_final_score(inter) - ) + self.assertEqual(final_score, axl.interaction_utils.compute_final_score(inter)) def test_compute_final_score_per_turn(self): for inter, final_score_per_round in zip( self.interactions, self.final_score_per_turn ): self.assertEqual( - final_score_per_round, - axl.interaction_utils.compute_final_score_per_turn(inter), + final_score_per_round, axl.interaction_utils.compute_final_score_per_turn(inter) ) def test_compute_winner_index(self): @@ -72,27 +69,19 @@ def test_compute_cooperations(self): def test_compute_normalised_cooperations(self): for inter, coop in zip(self.interactions, self.normalised_cooperations): - self.assertEqual( - coop, axl.interaction_utils.compute_normalised_cooperation(inter) - ) + self.assertEqual(coop, axl.interaction_utils.compute_normalised_cooperation(inter)) def test_compute_state_distribution(self): for inter, dist in zip(self.interactions, self.state_distribution): - self.assertEqual( - dist, axl.interaction_utils.compute_state_distribution(inter) - ) + self.assertEqual(dist, axl.interaction_utils.compute_state_distribution(inter)) def test_compute_normalised_state_distribution(self): for inter, dist in zip(self.interactions, self.normalised_state_distribution): - self.assertEqual( - dist, axl.interaction_utils.compute_normalised_state_distribution(inter) - ) + self.assertEqual(dist, axl.interaction_utils.compute_normalised_state_distribution(inter)) def test_compute_state_to_action_distribution(self): for inter, dist in zip(self.interactions, self.state_to_action_distribution): - self.assertEqual( - dist, axl.interaction_utils.compute_state_to_action_distribution(inter) - ) + self.assertEqual(dist, axl.interaction_utils.compute_state_to_action_distribution(inter)) inter = [(C, D), (D, C), (C, D), (D, C), (D, D), (C, C), (C, D)] expected_dist = [ Counter( @@ -107,20 +96,14 @@ def test_compute_state_to_action_distribution(self): Counter({((C, C), D): 1, ((C, D), C): 2, ((D, C), D): 2, ((D, D), C): 1}), ] - self.assertEqual( - expected_dist, - axl.interaction_utils.compute_state_to_action_distribution(inter), - ) + self.assertEqual(expected_dist, axl.interaction_utils.compute_state_to_action_distribution(inter)) def test_compute_normalised_state_to_action_distribution(self): for inter, dist in zip( self.interactions, self.normalised_state_to_action_distribution ): self.assertEqual( - dist, - axl.interaction_utils.compute_normalised_state_to_action_distribution( - inter - ), + dist, axl.interaction_utils.compute_normalised_state_to_action_distribution(inter) ) inter = [(C, D), (D, C), (C, D), (D, C), (D, D), (C, C), (C, D)] expected_dist = [ @@ -136,10 +119,7 @@ def test_compute_normalised_state_to_action_distribution(self): Counter({((C, C), D): 1, ((C, D), C): 1, ((D, C), D): 1, ((D, D), C): 1}), ] self.assertEqual( - expected_dist, - axl.interaction_utils.compute_normalised_state_to_action_distribution( - inter - ), + expected_dist, axl.interaction_utils.compute_normalised_state_to_action_distribution(inter) ) def test_compute_sparklines(self): @@ -157,14 +137,10 @@ def test_read_interactions_from_file(self): (0, 1): [[(C, D), (C, D)] for _ in range(3)], (1, 1): [[(D, D), (D, D)] for _ in range(3)], } - interactions = axl.interaction_utils.read_interactions_from_file( - tmp_file.name, progress_bar=False - ) + interactions = axl.interaction_utils.read_interactions_from_file(tmp_file.name, progress_bar=False) self.assertEqual(expected_interactions, interactions) def test_string_to_interactions(self): string = "CDCDDD" interactions = [(C, D), (C, D), (D, D)] - self.assertEqual( - axl.interaction_utils.string_to_interactions(string), interactions - ) + self.assertEqual(axl.interaction_utils.string_to_interactions(string), interactions) diff --git a/axelrod/tests/unit/test_match.py b/axelrod/tests/unit/test_match.py index bc7f113ec..71913d103 100644 --- a/axelrod/tests/unit/test_match.py +++ b/axelrod/tests/unit/test_match.py @@ -70,7 +70,9 @@ def test_default_init(self): self.assertEqual(match.noise, 0) self.assertEqual(match.game.RPST(), (3, 1, 0, 5)) - self.assertEqual(match.players[0].match_attributes["length"], axl.DEFAULT_TURNS) + self.assertEqual( + match.players[0].match_attributes["length"], axl.DEFAULT_TURNS + ) self.assertEqual(match._cache, {}) def test_example_prob_end(self): @@ -95,7 +97,9 @@ def test_example_prob_end(self): def test_non_default_attributes(self, turns, game): p1, p2 = axl.Cooperator(), axl.Cooperator() match_attributes = {"length": 500, "game": game, "noise": 0.5} - match = axl.Match((p1, p2), turns, game=game, match_attributes=match_attributes) + match = axl.Match( + (p1, p2), turns, game=game, match_attributes=match_attributes + ) self.assertEqual(match.players[0].match_attributes["length"], 500) self.assertEqual(match.players[0].match_attributes["noise"], 0.5) @@ -158,7 +162,9 @@ def test_play(self): match = axl.Match(players, 3, deterministic_cache=cache) expected_result = [(C, D), (C, D), (C, D)] self.assertEqual(match.play(), expected_result) - self.assertEqual(cache[(axl.Cooperator(), axl.Defector())], expected_result) + self.assertEqual( + cache[(axl.Cooperator(), axl.Defector())], expected_result + ) # a deliberately incorrect result so we can tell it came from the cache expected_result = [(C, C), (D, D), (D, C), (C, C), (C, D)] @@ -182,7 +188,8 @@ def test_cache_grows(self): self.assertEqual(match.play(), expected_result_5_turn) # The cache should now hold the 5-turn result.. self.assertEqual( - cache[(axl.Cooperator(), axl.Defector())], expected_result_5_turn + cache[(axl.Cooperator(), axl.Defector())], + expected_result_5_turn ) def test_cache_doesnt_shrink(self): @@ -201,7 +208,8 @@ def test_cache_doesnt_shrink(self): self.assertEqual(match.play(), expected_result_3_turn) # The cache should still hold the 5. self.assertEqual( - cache[(axl.Cooperator(), axl.Defector())], expected_result_5_turn + cache[(axl.Cooperator(), axl.Defector())], + expected_result_5_turn ) def test_scores(self): diff --git a/axelrod/tests/unit/test_mock_player.py b/axelrod/tests/unit/test_mock_player.py index 1f380b5ba..457e77711 100644 --- a/axelrod/tests/unit/test_mock_player.py +++ b/axelrod/tests/unit/test_mock_player.py @@ -17,3 +17,4 @@ def test_strategy(self): p2 = axl.Player() for action in actions: self.assertEqual(action, m.strategy(p2)) + diff --git a/axelrod/tests/unit/test_moran.py b/axelrod/tests/unit/test_moran.py index c481e2c31..d972b288f 100644 --- a/axelrod/tests/unit/test_moran.py +++ b/axelrod/tests/unit/test_moran.py @@ -48,9 +48,7 @@ def test_init(self): sorted([(0, 1), (2, 0), (1, 2), (0, 0), (1, 1), (2, 2)]), ) - mp = axl.MoranProcess( - players, interaction_graph=graph, reproduction_graph=graph - ) + mp = axl.MoranProcess(players, interaction_graph=graph, reproduction_graph=graph) self.assertEqual(mp.interaction_graph._edges, [(0, 1), (2, 0), (1, 2)]) self.assertEqual(mp.reproduction_graph._edges, [(0, 1), (2, 0), (1, 2)]) @@ -382,38 +380,38 @@ def test_cooperator_can_win_with_fitness_transformation(self): def test_atomic_mutation_fsm(self): axl.seed(12) - players = [ - axl.EvolvableFSMPlayer(num_states=2, initial_state=1, initial_action=C) - for _ in range(5) - ] + players = [axl.EvolvableFSMPlayer(num_states=2, initial_state=1, initial_action=C) + for _ in range(5)] mp = axl.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", - ) + '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) def test_atomic_mutation_cycler(self): axl.seed(10) cycle_length = 5 - players = [axl.EvolvableCycler(cycle_length=cycle_length) for _ in range(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(mp.winning_strategy_name, 'EvolvableCycler: CDCDD, 5, 0.2, 1') self.assertEqual(len(mp.populations), 19) self.assertTrue(mp.fixated) def test_mutation_method_exceptions(self): axl.seed(10) cycle_length = 5 - players = [axl.EvolvableCycler(cycle_length=cycle_length) for _ in range(5)] + players = [axl.EvolvableCycler(cycle_length=cycle_length) + for _ in range(5)] with self.assertRaises(ValueError): axl.MoranProcess(players, turns=10, mutation_method="random") axl.seed(0) - players = [axl.Cycler(cycle="CD" * random.randint(2, 10)) for _ in range(10)] + players = [axl.Cycler(cycle="CD" * random.randint(2, 10)) + for _ in range(10)] mp = axl.MoranProcess(players, turns=10, mutation_method="atomic") with self.assertRaises(TypeError): @@ -539,11 +537,7 @@ def test_init(self): """Test the initialisation process""" self.assertEqual( set(self.amp.cached_outcomes.keys()), - { - ("Cooperator", "Defector"), - ("Cooperator", "Cooperator"), - ("Defector", "Defector"), - }, + {("Cooperator", "Defector"), ("Cooperator", "Cooperator"), ("Defector", "Defector")}, ) self.assertEqual(self.amp.players, self.players) self.assertEqual(self.amp.turns, 0) diff --git a/axelrod/tests/unit/test_pickling.py b/axelrod/tests/unit/test_pickling.py index 003d83ec5..1cb14101d 100644 --- a/axelrod/tests/unit/test_pickling.py +++ b/axelrod/tests/unit/test_pickling.py @@ -11,9 +11,7 @@ # First set: special cases -PointerToWrappedStrategy = axl.strategy_transformers.FlipTransformer()( - axl.strategy_transformers.FlipTransformer()(axl.Cooperator) -) +PointerToWrappedStrategy = axl.strategy_transformers.FlipTransformer()(axl.strategy_transformers.FlipTransformer()(axl.Cooperator)) class MyDefector(axl.Player): @@ -162,9 +160,7 @@ def __init__(self): super().__init__(team=team) -TransformedMetaThue = axl.strategy_transformers.IdentityTransformer(name_prefix=None)( - MetaThue -) +TransformedMetaThue = axl.strategy_transformers.IdentityTransformer(name_prefix=None)(MetaThue) transformed_no_prefix = [ @@ -240,17 +236,10 @@ def test_parameterized_player(self): self.assert_original_equals_pickled(player) def test_sequence_player(self): - inline_transformed_thue = axl.strategy_transformers.IdentityTransformer( - name_prefix="Transformed" - )(axl.ThueMorse)() - for player in [ - axl.ThueMorse(), - axl.ThueMorseInverse(), - MetaThue(), - TransformedMetaThue(), - inline_transformed_thue, - TransformedThue(), - ]: + inline_transformed_thue = axl.strategy_transformers.IdentityTransformer(name_prefix="Transformed")(axl.ThueMorse)() + for player in [axl.ThueMorse(), axl.ThueMorseInverse(), MetaThue(), TransformedMetaThue(), + inline_transformed_thue, TransformedThue(), + ]: self.assert_equals_instance_from_pickling(player) opponents = (axl.Defector, axl.Cooperator, axl.Random, axl.CyclerCCCDCD) for opponent_class in opponents: @@ -305,9 +294,7 @@ def test_dual_transformer_regression_test(self): player_class = axl.WinStayLoseShift player_class = axl.strategy_transformers.DualTransformer()(player_class) - player_class = axl.strategy_transformers.InitialTransformer((C, D))( - player_class - ) + player_class = axl.strategy_transformers.InitialTransformer((C, D))(player_class) player_class = axl.strategy_transformers.DualTransformer()(player_class) player_class = axl.strategy_transformers.TrackHistoryTransformer()(player_class) @@ -401,9 +388,7 @@ def test_with_various_name_prefixes(self): self.assert_original_equals_pickled(new_prefix) def test_dynamic_class_no_name_prefix(self): - player = axl.strategy_transformers.FlipTransformer(name_prefix=None)( - axl.Cooperator - )() + player = axl.strategy_transformers.FlipTransformer(name_prefix=None)(axl.Cooperator)() self.assertEqual(player.__class__.__name__, "Cooperator") self.assert_original_equals_pickled(player) diff --git a/axelrod/tests/unit/test_property.py b/axelrod/tests/unit/test_property.py index 41afc1c67..fbf89cca2 100644 --- a/axelrod/tests/unit/test_property.py +++ b/axelrod/tests/unit/test_property.py @@ -13,9 +13,7 @@ from hypothesis import given, settings -stochastic_strategies = [ - s for s in axl.strategies if axl.Classifiers["stochastic"](s()) -] +stochastic_strategies = [s for s in axl.strategies if axl.Classifiers["stochastic"](s())] class TestStrategyList(unittest.TestCase): diff --git a/axelrod/tournament.py b/axelrod/tournament.py index b4ab6c4ce..26144757c 100644 --- a/axelrod/tournament.py +++ b/axelrod/tournament.py @@ -253,14 +253,8 @@ def _write_interactions_to_file(self, results, writer): ) = results for index, player_index in enumerate(index_pair): opponent_index = index_pair[index - 1] - row = [ - self.num_interactions, - player_index, - opponent_index, - repetition, - str(self.players[player_index]), - str(self.players[opponent_index]), - ] + row = [self.num_interactions, player_index, opponent_index, repetition, + str(self.players[player_index]), str(self.players[opponent_index])] history = actions_to_str([i[index] for i in interaction]) row.append(history)