From deab302214ed40265ff36f50d3a935ff620fe3f1 Mon Sep 17 00:00:00 2001 From: "T.J. Gaffney" Date: Tue, 31 Mar 2020 04:23:44 -0700 Subject: [PATCH 1/4] Create and use axl_filename --- axelrod/load_data_.py | 13 ++++++++++++- axelrod/plot.py | 3 ++- axelrod/tests/integration/test_tournament.py | 7 ++++--- axelrod/tests/unit/test_deterministic_cache.py | 7 ++++--- axelrod/tests/unit/test_fingerprint.py | 13 ++++++++----- axelrod/tests/unit/test_plot.py | 3 ++- axelrod/tests/unit/test_resultset.py | 5 +++-- axelrod/tests/unit/test_tournament.py | 9 ++++++--- 8 files changed, 41 insertions(+), 19 deletions(-) diff --git a/axelrod/load_data_.py b/axelrod/load_data_.py index 37d6ae677..812c0a208 100644 --- a/axelrod/load_data_.py +++ b/axelrod/load_data_.py @@ -1,8 +1,19 @@ -from typing import Dict, List, Tuple +from typing import Dict, List, Text, Tuple +import os import pkg_resources +def axl_filename(axl_path: Text) -> Text: + """Get the path to Axelrod/ from the working directory.""" + # Working directory + dirname = os.path.dirname(__file__) + + # We go up a dir because this code is located in Axelrod/axelrod and + # axl_path is from the top-level Axelrod dir. + return os.path.join(dirname, "..", axl_path) + + def load_file(filename: str, directory: str) -> List[List[str]]: """Loads a data file stored in the Axelrod library's data subdirectory, likely for parameters for a strategy.""" diff --git a/axelrod/plot.py b/axelrod/plot.py index f2c1bcee1..2349a802f 100644 --- a/axelrod/plot.py +++ b/axelrod/plot.py @@ -8,6 +8,7 @@ from numpy import arange, median, nan_to_num from .result_set import ResultSet +from .load_data_ import axl_filename titleType = List[str] namesType = List[str] @@ -323,7 +324,7 @@ def save_all_plots( for method, name in plots: f = getattr(self, method)(title="{} - {}".format(title_prefix, name)) - f.savefig("{}_{}.{}".format(prefix, method, filetype)) + f.savefig(axl_filename("{}_{}.{}".format(prefix, method, filetype))) plt.close(f) if progress_bar: diff --git a/axelrod/tests/integration/test_tournament.py b/axelrod/tests/integration/test_tournament.py index 28d505416..c03fa818f 100644 --- a/axelrod/tests/integration/test_tournament.py +++ b/axelrod/tests/integration/test_tournament.py @@ -4,6 +4,7 @@ from hypothesis import given, settings import axelrod +from axelrod.load_data_ import axl_filename from axelrod.strategy_transformers import FinalTransformer from axelrod.tests.property import tournaments @@ -45,7 +46,7 @@ def setUpClass(cls): def test_big_tournaments(self, tournament): """A test to check that tournament runs with a sample of non-cheating strategies.""" - filename = "test_outputs/test_tournament.csv" + filename = axl_filename("test_outputs/test_tournament.csv") self.assertIsNone( tournament.play(progress_bar=False, filename=filename, build_results=False) ) @@ -90,7 +91,7 @@ def test_repeat_tournament_deterministic(self): turns=2, repetitions=2, ) - files.append("test_outputs/stochastic_tournament_{}.csv".format(_)) + files.append(axl_filename("test_outputs/stochastic_tournament_{}.csv".format(_))) tournament.play(progress_bar=False, filename=files[-1], build_results=False) self.assertTrue(filecmp.cmp(files[0], files[1])) @@ -113,7 +114,7 @@ def test_repeat_tournament_stochastic(self): turns=2, repetitions=2, ) - files.append("test_outputs/stochastic_tournament_{}.csv".format(_)) + files.append(axl_filename("test_outputs/stochastic_tournament_{}.csv".format(_))) tournament.play(progress_bar=False, filename=files[-1], build_results=False) self.assertTrue(filecmp.cmp(files[0], files[1])) diff --git a/axelrod/tests/unit/test_deterministic_cache.py b/axelrod/tests/unit/test_deterministic_cache.py index 8728787aa..4e2f46e41 100644 --- a/axelrod/tests/unit/test_deterministic_cache.py +++ b/axelrod/tests/unit/test_deterministic_cache.py @@ -3,6 +3,7 @@ import unittest from axelrod import Action, Defector, DeterministicCache, Random, TitForTat +from axelrod.load_data_ import axl_filename C, D = Action.C, Action.D @@ -12,8 +13,8 @@ class TestDeterministicCache(unittest.TestCase): def setUpClass(cls): cls.test_key = (TitForTat(), Defector()) cls.test_value = [(C, D), (D, D), (D, D)] - cls.test_save_file = "test_cache_save.txt" - cls.test_load_file = "test_cache_load.txt" + cls.test_save_file = axl_filename("test_outputs/test_cache_save.txt") + cls.test_load_file = axl_filename("test_outputs/test_cache_load.txt") test_data_to_pickle = {("Tit For Tat", "Defector"): [(C, D), (D, D), (D, D)]} cls.test_pickle = pickle.dumps(test_data_to_pickle) @@ -92,7 +93,7 @@ def test_load(self): self.assertEqual(self.cache[self.test_key], self.test_value) def test_load_error_for_inccorect_format(self): - filename = "test_outputs/test.cache" + filename = axl_filename("test_outputs/test.cache") with open(filename, "wb") as io: pickle.dump(range(5), io) diff --git a/axelrod/tests/unit/test_fingerprint.py b/axelrod/tests/unit/test_fingerprint.py index bab8b5055..05cc287a4 100644 --- a/axelrod/tests/unit/test_fingerprint.py +++ b/axelrod/tests/unit/test_fingerprint.py @@ -9,6 +9,7 @@ import axelrod as axl from axelrod.fingerprint import AshlockFingerprint, Point, TransitiveFingerprint +from axelrod.load_data_ import axl_filename from axelrod.strategy_transformers import DualTransformer, JossAnnTransformer from axelrod.tests.property import strategy_lists @@ -195,7 +196,7 @@ def test_temp_file_creation(self): RecordedMksTemp.reset_record() af = AshlockFingerprint(axl.TitForTat) - filename = "test_outputs/test_fingerprint.csv" + filename = axl_filename("test_outputs/test_fingerprint.csv") self.assertEqual(RecordedMksTemp.record, []) @@ -211,7 +212,7 @@ def test_temp_file_creation(self): self.assertFalse(os.path.isfile(filename)) def test_fingerprint_with_filename(self): - filename = "test_outputs/test_fingerprint.csv" + filename = axl_filename("test_outputs/test_fingerprint.csv") af = AshlockFingerprint(axl.TitForTat) af.fingerprint( turns=1, repetitions=1, step=0.5, progress_bar=False, filename=filename @@ -425,7 +426,7 @@ def test_init_with_not_default_number(self): ) def test_fingerprint_with_filename(self): - filename = "test_outputs/test_fingerprint.csv" + filename = axl_filename("test_outputs/test_fingerprint.csv") strategy = axl.TitForTat() tf = TransitiveFingerprint(strategy) tf.fingerprint(turns=1, repetitions=1, progress_bar=False, filename=filename) @@ -437,7 +438,9 @@ def test_serial_fingerprint(self): strategy = axl.TitForTat() tf = TransitiveFingerprint(strategy) tf.fingerprint( - repetitions=1, progress_bar=False, filename="test_outputs/tran_fin.csv" + repetitions=1, + progress_bar=False, + filename=axl_filename("test_outputs/tran_fin.csv"), ) self.assertEqual(tf.data.shape, (50, 50)) @@ -450,7 +453,7 @@ def test_parallel_fingerprint(self): def test_analyse_cooperation_ratio(self): tf = TransitiveFingerprint(axl.TitForTat) - filename = "test_outputs/test_fingerprint.csv" + filename = axl_filename("test_outputs/test_fingerprint.csv") with open(filename, "w") as f: f.write( """Interaction index,Player index,Opponent index,Repetition,Player name,Opponent name,Actions diff --git a/axelrod/tests/unit/test_plot.py b/axelrod/tests/unit/test_plot.py index ddad0fef7..a48624d0f 100644 --- a/axelrod/tests/unit/test_plot.py +++ b/axelrod/tests/unit/test_plot.py @@ -2,6 +2,7 @@ import unittest import axelrod +from axelrod.load_data_ import axl_filename import matplotlib import matplotlib.pyplot as plt from numpy import mean @@ -10,7 +11,7 @@ class TestPlot(unittest.TestCase): @classmethod def setUpClass(cls): - cls.filename = "test_outputs/test_results.csv" + cls.filename = axl_filename("test_outputs/test_results.csv") cls.players = [axelrod.Alternator(), axelrod.TitForTat(), axelrod.Defector()] cls.repetitions = 3 diff --git a/axelrod/tests/unit/test_resultset.py b/axelrod/tests/unit/test_resultset.py index 9f5586811..37237d8fc 100644 --- a/axelrod/tests/unit/test_resultset.py +++ b/axelrod/tests/unit/test_resultset.py @@ -5,6 +5,7 @@ import axelrod import axelrod.interaction_utils as iu import pandas as pd +from axelrod.load_data_ import axl_filename from axelrod.result_set import create_counter_dict from axelrod.tests.property import prob_end_tournaments, tournaments from numpy import mean, nanmedian, std @@ -19,7 +20,7 @@ class TestResultSet(unittest.TestCase): @classmethod def setUpClass(cls): - cls.filename = "test_outputs/test_results.csv" + cls.filename = axl_filename("test_outputs/test_results.csv") cls.players = [axelrod.Alternator(), axelrod.TitForTat(), axelrod.Defector()] cls.repetitions = 3 @@ -647,7 +648,7 @@ class TestResultSetSpatialStructure(TestResultSet): @classmethod def setUpClass(cls): - cls.filename = "test_outputs/test_results_spatial.csv" + cls.filename = axl_filename("test_outputs/test_results_spatial.csv") cls.players = [axelrod.Alternator(), axelrod.TitForTat(), axelrod.Defector()] cls.turns = 5 cls.edges = [(0, 1), (0, 2)] diff --git a/axelrod/tests/unit/test_tournament.py b/axelrod/tests/unit/test_tournament.py index 27f994f09..c1a096ff6 100644 --- a/axelrod/tests/unit/test_tournament.py +++ b/axelrod/tests/unit/test_tournament.py @@ -12,6 +12,7 @@ from unittest.mock import MagicMock, patch import axelrod +from axelrod.load_data_ import axl_filename import numpy as np import pandas as pd from axelrod.tests.property import ( @@ -88,7 +89,7 @@ def setUpClass(cls): [200, 200, 1, 200, 200], ] - cls.filename = "test_outputs/test_tournament.csv" + cls.filename = axl_filename("test_outputs/test_tournament.csv") def setUp(self): self.test_tournament = axelrod.Tournament( @@ -733,7 +734,9 @@ def test_write_to_csv_with_results(self): ) tournament.play(filename=self.filename, progress_bar=False) df = pd.read_csv(self.filename) - expected_df = pd.read_csv("test_outputs/expected_test_tournament.csv") + expected_df = pd.read_csv( + axl_filename("test_outputs/expected_test_tournament.csv") + ) self.assertTrue(df.equals(expected_df)) def test_write_to_csv_without_results(self): @@ -747,7 +750,7 @@ def test_write_to_csv_without_results(self): tournament.play(filename=self.filename, progress_bar=False, build_results=False) df = pd.read_csv(self.filename) expected_df = pd.read_csv( - "test_outputs/expected_test_tournament_no_results.csv" + axl_filename("test_outputs/expected_test_tournament_no_results.csv") ) self.assertTrue(df.equals(expected_df)) From 21a5a8f9687388e4923668b6facc633cd740df49 Mon Sep 17 00:00:00 2001 From: "T.J. Gaffney" Date: Sat, 4 Apr 2020 12:50:09 -0700 Subject: [PATCH 2/4] Add test_axl_filename --- axelrod/tests/unit/test_load_data.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 axelrod/tests/unit/test_load_data.py diff --git a/axelrod/tests/unit/test_load_data.py b/axelrod/tests/unit/test_load_data.py new file mode 100644 index 000000000..52119f3ec --- /dev/null +++ b/axelrod/tests/unit/test_load_data.py @@ -0,0 +1,15 @@ +import os +import unittest + +from axelrod.load_data_ import axl_filename + + +class TestLoadData(unittest.TestCase): + def test_axl_filename(self): + actual_fn = axl_filename("axelrod/strategies/titfortat.py") + + # First go from "unit" up to "tests", then up to "axelrod" + dirname = os.path.dirname(__file__) + expected_fn = os.path.join(dirname, "../../strategies/titfortat.py") + + self.assertTrue(os.path.samefile(actual_fn, expected_fn)) From f5bad9f8896dbbe697418f611a142df0d538ab4c Mon Sep 17 00:00:00 2001 From: "T.J. Gaffney" Date: Mon, 6 Apr 2020 02:19:41 -0700 Subject: [PATCH 3/4] Update axl_filename to use pathlib and take multiple arguments --- axelrod/load_data_.py | 27 ++++++++++++----- axelrod/tests/integration/test_tournament.py | 30 +++++++++++-------- .../tests/unit/test_deterministic_cache.py | 6 ++-- axelrod/tests/unit/test_fingerprint.py | 8 ++--- axelrod/tests/unit/test_plot.py | 2 +- axelrod/tests/unit/test_resultset.py | 2 +- axelrod/tests/unit/test_tournament.py | 6 ++-- requirements.txt | 1 + 8 files changed, 50 insertions(+), 32 deletions(-) diff --git a/axelrod/load_data_.py b/axelrod/load_data_.py index 812c0a208..26b309127 100644 --- a/axelrod/load_data_.py +++ b/axelrod/load_data_.py @@ -1,17 +1,28 @@ +import pathlib from typing import Dict, List, Text, Tuple -import os import pkg_resources -def axl_filename(axl_path: Text) -> Text: - """Get the path to Axelrod/ from the working directory.""" - # Working directory - dirname = os.path.dirname(__file__) +def axl_filename(*axl_path: Text) -> Text: + """Given a path under Axelrod/, return absolute filepath. - # We go up a dir because this code is located in Axelrod/axelrod and - # axl_path is from the top-level Axelrod dir. - return os.path.join(dirname, "..", axl_path) + Parameters + ---------- + axl_path + Path to file located under top-level Axelrod directory, with file names + separated at "/". For example, to get the path to "Axelrod/xxx/yyy.py" + call this function with axl_filename("xxx", "yyy.py"). + + Returns + ------- + Absolute path to the given path. + """ + # We go up a dir because this code is located in Axelrod/axelrod. + path = pathlib.Path(__file__).resolve().parent.parent + for p in axl_path: + path = path / p + return str(path) def load_file(filename: str, directory: str) -> List[List[str]]: diff --git a/axelrod/tests/integration/test_tournament.py b/axelrod/tests/integration/test_tournament.py index c03fa818f..df986c02b 100644 --- a/axelrod/tests/integration/test_tournament.py +++ b/axelrod/tests/integration/test_tournament.py @@ -33,20 +33,22 @@ def setUpClass(cls): ] cls.expected_outcome.sort() - @given(tournaments( - strategies=axelrod.short_run_time_strategies, - min_size=10, - max_size=30, - min_turns=2, - max_turns=210, - min_repetitions=1, - max_repetitions=4, - )) + @given( + tournaments( + strategies=axelrod.short_run_time_strategies, + min_size=10, + max_size=30, + min_turns=2, + max_turns=210, + min_repetitions=1, + max_repetitions=4, + ) + ) @settings(max_examples=1) def test_big_tournaments(self, tournament): """A test to check that tournament runs with a sample of non-cheating strategies.""" - filename = axl_filename("test_outputs/test_tournament.csv") + filename = axl_filename("test_outputs", "test_tournament.csv") self.assertIsNone( tournament.play(progress_bar=False, filename=filename, build_results=False) ) @@ -91,7 +93,9 @@ def test_repeat_tournament_deterministic(self): turns=2, repetitions=2, ) - files.append(axl_filename("test_outputs/stochastic_tournament_{}.csv".format(_))) + files.append( + axl_filename("test_outputs", "stochastic_tournament_{}.csv".format(_)) + ) tournament.play(progress_bar=False, filename=files[-1], build_results=False) self.assertTrue(filecmp.cmp(files[0], files[1])) @@ -114,7 +118,9 @@ def test_repeat_tournament_stochastic(self): turns=2, repetitions=2, ) - files.append(axl_filename("test_outputs/stochastic_tournament_{}.csv".format(_))) + files.append( + axl_filename("test_outputs", "stochastic_tournament_{}.csv".format(_)) + ) tournament.play(progress_bar=False, filename=files[-1], build_results=False) self.assertTrue(filecmp.cmp(files[0], files[1])) diff --git a/axelrod/tests/unit/test_deterministic_cache.py b/axelrod/tests/unit/test_deterministic_cache.py index 4e2f46e41..8d5d3fcd6 100644 --- a/axelrod/tests/unit/test_deterministic_cache.py +++ b/axelrod/tests/unit/test_deterministic_cache.py @@ -13,8 +13,8 @@ class TestDeterministicCache(unittest.TestCase): def setUpClass(cls): cls.test_key = (TitForTat(), Defector()) cls.test_value = [(C, D), (D, D), (D, D)] - cls.test_save_file = axl_filename("test_outputs/test_cache_save.txt") - cls.test_load_file = axl_filename("test_outputs/test_cache_load.txt") + cls.test_save_file = axl_filename("test_outputs", "test_cache_save.txt") + cls.test_load_file = axl_filename("test_outputs", "test_cache_load.txt") test_data_to_pickle = {("Tit For Tat", "Defector"): [(C, D), (D, D), (D, D)]} cls.test_pickle = pickle.dumps(test_data_to_pickle) @@ -93,7 +93,7 @@ def test_load(self): self.assertEqual(self.cache[self.test_key], self.test_value) def test_load_error_for_inccorect_format(self): - filename = axl_filename("test_outputs/test.cache") + filename = axl_filename("test_outputs", "test.cache") with open(filename, "wb") as io: pickle.dump(range(5), io) diff --git a/axelrod/tests/unit/test_fingerprint.py b/axelrod/tests/unit/test_fingerprint.py index 05cc287a4..c0a225209 100644 --- a/axelrod/tests/unit/test_fingerprint.py +++ b/axelrod/tests/unit/test_fingerprint.py @@ -212,7 +212,7 @@ def test_temp_file_creation(self): self.assertFalse(os.path.isfile(filename)) def test_fingerprint_with_filename(self): - filename = axl_filename("test_outputs/test_fingerprint.csv") + filename = axl_filename("test_outputs", "test_fingerprint.csv") af = AshlockFingerprint(axl.TitForTat) af.fingerprint( turns=1, repetitions=1, step=0.5, progress_bar=False, filename=filename @@ -426,7 +426,7 @@ def test_init_with_not_default_number(self): ) def test_fingerprint_with_filename(self): - filename = axl_filename("test_outputs/test_fingerprint.csv") + filename = axl_filename("test_outputs", "test_fingerprint.csv") strategy = axl.TitForTat() tf = TransitiveFingerprint(strategy) tf.fingerprint(turns=1, repetitions=1, progress_bar=False, filename=filename) @@ -440,7 +440,7 @@ def test_serial_fingerprint(self): tf.fingerprint( repetitions=1, progress_bar=False, - filename=axl_filename("test_outputs/tran_fin.csv"), + filename=axl_filename("test_outputs", "tran_fin.csv"), ) self.assertEqual(tf.data.shape, (50, 50)) @@ -453,7 +453,7 @@ def test_parallel_fingerprint(self): def test_analyse_cooperation_ratio(self): tf = TransitiveFingerprint(axl.TitForTat) - filename = axl_filename("test_outputs/test_fingerprint.csv") + filename = axl_filename("test_outputs", "test_fingerprint.csv") with open(filename, "w") as f: f.write( """Interaction index,Player index,Opponent index,Repetition,Player name,Opponent name,Actions diff --git a/axelrod/tests/unit/test_plot.py b/axelrod/tests/unit/test_plot.py index a48624d0f..52ce0d45e 100644 --- a/axelrod/tests/unit/test_plot.py +++ b/axelrod/tests/unit/test_plot.py @@ -11,7 +11,7 @@ class TestPlot(unittest.TestCase): @classmethod def setUpClass(cls): - cls.filename = axl_filename("test_outputs/test_results.csv") + cls.filename = axl_filename("test_outputs", "test_results.csv") cls.players = [axelrod.Alternator(), axelrod.TitForTat(), axelrod.Defector()] cls.repetitions = 3 diff --git a/axelrod/tests/unit/test_resultset.py b/axelrod/tests/unit/test_resultset.py index 37237d8fc..addd87236 100644 --- a/axelrod/tests/unit/test_resultset.py +++ b/axelrod/tests/unit/test_resultset.py @@ -648,7 +648,7 @@ class TestResultSetSpatialStructure(TestResultSet): @classmethod def setUpClass(cls): - cls.filename = axl_filename("test_outputs/test_results_spatial.csv") + cls.filename = axl_filename("test_outputs", "test_results_spatial.csv") cls.players = [axelrod.Alternator(), axelrod.TitForTat(), axelrod.Defector()] cls.turns = 5 cls.edges = [(0, 1), (0, 2)] diff --git a/axelrod/tests/unit/test_tournament.py b/axelrod/tests/unit/test_tournament.py index c1a096ff6..4f8a1ff51 100644 --- a/axelrod/tests/unit/test_tournament.py +++ b/axelrod/tests/unit/test_tournament.py @@ -89,7 +89,7 @@ def setUpClass(cls): [200, 200, 1, 200, 200], ] - cls.filename = axl_filename("test_outputs/test_tournament.csv") + cls.filename = axl_filename("test_outputs", "test_tournament.csv") def setUp(self): self.test_tournament = axelrod.Tournament( @@ -735,7 +735,7 @@ def test_write_to_csv_with_results(self): tournament.play(filename=self.filename, progress_bar=False) df = pd.read_csv(self.filename) expected_df = pd.read_csv( - axl_filename("test_outputs/expected_test_tournament.csv") + axl_filename("test_outputs", "expected_test_tournament.csv") ) self.assertTrue(df.equals(expected_df)) @@ -750,7 +750,7 @@ def test_write_to_csv_without_results(self): tournament.play(filename=self.filename, progress_bar=False, build_results=False) df = pd.read_csv(self.filename) expected_df = pd.read_csv( - axl_filename("test_outputs/expected_test_tournament_no_results.csv") + axl_filename("test_outputs", "expected_test_tournament_no_results.csv") ) self.assertTrue(df.equals(expected_df)) diff --git a/requirements.txt b/requirements.txt index 5c3b872b2..98c84f82d 100644 --- a/requirements.txt +++ b/requirements.txt @@ -5,6 +5,7 @@ hypothesis==3.2 matplotlib>=2.0.0 numpy>=1.9.2 pandas>=0.18.1 +pathlib>=1.0.1 prompt-toolkit>=1.0.7 scipy>=0.19.0 toolz>=0.8.0 From 25514fcf064949d1b62b3aa1d31e293c78c9f518 Mon Sep 17 00:00:00 2001 From: "T.J. Gaffney" Date: Mon, 6 Apr 2020 04:50:48 -0700 Subject: [PATCH 4/4] Change axl_filename to take a pathlib.Path --- axelrod/load_data_.py | 14 ++++----- axelrod/plot.py | 4 ++- axelrod/tests/integration/test_tournament.py | 14 ++++----- .../tests/unit/test_deterministic_cache.py | 10 +++++-- axelrod/tests/unit/test_fingerprint.py | 19 +++++++----- axelrod/tests/unit/test_load_data.py | 4 ++- axelrod/tests/unit/test_plot.py | 4 ++- axelrod/tests/unit/test_resultset.py | 13 +++++--- axelrod/tests/unit/test_tournament.py | 30 +++++++------------ 9 files changed, 59 insertions(+), 53 deletions(-) diff --git a/axelrod/load_data_.py b/axelrod/load_data_.py index 26b309127..ac29250fd 100644 --- a/axelrod/load_data_.py +++ b/axelrod/load_data_.py @@ -4,25 +4,21 @@ import pkg_resources -def axl_filename(*axl_path: Text) -> Text: +def axl_filename(path: pathlib.Path) -> pathlib.Path: """Given a path under Axelrod/, return absolute filepath. Parameters ---------- axl_path - Path to file located under top-level Axelrod directory, with file names - separated at "/". For example, to get the path to "Axelrod/xxx/yyy.py" - call this function with axl_filename("xxx", "yyy.py"). + A pathlib.Path object with the relative directory under Axelrod/ Returns ------- - Absolute path to the given path. + A pathlib.Path object with the absolute directory. """ # We go up a dir because this code is located in Axelrod/axelrod. - path = pathlib.Path(__file__).resolve().parent.parent - for p in axl_path: - path = path / p - return str(path) + axl_path = pathlib.Path(__file__).resolve().parent.parent + return axl_path / path def load_file(filename: str, directory: str) -> List[List[str]]: diff --git a/axelrod/plot.py b/axelrod/plot.py index 2349a802f..edc596529 100644 --- a/axelrod/plot.py +++ b/axelrod/plot.py @@ -4,6 +4,7 @@ import matplotlib import matplotlib.pyplot as plt import matplotlib.transforms as transforms +import pathlib import tqdm from numpy import arange, median, nan_to_num @@ -324,7 +325,8 @@ def save_all_plots( for method, name in plots: f = getattr(self, method)(title="{} - {}".format(title_prefix, name)) - f.savefig(axl_filename("{}_{}.{}".format(prefix, method, filetype))) + path = pathlib.Path("{}_{}.{}".format(prefix, method, filetype)) + f.savefig(axl_filename(path)) plt.close(f) if progress_bar: diff --git a/axelrod/tests/integration/test_tournament.py b/axelrod/tests/integration/test_tournament.py index b4cb21d92..3e031450e 100644 --- a/axelrod/tests/integration/test_tournament.py +++ b/axelrod/tests/integration/test_tournament.py @@ -1,6 +1,7 @@ import unittest import filecmp +import pathlib import axelrod as axl from axelrod.load_data_ import axl_filename @@ -49,7 +50,8 @@ def setUpClass(cls): def test_big_tournaments(self, tournament): """A test to check that tournament runs with a sample of non-cheating strategies.""" - filename = axl_filename("test_outputs", "test_tournament.csv") + path = pathlib.Path("test_outputs/test_tournament.csv") + filename = axl_filename(path) self.assertIsNone( tournament.play(progress_bar=False, filename=filename, build_results=False) ) @@ -94,9 +96,8 @@ def test_repeat_tournament_deterministic(self): turns=2, repetitions=2, ) - files.append( - axl_filename("test_outputs", "stochastic_tournament_{}.csv".format(_)) - ) + path = pathlib.Path("test_outputs/stochastic_tournament_{}.csv".format(_)) + files.append(axl_filename(path)) tournament.play(progress_bar=False, filename=files[-1], build_results=False) self.assertTrue(filecmp.cmp(files[0], files[1])) @@ -119,9 +120,8 @@ def test_repeat_tournament_stochastic(self): turns=2, repetitions=2, ) - files.append( - axl_filename("test_outputs", "stochastic_tournament_{}.csv".format(_)) - ) + path = pathlib.Path("test_outputs/stochastic_tournament_{}.csv".format(_)) + files.append(axl_filename(path)) tournament.play(progress_bar=False, filename=files[-1], build_results=False) self.assertTrue(filecmp.cmp(files[0], files[1])) diff --git a/axelrod/tests/unit/test_deterministic_cache.py b/axelrod/tests/unit/test_deterministic_cache.py index 3278e1af0..82d11904c 100644 --- a/axelrod/tests/unit/test_deterministic_cache.py +++ b/axelrod/tests/unit/test_deterministic_cache.py @@ -1,5 +1,6 @@ import unittest import os +import pathlib import pickle import axelrod as axl @@ -13,8 +14,10 @@ class TestDeterministicCache(unittest.TestCase): def setUpClass(cls): cls.test_key = (axl.TitForTat(), axl.Defector()) cls.test_value = [(C, D), (D, D), (D, D)] - cls.test_save_file = axl_filename("test_outputs", "test_cache_save.txt") - cls.test_load_file = axl_filename("test_outputs", "test_cache_load.txt") + save_path = pathlib.Path("test_outputs/test_cache_save.txt") + cls.test_save_file = axl_filename(save_path) + load_path = pathlib.Path("test_outputs/test_cache_load.txt") + cls.test_load_file = axl_filename(load_path) test_data_to_pickle = {("Tit For Tat", "Defector"): [(C, D), (D, D), (D, D)]} cls.test_pickle = pickle.dumps(test_data_to_pickle) @@ -93,7 +96,8 @@ def test_load(self): self.assertEqual(self.cache[self.test_key], self.test_value) def test_load_error_for_inccorect_format(self): - filename = axl_filename("test_outputs", "test.cache") + path = pathlib.Path("test_outputs/test.cache") + filename = axl_filename(path) with open(filename, "wb") as io: pickle.dump(range(5), io) diff --git a/axelrod/tests/unit/test_fingerprint.py b/axelrod/tests/unit/test_fingerprint.py index b8f481307..f60a93e7a 100644 --- a/axelrod/tests/unit/test_fingerprint.py +++ b/axelrod/tests/unit/test_fingerprint.py @@ -2,12 +2,10 @@ from unittest.mock import patch import os - from tempfile import mkstemp - import matplotlib.pyplot - import numpy as np +import pathlib import axelrod as axl from axelrod.fingerprint import AshlockFingerprint, Point, TransitiveFingerprint @@ -201,7 +199,8 @@ def test_temp_file_creation(self): RecordedMksTemp.reset_record() af = AshlockFingerprint(axl.TitForTat) - filename = axl_filename("test_outputs/test_fingerprint.csv") + path = pathlib.Path("test_outputs/test_fingerprint.csv") + filename = axl_filename(path) self.assertEqual(RecordedMksTemp.record, []) @@ -217,7 +216,8 @@ def test_temp_file_creation(self): self.assertFalse(os.path.isfile(filename)) def test_fingerprint_with_filename(self): - filename = axl_filename("test_outputs", "test_fingerprint.csv") + path = pathlib.Path("test_outputs/test_fingerprint.csv") + filename = axl_filename(path) af = AshlockFingerprint(axl.TitForTat) af.fingerprint( turns=1, repetitions=1, step=0.5, progress_bar=False, filename=filename @@ -431,7 +431,8 @@ def test_init_with_not_default_number(self): ) def test_fingerprint_with_filename(self): - filename = axl_filename("test_outputs", "test_fingerprint.csv") + path = pathlib.Path("test_outputs/test_fingerprint.csv") + filename = axl_filename(path) strategy = axl.TitForTat() tf = TransitiveFingerprint(strategy) tf.fingerprint(turns=1, repetitions=1, progress_bar=False, filename=filename) @@ -442,10 +443,11 @@ def test_fingerprint_with_filename(self): def test_serial_fingerprint(self): strategy = axl.TitForTat() tf = TransitiveFingerprint(strategy) + path = pathlib.Path("test_outputs/test_fingerprint.csv") tf.fingerprint( repetitions=1, progress_bar=False, - filename=axl_filename("test_outputs", "tran_fin.csv"), + filename=axl_filename(path), ) self.assertEqual(tf.data.shape, (50, 50)) @@ -458,7 +460,8 @@ def test_parallel_fingerprint(self): def test_analyse_cooperation_ratio(self): tf = TransitiveFingerprint(axl.TitForTat) - filename = axl_filename("test_outputs", "test_fingerprint.csv") + path = pathlib.Path("test_outputs/test_fingerprint.csv") + filename = axl_filename(path) with open(filename, "w") as f: f.write( """Interaction index,Player index,Opponent index,Repetition,Player name,Opponent name,Actions diff --git a/axelrod/tests/unit/test_load_data.py b/axelrod/tests/unit/test_load_data.py index 52119f3ec..6dd880335 100644 --- a/axelrod/tests/unit/test_load_data.py +++ b/axelrod/tests/unit/test_load_data.py @@ -1,4 +1,5 @@ import os +import pathlib import unittest from axelrod.load_data_ import axl_filename @@ -6,7 +7,8 @@ class TestLoadData(unittest.TestCase): def test_axl_filename(self): - actual_fn = axl_filename("axelrod/strategies/titfortat.py") + path = pathlib.Path("axelrod/strategies/titfortat.py") + actual_fn = axl_filename(path) # First go from "unit" up to "tests", then up to "axelrod" dirname = os.path.dirname(__file__) diff --git a/axelrod/tests/unit/test_plot.py b/axelrod/tests/unit/test_plot.py index 90d4a083e..89d40d8d9 100644 --- a/axelrod/tests/unit/test_plot.py +++ b/axelrod/tests/unit/test_plot.py @@ -3,6 +3,7 @@ import tempfile import matplotlib import matplotlib.pyplot as plt +import pathlib from numpy import mean @@ -13,7 +14,8 @@ class TestPlot(unittest.TestCase): @classmethod def setUpClass(cls): - cls.filename = axl_filename("test_outputs", "test_results.csv") + path = pathlib.Path("test_outputs/test_results.csv") + cls.filename = axl_filename(path) cls.players = [axl.Alternator(), axl.TitForTat(), axl.Defector()] cls.repetitions = 3 diff --git a/axelrod/tests/unit/test_resultset.py b/axelrod/tests/unit/test_resultset.py index 1d988c615..8bd0be3af 100644 --- a/axelrod/tests/unit/test_resultset.py +++ b/axelrod/tests/unit/test_resultset.py @@ -4,6 +4,7 @@ import pandas as pd from dask.dataframe.core import DataFrame from numpy import mean, nanmedian, std +import pathlib import axelrod as axl from axelrod.load_data_ import axl_filename @@ -19,7 +20,8 @@ class TestResultSet(unittest.TestCase): @classmethod def setUpClass(cls): - cls.filename = axl_filename("test_outputs", "test_results.csv") + path = pathlib.Path("test_outputs/test_results.csv") + cls.filename = str(axl_filename(path)) cls.players = [axl.Alternator(), axl.TitForTat(), axl.Defector()] cls.repetitions = 3 @@ -677,7 +679,8 @@ class TestResultSetSpatialStructure(TestResultSet): @classmethod def setUpClass(cls): - cls.filename = axl_filename("test_outputs", "test_results_spatial.csv") + path = pathlib.Path("test_outputs/test_results_spatial.csv") + cls.filename = str(axl_filename(path)) cls.players = [axl.Alternator(), axl.TitForTat(), axl.Defector()] cls.turns = 5 cls.edges = [(0, 1), (0, 2)] @@ -857,7 +860,8 @@ class TestResultSetSpatialStructureTwo(TestResultSetSpatialStructure): @classmethod def setUpClass(cls): - cls.filename = axl_filename("test_outputs", "test_results_spatial_two.csv") + path = pathlib.Path("test_outputs/test_results_spatial_two.csv") + cls.filename = str(axl_filename(path)) cls.players = [ axl.Alternator(), axl.TitForTat(), @@ -1058,7 +1062,8 @@ class TestResultSetSpatialStructureThree(TestResultSetSpatialStructure): @classmethod def setUpClass(cls): - cls.filename = axl_filename("test_outputs", "test_results_spatial_three.csv") + path = pathlib.Path("test_outputs/test_results_spatial_three.csv") + cls.filename = str(axl_filename(path)) cls.players = [ axl.Alternator(), axl.TitForTat(), diff --git a/axelrod/tests/unit/test_tournament.py b/axelrod/tests/unit/test_tournament.py index 0ad0799a2..70410457a 100644 --- a/axelrod/tests/unit/test_tournament.py +++ b/axelrod/tests/unit/test_tournament.py @@ -7,6 +7,7 @@ import io import logging import os +import pathlib import pickle import warnings from multiprocessing import Queue, cpu_count @@ -90,7 +91,8 @@ def setUpClass(cls): [200, 200, 1, 200, 200], ] - cls.filename = axl_filename("test_outputs", "test_tournament.csv") + path = pathlib.Path("test_outputs/test_tournament.csv") + cls.filename = axl_filename(path) def setUp(self): self.test_tournament = axl.Tournament( @@ -110,9 +112,7 @@ def test_init(self): noise=0.2, ) self.assertEqual(len(tournament.players), len(test_strategies)) - self.assertIsInstance( - tournament.players[0].match_attributes["game"], axl.Game - ) + self.assertIsInstance(tournament.players[0].match_attributes["game"], axl.Game) self.assertEqual(tournament.game.score((C, C)), (3, 3)) self.assertEqual(tournament.turns, self.test_turns) self.assertEqual(tournament.repetitions, 10) @@ -415,9 +415,7 @@ def test_progress_bar_play_parallel(self): # these two examples were identified by hypothesis. @example( tournament=axl.Tournament( - players=[axl.BackStabber(), axl.MindReader()], - turns=2, - repetitions=1, + players=[axl.BackStabber(), axl.MindReader()], turns=2, repetitions=1, ) ) @example( @@ -735,9 +733,8 @@ def test_write_to_csv_with_results(self): ) tournament.play(filename=self.filename, progress_bar=False) df = pd.read_csv(self.filename) - expected_df = pd.read_csv( - axl_filename("test_outputs", "expected_test_tournament.csv") - ) + path = pathlib.Path("test_outputs/expected_test_tournament.csv") + expected_df = pd.read_csv(axl_filename(path)) self.assertTrue(df.equals(expected_df)) def test_write_to_csv_without_results(self): @@ -750,9 +747,8 @@ def test_write_to_csv_without_results(self): ) tournament.play(filename=self.filename, progress_bar=False, build_results=False) df = pd.read_csv(self.filename) - expected_df = pd.read_csv( - axl_filename("test_outputs", "expected_test_tournament_no_results.csv") - ) + path = pathlib.Path("test_outputs/expected_test_tournament_no_results.csv") + expected_df = pd.read_csv(axl_filename(path)) self.assertTrue(df.equals(expected_df)) @@ -808,16 +804,12 @@ def test_init(self): # these two examples were identified by hypothesis. @example( tournament=axl.Tournament( - players=[axl.BackStabber(), axl.MindReader()], - prob_end=0.2, - repetitions=1, + players=[axl.BackStabber(), axl.MindReader()], prob_end=0.2, repetitions=1, ) ) @example( tournament=axl.Tournament( - players=[axl.ThueMorse(), axl.MindReader()], - prob_end=0.2, - repetitions=1, + players=[axl.ThueMorse(), axl.MindReader()], prob_end=0.2, repetitions=1, ) ) def test_property_serial_play(self, tournament):