Skip to content

Commit

Permalink
Fix failing tests rebased for the dev branch (#1372)
Browse files Browse the repository at this point in the history
* Added new SpitefulCC Player to grudger.py, updated the list of all strategies and added coverage test in test_grudger.py

* changed 236 strategies to 237 in docs/index.rst

* changed SpitefulCC classifier and added strategy description

* changed description spitefulCC strategy

* Fix doctest.

This was failing on #1364
but the fix is trivial.

* Correct expected actions for meta strategy.

* Run black and isort.

Co-authored-by: Laura Romero <romerocarrillol@outlook.com>
  • Loading branch information
drvinceknight and RomeroLaura committed Sep 9, 2020
1 parent 7cbe2d7 commit e175c73
Show file tree
Hide file tree
Showing 30 changed files with 231 additions and 84 deletions.
4 changes: 2 additions & 2 deletions axelrod/ecosystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def __init__(
population: List[int] = None,
) -> None:
"""Create a new ecosystem.
Parameters
----------
results: ResultSet
Expand Down Expand Up @@ -83,7 +83,7 @@ def __init__(

def reproduce(self, turns: int):
"""Reproduce populations according to the payoff matrix.
Parameters
----------
turns: int
Expand Down
2 changes: 1 addition & 1 deletion axelrod/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def __init__(
self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1
) -> None:
"""Create a new game object.
Parameters
----------
r: int or float
Expand Down
8 changes: 4 additions & 4 deletions axelrod/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@

class Graph(object):
"""Weighted and directed graph class.
This class is intended for the graph associated to a Markov process,
since it gives easy access to the neighbors of a particular state.
Vertices can be any hashable Python object.
Initialize with a list of edges:
[[node1, node2, weights], ...]
Weights can be omitted for an undirected graph.
For efficiency, neighbors are cached in dictionaries. Undirected
graphs are implemented as directed graphs in which every edge (s, t)
has the opposite edge (t, s).
Attributes
----------
directed: Boolean indicating whether the graph is directed
Expand All @@ -31,7 +31,7 @@ class Graph(object):
all tails to their edge weights (None means no weight)
in_mapping: a dictionary mapping all tails to dictionaries that map
all heads to their edge weights (none means to weight)
Properties
----------
vertices: the set of vertices in the graph
Expand Down
7 changes: 6 additions & 1 deletion axelrod/load_data_.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,12 @@ def load_pso_tables(filename="pso_gambler.csv", directory="data"):
rows = load_file(filename, directory)
d = dict()
for row in rows:
name, a, b, c, = str(row[0]), int(row[1]), int(row[2]), int(row[3])
name, a, b, c, = (
str(row[0]),
int(row[1]),
int(row[2]),
int(row[3]),
)
values = list(map(float, row[4:]))
d[(name, int(a), int(b), int(c))] = values
return d
6 changes: 4 additions & 2 deletions axelrod/result_set.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,10 @@ def _reshape_out(
"DD to C count",
"DD to D count",
]
self.state_to_action_distribution = self._build_state_to_action_distribution(
sum_per_player_opponent_df[columns]
self.state_to_action_distribution = (
self._build_state_to_action_distribution(
sum_per_player_opponent_df[columns]
)
)
self.normalised_state_to_action_distribution = (
self._build_normalised_state_to_action_distribution()
Expand Down
2 changes: 2 additions & 0 deletions axelrod/strategies/_strategies.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@
GrudgerAlternator,
OppositeGrudger,
SoftGrudger,
SpitefulCC,
)
from .grumpy import Grumpy
from .handshake import Handshake
Expand Down Expand Up @@ -467,6 +468,7 @@
SolutionB1,
SolutionB5,
SpitefulTitForTat,
SpitefulCC,
Stalker,
StochasticCooperator,
StochasticWSLS,
Expand Down
5 changes: 3 additions & 2 deletions axelrod/strategies/cooperator.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,9 @@ def strategy(self, opponent: Player) -> Action:
After 3 rounds, if opponent has not defected to a max history depth of
10, defect.
"""
if self._has_played_enough_rounds_to_be_tricky() and self._opponents_has_cooperated_enough_to_be_tricky(
opponent
if (
self._has_played_enough_rounds_to_be_tricky()
and self._opponents_has_cooperated_enough_to_be_tricky(opponent)
):
return D
return C
Expand Down
35 changes: 33 additions & 2 deletions axelrod/strategies/grudger.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,7 @@ def __init__(self) -> None:
self.grudge_memory = 0

def strategy(self, opponent: Player) -> Action:
"""Begins by playing C, then plays D, D, D, D, C, C against a defection
"""
"""Begins by playing C, then plays D, D, D, D, C, C against a defection"""
if self.grudged:
strategy = [D, D, D, C, C][self.grudge_memory]
self.grudge_memory += 1
Expand Down Expand Up @@ -310,3 +309,35 @@ def strategy(self, opponent: Player) -> Action:

def __repr__(self) -> str:
return "%s: n=%s,d=%s,c=%s" % (self.name, self.n, self.d, self.c)


class SpitefulCC(Player):
"""
Behaves like Grudger after cooperating for 2 turns
Names:
- spiteful_cc: [Mathieu2015]_
"""

name = "SpitefulCC"
classifier = {
"memory_depth": float("inf"), # Long memory
"stochastic": False,
"long_run_time": False,
"inspects_source": False,
"manipulates_source": False,
"manipulates_state": False,
}

@staticmethod
def strategy(opponent: Player) -> Action:
"""
Cooperates until the oponent defects, then defects forever.
Always cooperates twice at the start.
"""
if len(opponent.history) < 2:
return C
elif opponent.defections:
return D
return C
14 changes: 8 additions & 6 deletions axelrod/strategies/human.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,12 +118,14 @@ def _status_messages(self):
if PROMPT2
else lambda cli: [(token_toolbar, self._history_toolbar())]
)
print_statement = "{}Turn {}: {} played {}, opponent played {}".format(
linesep,
len(self.history),
self.human_name,
self.symbols[self.history[-1]],
self.symbols[self.history.coplays[-1]],
print_statement = (
"{}Turn {}: {} played {}, opponent played {}".format(
linesep,
len(self.history),
self.human_name,
self.symbols[self.history[-1]],
self.symbols[self.history.coplays[-1]],
)
)
else:
toolbar = None
Expand Down
3 changes: 2 additions & 1 deletion axelrod/strategies/lookerup.py
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,8 @@ def mutate(self):
if r < self.mutation_probability:
initial_actions[i] = initial_actions[i].flip()
return self.create_new(
lookup_dict=lookup_dict, initial_actions=tuple(initial_actions),
lookup_dict=lookup_dict,
initial_actions=tuple(initial_actions),
)

def crossover(self, other):
Expand Down
2 changes: 1 addition & 1 deletion axelrod/strategies/sequence_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def __init__(self) -> None:


class ThueMorseInverse(ThueMorse):
""" A player who plays the inverse of the Thue-Morse sequence.
"""A player who plays the inverse of the Thue-Morse sequence.
Names:
Expand Down
12 changes: 6 additions & 6 deletions axelrod/strategies/titfortat.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,13 +307,13 @@ def strategy(opponent: Player) -> Action:

class OmegaTFT(Player):
"""OmegaTFT modifies Tit For Tat in two ways:
- checks for deadlock loops of alternating rounds of (C, D) and (D, C),
and attempting to break them
- uses a more sophisticated retaliation mechanism that is noise tolerant
- checks for deadlock loops of alternating rounds of (C, D) and (D, C),
and attempting to break them
- uses a more sophisticated retaliation mechanism that is noise tolerant
Names:
Names:
- OmegaTFT: [Slany2007]_
- OmegaTFT: [Slany2007]_
"""

name = "Omega TFT"
Expand Down Expand Up @@ -394,7 +394,7 @@ class OriginalGradual(Player):
Names:
- Gradual: [Beaufils1997]_
"""
"""

name = "Original Gradual"
classifier = {
Expand Down
14 changes: 12 additions & 2 deletions axelrod/tests/property.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,12 @@ def spatial_tournaments(

all_potential_edges = list(itertools.combinations(player_indices, 2))
all_potential_edges.extend([(i, i) for i in player_indices]) # Loops
edges = draw(lists(sampled_from(all_potential_edges), unique=True,))
edges = draw(
lists(
sampled_from(all_potential_edges),
unique=True,
)
)

# Ensure all players/nodes are connected:
node_indices = sorted(set([node for edge in edges for node in edge]))
Expand Down Expand Up @@ -311,7 +316,12 @@ def prob_end_spatial_tournaments(

all_potential_edges = list(itertools.combinations(player_indices, 2))
all_potential_edges.extend([(i, i) for i in player_indices]) # Loops
edges = draw(lists(sampled_from(all_potential_edges), unique=True,))
edges = draw(
lists(
sampled_from(all_potential_edges),
unique=True,
)
)

# Ensure all players/nodes are connected:
node_indices = sorted(set([node for edge in edges for node in edge]))
Expand Down
6 changes: 3 additions & 3 deletions axelrod/tests/strategies/test_axelrod_second.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ def test_strategy3(self):

def test_strategy4(self):
"""If score is greater than 2.25 either cooperate or defect,
if turn number <= 5; cooperate"""
if turn number <= 5; cooperate"""

opponent = axl.MockPlayer(actions=[C] * 5)
actions = [(C, C)] * 5
Expand Down Expand Up @@ -304,8 +304,8 @@ def test_strategy5(self):
)

def test_strategy6(self):
""" Given score per turn is greater than 2.25,
Tranquilizer will never defect twice in a row"""
"""Given score per turn is greater than 2.25,
Tranquilizer will never defect twice in a row"""

opponent = axl.MockPlayer(actions=[C] * 6)
actions = [(C, C)] * 4 + [(D, C), (C, C)]
Expand Down
12 changes: 9 additions & 3 deletions axelrod/tests/strategies/test_better_and_better.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,21 @@ def test_strategy(self):
"""Tests that the strategy gives expected behaviour."""
expected_actions = [(D, D)] * 90 + [(C, D)]
self.versus_test(
axl.Defector(), expected_actions=expected_actions, seed=6,
axl.Defector(),
expected_actions=expected_actions,
seed=6,
)
expected_actions = [(D, C)] * 10
self.versus_test(
axl.Cooperator(), expected_actions=expected_actions, seed=8,
axl.Cooperator(),
expected_actions=expected_actions,
seed=8,
)
expected_actions = [(D, D)] * 41 + [(C, D)]
self.versus_test(
axl.Defector(), expected_actions=expected_actions, seed=13,
axl.Defector(),
expected_actions=expected_actions,
seed=13,
)
expected_indices = [18, 39, 49, 67, 77, 116, 139, 142, 149]
m = axl.Match((self.player(), axl.Defector()), turns=150, seed=111)
Expand Down
6 changes: 5 additions & 1 deletion axelrod/tests/strategies/test_finite_state_machines.py
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,11 @@ def test_strategy(self):
(5, D),
(3, C),
(5, C),
] + [(7, C), (8, D), (6, C),] * 5
] + [
(7, C),
(8, D),
(6, C),
] * 5
self.transitions_test(state_and_actions)

state_and_actions = (
Expand Down
23 changes: 19 additions & 4 deletions axelrod/tests/strategies/test_gambler.py
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,9 @@ def test_vs_DCDDC2(self):
(D, D), # different than above test
]
self.versus_test(
axl.MockPlayer(opponent_actions), expected_actions=expected, seed=5,
axl.MockPlayer(opponent_actions),
expected_actions=expected,
seed=5,
)

def test_vs_DCDDC3(self):
Expand Down Expand Up @@ -580,7 +582,14 @@ 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):
Expand All @@ -591,7 +600,10 @@ class TestEvolvableGambler4(TestEvolvablePlayer):
init_parameters = {
"parameters": (2, 2, 2),
"pattern": [random.random() for _ in range(64)],
"initial_actions": (C, C,),
"initial_actions": (
C,
C,
),
}


Expand All @@ -600,7 +612,10 @@ 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,
),
)


Expand Down
Loading

0 comments on commit e175c73

Please sign in to comment.