Exemple #1
0
    def fingerprint(self, turns=50, repetitions=10, step=0.01, processes=None,
                    filename=None, in_memory=False, progress_bar=True):
        """Build and play the spatial tournament.

        Creates the probes and their edges then builds a spatial tournament.
        When the coordinates of the probe sum to more than 1, the dual of the
        probe is taken instead and then the Joss-Ann Transformer is applied. If
        the coordinates sum to less than 1 (or equal), then only the Joss-Ann is
        applied, a dual is not required.

        Parameters
        ----------
        turns : integer, optional
            The number of turns per match
        repetitions : integer, optional
            The number of times the round robin should be repeated
        step : float, optional
            The separation between each Point. Smaller steps will
            produce more Points that will be closer together.
        processes : integer, optional
            The number of processes to be used for parallel processing
        progress_bar : bool
            Whether or not to create a progress bar which will be updated

        Returns
        ----------
        self.data : dictionary
            A dictionary where the keys are coordinates of the form (x, y) and
            the values are the mean score for the corresponding interactions.
        """

        if on_windows and (filename is None):
            in_memory = True
        elif filename is not None:
            outputfile = open(filename, 'w')
            filename = outputfile.name
        else:
            outputfile = NamedTemporaryFile(mode='w')
            filename = outputfile.name

        edges, tourn_players = self.construct_tournament_elements(step,
                                                     progress_bar=progress_bar)
        self.step = step
        self.spatial_tournament = axl.SpatialTournament(tourn_players,
                                                        turns=turns,
                                                        repetitions=repetitions,
                                                        edges=edges)
        self.spatial_tournament.play(build_results=False,
                                     filename=filename,
                                     processes=processes,
                                     in_memory=in_memory,
                                     progress_bar=progress_bar)
        if in_memory:
            self.interactions = self.spatial_tournament.interactions_dict
        else:
            self.interactions = read_interactions_from_file(filename,
                                                     progress_bar=progress_bar)

        self.data = self.generate_data(self.interactions, self.points, edges)
        return self.data
Exemple #2
0
    def test_equality_with_prob_end(self, tournament):
        filename = "test_outputs/test_results.csv"
        tournament.play(filename=filename, progress_bar=False, build_results=False)
        brs = axelrod.ResultSetFromFile(filename, progress_bar=False)
        interactions = iu.read_interactions_from_file(filename, progress_bar=False)
        rs = axelrod.ResultSet(tournament.players, interactions, progress_bar=False)

        # Not testing full equality because of floating point errors.
        self.assertEqual(rs.ranked_names, brs.ranked_names)
        self.assertEqual(rs.scores, brs.scores)
        self.assertEqual(rs.match_lengths, brs.match_lengths)
        self.assertEqual(rs.cooperation, brs.cooperation)
 def test_read_interactions_from_file(self):
     tmp_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
     players = [axelrod.Cooperator(), axelrod.Defector()]
     tournament = axelrod.Tournament(players=players, turns=2, repetitions=3)
     tournament.play(filename=tmp_file.name)
     tmp_file.close()
     expected_interactions = {
         (0, 0): [[(C, C), (C, C)] for _ in range(3)],
         (0, 1): [[(C, D), (C, D)] for _ in range(3)],
         (1, 1): [[(D, D), (D, D)] for _ in range(3)],
     }
     interactions = iu.read_interactions_from_file(tmp_file.name, progress_bar=False)
     self.assertEqual(expected_interactions, interactions)
 def test_read_interactions_from_file(self):
     tmp_file = tempfile.NamedTemporaryFile(mode="w", delete=False)
     players = [axelrod.Cooperator(), axelrod.Defector()]
     tournament = axelrod.Tournament(players=players, turns=2, repetitions=3)
     tournament.play(filename=tmp_file.name)
     tmp_file.close()
     expected_interactions = {
         (0, 0): [[(C, C), (C, C)] for _ in range(3)],
         (0, 1): [[(C, D), (C, D)] for _ in range(3)],
         (1, 1): [[(D, D), (D, D)] for _ in range(3)],
     }
     interactions = iu.read_interactions_from_file(tmp_file.name, progress_bar=False)
     self.assertEqual(expected_interactions, interactions)
    def test_equality_with_prob_end(self, tournament):
        filename = "test_outputs/test_results.csv"
        tournament.play(filename=filename, progress_bar=False,
                        build_results=False)
        brs = axelrod.ResultSetFromFile(filename, progress_bar=False)
        interactions = iu.read_interactions_from_file(filename)
        rs = axelrod.ResultSet(tournament.players, interactions,
                               progress_bar=False)

        # Not testing full equality because of floating point errors.
        self.assertEqual(rs.ranked_names, brs.ranked_names)
        self.assertEqual(rs.scores, brs.scores)
        self.assertEqual(rs.match_lengths, brs.match_lengths)
        self.assertEqual(rs.cooperation, brs.cooperation)
Exemple #6
0
    def test_equality_with_round_robin(self, tournament):
        filename = "test_outputs/test_results.csv"
        tournament.play(filename=filename, progress_bar=False, build_results=False)
        brs = axelrod.ResultSetFromFile(filename, progress_bar=False)
        interactions = iu.read_interactions_from_file(filename, progress_bar=False)
        rs = axelrod.ResultSet(tournament.players, interactions, progress_bar=False)

        # Not testing full equality because of floating point errors.
        self.assertEqual(rs.scores, brs.scores)
        self.assertEqual(rs.wins, brs.wins)
        self.assertEqual(rs.match_lengths, brs.match_lengths)
        self.assertEqual(rs.cooperation, brs.cooperation)

        # Test that players are in the results (due to floating point errors
        # the order might not be the same)
        self.assertEqual(set(rs.ranked_names), set(brs.ranked_names))
Exemple #7
0
    def fingerprint(
        self,
        turns: int = 50,
        repetitions: int = 10,
        step: float = 0.01,
        processes: int = None,
        filename: str = None,
        progress_bar: bool = True,
    ) -> dict:
        """Build and play the spatial tournament.

        Creates the probes and their edges then builds a spatial tournament.
        When the coordinates of the probe sum to more than 1, the dual of the
        probe is taken instead and then the Joss-Ann Transformer is applied. If
        the coordinates sum to less than 1 (or equal), then only the Joss-Ann is
        applied, a dual is not required.

        Parameters
        ----------
        turns : int, optional
            The number of turns per match
        repetitions : int, optional
            The number of times the round robin should be repeated
        step : float, optional
            The separation between each Point. Smaller steps will
            produce more Points that will be closer together.
        processes : int, optional
            The number of processes to be used for parallel processing
        filename: str, optional
            The name of the file for self.spatial_tournament's interactions.
            if None, will auto-generate a filename.
        progress_bar : bool
            Whether or not to create a progress bar which will be updated

        Returns
        ----------
        self.data : dict
            A dictionary where the keys are coordinates of the form (x, y) and
            the values are the mean score for the corresponding interactions.
        """

        temp_file_descriptor = None
        if filename is None:
            temp_file_descriptor, filename = mkstemp()  # type: ignore

        edges, tourn_players = self._construct_tournament_elements(
            step, progress_bar=progress_bar)

        self.step = step
        self.spatial_tournament = axl.Tournament(tourn_players,
                                                 turns=turns,
                                                 repetitions=repetitions,
                                                 edges=edges)
        self.spatial_tournament.play(
            build_results=False,
            filename=filename,
            processes=processes,
            progress_bar=progress_bar,
        )

        self.interactions = read_interactions_from_file(
            filename, progress_bar=progress_bar)

        if temp_file_descriptor is not None:
            assert filename is not None
            os.close(temp_file_descriptor)
            os.remove(filename)

        self.data = _generate_data(self.interactions, self.points, edges)
        return self.data
Exemple #8
0
    def fingerprint(
        self,
        turns: int = 50,
        repetitions: int = 10,
        step: float = 0.01,
        processes: int = None,
        filename: str = None,
        progress_bar: bool = True,
    ) -> dict:
        """Build and play the spatial tournament.

        Creates the probes and their edges then builds a spatial tournament.
        When the coordinates of the probe sum to more than 1, the dual of the
        probe is taken instead and then the Joss-Ann Transformer is applied. If
        the coordinates sum to less than 1 (or equal), then only the Joss-Ann is
        applied, a dual is not required.

        Parameters
        ----------
        turns : int, optional
            The number of turns per match
        repetitions : int, optional
            The number of times the round robin should be repeated
        step : float, optional
            The separation between each Point. Smaller steps will
            produce more Points that will be closer together.
        processes : int, optional
            The number of processes to be used for parallel processing
        filename: str, optional
            The name of the file for self.spatial_tournament's interactions.
            if None, will auto-generate a filename.
        progress_bar : bool
            Whether or not to create a progress bar which will be updated

        Returns
        ----------
        self.data : dict
            A dictionary where the keys are coordinates of the form (x, y) and
            the values are the mean score for the corresponding interactions.
        """

        temp_file_descriptor = None
        if filename is None:
            temp_file_descriptor, filename = mkstemp()  # type: ignore

        edges, tourn_players = self._construct_tournament_elements(
            step, progress_bar=progress_bar
        )

        self.step = step
        self.spatial_tournament = axl.Tournament(
            tourn_players, turns=turns, repetitions=repetitions, edges=edges
        )
        self.spatial_tournament.play(
            build_results=False,
            filename=filename,
            processes=processes,
            progress_bar=progress_bar,
        )

        self.interactions = read_interactions_from_file(
            filename, progress_bar=progress_bar
        )

        if temp_file_descriptor is not None:
            assert filename is not None
            os.close(temp_file_descriptor)
            os.remove(filename)

        self.data = _generate_data(self.interactions, self.points, edges)
        return self.data
class TestResultSetFromFile(unittest.TestCase):
    filename = "test_outputs/test_results_from_file.csv"
    players = [axelrod.Cooperator(),
               axelrod.TitForTat(),
               axelrod.Defector()]
    tournament = axelrod.Tournament(players=players, turns=2, repetitions=3)
    tournament.play(filename=filename)

    interactions = iu.read_interactions_from_file(filename)

    def test_init(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        self.assertEqual(brs.players, [str(p) for p in self.players])
        self.assertEqual(brs.nplayers, len(self.players))
        self.assertEqual(brs.nrepetitions, 3)

    def test_init_with_different_game(self):
        game = axelrod.Game(p=-1, r=-1, s=-1, t=-1)
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False,
                                   game=game)
        self.assertEqual(brs.game.RPST(), (-1, -1, -1, -1))

    def test_init_with_progress_bar(self):
        """Just able to test that no error occurs"""
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=True)
        self.assertEqual(brs.nplayers, len(self.players))
        self.assertEqual(brs.nrepetitions, 3)
        self.assertEqual(brs.num_interactions, 18)

    def test_init_with_num_interactions(self):
        """Just able to test that no error occurs"""
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=True,
                                        num_interactions=18)
        self.assertEqual(brs.nplayers, len(self.players))
        self.assertEqual(brs.nrepetitions, 3)
        self.assertEqual(brs.num_interactions, 18)

    def test_init_with_players_nrepetitions(self):
        """Just able to test that no error occurs"""
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=True,
                                        num_interactions=18, nrepetitions=3,
                                        players=[str(p) for p in self.players])
        self.assertEqual(brs.nplayers, len(self.players))
        self.assertEqual(brs.nrepetitions, 3)
        self.assertEqual(brs.num_interactions, 18)

    def test_equality(self):
        """A test that checks overall equality by comparing to the base result
        set class"""
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        rs = axelrod.ResultSet(self.players, self.interactions, progress_bar=False)
        self.assertEqual(rs, brs)

    def test_interactions_equality(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False,
                                        keep_interactions=True)
        rs = axelrod.ResultSet(self.players, self.interactions, progress_bar=False)
        self.assertEqual(rs.interactions, brs.interactions)

    @given(tournament=tournaments(max_size=5,
                                  max_turns=5,
                                  max_noise=0,
                                  max_repetitions=3))
    @settings(max_examples=50, timeout=0)
    def test_equality_with_round_robin(self, tournament):
        filename = "test_outputs/test_results.csv"
        tournament.play(filename=filename, progress_bar=False,
                        build_results=False)
        brs = axelrod.ResultSetFromFile(filename, progress_bar=False)
        interactions = iu.read_interactions_from_file(filename)
        rs = axelrod.ResultSet(tournament.players, interactions,
                               progress_bar=False)

        # Not testing full equality because of floating point errors.
        self.assertEqual(rs.ranked_names, brs.ranked_names)
        self.assertEqual(rs.scores, brs.scores)
        self.assertEqual(rs.match_lengths, brs.match_lengths)
        self.assertEqual(rs.cooperation, brs.cooperation)

    @given(tournament=prob_end_tournaments(max_size=5,
                                           min_prob_end=.7,
                                           max_repetitions=3))
    @settings(max_examples=50, timeout=0)
    def test_equality_with_prob_end(self, tournament):
        filename = "test_outputs/test_results.csv"
        tournament.play(filename=filename, progress_bar=False,
                        build_results=False)
        brs = axelrod.ResultSetFromFile(filename, progress_bar=False)
        interactions = iu.read_interactions_from_file(filename)
        rs = axelrod.ResultSet(tournament.players, interactions,
                               progress_bar=False)

        # Not testing full equality because of floating point errors.
        self.assertEqual(rs.ranked_names, brs.ranked_names)
        self.assertEqual(rs.scores, brs.scores)
        self.assertEqual(rs.match_lengths, brs.match_lengths)
        self.assertEqual(rs.cooperation, brs.cooperation)

    def test_read_players_and_repetitions(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        players, nrepetitions = brs._read_players_and_repetition_numbers()
        expected_players = ['Cooperator', 'Tit For Tat', 'Defector']
        self.assertEqual(brs.players, expected_players)
        self.assertEqual(nrepetitions, 3)

    def test_update_repetitions(self):
        brs = axelrod.ResultSetFromFile(filename=self.filename, progress_bar=False)
        brs.repetitions_d = {}
        brs._update_repetitions((0, 0))
        self.assertEqual(brs.repetitions_d, {(0, 0): 1})
        brs._update_repetitions((0, 0))
        self.assertEqual(brs.repetitions_d, {(0, 0): 2})
        brs._update_repetitions((0, 1))
        self.assertEqual(brs.repetitions_d, {(0, 0): 2, (0, 1): 1})

    def test_build_repetitions(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        brs.repetitions_d = {}
        brs._update_repetitions((0, 0))
        brs._update_repetitions((0, 0))
        nrepetitions = brs._build_nrepetitions()
        self.assertEqual(nrepetitions, 2)
        self.assertFalse(hasattr(brs, 'repetitions_d'))

    def test_update_players(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        brs.players_d = {}
        brs._update_players((0, 0), ('Cooperator', 'Cooperator'))
        self.assertEqual(brs.players_d, {0: 'Cooperator'})
        brs._update_players((0, 0), ('Cooperator', 'Cooperator'))
        self.assertEqual(brs.players_d, {0: 'Cooperator'})
        brs._update_players((0, 1), ('Cooperator', 'Defector'))
        self.assertEqual(brs.players_d, {0: 'Cooperator', 1: 'Defector'})

    def test_build_players(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        brs.players_d = {}
        brs._update_players((0, 0), ('Cooperator', 'Cooperator'))
        brs._update_players((0, 1), ('Cooperator', 'Defector'))
        players = brs._build_players()
        self.assertEqual(players, ['Cooperator', 'Defector'])
        self.assertFalse(hasattr(brs, 'players_d'))

    def test_build_read_match_chunks(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        matches = brs.read_match_chunks()
        chunk = next(matches)
        self.assertEqual(chunk[0], ['0'] * 2 + ['Cooperator'] * 2 + ['CC'] * 2)
        self.assertEqual(chunk[1], ['0'] * 2 + ['Cooperator'] * 2 + ['CC'] * 2)
        self.assertEqual(chunk[2], ['0'] * 2 + ['Cooperator'] * 2 + ['CC'] * 2)
        self.assertEqual(len(list(matches)), 5)

    def test_build_all(self):
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        rs = axelrod.ResultSet(self.players, self.interactions,
                               progress_bar=False)

        brs._build_empty_metrics()
        self.assertNotEqual(brs, rs)
        brs._build_score_related_metrics(progress_bar=False)
        self.assertEqual(brs, rs)

    def test_buid_empty_metrics(self):
        plist = range(3)
        nrepetitions = 3
        replist = range(nrepetitions)
        expected_match_lengths = [[[0 for opponent in plist] for player in plist]
                                  for _ in replist]
        expected_wins = [[0 for _ in replist] for player in plist]
        expected_scores = [[0 for _ in replist] for player in plist]
        expected_normalised_scores = [[[] for _ in replist] for player in plist]
        expected_payoffs = [[[] for opponent in plist] for player in plist]
        expected_score_diffs = [[[0] * nrepetitions for opponent in plist]
                                for player in plist]
        expected_cooperation = [[0 for opponent in plist] for player in plist]
        expected_normalised_cooperation = [[[] for opponent in plist]
                                       for player in plist]
        expected_good_partner_matrix = [[0 for opponent in plist]
                                        for player in plist]

        expected_good_partner_rating = [0 for player in plist]
        brs = axelrod.ResultSetFromFile(self.filename, progress_bar=False)
        brs.match_lengths = []
        brs.wins = []
        brs.scores = []
        brs.normalised_scores = []
        brs.payoffs = []
        brs.score_diffs = []
        brs.cooperation = []
        brs.normalised_cooperation = []
        brs.good_partner_matrix = []
        brs.total_interactions = []
        brs.good_partner_rating = []
        brs._build_empty_metrics()
        self.assertEqual(brs.match_lengths, expected_match_lengths)
        self.assertEqual(brs.wins, expected_wins)
        self.assertEqual(brs.scores, expected_scores)
        self.assertEqual(brs.normalised_scores, expected_normalised_scores)
        self.assertEqual(brs.payoffs, expected_payoffs)
        self.assertEqual(brs.score_diffs, expected_score_diffs)
        self.assertEqual(brs.cooperation, expected_cooperation)
        self.assertEqual(brs.normalised_cooperation,
                         expected_normalised_cooperation)
        self.assertEqual(brs.good_partner_matrix, expected_good_partner_matrix)
        self.assertEqual(brs.good_partner_rating, expected_good_partner_rating)