Skip to content
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

Run black and isort over entire library #1203

Merged
merged 4 commits into from
Aug 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 7 additions & 3 deletions axelrod/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@
from .plot import Plot
from .game import DefaultGame, Game
from .player import (
get_state_distribution_from_history, is_basic, obey_axelrod,
update_history, update_state_distribution, Player)
get_state_distribution_from_history,
is_basic,
obey_axelrod,
update_history,
update_state_distribution,
Player,
)
from .mock_player import MockPlayer
from .match import Match
from .moran import MoranProcess, ApproximateMoranProcess
Expand All @@ -21,4 +26,3 @@
from .result_set import ResultSet
from .ecosystem import Ecosystem
from .fingerprint import AshlockFingerprint, TransitiveFingerprint

6 changes: 2 additions & 4 deletions axelrod/_strategy_utils.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
"""Utilities used by various strategies."""

import itertools

from functools import lru_cache

from axelrod.player import update_history
from axelrod.action import Action
from axelrod.player import update_history
from axelrod.strategies.cooperator import Cooperator
from axelrod.strategies.defector import Defector


C, D = Action.C, Action.D


Expand Down Expand Up @@ -66,7 +64,7 @@ def inspect_strategy(inspector, opponent):
Action
The action that would be taken by the opponent.
"""
if hasattr(opponent, 'foil_strategy_inspection'):
if hasattr(opponent, "foil_strategy_inspection"):
return opponent.foil_strategy_inspection()
else:
return opponent.strategy(inspector)
Expand Down
9 changes: 5 additions & 4 deletions axelrod/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

class UnknownActionError(ValueError):
"""Error indicating an unknown action was used."""

def __init__(self, *args):
super(UnknownActionError, self).__init__(*args)

Expand All @@ -30,10 +31,10 @@ def __bool__(self):
return bool(self.value)

def __repr__(self):
return '{}'.format(self.name)
return "{}".format(self.name)

def __str__(self):
return '{}'.format(self.name)
return "{}".format(self.name)

def flip(self):
"""Returns the opposite Action."""
Expand Down Expand Up @@ -61,9 +62,9 @@ def from_char(cls, character):
UnknownActionError
If the input string is not 'C' or 'D'
"""
if character == 'C':
if character == "C":
return cls.C
if character == 'D':
if character == "D":
return cls.D
raise UnknownActionError('Character must be "C" or "D".')

Expand Down
30 changes: 16 additions & 14 deletions axelrod/deterministic_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,13 @@
...
"""

from collections import UserDict
import pickle
from collections import UserDict
from typing import List, Tuple

from .action import Action
from .player import Player

from typing import List, Tuple

CachePlayerKey = Tuple[Player, Player, int]
CacheKey = Tuple[str, str, int]

Expand Down Expand Up @@ -53,13 +52,13 @@ def _is_valid_key(key: CachePlayerKey) -> bool:
return False

if not (
isinstance(key[0], Player) and
isinstance(key[1], Player) and
isinstance(key[2], int)
isinstance(key[0], Player)
and isinstance(key[1], Player)
and isinstance(key[2], int)
):
return False

if key[0].classifier['stochastic'] or key[1].classifier['stochastic']:
if key[0].classifier["stochastic"] or key[1].classifier["stochastic"]:
return False

return True
Expand Down Expand Up @@ -106,7 +105,7 @@ class DeterministicCache(UserDict):
methods to save/load the cache to/from a file.
"""

def __init__(self, file_name: str=None) -> None:
def __init__(self, file_name: str = None) -> None:
"""Initialize a new cache.

Parameters
Expand All @@ -131,16 +130,18 @@ def __contains__(self, key):
def __setitem__(self, key: CachePlayerKey, value):
"""Validate the key and value before setting them."""
if not self.mutable:
raise ValueError('Cannot update cache unless mutable is True.')
raise ValueError("Cannot update cache unless mutable is True.")

if not _is_valid_key(key):
raise ValueError(
"Key must be a tuple of 2 deterministic axelrod Player classes "
"and an integer")
"and an integer"
)

if not _is_valid_value(value):
raise ValueError(
'Value must be a list with length equal to turns attribute')
"Value must be a list with length equal to turns attribute"
)

super().__setitem__(_key_transform(key), value)

Expand All @@ -152,7 +153,7 @@ def save(self, file_name: str) -> bool:
file_name : string
File path to which the cache should be saved
"""
with open(file_name, 'wb') as io:
with open(file_name, "wb") as io:
pickle.dump(self.data, io)
return True

Expand All @@ -164,13 +165,14 @@ def load(self, file_name: str) -> bool:
file_name : string
Path to a previously saved cache file
"""
with open(file_name, 'rb') as io:
with open(file_name, "rb") as io:
data = pickle.load(io)

if isinstance(data, dict):
self.data = data
else:
raise ValueError(
"Cache file exists but is not the correct format. "
"Try deleting and re-building the cache file.")
"Try deleting and re-building the cache file."
)
return True
21 changes: 13 additions & 8 deletions axelrod/ecosystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,7 @@
"""

import random

from typing import List, Callable
from typing import Callable, List

from axelrod.result_set import ResultSet

Expand All @@ -27,9 +26,12 @@ class Ecosystem(object):
The number of players
"""

def __init__(self, results: ResultSet,
fitness: Callable[[float], float] = None,
population: List[int] = None) -> None:
def __init__(
self,
results: ResultSet,
fitness: Callable[[float], float] = None,
population: List[int] = None,
) -> None:
"""Create a new ecosystem.

Parameters
Expand Down Expand Up @@ -58,16 +60,19 @@ def __init__(self, results: ResultSet,
if population:
if min(population) < 0:
raise TypeError(
"Minimum value of population vector must be non-negative")
"Minimum value of population vector must be non-negative"
)
elif len(population) != self.num_players:
raise TypeError(
"Population vector must be same size as number of players")
"Population vector must be same size as number of players"
)
else:
norm = sum(population)
self.population_sizes = [[p / norm for p in population]]
else:
self.population_sizes = [
[1 / self.num_players for _ in range(self.num_players)]]
[1 / self.num_players for _ in range(self.num_players)]
]

# This function is quite arbitrary and probably only influences the
# kinetics for the current code.
Expand Down
15 changes: 8 additions & 7 deletions axelrod/eigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@
eigenvectors.
"""

import numpy
from typing import Tuple

import numpy


def _normalise(nvec: numpy.ndarray) -> numpy.ndarray:
"""Normalises the given numpy array."""
with numpy.errstate(invalid='ignore'):
with numpy.errstate(invalid="ignore"):
result = nvec / numpy.sqrt(numpy.dot(nvec, nvec))
return result

Expand Down Expand Up @@ -45,8 +46,9 @@ def _power_iteration(mat: numpy.matrix, initial: numpy.ndarray) -> numpy.ndarray
yield vec


def principal_eigenvector(mat: numpy.matrix, maximum_iterations=1000,
max_error=1e-3) -> Tuple[numpy.ndarray, float]:
def principal_eigenvector(
mat: numpy.matrix, maximum_iterations=1000, max_error=1e-3
) -> Tuple[numpy.ndarray, float]:
"""
Computes the (normalised) principal eigenvector of the given matrix.

Expand Down Expand Up @@ -75,7 +77,7 @@ def principal_eigenvector(mat: numpy.matrix, maximum_iterations=1000,

# Power iteration
if not maximum_iterations:
maximum_iterations = float('inf')
maximum_iterations = float("inf")
last = initial
for i, vector in enumerate(_power_iteration(mat, initial=initial)):
if i > maximum_iterations:
Expand All @@ -84,8 +86,7 @@ def principal_eigenvector(mat: numpy.matrix, maximum_iterations=1000,
break
last = vector
# Compute the eigenvalue (Rayleigh quotient)
eigenvalue = numpy.dot(
numpy.dot(mat_, vector), vector) / numpy.dot(vector, vector)
eigenvalue = numpy.dot(numpy.dot(mat_, vector), vector) / numpy.dot(vector, vector)
# Liberate the eigenvalue from numpy
eigenvalue = float(eigenvalue)
return vector, eigenvalue
Loading