Skip to content

Commit

Permalink
Run black on all files (#1368)
Browse files Browse the repository at this point in the history
* Add check to config.yml

* Install black before trying to use it.

* Move black installation

This is just to avoid installing in case the CI fails beforehand.

* Run black

* Additional documentation on running black

* Revert "Run black"

This reverts commit c50a6e3.

* Remove unnecessary installs.

* Revert "Revert "Run black""

This reverts commit 10ab222.

* Run isort.

* Make black and isort compatible.

Co-authored-by: T.J. Gaffney <[email protected]>
  • Loading branch information
drvinceknight and gaffney2010 authored Sep 9, 2020
1 parent bf42a8b commit c0d7752
Show file tree
Hide file tree
Showing 114 changed files with 3,274 additions and 1,141 deletions.
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
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
11 changes: 9 additions & 2 deletions axelrod/game.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
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
5 changes: 3 additions & 2 deletions axelrod/graph.py
Original file line number Diff line number Diff line change
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
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
46 changes: 32 additions & 14 deletions axelrod/moran.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def __init__(
fitness_transformation: Callable = None,
mutation_method="transition",
stop_on_fixation=True,
seed=None
seed=None,
) -> None:
"""
An agent based Moran process class. In each round, each player plays a
Expand Down Expand Up @@ -93,7 +93,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()
Expand Down Expand Up @@ -127,7 +129,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:
Expand All @@ -146,14 +150,18 @@ 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:
"""Copy the initial players into the first population, setting seeds as needed."""
self.players = []
for player in self.initial_players:
if (self.mutation_method == "atomic") and issubclass(player.__class__, EvolvablePlayer):
if (self.mutation_method == "atomic") and issubclass(
player.__class__, EvolvablePlayer
):
# For reproducibility, we generate random seeds for evolvable players.
seed = next(self._bulk_random)
new_player = player.create_new(seed=seed)
Expand All @@ -163,8 +171,9 @@ def set_players(self) -> None:
self.players.append(player)
self.populations = [self.population_distribution()]

def fitness_proportionate_selection(self,
scores: List, fitness_transformation: Callable = None) -> int:
def fitness_proportionate_selection(
self, scores: List, fitness_transformation: Callable = None
) -> int:
"""Randomly selects an individual proportionally to score.
Parameters
Expand Down Expand Up @@ -200,7 +209,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"
Expand Down Expand Up @@ -237,7 +248,9 @@ def death(self, index: int = None) -> int:
# Select locally
# index is not None in this case
vertex = self._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
Expand Down Expand Up @@ -370,7 +383,7 @@ def score_all(self) -> List:
noise=self.noise,
game=self.game,
deterministic_cache=self.deterministic_cache,
seed=next(self._bulk_random)
seed=next(self._bulk_random),
)
match.play()
match_scores = match.final_score_per_turn()
Expand Down Expand Up @@ -484,8 +497,11 @@ class ApproximateMoranProcess(MoranProcess):
"""

def __init__(
self, players: List[Player], cached_outcomes: dict, mutation_rate: float = 0,
seed: Optional[int] = None
self,
players: List[Player],
cached_outcomes: dict,
mutation_rate: float = 0,
seed: Optional[int] = None,
) -> None:
"""
Parameters
Expand All @@ -503,7 +519,7 @@ def __init__(
noise=0,
deterministic_cache=None,
mutation_rate=mutation_rate,
seed=seed
seed=seed,
)
self.cached_outcomes = cached_outcomes

Expand All @@ -529,7 +545,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]
scores[j] += cached_score[1]
Expand Down
Loading

0 comments on commit c0d7752

Please sign in to comment.