diff --git a/.github/workflows/config.yml b/.github/workflows/config.yml index 043b9d664..d7005ffc3 100644 --- a/.github/workflows/config.yml +++ b/.github/workflows/config.yml @@ -39,6 +39,7 @@ jobs: python -m pip install coverage python -m pip install hypothesis==3.2 python -m pip install mypy + python -m pip install black - name: Run tests run: | coverage run --source=axelrod -m unittest discover @@ -54,6 +55,9 @@ jobs: - name: Check that all strategies are indexed run: | python run_strategy_indexer.py + - name: Check format + run: | + python -m black -l 80 . --check - name: Check that installs run: | python setup.py install diff --git a/.prepare-commit-msg.py b/.prepare-commit-msg.py index 198911e21..a69f58d59 100755 --- a/.prepare-commit-msg.py +++ b/.prepare-commit-msg.py @@ -41,7 +41,9 @@ if branch.startswith(issue_prefix): issue_number = re.match("%s(.*)" % issue_prefix, branch).group(1) - print("prepare-commit-msg: Prepending [#%s] to commit message" % issue_number) + print( + "prepare-commit-msg: Prepending [#%s] to commit message" % issue_number + ) with open(commit_msg_filepath, "r+") as f: content = f.read() diff --git a/axelrod/classifier.py b/axelrod/classifier.py index a88dbe39e..39dc2ebe6 100644 --- a/axelrod/classifier.py +++ b/axelrod/classifier.py @@ -59,12 +59,18 @@ def classify_player(self, player: Type[Player]) -> T: stochastic = Classifier[bool]("stochastic", lambda _: False) -memory_depth = Classifier[Union[float, int]]("memory_depth", lambda _: float("inf")) +memory_depth = Classifier[Union[float, int]]( + "memory_depth", lambda _: float("inf") +) makes_use_of = Classifier[Optional[Set[Text]]]("makes_use_of", lambda _: None) long_run_time = Classifier[bool]("long_run_time", lambda _: False) inspects_source = Classifier[Optional[bool]]("inspects_source", lambda _: None) -manipulates_source = Classifier[Optional[bool]]("manipulates_source", lambda _: None) -manipulates_state = Classifier[Optional[bool]]("manipulates_state", lambda _: None) +manipulates_source = Classifier[Optional[bool]]( + "manipulates_source", lambda _: None +) +manipulates_state = Classifier[Optional[bool]]( + "manipulates_state", lambda _: None +) # Should list all known classifiers. all_classifiers = [ diff --git a/axelrod/compute_finite_state_machine_memory.py b/axelrod/compute_finite_state_machine_memory.py index 0f83d3494..bcba5754b 100644 --- a/axelrod/compute_finite_state_machine_memory.py +++ b/axelrod/compute_finite_state_machine_memory.py @@ -112,7 +112,10 @@ def get_accessible_transitions( if trans.state in accessible_states: accessible_transitions[ (trans.state, trans.last_opponent_action) - ] = (trans.next_state, trans.next_action) + ] = ( + trans.next_state, + trans.next_action, + ) return accessible_transitions @@ -263,4 +266,3 @@ 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 e80da1c69..2c45b070e 100644 --- a/axelrod/evolvable_player.py +++ b/axelrod/evolvable_player.py @@ -7,6 +7,7 @@ class InsufficientParametersError(Exception): """Error indicating that insufficient parameters were specified to initialize an Evolvable Player.""" + def __init__(self, *args): super().__init__(*args) @@ -38,7 +39,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/fingerprint.py b/axelrod/fingerprint.py index 20390abfd..2ad08b4d8 100644 --- a/axelrod/fingerprint.py +++ b/axelrod/fingerprint.py @@ -178,7 +178,10 @@ def _generate_data(interactions: dict, points: list, edges: list) -> dict: """ edge_scores = [ np.mean( - [compute_final_score_per_turn(scores)[0] for scores in interactions[edge]] + [ + compute_final_score_per_turn(scores)[0] + for scores in interactions[edge] + ] ) for edge in edges ] @@ -216,7 +219,9 @@ def _reshape_data(data: dict, points: list, size: int) -> np.ndarray: class AshlockFingerprint(object): def __init__( - self, strategy: Union[type, Player], probe: Union[type, Player] = axl.TitForTat + self, + strategy: Union[type, Player], + probe: Union[type, Player] = axl.TitForTat, ) -> None: """ Parameters @@ -512,7 +517,9 @@ def analyse_cooperation_ratio(filename): opponent in each turn. The ith row corresponds to the ith opponent and the jth column the jth turn. """ - did_c = np.vectorize(lambda actions: [int(action == "C") for action in actions]) + did_c = np.vectorize( + lambda actions: [int(action == "C") for action in actions] + ) cooperation_rates = {} df = dd.read_csv(filename) @@ -521,7 +528,10 @@ def analyse_cooperation_ratio(filename): df = df[df["Player index"] == 0][["Opponent index", "Actions"]] for _, row in df.iterrows(): - opponent_index, player_history = row["Opponent index"], row["Actions"] + opponent_index, player_history = ( + row["Opponent index"], + row["Actions"], + ) if opponent_index in cooperation_rates: cooperation_rates[opponent_index].append(did_c(player_history)) else: @@ -586,7 +596,8 @@ def plot( if display_names: plt.yticks( - range(len(self.opponents)), [str(player) for player in self.opponents] + range(len(self.opponents)), + [str(player) for player in self.opponents], ) else: plt.yticks([0, len(self.opponents) - 1], [0, 1]) diff --git a/axelrod/game.py b/axelrod/game.py index 1c3278275..af30aca29 100644 --- a/axelrod/game.py +++ b/axelrod/game.py @@ -16,7 +16,9 @@ class Game(object): The numerical score attribute to all combinations of action pairs. """ - def __init__(self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1) -> None: + def __init__( + self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1 + ) -> None: """Create a new game object. Parameters @@ -30,7 +32,12 @@ def __init__(self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1) -> No p: int or float Score obtained by both player for mutual defection. """ - self.scores = {(C, C): (r, r), (D, D): (p, p), (C, D): (s, t), (D, C): (t, s)} + self.scores = { + (C, C): (r, r), + (D, D): (p, p), + (C, D): (s, t), + (D, C): (t, s), + } def RPST(self) -> Tuple[Score, Score, Score, Score]: """Returns game matrix values in Press and Dyson notation.""" diff --git a/axelrod/graph.py b/axelrod/graph.py index 9f41bde4d..6b91677b0 100644 --- a/axelrod/graph.py +++ b/axelrod/graph.py @@ -155,8 +155,9 @@ 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/history.py b/axelrod/history.py index 9e21b04c7..1edd6ee68 100644 --- a/axelrod/history.py +++ b/axelrod/history.py @@ -82,7 +82,9 @@ def __eq__(self, other): if isinstance(other, list): return self._plays == other elif isinstance(other, History): - return self._plays == other._plays and self._coplays == other._coplays + return ( + self._plays == other._plays and self._coplays == other._coplays + ) raise TypeError("Cannot compare types.") def __getitem__(self, key): diff --git a/axelrod/interaction_utils.py b/axelrod/interaction_utils.py index 82159f94c..220053ee3 100644 --- a/axelrod/interaction_utils.py +++ b/axelrod/interaction_utils.py @@ -32,7 +32,8 @@ def compute_final_score(interactions, game=None): return None final_score = tuple( - sum([score[player_index] for score in scores]) for player_index in [0, 1] + sum([score[player_index] for score in scores]) + for player_index in [0, 1] ) return final_score diff --git a/axelrod/moran.py b/axelrod/moran.py index 1c0bdc487..314f0b859 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 @@ -132,7 +132,9 @@ def __init__( if m in ["atomic", "transition"]: self.mutation_method = m else: - raise ValueError("Invalid mutation method {}".format(mutation_method)) + raise ValueError( + "Invalid mutation method {}".format(mutation_method) + ) assert (mutation_rate >= 0) and (mutation_rate <= 1) assert (noise >= 0) and (noise <= 1) mode = mode.lower() @@ -152,7 +154,9 @@ def __init__( d[str(p)] = p mutation_targets = dict() for key in sorted(keys): - mutation_targets[key] = [v for (k, v) in sorted(d.items()) if k != key] + mutation_targets[key] = [ + v for (k, v) in sorted(d.items()) if k != key + ] self.mutation_targets = mutation_targets if interaction_graph is None: @@ -171,7 +175,9 @@ def __init__( self.fitness_transformation = fitness_transformation # Map players to graph vertices self.locations = sorted(interaction_graph.vertices) - self.index = dict(zip(sorted(interaction_graph.vertices), range(len(players)))) + self.index = dict( + zip(sorted(interaction_graph.vertices), range(len(players))) + ) self.fixated = self.fixation_check() def set_players(self) -> None: @@ -193,7 +199,9 @@ 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" @@ -230,7 +238,9 @@ def death(self, index: int = None) -> int: # Select locally # index is not None in this case vertex = random.choice( - sorted(self.reproduction_graph.out_vertices(self.locations[index])) + sorted( + self.reproduction_graph.out_vertices(self.locations[index]) + ) ) i = self.index[vertex] return i @@ -476,7 +486,10 @@ class ApproximateMoranProcess(MoranProcess): """ def __init__( - self, players: List[Player], cached_outcomes: dict, mutation_rate: float = 0 + self, + players: List[Player], + cached_outcomes: dict, + mutation_rate: float = 0, ) -> None: """ Parameters @@ -511,7 +524,9 @@ def score_all(self) -> List: scores = [0] * N for i in range(N): for j in range(i + 1, N): - player_names = tuple([str(self.players[i]), str(self.players[j])]) + player_names = tuple( + [str(self.players[i]), str(self.players[j])] + ) cached_score = self._get_scores_from_cache(player_names) scores[i] += cached_score[0] diff --git a/axelrod/player.py b/axelrod/player.py index 61cc609af..325350f74 100644 --- a/axelrod/player.py +++ b/axelrod/player.py @@ -72,7 +72,9 @@ def __eq__(self, other): if self.__repr__() != other.__repr__(): return False - for attribute in set(list(self.__dict__.keys()) + list(other.__dict__.keys())): + for attribute in set( + list(self.__dict__.keys()) + list(other.__dict__.keys()) + ): value = getattr(self, attribute, None) other_value = getattr(other, attribute, None) @@ -86,14 +88,20 @@ def __eq__(self, other): ): # Split the original generator so it is not touched generator, original_value = itertools.tee(value) - other_generator, original_other_value = itertools.tee(other_value) + other_generator, original_other_value = itertools.tee( + other_value + ) if isinstance(value, types.GeneratorType): setattr(self, attribute, (ele for ele in original_value)) - setattr(other, attribute, (ele for ele in original_other_value)) + setattr( + other, attribute, (ele for ele in original_other_value) + ) else: setattr(self, attribute, itertools.cycle(original_value)) - setattr(other, attribute, itertools.cycle(original_other_value)) + setattr( + other, attribute, itertools.cycle(original_other_value) + ) for _ in range(200): try: @@ -128,7 +136,9 @@ def __repr__(self): Appends the `__init__` parameters to the strategy's name.""" name = self.name prefix = ": " - gen = (value for value in self.init_kwargs.values() if value is not None) + gen = ( + value for value in self.init_kwargs.values() if value is not None + ) for value in gen: try: if issubclass(value, Player): diff --git a/axelrod/plot.py b/axelrod/plot.py index edc596529..dd30f23ec 100644 --- a/axelrod/plot.py +++ b/axelrod/plot.py @@ -97,7 +97,9 @@ def _winplot_dataset(self): # Sort wins by median wins = self.result_set.wins medians = map(median, wins) - medians = sorted([(m, i) for (i, m) in enumerate(medians)], reverse=True) + medians = sorted( + [(m, i) for (i, m) in enumerate(medians)], reverse=True + ) # Reorder and grab names wins = [wins[x[-1]] for x in medians] ranked_names = [str(self.players[x[-1]]) for x in medians] @@ -324,7 +326,9 @@ def save_all_plots( pbar = tqdm.tqdm(total=total, desc="Obtaining plots") for method, name in plots: - f = getattr(self, method)(title="{} - {}".format(title_prefix, name)) + f = getattr(self, method)( + title="{} - {}".format(title_prefix, name) + ) path = pathlib.Path("{}_{}.{}".format(prefix, method, filetype)) f.savefig(axl_filename(path)) plt.close(f) diff --git a/axelrod/result_set.py b/axelrod/result_set.py index 36e33a4b7..e4be569f2 100644 --- a/axelrod/result_set.py +++ b/axelrod/result_set.py @@ -118,9 +118,15 @@ def _reshape_out( alternative=0, ) - self.wins = self._reshape_two_dim_list(sum_per_player_repetition_df["Win"]) - self.scores = self._reshape_two_dim_list(sum_per_player_repetition_df["Score"]) - self.normalised_scores = self._reshape_two_dim_list(normalised_scores_series) + self.wins = self._reshape_two_dim_list( + sum_per_player_repetition_df["Win"] + ) + self.scores = self._reshape_two_dim_list( + sum_per_player_repetition_df["Score"] + ) + self.normalised_scores = self._reshape_two_dim_list( + normalised_scores_series + ) self.cooperation = self._build_cooperation( sum_per_player_opponent_df["Cooperation count"] @@ -133,7 +139,9 @@ def _reshape_out( self.state_distribution = self._build_state_distribution( sum_per_player_opponent_df[columns] ) - self.normalised_state_distribution = self._build_normalised_state_distribution() + self.normalised_state_distribution = ( + self._build_normalised_state_distribution() + ) columns = [ "CC to C count", @@ -167,7 +175,9 @@ def _reshape_out( self.ranked_names = self._build_ranked_names() self.payoff_matrix = self._build_summary_matrix(self.payoffs) - self.payoff_stddevs = self._build_summary_matrix(self.payoffs, func=np.std) + self.payoff_stddevs = self._build_summary_matrix( + self.payoffs, func=np.std + ) self.payoff_diffs_means = self._build_payoff_diffs_means() self.cooperating_rating = self._build_cooperating_rating() @@ -267,7 +277,9 @@ def _build_good_partner_matrix(self, good_partner_series): # interactions. row.append(0) else: - row.append(good_partner_dict.get((player_index, opponent_index), 0)) + row.append( + good_partner_dict.get((player_index, opponent_index), 0) + ) good_partner_matrix.append(row) return good_partner_matrix @@ -335,13 +347,17 @@ def _build_normalised_state_distribution(self): for counter in player: total = sum(counter.values()) counters.append( - Counter({key: value / total for key, value in counter.items()}) + Counter( + {key: value / total for key, value in counter.items()} + ) ) normalised_state_distribution.append(counters) return normalised_state_distribution @update_progress_bar - def _build_state_to_action_distribution(self, state_to_action_distribution_series): + def _build_state_to_action_distribution( + self, state_to_action_distribution_series + ): state_to_action_key_map = { "CC to C count": ((C, C), C), "CC to D count": ((C, C), D), @@ -397,8 +413,12 @@ def _build_normalised_state_to_action_distribution(self): return normalised_state_to_action_distribution @update_progress_bar - def _build_initial_cooperation_count(self, initial_cooperation_count_series): - initial_cooperation_count_dict = initial_cooperation_count_series.to_dict() + def _build_initial_cooperation_count( + self, initial_cooperation_count_series + ): + initial_cooperation_count_dict = ( + initial_cooperation_count_series.to_dict() + ) initial_cooperation_count = [ initial_cooperation_count_dict.get(player_index, 0) for player_index in range(self.num_players) @@ -428,7 +448,8 @@ def _build_initial_cooperation_rate(self, interactions_series): warnings.simplefilter("ignore") initial_cooperation_rate = list( np.nan_to_num( - np.array(self.initial_cooperation_count) / interactions_array + np.array(self.initial_cooperation_count) + / interactions_array ) ) return initial_cooperation_rate @@ -454,7 +475,9 @@ def _build_eigenmoses_rating(self): The eigenmoses rating as defined in: http://www.scottaaronson.com/morality.pdf """ - eigenvector, eigenvalue = eigen.principal_eigenvector(self.vengeful_cooperation) + eigenvector, eigenvalue = eigen.principal_eigenvector( + self.vengeful_cooperation + ) return eigenvector.tolist() @@ -578,7 +601,9 @@ def _build_tasks(self, df): ] sum_per_player_opponent_task = df.groupby(groups)[columns].sum() - ignore_self_interactions_task = df["Player index"] != df["Opponent index"] + ignore_self_interactions_task = ( + df["Player index"] != df["Opponent index"] + ) adf = df[ignore_self_interactions_task] groups = ["Player index", "Repetition"] @@ -592,7 +617,9 @@ def _build_tasks(self, df): groups = ["Player index"] column = "Initial cooperation" initial_cooperation_count_task = adf.groupby(groups)[column].sum() - interactions_count_task = adf.groupby("Player index")["Player index"].count() + interactions_count_task = adf.groupby("Player index")[ + "Player index" + ].count() return ( mean_per_reps_player_opponent_task, @@ -643,8 +670,12 @@ def list_equal_with_nans(v1: List[float], v2: List[float]) -> bool: self.cooperating_rating == other.cooperating_rating, self.good_partner_matrix == other.good_partner_matrix, self.good_partner_rating == other.good_partner_rating, - list_equal_with_nans(self.eigenmoses_rating, other.eigenmoses_rating), - list_equal_with_nans(self.eigenjesus_rating, other.eigenjesus_rating), + list_equal_with_nans( + self.eigenmoses_rating, other.eigenmoses_rating + ), + list_equal_with_nans( + self.eigenjesus_rating, other.eigenjesus_rating + ), ] ) @@ -714,7 +745,9 @@ def summarise(self): rates = [] for state in states: counts = [ - counter[(state, C)] for counter in player if counter[(state, C)] > 0 + counter[(state, C)] + for counter in player + if counter[(state, C)] > 0 ] if len(counts) > 0: @@ -737,7 +770,9 @@ def summarise(self): summary_data = [] for rank, i in enumerate(self.ranking): - data = list(summary_measures[i]) + state_prob[i] + state_to_C_prob[i] + data = ( + list(summary_measures[i]) + state_prob[i] + state_to_C_prob[i] + ) summary_data.append(self.player(rank, *data)) return summary_data diff --git a/axelrod/strategies/__init__.py b/axelrod/strategies/__init__.py index 1e8e1a4ff..fe8fbef88 100644 --- a/axelrod/strategies/__init__.py +++ b/axelrod/strategies/__init__.py @@ -89,7 +89,9 @@ short_run_time_strategies = [ s for s in strategies if not Classifiers["long_run_time"](s()) ] -cheating_strategies = [s for s in all_strategies if not Classifiers.obey_axelrod(s())] +cheating_strategies = [ + s for s in all_strategies if not Classifiers.obey_axelrod(s()) +] ordinary_strategies = strategies # This is a legacy and will be removed diff --git a/axelrod/strategies/_filters.py b/axelrod/strategies/_filters.py index c9c199bf7..2dc7a88b6 100644 --- a/axelrod/strategies/_filters.py +++ b/axelrod/strategies/_filters.py @@ -155,15 +155,24 @@ class ExampleStrategy(Player): ), "manipulates_state": FilterFunction( function=passes_operator_filter, - kwargs={"classifier_key": "manipulates_state", "operator": operator.eq}, + kwargs={ + "classifier_key": "manipulates_state", + "operator": operator.eq, + }, ), "manipulates_source": FilterFunction( function=passes_operator_filter, - kwargs={"classifier_key": "manipulates_source", "operator": operator.eq}, + kwargs={ + "classifier_key": "manipulates_source", + "operator": operator.eq, + }, ), "inspects_source": FilterFunction( function=passes_operator_filter, - kwargs={"classifier_key": "inspects_source", "operator": operator.eq}, + kwargs={ + "classifier_key": "inspects_source", + "operator": operator.eq, + }, ), "memory_depth": FilterFunction( function=passes_operator_filter, @@ -178,7 +187,8 @@ class ExampleStrategy(Player): kwargs={"classifier_key": "memory_depth", "operator": operator.le}, ), "makes_use_of": FilterFunction( - function=passes_in_list_filter, kwargs={"classifier_key": "makes_use_of"} + function=passes_in_list_filter, + kwargs={"classifier_key": "makes_use_of"}, ), } diff --git a/axelrod/strategies/_strategies.py b/axelrod/strategies/_strategies.py index 48cd04ab8..9e9b0523a 100644 --- a/axelrod/strategies/_strategies.py +++ b/axelrod/strategies/_strategies.py @@ -172,7 +172,12 @@ Prober4, RemorsefulProber, ) -from .punisher import InversePunisher, LevelPunisher, Punisher, TrickyLevelPunisher +from .punisher import ( + InversePunisher, + LevelPunisher, + Punisher, + TrickyLevelPunisher, +) from .qlearner import ( ArrogantQLearner, CautiousQLearner, diff --git a/axelrod/strategies/adaptor.py b/axelrod/strategies/adaptor.py index 2648b2704..62407d60a 100644 --- a/axelrod/strategies/adaptor.py +++ b/axelrod/strategies/adaptor.py @@ -39,12 +39,13 @@ 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. + self.s = 0.0 def strategy(self, opponent: Player) -> Action: if self.history: @@ -54,7 +55,8 @@ 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 @@ -74,10 +76,10 @@ class AdaptorBrief(AbstractAdaptor): def __init__(self) -> None: delta = { - (C, C): 0., # R + (C, C): 0.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) @@ -96,9 +98,9 @@ class AdaptorLong(AbstractAdaptor): def __init__(self) -> None: delta = { - (C, C): 0., # R + (C, C): 0.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 2d3a1bc85..a17df6a7b 100644 --- a/axelrod/strategies/ann.py +++ b/axelrod/strategies/ann.py @@ -3,7 +3,11 @@ 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 @@ -110,7 +114,10 @@ def compute_features(player: Player, opponent: Player) -> List[int]: def activate( - bias: List[float], hidden: List[float], output: List[float], inputs: List[int] + bias: List[float], + hidden: List[float], + output: List[float], + inputs: List[int], ) -> float: """ Compute the output of the neural network: @@ -191,8 +198,7 @@ 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 @@ -222,20 +228,31 @@ 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 @@ -243,22 +260,36 @@ 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. / size + mutation_probability = 10.0 / 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): @@ -269,13 +300,19 @@ def mutate_weights(weights, num_features, num_hidden, mutation_probability, 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): if other.__class__ != self.__class__: - raise TypeError("Crossover must be between the same player classes.") + raise TypeError( + "Crossover must be between the same player classes." + ) weights = crossover_lists(self.weights, other.weights) return self.create_new(weights=weights) @@ -298,9 +335,8 @@ 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): @@ -321,9 +357,8 @@ 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): @@ -344,7 +379,5 @@ 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 f9dab0b94..e97e3ab96 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,12 +266,14 @@ 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 @@ -436,25 +438,34 @@ def strategy(self, opponent: Player) -> Action: # Check if opponent plays randomly, if so, defect for the rest of the game p_value = chisquare([opponent.cooperations, opponent.defections]).pvalue - self.opponent_is_random = (p_value >= self.alpha) or self.opponent_is_random + self.opponent_is_random = ( + p_value >= self.alpha + ) or self.opponent_is_random 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 return C if self.next_random_defection_turn is None: - self.next_random_defection_turn = random.randint(5, 15) + len(self.history) + self.next_random_defection_turn = random.randint(5, 15) + len( + self.history + ) if len(self.history) == self.next_random_defection_turn: # resample the next defection turn - self.next_random_defection_turn = random.randint(5, 15) + len(self.history) + self.next_random_defection_turn = random.randint(5, 15) + len( + self.history + ) return D return C @@ -485,6 +496,7 @@ 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 @@ -588,7 +600,27 @@ 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__() @@ -618,7 +650,9 @@ def strategy(self, opponent: Player) -> Action: else: # TFT return D if opponent.history[-1] == D else C - A = self.score_history(self.history[-3:], opponent.history[-3:], self.score_map) + A = self.score_history( + self.history[-3:], opponent.history[-3:], self.score_map + ) if A in self.As: return D return C @@ -869,7 +903,9 @@ def strategy(self, opponent: Player) -> Action: return opponent.history[-1] if round_number % 15 == 0: - p_value = chisquare([opponent.cooperations, opponent.defections]).pvalue + p_value = chisquare( + [opponent.cooperations, opponent.defections] + ).pvalue self.opponent_is_random = p_value >= self.alpha if self.opponent_is_random: @@ -1003,8 +1039,10 @@ 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 50e4e18ee..16bb8908f 100644 --- a/axelrod/strategies/axelrod_second.py +++ b/axelrod/strategies/axelrod_second.py @@ -61,6 +61,7 @@ def strategy(self, opponent: Player) -> Action: return D return C + class SecondByEatherley(Player): """ Strategy submitted to Axelrod's second tournament by Graham Eatherley. @@ -334,8 +335,12 @@ def __init__(self): self.opponent_consecutive_defections = 0 # equal to S variable self.one_turn_after_good_defection_ratio = 5 # equal to AD variable self.two_turns_after_good_defection_ratio = 0 # equal to NO variable - self.one_turn_after_good_defection_ratio_count = 1 # equal to AK variable - self.two_turns_after_good_defection_ratio_count = 1 # equal to NK variable + self.one_turn_after_good_defection_ratio_count = ( + 1 # equal to AK variable + ) + self.two_turns_after_good_defection_ratio_count = ( + 1 # equal to NK variable + ) # All above variables correspond to those in original Fotran Code self.dict = {C: 0, D: 1} @@ -360,7 +365,12 @@ def update_state(self, opponent): ) + (3 - (3 * self.dict[opponent.history[-1]])) + (2 * self.dict[self.history[-1]]) - - ((self.dict[opponent.history[-1]] * self.dict[self.history[-1]])) + - ( + ( + self.dict[opponent.history[-1]] + * self.dict[self.history[-1]] + ) + ) ) / (self.two_turns_after_good_defection_ratio_count + 1) self.two_turns_after_good_defection_ratio_count += 1 elif self.num_turns_after_good_defection == 1: @@ -372,7 +382,10 @@ def update_state(self, opponent): ) + (3 - (3 * self.dict[opponent.history[-1]])) + (2 * self.dict[self.history[-1]]) - - (self.dict[opponent.history[-1]] * self.dict[self.history[-1]]) + - ( + self.dict[opponent.history[-1]] + * self.dict[self.history[-1]] + ) ) / (self.one_turn_after_good_defection_ratio_count + 1) self.one_turn_after_good_defection_ratio_count += 1 @@ -409,7 +422,10 @@ def strategy(self, opponent: Player) -> Action: return D if (current_score[0] / ((len(self.history)) + 1)) >= 1.75: probability = ( - (0.25 + ((opponent.cooperations + 1) / ((len(self.history)) + 1))) + ( + 0.25 + + ((opponent.cooperations + 1) / ((len(self.history)) + 1)) + ) - (self.opponent_consecutive_defections * 0.25) + ((current_score[0] - current_score[1]) / 100) + (4 / ((len(self.history)) + 1)) @@ -525,7 +541,12 @@ class SecondByKluepfel(Player): def __init__(self): super().__init__() - self.cd_counts, self.dd_counts, self.dc_counts, self.cc_counts = 0, 0, 0, 0 + self.cd_counts, self.dd_counts, self.dc_counts, self.cc_counts = ( + 0, + 0, + 0, + 0, + ) def strategy(self, opponent: Player) -> Action: # First update the response matrix. @@ -543,7 +564,9 @@ def strategy(self, opponent: Player) -> Action: # Check for randomness if len(self.history) > 26: - if self.cd_counts >= (self.cd_counts + self.dd_counts) / 2 - 0.75 * np.sqrt( + if self.cd_counts >= ( + self.cd_counts + self.dd_counts + ) / 2 - 0.75 * np.sqrt( self.cd_counts + self.dd_counts ) and self.dc_counts >= ( self.dc_counts + self.cc_counts @@ -983,7 +1006,10 @@ def strategy(self, opponent: Player) -> Action: if self.forgive_flag: self.forgive_flag = False self.defect_padding = 0 - if self.grudge < len(self.history) + 1 and opponent.history[-1] == D: + if ( + self.grudge < len(self.history) + 1 + and opponent.history[-1] == D + ): # Then override self.grudge += 20 return self.try_return(C) @@ -1110,7 +1136,9 @@ def __init__(self): self.mode = "Normal" self.recorded_defects = 0 # Count opponent defects after turn 1 self.exit_defect_meter = 0 # When >= 11, then exit defect mode. - self.coops_in_first_36 = None # On turn 37, count cooperations in first 36 + self.coops_in_first_36 = ( + None # On turn 37, count cooperations in first 36 + ) self.was_defective = False # Previously in Defect mode self.prob = 0.25 # After turn 37, probability that we'll defect @@ -1120,7 +1148,9 @@ def __init__(self): self.more_coop = 0 # This schedules cooperation for future turns # Initial last_generous_n_turns_ago to 3 because this counts up and # triggers a strategy change at 2. - self.last_generous_n_turns_ago = 3 # How many tuns ago was a "generous" move + self.last_generous_n_turns_ago = ( + 3 # How many tuns ago was a "generous" move + ) self.burned = False self.defect_streak = 0 @@ -1129,7 +1159,9 @@ def __init__(self): 0, ] # Counters that get (almost) alternatively incremented. self.parity_bit = 0 # Which parity_streak to increment - self.parity_limit = 5 # When a parity streak hits this limit, alter strategy. + self.parity_limit = ( + 5 # When a parity streak hits this limit, alter strategy. + ) self.parity_hits = 0 # Counts how many times a parity_limit was hit. # After hitting parity_hits 8 times, lower parity_limit to 3. @@ -1168,7 +1200,9 @@ def calculate_chi_squared(self, turn): denom = turn - 2 expected_matrix = ( - np.outer(self.move_history.sum(axis=1), self.move_history.sum(axis=0)) + np.outer( + self.move_history.sum(axis=1), self.move_history.sum(axis=0) + ) / denom ) @@ -1177,7 +1211,9 @@ def calculate_chi_squared(self, turn): for j in range(2): expect = expected_matrix[i, j] if expect > 1.0: - chi_squared += (expect - self.move_history[i, j]) ** 2 / expect + chi_squared += ( + expect - self.move_history[i, j] + ) ** 2 / expect return chi_squared @@ -1199,7 +1235,10 @@ def detect_random(self, turn): if self.move_history[0, 0] / denom >= 0.8: return False - if self.recorded_defects / denom < 0.25 or self.recorded_defects / denom > 0.75: + if ( + self.recorded_defects / denom < 0.25 + or self.recorded_defects / denom > 0.75 + ): return False if self.calculate_chi_squared(turn) > 3: @@ -1291,7 +1330,11 @@ def strategy(self, opponent: Player) -> Action: # Only enter Fair-weather mode if the opponent Cooperated the first 37 # turns then Defected on the 38th. - if turn == 38 and opponent.history[-1] == D and opponent.cooperations == 36: + if ( + turn == 38 + and opponent.history[-1] == D + and opponent.cooperations == 36 + ): self.mode = "Fair-weather" return self.try_return(to_return=C, lower_flags=False) @@ -1312,7 +1355,9 @@ def strategy(self, opponent: Player) -> Action: self.parity_streak[ self.parity_bit ] = 0 # Reset `parity_streak` when we hit the limit. - self.parity_hits += 1 # Keep track of how many times we hit the limit. + self.parity_hits += ( + 1 # Keep track of how many times we hit the limit. + ) if self.parity_hits >= 8: # After 8 times, lower the limit. self.parity_limit = 3 return self.try_return( @@ -1539,7 +1584,9 @@ def strategy(self, opponent: Player) -> Action: recent_history[-go_back] = opponent.history[-go_back] return random_choice( - self.prob_coop[(recent_history[-3], recent_history[-2], recent_history[-1])] + self.prob_coop[ + (recent_history[-3], recent_history[-2], recent_history[-1]) + ] ) @@ -1725,7 +1772,10 @@ def strategy(self, opponent: Player) -> Action: else: self.def_after_ab_count += 1 self.streak_needed = ( - np.floor(20.0 * self.def_after_ab_count / self.coop_after_ab_count) + 1 + np.floor( + 20.0 * self.def_after_ab_count / self.coop_after_ab_count + ) + + 1 ) self.current_streak = 0 return C @@ -1826,7 +1876,9 @@ def strategy(self, opponent: Player) -> Action: # Update history if turn >= 3: - self.count_them_us_them[(them_three_ago, us_two_ago, them_two_ago)] += 1 + self.count_them_us_them[ + (them_three_ago, us_two_ago, them_two_ago) + ] += 1 if ( self.count_them_us_them[(them_two_ago, us_last, C)] @@ -1889,7 +1941,9 @@ def __init__(self) -> None: (10, D, 7, C), ) - super().__init__(transitions=transitions, initial_state=0, initial_action=C) + super().__init__( + transitions=transitions, initial_state=0, initial_action=C + ) class SecondByMikkelson(FSMPlayer): @@ -2126,6 +2180,8 @@ 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/backstabber.py b/axelrod/strategies/backstabber.py index b3a522ae2..70663b3ed 100644 --- a/axelrod/strategies/backstabber.py +++ b/axelrod/strategies/backstabber.py @@ -99,7 +99,9 @@ def _opponent_triggers_alt_strategy(opponent: Player) -> bool: return before_alt_strategy < current_round <= last_round_of_alt_strategy -def _opponent_defected_in_first_n_rounds(opponent: Player, first_n_rounds: int) -> bool: +def _opponent_defected_in_first_n_rounds( + opponent: Player, first_n_rounds: int +) -> bool: """ If opponent defected in the first N rounds, return True. Else return False. """ diff --git a/axelrod/strategies/bush_mosteller.py b/axelrod/strategies/bush_mosteller.py index d6ed5adf3..ec49e1069 100644 --- a/axelrod/strategies/bush_mosteller.py +++ b/axelrod/strategies/bush_mosteller.py @@ -66,7 +66,10 @@ def __init__( self._c_prob, self._d_prob = c_prob, d_prob self._init_c_prob, self._init_d_prob = c_prob, d_prob self._aspiration_level = abs( - (max(self.match_attributes["game"].RPST()) / aspiration_level_divider) + ( + max(self.match_attributes["game"].RPST()) + / aspiration_level_divider + ) ) self._stimulus = 0.0 @@ -108,7 +111,9 @@ def stimulus_update(self, opponent: Player): ) elif self._stimulus < 0: - self._c_prob += self._learning_rate * self._stimulus * self._c_prob + self._c_prob += ( + self._learning_rate * self._stimulus * self._c_prob + ) # Updates probability following previous choice D if self.history[-1] == D: @@ -118,7 +123,9 @@ def stimulus_update(self, opponent: Player): ) elif self._stimulus < 0: - self._d_prob += self._learning_rate * self._stimulus * self._d_prob + self._d_prob += ( + self._learning_rate * self._stimulus * self._d_prob + ) def strategy(self, opponent: Player) -> Action: diff --git a/axelrod/strategies/calculator.py b/axelrod/strategies/calculator.py index 8ac9b59d0..92f86cb76 100644 --- a/axelrod/strategies/calculator.py +++ b/axelrod/strategies/calculator.py @@ -36,8 +36,9 @@ 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 509141717..8e3859228 100644 --- a/axelrod/strategies/cycler.py +++ b/axelrod/strategies/cycler.py @@ -4,7 +4,11 @@ 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 @@ -109,25 +113,27 @@ 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 @classmethod - def _normalize_parameters(cls, cycle=None, cycle_length=None) -> Tuple[str, int]: + 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 @@ -137,7 +143,9 @@ def _generate_random_cycle(cls, cycle_length: int) -> str: """ Generate a sequence of random moves """ - return actions_to_str(random.choice(actions) for _ in range(cycle_length)) + return actions_to_str( + random.choice(actions) for _ in range(cycle_length) + ) def mutate(self) -> EvolvablePlayer: """ @@ -147,7 +155,9 @@ 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 @@ -159,7 +169,9 @@ def crossover(self, other) -> EvolvablePlayer: Creates and returns a new Player instance with a single crossover point. """ if other.__class__ != self.__class__: - raise TypeError("Crossover must be between the same player classes.") + raise TypeError( + "Crossover must be between the same player classes." + ) cycle_list = crossover_lists(self.cycle, other.cycle) cycle = "".join(cycle_list) cycle, _ = self._normalize_parameters(cycle) diff --git a/axelrod/strategies/dbs.py b/axelrod/strategies/dbs.py index dafdb8ec2..46e21b82c 100644 --- a/axelrod/strategies/dbs.py +++ b/axelrod/strategies/dbs.py @@ -267,7 +267,9 @@ def strategy(self, opponent: Player) -> Action: if r_minus_in_Rd: self.v += 1 # If the number of violations is superior to a threshold, clean Rd. - if (self.v > self.reject_threshold) or (r_plus_in_Rc and r_minus_in_Rd): + if (self.v > self.reject_threshold) or ( + r_plus_in_Rc and r_minus_in_Rd + ): self.Rd.clear() self.v = 0 @@ -275,7 +277,9 @@ def strategy(self, opponent: Player) -> Action: Rp = {} all_cond = [(C, C), (C, D), (D, C), (D, D)] for outcome in all_cond: - if (outcome not in self.Rc.keys()) and (outcome not in self.Rd.keys()): + if (outcome not in self.Rc.keys()) and ( + outcome not in self.Rd.keys() + ): # Compute opponent's C answer probability. Rp[outcome] = self.compute_prob_rule(outcome, self.alpha) @@ -328,8 +332,12 @@ def get_siblings(self): siblings which are DeterministicNodes, their depth is equal to current node depth's + 1. """ - opponent_c_choice = DeterministicNode(self.own_action, C, self.depth + 1) - opponent_d_choice = DeterministicNode(self.own_action, D, self.depth + 1) + opponent_c_choice = DeterministicNode( + self.own_action, C, self.depth + 1 + ) + opponent_d_choice = DeterministicNode( + self.own_action, D, self.depth + 1 + ) return opponent_c_choice, opponent_d_choice def is_stochastic(self): @@ -355,8 +363,12 @@ def get_siblings(self, policy): of the same depth as the current node. Their probabilities pC are defined by the policy argument. """ - c_choice = StochasticNode(C, policy[(self.action1, self.action2)], self.depth) - d_choice = StochasticNode(D, policy[(self.action1, self.action2)], self.depth) + c_choice = StochasticNode( + C, policy[(self.action1, self.action2)], self.depth + ) + d_choice = StochasticNode( + D, policy[(self.action1, self.action2)], self.depth + ) return c_choice, d_choice def is_stochastic(self): @@ -402,7 +414,9 @@ def minimax_tree_search(begin_node, policy, max_depth): # The stochastic node value is the expected value of siblings. node_value = begin_node.pC * minimax_tree_search( siblings[0], policy, max_depth - ) + (1 - begin_node.pC) * minimax_tree_search(siblings[1], policy, max_depth) + ) + (1 - begin_node.pC) * minimax_tree_search( + siblings[1], policy, max_depth + ) return node_value else: # Deterministic node if begin_node.depth == max_depth: @@ -434,7 +448,9 @@ def move_gen(outcome, policy, depth_search_tree=5): using tree-search procedure. """ current_node = DeterministicNode(outcome[0], outcome[1], depth=0) - values_of_choices = minimax_tree_search(current_node, policy, depth_search_tree) + values_of_choices = minimax_tree_search( + current_node, policy, depth_search_tree + ) # Returns the Action which correspond to the best choice in terms of # expected value. In case value(C) == value(D), returns C. actions_tuple = (C, D) diff --git a/axelrod/strategies/defector.py b/axelrod/strategies/defector.py index 4e05184f8..56c6fa3a7 100644 --- a/axelrod/strategies/defector.py +++ b/axelrod/strategies/defector.py @@ -56,6 +56,9 @@ def strategy(self, opponent: Player) -> Action: Defect if opponent has cooperated at least once in the past and has defected for the last 3 turns in a row. """ - if opponent.history.cooperations > 0 and opponent.history[-3:] == [D] * 3: + if ( + opponent.history.cooperations > 0 + and opponent.history[-3:] == [D] * 3 + ): return C return D diff --git a/axelrod/strategies/finite_state_machines.py b/axelrod/strategies/finite_state_machines.py index e7bdd7f63..d942e8642 100644 --- a/axelrod/strategies/finite_state_machines.py +++ b/axelrod/strategies/finite_state_machines.py @@ -4,7 +4,11 @@ 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 @@ -68,7 +72,9 @@ def state_transitions(self) -> dict: return self._state_transitions.copy() def transitions(self) -> list: - return [[x[0], x[1], y[0], y[1]] for x, y in self._state_transitions.items()] + return [ + [x[0], x[1], y[0], y[1]] for x, y in self._state_transitions.items() + ] def move(self, opponent_action: Action) -> Action: """Computes the response move and changes state.""" @@ -111,7 +117,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 @@ -150,23 +156,33 @@ 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: @@ -174,12 +190,25 @@ def normalize_transitions(cls, transitions: Sequence[Sequence]) -> Tuple[Tuple[A 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") - transitions, initial_state, initial_action = cls.random_params(num_states) + 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 return transitions, initial_state, initial_action, num_states @@ -189,7 +218,9 @@ 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: @@ -230,7 +261,9 @@ 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. @@ -251,8 +284,12 @@ 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()) + raise TypeError( + "Crossover must be between the same player classes." + ) + transitions = self.crossover_rows( + self.fsm.transitions(), other.fsm.transitions() + ) transitions = self.normalize_transitions(transitions) return self.create_new(transitions=transitions) @@ -270,22 +307,28 @@ 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.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.""" diff --git a/axelrod/strategies/gambler.py b/axelrod/strategies/gambler.py index f127ce0f4..847db5806 100644 --- a/axelrod/strategies/gambler.py +++ b/axelrod/strategies/gambler.py @@ -13,7 +13,13 @@ 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") @@ -56,7 +62,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, @@ -64,7 +70,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__( @@ -72,7 +78,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, @@ -103,7 +109,9 @@ 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/gobymajority.py b/axelrod/strategies/gobymajority.py index e79efca0a..137c2640c 100644 --- a/axelrod/strategies/gobymajority.py +++ b/axelrod/strategies/gobymajority.py @@ -61,7 +61,9 @@ def __init__( self.memory = self.classifier["memory_depth"] else: self.memory = 0 - self.name = "Go By Majority" + (self.memory > 0) * (": %i" % self.memory) + self.name = "Go By Majority" + (self.memory > 0) * ( + ": %i" % self.memory + ) if self.soft: self.name = "Soft " + self.name else: diff --git a/axelrod/strategies/grudger.py b/axelrod/strategies/grudger.py index 61215bb9a..1473b8def 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 8ae2ed811..9df9bd251 100644 --- a/axelrod/strategies/hmm.py +++ b/axelrod/strategies/hmm.py @@ -3,7 +3,12 @@ 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 @@ -57,7 +62,11 @@ class SimpleHMM(object): """ def __init__( - self, transitions_C, transitions_D, emission_probabilities, initial_state + self, + transitions_C, + transitions_D, + emission_probabilities, + initial_state, ) -> None: """ Params @@ -147,7 +156,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: @@ -158,7 +167,10 @@ 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 @@ -189,6 +201,7 @@ def strategy(self, opponent: Player) -> Action: class EvolvableHMMPlayer(HMMPlayer, EvolvablePlayer): """Evolvable version of HMMPlayer.""" + name = "EvolvableHMMPlayer" def __init__( @@ -199,17 +212,34 @@ 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, @@ -218,17 +248,38 @@ 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)): @@ -239,7 +290,15 @@ def _normalize_parameters(cls, transitions_C=None, transitions_D=None, emission_ 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): @@ -252,7 +311,13 @@ 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): @@ -267,11 +332,14 @@ 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() @@ -288,15 +356,22 @@ def mutate(self): def crossover(self, other): if other.__class__ != self.__class__: - raise TypeError("Crossover must be between the same player classes.") - transitions_C = crossover_lists(self.hmm.transitions_C, other.hmm.transitions_C) - transitions_D = crossover_lists(self.hmm.transitions_D, other.hmm.transitions_D) + raise TypeError( + "Crossover must be between the same player classes." + ) + 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): @@ -313,12 +388,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 @@ -331,7 +406,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/human.py b/axelrod/strategies/human.py index 753194248..385f878c1 100644 --- a/axelrod/strategies/human.py +++ b/axelrod/strategies/human.py @@ -36,7 +36,9 @@ def validate(self, document) -> None: text = document.text if text and text.upper() not in ["C", "D"]: - raise ValidationError(message="Action must be C or D", cursor_position=0) + raise ValidationError( + message="Action must be C or D", cursor_position=0 + ) class Human(Player): @@ -84,10 +86,14 @@ def _history_toolbar(self): Described at http://python-prompt-toolkit.readthedocs.io/en/latest/pages/building_prompts.html#adding-a-bottom-toolbar """ my_history = [self.symbols[action] for action in self.history] - opponent_history = [self.symbols[action] for action in self.history.coplays] + opponent_history = [ + self.symbols[action] for action in self.history.coplays + ] history = list(zip(my_history, opponent_history)) if self.history: - content = "History ({}, opponent): {}".format(self.human_name, history) + content = "History ({}, opponent): {}".format( + self.human_name, history + ) else: content = "" return content diff --git a/axelrod/strategies/hunter.py b/axelrod/strategies/hunter.py index fe2b39fa1..7676da443 100644 --- a/axelrod/strategies/hunter.py +++ b/axelrod/strategies/hunter.py @@ -27,7 +27,10 @@ class DefectorHunter(Player): } def strategy(self, opponent: Player) -> Action: - if len(self.history) >= 4 and len(opponent.history) == opponent.defections: + if ( + len(self.history) >= 4 + and len(opponent.history) == opponent.defections + ): return D return C @@ -52,7 +55,10 @@ class CooperatorHunter(Player): } def strategy(self, opponent: Player) -> Action: - if len(self.history) >= 4 and len(opponent.history) == opponent.cooperations: + if ( + len(self.history) >= 4 + and len(opponent.history) == opponent.cooperations + ): return D return C @@ -250,6 +256,8 @@ def strategy(self, opponent: Player) -> Action: probabilities.append(self.countCC / self.cooperations) if self.defections > 5: probabilities.append(self.countDD / self.defections) - if probabilities and all([abs(p - 0.5) < 0.25 for p in probabilities]): + if probabilities and all( + [abs(p - 0.5) < 0.25 for p in probabilities] + ): return D return C diff --git a/axelrod/strategies/lookerup.py b/axelrod/strategies/lookerup.py index b66d06293..4b6f17d06 100644 --- a/axelrod/strategies/lookerup.py +++ b/axelrod/strategies/lookerup.py @@ -6,7 +6,11 @@ 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 @@ -101,7 +105,11 @@ def _raise_error_for_bad_lookup_dict(self): @classmethod def from_pattern( - cls, pattern: tuple, player_depth: int, op_depth: int, op_openings_depth: int + cls, + pattern: tuple, + player_depth: int, + op_depth: int, + op_openings_depth: int, ): keys = create_lookup_table_keys( player_depth=player_depth, @@ -151,7 +159,9 @@ def display( """ def sorter(plays): - return tuple(actions_to_str(getattr(plays, field) for field in sort_by)) + return tuple( + actions_to_str(getattr(plays, field) for field in sort_by) + ) col_width = 11 sorted_keys = sorted(self._dict, key=sorter) @@ -319,7 +329,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__() @@ -404,10 +414,20 @@ 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 + ( + lookup_dict, + initial_actions, + pattern, + parameters, + mutation_probability, + ) = self._normalize_parameters( + lookup_dict, + initial_actions, + pattern, + parameters, + mutation_probability, ) LookerUp.__init__( self, @@ -427,30 +447,50 @@ 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_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 plays, op_plays, op_start_plays = parameters - lookup_table = cls._get_lookup_table(lookup_dict, pattern, parameters) + lookup_table = cls._get_lookup_table( + lookup_dict, pattern, parameters + ) lookup_dict = lookup_table.dictionary elif parameters: # Generate a random pattern and (maybe) initial actions plays, op_plays, op_start_plays = parameters - pattern, lookup_table = cls.random_params(plays, op_plays, op_start_plays) + pattern, lookup_table = cls.random_params( + plays, op_plays, op_start_plays + ) lookup_dict = lookup_table.dictionary if not initial_actions: num_actions = max([plays, op_plays, op_start_plays]) - initial_actions = tuple([choice((C, D)) for _ in range(num_actions)]) + 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) @@ -458,8 +498,14 @@ def _normalize_parameters(cls, lookup_dict=None, initial_actions=None, pattern=N 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. / len(keys) - return lookup_dict, initial_actions, pattern, parameters, mutation_probability + mutation_probability = 2.0 / len(keys) + return ( + lookup_dict, + initial_actions, + pattern, + parameters, + mutation_probability, + ) @classmethod def random_value(cls): @@ -487,7 +533,9 @@ def mutate_table(cls, table, mutation_probability): return table def mutate(self): - lookup_dict = self.mutate_table(self.lookup_dict, self.mutation_probability) + lookup_dict = self.mutate_table( + self.lookup_dict, self.mutation_probability + ) # Add in starting moves initial_actions = list(self.initial_actions) for i in range(len(initial_actions)): @@ -495,14 +543,17 @@ 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): if other.__class__ != self.__class__: - raise TypeError("Crossover must be between the same player classes.") - lookup_dict = crossover_dictionaries(self.lookup_dict, other.lookup_dict) + raise TypeError( + "Crossover must be between the same player classes." + ) + lookup_dict = crossover_dictionaries( + self.lookup_dict, other.lookup_dict + ) return self.create_new(lookup_dict=lookup_dict) @@ -519,7 +570,9 @@ class EvolvedLookerUp1_1_1(LookerUp): def __init__(self) -> None: params = Plays(self_plays=1, op_plays=1, op_openings=1) - super().__init__(parameters=params, pattern="CDDDDCDD", initial_actions=(C,)) + super().__init__( + parameters=params, pattern="CDDDDCDD", initial_actions=(C,) + ) class EvolvedLookerUp2_2_2(LookerUp): @@ -535,8 +588,12 @@ class EvolvedLookerUp2_2_2(LookerUp): def __init__(self) -> None: params = Plays(self_plays=2, op_plays=2, op_openings=2) - pattern = "CDDCDCDDCDDDCDDDDDCDCDCCCDDCCDCDDDCCCCCDDDCDDDDDDDDDCCDDCDDDCCCD" - super().__init__(parameters=params, pattern=pattern, initial_actions=(C, C)) + pattern = ( + "CDDCDCDDCDDDCDDDDDCDCDCCCDDCCDCDDDCCCCCDDDCDDDDDDDDDCCDDCDDDCCCD" + ) + super().__init__( + parameters=params, pattern=pattern, initial_actions=(C, C) + ) class Winner12(LookerUp): @@ -553,7 +610,9 @@ class Winner12(LookerUp): def __init__(self) -> None: params = Plays(self_plays=1, op_plays=2, op_openings=0) pattern = "CDCDDCDD" - super().__init__(parameters=params, pattern=pattern, initial_actions=(C, C)) + super().__init__( + parameters=params, pattern=pattern, initial_actions=(C, C) + ) class Winner21(LookerUp): @@ -570,7 +629,9 @@ class Winner21(LookerUp): def __init__(self) -> None: params = Plays(self_plays=1, op_plays=2, op_openings=0) pattern = "CDCDCDDD" - super().__init__(parameters=params, pattern=pattern, initial_actions=(D, C)) + super().__init__( + parameters=params, pattern=pattern, initial_actions=(D, C) + ) def get_last_n_plays(player: Player, depth: int) -> tuple: diff --git a/axelrod/strategies/memoryone.py b/axelrod/strategies/memoryone.py index 8fa4aeae6..5e5e64375 100644 --- a/axelrod/strategies/memoryone.py +++ b/axelrod/strategies/memoryone.py @@ -36,7 +36,9 @@ class MemoryOnePlayer(Player): } def __init__( - self, four_vector: Tuple[float, float, float, float] = None, initial: Action = C + self, + four_vector: Tuple[float, float, float, float] = None, + initial: Action = C, ) -> None: """ Parameters @@ -83,7 +85,9 @@ def set_four_vector(self, four_vector: Tuple[float, float, float, float]): "between 0 and 1.".format(str(four_vector)) ) - self._four_vector = dict(zip([(C, C), (C, D), (D, C), (D, D)], four_vector)) + self._four_vector = dict( + zip([(C, C), (C, D), (D, C), (D, D)], four_vector) + ) self.classifier["stochastic"] = any(0 < x < 1 for x in set(four_vector)) def strategy(self, opponent: Player) -> Action: diff --git a/axelrod/strategies/memorytwo.py b/axelrod/strategies/memorytwo.py index 3466256b3..cd503801f 100644 --- a/axelrod/strategies/memorytwo.py +++ b/axelrod/strategies/memorytwo.py @@ -87,13 +87,16 @@ def set_sixteen_vector(self, sixteen_vector: Tuple): ) states = [ - (hist[:2], hist[2:]) for hist in list(itertools.product((C, D), repeat=4)) + (hist[:2], hist[2:]) + for hist in list(itertools.product((C, D), repeat=4)) ] self._sixteen_vector = dict( zip(states, sixteen_vector) ) # type: Dict[tuple, float] - self.classifier["stochastic"] = any(0 < x < 1 for x in set(sixteen_vector)) + self.classifier["stochastic"] = any( + 0 < x < 1 for x in set(sixteen_vector) + ) def strategy(self, opponent: Player) -> Action: if len(opponent.history) <= 1: @@ -232,7 +235,11 @@ class MEM2(Player): def __init__(self) -> None: super().__init__() - self.players = {"TFT": TitForTat(), "TFTT": TitFor2Tats(), "ALLD": Defector()} + self.players = { + "TFT": TitForTat(), + "TFTT": TitFor2Tats(), + "ALLD": Defector(), + } self.play_as = "TFT" self.shift_counter = 3 self.alld_counter = 0 diff --git a/axelrod/strategies/meta.py b/axelrod/strategies/meta.py index 09bebd26b..45b5641c0 100644 --- a/axelrod/strategies/meta.py +++ b/axelrod/strategies/meta.py @@ -20,7 +20,9 @@ ) # Needs to be computed manually to prevent circular dependency -ordinary_strategies = [s for s in all_strategies if Classifiers.obey_axelrod(s())] +ordinary_strategies = [ + s for s in all_strategies if Classifiers.obey_axelrod(s()) +] C, D = Action.C, Action.D @@ -72,7 +74,9 @@ def __init__(self, team=None): self.classifier[key] = any(map(Classifiers[key], self.team)) for t in self.team: - self.classifier["makes_use_of"].update(Classifiers["makes_use_of"](t)) + self.classifier["makes_use_of"].update( + Classifiers["makes_use_of"](t) + ) self._last_results = None @@ -332,7 +336,11 @@ class MetaMajorityMemoryOne(MetaMajority): name = "Meta Majority Memory One" def __init__(self): - team = [s for s in ordinary_strategies if Classifiers["memory_depth"](s()) <= 1] + team = [ + s + for s in ordinary_strategies + if Classifiers["memory_depth"](s()) <= 1 + ] super().__init__(team=team) self.classifier["long_run_time"] = False @@ -386,7 +394,11 @@ class MetaWinnerMemoryOne(MetaWinner): name = "Meta Winner Memory One" def __init__(self): - team = [s for s in ordinary_strategies if Classifiers["memory_depth"](s()) <= 1] + team = [ + s + for s in ordinary_strategies + if Classifiers["memory_depth"](s()) <= 1 + ] super().__init__(team=team) self.classifier["long_run_time"] = False @@ -440,7 +452,9 @@ class MetaWinnerDeterministic(MetaWinner): name = "Meta Winner Deterministic" def __init__(self): - team = [s for s in ordinary_strategies if not Classifiers["stochastic"](s())] + team = [ + s for s in ordinary_strategies if not Classifiers["stochastic"](s()) + ] super().__init__(team=team) self.classifier["stochastic"] = False @@ -456,7 +470,9 @@ class MetaWinnerStochastic(MetaWinner): name = "Meta Winner Stochastic" def __init__(self): - team = [s for s in ordinary_strategies if Classifiers["stochastic"](s())] + team = [ + s for s in ordinary_strategies if Classifiers["stochastic"](s()) + ] super().__init__(team=team) @@ -512,7 +528,9 @@ class NMWEDeterministic(NiceMetaWinnerEnsemble): name = "NMWE Deterministic" def __init__(self): - team = [s for s in ordinary_strategies if not Classifiers["stochastic"](s())] + team = [ + s for s in ordinary_strategies if not Classifiers["stochastic"](s()) + ] super().__init__(team=team) self.classifier["stochastic"] = True @@ -528,7 +546,9 @@ class NMWEStochastic(NiceMetaWinnerEnsemble): name = "NMWE Stochastic" def __init__(self): - team = [s for s in ordinary_strategies if Classifiers["stochastic"](s())] + team = [ + s for s in ordinary_strategies if Classifiers["stochastic"](s()) + ] super().__init__(team=team) @@ -581,7 +601,11 @@ class NMWEMemoryOne(NiceMetaWinnerEnsemble): name = "NMWE Memory One" def __init__(self): - team = [s for s in ordinary_strategies if Classifiers["memory_depth"](s()) <= 1] + team = [ + s + for s in ordinary_strategies + if Classifiers["memory_depth"](s()) <= 1 + ] super().__init__(team=team) self.classifier["long_run_time"] = False diff --git a/axelrod/strategies/prober.py b/axelrod/strategies/prober.py index 96940a1fc..79a41971a 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/punisher.py b/axelrod/strategies/punisher.py index dd8145576..0bf70491d 100644 --- a/axelrod/strategies/punisher.py +++ b/axelrod/strategies/punisher.py @@ -54,7 +54,9 @@ def strategy(self, opponent: Player) -> Action: return D elif D in opponent.history[-1:]: - self.mem_length = (opponent.defections * 20) // len(opponent.history) + self.mem_length = (opponent.defections * 20) // len( + opponent.history + ) self.grudged = True return D @@ -105,7 +107,9 @@ def strategy(self, opponent: Player) -> Action: self.grudge_memory += 1 return D elif D in opponent.history[-1:]: - self.mem_length = (opponent.cooperations * 20) // len(opponent.history) + self.mem_length = (opponent.cooperations * 20) // len( + opponent.history + ) if self.mem_length == 0: self.mem_length += 1 self.grudged = True diff --git a/axelrod/strategies/qlearner.py b/axelrod/strategies/qlearner.py index dd308feb6..6363d5951 100644 --- a/axelrod/strategies/qlearner.py +++ b/axelrod/strategies/qlearner.py @@ -68,7 +68,9 @@ def strategy(self, opponent: Player) -> Action: if state not in self.Qs: self.Qs[state] = OrderedDict(zip([C, D], [0, 0])) self.Vs[state] = 0 - self.perform_q_learning(self.prev_state, state, self.prev_action, reward) + self.perform_q_learning( + self.prev_state, state, self.prev_action, reward + ) action = self.select_action(state) self.prev_state = state self.prev_action = action @@ -93,16 +95,22 @@ def find_state(self, opponent: Player) -> str: action_str = actions_to_str(opponent.history[-self.memory_length :]) return action_str + prob - def perform_q_learning(self, prev_state: str, state: str, action: Action, reward): + def perform_q_learning( + self, prev_state: str, state: str, action: Action, reward + ): """ Performs the qlearning algorithm """ - self.Qs[prev_state][action] = (1.0 - self.learning_rate) * self.Qs[prev_state][ - action - ] + self.learning_rate * (reward + self.discount_rate * self.Vs[state]) + self.Qs[prev_state][action] = (1.0 - self.learning_rate) * self.Qs[ + prev_state + ][action] + self.learning_rate * ( + reward + self.discount_rate * self.Vs[state] + ) self.Vs[prev_state] = max(self.Qs[prev_state].values()) - def find_reward(self, opponent: Player) -> Dict[Action, Dict[Action, Score]]: + def find_reward( + self, opponent: Player + ) -> Dict[Action, Dict[Action, Score]]: """ Finds the reward gained on the last iteration """ diff --git a/axelrod/strategies/revised_downing.py b/axelrod/strategies/revised_downing.py index 2304af708..f3e290fd0 100644 --- a/axelrod/strategies/revised_downing.py +++ b/axelrod/strategies/revised_downing.py @@ -7,6 +7,7 @@ C, D = Action.C, Action.D + class RevisedDowning(Player): """ Strategy submitted to Axelrod's second tournament by Leslie Downing. @@ -72,4 +73,3 @@ def strategy(self, opponent: Player) -> Action: else: move = D return move - diff --git a/axelrod/strategies/shortmem.py b/axelrod/strategies/shortmem.py index 23bf7c523..ae4476cd7 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/strategies/titfortat.py b/axelrod/strategies/titfortat.py index cb3b79245..d64faa754 100644 --- a/axelrod/strategies/titfortat.py +++ b/axelrod/strategies/titfortat.py @@ -1,7 +1,10 @@ from axelrod.action import Action, actions_to_str from axelrod.player import Player from axelrod.random_ import random_choice -from axelrod.strategy_transformers import FinalTransformer, TrackHistoryTransformer +from axelrod.strategy_transformers import ( + FinalTransformer, + TrackHistoryTransformer, +) C, D = Action.C, Action.D diff --git a/axelrod/strategies/zero_determinant.py b/axelrod/strategies/zero_determinant.py index aaacfb130..927b99a67 100644 --- a/axelrod/strategies/zero_determinant.py +++ b/axelrod/strategies/zero_determinant.py @@ -152,7 +152,9 @@ class ZDExtort2v2(LRPlayer): name = "ZD-Extort-2 v2" - def __init__(self, phi: float = 1 / 8, s: float = 0.5, l: float = 1) -> None: + def __init__( + self, phi: float = 1 / 8, s: float = 0.5, l: float = 1 + ) -> None: super().__init__(phi, s, l) @@ -169,7 +171,9 @@ class ZDExtort3(LRPlayer): name = "ZD-Extort3" - def __init__(self, phi: float = 3 / 26, s: float = 1 / 3, l: float = 1) -> None: + def __init__( + self, phi: float = 3 / 26, s: float = 1 / 3, l: float = 1 + ) -> None: super().__init__(phi, s, l) @@ -186,7 +190,9 @@ class ZDExtort4(LRPlayer): name = "ZD-Extort-4" - def __init__(self, phi: float = 4 / 17, s: float = 0.25, l: float = 1) -> None: + def __init__( + self, phi: float = 4 / 17, s: float = 0.25, l: float = 1 + ) -> None: super().__init__(phi, s, l) @@ -201,7 +207,9 @@ class ZDGen2(LRPlayer): name = "ZD-GEN-2" - def __init__(self, phi: float = 1 / 8, s: float = 0.5, l: float = 3) -> None: + def __init__( + self, phi: float = 1 / 8, s: float = 0.5, l: float = 3 + ) -> None: super().__init__(phi, s, l) @@ -252,5 +260,7 @@ class ZDSet2(LRPlayer): name = "ZD-SET-2" - def __init__(self, phi: float = 1 / 4, s: float = 0.0, l: float = 2) -> None: + def __init__( + self, phi: float = 1 / 4, s: float = 0.0, l: float = 2 + ) -> None: super().__init__(phi, s, l) diff --git a/axelrod/strategy_transformers.py b/axelrod/strategy_transformers.py index 6d50d77c2..354c65bc4 100644 --- a/axelrod/strategy_transformers.py +++ b/axelrod/strategy_transformers.py @@ -27,7 +27,9 @@ # Alternator. -def StrategyTransformerFactory(strategy_wrapper, name_prefix=None, reclassifier=None): +def StrategyTransformerFactory( + strategy_wrapper, name_prefix=None, reclassifier=None +): """Modify an existing strategy dynamically by wrapping the strategy method with the argument `strategy_wrapper`. @@ -232,7 +234,11 @@ class DecoratorReBuilder(object): """ def __call__( - self, factory_args: tuple, args: tuple, kwargs: dict, instance_name_prefix: str + self, + factory_args: tuple, + args: tuple, + kwargs: dict, + instance_name_prefix: str, ) -> Any: decorator_class = StrategyTransformerFactory(*factory_args) @@ -246,7 +252,9 @@ class StrategyReBuilder(object): that could not normally be pickled. """ - def __call__(self, decorators: list, import_name: str, module_name: str) -> Player: + def __call__( + self, decorators: list, import_name: str, module_name: str + ) -> Player: module_ = import_module(module_name) import_class = getattr(module_, import_name) @@ -275,7 +283,9 @@ def __call__(self, PlayerClass): return Composition() -def generic_strategy_wrapper(player, opponent, proposed_action, *args, **kwargs): +def generic_strategy_wrapper( + player, opponent, proposed_action, *args, **kwargs +): """ Strategy wrapper functions should be of the following form. @@ -307,7 +317,9 @@ def flip_wrapper(player, opponent, action): return action.flip() -FlipTransformer = StrategyTransformerFactory(flip_wrapper, name_prefix="Flipped") +FlipTransformer = StrategyTransformerFactory( + flip_wrapper, name_prefix="Flipped" +) def dual_wrapper(player, opponent: Player, proposed_action: Action) -> Action: @@ -377,7 +389,9 @@ def forgiver_reclassifier(original_classifier, p): ForgiverTransformer = StrategyTransformerFactory( - forgiver_wrapper, name_prefix="Forgiving", reclassifier=forgiver_reclassifier + forgiver_wrapper, + name_prefix="Forgiving", + reclassifier=forgiver_reclassifier, ) @@ -495,14 +509,18 @@ def grudge_wrapper(player, opponent, action, grudges): return action -GrudgeTransformer = StrategyTransformerFactory(grudge_wrapper, name_prefix="Grudging") +GrudgeTransformer = StrategyTransformerFactory( + grudge_wrapper, name_prefix="Grudging" +) def apology_wrapper(player, opponent, action, myseq, opseq): length = len(myseq) if len(player.history) < length: return action - if (myseq == player.history[-length:]) and (opseq == opponent.history[-length:]): + if (myseq == player.history[-length:]) and ( + opseq == opponent.history[-length:] + ): return C return action @@ -535,9 +553,7 @@ 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/integration/test_filtering.py b/axelrod/tests/integration/test_filtering.py index bce495b76..f99a3282b 100644 --- a/axelrod/tests/integration/test_filtering.py +++ b/axelrod/tests/integration/test_filtering.py @@ -35,7 +35,9 @@ def test_boolean_filtering(self, strategies): for classifier in classifiers: comprehension = set(filter(axl.Classifiers[classifier], strategies)) filterset = {classifier: True} - filtered = set(axl.filtered_strategies(filterset, strategies=strategies)) + filtered = set( + axl.filtered_strategies(filterset, strategies=strategies) + ) self.assertEqual(comprehension, filtered) @given( @@ -89,7 +91,9 @@ def test_memory_depth_filtering( ] ) filterset = {"memory_depth": memory_depth} - filtered = set(axl.filtered_strategies(filterset, strategies=strategies)) + filtered = set( + axl.filtered_strategies(filterset, strategies=strategies) + ) self.assertEqual(comprehension, filtered) @given( @@ -111,13 +115,17 @@ def test_makes_use_of_filtering(self, seed_, strategies): [ s for s in strategies - if set(classifier).issubset(set(axl.Classifiers["makes_use_of"](s))) + if set(classifier).issubset( + set(axl.Classifiers["makes_use_of"](s)) + ) ] ) axl.seed(seed_) filterset = {"makes_use_of": classifier} - filtered = set(axl.filtered_strategies(filterset, strategies=strategies)) + filtered = set( + axl.filtered_strategies(filterset, strategies=strategies) + ) self.assertEqual( comprehension, filtered, msg="classifier: {}".format(classifier) diff --git a/axelrod/tests/integration/test_matches.py b/axelrod/tests/integration/test_matches.py index a627fe885..0420f77ac 100644 --- a/axelrod/tests/integration/test_matches.py +++ b/axelrod/tests/integration/test_matches.py @@ -10,10 +10,14 @@ C, D = axl.Action.C, axl.Action.D deterministic_strategies = [ - s for s in axl.short_run_time_strategies if not axl.Classifiers["stochastic"](s()) + s + for s in axl.short_run_time_strategies + if not axl.Classifiers["stochastic"](s()) ] stochastic_strategies = [ - s for s in axl.short_run_time_strategies if axl.Classifiers["stochastic"](s()) + s + for s in axl.short_run_time_strategies + if axl.Classifiers["stochastic"](s()) ] diff --git a/axelrod/tests/integration/test_tournament.py b/axelrod/tests/integration/test_tournament.py index 2ab59c974..0c40f3405 100644 --- a/axelrod/tests/integration/test_tournament.py +++ b/axelrod/tests/integration/test_tournament.py @@ -53,7 +53,9 @@ def test_big_tournaments(self, tournament): path = pathlib.Path("test_outputs/test_tournament.csv") filename = axl_filename(path) self.assertIsNone( - tournament.play(progress_bar=False, filename=filename, build_results=False) + tournament.play( + progress_bar=False, filename=filename, build_results=False + ) ) def test_serial_play(self): @@ -96,9 +98,13 @@ def test_repeat_tournament_deterministic(self): turns=2, repetitions=2, ) - path = pathlib.Path("test_outputs/stochastic_tournament_{}.csv".format(_)) + path = pathlib.Path( + "test_outputs/stochastic_tournament_{}.csv".format(_) + ) files.append(axl_filename(path)) - tournament.play(progress_bar=False, filename=files[-1], build_results=False) + tournament.play( + progress_bar=False, filename=files[-1], build_results=False + ) self.assertTrue(filecmp.cmp(files[0], files[1])) def test_repeat_tournament_stochastic(self): @@ -120,9 +126,13 @@ def test_repeat_tournament_stochastic(self): turns=2, repetitions=2, ) - path = pathlib.Path("test_outputs/stochastic_tournament_{}.csv".format(_)) + path = pathlib.Path( + "test_outputs/stochastic_tournament_{}.csv".format(_) + ) files.append(axl_filename(path)) - tournament.play(progress_bar=False, filename=files[-1], build_results=False) + tournament.play( + progress_bar=False, filename=files[-1], build_results=False + ) self.assertTrue(filecmp.cmp(files[0], files[1])) diff --git a/axelrod/tests/property.py b/axelrod/tests/property.py index 95d08e2b8..ff49a63f2 100644 --- a/axelrod/tests/property.py +++ b/axelrod/tests/property.py @@ -5,12 +5,21 @@ import axelrod as axl -from hypothesis.strategies import composite, floats, integers, lists, sampled_from +from hypothesis.strategies import ( + composite, + floats, + integers, + lists, + sampled_from, +) @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 @@ -101,14 +110,20 @@ def tournaments( The maximum number of repetitions """ strategies = draw( - strategy_lists(strategies=strategies, min_size=min_size, max_size=max_size) + strategy_lists( + strategies=strategies, min_size=min_size, max_size=max_size + ) ) players = [s() for s in strategies] turns = draw(integers(min_value=min_turns, max_value=max_turns)) - repetitions = draw(integers(min_value=min_repetitions, max_value=max_repetitions)) + 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 @@ -148,11 +163,15 @@ def prob_end_tournaments( The maximum number of repetitions """ strategies = draw( - strategy_lists(strategies=strategies, min_size=min_size, max_size=max_size) + strategy_lists( + strategies=strategies, min_size=min_size, max_size=max_size + ) ) players = [s() for s in strategies] prob_end = draw(floats(min_value=min_prob_end, max_value=max_prob_end)) - repetitions = draw(integers(min_value=min_repetitions, max_value=max_repetitions)) + 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( @@ -197,7 +216,9 @@ def spatial_tournaments( The maximum number of repetitions """ strategies = draw( - strategy_lists(strategies=strategies, min_size=min_size, max_size=max_size) + strategy_lists( + strategies=strategies, min_size=min_size, max_size=max_size + ) ) players = [s() for s in strategies] player_indices = list(range(len(players))) @@ -214,13 +235,17 @@ def spatial_tournaments( # Ensure all players/nodes are connected: node_indices = sorted(set([node for edge in edges for node in edge])) - missing_nodes = [index for index in player_indices if index not in node_indices] + missing_nodes = [ + index for index in player_indices if index not in node_indices + ] for index in missing_nodes: opponent = draw(sampled_from(player_indices)) edges.append((index, opponent)) turns = draw(integers(min_value=min_turns, max_value=max_turns)) - repetitions = draw(integers(min_value=min_repetitions, max_value=max_repetitions)) + 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( @@ -265,7 +290,9 @@ def prob_end_spatial_tournaments( The maximum number of repetitions """ strategies = draw( - strategy_lists(strategies=strategies, min_size=min_size, max_size=max_size) + strategy_lists( + strategies=strategies, min_size=min_size, max_size=max_size + ) ) players = [s() for s in strategies] player_indices = list(range(len(players))) @@ -282,17 +309,25 @@ def prob_end_spatial_tournaments( # Ensure all players/nodes are connected: node_indices = sorted(set([node for edge in edges for node in edge])) - missing_nodes = [index for index in player_indices if index not in node_indices] + missing_nodes = [ + index for index in player_indices if index not in node_indices + ] for index in missing_nodes: opponent = draw(sampled_from(player_indices)) edges.append((index, opponent)) prob_end = draw(floats(min_value=min_prob_end, max_value=max_prob_end)) - repetitions = draw(integers(min_value=min_repetitions, max_value=max_repetitions)) + 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, prob_end=prob_end, repetitions=repetitions, noise=noise, edges=edges + players, + prob_end=prob_end, + repetitions=repetitions, + noise=noise, + edges=edges, ) return tournament diff --git a/axelrod/tests/strategies/test_ann.py b/axelrod/tests/strategies/test_ann.py index 3a63d2131..89eaca9b6 100644 --- a/axelrod/tests/strategies/test_ann.py +++ b/axelrod/tests/strategies/test_ann.py @@ -19,6 +19,7 @@ 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) @@ -100,13 +101,12 @@ 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,7 +126,7 @@ 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], } @@ -135,7 +135,7 @@ class TestEvolvableANN3(TestEvolvablePlayer): axl.EvolvableANN, num_features=num_features, num_hidden=num_hidden, - weights=weights + weights=weights, ) diff --git a/axelrod/tests/strategies/test_apavlov.py b/axelrod/tests/strategies/test_apavlov.py index e720dce56..3b38e5b1e 100644 --- a/axelrod/tests/strategies/test_apavlov.py +++ b/axelrod/tests/strategies/test_apavlov.py @@ -32,7 +32,9 @@ def test_strategy(self): opponent = axl.MockPlayer(actions=[C] * 6 + [D]) actions = [(C, C)] * 6 + [(C, D), (D, C)] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_class": "Cooperative"} + opponent, + expected_actions=actions, + attrs={"opponent_class": "Cooperative"}, ) actions = [(C, D)] + [(D, D)] * 6 @@ -62,25 +64,42 @@ def test_strategy(self): opponent = axl.MockPlayer(actions=[D, D, C, D, D, C]) actions = [(C, D), (D, D), (D, C), (C, D), (D, D), (D, C), (D, D)] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_class": "PavlovD"} + opponent, + expected_actions=actions, + attrs={"opponent_class": "PavlovD"}, ) opponent = axl.MockPlayer(actions=[D, D, C, D, D, C, D]) - actions = [(C, D), (D, D), (D, C), (C, D), (D, D), (D, C), (D, D), (C, D)] + actions = [ + (C, D), + (D, D), + (D, C), + (C, D), + (D, D), + (D, C), + (D, D), + (C, D), + ] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_class": "PavlovD"} + opponent, + expected_actions=actions, + attrs={"opponent_class": "PavlovD"}, ) opponent = axl.MockPlayer(actions=[C, C, C, D, D, D]) actions = [(C, C), (C, C), (C, C), (C, D), (D, D), (D, D), (D, C)] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_class": "Random"} + opponent, + expected_actions=actions, + attrs={"opponent_class": "Random"}, ) opponent = axl.MockPlayer(actions=[D, D, D, C, C, C]) actions = [(C, D), (D, D), (D, D), (D, C), (C, C), (C, C), (D, D)] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_class": "Random"} + opponent, + expected_actions=actions, + attrs={"opponent_class": "Random"}, ) @@ -127,37 +146,95 @@ def test_strategy(self): ) opponent = axl.MockPlayer(actions=[C, D, D, C, D, D, D]) - actions = [(C, C), (C, D), (D, D), (D, C), (C, D), (D, D), (D, D), (D, C)] + actions = [ + (C, C), + (C, D), + (D, D), + (D, C), + (C, D), + (D, D), + (D, D), + (D, C), + ] self.versus_test( opponent, expected_actions=actions, attrs={"opponent_class": "ALLD"} ) opponent = axl.MockPlayer(actions=[C, D, D, C, C, D, D]) - actions = [(C, C), (C, D), (D, D), (D, C), (C, C), (C, D), (C, D), (D, C)] + actions = [ + (C, C), + (C, D), + (D, D), + (D, C), + (C, C), + (C, D), + (C, D), + (D, C), + ] self.versus_test( opponent, expected_actions=actions, attrs={"opponent_class": "STFT"} ) opponent = axl.MockPlayer(actions=[C, D, C, D, C, D, D]) - actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (C, D), (C, D), (D, C)] + actions = [ + (C, C), + (C, D), + (D, C), + (C, D), + (D, C), + (C, D), + (C, D), + (D, C), + ] self.versus_test( opponent, expected_actions=actions, attrs={"opponent_class": "STFT"} ) opponent = axl.MockPlayer(actions=[D, D, D, C, C, C, C]) - actions = [(C, D), (D, D), (D, D), (D, C), (C, C), (C, C), (C, C), (C, D)] + actions = [ + (C, D), + (D, D), + (D, D), + (D, C), + (C, C), + (C, C), + (C, C), + (C, D), + ] self.versus_test( opponent, expected_actions=actions, attrs={"opponent_class": "STFT"} ) opponent = axl.MockPlayer(actions=[C, C, C, C, D, D]) - actions = [(C, C), (C, C), (C, C), (C, C), (C, D), (D, D), (D, C), (D, C)] + actions = [ + (C, C), + (C, C), + (C, C), + (C, C), + (C, D), + (D, D), + (D, C), + (D, C), + ] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_class": "Random"} + opponent, + expected_actions=actions, + attrs={"opponent_class": "Random"}, ) opponent = axl.MockPlayer(actions=[D, D, C, C, C, C]) - actions = [(C, D), (D, D), (D, C), (C, C), (C, C), (C, C), (D, D), (D, D)] + actions = [ + (C, D), + (D, D), + (D, C), + (C, C), + (C, C), + (C, C), + (D, D), + (D, D), + ] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_class": "Random"} + opponent, + expected_actions=actions, + attrs={"opponent_class": "Random"}, ) diff --git a/axelrod/tests/strategies/test_axelrod_first.py b/axelrod/tests/strategies/test_axelrod_first.py index 35ee2d5f4..2319c0075 100644 --- a/axelrod/tests/strategies/test_axelrod_first.py +++ b/axelrod/tests/strategies/test_axelrod_first.py @@ -97,7 +97,9 @@ class TestFirstByFeld(TestPlayer): def test_cooperation_probability(self): # Test cooperation probabilities - p1 = self.player(start_coop_prob=1.0, end_coop_prob=0.8, rounds_of_decay=100) + p1 = self.player( + start_coop_prob=1.0, end_coop_prob=0.8, rounds_of_decay=100 + ) self.assertEqual(1.0, p1._cooperation_probability()) p2 = axl.Cooperator() match = axl.Match((p1, p2), turns=50) @@ -108,7 +110,9 @@ def test_cooperation_probability(self): self.assertEqual(0.8, p1._cooperation_probability()) # Test cooperation probabilities, second set of params - p1 = self.player(start_coop_prob=1.0, end_coop_prob=0.5, rounds_of_decay=200) + p1 = self.player( + start_coop_prob=1.0, end_coop_prob=0.5, rounds_of_decay=200 + ) self.assertEqual(1.0, p1._cooperation_probability()) match = axl.Match((p1, p2), turns=100) match.play() @@ -121,10 +125,14 @@ def test_decay(self): # Test beyond 200 rounds for opponent in [axl.Cooperator(), axl.Defector()]: player = self.player() - self.assertEqual(player._cooperation_probability(), player._start_coop_prob) + self.assertEqual( + player._cooperation_probability(), player._start_coop_prob + ) match = axl.Match((player, opponent), turns=201) match.play() - self.assertEqual(player._cooperation_probability(), player._end_coop_prob) + self.assertEqual( + player._cooperation_probability(), player._end_coop_prob + ) def test_strategy(self): actions = [(C, C)] * 41 + [(D, C)] @@ -187,7 +195,10 @@ def test_strategy(self): self.versus_test( axl.Cooperator(), expected_actions=actions, attrs=expected_attrs ) - expected_attrs = {"opponent_is_random": False, "next_random_defection_turn": 68} + expected_attrs = { + "opponent_is_random": False, + "next_random_defection_turn": 68, + } actions += [(C, C)] # 57 turns self.versus_test( axl.Cooperator(), expected_actions=actions, attrs=expected_attrs @@ -218,20 +229,35 @@ def test_strategy(self): actions += [(C, D), (D, C)] * 3 # 56 turns actions += [(C, D), (D, C)] * 50 self.versus_test( - axl.TitForTat(), expected_actions=actions, seed=0, attrs=expected_attrs + axl.TitForTat(), + expected_actions=actions, + seed=0, + attrs=expected_attrs, ) # Test random defections - expected_attrs = {"opponent_is_random": False, "next_random_defection_turn": 78} + expected_attrs = { + "opponent_is_random": False, + "next_random_defection_turn": 78, + } actions = [(C, C)] * 50 + [(D, C)] + [(C, C)] * 16 + [(D, C)] + [(C, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, seed=0, attrs=expected_attrs + axl.Cooperator(), + expected_actions=actions, + seed=0, + attrs=expected_attrs, ) - expected_attrs = {"opponent_is_random": False, "next_random_defection_turn": 77} + expected_attrs = { + "opponent_is_random": False, + "next_random_defection_turn": 77, + } actions = [(C, C)] * 50 + [(D, C)] + [(C, C)] * 12 + [(D, C)] + [(C, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, seed=1, attrs=expected_attrs + axl.Cooperator(), + expected_actions=actions, + seed=1, + attrs=expected_attrs, ) @@ -257,11 +283,29 @@ def test_strategy(self): self.versus_test(axl.Alternator(), expected_actions=actions) opponent = axl.MockPlayer(actions=[D] * 8) - actions = [(C, D), (C, D), (D, D), (C, D), (D, D), (C, D), (C, D), (D, D)] + actions = [ + (C, D), + (C, D), + (D, D), + (C, D), + (D, D), + (C, D), + (C, D), + (D, D), + ] self.versus_test(opponent, expected_actions=actions, seed=1) opponent = axl.MockPlayer(actions=[D] * 8) - actions = [(C, D), (D, D), (C, D), (D, D), (C, D), (C, D), (C, D), (D, D)] + actions = [ + (C, D), + (D, D), + (C, D), + (D, D), + (C, D), + (C, D), + (C, D), + (D, D), + ] self.versus_test(opponent, expected_actions=actions, seed=2) @@ -337,14 +381,41 @@ def test_strategy(self): actions = [(C, C)] * 9 self.versus_test(axl.Cooperator(), expected_actions=actions) - actions = [(C, D), (D, D), (D, D), (C, D), (C, D), (C, D), (C, D), (C, D)] + actions = [ + (C, D), + (D, D), + (D, D), + (C, D), + (C, D), + (C, D), + (C, D), + (C, D), + ] self.versus_test(axl.Defector(), expected_actions=actions) - actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (C, D), (D, C), (C, D)] + actions = [ + (C, C), + (C, D), + (D, C), + (C, D), + (D, C), + (C, D), + (D, C), + (C, D), + ] self.versus_test(axl.Alternator(), expected_actions=actions) opponent = axl.MockPlayer(actions=[D, C]) - actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C), (D, D), (D, C)] + actions = [ + (C, D), + (D, C), + (D, D), + (D, C), + (D, D), + (D, C), + (D, D), + (D, C), + ] self.versus_test(opponent, expected_actions=actions) @@ -493,7 +564,9 @@ def test_strategy(self): opponent = axl.Cooperator() actions = [(C, C)] * 17 + [(D, C)] * 2 self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_is_random": False} + opponent, + expected_actions=actions, + attrs={"opponent_is_random": False}, ) actions = actions[:-2] + [(C, C)] * 2 @@ -509,7 +582,9 @@ def test_strategy(self): opponent = axl.Defector() actions = [(C, D)] * 4 + [(D, D)] * 15 self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_is_random": False} + opponent, + expected_actions=actions, + attrs={"opponent_is_random": False}, ) # SteinAndRapoport vs Alternator @@ -524,7 +599,9 @@ def test_strategy(self): actions += [(D, D), (D, C), (D, D), (D, C)] self.versus_test( - opponent, expected_actions=actions, attrs={"opponent_is_random": True} + opponent, + expected_actions=actions, + attrs={"opponent_is_random": True}, ) # The test is carried out again every 15 rounds. @@ -569,8 +646,11 @@ 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 7c9122d8d..26a9fe816 100644 --- a/axelrod/tests/strategies/test_axelrod_second.py +++ b/axelrod/tests/strategies/test_axelrod_second.py @@ -112,7 +112,9 @@ def test_strategy(self): # Now play TfT opponent = axl.MockPlayer(actions=[C, D, C, D, D, C]) actions = [(D, C), (C, D), (C, C), (C, D), (D, D), (D, C), (C, C)] - self.versus_test(opponent, expected_actions=actions, attrs={"is_TFT": True}) + self.versus_test( + opponent, expected_actions=actions, attrs={"is_TFT": True} + ) class TestGladstein(TestPlayer): @@ -151,11 +153,15 @@ def test_strategy(self): # Ratio is 1/3 when MockPlayer defected for the first time. opponent = axl.MockPlayer(actions=[C, C, C, D, D]) actions = [(D, C), (C, C), (C, C), (D, D), (C, D)] - self.versus_test(opponent, expected_actions=actions, attrs={"patsy": False}) + self.versus_test( + opponent, expected_actions=actions, attrs={"patsy": False} + ) opponent = axl.AntiTitForTat() actions = [(D, C), (C, C), (C, D), (C, D), (D, D)] - self.versus_test(opponent, expected_actions=actions, attrs={"patsy": False}) + self.versus_test( + opponent, expected_actions=actions, attrs={"patsy": False} + ) class TestTranquilizer(TestPlayer): @@ -188,7 +194,16 @@ def test_init(self): def test_strategy(self): opponent = axl.Bully() - actions = [(C, D), (D, D), (D, C), (C, C), (C, D), (D, D), (D, C), (C, C)] + actions = [ + (C, D), + (D, D), + (D, C), + (C, C), + (C, D), + (D, D), + (D, C), + (C, C), + ] expected_attrs = { "num_turns_after_good_defection": 0, "one_turn_after_good_defection_ratio": 5, @@ -196,7 +211,9 @@ def test_strategy(self): "one_turn_after_good_defection_ratio_count": 1, "two_turns_after_good_defection_ratio_count": 1, } - self.versus_test(opponent, expected_actions=actions, attrs=expected_attrs) + self.versus_test( + opponent, expected_actions=actions, attrs=expected_attrs + ) # Tests whether TitForTat is played given score is below 1.75 @@ -209,10 +226,14 @@ def test_strategy(self): "one_turn_after_good_defection_ratio_count": 1, "two_turns_after_good_defection_ratio_count": 1, } - self.versus_test(opponent, expected_actions=actions, attrs=expected_attrs) + self.versus_test( + opponent, expected_actions=actions, attrs=expected_attrs + ) opponent = axl.MockPlayer([C] * 2 + [D] * 8 + [C] * 4) - actions = [(C, C), (C, C)] + [(C, D)] + [(D, D)] * 7 + [(D, C)] + [(C, C)] * 3 + actions = ( + [(C, C), (C, C)] + [(C, D)] + [(D, D)] * 7 + [(D, C)] + [(C, C)] * 3 + ) expected_attrs = { "num_turns_after_good_defection": 0, "one_turn_after_good_defection_ratio": 5, @@ -220,7 +241,9 @@ def test_strategy(self): "one_turn_after_good_defection_ratio_count": 1, "two_turns_after_good_defection_ratio_count": 1, } - self.versus_test(opponent, expected_actions=actions, attrs=expected_attrs) + self.versus_test( + opponent, expected_actions=actions, attrs=expected_attrs + ) # If score is between 1.75 and 2.25, may cooperate or defect @@ -353,7 +376,9 @@ def test_strategy(self): "one_turn_after_good_defection_ratio_count": 1, "two_turns_after_good_defection_ratio_count": 1, } - self.versus_test(opponent, expected_actions=actions, attrs=expected_attrs) + self.versus_test( + opponent, expected_actions=actions, attrs=expected_attrs + ) class TestGrofman(TestPlayer): @@ -646,7 +671,9 @@ def test_strategy(self): # Tries to cooperate every third time until detecting defective actions = ( - [(C, D), (D, D), (D, D), (D, D)] * 6 + [(C, D), (D, D)] + [(D, D)] * 100 + [(C, D), (D, D), (D, D), (D, D)] * 6 + + [(C, D), (D, D)] + + [(D, D)] * 100 ) self.versus_test(axl.Defector(), expected_actions=actions) @@ -1017,14 +1044,20 @@ def test_strategy(self): # Immediately exit Fair-weather actions += [(D, C), (C, C), (D, C), (C, C)] self.versus_test( - Defect37_big, expected_actions=actions, seed=2, attrs={"mode": "Normal"} + Defect37_big, + expected_actions=actions, + seed=2, + attrs={"mode": "Normal"}, ) actions = [(C, C)] * 36 + [(D, D)] + [(C, C)] * 100 actions += [(C, D)] # Immediately exit Fair-weather actions += [(D, C), (C, C), (C, C), (C, C)] self.versus_test( - Defect37_big, expected_actions=actions, seed=1, attrs={"mode": "Normal"} + Defect37_big, + expected_actions=actions, + seed=1, + attrs={"mode": "Normal"}, ) # Opponent defects on 1st turn @@ -1263,14 +1296,18 @@ def test_strategy(self): actions = [(C, D)] + [(D, D)] * 8 self.versus_test( - axl.Defector(), expected_actions=actions, attrs={"score_to_beat_inc": 5} + axl.Defector(), + expected_actions=actions, + attrs={"score_to_beat_inc": 5}, ) actions = [(C, D)] + [(D, D)] * 8 # On tenth turn, try a fresh start actions += [(C, D), (C, D)] + [(D, D)] * 2 self.versus_test( - axl.Defector(), expected_actions=actions, attrs={"last_fresh_start": 11} + axl.Defector(), + expected_actions=actions, + attrs={"last_fresh_start": 11}, ) actions = [(C, C), (C, D)] @@ -1548,7 +1585,9 @@ class TestRichardHufford(TestPlayer): def test_strategy(self): actions = [(C, C)] * 19 + [(D, C), (C, C), (C, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, attrs={"streak_needed": 14} + axl.Cooperator(), + expected_actions=actions, + attrs={"streak_needed": 14}, ) actions = [(C, C)] * 19 + [(D, C), (C, C)] @@ -1557,14 +1596,18 @@ def test_strategy(self): ] # This is the first Cooperation that gets counted on the new streak actions += [(C, C)] * 13 + [(D, C), (C, C), (C, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, attrs={"streak_needed": 11} + axl.Cooperator(), + expected_actions=actions, + attrs={"streak_needed": 11}, ) opponent_actions = [C] * 20 + [D] BoredCooperator = axl.MockPlayer(actions=opponent_actions) actions = [(C, C)] * 19 + [(D, C), (C, D), (C, C)] self.versus_test( - BoredCooperator, expected_actions=actions, attrs={"streak_needed": 31} + BoredCooperator, + expected_actions=actions, + attrs={"streak_needed": 31}, ) actions = [(C, D)] # "Disagreement" @@ -1573,7 +1616,9 @@ def test_strategy(self): actions += [(C, D)] # TFT. Disagreement actions += [(D, C)] # Three of last four are disagreements. actions += [(C, C)] # TFT. Disagreement - actions += [(D, D)] # Three of last four are disagreements. Disagreement + actions += [ + (D, D) + ] # Three of last four are disagreements. Disagreement actions += [(D, D)] # Three of last four are disagreements. actions += [(D, D)] # Now there are 5/9 disagreements, so Defect. self.versus_test( @@ -1609,23 +1654,39 @@ def test_strategy(self): # It's actually impossible to Defect on the third move. actions += [(D, D)] # (D, C, *) gets updated, then checked. actions += [(C, D)] # (D, C, *) gets updated, but (D, D, *) checked. - actions += [(D, D)] * 30 # (D, D, *) gets updated and checked from here on. + actions += [ + (D, D) + ] * 30 # (D, D, *) gets updated and checked from here on. self.versus_test(axl.Defector(), expected_actions=actions) actions = [(C, C), (C, D)] - actions += [(C, C)] # Increment (C, C, C). Check (C, C, *). Cooperate. + actions += [ + (C, C) + ] # Increment (C, C, C). Check (C, C, *). Cooperate. # Reminder that first C is default value and last C is opponent's first move. - actions += [(C, D)] # Increment (C, C, D). Check (D, C, *) = 0. Cooperate. - actions += [(C, C)] # Increment (D, C, C). Check (C, C, *) = 0. Cooperate. + actions += [ + (C, D) + ] # Increment (C, C, D). Check (D, C, *) = 0. Cooperate. + actions += [ + (C, C) + ] # Increment (D, C, C). Check (C, C, *) = 0. Cooperate. # There is one Defection and one Cooperation in this scenario, # but the Cooperation was due to a default value only. We can see where this is going. - actions += [(C, D)] # Increment (C, C, D). Check (D, C, *) = 1. Cooperate. - actions += [(D, C)] # Increment (D, C, C). Check (C, C, *) = -1. Defect. + actions += [ + (C, D) + ] # Increment (C, C, D). Check (D, C, *) = 1. Cooperate. + actions += [ + (D, C) + ] # Increment (D, C, C). Check (C, C, *) = -1. Defect. actions += [ (C, D) ] # Increment (C, C, D). Check (D, D, *) = 0 (New). Cooperate. - actions += [(D, C)] # Increment (D, D, C). Check (C, C, *) < 0. Defect. - actions += [(C, D)] # Increment (C, C, D). Check (D, D, *) > 0. Cooperate. + actions += [ + (D, C) + ] # Increment (D, D, C). Check (C, C, *) < 0. Defect. + actions += [ + (C, D) + ] # Increment (C, C, D). Check (D, D, *) > 0. Cooperate. actions += [(D, C), (C, D)] * 15 # This pattern continues for a while. actions += [ (D, C), @@ -1809,7 +1870,9 @@ def test_strategy(self): opponent_actions = [C] * 100 + [D] * 10 Change_of_Heart = axl.MockPlayer(actions=opponent_actions) actions = [(C, C)] * 100 + [(C, D)] * 4 - self.versus_test(Change_of_Heart, expected_actions=actions, attrs={"credit": 2}) + self.versus_test( + Change_of_Heart, expected_actions=actions, attrs={"credit": 2} + ) Change_of_Heart = axl.MockPlayer(actions=opponent_actions) actions += [(C, D)] * 2 self.versus_test( @@ -1817,6 +1880,7 @@ def test_strategy(self): ) # Still Cooperate, because Defect rate is low + class TestRowsam(TestPlayer): name = "Second by Rowsam" player = axl.SecondByRowsam @@ -1838,12 +1902,18 @@ 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 @@ -1851,8 +1921,11 @@ 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 @@ -1860,8 +1933,11 @@ 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 @@ -1869,8 +1945,11 @@ 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,8 +1957,11 @@ 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 @@ -1887,27 +1969,42 @@ 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): @@ -1939,36 +2036,42 @@ 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 @@ -1985,51 +2088,66 @@ 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 1f580c9cf..c4a988aec 100644 --- a/axelrod/tests/strategies/test_backstabber.py +++ b/axelrod/tests/strategies/test_backstabber.py @@ -117,9 +117,13 @@ def test_when_alt_strategy_is_triggered(self): def test_starting_defect_keeps_alt_strategy_from_triggering(self): opponent_actions_suffix = [C, D, C, D, D] + 3 * [C] - expected_actions_suffix = [(C, C), (C, D), (C, C), (C, D), (C, D)] + 3 * [ - (D, C) - ] + expected_actions_suffix = [ + (C, C), + (C, D), + (C, C), + (C, D), + (C, D), + ] + 3 * [(D, C)] defects_on_first = [D] + [C] * 6 defects_on_first_actions = [(C, D)] + [(C, C)] * 6 diff --git a/axelrod/tests/strategies/test_calculator.py b/axelrod/tests/strategies/test_calculator.py index 3b2dc66c8..aea080aaf 100644 --- a/axelrod/tests/strategies/test_calculator.py +++ b/axelrod/tests/strategies/test_calculator.py @@ -31,7 +31,12 @@ def test_twenty_rounds_joss_then_defects_for_cyclers(self): twenty_alternator_actions, flip_indices ) - expected_actions = twenty_test_actions + [(D, C), (D, D), (D, C), (D, D)] + expected_actions = twenty_test_actions + [ + (D, C), + (D, D), + (D, C), + (D, D), + ] self.versus_test( axl.Alternator(), expected_actions=twenty_test_actions, seed=seed ) @@ -82,7 +87,9 @@ def test_twenty_rounds_joss_then_tit_for_tat_for_non_cyclers(self): (D, C), ] - opponent_actions = twenty_non_cyclical_actions + subsequent_opponent_actions + opponent_actions = ( + twenty_non_cyclical_actions + subsequent_opponent_actions + ) test_actions = twenty_test_actions + subsequent_test_actions self.versus_test( axl.MockPlayer(actions=twenty_non_cyclical_actions), @@ -98,7 +105,9 @@ def test_twenty_rounds_joss_then_tit_for_tat_for_non_cyclers(self): def test_edge_case_calculator_sees_cycles_of_size_ten(self): seed = 3 ten_length_cycle = [C, D, C, C, D, C, C, C, D, C] - self.assertEqual(detect_cycle((ten_length_cycle * 2)), tuple(ten_length_cycle)) + self.assertEqual( + detect_cycle((ten_length_cycle * 2)), tuple(ten_length_cycle) + ) ten_cycle_twenty_rounds = get_joss_strategy_actions( ten_length_cycle * 2, indices_to_flip=[16] @@ -122,7 +131,9 @@ def test_edge_case_calculator_ignores_cycles_gt_len_ten(self): ) opponent_actions = twenty_rounds_of_eleven_len_cycle[:-1] + [D] + [C, D] - self.assertEqual(detect_cycle(opponent_actions), tuple(eleven_length_cycle)) + self.assertEqual( + detect_cycle(opponent_actions), tuple(eleven_length_cycle) + ) uses_tit_for_tat_after_twenty_rounds = twenty_rounds + [(D, C), (C, D)] self.versus_test( @@ -142,13 +153,19 @@ def test_get_joss_strategy_actions(self): self.assertEqual(get_joss_strategy_actions(opponent, []), without_flip) self.assertEqual( - get_joss_strategy_actions(opponent, flip_never_occurs_at_index_zero), + get_joss_strategy_actions( + opponent, flip_never_occurs_at_index_zero + ), without_flip, ) - self.assertEqual(get_joss_strategy_actions(opponent, flip_indices), with_flip) + self.assertEqual( + get_joss_strategy_actions(opponent, flip_indices), with_flip + ) -def get_joss_strategy_actions(opponent_moves: list, indices_to_flip: list) -> list: +def get_joss_strategy_actions( + opponent_moves: list, indices_to_flip: list +) -> list: """ Takes a list of opponent moves and returns a tuple list of [(Joss moves, opponent moves)]. "indices_to_flip" are the indices where Joss differs from it's expected TitForTat. diff --git a/axelrod/tests/strategies/test_cooperator.py b/axelrod/tests/strategies/test_cooperator.py index aca2290ae..7dd4e7d3b 100644 --- a/axelrod/tests/strategies/test_cooperator.py +++ b/axelrod/tests/strategies/test_cooperator.py @@ -41,7 +41,9 @@ class TestTrickyCooperator(TestPlayer): def test_strategy(self): # Test if it tries to trick opponent. - self.versus_test(axl.Cooperator(), [(C, C), (C, C), (C, C), (D, C), (D, C)]) + self.versus_test( + axl.Cooperator(), [(C, C), (C, C), (C, C), (D, C), (D, C)] + ) opponent_actions = [C, C, C, C, D, D] expected_actions = [(C, C), (C, C), (C, C), (D, C), (D, D), (C, D)] @@ -68,7 +70,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) @@ -76,4 +78,6 @@ def test_defects_after_three_rounds_if_opponent_only_cooperated_in_max_history_d def test_defects_when_opponent_has_no_defections_to_history_depth_ten(self): opponent_actions = [D] + [C] * 10 + [D, C] expected_actions = [(C, D)] + [(C, C)] * 10 + [(D, D), (C, C)] - self.versus_test(axl.MockPlayer(actions=opponent_actions), expected_actions) + self.versus_test( + axl.MockPlayer(actions=opponent_actions), expected_actions + ) diff --git a/axelrod/tests/strategies/test_cycler.py b/axelrod/tests/strategies/test_cycler.py index 83de4f135..e8458e0ee 100644 --- a/axelrod/tests/strategies/test_cycler.py +++ b/axelrod/tests/strategies/test_cycler.py @@ -97,7 +97,9 @@ def test_memory_depth_is_len_cycle_minus_one(self): def test_cycler_works_as_expected(self): expected = [(C, D), (D, D), (D, D), (C, D)] * 2 self.versus_test( - axl.Defector(), expected_actions=expected, init_kwargs={"cycle": "CDDC"} + axl.Defector(), + expected_actions=expected, + init_kwargs={"cycle": "CDDC"}, ) def test_cycle_raises_value_error_on_bad_cycle_str(self): @@ -168,7 +170,8 @@ def test_normalized_parameters(self): cycle = "C" * random.randint(0, 20) + "D" * random.randint(0, 20) self.assertEqual( - self.player_class._normalize_parameters(cycle=cycle), (cycle, len(cycle)) + self.player_class._normalize_parameters(cycle=cycle), + (cycle, len(cycle)), ) cycle_length = random.randint(1, 20) diff --git a/axelrod/tests/strategies/test_darwin.py b/axelrod/tests/strategies/test_darwin.py index 8aa0b6391..76d516108 100644 --- a/axelrod/tests/strategies/test_darwin.py +++ b/axelrod/tests/strategies/test_darwin.py @@ -76,7 +76,9 @@ def test_against_geller_and_mindreader(self): def test_reset_history_and_attributes(self): # Overwrite this method because Darwin does not reset - self.versus_test(axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 4) + self.versus_test( + axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 4 + ) p1 = self.player() self.assertEqual(p1.genome, [D, C, C, C, D]) @@ -89,7 +91,9 @@ def test_all_darwin_instances_share_one_genome(self): p2 = self.player() self.assertIs(p1.genome, p2.genome) - self.versus_test(axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 4) + self.versus_test( + axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 4 + ) self.assertEqual(p2.genome, [D, C, C, C, D]) self.assertIs(p1.genome, p2.genome) @@ -97,7 +101,9 @@ def test_all_darwin_instances_share_one_genome(self): self.assertIs(p3.genome, p2.genome) def test_reset_genome(self): - self.versus_test(axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 4) + self.versus_test( + axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 4 + ) self.player.reset_genome() self.assertEqual(self.player().genome, [C]) diff --git a/axelrod/tests/strategies/test_dbs.py b/axelrod/tests/strategies/test_dbs.py index 93d61e41a..a3afb81a4 100644 --- a/axelrod/tests/strategies/test_dbs.py +++ b/axelrod/tests/strategies/test_dbs.py @@ -67,7 +67,9 @@ def test_move_gen_cooperator(self): """ expected_output = [D, D, D, D] for inp, out in zip(self.input_pos, expected_output): - out_move = dbs.move_gen(inp, self.cooperator_policy, depth_search_tree=5) + out_move = dbs.move_gen( + inp, self.cooperator_policy, depth_search_tree=5 + ) self.assertEqual(out_move, out) def test_minimaxTreeSearch_defector(self): @@ -89,7 +91,9 @@ def test_move_gen_defector(self): """ expected_output = [D, D, D, D] for inp, out in zip(self.input_pos, expected_output): - out_move = dbs.move_gen(inp, self.defector_policy, depth_search_tree=5) + out_move = dbs.move_gen( + inp, self.defector_policy, depth_search_tree=5 + ) self.assertEqual(out_move, out) def test_minimaxTreeSearch_titForTat(self): @@ -125,7 +129,9 @@ def test_move_gen_titForTat(self): """ expected_output = [C, C, C, C] for inp, out in zip(self.input_pos, expected_output): - out_move = dbs.move_gen(inp, self.titForTat_policy, depth_search_tree=5) + out_move = dbs.move_gen( + inp, self.titForTat_policy, depth_search_tree=5 + ) self.assertEqual(out_move, out) def test_minimaxTreeSearch_alternator(self): @@ -147,7 +153,9 @@ def test_move_gen_alternator(self): """ expected_output = [D, D, D, D] for inp, out in zip(self.input_pos, expected_output): - out_move = dbs.move_gen(inp, self.random_policy, depth_search_tree=5) + out_move = dbs.move_gen( + inp, self.random_policy, depth_search_tree=5 + ) self.assertEqual(out_move, out) def test_minimaxTreeSearch_random(self): @@ -169,7 +177,9 @@ def test_move_gen_random(self): """ expected_output = [D, D, D, D] for inp, out in zip(self.input_pos, expected_output): - out_move = dbs.move_gen(inp, self.random_policy, depth_search_tree=5) + out_move = dbs.move_gen( + inp, self.random_policy, depth_search_tree=5 + ) self.assertEqual(out_move, out) def test_minimaxTreeSearch_grudger(self): @@ -192,7 +202,9 @@ def test_move_gen_grudger(self): """ expected_output = [C, D, D, D] for inp, out in zip(self.input_pos, expected_output): - out_move = dbs.move_gen(inp, self.grudger_policy, depth_search_tree=5) + out_move = dbs.move_gen( + inp, self.grudger_policy, depth_search_tree=5 + ) self.assertEqual(out_move, out) diff --git a/axelrod/tests/strategies/test_doubler.py b/axelrod/tests/strategies/test_doubler.py index e3d436302..a02f42695 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 ccb6ac37d..101c2f783 100644 --- a/axelrod/tests/strategies/test_evolvable_player.py +++ b/axelrod/tests/strategies/test_evolvable_player.py @@ -4,17 +4,19 @@ import axelrod as axl from axelrod.action import Action -from axelrod.evolvable_player import copy_lists, crossover_lists, crossover_dictionaries +from axelrod.evolvable_player import ( + copy_lists, + crossover_lists, + crossover_dictionaries, +) from .test_player import TestPlayer C, D = Action.C, Action.D def PartialClass(cls, **kwargs): - class PartialedClass(cls): - __init__ = functools.partialmethod( - cls.__init__, **kwargs) + __init__ = functools.partialmethod(cls.__init__, **kwargs) return PartialedClass @@ -41,7 +43,9 @@ def mutate(self): def crossover(self, other): if other.__class__ != self.__class__: - raise TypeError("Crossover must be between the same player classes.") + raise TypeError( + "Crossover must be between the same player classes." + ) value = self.value + other.value return EvolvableTestOpponent(value) @@ -119,7 +123,11 @@ def test_crossover(self): players.append(player) player1, player2 = players crossed = player1.crossover(player2) - if player1 != crossed and player2 != crossed and crossed == crossed.clone(): + if ( + player1 != crossed + and player2 != crossed + and crossed == crossed.clone() + ): return # Should never get here unless a change breaks the test, so don't include in coverage. self.assertFalse(True) # pragma: no cover @@ -135,7 +143,9 @@ def test_serialization(self): axl.seed(0) player = self.player() serialized = player.serialize_parameters() - deserialized_player = player.__class__.deserialize_parameters(serialized) + deserialized_player = player.__class__.deserialize_parameters( + serialized + ) self.assertEqual(player, deserialized_player) self.assertEqual(deserialized_player, deserialized_player.clone()) @@ -145,7 +155,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()) @@ -176,12 +186,13 @@ def test_behavior(self): self.behavior_test(player, parent_player) serialized = player.serialize_parameters() - deserialized_player = player.__class__.deserialize_parameters(serialized) + deserialized_player = player.__class__.deserialize_parameters( + serialized + ) self.behavior_test(deserialized_player, parent_player) class TestUtilityFunctions(unittest.TestCase): - def test_copy_lists(self): l1 = [list(range(10)), list(range(20))] l2 = copy_lists(l1) @@ -200,14 +211,13 @@ 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 12fe52e5d..c40a44b86 100644 --- a/axelrod/tests/strategies/test_finite_state_machines.py +++ b/axelrod/tests/strategies/test_finite_state_machines.py @@ -5,9 +5,15 @@ import random import axelrod as axl -from axelrod.compute_finite_state_machine_memory import get_memory_from_transitions +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 @@ -44,8 +50,15 @@ def test__eq__false_by_state(self): self.assertFalse(new_two_state.__eq__(self.two_state)) def test__eq__false_by_transition(self): - different_transitions = ((1, C, 0, D), (1, D, 0, D), (0, C, 1, D), (0, D, 1, C)) - new_two_state = SimpleFSM(transitions=different_transitions, initial_state=1) + different_transitions = ( + (1, C, 0, D), + (1, D, 0, D), + (0, C, 1, D), + (0, D, 1, C), + ) + new_two_state = SimpleFSM( + transitions=different_transitions, initial_state=1 + ) self.assertFalse(new_two_state.__eq__(self.two_state)) @@ -89,7 +102,9 @@ def test_state_setter_raises_error_for_bad_input(self): with self.assertRaises(ValueError) as cm: self.two_state.state = 5 error_msg = cm.exception.args[0] - self.assertEqual(error_msg, "state: 5 does not have values for both C and D") + self.assertEqual( + error_msg, "state: 5 does not have values for both C and D" + ) class TestSampleFSMPlayer(TestPlayer): @@ -155,7 +170,12 @@ def test_wsls(self): """Tests that the player defined by the table for TFT is in fact WSLS (also known as Pavlov.""" wsls_init_kwargs = { - "transitions": ((1, C, 1, C), (1, D, 2, D), (2, C, 2, D), (2, D, 1, C)), + "transitions": ( + (1, C, 1, C), + (1, D, 2, D), + (2, C, 2, D), + (2, D, 1, C), + ), "initial_state": 1, "initial_action": C, } @@ -270,7 +290,9 @@ def test_strategy(self): opponent = axl.MockPlayer([D, D, C, C, D]) actions = [(C, D), (C, D), (C, C), (D, C), (C, D)] self.versus_test( - opponent, expected_actions=actions, init_kwargs={"transitions": transitions} + opponent, + expected_actions=actions, + init_kwargs={"transitions": transitions}, ) def test_memory(self): @@ -278,7 +300,10 @@ 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): @@ -309,7 +334,15 @@ def test_strategy(self): state_and_actions = [(1, C), (1, D), (2, C), (1, C)] self.transitions_test(state_and_actions) - state_and_actions = [(1, D), (2, D), (3, C), (3, C), (3, C), (3, D), (1, C)] * 2 + state_and_actions = [ + (1, D), + (2, D), + (3, C), + (3, C), + (3, C), + (3, D), + (1, C), + ] * 2 self.transitions_test(state_and_actions) @unittest.expectedFailure @@ -413,11 +446,15 @@ def test_strategy(self): ] + [(7, D), (7, C), (8, C), (8, D), (6, D)] * 3 self.transitions_test(state_and_actions) - state_and_actions = [(0, D), (1, C), (2, D), (3, C), (5, D), (3, C), (5, C)] + [ - (7, C), - (8, D), - (6, C), - ] * 5 + state_and_actions = [ + (0, D), + (1, C), + (2, D), + (3, C), + (5, D), + (3, C), + (5, C), + ] + [(7, C), (8, D), (6, C),] * 5 self.transitions_test(state_and_actions) state_and_actions = ( @@ -518,7 +555,9 @@ class TestRipoff(TestFSMPlayer): """ def test_strategy(self): - state_and_actions = [(1, C), (2, C)] * 3 + [(1, D)] + [(3, C), (3, D)] * 5 + state_and_actions = ( + [(1, C), (2, C)] * 3 + [(1, D)] + [(3, C), (3, D)] * 5 + ) self.transitions_test(state_and_actions) state_and_actions = [(1, C), (2, D)] + [(3, D)] * 5 @@ -619,7 +658,11 @@ class TestSolutionB1(TestFSMPlayer): def test_strategy(self): state_and_actions = ( - [(1, D)] * 3 + [(1, C)] + [(2, C)] * 3 + [(2, D)] + [(3, C), (3, D)] * 3 + [(1, D)] * 3 + + [(1, C)] + + [(2, C)] * 3 + + [(2, D)] + + [(3, C), (3, D)] * 3 ) self.transitions_test(state_and_actions) @@ -800,7 +843,9 @@ class TestEvolvedFSM16(TestFSMPlayer): def test_strategy(self): # finished: 0, - state_and_actions = [(0, C)] * 3 + [(0, D)] + [(12, D), (11, D), (5, C)] * 3 + state_and_actions = ( + [(0, C)] * 3 + [(0, D)] + [(12, D), (11, D), (5, C)] * 3 + ) self.transitions_test(state_and_actions) # finished: 0, 5, 10 @@ -847,7 +892,13 @@ def test_strategy(self): self.transitions_test(state_and_actions) # finished: 0, 1, 2, 3, 5, 10, 11, 12, 13, 14, 15 - state_and_actions = to_state_seven + [(7, D), (1, D), (6, C), (5, D), (10, C)] + state_and_actions = to_state_seven + [ + (7, D), + (1, D), + (6, C), + (5, D), + (10, C), + ] self.transitions_test(state_and_actions) # finished: 0, 1, 2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15 @@ -977,7 +1028,12 @@ def test_strategy(self): # finished 0, 1, 2, 3, 4, 5, 6, 8, 10, 12, 13, 15 to_state_eleven = [(0, D), (3, C), (10, D), (1, D), (15, D)] - state_and_actions = to_state_eleven + [(11, C), (14, C), (3, C), (10, D)] + state_and_actions = to_state_eleven + [ + (11, C), + (14, C), + (3, C), + (10, D), + ] self.transitions_test(state_and_actions) # finished 0, 1, 2, 3, 4, 5, 6, 8, 10, 11, 12, 13, 15 @@ -1049,21 +1105,23 @@ 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) @@ -1078,7 +1136,9 @@ def test_vector_to_instance(self): self.assertIsInstance(player, axl.EvolvableFSMPlayer) serialized = player.serialize_parameters() - deserialized_player = player.__class__.deserialize_parameters(serialized) + deserialized_player = player.__class__.deserialize_parameters( + serialized + ) self.assertEqual(player, deserialized_player) self.assertEqual(deserialized_player, deserialized_player.clone()) @@ -1114,7 +1174,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, } @@ -1123,7 +1183,8 @@ 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 e83b86d76..43754f5b0 100644 --- a/axelrod/tests/strategies/test_forgiver.py +++ b/axelrod/tests/strategies/test_forgiver.py @@ -25,15 +25,19 @@ def test_strategy(self): # If opponent has defected more than 10 percent of the time, defect. self.versus_test(axl.Cooperator(), expected_actions=[(C, C)] * 10) - self.versus_test(axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 10) + 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 self.versus_test( - axl.MockPlayer(actions=final_action_lowers_defections_to_ten_percent), + axl.MockPlayer( + actions=final_action_lowers_defections_to_ten_percent + ), expected_actions=expected * 5, ) @@ -62,7 +66,9 @@ class TestForgivingTitForTat(TestPlayer): def test_strategy(self): self.versus_test(axl.Cooperator(), expected_actions=[(C, C)] * 5) - self.versus_test(axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 5) + self.versus_test( + axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 5 + ) self.versus_test( axl.Alternator(), expected_actions=[(C, C)] + [(C, D), (D, C)] * 5 ) @@ -77,7 +83,11 @@ def test_never_defects_if_opponent_defections_le_ten_percent(self): def test_plays_tit_for_tat_while_defections_gt_ten_percent(self): before_tft = (18 * [C] + [D]) * 3 + [D, D, D] - only_cooperates = ([(C, C)] * 18 + [(C, D)]) * 3 + [(C, D), (C, D), (C, D)] + only_cooperates = ([(C, C)] * 18 + [(C, D)]) * 3 + [ + (C, D), + (C, D), + (C, D), + ] self.versus_test( axl.MockPlayer(actions=before_tft), expected_actions=only_cooperates ) diff --git a/axelrod/tests/strategies/test_gambler.py b/axelrod/tests/strategies/test_gambler.py index 4a3b3c5fb..aa1f37be3 100755 --- a/axelrod/tests/strategies/test_gambler.py +++ b/axelrod/tests/strategies/test_gambler.py @@ -140,13 +140,17 @@ def test_defect_forever(self): opponent_actions = [C] + [D] + [C] * 10 expected = [(C, C), (C, D)] + [(D, C)] * 10 self.versus_test( - axl.MockPlayer(opponent_actions), expected_actions=expected, seed=seed + axl.MockPlayer(opponent_actions), + expected_actions=expected, + seed=seed, ) opponent_actions = [D] + [C] * 10 expected = [(C, D)] + [(D, C)] * 10 self.versus_test( - axl.MockPlayer(opponent_actions), expected_actions=expected, seed=seed + axl.MockPlayer(opponent_actions), + expected_actions=expected, + seed=seed, ) @@ -378,7 +382,9 @@ def test_vs_alternator(self): new_seed = 1 expected[4] = (C, C) expected[6] = (D, C) - self.versus_test(axl.Alternator(), expected_actions=expected, seed=new_seed) + self.versus_test( + axl.Alternator(), expected_actions=expected, seed=new_seed + ) def test_vs_DCDDC(self): opponent_actions = [D, C, D, D, C] @@ -396,7 +402,9 @@ def test_vs_DCDDC(self): (C, D), ] self.versus_test( - axl.MockPlayer(opponent_actions), expected_actions=expected, seed=seed + axl.MockPlayer(opponent_actions), + expected_actions=expected, + seed=seed, ) new_seed = 3 @@ -493,18 +501,23 @@ def test_vs_alternator(self): new_seed = 1 expected = [(C, C), (C, D), (C, C), (D, D), (D, C), (C, D), (D, C)] - self.versus_test(axl.Alternator(), expected_actions=expected, seed=new_seed) + self.versus_test( + axl.Alternator(), expected_actions=expected, seed=new_seed + ) 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)) + 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) @@ -513,19 +526,24 @@ 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)) + 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)) + parameters=(plays, op_plays, op_start_plays) + ) lb, ub = player.create_vector_bounds() self.assertIsInstance(lb, list) self.assertIsInstance(ub, list) @@ -542,8 +560,7 @@ 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): @@ -551,8 +568,7 @@ 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): @@ -560,9 +576,11 @@ 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. @@ -570,7 +588,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 e2b7bdf67..c0647ce6e 100644 --- a/axelrod/tests/strategies/test_geller.py +++ b/axelrod/tests/strategies/test_geller.py @@ -43,7 +43,9 @@ def test_strategy(self): """Should cooperate against cooperators and defect against defectors.""" self.versus_test(axl.Defector(), expected_actions=[(D, D)] * 5) self.versus_test(axl.Cooperator(), expected_actions=[(C, C)] * 5) - self.versus_test(axl.Alternator(), expected_actions=[(C, C), (D, D)] * 5) + self.versus_test( + axl.Alternator(), expected_actions=[(C, C), (D, D)] * 5 + ) def test_strategy_against_lookerup_players(self): """ @@ -64,7 +66,9 @@ def test_returns_foil_inspection_strategy_of_opponent(self): seed=2, ) - self.versus_test(axl.Darwin(), expected_actions=[(C, C), (C, C), (C, C)]) + 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)], seed=1 @@ -91,10 +95,13 @@ def test_foil_strategy_inspection(self): def test_returns_foil_inspection_strategy_of_opponent(self): self.versus_test( - axl.GellerDefector(), expected_actions=[(D, C), (D, C), (D, C), (D, C)] + axl.GellerDefector(), + expected_actions=[(D, C), (D, C), (D, C), (D, C)], ) - self.versus_test(axl.Darwin(), expected_actions=[(C, C), (C, C), (C, C)]) + 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)] @@ -122,10 +129,13 @@ def test_foil_strategy_inspection(self): def test_returns_foil_inspection_strategy_of_opponent(self): self.versus_test( - axl.GellerDefector(), expected_actions=[(D, D), (D, D), (D, D), (D, D)] + axl.GellerDefector(), + expected_actions=[(D, D), (D, D), (D, D), (D, D)], ) - self.versus_test(axl.Darwin(), expected_actions=[(C, C), (C, C), (C, C)]) + 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)] diff --git a/axelrod/tests/strategies/test_gobymajority.py b/axelrod/tests/strategies/test_gobymajority.py index 6cd553880..88c5c555a 100644 --- a/axelrod/tests/strategies/test_gobymajority.py +++ b/axelrod/tests/strategies/test_gobymajority.py @@ -38,7 +38,9 @@ def test_memory_depth_infinite_soft_is_false(self): + [(C, C)] ) opponent = axl.MockPlayer(actions=opponent_actions) - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) def test_memory_depth_even_soft_is_false(self): memory_depth = 4 @@ -46,7 +48,9 @@ def test_memory_depth_even_soft_is_false(self): if self.default_soft: init_kwargs["soft"] = False - opponent = axl.MockPlayer(actions=[C] * memory_depth + [D] * memory_depth) + opponent = axl.MockPlayer( + actions=[C] * memory_depth + [D] * memory_depth + ) actions = ( [(D, C)] + [(C, C)] * 3 @@ -55,7 +59,9 @@ def test_memory_depth_even_soft_is_false(self): + [(D, C)] * 3 + [(C, C)] ) - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) def test_memory_depth_odd(self): memory_depth = 5 @@ -64,7 +70,9 @@ def test_memory_depth_odd(self): first_action = [(C, C)] else: first_action = [(D, C)] - opponent = axl.MockPlayer(actions=[C] * memory_depth + [D] * memory_depth) + opponent = axl.MockPlayer( + actions=[C] * memory_depth + [D] * memory_depth + ) actions = ( first_action + [(C, C)] * 4 @@ -73,7 +81,9 @@ def test_memory_depth_odd(self): + [(D, C)] * 3 + [(C, C)] * 2 ) - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) def test_default_values(self): player = self.player() @@ -90,7 +100,11 @@ class TestGoByMajority(TestHardGoByMajority): def test_memory_depth_infinite_soft_is_true(self): opponent_actions = [C] * 50 + [D] * 100 + [C] * 52 actions = ( - [(C, C)] * 50 + [(C, D)] * 51 + [(D, D)] * 49 + [(D, C)] * 50 + [(C, C)] * 2 + [(C, C)] * 50 + + [(C, D)] * 51 + + [(D, D)] * 49 + + [(D, C)] * 50 + + [(C, C)] * 2 ) opponent = axl.MockPlayer(actions=opponent_actions) self.versus_test(opponent, expected_actions=actions) @@ -100,8 +114,12 @@ def test_memory_depth_even_soft_is_true(self): init_kwargs = {"memory_depth": memory_depth} opponent = axl.MockPlayer([C] * memory_depth + [D] * memory_depth) - actions = [(C, C)] * 4 + [(C, D)] * 3 + [(D, D)] + [(D, C)] * 2 + [(C, C)] * 2 - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + actions = ( + [(C, C)] * 4 + [(C, D)] * 3 + [(D, D)] + [(D, C)] * 2 + [(C, C)] * 2 + ) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) def test_name(self): player = self.player(soft=True) @@ -161,7 +179,9 @@ def test_strategy(self): else: cooperations = int(memory_depth * 1.5) - 1 defections = len(opponent_actions) - cooperations - 1 - player_actions = first_player_action + [C] * cooperations + [D] * defections + player_actions = ( + first_player_action + [C] * cooperations + [D] * defections + ) actions = list(zip(player_actions, opponent_actions)) self.versus_test(opponent, expected_actions=actions) diff --git a/axelrod/tests/strategies/test_grudger.py b/axelrod/tests/strategies/test_grudger.py index 79194b5d8..3ec1d6ac4 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, @@ -258,11 +258,31 @@ def test_strategy(self): """Test strategy with multiple initial parameters""" # Testing default parameters of n=1, d=4, c=2 (same as Soft Grudger) - actions = [(C, D), (D, D), (D, C), (D, C), (D, D), (C, D), (C, C), (C, C)] - self.versus_test(axl.MockPlayer(actions=[D, D, C, C]), expected_actions=actions) + actions = [ + (C, D), + (D, D), + (D, C), + (D, C), + (D, D), + (C, D), + (C, C), + (C, C), + ] + self.versus_test( + axl.MockPlayer(actions=[D, D, C, C]), expected_actions=actions + ) # Testing n=2, d=4, c=2 - actions = [(C, D), (C, D), (D, C), (D, C), (D, D), (D, D), (C, C), (C, C)] + actions = [ + (C, D), + (C, D), + (D, C), + (D, C), + (D, D), + (D, D), + (C, C), + (C, C), + ] self.versus_test( axl.MockPlayer(actions=[D, D, C, C]), expected_actions=actions, @@ -270,7 +290,16 @@ def test_strategy(self): ) # Testing n=1, d=1, c=1 - actions = [(C, D), (D, D), (C, C), (C, C), (C, D), (D, D), (C, C), (C, C)] + actions = [ + (C, D), + (D, D), + (C, C), + (C, C), + (C, D), + (D, D), + (C, C), + (C, C), + ] self.versus_test( axl.MockPlayer(actions=[D, D, C, C]), expected_actions=actions, diff --git a/axelrod/tests/strategies/test_grumpy.py b/axelrod/tests/strategies/test_grumpy.py index 1fba6bbdd..fa0e5b327 100644 --- a/axelrod/tests/strategies/test_grumpy.py +++ b/axelrod/tests/strategies/test_grumpy.py @@ -46,32 +46,42 @@ def test_starting_state(self): actions = ([(C, D)] * 11 + [(D, C)] * 22 + [(C, D)] * 11) * 3 init_kwargs = {"starting_state": "Nice"} - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) opponent = axl.MockPlayer(actions=opponent_actions) grumpy_starting = [(D, D)] * 11 + [(D, C)] * 22 + [(C, D)] * 11 actions = grumpy_starting + actions init_kwargs = {"starting_state": "Grumpy"} - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) def test_thresholds(self): init_kwargs = {"grumpy_threshold": 3, "nice_threshold": -2} opponent_actions = [D] * 4 + [C] * 7 + [D] * 3 opponent = axl.MockPlayer(actions=opponent_actions) actions = ([(C, D)] * 4 + [(D, C)] * 7 + [(C, D)] * 3) * 3 - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) init_kwargs = {"grumpy_threshold": 0, "nice_threshold": -2} opponent_actions = [D] * 1 + [C] * 4 + [D] * 3 opponent = axl.MockPlayer(actions=opponent_actions) actions = ([(C, D)] * 1 + [(D, C)] * 4 + [(C, D)] * 3) * 3 - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) init_kwargs = {"grumpy_threshold": 3, "nice_threshold": 0} opponent_actions = [D] * 4 + [C] * 5 + [D] * 1 opponent = axl.MockPlayer(actions=opponent_actions) actions = ([(C, D)] * 4 + [(D, C)] * 5 + [(C, D)] * 1) * 3 - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) def test_reset_state_with_non_default_init(self): player = axl.Grumpy(starting_state="Grumpy") diff --git a/axelrod/tests/strategies/test_hmm.py b/axelrod/tests/strategies/test_hmm.py index 558da9bf4..02e32bc1d 100644 --- a/axelrod/tests/strategies/test_hmm.py +++ b/axelrod/tests/strategies/test_hmm.py @@ -201,7 +201,9 @@ def test_rounds(self): class TestEvolvedHMM5vsDefector(TestMatch): def test_rounds(self): - self.versus_test(axl.EvolvedHMM5(), axl.Defector(), [C, C, D], [D, D, D]) + self.versus_test( + axl.EvolvedHMM5(), axl.Defector(), [C, C, D], [D, D, D] + ) class TestEvolvableHMMPlayer(unittest.TestCase): diff --git a/axelrod/tests/strategies/test_human.py b/axelrod/tests/strategies/test_human.py index 46c1f3f8a..1588e728d 100644 --- a/axelrod/tests/strategies/test_human.py +++ b/axelrod/tests/strategies/test_human.py @@ -28,7 +28,9 @@ def test_validator(self): ActionValidator().validate(test_document) test_document = TestDocument("E") - self.assertRaises(ValidationError, ActionValidator().validate, test_document) + self.assertRaises( + ValidationError, ActionValidator().validate, test_document + ) class TestHumanClass(TestPlayer): diff --git a/axelrod/tests/strategies/test_inverse.py b/axelrod/tests/strategies/test_inverse.py index 3eaee2a89..452790c7b 100644 --- a/axelrod/tests/strategies/test_inverse.py +++ b/axelrod/tests/strategies/test_inverse.py @@ -27,7 +27,9 @@ def test_strategy(self): self.versus_test(axl.Cooperator(), expected_actions=[(C, C)]) # Tests that if opponent has played all D then player chooses D. - self.versus_test(axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 9) + self.versus_test( + axl.Defector(), expected_actions=[(C, D)] + [(D, D)] * 9 + ) expected_actions = [ (C, D), diff --git a/axelrod/tests/strategies/test_lookerup.py b/axelrod/tests/strategies/test_lookerup.py index c813233f2..dd73887c7 100755 --- a/axelrod/tests/strategies/test_lookerup.py +++ b/axelrod/tests/strategies/test_lookerup.py @@ -71,7 +71,9 @@ def test_from_pattern(self): table = LookupTable.from_pattern( pattern, player_depth=2, op_depth=1, op_openings_depth=0 ) - self.assertEqual(table.dictionary, make_keys_into_plays(self.lookup_dict)) + self.assertEqual( + table.dictionary, make_keys_into_plays(self.lookup_dict) + ) def test_from_pattern_raises_error_pattern_len_ne_dict_size(self): too_big = (C,) * 17 @@ -153,7 +155,9 @@ def test_plays_equals_tuple(self): self.assertEqual(Plays(1, 2, 3), (1, 2, 3)) def test_plays_assign_values(self): - self.assertEqual(Plays(op_plays=2, self_plays=1, op_openings=3), Plays(1, 2, 3)) + self.assertEqual( + Plays(op_plays=2, self_plays=1, op_openings=3), Plays(1, 2, 3) + ) def test_make_keys_into_plays(self): old = {((C, D), (C,), ()): 1, ((D, D), (D,), ()): 2} @@ -310,7 +314,9 @@ def test_set_memory_depth(self): self.assertEqual(axl.Classifiers["memory_depth"](mem_depth_3), 3) mem_depth_inf = axl.LookerUp(pattern="CC", parameters=Plays(0, 0, 1)) - self.assertEqual(axl.Classifiers["memory_depth"](mem_depth_inf), float("inf")) + self.assertEqual( + axl.Classifiers["memory_depth"](mem_depth_inf), float("inf") + ) def test_strategy(self): actions = [(C, C), (C, D), (D, C), (C, D)] @@ -378,10 +384,13 @@ def test_opponent_starting_moves_table(self): def test_lookup_table_display(self): player = axl.LookerUp( - pattern="CCCC", parameters=Plays(self_plays=2, op_plays=0, op_openings=0) + pattern="CCCC", + parameters=Plays(self_plays=2, op_plays=0, op_openings=0), ) self.assertEqual( - player.lookup_table_display(("self_plays", "op_plays", "op_openings")), + player.lookup_table_display( + ("self_plays", "op_plays", "op_openings") + ), ( "self_plays | op_plays |op_openings\n" + " C, C , , : C,\n" @@ -423,12 +432,16 @@ def test_new_data(self): def test_vs_initial_defector(self): opponent = [D, C, C, D, D, C] expected = [(C, D), (D, C), (C, C), (D, D), (D, D), (D, C)] - self.versus_test(axl.MockPlayer(actions=opponent), expected_actions=expected) + self.versus_test( + axl.MockPlayer(actions=opponent), expected_actions=expected + ) def test_vs_initial_cooperator(self): opponent = [C, D, D, C, C, D] expected = [(C, C), (C, D), (D, D), (D, C), (D, C), (D, D)] - self.versus_test(axl.MockPlayer(actions=opponent), expected_actions=expected) + self.versus_test( + axl.MockPlayer(actions=opponent), expected_actions=expected + ) class TestEvolvedLookerUp2_2_2(TestPlayer): @@ -524,7 +537,14 @@ def test_vs_initial_defector(self): def test_vs_initial_d_c(self): opponent_actions = [D, C] + [C, D] * 3 - expected = [(C, D), (C, C)] + [(D, C), (C, D), (C, C), (D, D), (C, C), (C, D)] + expected = [(C, D), (C, C)] + [ + (D, C), + (C, D), + (C, C), + (D, D), + (C, C), + (C, D), + ] self.versus_test( axl.MockPlayer(actions=opponent_actions), expected_actions=expected ) @@ -609,7 +629,9 @@ def test_strategy(self): vs_alternator = [(D, C), (C, D)] + [(D, C), (D, D)] * 5 self.versus_test(axl.Alternator(), expected_actions=vs_alternator) - self.versus_test(axl.Cooperator(), expected_actions=[(D, C)] + [(C, C)] * 10) + self.versus_test( + axl.Cooperator(), expected_actions=[(D, C)] + [(C, C)] * 10 + ) self.versus_test( axl.Defector(), expected_actions=([(D, D), (C, D)] + [(D, D)] * 10) @@ -621,7 +643,11 @@ def test_convert_key(self): opponent_starting_plays = "" player_last_plays = "CC" opponent_last_plays = "D" - old_key = (opponent_starting_plays, player_last_plays, opponent_last_plays) + old_key = ( + opponent_starting_plays, + player_last_plays, + opponent_last_plays, + ) new_key = Plays(self_plays=(C, C), op_plays=(D,), op_openings=()) diff --git a/axelrod/tests/strategies/test_memoryone.py b/axelrod/tests/strategies/test_memoryone.py index 784baadf4..c6bad1aa6 100644 --- a/axelrod/tests/strategies/test_memoryone.py +++ b/axelrod/tests/strategies/test_memoryone.py @@ -19,9 +19,15 @@ class TestGenericPlayerOne(unittest.TestCase): p3 = axl.MemoryOnePlayer(four_vector=(1, 0.5, 1, 0.5)) def test_name(self): - self.assertEqual(self.p1.name, "Generic Memory One Player: (0, 0, 0, 0)") - self.assertEqual(self.p2.name, "Generic Memory One Player: (1, 0, 1, 0)") - self.assertEqual(self.p3.name, "Generic Memory One Player: (1, 0.5, 1, 0.5)") + self.assertEqual( + self.p1.name, "Generic Memory One Player: (0, 0, 0, 0)" + ) + self.assertEqual( + self.p2.name, "Generic Memory One Player: (1, 0, 1, 0)" + ) + self.assertEqual( + self.p3.name, "Generic Memory One Player: (1, 0.5, 1, 0.5)" + ) def test_stochastic_classification(self): self.assertFalse(axl.Classifiers["stochastic"](self.p1)) @@ -87,10 +93,14 @@ class TestGTFT(TestPlayer): def test_strategy(self): actions = [(C, C), (C, D), (D, C), (C, D), (D, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=0 + ) actions = [(C, C), (C, D), (C, C), (C, D), (D, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=1) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=1 + ) def test_four_vector(self): (R, P, S, T) = axl.Game().RPST() @@ -128,10 +138,14 @@ def test_strategy(self): self.versus_test(opponent=axl.Alternator(), expected_actions=actions) actions = [(C, D), (D, D), (D, D), (D, D), (C, D)] - self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Defector(), expected_actions=actions, seed=0 + ) actions = [(C, D), (D, D), (C, D), (D, D), (D, D)] - self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=1) + self.versus_test( + opponent=axl.Defector(), expected_actions=actions, seed=1 + ) class TestStochasticCooperator(TestPlayer): @@ -159,16 +173,24 @@ def test_four_vector(self): def test_strategy(self): actions = [(C, C), (D, D), (C, C), (C, D), (C, C), (D, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=15) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=15 + ) actions = [(C, C), (C, D), (D, C), (D, D), (C, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=1) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=1 + ) 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, C), (C, D), (D, C), (D, D), (D, C), (C, D)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=13) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=13 + ) class TestStochasticWSLS(TestPlayer): @@ -187,16 +209,24 @@ class TestStochasticWSLS(TestPlayer): def test_strategy(self): actions = [(C, C), (D, D), (C, C), (C, D), (D, 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, C), (C, D), (D, C), (D, 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), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=2 + ) actions = [(C, D), (C, C), (C, D), (D, C), (D, D), (C, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=31) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=31 + ) def test_four_vector(self): player = self.player() @@ -214,7 +244,8 @@ class TestMemoryOnePlayer(unittest.TestCase): def test_default_if_four_vector_not_set(self): player = MemoryOnePlayer() self.assertEqual( - player._four_vector, {(C, C): 1.0, (C, D): 0.0, (D, C): 0.0, (D, D): 1.0} + player._four_vector, + {(C, C): 1.0, (C, D): 0.0, (D, C): 0.0, (D, D): 1.0}, ) def test_exception_if_four_vector_not_set(self): @@ -256,10 +287,14 @@ def test_four_vector(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, D), (D, C), (C, D), (D, C), (C, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=5 + ) class TestALLCorALLD(TestPlayer): @@ -278,9 +313,13 @@ class TestALLCorALLD(TestPlayer): def test_strategy(self): actions = [(D, C)] * 10 - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=0 + ) actions = [(C, C)] * 10 - self.versus_test(opponent=axl.Cooperator(), expected_actions=actions, seed=1) + self.versus_test( + opponent=axl.Cooperator(), expected_actions=actions, seed=1 + ) class TestGenericReactiveStrategy(unittest.TestCase): @@ -299,13 +338,16 @@ def test_name(self): def test_four_vector(self): self.assertEqual( - self.p1._four_vector, {(C, D): 0.0, (D, C): 0.0, (C, C): 0.0, (D, D): 0.0} + self.p1._four_vector, + {(C, D): 0.0, (D, C): 0.0, (C, C): 0.0, (D, D): 0.0}, ) self.assertEqual( - self.p2._four_vector, {(C, D): 0.0, (D, C): 1.0, (C, C): 1.0, (D, D): 0.0} + self.p2._four_vector, + {(C, D): 0.0, (D, C): 1.0, (C, C): 1.0, (D, D): 0.0}, ) self.assertEqual( - self.p3._four_vector, {(C, D): 0.5, (D, C): 1.0, (C, C): 1.0, (D, D): 0.5} + self.p3._four_vector, + {(C, D): 0.5, (D, C): 1.0, (C, C): 1.0, (D, D): 0.5}, ) def test_stochastic_classification(self): diff --git a/axelrod/tests/strategies/test_memorytwo.py b/axelrod/tests/strategies/test_memorytwo.py index 3318c6983..824e1a730 100644 --- a/axelrod/tests/strategies/test_memorytwo.py +++ b/axelrod/tests/strategies/test_memorytwo.py @@ -45,7 +45,24 @@ class TestGenericPlayerTwo(unittest.TestCase): ) ) p4 = MemoryTwoPlayer( - sixteen_vector=(0.1, 0, 0.2, 0, 0.3, 0, 0.4, 0, 0.5, 0, 0.6, 0, 0.7, 0, 0.8, 0) + sixteen_vector=( + 0.1, + 0, + 0.2, + 0, + 0.3, + 0, + 0.4, + 0, + 0.5, + 0, + 0.6, + 0, + 0.7, + 0, + 0.8, + 0, + ) ) def test_name(self): @@ -141,9 +158,7 @@ def test_exception_if_probability_vector_outside_valid_values(self): class TestMemoryStochastic(TestPlayer): - name = ( - "Generic Memory Two Player: (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1): C" - ) + name = "Generic Memory Two Player: (1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1): C" player = axl.MemoryTwoPlayer expected_classifier = { "memory_depth": 2, # Memory-two Sixteen-Vector @@ -217,7 +232,9 @@ def test_strategy(self): # tests states 3, 5 and 12 actions = [(C, D), (C, C), (D, C), (D, D), (D, D), (C, D)] - self.versus_test(opponent=axl.SuspiciousTitForTat(), expected_actions=actions) + self.versus_test( + opponent=axl.SuspiciousTitForTat(), expected_actions=actions + ) # tests state 1 actions = [(C, C), (C, C), (C, C), (C, C)] @@ -250,12 +267,15 @@ def test_strategy_mutually_cooperative(self): # tests states 1, 4 and 8 actions = [(C, D), (C, D), (D, D), (C, C), (C, C), (C, D)] self.versus_test( - opponent=axl.Cycler(["D", "D", "D", "C", "C"]), expected_actions=actions + opponent=axl.Cycler(["D", "D", "D", "C", "C"]), + expected_actions=actions, ) # tests states 3, 5 actions = [(C, D), (C, C), (D, C), (D, D), (C, D)] - self.versus_test(opponent=axl.SuspiciousTitForTat(), expected_actions=actions) + self.versus_test( + opponent=axl.SuspiciousTitForTat(), expected_actions=actions + ) class TestMEM2(TestPlayer): diff --git a/axelrod/tests/strategies/test_meta.py b/axelrod/tests/strategies/test_meta.py index 242ba1662..23d6a2b0a 100644 --- a/axelrod/tests/strategies/test_meta.py +++ b/axelrod/tests/strategies/test_meta.py @@ -41,7 +41,9 @@ def classifier_test(self, expected_class_classifier=None): for t in player.team: try: - classifier["makes_use_of"].update(axl.Classifiers["make_use_of"](t)) + classifier["makes_use_of"].update( + axl.Classifiers["make_use_of"](t) + ) except KeyError: pass @@ -329,7 +331,9 @@ def test_strategy(self): opponent = axl.MockPlayer([C] * 100 + [D]) actions = [(C, C)] * 100 + [(C, D), (D, C)] self.versus_test( - opponent=opponent, expected_actions=actions, init_kwargs={"team": team} + opponent=opponent, + expected_actions=actions, + init_kwargs={"team": team}, ) @@ -384,10 +388,14 @@ class TestMetaMajorityLongMemory(TestMetaPlayer): def test_strategy(self): actions = [(C, C), (C, D), (D, C), (C, D), (D, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=0 + ) actions = [(C, C), (C, D), (D, C), (C, D), (D, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=1) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=1 + ) class TestMetaWinnerMemoryOne(TestMetaPlayer): @@ -507,7 +515,12 @@ def test_strategy(self): ) team.append(axl.Defector) - distribution = [0.2, 0.5, 0.3, 0] # If add a defector but does not occur + distribution = [ + 0.2, + 0.5, + 0.3, + 0, + ] # If add a defector but does not occur self.versus_test( opponent=axl.Cooperator(), expected_actions=actions, @@ -569,7 +582,9 @@ class TestNMWEStochastic(TestMetaPlayer): def test_strategy(self): actions = [(C, C), (C, D), (C, C), (C, D), (D, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=20) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=20 + ) class TestNMWEFiniteMemory(TestMetaPlayer): @@ -605,7 +620,9 @@ class TestNMWELongMemory(TestMetaPlayer): def test_strategy(self): actions = [(C, C), (C, D), (C, C), (D, D), (D, C)] - self.versus_test(opponent=axl.Alternator(), expected_actions=actions, seed=10) + self.versus_test( + opponent=axl.Alternator(), expected_actions=actions, seed=10 + ) class TestNMWEMemoryOne(TestMetaPlayer): diff --git a/axelrod/tests/strategies/test_negation.py b/axelrod/tests/strategies/test_negation.py index 8c7542aaa..f74211b46 100644 --- a/axelrod/tests/strategies/test_negation.py +++ b/axelrod/tests/strategies/test_negation.py @@ -36,4 +36,6 @@ def test_strategy(self): 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) + self.versus_test( + opponent=axl.Defector(), expected_actions=actions, seed=2 + ) diff --git a/axelrod/tests/strategies/test_player.py b/axelrod/tests/strategies/test_player.py index 09a661160..cf971343d 100644 --- a/axelrod/tests/strategies/test_player.py +++ b/axelrod/tests/strategies/test_player.py @@ -93,10 +93,12 @@ def test_state_distribution(self): match = axl.Match((player1, player2), turns=5) _ = match.play() self.assertEqual( - player1.state_distribution, {(C, C): 1, (C, D): 2, (D, C): 1, (D, D): 1} + player1.state_distribution, + {(C, C): 1, (C, D): 2, (D, C): 1, (D, D): 1}, ) self.assertEqual( - player2.state_distribution, {(C, C): 1, (C, D): 1, (D, C): 2, (D, D): 1} + player2.state_distribution, + {(C, C): 1, (C, D): 1, (D, C): 2, (D, D): 1}, ) def test_noisy_play(self): @@ -129,7 +131,9 @@ def test_history_assignment(self): player.history = [] def test_strategy(self): - self.assertRaises(NotImplementedError, self.player().strategy, self.player()) + self.assertRaises( + NotImplementedError, self.player().strategy, self.player() + ) def test_clone(self): """Tests player cloning.""" @@ -345,7 +349,9 @@ def test_init_kwargs(self): # Test that passing an unknown keyword argument or a spare one raises # an error. self.assertRaises(TypeError, ParameterisedTestPlayer, arg_test3="test") - self.assertRaises(TypeError, ParameterisedTestPlayer, "other", "other", "other") + self.assertRaises( + TypeError, ParameterisedTestPlayer, "other", "other", "other" + ) class TestOpponent(axl.Player): @@ -496,7 +502,9 @@ def test_clone(self, seed): self.assertEqual(player1.history, player2.history) @given( - strategies=strategy_lists(max_size=5, strategies=short_run_time_short_mem), + strategies=strategy_lists( + max_size=5, strategies=short_run_time_short_mem + ), seed=integers(min_value=1, max_value=200), turns=integers(min_value=1, max_value=200), ) @@ -608,17 +616,23 @@ def classifier_test(self, expected_class_classifier=None): self.assertEqual(expected_class_classifier, self.player.classifier) self.assertTrue( - "memory_depth" in player.classifier, msg="memory_depth not in classifier" + "memory_depth" in player.classifier, + msg="memory_depth not in classifier", ) self.assertTrue( - "stochastic" in player.classifier, msg="stochastic not in classifier" + "stochastic" in player.classifier, + msg="stochastic not in classifier", ) for key in TestOpponent.classifier: self.assertEqual( axl.Classifiers[key](player), self.expected_classifier[key], msg="%s - Behaviour: %s != Expected Behaviour: %s" - % (key, axl.Classifiers[key](player), self.expected_classifier[key]), + % ( + key, + axl.Classifiers[key](player), + self.expected_classifier[key], + ), ) diff --git a/axelrod/tests/strategies/test_prober.py b/axelrod/tests/strategies/test_prober.py index 771e0115a..eb0b3b8a9 100644 --- a/axelrod/tests/strategies/test_prober.py +++ b/axelrod/tests/strategies/test_prober.py @@ -194,7 +194,28 @@ class TestProber4(TestPlayer): "manipulates_source": False, "manipulates_state": False, } - initial_sequence = [C, C, D, C, D, D, D, C, C, D, C, D, C, C, D, C, D, D, C, D] + initial_sequence = [ + C, + C, + D, + C, + D, + D, + D, + C, + C, + D, + C, + D, + C, + C, + D, + C, + D, + D, + C, + D, + ] def test_strategy(self): # Starts by playing CCDCDDDCCDCDCCDCDDCD. @@ -214,7 +235,9 @@ def test_strategy(self): for history in provocative_histories: opponent = axl.MockPlayer(history + [C] * 5) actions = list(zip(self.initial_sequence, history)) + [(D, C)] * 5 - self.versus_test(opponent=opponent, expected_actions=actions, attrs=attrs) + self.versus_test( + opponent=opponent, expected_actions=actions, attrs=attrs + ) # Otherwise cooperates for 5 rounds and plays TfT afterwards unprovocative_histories = [ @@ -230,7 +253,9 @@ def test_strategy(self): opponent = axl.MockPlayer(history + [D] * 5 + [C, C]) actions = list(zip(self.initial_sequence, history)) + [(C, D)] * 5 actions += [(D, C), (C, C)] - self.versus_test(opponent=opponent, expected_actions=actions, attrs=attrs) + self.versus_test( + opponent=opponent, expected_actions=actions, attrs=attrs + ) class TestHardProber(TestPlayer): diff --git a/axelrod/tests/strategies/test_qlearner.py b/axelrod/tests/strategies/test_qlearner.py index 81a261109..225ac5f5c 100644 --- a/axelrod/tests/strategies/test_qlearner.py +++ b/axelrod/tests/strategies/test_qlearner.py @@ -43,7 +43,13 @@ def test_strategy(self): "CC2.0": {C: 2.7, D: 0}, "CCC3.0": {C: 0, D: 0}, }, - "Vs": {"": 0.9, "0.0": 2.7, "C1.0": 4.5, "CC2.0": 2.7, "CCC3.0": 0}, + "Vs": { + "": 0.9, + "0.0": 2.7, + "C1.0": 4.5, + "CC2.0": 2.7, + "CCC3.0": 0, + }, "prev_state": "CCC3.0", }, ) @@ -77,7 +83,13 @@ def test_strategy(self): "CC2.0": {C: 2.7, D: 0}, "CCC3.0": {C: 0, D: 0}, }, - "Vs": {"": 0.9, "0.0": 2.7, "C1.0": 4.5, "CC2.0": 2.7, "CCC3.0": 0}, + "Vs": { + "": 0.9, + "0.0": 2.7, + "C1.0": 4.5, + "CC2.0": 2.7, + "CCC3.0": 0, + }, "prev_state": "CCC3.0", }, ) @@ -111,7 +123,13 @@ def test_strategy(self): "DD0.0": {C: 0, D: 0}, "DDD0.0": {C: 0, D: 0}, }, - "Vs": {"": 0.1, "0.0": 0.0, "D0.0": 0.1, "DD0.0": 0.0, "DDD0.0": 0}, + "Vs": { + "": 0.1, + "0.0": 0.0, + "D0.0": 0.1, + "DD0.0": 0.0, + "DDD0.0": 0, + }, "prev_state": "DDD0.0", }, ) @@ -145,7 +163,13 @@ def test_strategy(self): "DD0.0": {C: 0, D: 0}, "DDD0.0": {C: 0, D: 0}, }, - "Vs": {"": 0.1, "0.0": 0.0, "D0.0": 0.1, "DD0.0": 0.0, "DDD0.0": 0}, + "Vs": { + "": 0.1, + "0.0": 0.0, + "D0.0": 0.1, + "DD0.0": 0.0, + "DDD0.0": 0, + }, "prev_state": "DDD0.0", }, ) diff --git a/axelrod/tests/strategies/test_rand.py b/axelrod/tests/strategies/test_rand.py index 76bfb3478..045cc249c 100644 --- a/axelrod/tests/strategies/test_rand.py +++ b/axelrod/tests/strategies/test_rand.py @@ -33,11 +33,15 @@ def test_strategy(self): opponent = axl.MockPlayer() actions = [(D, C), (D, C), (D, C)] - self.versus_test(opponent, expected_actions=actions, init_kwargs={"p": 0}) + self.versus_test( + opponent, expected_actions=actions, init_kwargs={"p": 0} + ) opponent = axl.MockPlayer() actions = [(C, C), (C, C), (C, C)] - self.versus_test(opponent, expected_actions=actions, init_kwargs={"p": 1}) + self.versus_test( + opponent, expected_actions=actions, init_kwargs={"p": 1} + ) def test_deterministic_classification(self): """Test classification when p is 0 or 1""" diff --git a/axelrod/tests/strategies/test_retaliate.py b/axelrod/tests/strategies/test_retaliate.py index 251438735..b0b8b9f5d 100644 --- a/axelrod/tests/strategies/test_retaliate.py +++ b/axelrod/tests/strategies/test_retaliate.py @@ -93,14 +93,18 @@ def test_strategy(self): opponent = axl.Cooperator() actions = [(C, C)] * 5 self.versus_test( - opponent=opponent, expected_actions=actions, attrs={"retaliating": False} + opponent=opponent, + expected_actions=actions, + attrs={"retaliating": False}, ) # Retaliate after a (C, D) round. opponent = axl.MockPlayer([C, C, C, D, C]) actions = [(C, C), (C, C), (C, C), (C, D), (D, C), (D, C)] self.versus_test( - opponent=opponent, expected_actions=actions, attrs={"retaliating": True} + opponent=opponent, + expected_actions=actions, + attrs={"retaliating": True}, ) opponent = axl.Alternator() @@ -108,7 +112,9 @@ def test_strategy(self): # Count retaliations actions = [(C, C), (C, D), (D, C), (D, D), (D, C)] self.versus_test( - opponent=opponent, expected_actions=actions, attrs={"retaliation_count": 3} + opponent=opponent, + expected_actions=actions, + attrs={"retaliation_count": 3}, ) opponent = axl.Alternator() diff --git a/axelrod/tests/strategies/test_revised_downing.py b/axelrod/tests/strategies/test_revised_downing.py index b46f6fdcc..a97db8e63 100644 --- a/axelrod/tests/strategies/test_revised_downing.py +++ b/axelrod/tests/strategies/test_revised_downing.py @@ -4,6 +4,7 @@ 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 c0d9ec84c..a0af6729c 100644 --- a/axelrod/tests/strategies/test_selfsteem.py +++ b/axelrod/tests/strategies/test_selfsteem.py @@ -26,18 +26,31 @@ def test_strategy(self): # Check for f > 0.95, defect actions = ( - [(C, C), (C, C), (D, C), (D, C), (C, C), (D, C)] + [(C, C)] * 4 + [(D, C)] + [(C, C), (C, C), (D, C), (D, C), (C, C), (D, C)] + + [(C, C)] * 4 + + [(D, C)] ) self.versus_test(axl.Cooperator(), expected_actions=actions, seed=1) # Check for f < -0.95, cooperate - actions = [(D, C), (C, C), (D, C), (D, C), (C, C), (D, C), (C, C), (C, C)] + 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 ) actions = [(D, D)] + [(D, D)] * 5 + [(D, D), (C, D), (C, D)] - self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=0) + self.versus_test( + opponent=axl.Defector(), expected_actions=actions, seed=0 + ) # Check for -0.3 < f < 0.3, random actions = ( @@ -56,7 +69,9 @@ def test_strategy(self): + [(D, D)] * 8 + [(C, D), (C, D), (D, D), (D, D), (D, D)] ) - self.versus_test(opponent=axl.Defector(), expected_actions=actions, seed=5) + self.versus_test( + opponent=axl.Defector(), expected_actions=actions, seed=5 + ) # Check for 0.95 > abs(f) > 0.3, follows TitForTat actions = ( diff --git a/axelrod/tests/strategies/test_shortmem.py b/axelrod/tests/strategies/test_shortmem.py index 48dcd0138..525aea843 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, @@ -44,14 +44,26 @@ def test_strategy(self): ) # If neither of the above conditions are met, apply TitForTat - actions = [(C, D)] * 5 + [(C, C)] * 6 + [(C, D), (D, D), (D, D), (D, C), (C, C)] + actions = ( + [(C, D)] * 5 + + [(C, C)] * 6 + + [(C, D), (D, D), (D, D), (D, C), (C, C)] + ) self.versus_test( - opponent=axl.MockPlayer(actions=[D] * 5 + [C] * 6 + [D, D, D, C, C]), + opponent=axl.MockPlayer( + actions=[D] * 5 + [C] * 6 + [D, D, D, C, C] + ), expected_actions=actions, ) - actions = [(C, C)] * 5 + [(C, D)] * 6 + [(D, C), (C, C), (C, C), (C, D), (D, D)] + actions = ( + [(C, C)] * 5 + + [(C, D)] * 6 + + [(D, C), (C, C), (C, C), (C, D), (D, D)] + ) self.versus_test( - opponent=axl.MockPlayer(actions=[C] * 5 + [D] * 6 + [C, C, C, D, D]), + opponent=axl.MockPlayer( + actions=[C] * 5 + [D] * 6 + [C, C, C, D, D] + ), expected_actions=actions, ) diff --git a/axelrod/tests/strategies/test_stalker.py b/axelrod/tests/strategies/test_stalker.py index cc013543c..4177cd058 100644 --- a/axelrod/tests/strategies/test_stalker.py +++ b/axelrod/tests/strategies/test_stalker.py @@ -28,12 +28,14 @@ def test_strategy(self): # wish_score < current_average_score < very_good_score actions = [(C, C)] * 7 + [(C, D), (C, D), (C, C), (C, C), (D, C)] self.versus_test( - opponent=axl.MockPlayer(actions=[C] * 7 + [D] * 2), expected_actions=actions + opponent=axl.MockPlayer(actions=[C] * 7 + [D] * 2), + expected_actions=actions, ) actions = [(C, C)] * 7 + [(C, D), (C, C), (D, C)] self.versus_test( - opponent=axl.MockPlayer(actions=[C] * 7 + [D]), expected_actions=actions + opponent=axl.MockPlayer(actions=[C] * 7 + [D]), + expected_actions=actions, ) # current_average_score > 2 @@ -43,7 +45,8 @@ def test_strategy(self): # 1 < current_average_score < 2 actions = [(C, C)] * 7 + [(C, D)] * 4 + [(D, D)] self.versus_test( - opponent=axl.MockPlayer(actions=[C] * 7 + [D] * 5), expected_actions=actions + opponent=axl.MockPlayer(actions=[C] * 7 + [D] * 5), + expected_actions=actions, ) # current_average_score < 1 @@ -72,7 +75,9 @@ def test_strategy(self): # defect in last round actions = [(C, C)] * 199 + [(D, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, match_attributes={"length": 200} + axl.Cooperator(), + expected_actions=actions, + match_attributes={"length": 200}, ) # Force a defection before the end of the actual match which ensures diff --git a/axelrod/tests/strategies/test_titfortat.py b/axelrod/tests/strategies/test_titfortat.py index b62e4b918..0b5b44527 100644 --- a/axelrod/tests/strategies/test_titfortat.py +++ b/axelrod/tests/strategies/test_titfortat.py @@ -386,7 +386,16 @@ def test_strategy(self): ) opponent = axl.MockPlayer(actions=[D, C, D, C, C, C, D, C]) - actions = [(C, D), (D, C), (C, D), (C, C), (C, C), (C, C), (C, D), (D, C)] + actions = [ + (C, D), + (D, C), + (C, D), + (C, C), + (C, C), + (C, C), + (C, D), + (D, C), + ] self.versus_test( opponent, expected_actions=actions, @@ -394,7 +403,16 @@ def test_strategy(self): ) opponent = axl.MockPlayer(actions=[D, C, D, C, C, D, D, D]) - actions = [(C, D), (D, C), (C, D), (C, C), (C, C), (C, D), (D, D), (D, D)] + actions = [ + (C, D), + (D, C), + (C, D), + (C, C), + (C, C), + (C, D), + (D, D), + (D, D), + ] self.versus_test( opponent, expected_actions=actions, @@ -471,7 +489,9 @@ def test_specific_set_of_results(self): to a memory one player that start by defecting and only cooperates if both players cooperated in the previous round. """ - mistrust_with_bug = axl.MemoryOnePlayer(initial=D, four_vector=(1, 0, 0, 0),) + mistrust_with_bug = axl.MemoryOnePlayer( + initial=D, four_vector=(1, 0, 0, 0), + ) players = [ self.player(), axl.TitForTat(), @@ -615,7 +635,16 @@ def test_strategy(self): ) opponent = axl.MockPlayer(actions=[D, C, D, C, C, C, D, C]) - actions = [(C, D), (D, C), (C, D), (C, C), (C, C), (C, C), (C, D), (D, C)] + actions = [ + (C, D), + (D, C), + (C, D), + (C, C), + (C, C), + (C, C), + (C, D), + (D, C), + ] self.versus_test( opponent, expected_actions=actions, @@ -628,7 +657,16 @@ def test_strategy(self): ) opponent = axl.MockPlayer(actions=[D, C, D, C, C, D, D, D]) - actions = [(C, D), (D, C), (C, D), (C, C), (C, C), (C, D), (D, D), (D, D)] + actions = [ + (C, D), + (D, C), + (C, D), + (C, C), + (C, C), + (C, D), + (D, D), + (D, D), + ] self.versus_test( opponent, expected_actions=actions, @@ -716,7 +754,9 @@ def test_init(self): self.assertEqual(ctft._recorded_history, []) @given( - strategies=strategy_lists(strategies=deterministic_strategies, max_size=1), + strategies=strategy_lists( + strategies=deterministic_strategies, max_size=1 + ), turns=integers(min_value=1, max_value=20), ) def test_is_tit_for_tat_with_no_noise(self, strategies, turns): @@ -907,7 +947,9 @@ class TestEugineNier(TestPlayer): def test_strategy(self): actions = [(C, C), (C, C), (C, C), (D, C)] self.versus_test( - axl.Cooperator(), expected_actions=actions, attrs={"is_defector": False} + axl.Cooperator(), + expected_actions=actions, + attrs={"is_defector": False}, ) actions = [(C, C), (C, C), (C, C), (C, C)] @@ -921,7 +963,9 @@ def test_strategy(self): # Plays TfT and defects in last round actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (D, D)] self.versus_test( - axl.Alternator(), expected_actions=actions, attrs={"is_defector": False} + axl.Alternator(), + expected_actions=actions, + attrs={"is_defector": False}, ) actions = [(C, C), (C, D), (D, C), (C, D), (D, C), (C, D)] @@ -934,7 +978,16 @@ def test_strategy(self): # Becomes defector after 5 defections opponent = axl.MockPlayer(actions=[D, C, D, D, D, D, C, C]) - actions = [(C, D), (D, C), (C, D), (D, D), (D, D), (D, D), (D, C), (D, C)] + actions = [ + (C, D), + (D, C), + (C, D), + (D, D), + (D, D), + (D, D), + (D, C), + (D, C), + ] self.versus_test(opponent, expected_actions=actions) @@ -982,30 +1035,44 @@ def test_strategy(self): ) actions = [(C, D), (D, D), (D, C), (C, C), (C, D)] self.versus_test( - axl.Random(), expected_actions=actions, seed=0, init_kwargs=init_kwargs + axl.Random(), + expected_actions=actions, + seed=0, + init_kwargs=init_kwargs, ) actions = [(C, C), (C, D), (D, D), (D, C)] self.versus_test( - axl.Random(), expected_actions=actions, seed=1, init_kwargs=init_kwargs + axl.Random(), + expected_actions=actions, + seed=1, + init_kwargs=init_kwargs, ) opponent = axl.MockPlayer(actions=[C, D]) actions = [(C, C), (C, D), (D, C), (C, D)] - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) opponent = axl.MockPlayer(actions=[C, C, D, D, C, D]) actions = [(C, C), (C, C), (C, D), (D, D), (D, C), (C, D)] - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) # TitFor2Tats test_strategy init_kwargs = {"N": 1, "M": 2} opponent = axl.MockPlayer(actions=[D, D, D, C, C]) actions = [(C, D), (C, D), (D, D), (D, C), (C, C), (C, D)] - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) # TwoTitsForTat test_strategy init_kwargs = {"N": 2, "M": 1} opponent = axl.MockPlayer(actions=[D, C, C, D, C]) actions = [(C, D), (D, C), (D, C), (C, D), (D, C)] - self.versus_test(opponent, expected_actions=actions, init_kwargs=init_kwargs) + self.versus_test( + opponent, expected_actions=actions, init_kwargs=init_kwargs + ) actions = [(C, C), (C, C)] self.versus_test( opponent=axl.Cooperator(), @@ -1014,7 +1081,9 @@ def test_strategy(self): ) actions = [(C, D), (D, D), (D, D)] self.versus_test( - opponent=axl.Defector(), expected_actions=actions, init_kwargs=init_kwargs, + opponent=axl.Defector(), + expected_actions=actions, + init_kwargs=init_kwargs, ) # Cooperator test_strategy @@ -1164,7 +1233,9 @@ def test_strategy(self): ) actions = [(C, D), (D, D), (D, D)] - self.versus_test(axl.Defector(), expected_actions=actions, init_kwargs={"p": 0}) + self.versus_test( + axl.Defector(), expected_actions=actions, init_kwargs={"p": 0} + ) actions = [(C, C), (C, C), (D, C), (C, C)] self.versus_test( @@ -1172,7 +1243,9 @@ def test_strategy(self): ) actions = [(C, D), (D, D), (C, D), (D, D)] - self.versus_test(axl.Defector(), expected_actions=actions, init_kwargs={"p": 1}) + self.versus_test( + axl.Defector(), expected_actions=actions, init_kwargs={"p": 1} + ) actions = [(C, C), (C, C), (D, C), (C, C), (D, C), (C, C)] self.versus_test(axl.Cooperator(), expected_actions=actions, seed=2) diff --git a/axelrod/tests/strategies/test_worse_and_worse.py b/axelrod/tests/strategies/test_worse_and_worse.py index a402a5e15..8ae3146e0 100644 --- a/axelrod/tests/strategies/test_worse_and_worse.py +++ b/axelrod/tests/strategies/test_worse_and_worse.py @@ -98,7 +98,8 @@ def test_strategy(self): actions = [(C, C), (C, C), (C, D), (D, C)] self.versus_test( - opponent=axl.MockPlayer(actions=[C, C, D, C]), expected_actions=actions + opponent=axl.MockPlayer(actions=[C, C, D, C]), + expected_actions=actions, ) actions = [(C, C)] * 18 + [(C, D), (D, C)] diff --git a/axelrod/tests/strategies/test_zero_determinant.py b/axelrod/tests/strategies/test_zero_determinant.py index 615ca27fd..660ec063d 100644 --- a/axelrod/tests/strategies/test_zero_determinant.py +++ b/axelrod/tests/strategies/test_zero_determinant.py @@ -32,7 +32,12 @@ class TestZDExtortion(TestPlayer): } def test_four_vector(self): - expected_dictionary = {(C, C): 0.64, (C, D): 0.18, (D, C): 0.28, (D, D): 0} + expected_dictionary = { + (C, C): 0.64, + (C, D): 0.18, + (D, C): 0.28, + (D, D): 0, + } test_four_vector(self, expected_dictionary) def test_strategy(self): @@ -42,7 +47,9 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=6) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=6 + ) class TestZDExtort2(TestPlayer): @@ -60,7 +67,12 @@ class TestZDExtort2(TestPlayer): } def test_four_vector(self): - expected_dictionary = {(C, C): 8 / 9, (C, D): 0.5, (D, C): 1 / 3, (D, D): 0.0} + expected_dictionary = { + (C, C): 8 / 9, + (C, D): 0.5, + (D, C): 1 / 3, + (D, D): 0.0, + } test_four_vector(self, expected_dictionary) def test_receive_match_attributes(self): @@ -80,10 +92,14 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (D, D), (D, C), (C, D), (C, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=2 + ) actions = [(C, D), (C, C), (C, D), (C, C), (C, D), (C, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=31) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=31 + ) class TestZDExtort2v2(TestPlayer): @@ -116,7 +132,9 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=5 + ) class TestZDExtort3(TestPlayer): @@ -150,7 +168,9 @@ def test_strategy(self): actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=6) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=6 + ) class TestZDExtort4(TestPlayer): @@ -168,7 +188,12 @@ class TestZDExtort4(TestPlayer): } def test_four_vector(self): - expected_dictionary = {(C, C): 11 / 17, (C, D): 0, (D, C): 8 / 17, (D, D): 0.0} + expected_dictionary = { + (C, C): 11 / 17, + (C, D): 0, + (D, C): 8 / 17, + (D, D): 0.0, + } test_four_vector(self, expected_dictionary) def test_strategy(self): @@ -178,7 +203,9 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=5 + ) class TestZDGen2(TestPlayer): @@ -196,7 +223,12 @@ class TestZDGen2(TestPlayer): } def test_four_vector(self): - expected_dictionary = {(C, C): 1, (C, D): 9 / 16, (D, C): 1 / 2, (D, D): 1 / 8} + expected_dictionary = { + (C, C): 1, + (C, D): 9 / 16, + (D, C): 1 / 2, + (D, D): 1 / 8, + } test_four_vector(self, expected_dictionary) def test_strategy(self): @@ -212,10 +244,14 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (D, D), (C, C), (C, D), (C, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=2 + ) actions = [(C, D), (C, C), (C, D), (C, C), (C, D), (C, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=31) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=31 + ) class TestZDGTFT2(TestPlayer): @@ -232,7 +268,12 @@ class TestZDGTFT2(TestPlayer): } def test_four_vector(self): - expected_dictionary = {(C, C): 1.0, (C, D): 1 / 8, (D, C): 1.0, (D, D): 0.25} + expected_dictionary = { + (C, C): 1.0, + (C, D): 1 / 8, + (D, C): 1.0, + (D, D): 0.25, + } test_four_vector(self, expected_dictionary) def test_receive_match_attributes(self): @@ -252,10 +293,14 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (C, D), (D, C), (C, D), (C, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=2) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=2 + ) actions = [(C, D), (C, C), (C, D), (C, C), (C, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=31) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=31 + ) class TestZDMischief(TestPlayer): @@ -283,7 +328,9 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=5 + ) class TestZDSet2(TestPlayer): @@ -316,4 +363,6 @@ def test_strategy(self): ) actions = [(C, D), (D, C), (D, D), (D, C), (D, D), (D, C)] - self.versus_test(opponent=axl.CyclerDC(), expected_actions=actions, seed=5) + self.versus_test( + opponent=axl.CyclerDC(), expected_actions=actions, seed=5 + ) diff --git a/axelrod/tests/unit/test_classification.py b/axelrod/tests/unit/test_classification.py index e0db01e5d..e76af2ca2 100644 --- a/axelrod/tests/unit/test_classification.py +++ b/axelrod/tests/unit/test_classification.py @@ -50,7 +50,9 @@ def tearDown(self) -> None: def test_classifier_build(self): dirname = os.path.dirname(__file__) - test_path = os.path.join(dirname, "../../../test_outputs/classifier_test.yaml") + test_path = os.path.join( + dirname, "../../../test_outputs/classifier_test.yaml" + ) # Just returns the name of the player. For testing. name_classifier = Classifier[Text]("name", lambda player: player.name) @@ -66,7 +68,10 @@ def test_classifier_build(self): self.assertDictEqual( all_player_dicts, - {"Cooperator": {"name": "Cooperator"}, "Defector": {"name": "Defector"}}, + { + "Cooperator": {"name": "Cooperator"}, + "Defector": {"name": "Defector"}, + }, ) def test_singletonity_of_classifiers_class(self): @@ -91,7 +96,9 @@ def test_key_error_on_uknown_classifier(self): Classifiers["invalid_key"](axl.TitForTat) def test_will_lookup_key_in_dict(self): - self.assertEqual(Classifiers["memory_depth"](TitForTatWithEmptyClassifier), 1) + self.assertEqual( + Classifiers["memory_depth"](TitForTatWithEmptyClassifier), 1 + ) def test_will_lookup_key_for_classes_that_cant_init(self): with self.assertRaises(Exception) as exptn: @@ -114,7 +121,9 @@ def test_known_classifiers(self): for s in axl.all_strategies: s = s() - self.assertTrue(None not in [Classifiers[key](s) for key in known_keys]) + self.assertTrue( + None not in [Classifiers[key](s) for key in known_keys] + ) def test_multiple_instances(self): """Certain instances of classes of strategies will have different @@ -185,13 +194,19 @@ def test_obey_axelrod(self): ] for strategy in known_cheaters: - self.assertFalse(axl.Classifiers.obey_axelrod(strategy()), msg=strategy) + self.assertFalse( + axl.Classifiers.obey_axelrod(strategy()), msg=strategy + ) for strategy in known_basic: - self.assertTrue(axl.Classifiers.obey_axelrod(strategy()), msg=strategy) + self.assertTrue( + axl.Classifiers.obey_axelrod(strategy()), msg=strategy + ) for strategy in known_ordinary: - self.assertTrue(axl.Classifiers.obey_axelrod(strategy()), msg=strategy) + self.assertTrue( + axl.Classifiers.obey_axelrod(strategy()), msg=strategy + ) def test_is_basic(self): """A test that verifies if the is_basic function works correctly""" @@ -294,7 +309,9 @@ def test_inclusion_of_strategy_lists(self): axl.basic_strategies, axl.long_run_time_strategies, ]: - self.assertTrue(str_reps(strategy_list).issubset(str_reps(strategies_set))) + self.assertTrue( + str_reps(strategy_list).issubset(str_reps(strategies_set)) + ) def test_long_run_strategies(self): long_run_time_strategies = [ @@ -319,7 +336,8 @@ def test_long_run_strategies(self): ] self.assertEqual( - str_reps(long_run_time_strategies), str_reps(axl.long_run_time_strategies) + str_reps(long_run_time_strategies), + str_reps(axl.long_run_time_strategies), ) self.assertTrue( all(map(Classifiers["long_run_time"], axl.long_run_time_strategies)) @@ -331,10 +349,13 @@ def test_short_run_strategies(self): ] self.assertEqual( - str_reps(short_run_time_strategies), str_reps(axl.short_run_time_strategies) + str_reps(short_run_time_strategies), + str_reps(axl.short_run_time_strategies), ) self.assertFalse( - any(map(Classifiers["long_run_time"], axl.short_run_time_strategies)) + any( + map(Classifiers["long_run_time"], axl.short_run_time_strategies) + ) ) def test_meta_inclusion(self): @@ -353,4 +374,6 @@ def test_demo_strategies(self): axl.Grudger, axl.Random, ] - self.assertTrue(str_reps(demo_strategies), str_reps(axl.demo_strategies)) + self.assertTrue( + str_reps(demo_strategies), str_reps(axl.demo_strategies) + ) 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 82e828676..8d46c2ced 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) @@ -347,4 +347,3 @@ 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_deterministic_cache.py b/axelrod/tests/unit/test_deterministic_cache.py index 82d11904c..733cb862c 100644 --- a/axelrod/tests/unit/test_deterministic_cache.py +++ b/axelrod/tests/unit/test_deterministic_cache.py @@ -18,7 +18,9 @@ def setUpClass(cls): cls.test_save_file = axl_filename(save_path) load_path = pathlib.Path("test_outputs/test_cache_load.txt") cls.test_load_file = axl_filename(load_path) - test_data_to_pickle = {("Tit For Tat", "Defector"): [(C, D), (D, D), (D, D)]} + test_data_to_pickle = { + ("Tit For Tat", "Defector"): [(C, D), (D, D), (D, D)] + } cls.test_pickle = pickle.dumps(test_data_to_pickle) with open(cls.test_load_file, "wb") as f: diff --git a/axelrod/tests/unit/test_eigen.py b/axelrod/tests/unit/test_eigen.py index 36f0bf5b9..2f28a1207 100644 --- a/axelrod/tests/unit/test_eigen.py +++ b/axelrod/tests/unit/test_eigen.py @@ -8,7 +8,6 @@ from axelrod.eigen import _normalise, principal_eigenvector - class FunctionCases(unittest.TestCase): def test_identity_matrices(self): for size in range(2, 6): @@ -38,10 +37,14 @@ def test_3x3_matrix(self): ) self.assertAlmostEqual(evalue, 3) assert_array_almost_equal(evector, numpy.dot(mat, evector) / evalue) - assert_array_almost_equal(evector, _normalise(numpy.array([0.5, 0.5, 1]))) + assert_array_almost_equal( + evector, _normalise(numpy.array([0.5, 0.5, 1])) + ) def test_4x4_matrix(self): - mat = numpy.array([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]]) + mat = numpy.array( + [[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]] + ) evector, evalue = principal_eigenvector( mat, maximum_iterations=None, max_error=1e-10 ) diff --git a/axelrod/tests/unit/test_filters.py b/axelrod/tests/unit/test_filters.py index f2d9e2e17..c9f084aa4 100644 --- a/axelrod/tests/unit/test_filters.py +++ b/axelrod/tests/unit/test_filters.py @@ -19,10 +19,14 @@ class TestStrategy(Player): def test_equality_filter(self): self.assertTrue( - passes_operator_filter(self.TestStrategy, "stochastic", True, operator.eq) + passes_operator_filter( + self.TestStrategy, "stochastic", True, operator.eq + ) ) self.assertFalse( - passes_operator_filter(self.TestStrategy, "stochastic", False, operator.eq) + passes_operator_filter( + self.TestStrategy, "stochastic", False, operator.eq + ) ) self.assertTrue( passes_operator_filter( @@ -71,7 +75,9 @@ def test_list_filter(self): passes_in_list_filter(self.TestStrategy, "makes_use_of", ["length"]) ) self.assertTrue( - passes_in_list_filter(self.TestStrategy, "makes_use_of", ["game", "length"]) + passes_in_list_filter( + self.TestStrategy, "makes_use_of", ["game", "length"] + ) ) self.assertFalse( passes_in_list_filter(self.TestStrategy, "makes_use_of", "test") @@ -120,11 +126,21 @@ def test_passes_filterset(self, smaller, larger): "min_memory_depth": smaller, } - self.assertTrue(passes_filterset(self.TestStrategy, full_passing_filterset_1)) - self.assertTrue(passes_filterset(self.TestStrategy, full_passing_filterset_2)) - self.assertTrue(passes_filterset(self.TestStrategy, sparse_passing_filterset)) - self.assertFalse(passes_filterset(self.TestStrategy, full_failing_filterset)) - self.assertFalse(passes_filterset(self.TestStrategy, sparse_failing_filterset)) + self.assertTrue( + passes_filterset(self.TestStrategy, full_passing_filterset_1) + ) + self.assertTrue( + passes_filterset(self.TestStrategy, full_passing_filterset_2) + ) + self.assertTrue( + passes_filterset(self.TestStrategy, sparse_passing_filterset) + ) + self.assertFalse( + passes_filterset(self.TestStrategy, full_failing_filterset) + ) + self.assertFalse( + passes_filterset(self.TestStrategy, sparse_failing_filterset) + ) def test_filtered_strategies(self): class StochasticTestStrategy(Player): @@ -135,7 +151,11 @@ class StochasticTestStrategy(Player): } class MemoryDepth2TestStrategy(Player): - classifier = {"stochastic": False, "memory_depth": 2, "makes_use_of": []} + classifier = { + "stochastic": False, + "memory_depth": 2, + "makes_use_of": [], + } class UsesLengthTestStrategy(Player): classifier = { diff --git a/axelrod/tests/unit/test_fingerprint.py b/axelrod/tests/unit/test_fingerprint.py index f60a93e7a..e68ae3bb2 100644 --- a/axelrod/tests/unit/test_fingerprint.py +++ b/axelrod/tests/unit/test_fingerprint.py @@ -94,7 +94,9 @@ def test_fingerprint_player(self): self.assertEqual(af.points, self.points_when_using_half_step) self.assertEqual(af.spatial_tournament.turns, 5) self.assertEqual(af.spatial_tournament.repetitions, 3) - self.assertEqual(af.spatial_tournament.edges, self.edges_when_using_half_step) + self.assertEqual( + af.spatial_tournament.edges, self.edges_when_using_half_step + ) # The first player is the fingerprinted one, the rest are probes. self.assertIsInstance(af.spatial_tournament.players[0], axl.Cooperator) @@ -133,7 +135,17 @@ def test_fingerprint_interactions_cooperator(self): # The keys are edges between players, values are repetitions. self.assertCountEqual( af.interactions.keys(), - [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (0, 7), (0, 8), (0, 9)], + [ + (0, 1), + (0, 2), + (0, 3), + (0, 4), + (0, 5), + (0, 6), + (0, 7), + (0, 8), + (0, 9), + ], ) self.assertEqual(len(af.interactions.values()), 9) @@ -191,7 +203,9 @@ def test_fingerprint_interactions_titfortat(self): def test_progress_bar_fingerprint(self): af = AshlockFingerprint(axl.TitForTat) - data = af.fingerprint(turns=10, repetitions=2, step=0.5, progress_bar=True) + data = af.fingerprint( + turns=10, repetitions=2, step=0.5, progress_bar=True + ) self.assertEqual(sorted(data.keys()), self.points_when_using_half_step) @patch("axelrod.fingerprint.mkstemp", RecordedMksTemp.mkstemp) @@ -220,7 +234,11 @@ def test_fingerprint_with_filename(self): filename = axl_filename(path) af = AshlockFingerprint(axl.TitForTat) af.fingerprint( - turns=1, repetitions=1, step=0.5, progress_bar=False, filename=filename + turns=1, + repetitions=1, + step=0.5, + progress_bar=False, + filename=filename, ) with open(filename, "r") as out: data = out.read() @@ -228,7 +246,9 @@ def test_fingerprint_with_filename(self): def test_serial_fingerprint(self): af = AshlockFingerprint(axl.TitForTat) - data = af.fingerprint(turns=10, repetitions=2, step=0.5, progress_bar=False) + data = af.fingerprint( + turns=10, repetitions=2, step=0.5, progress_bar=False + ) edge_keys = sorted(list(af.interactions.keys())) coord_keys = sorted(list(data.keys())) self.assertEqual(af.step, 0.5) @@ -251,7 +271,9 @@ def test_plot_data(self): af = AshlockFingerprint(axl.Cooperator()) af.fingerprint(turns=5, repetitions=3, step=0.5, progress_bar=False) - reshaped_data = np.array([[0.0, 0.0, 0.0], [2.0, 1.0, 2.0], [3.0, 3.0, 3.0]]) + reshaped_data = np.array( + [[0.0, 0.0, 0.0], [2.0, 1.0, 2.0], [3.0, 3.0, 3.0]] + ) plotted_data = af.plot().gca().images[0].get_array() np.testing.assert_allclose(plotted_data, reshaped_data) @@ -301,7 +323,9 @@ def test_wsls_fingerprint(self): Point(x=1.0, y=1.0): 1.300, } af = axl.AshlockFingerprint(axl.WinStayLoseShift(), axl.TitForTat) - data = af.fingerprint(turns=50, repetitions=2, step=0.25, progress_bar=False) + data = af.fingerprint( + turns=50, repetitions=2, step=0.25, progress_bar=False + ) for key, value in data.items(): self.assertAlmostEqual(value, test_data[key], places=2) @@ -337,7 +361,9 @@ def test_tft_fingerprint(self): } af = axl.AshlockFingerprint(axl.TitForTat(), axl.TitForTat) - data = af.fingerprint(turns=50, repetitions=2, step=0.25, progress_bar=False) + data = af.fingerprint( + turns=50, repetitions=2, step=0.25, progress_bar=False + ) for key, value in data.items(): self.assertAlmostEqual(value, test_data[key], places=2) @@ -373,7 +399,9 @@ def test_majority_fingerprint(self): } af = axl.AshlockFingerprint(axl.GoByMajority, axl.TitForTat) - data = af.fingerprint(turns=50, repetitions=2, step=0.25, progress_bar=False) + data = af.fingerprint( + turns=50, repetitions=2, step=0.25, progress_bar=False + ) for key, value in data.items(): self.assertAlmostEqual(value, test_data[key], places=2) @@ -387,19 +415,27 @@ def test_pair_fingerprints(self, strategy_pair): """ strategy, probe = strategy_pair af = AshlockFingerprint(strategy, probe) - data = af.fingerprint(turns=2, repetitions=2, step=0.5, progress_bar=False) + data = af.fingerprint( + turns=2, repetitions=2, step=0.5, progress_bar=False + ) self.assertIsInstance(data, dict) af = AshlockFingerprint(strategy(), probe) - data = af.fingerprint(turns=2, repetitions=2, step=0.5, progress_bar=False) + data = af.fingerprint( + turns=2, repetitions=2, step=0.5, progress_bar=False + ) self.assertIsInstance(data, dict) af = AshlockFingerprint(strategy, probe()) - data = af.fingerprint(turns=2, repetitions=2, step=0.5, progress_bar=False) + data = af.fingerprint( + turns=2, repetitions=2, step=0.5, progress_bar=False + ) self.assertIsInstance(data, dict) af = AshlockFingerprint(strategy(), probe()) - data = af.fingerprint(turns=2, repetitions=2, step=0.5, progress_bar=False) + data = af.fingerprint( + turns=2, repetitions=2, step=0.5, progress_bar=False + ) self.assertIsInstance(data, dict) @@ -409,13 +445,16 @@ def test_init(self): fingerprint = axl.TransitiveFingerprint(strategy=player) self.assertEqual(fingerprint.strategy, player) self.assertEqual( - fingerprint.opponents, [axl.Random(p) for p in np.linspace(0, 1, 50)] + fingerprint.opponents, + [axl.Random(p) for p in np.linspace(0, 1, 50)], ) def test_init_with_opponents(self): player = axl.TitForTat() opponents = [s() for s in axl.demo_strategies] - fingerprint = axl.TransitiveFingerprint(strategy=player, opponents=opponents) + fingerprint = axl.TransitiveFingerprint( + strategy=player, opponents=opponents + ) self.assertEqual(fingerprint.strategy, player) self.assertEqual(fingerprint.opponents, opponents) @@ -427,7 +466,8 @@ def test_init_with_not_default_number(self): ) self.assertEqual(fingerprint.strategy, player) self.assertEqual( - fingerprint.opponents, [axl.Random(p) for p in np.linspace(0, 1, 10)] + fingerprint.opponents, + [axl.Random(p) for p in np.linspace(0, 1, 10)], ) def test_fingerprint_with_filename(self): @@ -435,7 +475,9 @@ def test_fingerprint_with_filename(self): filename = axl_filename(path) strategy = axl.TitForTat() tf = TransitiveFingerprint(strategy) - tf.fingerprint(turns=1, repetitions=1, progress_bar=False, filename=filename) + tf.fingerprint( + turns=1, repetitions=1, progress_bar=False, filename=filename + ) with open(filename, "r") as out: data = out.read() self.assertEqual(len(data.split("\n")), 102) @@ -445,9 +487,7 @@ 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 1e0666ee6..9deb08e60 100644 --- a/axelrod/tests/unit/test_graph.py +++ b/axelrod/tests/unit/test_graph.py @@ -40,8 +40,12 @@ def test_undirected_graph_with_vertices_and_unweighted_edges(self): self.assertEqual(str(g), "") self.assertEqual(g._edges, [(1, 2), (2, 1), (2, 3), (3, 2)]) - self.assert_out_mapping(g, {1: {2: None}, 2: {1: None, 3: None}, 3: {2: None}}) - self.assert_in_mapping(g, {1: {2: None}, 2: {1: None, 3: None}, 3: {2: None}}) + self.assert_out_mapping( + g, {1: {2: None}, 2: {1: None, 3: None}, 3: {2: None}} + ) + self.assert_in_mapping( + g, {1: {2: None}, 2: {1: None, 3: None}, 3: {2: None}} + ) def test_undirected_graph_with_vertices_and_weighted_edges(self): g = axl.graph.Graph(edges=[[1, 2, 10], [2, 3, 5]]) @@ -92,7 +96,11 @@ def test_add_loops_with_existing_loop_and_using_strings(self): g.add_loops() self.assertEqual( list(sorted(g._edges)), - list(sorted([("a", "b"), ("b", "a"), ("c", "c"), ("a", "a"), ("b", "b")])), + list( + sorted( + [("a", "b"), ("b", "a"), ("c", "c"), ("a", "a"), ("b", "b")] + ) + ), ) @@ -148,9 +156,19 @@ def test_length_4_undirected(self): edges = [(0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2), (3, 0), (0, 3)] self.assertEqual(g.vertices, [0, 1, 2, 3]) self.assertEqual(g.edges, edges) - for vertex, neighbors in [(0, (1, 3)), (1, (0, 2)), (2, (1, 3)), (3, (0, 2))]: + for vertex, neighbors in [ + (0, (1, 3)), + (1, (0, 2)), + (2, (1, 3)), + (3, (0, 2)), + ]: self.assertEqual(set(g.out_vertices(vertex)), set(neighbors)) - for vertex, neighbors in [(0, (1, 3)), (1, (0, 2)), (2, (1, 3)), (3, (0, 2))]: + for vertex, neighbors in [ + (0, (1, 3)), + (1, (0, 2)), + (2, (1, 3)), + (3, (0, 2)), + ]: self.assertEqual(set(g.in_vertices(vertex)), set(neighbors)) @@ -211,7 +229,17 @@ def test_size_2_with_loops(self): def test_size_3_with_loops(self): g = axl.graph.complete_graph(3, loops=True) self.assertEqual(g.vertices, [0, 1, 2]) - edges = [(0, 1), (1, 0), (0, 2), (2, 0), (1, 2), (2, 1), (0, 0), (1, 1), (2, 2)] + edges = [ + (0, 1), + (1, 0), + (0, 2), + (2, 0), + (1, 2), + (2, 1), + (0, 0), + (1, 1), + (2, 2), + ] self.assertEqual(g.edges, edges) self.assertEqual(g.directed, False) @@ -247,59 +275,70 @@ 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 7c517958b..89d0c5d52 100644 --- a/axelrod/tests/unit/test_history.py +++ b/axelrod/tests/unit/test_history.py @@ -84,8 +84,7 @@ 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() @@ -95,7 +94,6 @@ def test_flip_plays(self): class TestLimitedHistory(unittest.TestCase): - def test_memory_depth(self): h = LimitedHistory(memory_depth=3) h.append(C, C) @@ -106,8 +104,9 @@ 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]) @@ -116,4 +115,5 @@ def test_memory_depth(self): self.assertEqual(h.defections, 2) self.assertEqual( h.state_distribution, - Counter({(D, D): 1, (C, D): 1, (D, C): 1, (C, C): 0})) + 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 2e1d2c5e1..af94eacfa 100644 --- a/axelrod/tests/unit/test_interaction_utils.py +++ b/axelrod/tests/unit/test_interaction_utils.py @@ -49,39 +49,65 @@ 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): for inter, winner in zip(self.interactions, self.winners): - self.assertEqual(winner, axl.interaction_utils.compute_winner_index(inter)) + self.assertEqual( + winner, axl.interaction_utils.compute_winner_index(inter) + ) def test_compute_cooperations(self): for inter, coop in zip(self.interactions, self.cooperations): - self.assertEqual(coop, axl.interaction_utils.compute_cooperations(inter)) + self.assertEqual( + coop, axl.interaction_utils.compute_cooperations(inter) + ) 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)) + for inter, dist in zip( + self.interactions, self.normalised_state_distribution + ): + 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)) + for inter, dist in zip( + self.interactions, self.state_to_action_distribution + ): + 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( @@ -93,17 +119,25 @@ def test_compute_state_to_action_distribution(self): ((D, D), C): 1, } ), - Counter({((C, C), D): 1, ((C, D), C): 2, ((D, C), D): 2, ((D, D), C): 1}), + 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 = [ @@ -116,15 +150,22 @@ def test_compute_normalised_state_to_action_distribution(self): ((D, D), C): 1, } ), - Counter({((C, C), D): 1, ((C, D), C): 1, ((D, C), D): 1, ((D, D), C): 1}), + 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): for inter, spark in zip(self.interactions, self.sparklines): - self.assertEqual(spark, axl.interaction_utils.compute_sparklines(inter)) + self.assertEqual( + spark, axl.interaction_utils.compute_sparklines(inter) + ) def test_read_interactions_from_file(self): tmp_file = tempfile.NamedTemporaryFile(mode="w", delete=False) @@ -137,10 +178,14 @@ 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 71913d103..1a5b7d93c 100644 --- a/axelrod/tests/unit/test_match.py +++ b/axelrod/tests/unit/test_match.py @@ -39,7 +39,9 @@ def test_init_with_prob_end(self, prob_end, game): self.assertEqual(match.noise, 0) self.assertEqual(match.game.RPST(), game.RPST()) - self.assertEqual(match.players[0].match_attributes["length"], float("inf")) + self.assertEqual( + match.players[0].match_attributes["length"], float("inf") + ) self.assertEqual(match._cache, {}) @given( @@ -57,7 +59,9 @@ def test_init_with_prob_end_and_turns(self, turns, prob_end, game): self.assertEqual(match.noise, 0) self.assertEqual(match.game.RPST(), game.RPST()) - self.assertEqual(match.players[0].match_attributes["length"], float("inf")) + self.assertEqual( + match.players[0].match_attributes["length"], float("inf") + ) self.assertEqual(match._cache, {}) def test_default_init(self): @@ -85,7 +89,9 @@ def test_example_prob_end(self): expected_lengths = [3, 1, 5] for seed, expected_length in zip(range(3), expected_lengths): axl.seed(seed) - self.assertEqual(match.players[0].match_attributes["length"], float("inf")) + self.assertEqual( + match.players[0].match_attributes["length"], float("inf") + ) self.assertEqual(len(match.play()), expected_length) self.assertEqual(match.noise, 0) self.assertEqual(match.game.RPST(), (3, 1, 0, 5)) @@ -188,8 +194,7 @@ 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): @@ -208,8 +213,7 @@ 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_match_generator.py b/axelrod/tests/unit/test_match_generator.py index 27faa78c0..7ac2b1ed9 100644 --- a/axelrod/tests/unit/test_match_generator.py +++ b/axelrod/tests/unit/test_match_generator.py @@ -149,7 +149,9 @@ def test_build_single_match_params_with_fixed_length_unknown(self): self.assertEqual(match_params["game"], test_game) self.assertEqual(match_params["prob_end"], None) self.assertEqual(match_params["noise"], 0) - self.assertEqual(match_params["match_attributes"], {"length": float("inf")}) + self.assertEqual( + match_params["match_attributes"], {"length": float("inf")} + ) # Check that can build a match players = [axl.Cooperator(), axl.Defector()] @@ -178,7 +180,9 @@ def test_build_match_chunks(self, repetitions): (i, j, repetitions) for i in range(5) for j in range(i, 5) ] - self.assertEqual(sorted(match_definitions), sorted(expected_match_definitions)) + self.assertEqual( + sorted(match_definitions), sorted(expected_match_definitions) + ) @given(repetitions=integers(min_value=1, max_value=test_repetitions)) @settings(max_examples=5) @@ -199,7 +203,9 @@ def test_spatial_build_match_chunks(self, repetitions): ] expected_match_definitions = [(i, j, repetitions) for i, j in cycle] - self.assertEqual(sorted(match_definitions), sorted(expected_match_definitions)) + self.assertEqual( + sorted(match_definitions), sorted(expected_match_definitions) + ) def test_len(self): turns = 5 diff --git a/axelrod/tests/unit/test_mock_player.py b/axelrod/tests/unit/test_mock_player.py index 457e77711..1f380b5ba 100644 --- a/axelrod/tests/unit/test_mock_player.py +++ b/axelrod/tests/unit/test_mock_player.py @@ -17,4 +17,3 @@ 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 d972b288f..6f9b9a77c 100644 --- a/axelrod/tests/unit/test_moran.py +++ b/axelrod/tests/unit/test_moran.py @@ -23,16 +23,21 @@ def test_init(self): self.assertEqual(mp.noise, 0) self.assertEqual(mp.initial_players, players) self.assertEqual(mp.players, list(players)) - self.assertEqual(mp.populations, [Counter({"Cooperator": 1, "Defector": 1})]) + self.assertEqual( + mp.populations, [Counter({"Cooperator": 1, "Defector": 1})] + ) self.assertIsNone(mp.winning_strategy_name) self.assertEqual(mp.mutation_rate, 0) self.assertEqual(mp.mode, "bd") self.assertEqual(mp.deterministic_cache, axl.DeterministicCache()) self.assertEqual( - mp.mutation_targets, {"Cooperator": [players[1]], "Defector": [players[0]]} + mp.mutation_targets, + {"Cooperator": [players[1]], "Defector": [players[0]]}, ) self.assertEqual(mp.interaction_graph._edges, [(0, 1), (1, 0)]) - self.assertEqual(mp.reproduction_graph._edges, [(0, 1), (1, 0), (0, 0), (1, 1)]) + self.assertEqual( + mp.reproduction_graph._edges, [(0, 1), (1, 0), (0, 0), (1, 1)] + ) self.assertEqual(mp.fitness_transformation, None) self.assertEqual(mp.locations, [0, 1]) self.assertEqual(mp.index, {0: 0, 1: 1}) @@ -48,7 +53,9 @@ 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)]) @@ -219,8 +226,12 @@ def test_two_random_players(self): def test_two_players_with_mutation(self): p1, p2 = axl.Cooperator(), axl.Defector() axl.seed(5) - mp = axl.MoranProcess((p1, p2), mutation_rate=0.2, stop_on_fixation=False) - self.assertDictEqual(mp.mutation_targets, {str(p1): [p2], str(p2): [p1]}) + mp = axl.MoranProcess( + (p1, p2), mutation_rate=0.2, stop_on_fixation=False + ) + self.assertDictEqual( + mp.mutation_targets, {str(p1): [p2], str(p2): [p1]} + ) # Test that mutation causes the population to alternate between # fixations counters = [ @@ -257,7 +268,9 @@ def test_three_players_with_mutation(self): p2 = axl.Random() p3 = axl.Defector() players = [p1, p2, p3] - mp = axl.MoranProcess(players, mutation_rate=0.2, stop_on_fixation=False) + mp = axl.MoranProcess( + players, mutation_rate=0.2, stop_on_fixation=False + ) self.assertDictEqual( mp.mutation_targets, {str(p1): [p3, p2], str(p2): [p1, p3], str(p3): [p1, p2]}, @@ -380,38 +393,48 @@ 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): @@ -537,7 +560,11 @@ 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 1cb14101d..d3cee3c0c 100644 --- a/axelrod/tests/unit/test_pickling.py +++ b/axelrod/tests/unit/test_pickling.py @@ -11,7 +11,9 @@ # 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): @@ -112,7 +114,9 @@ class JossAnn(axl.Cooperator): probability = [0.2, 0.3] -@axl.strategy_transformers.MixedTransformer(probability, strategies, name_prefix=None) +@axl.strategy_transformers.MixedTransformer( + probability, strategies, name_prefix=None +) class Mixed(axl.Cooperator): pass @@ -160,7 +164,9 @@ 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 = [ @@ -236,12 +242,24 @@ 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) + opponents = ( + axl.Defector, + axl.Cooperator, + axl.Random, + axl.CyclerCCCDCD, + ) for opponent_class in opponents: axl.seed(10) player.reset() @@ -275,9 +293,13 @@ def test_pickling_all_transformers_as_instance_called_on_a_class(self): self.assert_original_equals_pickled(player) def test_created_on_the_spot_multiple_transformers(self): - player_class = axl.strategy_transformers.FlipTransformer()(axl.Cooperator) + player_class = axl.strategy_transformers.FlipTransformer()( + axl.Cooperator + ) player_class = axl.strategy_transformers.DualTransformer()(player_class) - player = axl.strategy_transformers.FinalTransformer((C, D))(player_class)() + player = axl.strategy_transformers.FinalTransformer((C, D))( + player_class + )() self.assert_original_equals_pickled(player) @@ -294,9 +316,13 @@ 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) + player_class = axl.strategy_transformers.TrackHistoryTransformer()( + player_class + ) interspersed_dual_transformers = player_class() @@ -318,7 +344,8 @@ def test_class_and_instance_name_different_built_from_player_class(self): player = MyCooperator() class_names = [class_.__name__ for class_ in MyCooperator.mro()] self.assertEqual( - class_names, ["FlippedMyCooperator", "MyCooperator", "Player", "object"] + class_names, + ["FlippedMyCooperator", "MyCooperator", "Player", "object"], ) self.assert_original_equals_pickled(player) @@ -378,17 +405,23 @@ def test_with_various_name_prefixes(self): self.assertEqual(no_prefix.__class__.__name__, "Flip") self.assert_original_equals_pickled(no_prefix) - default_prefix = axl.strategy_transformers.FlipTransformer()(axl.Cooperator)() + default_prefix = axl.strategy_transformers.FlipTransformer()( + axl.Cooperator + )() self.assertEqual(default_prefix.__class__.__name__, "FlippedCooperator") self.assert_original_equals_pickled(default_prefix) - fliptastic = axl.strategy_transformers.FlipTransformer(name_prefix="Fliptastic") + fliptastic = axl.strategy_transformers.FlipTransformer( + name_prefix="Fliptastic" + ) new_prefix = fliptastic(axl.Cooperator)() self.assertEqual(new_prefix.__class__.__name__, "FliptasticCooperator") 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_plot.py b/axelrod/tests/unit/test_plot.py index 89d40d8d9..558194e8b 100644 --- a/axelrod/tests/unit/test_plot.py +++ b/axelrod/tests/unit/test_plot.py @@ -34,7 +34,11 @@ def setUpClass(cls): [3 / 2 for _ in range(3)], ] cls.expected_boxplot_xticks_locations = [1, 2, 3, 4] - cls.expected_boxplot_xticks_labels = ["Defector", "Tit For Tat", "Alternator"] + cls.expected_boxplot_xticks_labels = [ + "Defector", + "Tit For Tat", + "Alternator", + ] cls.expected_lengthplot_dataset = [ [cls.turns for _ in range(3)], @@ -43,9 +47,21 @@ def setUpClass(cls): ] cls.expected_payoff_dataset = [ - [0, mean([9 / 5 for _ in range(3)]), mean([17 / 5 for _ in range(3)])], - [mean([4 / 5 for _ in range(3)]), 0, mean([13 / 5 for _ in range(3)])], - [mean([2 / 5 for _ in range(3)]), mean([13 / 5 for _ in range(3)]), 0], + [ + 0, + mean([9 / 5 for _ in range(3)]), + mean([17 / 5 for _ in range(3)]), + ], + [ + mean([4 / 5 for _ in range(3)]), + 0, + mean([13 / 5 for _ in range(3)]), + ], + [ + mean([2 / 5 for _ in range(3)]), + mean([13 / 5 for _ in range(3)]), + 0, + ], ] cls.expected_winplot_dataset = ( [[2, 2, 2], [0, 0, 0], [0, 0, 0]], @@ -106,12 +122,15 @@ def test_init_from_resulsetfromfile(self): def test_boxplot_dataset(self): plot = axl.Plot(self.test_result_set) - self.assertSequenceEqual(plot._boxplot_dataset, self.expected_boxplot_dataset) + self.assertSequenceEqual( + plot._boxplot_dataset, self.expected_boxplot_dataset + ) def test_boxplot_xticks_locations(self): plot = axl.Plot(self.test_result_set) self.assertEqual( - plot._boxplot_xticks_locations, self.expected_boxplot_xticks_locations + plot._boxplot_xticks_locations, + self.expected_boxplot_xticks_locations, ) def test_boxplot_xticks_labels(self): @@ -147,7 +166,9 @@ def test_boxplot_with_title(self): def test_winplot_dataset(self): plot = axl.Plot(self.test_result_set) - self.assertSequenceEqual(plot._winplot_dataset, self.expected_winplot_dataset) + self.assertSequenceEqual( + plot._winplot_dataset, self.expected_winplot_dataset + ) def test_winplot(self): plot = axl.Plot(self.test_result_set) @@ -157,7 +178,9 @@ def test_winplot(self): def test_sdvplot_dataset(self): plot = axl.Plot(self.test_result_set) - self.assertSequenceEqual(plot._sdv_plot_dataset, self.expected_sdvplot_dataset) + self.assertSequenceEqual( + plot._sdv_plot_dataset, self.expected_sdvplot_dataset + ) def test_sdvplot(self): plot = axl.Plot(self.test_result_set) @@ -167,7 +190,9 @@ def test_sdvplot(self): def test_lengthplot_dataset(self): plot = axl.Plot(self.test_result_set) - self.assertSequenceEqual(plot._winplot_dataset, self.expected_winplot_dataset) + self.assertSequenceEqual( + plot._winplot_dataset, self.expected_winplot_dataset + ) def test_lengthplot(self): plot = axl.Plot(self.test_result_set) @@ -183,7 +208,9 @@ def test_pdplot(self): def test_payoff_dataset(self): plot = axl.Plot(self.test_result_set) - self.assertSequenceEqual(plot._payoff_dataset, self.expected_payoff_dataset) + self.assertSequenceEqual( + plot._payoff_dataset, self.expected_payoff_dataset + ) def test_payoff(self): plot = axl.Plot(self.test_result_set) @@ -252,6 +279,8 @@ def test_all_plots(self): ) self.assertIsNone( plot.save_all_plots( - prefix="test_outputs/", title_prefix="A prefix", progress_bar=True + prefix="test_outputs/", + title_prefix="A prefix", + progress_bar=True, ) ) diff --git a/axelrod/tests/unit/test_property.py b/axelrod/tests/unit/test_property.py index fbf89cca2..990821696 100644 --- a/axelrod/tests/unit/test_property.py +++ b/axelrod/tests/unit/test_property.py @@ -13,7 +13,9 @@ 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): @@ -131,7 +133,11 @@ def test_decorator(self, tournament): self.assertLessEqual(tournament.repetitions, 50) self.assertGreaterEqual(tournament.repetitions, 2) - @given(tournament=prob_end_tournaments(strategies=axl.basic_strategies, max_size=3)) + @given( + tournament=prob_end_tournaments( + strategies=axl.basic_strategies, max_size=3 + ) + ) @settings(max_examples=5) def test_decorator_with_given_strategies(self, tournament): self.assertIsInstance(tournament, axl.Tournament) @@ -166,7 +172,11 @@ def test_decorator(self, tournament): self.assertLessEqual(tournament.repetitions, 50) self.assertGreaterEqual(tournament.repetitions, 2) - @given(tournament=spatial_tournaments(strategies=axl.basic_strategies, max_size=3)) + @given( + tournament=spatial_tournaments( + strategies=axl.basic_strategies, max_size=3 + ) + ) @settings(max_examples=5) def test_decorator_with_given_strategies(self, tournament): self.assertIsInstance(tournament, axl.Tournament) diff --git a/axelrod/tests/unit/test_resultset.py b/axelrod/tests/unit/test_resultset.py index 8bd0be3af..a038389a2 100644 --- a/axelrod/tests/unit/test_resultset.py +++ b/axelrod/tests/unit/test_resultset.py @@ -72,15 +72,39 @@ def setUpClass(cls): # Recalculating to deal with numeric imprecision cls.expected_payoff_matrix = [ - [0, mean([13 / 5 for _ in range(3)]), mean([2 / 5 for _ in range(3)])], - [mean([13 / 5 for _ in range(3)]), 0, mean([4 / 5 for _ in range(3)])], - [mean([17 / 5 for _ in range(3)]), mean([9 / 5 for _ in range(3)]), 0], + [ + 0, + mean([13 / 5 for _ in range(3)]), + mean([2 / 5 for _ in range(3)]), + ], + [ + mean([13 / 5 for _ in range(3)]), + 0, + mean([4 / 5 for _ in range(3)]), + ], + [ + mean([17 / 5 for _ in range(3)]), + mean([9 / 5 for _ in range(3)]), + 0, + ], ] cls.expected_payoff_stddevs = [ - [0, std([13 / 5 for _ in range(3)]), std([2 / 5 for _ in range(3)])], - [std([13 / 5 for _ in range(3)]), 0, std([4 / 5 for _ in range(3)])], - [std([17 / 5 for _ in range(3)]), std([9 / 5 for _ in range(3)]), 0], + [ + 0, + std([13 / 5 for _ in range(3)]), + std([2 / 5 for _ in range(3)]), + ], + [ + std([13 / 5 for _ in range(3)]), + 0, + std([4 / 5 for _ in range(3)]), + ], + [ + std([17 / 5 for _ in range(3)]), + std([9 / 5 for _ in range(3)]), + 0, + ], ] cls.expected_cooperation = [[0, 9, 9], [9, 0, 3], [0, 0, 0]] @@ -89,8 +113,16 @@ def setUpClass(cls): cls.expected_initial_cooperation_rate = [1, 1, 0] cls.expected_normalised_cooperation = [ - [0, mean([3 / 5 for _ in range(3)]), mean([3 / 5 for _ in range(3)])], - [mean([3 / 5 for _ in range(3)]), 0, mean([1 / 5 for _ in range(3)])], + [ + 0, + mean([3 / 5 for _ in range(3)]), + mean([3 / 5 for _ in range(3)]), + ], + [ + mean([3 / 5 for _ in range(3)]), + 0, + mean([1 / 5 for _ in range(3)]), + ], [0, 0, 0], ] @@ -177,7 +209,11 @@ def setUpClass(cls): cls.expected_good_partner_rating = [1.0, 1.0, 0] - cls.expected_eigenjesus_rating = [0.5547001962252291, 0.8320502943378436, 0.0] + cls.expected_eigenjesus_rating = [ + 0.5547001962252291, + 0.8320502943378436, + 0.0, + ] cls.expected_eigenmoses_rating = [ -0.4578520302117101, @@ -338,7 +374,9 @@ def test_score_diffs(self): for i, row in enumerate(rs.score_diffs): for j, col in enumerate(row): for k, score in enumerate(col): - self.assertAlmostEqual(score, self.expected_score_diffs[i][j][k]) + self.assertAlmostEqual( + score, self.expected_score_diffs[i][j][k] + ) def test_payoff_diffs_means(self): rs = axl.ResultSet( @@ -348,7 +386,9 @@ def test_payoff_diffs_means(self): self.assertEqual(len(rs.payoff_diffs_means), rs.num_players) for i, row in enumerate(rs.payoff_diffs_means): for j, col in enumerate(row): - self.assertAlmostEqual(col, self.expected_payoff_diffs_means[i][j]) + self.assertAlmostEqual( + col, self.expected_payoff_diffs_means[i][j] + ) def test_payoff_stddevs(self): rs = axl.ResultSet( @@ -373,7 +413,8 @@ def test_initial_cooperation_count(self): self.assertIsInstance(rs.initial_cooperation_count, list) self.assertEqual(len(rs.initial_cooperation_count), rs.num_players) self.assertEqual( - rs.initial_cooperation_count, self.expected_initial_cooperation_count + rs.initial_cooperation_count, + self.expected_initial_cooperation_count, ) def test_normalised_cooperation(self): @@ -384,7 +425,9 @@ def test_normalised_cooperation(self): self.assertEqual(len(rs.normalised_cooperation), rs.num_players) for i, row in enumerate(rs.normalised_cooperation): for j, col in enumerate(row): - self.assertAlmostEqual(col, self.expected_normalised_cooperation[i][j]) + self.assertAlmostEqual( + col, self.expected_normalised_cooperation[i][j] + ) def test_initial_cooperation_rate(self): rs = axl.ResultSet( @@ -402,7 +445,9 @@ def test_state_distribution(self): ) self.assertIsInstance(rs.state_distribution, list) self.assertEqual(len(rs.state_distribution), rs.num_players) - self.assertEqual(rs.state_distribution, self.expected_state_distribution) + self.assertEqual( + rs.state_distribution, self.expected_state_distribution + ) def test_state_normalised_distribution(self): rs = axl.ResultSet( @@ -447,7 +492,9 @@ def test_vengeful_cooperation(self): self.assertEqual(len(rs.vengeful_cooperation), rs.num_players) for i, row in enumerate(rs.vengeful_cooperation): for j, col in enumerate(row): - self.assertAlmostEqual(col, self.expected_vengeful_cooperation[i][j]) + self.assertAlmostEqual( + col, self.expected_vengeful_cooperation[i][j] + ) def test_cooperating_rating(self): rs = axl.ResultSet( @@ -455,7 +502,9 @@ def test_cooperating_rating(self): ) self.assertIsInstance(rs.cooperating_rating, list) self.assertEqual(len(rs.cooperating_rating), rs.num_players) - self.assertEqual(rs.cooperating_rating, self.expected_cooperating_rating) + self.assertEqual( + rs.cooperating_rating, self.expected_cooperating_rating + ) def test_good_partner_matrix(self): rs = axl.ResultSet( @@ -463,7 +512,9 @@ def test_good_partner_matrix(self): ) self.assertIsInstance(rs.good_partner_matrix, list) self.assertEqual(len(rs.good_partner_matrix), rs.num_players) - self.assertEqual(rs.good_partner_matrix, self.expected_good_partner_matrix) + self.assertEqual( + rs.good_partner_matrix, self.expected_good_partner_matrix + ) def test_good_partner_rating(self): rs = axl.ResultSet( @@ -471,7 +522,9 @@ def test_good_partner_rating(self): ) self.assertIsInstance(rs.good_partner_rating, list) self.assertEqual(len(rs.good_partner_rating), rs.num_players) - self.assertEqual(rs.good_partner_rating, self.expected_good_partner_rating) + self.assertEqual( + rs.good_partner_rating, self.expected_good_partner_rating + ) def test_eigenjesus_rating(self): rs = axl.ResultSet( @@ -504,7 +557,10 @@ def test_self_interaction_for_random_strategies(self): def test_equality(self): rs_sets = [ axl.ResultSet( - self.filename, self.players, self.repetitions, progress_bar=False + self.filename, + self.players, + self.repetitions, + progress_bar=False, ) for _ in range(2) ] @@ -534,25 +590,34 @@ def test_summarise(self): [float(player.Median_score) for player in sd], ranked_median_scores ) - ranked_cooperation_rating = [rs.cooperating_rating[i] for i in rs.ranking] + ranked_cooperation_rating = [ + rs.cooperating_rating[i] for i in rs.ranking + ] self.assertEqual( [float(player.Cooperation_rating) for player in sd], ranked_cooperation_rating, ) ranked_median_wins = [nanmedian(rs.wins[i]) for i in rs.ranking] - self.assertEqual([float(player.Wins) for player in sd], ranked_median_wins) + self.assertEqual( + [float(player.Wins) for player in sd], ranked_median_wins + ) ranked_initial_coop_rates = [ self.expected_initial_cooperation_rate[i] for i in rs.ranking ] self.assertEqual( - [float(player.Initial_C_rate) for player in sd], ranked_initial_coop_rates + [float(player.Initial_C_rate) for player in sd], + ranked_initial_coop_rates, ) for player in sd: self.assertEqual( - player.CC_rate + player.CD_rate + player.DC_rate + player.DD_rate, 1 + player.CC_rate + + player.CD_rate + + player.DC_rate + + player.DD_rate, + 1, ) for rate in [ player.CC_to_C_rate, @@ -729,13 +794,21 @@ def setUpClass(cls): # Recalculating to deal with numeric imprecision cls.expected_payoff_matrix = [ - [0, mean([13 / 5 for _ in range(3)]), mean([2 / 5 for _ in range(3)])], + [ + 0, + mean([13 / 5 for _ in range(3)]), + mean([2 / 5 for _ in range(3)]), + ], [mean([13 / 5 for _ in range(3)]), 0, 0], [mean([17 / 5 for _ in range(3)]), 0, 0], ] cls.expected_payoff_stddevs = [ - [0, std([13 / 5 for _ in range(3)]), std([2 / 5 for _ in range(3)])], + [ + 0, + std([13 / 5 for _ in range(3)]), + std([2 / 5 for _ in range(3)]), + ], [std([13 / 5 for _ in range(3)]), 0, 0], [std([17 / 5 for _ in range(3)]), 0, 0], ] @@ -743,7 +816,11 @@ def setUpClass(cls): cls.expected_cooperation = [[0, 9, 9], [9, 0, 0], [0, 0, 0]] cls.expected_normalised_cooperation = [ - [0, mean([3 / 5 for _ in range(3)]), mean([3 / 5 for _ in range(3)])], + [ + 0, + mean([3 / 5 for _ in range(3)]), + mean([3 / 5 for _ in range(3)]), + ], [mean([3 / 5 for _ in range(3)]), 0, 0], [0, 0, 0], ] @@ -762,7 +839,11 @@ def setUpClass(cls): cls.expected_good_partner_rating = [1.0, 1.0, 0.0] - cls.expected_eigenjesus_rating = [0.447213595499958, 0.894427190999916, 0.0] + cls.expected_eigenjesus_rating = [ + 0.447213595499958, + 0.894427190999916, + 0.0, + ] cls.expected_eigenmoses_rating = [ -0.32929277996907086, @@ -786,7 +867,11 @@ def setUpClass(cls): Counter({(C, C): 0.2, (C, D): 0.4, (D, C): 0.4}), Counter({(C, D): 0.6, (D, D): 0.4}), ], - [Counter({(C, C): 0.2, (C, D): 0.4, (D, C): 0.4}), Counter(), Counter()], + [ + Counter({(C, C): 0.2, (C, D): 0.4, (D, C): 0.4}), + Counter(), + Counter(), + ], [Counter({(D, C): 0.6, (D, D): 0.4}), Counter(), Counter()], ] @@ -815,7 +900,11 @@ def setUpClass(cls): Counter(), Counter(), ], - [Counter({((D, C), D): 1.0, ((D, D), D): 1.0}), Counter(), Counter()], + [ + Counter({((D, C), D): 1.0, ((D, D), D): 1.0}), + Counter(), + Counter(), + ], ] def test_match_lengths(self): @@ -872,7 +961,8 @@ def setUpClass(cls): cls.edges = [(0, 1), (2, 3)] cls.expected_match_lengths = [ - [[0, 5, 0, 0], [5, 0, 0, 0], [0, 0, 0, 5], [0, 0, 5, 0]] for _ in range(3) + [[0, 5, 0, 0], [5, 0, 0, 0], [0, 0, 0, 5], [0, 0, 5, 0]] + for _ in range(3) ] cls.expected_scores = [ @@ -914,10 +1004,30 @@ def setUpClass(cls): ] cls.expected_score_diffs = [ - [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], - [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], - [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [5.0, 5.0, 5.0]], - [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [-5.0, -5.0, -5.0], [0.0, 0.0, 0.0]], + [ + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + ], + [ + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + ], + [ + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [5.0, 5.0, 5.0], + ], + [ + [0.0, 0.0, 0.0], + [0.0, 0.0, 0.0], + [-5.0, -5.0, -5.0], + [0.0, 0.0, 0.0], + ], ] cls.expected_payoff_diffs_means = [ @@ -1074,14 +1184,17 @@ def setUpClass(cls): cls.edges = [(0, 0), (1, 1), (2, 2), (3, 3)] cls.expected_match_lengths = [ - [[5, 0, 0, 0], [0, 5, 0, 0], [0, 0, 5, 0], [0, 0, 0, 5]] for _ in range(3) + [[5, 0, 0, 0], [0, 5, 0, 0], [0, 0, 5, 0], [0, 0, 0, 5]] + for _ in range(3) ] cls.expected_scores = [[0 for _ in range(3)] for _ in range(4)] cls.expected_wins = [[0 for _ in range(3)] for _ in range(4)] - cls.expected_normalised_scores = [[0 for _ in range(3)] for i in range(4)] + cls.expected_normalised_scores = [ + [0 for _ in range(3)] for i in range(4) + ] cls.expected_ranking = [0, 1, 2, 3] @@ -1109,7 +1222,9 @@ def setUpClass(cls): [[0.0 for _ in range(3)] for _ in range(4)] for _ in range(4) ] - cls.expected_payoff_diffs_means = [[0.0 for _ in range(4)] for _ in range(4)] + cls.expected_payoff_diffs_means = [ + [0.0 for _ in range(4)] for _ in range(4) + ] # Recalculating to deal with numeric imprecision cls.expected_payoff_matrix = [ @@ -1150,7 +1265,9 @@ def setUpClass(cls): cls.expected_cooperating_rating = [0.0 for _ in range(4)] - cls.expected_good_partner_matrix = [[0.0 for _ in range(4)] for _ in range(4)] + cls.expected_good_partner_matrix = [ + [0.0 for _ in range(4)] for _ in range(4) + ] cls.expected_good_partner_rating = [0.0 for _ in range(4)] @@ -1218,7 +1335,9 @@ class TestSummary(unittest.TestCase): """Separate test to check that summary always builds without failures""" @given( - tournament=tournaments(min_size=2, max_size=5, max_turns=5, max_repetitions=3) + tournament=tournaments( + min_size=2, max_size=5, max_turns=5, max_repetitions=3 + ) ) @settings(max_examples=5) def test_summarise_without_failure(self, tournament): @@ -1229,7 +1348,11 @@ def test_summarise_without_failure(self, tournament): for player in sd: # round for numerical error total_rate = round( - player.CC_rate + player.CD_rate + player.DC_rate + player.DD_rate, 3 + player.CC_rate + + player.CD_rate + + player.DC_rate + + player.DD_rate, + 3, ) self.assertTrue(total_rate in [0, 1]) self.assertTrue(0 <= player.Initial_C_rate <= 1) @@ -1241,9 +1364,13 @@ class TestCreateCounterDict(unittest.TestCase): def test_basic_use(self): key_map = {"Col 1": "Var 1", "Col 2": "Var 2"} df = pd.DataFrame( - {"Col 1": [10, 20, 30], "Col 2": [1, 2, 0]}, index=[[5, 6, 7], [1, 2, 3]] + {"Col 1": [10, 20, 30], "Col 2": [1, 2, 0]}, + index=[[5, 6, 7], [1, 2, 3]], + ) + self.assertEqual( + create_counter_dict(df, 6, 2, key_map), + Counter({"Var 1": 20, "Var 2": 2}), ) self.assertEqual( - create_counter_dict(df, 6, 2, key_map), Counter({"Var 1": 20, "Var 2": 2}) + create_counter_dict(df, 7, 3, key_map), Counter({"Var 1": 30}) ) - self.assertEqual(create_counter_dict(df, 7, 3, key_map), Counter({"Var 1": 30})) diff --git a/axelrod/tests/unit/test_strategy_transformers.py b/axelrod/tests/unit/test_strategy_transformers.py index 7b909ab22..c3b51477b 100644 --- a/axelrod/tests/unit/test_strategy_transformers.py +++ b/axelrod/tests/unit/test_strategy_transformers.py @@ -54,9 +54,13 @@ def test_DecoratorReBuilder(self): args = decorator.args kwargs = decorator.kwargs.copy() - new_decorator = DecoratorReBuilder()(factory_args, args, kwargs, new_prefix) + new_decorator = DecoratorReBuilder()( + factory_args, args, kwargs, new_prefix + ) - self.assertEqual(decorator(axl.Cooperator)(), new_decorator(axl.Cooperator)()) + self.assertEqual( + decorator(axl.Cooperator)(), new_decorator(axl.Cooperator)() + ) def test_StrategyReBuilder_declared_class_with_name_prefix(self): player = CanNotPickle() @@ -158,9 +162,15 @@ def test_repr(self): str(InitialTransformer([D, D, C])(axl.Alternator)()), "Initial Alternator: [D, D, C]", ) - self.assertEqual(str(FlipTransformer()(axl.Random)(0.1)), "Flipped Random: 0.1") self.assertEqual( - str(MixedTransformer(0.3, (axl.Alternator, axl.Bully))(axl.Random)(0.1)), + str(FlipTransformer()(axl.Random)(0.1)), "Flipped Random: 0.1" + ) + self.assertEqual( + str( + MixedTransformer(0.3, (axl.Alternator, axl.Bully))(axl.Random)( + 0.1 + ) + ), "Mutated Random: 0.1: 0.3, ['Alternator', 'Bully']", ) @@ -395,7 +405,9 @@ def test_final_transformer(self): p2 = FinalTransformer([D, D, D])(axl.Cooperator)() self.assertEqual(axl.Classifiers["makes_use_of"](p2), set(["length"])) self.assertEqual(axl.Classifiers["memory_depth"](p2), 3) - self.assertEqual(axl.Classifiers["makes_use_of"](axl.Cooperator()), set([])) + self.assertEqual( + axl.Classifiers["makes_use_of"](axl.Cooperator()), set([]) + ) p2.match_attributes["length"] = 6 for _ in range(8): @@ -432,7 +444,9 @@ def test_composition(self): p1.play(p2) self.assertEqual(p1.history, [D, D, C, C, C, C, D, D]) - cls1 = FinalTransformer([D, D])(InitialTransformer([D, D])(axl.Cooperator)) + cls1 = FinalTransformer([D, D])( + InitialTransformer([D, D])(axl.Cooperator) + ) p1 = cls1() p2 = axl.Cooperator() p1.match_attributes["length"] = 8 @@ -575,7 +589,9 @@ def test_deadlock(self): # Now let's use the transformer to break the deadlock to achieve # Mutual cooperation p1 = axl.TitForTat() - p2 = DeadlockBreakingTransformer()(InitialTransformer([D])(axl.TitForTat))() + p2 = DeadlockBreakingTransformer()( + InitialTransformer([D])(axl.TitForTat) + )() for _ in range(4): p1.play(p2) self.assertEqual(p1.history, [C, D, C, C]) diff --git a/axelrod/tests/unit/test_strategy_utils.py b/axelrod/tests/unit/test_strategy_utils.py index fef7e2af6..d6be4c72d 100644 --- a/axelrod/tests/unit/test_strategy_utils.py +++ b/axelrod/tests/unit/test_strategy_utils.py @@ -37,7 +37,9 @@ def test_no_cycle(self): history = [D, D, C, C, C] self.assertIsNone(detect_cycle(history)) - def test_regression_test_can_detect_cycle_that_is_repeated_exactly_once(self): + def test_regression_test_can_detect_cycle_that_is_repeated_exactly_once( + self, + ): self.assertEqual(detect_cycle([C, D, C, D]), (C, D)) self.assertEqual(detect_cycle([C, D, C, D, C]), (C, D)) @@ -55,11 +57,14 @@ def test_min_size_greater_than_two_times_history_tail_returns_none(self): def test_min_size_greater_than_two_times_max_size_has_no_effect(self): self.assertEqual( - detect_cycle([C, C, C, C, C, C, C, C], min_size=2, max_size=3), (C, C) + detect_cycle([C, C, C, C, C, C, C, C], min_size=2, max_size=3), + (C, C), ) def test_cycle_greater_than_max_size_returns_none(self): - self.assertEqual(detect_cycle([C, C, D] * 2, min_size=1, max_size=3), (C, C, D)) + self.assertEqual( + detect_cycle([C, C, D] * 2, min_size=1, max_size=3), (C, C, D) + ) self.assertIsNone(detect_cycle([C, C, D] * 2, min_size=1, max_size=2)) @@ -81,7 +86,9 @@ def test_strategies_with_countermeasures_return_their_countermeasures(self): inspector = axl.Cooperator() d_geller.play(inspector) - self.assertEqual(inspect_strategy(inspector=inspector, opponent=d_geller), D) + self.assertEqual( + inspect_strategy(inspector=inspector, opponent=d_geller), D + ) self.assertEqual(d_geller.strategy(inspector), C) diff --git a/axelrod/tests/unit/test_tournament.py b/axelrod/tests/unit/test_tournament.py index c91abcf46..b5742adf8 100644 --- a/axelrod/tests/unit/test_tournament.py +++ b/axelrod/tests/unit/test_tournament.py @@ -44,7 +44,9 @@ test_edges = [(0, 1), (1, 2), (3, 4)] deterministic_strategies = [ - s for s in axl.short_run_time_strategies if not axl.Classifiers["stochastic"](s()) + s + for s in axl.short_run_time_strategies + if not axl.Classifiers["stochastic"](s()) ] @@ -110,7 +112,9 @@ def test_init(self): noise=0.2, ) self.assertEqual(len(tournament.players), len(test_strategies)) - self.assertIsInstance(tournament.players[0].match_attributes["game"], axl.Game) + self.assertIsInstance( + tournament.players[0].match_attributes["game"], axl.Game + ) self.assertEqual(tournament.game.score((C, C)), (3, 3)) self.assertEqual(tournament.turns, self.test_turns) self.assertEqual(tournament.repetitions, 10) @@ -126,7 +130,9 @@ def test_init_with_match_attributes(self): ) mg = tournament.match_generator match_params = mg.build_single_match_params() - self.assertEqual(match_params["match_attributes"], {"length": float("inf")}) + self.assertEqual( + match_params["match_attributes"], {"length": float("inf")} + ) def test_warning(self): tournament = axl.Tournament( @@ -278,7 +284,11 @@ def test_serial_play_with_different_game(self): # Test that a non default game is passed to the result set game = axl.Game(p=-1, r=-1, s=-1, t=-1) tournament = axl.Tournament( - name=self.test_name, players=self.players, game=game, turns=1, repetitions=1 + name=self.test_name, + players=self.players, + game=game, + turns=1, + repetitions=1, ) results = tournament.play(progress_bar=False) self.assertLessEqual(np.max(results.scores), 0) @@ -412,7 +422,9 @@ def test_progress_bar_play_parallel(self): # these two examples were identified by hypothesis. @example( tournament=axl.Tournament( - players=[axl.BackStabber(), axl.MindReader()], turns=2, repetitions=1, + players=[axl.BackStabber(), axl.MindReader()], + turns=2, + repetitions=1, ) ) @example( @@ -544,7 +556,9 @@ def test_n_workers(self): tournament._n_workers(processes=max_processes + 2), max_processes ) - @unittest.skipIf(cpu_count() < 2, "not supported on single processor machines") + @unittest.skipIf( + cpu_count() < 2, "not supported on single processor machines" + ) def test_2_workers(self): # This is a separate test with a skip condition because we # cannot guarantee that the tests will always run on a machine @@ -742,9 +756,13 @@ def test_write_to_csv_without_results(self): turns=2, repetitions=2, ) - tournament.play(filename=self.filename, progress_bar=False, build_results=False) + tournament.play( + filename=self.filename, progress_bar=False, build_results=False + ) df = pd.read_csv(self.filename) - path = pathlib.Path("test_outputs/expected_test_tournament_no_results.csv") + path = pathlib.Path( + "test_outputs/expected_test_tournament_no_results.csv" + ) expected_df = pd.read_csv(axl_filename(path)) self.assertTrue(df.equals(expected_df)) @@ -766,7 +784,9 @@ def test_init(self): prob_end=self.test_prob_end, noise=0.2, ) - self.assertEqual(tournament.match_generator.prob_end, tournament.prob_end) + self.assertEqual( + tournament.match_generator.prob_end, tournament.prob_end + ) self.assertEqual(len(tournament.players), len(test_strategies)) self.assertEqual(tournament.game.score((C, C)), (3, 3)) self.assertIsNone(tournament.turns) @@ -800,12 +820,16 @@ def test_init(self): # these two examples were identified by hypothesis. @example( tournament=axl.Tournament( - players=[axl.BackStabber(), axl.MindReader()], prob_end=0.2, repetitions=1, + players=[axl.BackStabber(), axl.MindReader()], + prob_end=0.2, + repetitions=1, ) ) @example( tournament=axl.Tournament( - players=[axl.ThueMorse(), axl.MindReader()], prob_end=0.2, repetitions=1, + players=[axl.ThueMorse(), axl.MindReader()], + prob_end=0.2, + repetitions=1, ) ) def test_property_serial_play(self, tournament): @@ -858,7 +882,9 @@ def test_init(self): seed=integers(min_value=0, max_value=4294967295), ) @settings(max_examples=5) - def test_complete_tournament(self, strategies, turns, repetitions, noise, seed): + def test_complete_tournament( + self, strategies, turns, repetitions, noise, seed + ): """ A test to check that a spatial tournament on the complete multigraph gives the same results as the round robin. @@ -877,7 +903,11 @@ def test_complete_tournament(self, strategies, turns, repetitions, noise, seed): ) # create a complete spatial tournament spatial_tournament = axl.Tournament( - players, repetitions=repetitions, turns=turns, noise=noise, edges=edges + players, + repetitions=repetitions, + turns=turns, + noise=noise, + edges=edges, ) axl.seed(seed) @@ -888,16 +918,23 @@ def test_complete_tournament(self, strategies, turns, repetitions, noise, seed): self.assertEqual(results.ranked_names, spatial_results.ranked_names) self.assertEqual(results.num_players, spatial_results.num_players) self.assertEqual(results.repetitions, spatial_results.repetitions) - self.assertEqual(results.payoff_diffs_means, spatial_results.payoff_diffs_means) + self.assertEqual( + results.payoff_diffs_means, spatial_results.payoff_diffs_means + ) self.assertEqual(results.payoff_matrix, spatial_results.payoff_matrix) self.assertEqual(results.payoff_stddevs, spatial_results.payoff_stddevs) self.assertEqual(results.payoffs, spatial_results.payoffs) - self.assertEqual(results.cooperating_rating, spatial_results.cooperating_rating) + self.assertEqual( + results.cooperating_rating, spatial_results.cooperating_rating + ) self.assertEqual(results.cooperation, spatial_results.cooperation) self.assertEqual( - results.normalised_cooperation, spatial_results.normalised_cooperation + results.normalised_cooperation, + spatial_results.normalised_cooperation, + ) + self.assertEqual( + results.normalised_scores, spatial_results.normalised_scores ) - self.assertEqual(results.normalised_scores, spatial_results.normalised_scores) self.assertEqual( results.good_partner_matrix, spatial_results.good_partner_matrix ) @@ -917,7 +954,12 @@ def test_particular_tournament(self): edges = [(0, 2), (0, 3), (1, 2), (1, 3)] tournament = axl.Tournament(players, edges=edges) results = tournament.play(progress_bar=False) - expected_ranked_names = ["Cooperator", "Tit For Tat", "Grudger", "Defector"] + expected_ranked_names = [ + "Cooperator", + "Tit For Tat", + "Grudger", + "Defector", + ] self.assertEqual(results.ranked_names, expected_ranked_names) # Check that this tournament runs with noise @@ -973,13 +1015,17 @@ def test_complete_tournament(self, strategies, prob_end, seed, reps): players = [s() for s in strategies] # create a prob end round robin tournament - tournament = axl.Tournament(players, prob_end=prob_end, repetitions=reps) + tournament = axl.Tournament( + players, prob_end=prob_end, repetitions=reps + ) axl.seed(seed) results = tournament.play(progress_bar=False) # create a complete spatial tournament # edges - edges = [(i, j) for i in range(len(players)) for j in range(i, len(players))] + edges = [ + (i, j) for i in range(len(players)) for j in range(i, len(players)) + ] spatial_tournament = axl.Tournament( players, prob_end=prob_end, repetitions=reps, edges=edges @@ -1019,7 +1065,9 @@ def test_one_turn_tournament(self, tournament, seed): one_turn_results = tournament.play(progress_bar=False) self.assertEqual(prob_end_results.scores, one_turn_results.scores) self.assertEqual(prob_end_results.wins, one_turn_results.wins) - self.assertEqual(prob_end_results.cooperation, one_turn_results.cooperation) + self.assertEqual( + prob_end_results.cooperation, one_turn_results.cooperation + ) class TestHelperFunctions(unittest.TestCase): diff --git a/axelrod/tournament.py b/axelrod/tournament.py index 26144757c..427cd938a 100644 --- a/axelrod/tournament.py +++ b/axelrod/tournament.py @@ -229,7 +229,9 @@ def _get_file_objects(self, build_results=True): def _get_progress_bar(self): if self.use_progress_bar: - return tqdm.tqdm(total=self.match_generator.size, desc="Playing matches") + return tqdm.tqdm( + total=self.match_generator.size, desc="Playing matches" + ) return None def _write_interactions_to_file(self, results, writer): @@ -253,8 +255,14 @@ 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) @@ -274,16 +282,24 @@ def _write_interactions_to_file(self, results, writer): for state in states: row.append(state_distribution[state]) for state in states: - row.append(state_to_action_distributions[index][(state, C)]) - row.append(state_to_action_distributions[index][(state, D)]) + row.append( + state_to_action_distributions[index][(state, C)] + ) + row.append( + state_to_action_distributions[index][(state, D)] + ) - row.append(int(cooperations[index] >= cooperations[index - 1])) + row.append( + int(cooperations[index] >= cooperations[index - 1]) + ) writer.writerow(row) repetition += 1 self.num_interactions += 1 - def _run_parallel(self, processes: int = 2, build_results: bool = True) -> bool: + def _run_parallel( + self, processes: int = 2, build_results: bool = True + ) -> bool: """ Run all matches in parallel @@ -346,7 +362,8 @@ def _start_workers( """ for worker in range(workers): process = Process( - target=self._worker, args=(work_queue, done_queue, build_results) + target=self._worker, + args=(work_queue, done_queue, build_results), ) work_queue.put("STOP") process.start() @@ -384,7 +401,9 @@ def _process_done_queue( _close_objects(out_file, progress_bar) return True - def _worker(self, work_queue: Queue, done_queue: Queue, build_results: bool = True): + def _worker( + self, work_queue: Queue, done_queue: Queue, build_results: bool = True + ): """ The work for each parallel sub-process to execute. @@ -451,13 +470,17 @@ def _calculate_results(self, interactions): turns = len(interactions) results.append(turns) - score_per_turns = iu.compute_final_score_per_turn(interactions, self.game) + score_per_turns = iu.compute_final_score_per_turn( + interactions, self.game + ) results.append(score_per_turns) score_diffs_per_turns = score_diffs[0] / turns, score_diffs[1] / turns results.append(score_diffs_per_turns) - initial_coops = tuple(map(bool, iu.compute_cooperations(interactions[:1]))) + initial_coops = tuple( + map(bool, iu.compute_cooperations(interactions[:1])) + ) results.append(initial_coops) cooperations = iu.compute_cooperations(interactions) diff --git a/docs/conf.py b/docs/conf.py index 4f7d3347c..439ff1fd1 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -235,7 +235,13 @@ # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ - ("index", "Axelrod.tex", "Axelrod Documentation", "Vincent Knight", "manual") + ( + "index", + "Axelrod.tex", + "Axelrod Documentation", + "Vincent Knight", + "manual", + ) ] # The name of an image file (relative to this directory) to place at the top of @@ -263,7 +269,9 @@ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). -man_pages = [("index", "axelrod", "Axelrod Documentation", ["Vincent Knight"], 1)] +man_pages = [ + ("index", "axelrod", "Axelrod Documentation", ["Vincent Knight"], 1) +] # If true, show URL addresses after external links. # man_show_urls = False diff --git a/docs/tutorials/contributing/guidelines.rst b/docs/tutorials/contributing/guidelines.rst index 42fc0923d..ad40aeb9a 100644 --- a/docs/tutorials/contributing/guidelines.rst +++ b/docs/tutorials/contributing/guidelines.rst @@ -12,8 +12,11 @@ The project follows the following guidelines: `_ which includes **using descriptive variable names**. 3. Code Format: Use the `Black formatter `_ to format - all code and the `isort utility `_ to - sort import statements. + all code and the `isort utility `_ to + sort import statements. You can run black on all code with:: + + $ python -m black -l 80 . + 4. Commits: Please try to use commit messages that give a meaningful history for anyone using git's log features. Try to use messages that complete sentence, "This commit will..." There is some excellent guidance on the subject diff --git a/doctests.py b/doctests.py index 8bc74f50f..3ac377571 100644 --- a/doctests.py +++ b/doctests.py @@ -27,7 +27,8 @@ def load_tests(loader, tests, ignore): tests.addTests( doctest.DocFileSuite( # ELLIPSIS option tells doctest to ignore portions of the verification value. - os.path.join(root, f), optionflags=doctest.ELLIPSIS + os.path.join(root, f), + optionflags=doctest.ELLIPSIS, ) )