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

Create function to handle relative paths #1307

Merged
merged 5 commits into from
Apr 7, 2020
Merged
Show file tree
Hide file tree
Changes from 3 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
24 changes: 23 additions & 1 deletion axelrod/load_data_.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,30 @@
from typing import Dict, List, Tuple
import pathlib
from typing import Dict, List, Text, Tuple

import pkg_resources


def axl_filename(*axl_path: Text) -> Text:
gaffney2010 marked this conversation as resolved.
Show resolved Hide resolved
"""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").

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]]:
"""Loads a data file stored in the Axelrod library's data subdirectory,
likely for parameters for a strategy."""
Expand Down
3 changes: 2 additions & 1 deletion axelrod/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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:
Expand Down
31 changes: 19 additions & 12 deletions axelrod/tests/integration/test_tournament.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -32,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 = "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)
)
Expand Down Expand Up @@ -90,7 +93,9 @@ 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]))

Expand All @@ -113,7 +118,9 @@ 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]))

Expand Down
7 changes: 4 additions & 3 deletions axelrod/tests/unit/test_deterministic_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)

Expand Down Expand Up @@ -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)

Expand Down
13 changes: 8 additions & 5 deletions axelrod/tests/unit/test_fingerprint.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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, [])

Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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))

Expand All @@ -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
Expand Down
15 changes: 15 additions & 0 deletions axelrod/tests/unit/test_load_data.py
Original file line number Diff line number Diff line change
@@ -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))
3 changes: 2 additions & 1 deletion axelrod/tests/unit/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
5 changes: 3 additions & 2 deletions axelrod/tests/unit/test_resultset.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)]
Expand Down
9 changes: 6 additions & 3 deletions axelrod/tests/unit/test_tournament.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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):
Expand All @@ -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))

Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down