Skip to content

Added docstrings to strategy methods #1375

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 21 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
1622f94
Added docstrings to strategy methods so they don't display the defaul…
czemtsop Sep 26, 2020
02d4ccd
Run black on all files (#1368)
drvinceknight Sep 9, 2020
3c9e165
Write a new documentation page with branch info (#1367)
drvinceknight Sep 9, 2020
e408ad7
Fix failing tests rebased for the dev branch (#1372)
drvinceknight Sep 9, 2020
a475cc5
[#1370] Remove some tests from test_meta.py (#1373)
marcharper Sep 25, 2020
5639e7f
Added docstrings to strategy methods so they don't display the defaul…
czemtsop Sep 26, 2020
e036f2d
Added new SpitefulCC Player to grudger.py, updated the list of all st…
RomeroLaura Aug 7, 2020
b5ad28a
changed SpitefulCC classifier and added strategy description
RomeroLaura Aug 8, 2020
f6e2f3c
changed description spitefulCC strategy
RomeroLaura Aug 8, 2020
2bd889d
fix test_meta.py
RomeroLaura Aug 19, 2020
ec204bc
Run black on all files (#1368)
drvinceknight Sep 9, 2020
98ccf34
Run black on all files (#1368)
drvinceknight Sep 9, 2020
2c61618
changed SpitefulCC classifier and added strategy description
RomeroLaura Aug 8, 2020
87fa66e
Run black on all files (#1368)
drvinceknight Sep 9, 2020
e8c8de6
Fix failing tests rebased for the dev branch (#1372)
drvinceknight Sep 9, 2020
1c62084
Rebased to dev branch
czemtsop Sep 26, 2020
4c3da85
Resolve merge conflicts
czemtsop Sep 26, 2020
075c3d9
Reformatted with black
czemtsop Sep 26, 2020
a4e9cd6
Modified test_boolean_filtering() test
czemtsop Sep 30, 2020
2325486
Modified test_boolean_filtering() test
czemtsop Sep 30, 2020
41bfb70
#1376 Modified test_boolean_filtering() test
czemtsop Sep 30, 2020
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .github/workflows/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,10 @@ jobs:
run: |
python -m pip install pylint
python -m pylint --disable=all --enable=unused-import axelrod/strategies/_strategies.py
- name: Check format
run: |
python -m pip install black
python -m black -l 80 . --check
- name: Check that installs
run: |
python setup.py install
Expand Down
2 changes: 1 addition & 1 deletion .isort.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ multi_line_output = 3
include_trailing_comma = True
force_grid_wrap = 0
combine_as_imports = True
line_length = 88
line_length = 80
4 changes: 3 additions & 1 deletion .prepare-commit-msg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
6 changes: 3 additions & 3 deletions axelrod/_strategy_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def simulate_match(player_1, player_2, strategy, rounds=10):


def _calculate_scores(p1, p2, game):
"""Calculates the scores for two players based their history.
"""Calculates the scores for two players based on their history.

Parameters
----------
Expand Down Expand Up @@ -142,9 +142,9 @@ def look_ahead(player1, player2, game, rounds=10):

Parameters
----------
player_1: Player
player1: Player
The player that will look ahead.
player_2: Player
player2: Player
The opponent that will be inspected.
game: Game
The Game object used to score rounds.
Expand Down
5 changes: 4 additions & 1 deletion axelrod/compute_finite_state_machine_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,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

Expand Down
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
3 changes: 2 additions & 1 deletion axelrod/evolvable_player.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -49,7 +50,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
Expand Down
40 changes: 27 additions & 13 deletions axelrod/fingerprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def _create_points(step: float, progress_bar: bool = True) -> List[Point]:
num = int((1 / step) // 1) + 1

if progress_bar:
p_bar = tqdm.tqdm(total=num**2, desc="Generating points")
p_bar = tqdm.tqdm(total=num ** 2, desc="Generating points")

points = []
for x in np.linspace(0, 1, num):
Expand Down Expand Up @@ -88,8 +88,8 @@ def _create_jossann(point: Point, probe: Any) -> Player:

if x + y >= 1:
joss_ann = DualTransformer()(
JossAnnTransformer((1 - x, 1 - y))(
probe_class))(**init_kwargs)
JossAnnTransformer((1 - x, 1 - y))(probe_class)
)(**init_kwargs)
else:
joss_ann = JossAnnTransformer((x, y))(probe_class)(**init_kwargs)
return joss_ann
Expand Down Expand Up @@ -177,7 +177,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
]
Expand Down Expand Up @@ -215,7 +218,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
Expand Down Expand Up @@ -277,7 +282,7 @@ def fingerprint(
processes: int = None,
filename: str = None,
progress_bar: bool = True,
seed: int = None
seed: int = None,
) -> dict:
"""Build and play the spatial tournament.

Expand Down Expand Up @@ -323,8 +328,11 @@ def fingerprint(

self.step = step
self.spatial_tournament = axl.Tournament(
tourn_players, turns=turns, repetitions=repetitions, edges=edges,
seed=seed
tourn_players,
turns=turns,
repetitions=repetitions,
edges=edges,
seed=seed,
)
self.spatial_tournament.play(
build_results=False,
Expand Down Expand Up @@ -432,7 +440,7 @@ def fingerprint(
processes: int = None,
filename: str = None,
progress_bar: bool = True,
seed: int = None
seed: int = None,
) -> np.array:
"""Creates a spatial tournament to run the necessary matches to obtain
fingerprint data.
Expand Down Expand Up @@ -479,7 +487,7 @@ def fingerprint(
turns=turns,
noise=noise,
repetitions=repetitions,
seed=seed
seed=seed,
)
tournament.play(
filename=filename,
Expand Down Expand Up @@ -516,7 +524,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)
Expand All @@ -525,7 +535,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:
Expand Down Expand Up @@ -590,7 +603,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])
Expand Down
13 changes: 10 additions & 3 deletions axelrod/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ 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
----------
r: int or float
Expand All @@ -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."""
Expand Down
13 changes: 7 additions & 6 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 Expand Up @@ -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)
Expand Down
8 changes: 6 additions & 2 deletions axelrod/history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -121,7 +123,9 @@ def __init__(self, memory_depth, plays=None, coplays=None):
def flip_plays(self):
"""Creates a flipped plays history for use with DualTransformer."""
flipped_plays = [action.flip() for action in self._plays]
return self.__class__(self.memory_depth, plays=flipped_plays, coplays=self._coplays)
return self.__class__(
self.memory_depth, plays=flipped_plays, coplays=self._coplays
)

def append(self, play, coplay):
"""Appends a new (play, coplay) pair an updates metadata for
Expand Down
3 changes: 2 additions & 1 deletion axelrod/interaction_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

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
5 changes: 3 additions & 2 deletions axelrod/match.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def __init__(
noise=0,
match_attributes=None,
reset=True,
seed=None
seed=None,
):
"""
Parameters
Expand Down Expand Up @@ -193,7 +193,8 @@ def play(self):
result = []
for _ in range(turns):
plays = self.simultaneous_play(
self.players[0], self.players[1], self.noise)
self.players[0], self.players[1], self.noise
)
result.append(plays)

if self._cache_update_required:
Expand Down
2 changes: 1 addition & 1 deletion axelrod/match_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ def __init__(
prob_end=None,
edges=None,
match_attributes=None,
seed=None
seed=None,
):
"""
A class to generate matches. This is used by the Tournament class which
Expand Down
Loading