Skip to content

Commit f7244e6

Browse files
Merge pull request #1307 from gaffney2010/file-stuff
Create function to handle relative paths
2 parents ecad2a1 + 25514fc commit f7244e6

File tree

10 files changed

+95
-28
lines changed

10 files changed

+95
-28
lines changed

axelrod/load_data_.py

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,26 @@
1-
from typing import Dict, List, Tuple
1+
import pathlib
2+
from typing import Dict, List, Text, Tuple
23

34
import pkg_resources
45

56

7+
def axl_filename(path: pathlib.Path) -> pathlib.Path:
8+
"""Given a path under Axelrod/, return absolute filepath.
9+
10+
Parameters
11+
----------
12+
axl_path
13+
A pathlib.Path object with the relative directory under Axelrod/
14+
15+
Returns
16+
-------
17+
A pathlib.Path object with the absolute directory.
18+
"""
19+
# We go up a dir because this code is located in Axelrod/axelrod.
20+
axl_path = pathlib.Path(__file__).resolve().parent.parent
21+
return axl_path / path
22+
23+
624
def load_file(filename: str, directory: str) -> List[List[str]]:
725
"""Loads a data file stored in the Axelrod library's data subdirectory,
826
likely for parameters for a strategy."""

axelrod/plot.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,12 @@
44
import matplotlib
55
import matplotlib.pyplot as plt
66
import matplotlib.transforms as transforms
7+
import pathlib
78
import tqdm
89
from numpy import arange, median, nan_to_num
910

1011
from .result_set import ResultSet
12+
from .load_data_ import axl_filename
1113

1214
titleType = List[str]
1315
namesType = List[str]
@@ -323,7 +325,8 @@ def save_all_plots(
323325

324326
for method, name in plots:
325327
f = getattr(self, method)(title="{} - {}".format(title_prefix, name))
326-
f.savefig("{}_{}.{}".format(prefix, method, filetype))
328+
path = pathlib.Path("{}_{}.{}".format(prefix, method, filetype))
329+
f.savefig(axl_filename(path))
327330
plt.close(f)
328331

329332
if progress_bar:

axelrod/tests/integration/test_tournament.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import unittest
22

33
import filecmp
4+
import pathlib
45

56
import axelrod as axl
7+
from axelrod.load_data_ import axl_filename
68
from axelrod.strategy_transformers import FinalTransformer
79
from axelrod.tests.property import tournaments
810

@@ -48,7 +50,8 @@ def setUpClass(cls):
4850
def test_big_tournaments(self, tournament):
4951
"""A test to check that tournament runs with a sample of non-cheating
5052
strategies."""
51-
filename = "test_outputs/test_tournament.csv"
53+
path = pathlib.Path("test_outputs/test_tournament.csv")
54+
filename = axl_filename(path)
5255
self.assertIsNone(
5356
tournament.play(progress_bar=False, filename=filename, build_results=False)
5457
)
@@ -93,7 +96,8 @@ def test_repeat_tournament_deterministic(self):
9396
turns=2,
9497
repetitions=2,
9598
)
96-
files.append("test_outputs/stochastic_tournament_{}.csv".format(_))
99+
path = pathlib.Path("test_outputs/stochastic_tournament_{}.csv".format(_))
100+
files.append(axl_filename(path))
97101
tournament.play(progress_bar=False, filename=files[-1], build_results=False)
98102
self.assertTrue(filecmp.cmp(files[0], files[1]))
99103

@@ -116,7 +120,8 @@ def test_repeat_tournament_stochastic(self):
116120
turns=2,
117121
repetitions=2,
118122
)
119-
files.append("test_outputs/stochastic_tournament_{}.csv".format(_))
123+
path = pathlib.Path("test_outputs/stochastic_tournament_{}.csv".format(_))
124+
files.append(axl_filename(path))
120125
tournament.play(progress_bar=False, filename=files[-1], build_results=False)
121126
self.assertTrue(filecmp.cmp(files[0], files[1]))
122127

axelrod/tests/unit/test_deterministic_cache.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
import unittest
22
import os
3+
import pathlib
34
import pickle
45

56
import axelrod as axl
7+
from axelrod.load_data_ import axl_filename
68

79
C, D = axl.Action.C, axl.Action.D
810

@@ -12,8 +14,10 @@ class TestDeterministicCache(unittest.TestCase):
1214
def setUpClass(cls):
1315
cls.test_key = (axl.TitForTat(), axl.Defector())
1416
cls.test_value = [(C, D), (D, D), (D, D)]
15-
cls.test_save_file = "test_cache_save.txt"
16-
cls.test_load_file = "test_cache_load.txt"
17+
save_path = pathlib.Path("test_outputs/test_cache_save.txt")
18+
cls.test_save_file = axl_filename(save_path)
19+
load_path = pathlib.Path("test_outputs/test_cache_load.txt")
20+
cls.test_load_file = axl_filename(load_path)
1721
test_data_to_pickle = {("Tit For Tat", "Defector"): [(C, D), (D, D), (D, D)]}
1822
cls.test_pickle = pickle.dumps(test_data_to_pickle)
1923

@@ -92,7 +96,8 @@ def test_load(self):
9296
self.assertEqual(self.cache[self.test_key], self.test_value)
9397

9498
def test_load_error_for_inccorect_format(self):
95-
filename = "test_outputs/test.cache"
99+
path = pathlib.Path("test_outputs/test.cache")
100+
filename = axl_filename(path)
96101
with open(filename, "wb") as io:
97102
pickle.dump(range(5), io)
98103

axelrod/tests/unit/test_fingerprint.py

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22
from unittest.mock import patch
33

44
import os
5-
65
from tempfile import mkstemp
7-
86
import matplotlib.pyplot
9-
107
import numpy as np
8+
import pathlib
119

1210
import axelrod as axl
1311
from axelrod.fingerprint import AshlockFingerprint, Point, TransitiveFingerprint
12+
from axelrod.load_data_ import axl_filename
1413
from axelrod.strategy_transformers import DualTransformer, JossAnnTransformer
1514
from axelrod.tests.property import strategy_lists
1615

@@ -200,7 +199,8 @@ def test_temp_file_creation(self):
200199

201200
RecordedMksTemp.reset_record()
202201
af = AshlockFingerprint(axl.TitForTat)
203-
filename = "test_outputs/test_fingerprint.csv"
202+
path = pathlib.Path("test_outputs/test_fingerprint.csv")
203+
filename = axl_filename(path)
204204

205205
self.assertEqual(RecordedMksTemp.record, [])
206206

@@ -216,7 +216,8 @@ def test_temp_file_creation(self):
216216
self.assertFalse(os.path.isfile(filename))
217217

218218
def test_fingerprint_with_filename(self):
219-
filename = "test_outputs/test_fingerprint.csv"
219+
path = pathlib.Path("test_outputs/test_fingerprint.csv")
220+
filename = axl_filename(path)
220221
af = AshlockFingerprint(axl.TitForTat)
221222
af.fingerprint(
222223
turns=1, repetitions=1, step=0.5, progress_bar=False, filename=filename
@@ -430,7 +431,8 @@ def test_init_with_not_default_number(self):
430431
)
431432

432433
def test_fingerprint_with_filename(self):
433-
filename = "test_outputs/test_fingerprint.csv"
434+
path = pathlib.Path("test_outputs/test_fingerprint.csv")
435+
filename = axl_filename(path)
434436
strategy = axl.TitForTat()
435437
tf = TransitiveFingerprint(strategy)
436438
tf.fingerprint(turns=1, repetitions=1, progress_bar=False, filename=filename)
@@ -441,8 +443,11 @@ def test_fingerprint_with_filename(self):
441443
def test_serial_fingerprint(self):
442444
strategy = axl.TitForTat()
443445
tf = TransitiveFingerprint(strategy)
446+
path = pathlib.Path("test_outputs/test_fingerprint.csv")
444447
tf.fingerprint(
445-
repetitions=1, progress_bar=False, filename="test_outputs/tran_fin.csv"
448+
repetitions=1,
449+
progress_bar=False,
450+
filename=axl_filename(path),
446451
)
447452
self.assertEqual(tf.data.shape, (50, 50))
448453

@@ -455,7 +460,8 @@ def test_parallel_fingerprint(self):
455460

456461
def test_analyse_cooperation_ratio(self):
457462
tf = TransitiveFingerprint(axl.TitForTat)
458-
filename = "test_outputs/test_fingerprint.csv"
463+
path = pathlib.Path("test_outputs/test_fingerprint.csv")
464+
filename = axl_filename(path)
459465
with open(filename, "w") as f:
460466
f.write(
461467
"""Interaction index,Player index,Opponent index,Repetition,Player name,Opponent name,Actions

axelrod/tests/unit/test_load_data.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import os
2+
import pathlib
3+
import unittest
4+
5+
from axelrod.load_data_ import axl_filename
6+
7+
8+
class TestLoadData(unittest.TestCase):
9+
def test_axl_filename(self):
10+
path = pathlib.Path("axelrod/strategies/titfortat.py")
11+
actual_fn = axl_filename(path)
12+
13+
# First go from "unit" up to "tests", then up to "axelrod"
14+
dirname = os.path.dirname(__file__)
15+
expected_fn = os.path.join(dirname, "../../strategies/titfortat.py")
16+
17+
self.assertTrue(os.path.samefile(actual_fn, expected_fn))

axelrod/tests/unit/test_plot.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,21 @@
11
import unittest
22

33
import tempfile
4-
54
import matplotlib
65
import matplotlib.pyplot as plt
6+
import pathlib
77

88
from numpy import mean
99

1010
import axelrod as axl
11+
from axelrod.load_data_ import axl_filename
1112

1213

1314
class TestPlot(unittest.TestCase):
1415
@classmethod
1516
def setUpClass(cls):
16-
cls.filename = "test_outputs/test_results.csv"
17+
path = pathlib.Path("test_outputs/test_results.csv")
18+
cls.filename = axl_filename(path)
1719

1820
cls.players = [axl.Alternator(), axl.TitForTat(), axl.Defector()]
1921
cls.repetitions = 3

axelrod/tests/unit/test_resultset.py

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
import pandas as pd
55
from dask.dataframe.core import DataFrame
66
from numpy import mean, nanmedian, std
7+
import pathlib
78

89
import axelrod as axl
10+
from axelrod.load_data_ import axl_filename
911
from axelrod.result_set import create_counter_dict
1012
from axelrod.tests.property import prob_end_tournaments, tournaments
1113

@@ -18,7 +20,8 @@ class TestResultSet(unittest.TestCase):
1820
@classmethod
1921
def setUpClass(cls):
2022

21-
cls.filename = "test_outputs/test_results.csv"
23+
path = pathlib.Path("test_outputs/test_results.csv")
24+
cls.filename = str(axl_filename(path))
2225

2326
cls.players = [axl.Alternator(), axl.TitForTat(), axl.Defector()]
2427
cls.repetitions = 3
@@ -192,7 +195,7 @@ def test_init(self):
192195
def _clear_matrix(self, matrix):
193196
for i, row in enumerate(matrix):
194197
for j, _ in enumerate(row):
195-
matrix[i][j] = 0
198+
matrix[i][j] = 0
196199

197200
def test_ne_vectors(self):
198201
rs_1 = axl.ResultSet(self.filename, self.players, self.repetitions)
@@ -676,7 +679,8 @@ class TestResultSetSpatialStructure(TestResultSet):
676679
@classmethod
677680
def setUpClass(cls):
678681

679-
cls.filename = "test_outputs/test_results_spatial.csv"
682+
path = pathlib.Path("test_outputs/test_results_spatial.csv")
683+
cls.filename = str(axl_filename(path))
680684
cls.players = [axl.Alternator(), axl.TitForTat(), axl.Defector()]
681685
cls.turns = 5
682686
cls.edges = [(0, 1), (0, 2)]
@@ -856,7 +860,8 @@ class TestResultSetSpatialStructureTwo(TestResultSetSpatialStructure):
856860
@classmethod
857861
def setUpClass(cls):
858862

859-
cls.filename = "test_outputs/test_results_spatial_two.csv"
863+
path = pathlib.Path("test_outputs/test_results_spatial_two.csv")
864+
cls.filename = str(axl_filename(path))
860865
cls.players = [
861866
axl.Alternator(),
862867
axl.TitForTat(),
@@ -1057,7 +1062,8 @@ class TestResultSetSpatialStructureThree(TestResultSetSpatialStructure):
10571062
@classmethod
10581063
def setUpClass(cls):
10591064

1060-
cls.filename = "test_outputs/test_results_spatial_three.csv"
1065+
path = pathlib.Path("test_outputs/test_results_spatial_three.csv")
1066+
cls.filename = str(axl_filename(path))
10611067
cls.players = [
10621068
axl.Alternator(),
10631069
axl.TitForTat(),

axelrod/tests/unit/test_tournament.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,12 @@
55
import io
66
import logging
77
import os
8+
import pathlib
89
import pickle
910
import warnings
1011
from multiprocessing import Queue, cpu_count
12+
13+
from axelrod.load_data_ import axl_filename
1114
import numpy as np
1215
import pandas as pd
1316
from tqdm import tqdm
@@ -86,7 +89,8 @@ def setUpClass(cls):
8689
[200, 200, 1, 200, 200],
8790
]
8891

89-
cls.filename = "test_outputs/test_tournament.csv"
92+
path = pathlib.Path("test_outputs/test_tournament.csv")
93+
cls.filename = axl_filename(path)
9094

9195
def setUp(self):
9296
self.test_tournament = axl.Tournament(
@@ -726,7 +730,8 @@ def test_write_to_csv_with_results(self):
726730
)
727731
tournament.play(filename=self.filename, progress_bar=False)
728732
df = pd.read_csv(self.filename)
729-
expected_df = pd.read_csv("test_outputs/expected_test_tournament.csv")
733+
path = pathlib.Path("test_outputs/expected_test_tournament.csv")
734+
expected_df = pd.read_csv(axl_filename(path))
730735
self.assertTrue(df.equals(expected_df))
731736

732737
def test_write_to_csv_without_results(self):
@@ -739,9 +744,8 @@ def test_write_to_csv_without_results(self):
739744
)
740745
tournament.play(filename=self.filename, progress_bar=False, build_results=False)
741746
df = pd.read_csv(self.filename)
742-
expected_df = pd.read_csv(
743-
"test_outputs/expected_test_tournament_no_results.csv"
744-
)
747+
path = pathlib.Path("test_outputs/expected_test_tournament_no_results.csv")
748+
expected_df = pd.read_csv(axl_filename(path))
745749
self.assertTrue(df.equals(expected_df))
746750

747751

requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ hypothesis==3.2
55
matplotlib>=2.0.0
66
numpy>=1.9.2
77
pandas>=0.18.1
8+
pathlib>=1.0.1
89
prompt-toolkit>=1.0.7
910
pyyaml>=3.01
1011
scipy>=0.19.0

0 commit comments

Comments
 (0)