Skip to content

Commit c0d7752

Browse files
Run black on all files (#1368)
* 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]>
1 parent bf42a8b commit c0d7752

File tree

114 files changed

+3274
-1141
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

114 files changed

+3274
-1141
lines changed

.github/workflows/config.yml

+4
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,10 @@ jobs:
5858
run: |
5959
python -m pip install pylint
6060
python -m pylint --disable=all --enable=unused-import axelrod/strategies/_strategies.py
61+
- name: Check format
62+
run: |
63+
python -m pip install black
64+
python -m black -l 80 . --check
6165
- name: Check that installs
6266
run: |
6367
python setup.py install

.isort.cfg

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,4 @@ multi_line_output = 3
44
include_trailing_comma = True
55
force_grid_wrap = 0
66
combine_as_imports = True
7-
line_length = 88
7+
line_length = 80

.prepare-commit-msg.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,9 @@
4141

4242
if branch.startswith(issue_prefix):
4343
issue_number = re.match("%s(.*)" % issue_prefix, branch).group(1)
44-
print("prepare-commit-msg: Prepending [#%s] to commit message" % issue_number)
44+
print(
45+
"prepare-commit-msg: Prepending [#%s] to commit message" % issue_number
46+
)
4547

4648
with open(commit_msg_filepath, "r+") as f:
4749
content = f.read()

axelrod/evolvable_player.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
class InsufficientParametersError(Exception):
99
"""Error indicating that insufficient parameters were specified to initialize an Evolvable Player."""
10+
1011
def __init__(self, *args):
1112
super().__init__(*args)
1213

@@ -49,7 +50,7 @@ def create_new(self, **kwargs):
4950
def serialize_parameters(self):
5051
"""Serialize parameters."""
5152
pickled = dumps(self.init_kwargs) # bytes
52-
s = base64.b64encode(pickled).decode('utf8') # string
53+
s = base64.b64encode(pickled).decode("utf8") # string
5354
return s
5455

5556
@classmethod

axelrod/fingerprint.py

+27-13
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def _create_points(step: float, progress_bar: bool = True) -> List[Point]:
4242
num = int((1 / step) // 1) + 1
4343

4444
if progress_bar:
45-
p_bar = tqdm.tqdm(total=num**2, desc="Generating points")
45+
p_bar = tqdm.tqdm(total=num ** 2, desc="Generating points")
4646

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

8989
if x + y >= 1:
9090
joss_ann = DualTransformer()(
91-
JossAnnTransformer((1 - x, 1 - y))(
92-
probe_class))(**init_kwargs)
91+
JossAnnTransformer((1 - x, 1 - y))(probe_class)
92+
)(**init_kwargs)
9393
else:
9494
joss_ann = JossAnnTransformer((x, y))(probe_class)(**init_kwargs)
9595
return joss_ann
@@ -177,7 +177,10 @@ def _generate_data(interactions: dict, points: list, edges: list) -> dict:
177177
"""
178178
edge_scores = [
179179
np.mean(
180-
[compute_final_score_per_turn(scores)[0] for scores in interactions[edge]]
180+
[
181+
compute_final_score_per_turn(scores)[0]
182+
for scores in interactions[edge]
183+
]
181184
)
182185
for edge in edges
183186
]
@@ -215,7 +218,9 @@ def _reshape_data(data: dict, points: list, size: int) -> np.ndarray:
215218

216219
class AshlockFingerprint(object):
217220
def __init__(
218-
self, strategy: Union[type, Player], probe: Union[type, Player] = axl.TitForTat
221+
self,
222+
strategy: Union[type, Player],
223+
probe: Union[type, Player] = axl.TitForTat,
219224
) -> None:
220225
"""
221226
Parameters
@@ -277,7 +282,7 @@ def fingerprint(
277282
processes: int = None,
278283
filename: str = None,
279284
progress_bar: bool = True,
280-
seed: int = None
285+
seed: int = None,
281286
) -> dict:
282287
"""Build and play the spatial tournament.
283288
@@ -323,8 +328,11 @@ def fingerprint(
323328

324329
self.step = step
325330
self.spatial_tournament = axl.Tournament(
326-
tourn_players, turns=turns, repetitions=repetitions, edges=edges,
327-
seed=seed
331+
tourn_players,
332+
turns=turns,
333+
repetitions=repetitions,
334+
edges=edges,
335+
seed=seed,
328336
)
329337
self.spatial_tournament.play(
330338
build_results=False,
@@ -432,7 +440,7 @@ def fingerprint(
432440
processes: int = None,
433441
filename: str = None,
434442
progress_bar: bool = True,
435-
seed: int = None
443+
seed: int = None,
436444
) -> np.array:
437445
"""Creates a spatial tournament to run the necessary matches to obtain
438446
fingerprint data.
@@ -479,7 +487,7 @@ def fingerprint(
479487
turns=turns,
480488
noise=noise,
481489
repetitions=repetitions,
482-
seed=seed
490+
seed=seed,
483491
)
484492
tournament.play(
485493
filename=filename,
@@ -516,7 +524,9 @@ def analyse_cooperation_ratio(filename):
516524
opponent in each turn. The ith row corresponds to the ith opponent
517525
and the jth column the jth turn.
518526
"""
519-
did_c = np.vectorize(lambda actions: [int(action == "C") for action in actions])
527+
did_c = np.vectorize(
528+
lambda actions: [int(action == "C") for action in actions]
529+
)
520530

521531
cooperation_rates = {}
522532
df = dd.read_csv(filename)
@@ -525,7 +535,10 @@ def analyse_cooperation_ratio(filename):
525535
df = df[df["Player index"] == 0][["Opponent index", "Actions"]]
526536

527537
for _, row in df.iterrows():
528-
opponent_index, player_history = row["Opponent index"], row["Actions"]
538+
opponent_index, player_history = (
539+
row["Opponent index"],
540+
row["Actions"],
541+
)
529542
if opponent_index in cooperation_rates:
530543
cooperation_rates[opponent_index].append(did_c(player_history))
531544
else:
@@ -590,7 +603,8 @@ def plot(
590603

591604
if display_names:
592605
plt.yticks(
593-
range(len(self.opponents)), [str(player) for player in self.opponents]
606+
range(len(self.opponents)),
607+
[str(player) for player in self.opponents],
594608
)
595609
else:
596610
plt.yticks([0, len(self.opponents) - 1], [0, 1])

axelrod/game.py

+9-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,9 @@ class Game(object):
1616
The numerical score attribute to all combinations of action pairs.
1717
"""
1818

19-
def __init__(self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1) -> None:
19+
def __init__(
20+
self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1
21+
) -> None:
2022
"""Create a new game object.
2123
2224
Parameters
@@ -30,7 +32,12 @@ def __init__(self, r: Score = 3, s: Score = 0, t: Score = 5, p: Score = 1) -> No
3032
p: int or float
3133
Score obtained by both player for mutual defection.
3234
"""
33-
self.scores = {(C, C): (r, r), (D, D): (p, p), (C, D): (s, t), (D, C): (t, s)}
35+
self.scores = {
36+
(C, C): (r, r),
37+
(D, D): (p, p),
38+
(C, D): (s, t),
39+
(D, C): (t, s),
40+
}
3441

3542
def RPST(self) -> Tuple[Score, Score, Score, Score]:
3643
"""Returns game matrix values in Press and Dyson notation."""

axelrod/graph.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -155,8 +155,9 @@ def attached_complete_graphs(length, loops=True, directed=False):
155155
for cluster in range(2):
156156
for i in range(length):
157157
for j in range(i + 1, length):
158-
edges.append(("{}:{}".format(cluster, i),
159-
"{}:{}".format(cluster, j)))
158+
edges.append(
159+
("{}:{}".format(cluster, i), "{}:{}".format(cluster, j))
160+
)
160161
# Attach at one node
161162
edges.append(("0:0", "1:0"))
162163
graph = Graph(directed=directed, edges=edges)

axelrod/history.py

+6-2
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,9 @@ def __eq__(self, other):
8282
if isinstance(other, list):
8383
return self._plays == other
8484
elif isinstance(other, History):
85-
return self._plays == other._plays and self._coplays == other._coplays
85+
return (
86+
self._plays == other._plays and self._coplays == other._coplays
87+
)
8688
raise TypeError("Cannot compare types.")
8789

8890
def __getitem__(self, key):
@@ -121,7 +123,9 @@ def __init__(self, memory_depth, plays=None, coplays=None):
121123
def flip_plays(self):
122124
"""Creates a flipped plays history for use with DualTransformer."""
123125
flipped_plays = [action.flip() for action in self._plays]
124-
return self.__class__(self.memory_depth, plays=flipped_plays, coplays=self._coplays)
126+
return self.__class__(
127+
self.memory_depth, plays=flipped_plays, coplays=self._coplays
128+
)
125129

126130
def append(self, play, coplay):
127131
"""Appends a new (play, coplay) pair an updates metadata for

axelrod/interaction_utils.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ def compute_final_score(interactions, game=None):
3232
return None
3333

3434
final_score = tuple(
35-
sum([score[player_index] for score in scores]) for player_index in [0, 1]
35+
sum([score[player_index] for score in scores])
36+
for player_index in [0, 1]
3637
)
3738
return final_score
3839

axelrod/match.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def __init__(
2929
noise=0,
3030
match_attributes=None,
3131
reset=True,
32-
seed=None
32+
seed=None,
3333
):
3434
"""
3535
Parameters
@@ -193,7 +193,8 @@ def play(self):
193193
result = []
194194
for _ in range(turns):
195195
plays = self.simultaneous_play(
196-
self.players[0], self.players[1], self.noise)
196+
self.players[0], self.players[1], self.noise
197+
)
197198
result.append(plays)
198199

199200
if self._cache_update_required:

axelrod/match_generator.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ def __init__(
1212
prob_end=None,
1313
edges=None,
1414
match_attributes=None,
15-
seed=None
15+
seed=None,
1616
):
1717
"""
1818
A class to generate matches. This is used by the Tournament class which

axelrod/moran.py

+32-14
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ def __init__(
2828
fitness_transformation: Callable = None,
2929
mutation_method="transition",
3030
stop_on_fixation=True,
31-
seed=None
31+
seed=None,
3232
) -> None:
3333
"""
3434
An agent based Moran process class. In each round, each player plays a
@@ -93,7 +93,9 @@ def __init__(
9393
if m in ["atomic", "transition"]:
9494
self.mutation_method = m
9595
else:
96-
raise ValueError("Invalid mutation method {}".format(mutation_method))
96+
raise ValueError(
97+
"Invalid mutation method {}".format(mutation_method)
98+
)
9799
assert (mutation_rate >= 0) and (mutation_rate <= 1)
98100
assert (noise >= 0) and (noise <= 1)
99101
mode = mode.lower()
@@ -127,7 +129,9 @@ def __init__(
127129
d[str(p)] = p
128130
mutation_targets = dict()
129131
for key in sorted(keys):
130-
mutation_targets[key] = [v for (k, v) in sorted(d.items()) if k != key]
132+
mutation_targets[key] = [
133+
v for (k, v) in sorted(d.items()) if k != key
134+
]
131135
self.mutation_targets = mutation_targets
132136

133137
if interaction_graph is None:
@@ -146,14 +150,18 @@ def __init__(
146150
self.fitness_transformation = fitness_transformation
147151
# Map players to graph vertices
148152
self.locations = sorted(interaction_graph.vertices)
149-
self.index = dict(zip(sorted(interaction_graph.vertices), range(len(players))))
153+
self.index = dict(
154+
zip(sorted(interaction_graph.vertices), range(len(players)))
155+
)
150156
self.fixated = self.fixation_check()
151157

152158
def set_players(self) -> None:
153159
"""Copy the initial players into the first population, setting seeds as needed."""
154160
self.players = []
155161
for player in self.initial_players:
156-
if (self.mutation_method == "atomic") and issubclass(player.__class__, EvolvablePlayer):
162+
if (self.mutation_method == "atomic") and issubclass(
163+
player.__class__, EvolvablePlayer
164+
):
157165
# For reproducibility, we generate random seeds for evolvable players.
158166
seed = next(self._bulk_random)
159167
new_player = player.create_new(seed=seed)
@@ -163,8 +171,9 @@ def set_players(self) -> None:
163171
self.players.append(player)
164172
self.populations = [self.population_distribution()]
165173

166-
def fitness_proportionate_selection(self,
167-
scores: List, fitness_transformation: Callable = None) -> int:
174+
def fitness_proportionate_selection(
175+
self, scores: List, fitness_transformation: Callable = None
176+
) -> int:
168177
"""Randomly selects an individual proportionally to score.
169178
170179
Parameters
@@ -200,7 +209,9 @@ def mutate(self, index: int) -> Player:
200209

201210
if self.mutation_method == "atomic":
202211
if not issubclass(self.players[index].__class__, EvolvablePlayer):
203-
raise TypeError("Player is not evolvable. Use a subclass of EvolvablePlayer.")
212+
raise TypeError(
213+
"Player is not evolvable. Use a subclass of EvolvablePlayer."
214+
)
204215
return self.players[index].mutate()
205216

206217
# Assuming mutation_method == "transition"
@@ -237,7 +248,9 @@ def death(self, index: int = None) -> int:
237248
# Select locally
238249
# index is not None in this case
239250
vertex = self._random.choice(
240-
sorted(self.reproduction_graph.out_vertices(self.locations[index]))
251+
sorted(
252+
self.reproduction_graph.out_vertices(self.locations[index])
253+
)
241254
)
242255
i = self.index[vertex]
243256
return i
@@ -370,7 +383,7 @@ def score_all(self) -> List:
370383
noise=self.noise,
371384
game=self.game,
372385
deterministic_cache=self.deterministic_cache,
373-
seed=next(self._bulk_random)
386+
seed=next(self._bulk_random),
374387
)
375388
match.play()
376389
match_scores = match.final_score_per_turn()
@@ -484,8 +497,11 @@ class ApproximateMoranProcess(MoranProcess):
484497
"""
485498

486499
def __init__(
487-
self, players: List[Player], cached_outcomes: dict, mutation_rate: float = 0,
488-
seed: Optional[int] = None
500+
self,
501+
players: List[Player],
502+
cached_outcomes: dict,
503+
mutation_rate: float = 0,
504+
seed: Optional[int] = None,
489505
) -> None:
490506
"""
491507
Parameters
@@ -503,7 +519,7 @@ def __init__(
503519
noise=0,
504520
deterministic_cache=None,
505521
mutation_rate=mutation_rate,
506-
seed=seed
522+
seed=seed,
507523
)
508524
self.cached_outcomes = cached_outcomes
509525

@@ -529,7 +545,9 @@ def score_all(self) -> List:
529545
scores = [0] * N
530546
for i in range(N):
531547
for j in range(i + 1, N):
532-
player_names = tuple([str(self.players[i]), str(self.players[j])])
548+
player_names = tuple(
549+
[str(self.players[i]), str(self.players[j])]
550+
)
533551
cached_score = self._get_scores_from_cache(player_names)
534552
scores[i] += cached_score[0]
535553
scores[j] += cached_score[1]

0 commit comments

Comments
 (0)