Skip to content

Commit 4765acd

Browse files
authored
Merge pull request #1218 from Axelrod-Python/fix-numpy-depreciation
Fix numpy depreciation: `np.matrix -> np.array`
2 parents f32e14b + 683194c commit 4765acd

File tree

12 files changed

+217
-196
lines changed

12 files changed

+217
-196
lines changed

.prepare-commit-msg.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -30,18 +30,20 @@
3030
# e.g. for a branch named 'issue-123', the commit message will start with
3131
# '[#123]'
3232
# If you wish to use a diferent prefix on branch names, change it here.
33-
issue_prefix = 'issue-'
33+
issue_prefix = "issue-"
3434

3535
commit_msg_filepath = sys.argv[1]
36-
branch = check_output(
37-
['git', 'symbolic-ref', '--short', 'HEAD']
38-
).strip().decode(encoding='UTF-8')
36+
branch = (
37+
check_output(["git", "symbolic-ref", "--short", "HEAD"])
38+
.strip()
39+
.decode(encoding="UTF-8")
40+
)
3941

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

44-
with open(commit_msg_filepath, 'r+') as f:
46+
with open(commit_msg_filepath, "r+") as f:
4547
content = f.read()
4648
f.seek(0, 0)
4749
f.write("[#%s] %s" % (issue_number, content))

axelrod/eigen.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,24 +13,24 @@
1313
def _normalise(nvec: numpy.ndarray) -> numpy.ndarray:
1414
"""Normalises the given numpy array."""
1515
with numpy.errstate(invalid="ignore"):
16-
result = nvec / numpy.sqrt(numpy.dot(nvec, nvec))
16+
result = nvec / numpy.sqrt((nvec @ nvec))
1717
return result
1818

1919

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

2626

27-
def _power_iteration(mat: numpy.matrix, initial: numpy.ndarray) -> numpy.ndarray:
27+
def _power_iteration(mat: numpy.array, initial: numpy.ndarray) -> numpy.ndarray:
2828
"""
2929
Generator of successive approximations.
3030
3131
Params
3232
------
33-
mat: numpy.matrix
33+
mat: numpy.array
3434
The matrix to use for multiplication iteration
3535
initial: numpy.array, None
3636
The initial state. Will be set to numpy.array([1, 1, ...]) if None
@@ -47,14 +47,14 @@ def _power_iteration(mat: numpy.matrix, initial: numpy.ndarray) -> numpy.ndarray
4747

4848

4949
def principal_eigenvector(
50-
mat: numpy.matrix, maximum_iterations=1000, max_error=1e-3
50+
mat: numpy.array, maximum_iterations=1000, max_error=1e-3
5151
) -> Tuple[numpy.ndarray, float]:
5252
"""
5353
Computes the (normalised) principal eigenvector of the given matrix.
5454
5555
Params
5656
------
57-
mat: numpy.matrix
57+
mat: numpy.array
5858
The matrix to use for multiplication iteration
5959
initial: numpy.array, None
6060
The initial state. Will be set to numpy.array([1, 1, ...]) if None
@@ -71,7 +71,7 @@ def principal_eigenvector(
7171
Eigenvalue corresonding to the returned eigenvector
7272
"""
7373

74-
mat_ = numpy.matrix(mat)
74+
mat_ = numpy.array(mat)
7575
size = mat_.shape[0]
7676
initial = numpy.ones(size)
7777

@@ -86,7 +86,7 @@ def principal_eigenvector(
8686
break
8787
last = vector
8888
# Compute the eigenvalue (Rayleigh quotient)
89-
eigenvalue = numpy.dot(numpy.dot(mat_, vector), vector) / numpy.dot(vector, vector)
89+
eigenvalue = ((mat_ @ vector) @ vector) / (vector @ vector)
9090
# Liberate the eigenvalue from numpy
9191
eigenvalue = float(eigenvalue)
9292
return vector, eigenvalue

axelrod/graph.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def cycle(length, directed=False):
115115
-------
116116
a Graph object for the cycle
117117
"""
118-
edges = [(i, i+1) for i in range(length-1)]
118+
edges = [(i, i + 1) for i in range(length - 1)]
119119
edges.append((length - 1, 0))
120120
return Graph(edges=edges, directed=directed)
121121

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

142142
if loops:

axelrod/moran.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,7 @@ def __init__(
156156
self.fitness_transformation = fitness_transformation
157157
# Map players to graph vertices
158158
self.locations = sorted(interaction_graph.vertices)
159-
self.index = dict(
160-
zip(sorted(interaction_graph.vertices), range(len(players)))
161-
)
159+
self.index = dict(zip(sorted(interaction_graph.vertices), range(len(players))))
162160

163161
def set_players(self) -> None:
164162
"""Copy the initial players into the first population."""

axelrod/strategies/human.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,7 @@ def validate(self, document) -> None:
2222
text = document.text
2323

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

2827

2928
class Human(Player):

axelrod/tests/unit/test_eigen.py

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,26 +16,28 @@ def test_identity_matrices(self):
1616
assert_array_almost_equal(evector, _normalise(numpy.ones(size)))
1717

1818
def test_2x2_matrix(self):
19-
mat = [[2, 1], [1, 2]]
19+
mat = numpy.array([[2, 1], [1, 2]])
2020
evector, evalue = principal_eigenvector(mat)
2121
self.assertAlmostEqual(evalue, 3)
2222
assert_array_almost_equal(evector, numpy.dot(mat, evector) / evalue)
23-
assert_array_almost_equal(evector, _normalise([1, 1]))
23+
assert_array_almost_equal(evector, _normalise(numpy.array([1, 1])))
2424

2525
def test_3x3_matrix(self):
26-
mat = [[1, 2, 0], [-2, 1, 2], [1, 3, 1]]
26+
mat = numpy.array([[1, 2, 0], [-2, 1, 2], [1, 3, 1]])
2727
evector, evalue = principal_eigenvector(
2828
mat, maximum_iterations=None, max_error=1e-10
2929
)
3030
self.assertAlmostEqual(evalue, 3)
3131
assert_array_almost_equal(evector, numpy.dot(mat, evector) / evalue)
32-
assert_array_almost_equal(evector, _normalise([0.5, 0.5, 1]))
32+
assert_array_almost_equal(evector, _normalise(numpy.array([0.5, 0.5, 1])))
3333

3434
def test_4x4_matrix(self):
35-
mat = [[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]]
35+
mat = numpy.array([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
3636
evector, evalue = principal_eigenvector(
3737
mat, maximum_iterations=None, max_error=1e-10
3838
)
3939
self.assertAlmostEqual(evalue, 3, places=3)
4040
assert_array_almost_equal(evector, numpy.dot(mat, evector) / evalue)
41-
assert_array_almost_equal(evector, _normalise([0, 0, 0, 1]), decimal=4)
41+
assert_array_almost_equal(
42+
evector, _normalise(numpy.array([0, 0, 0, 1])), decimal=4
43+
)

axelrod/tests/unit/test_graph.py

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66

77
class TestGraph(unittest.TestCase):
8-
98
def assert_out_mapping(self, g, expected_out_mapping):
109
self.assertDictEqual(g.out_mapping, expected_out_mapping)
1110
for node, out_dict in expected_out_mapping.items():
@@ -97,7 +96,6 @@ def test_add_loops_with_existing_loop_and_using_strings(self):
9796

9897

9998
class TestCycle(unittest.TestCase):
100-
10199
def test_length_1_directed(self):
102100
g = graph.cycle(1, directed=True)
103101
self.assertEqual(g.vertices, [0])
@@ -124,7 +122,7 @@ def test_length_3_directed(self):
124122
g = graph.cycle(3, directed=True)
125123
self.assertEqual(g.vertices, [0, 1, 2])
126124
self.assertEqual(g.edges, [(0, 1), (1, 2), (2, 0)])
127-
125+
128126
def test_length_3_undirected(self):
129127
g = graph.cycle(3, directed=False)
130128
edges = [(0, 1), (1, 0), (1, 2), (2, 1), (2, 0), (0, 2)]
@@ -156,7 +154,6 @@ def test_length_4_undirected(self):
156154

157155

158156
class TestComplete(unittest.TestCase):
159-
160157
def test_size_2(self):
161158
g = graph.complete_graph(2, loops=False)
162159
self.assertEqual(g.vertices, [0, 1])
@@ -209,7 +206,7 @@ def test_size_2_with_loops(self):
209206
self.assertEqual(g.vertices, [0, 1])
210207
self.assertEqual(g.edges, [(0, 1), (1, 0), (0, 0), (1, 1)])
211208
self.assertEqual(g.directed, False)
212-
209+
213210
def test_size_3_with_loops(self):
214211
g = graph.complete_graph(3, loops=True)
215212
self.assertEqual(g.vertices, [0, 1, 2])

0 commit comments

Comments
 (0)