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

Fix numpy depreciation: np.matrix -> np.array #1218

Merged
merged 3 commits into from
Oct 30, 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
14 changes: 8 additions & 6 deletions .prepare-commit-msg.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,20 @@
# e.g. for a branch named 'issue-123', the commit message will start with
# '[#123]'
# If you wish to use a diferent prefix on branch names, change it here.
issue_prefix = 'issue-'
issue_prefix = "issue-"

commit_msg_filepath = sys.argv[1]
branch = check_output(
['git', 'symbolic-ref', '--short', 'HEAD']
).strip().decode(encoding='UTF-8')
branch = (
check_output(["git", "symbolic-ref", "--short", "HEAD"])
.strip()
.decode(encoding="UTF-8")
)

if branch.startswith(issue_prefix):
issue_number = re.match('%s(.*)' % issue_prefix, branch).group(1)
issue_number = re.match("%s(.*)" % issue_prefix, branch).group(1)
print("prepare-commit-msg: Prepending [#%s] to commit message" % issue_number)

with open(commit_msg_filepath, 'r+') as f:
with open(commit_msg_filepath, "r+") as f:
content = f.read()
f.seek(0, 0)
f.write("[#%s] %s" % (issue_number, content))
Expand Down
16 changes: 8 additions & 8 deletions axelrod/eigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,24 @@
def _normalise(nvec: numpy.ndarray) -> numpy.ndarray:
"""Normalises the given numpy array."""
with numpy.errstate(invalid="ignore"):
result = nvec / numpy.sqrt(numpy.dot(nvec, nvec))
result = nvec / numpy.sqrt((nvec @ nvec))
return result


def _squared_error(vector_1: numpy.ndarray, vector_2: numpy.ndarray) -> float:
"""Computes the squared error between two numpy arrays."""
diff = vector_1 - vector_2
s = numpy.dot(diff, diff)
s = diff @ diff
return numpy.sqrt(s)


def _power_iteration(mat: numpy.matrix, initial: numpy.ndarray) -> numpy.ndarray:
def _power_iteration(mat: numpy.array, initial: numpy.ndarray) -> numpy.ndarray:
"""
Generator of successive approximations.

Params
------
mat: numpy.matrix
mat: numpy.array
The matrix to use for multiplication iteration
initial: numpy.array, None
The initial state. Will be set to numpy.array([1, 1, ...]) if None
Expand All @@ -47,14 +47,14 @@ def _power_iteration(mat: numpy.matrix, initial: numpy.ndarray) -> numpy.ndarray


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

Params
------
mat: numpy.matrix
mat: numpy.array
The matrix to use for multiplication iteration
initial: numpy.array, None
The initial state. Will be set to numpy.array([1, 1, ...]) if None
Expand All @@ -71,7 +71,7 @@ def principal_eigenvector(
Eigenvalue corresonding to the returned eigenvector
"""

mat_ = numpy.matrix(mat)
mat_ = numpy.array(mat)
size = mat_.shape[0]
initial = numpy.ones(size)

Expand All @@ -86,7 +86,7 @@ def principal_eigenvector(
break
last = vector
# Compute the eigenvalue (Rayleigh quotient)
eigenvalue = numpy.dot(numpy.dot(mat_, vector), vector) / numpy.dot(vector, vector)
eigenvalue = ((mat_ @ vector) @ vector) / (vector @ vector)
# Liberate the eigenvalue from numpy
eigenvalue = float(eigenvalue)
return vector, eigenvalue
4 changes: 2 additions & 2 deletions axelrod/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ def cycle(length, directed=False):
-------
a Graph object for the cycle
"""
edges = [(i, i+1) for i in range(length-1)]
edges = [(i, i + 1) for i in range(length - 1)]
edges.append((length - 1, 0))
return Graph(edges=edges, directed=directed)

Expand All @@ -136,7 +136,7 @@ def complete_graph(size, loops=True):
-------
a Graph object for the complete graph
"""
edges = [(i, j) for i in range(size) for j in range(i+1, size)]
edges = [(i, j) for i in range(size) for j in range(i + 1, size)]
graph = Graph(edges=edges, directed=False)

if loops:
Expand Down
4 changes: 1 addition & 3 deletions axelrod/moran.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,7 @@ 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))))

def set_players(self) -> None:
"""Copy the initial players into the first population."""
Expand Down
3 changes: 1 addition & 2 deletions axelrod/strategies/human.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,7 @@ def validate(self, document) -> None:
text = document.text

if text and text.upper() not in ["C", "D"]:
raise ValidationError(message="Action must be C or D",
cursor_position=0)
raise ValidationError(message="Action must be C or D", cursor_position=0)


class Human(Player):
Expand Down
14 changes: 8 additions & 6 deletions axelrod/tests/unit/test_eigen.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,26 +16,28 @@ def test_identity_matrices(self):
assert_array_almost_equal(evector, _normalise(numpy.ones(size)))

def test_2x2_matrix(self):
mat = [[2, 1], [1, 2]]
mat = numpy.array([[2, 1], [1, 2]])
evector, evalue = principal_eigenvector(mat)
self.assertAlmostEqual(evalue, 3)
assert_array_almost_equal(evector, numpy.dot(mat, evector) / evalue)
assert_array_almost_equal(evector, _normalise([1, 1]))
assert_array_almost_equal(evector, _normalise(numpy.array([1, 1])))

def test_3x3_matrix(self):
mat = [[1, 2, 0], [-2, 1, 2], [1, 3, 1]]
mat = numpy.array([[1, 2, 0], [-2, 1, 2], [1, 3, 1]])
evector, evalue = principal_eigenvector(
mat, maximum_iterations=None, max_error=1e-10
)
self.assertAlmostEqual(evalue, 3)
assert_array_almost_equal(evector, numpy.dot(mat, evector) / evalue)
assert_array_almost_equal(evector, _normalise([0.5, 0.5, 1]))
assert_array_almost_equal(evector, _normalise(numpy.array([0.5, 0.5, 1])))

def test_4x4_matrix(self):
mat = [[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]]
mat = numpy.array([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
evector, evalue = principal_eigenvector(
mat, maximum_iterations=None, max_error=1e-10
)
self.assertAlmostEqual(evalue, 3, places=3)
assert_array_almost_equal(evector, numpy.dot(mat, evector) / evalue)
assert_array_almost_equal(evector, _normalise([0, 0, 0, 1]), decimal=4)
assert_array_almost_equal(
evector, _normalise(numpy.array([0, 0, 0, 1])), decimal=4
)
7 changes: 2 additions & 5 deletions axelrod/tests/unit/test_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@


class TestGraph(unittest.TestCase):

def assert_out_mapping(self, g, expected_out_mapping):
self.assertDictEqual(g.out_mapping, expected_out_mapping)
for node, out_dict in expected_out_mapping.items():
Expand Down Expand Up @@ -97,7 +96,6 @@ def test_add_loops_with_existing_loop_and_using_strings(self):


class TestCycle(unittest.TestCase):

def test_length_1_directed(self):
g = graph.cycle(1, directed=True)
self.assertEqual(g.vertices, [0])
Expand All @@ -124,7 +122,7 @@ def test_length_3_directed(self):
g = graph.cycle(3, directed=True)
self.assertEqual(g.vertices, [0, 1, 2])
self.assertEqual(g.edges, [(0, 1), (1, 2), (2, 0)])

def test_length_3_undirected(self):
g = graph.cycle(3, directed=False)
edges = [(0, 1), (1, 0), (1, 2), (2, 1), (2, 0), (0, 2)]
Expand Down Expand Up @@ -156,7 +154,6 @@ def test_length_4_undirected(self):


class TestComplete(unittest.TestCase):

def test_size_2(self):
g = graph.complete_graph(2, loops=False)
self.assertEqual(g.vertices, [0, 1])
Expand Down Expand Up @@ -209,7 +206,7 @@ def test_size_2_with_loops(self):
self.assertEqual(g.vertices, [0, 1])
self.assertEqual(g.edges, [(0, 1), (1, 0), (0, 0), (1, 1)])
self.assertEqual(g.directed, False)

def test_size_3_with_loops(self):
g = graph.complete_graph(3, loops=True)
self.assertEqual(g.vertices, [0, 1, 2])
Expand Down
Loading