def __repr__(self):
     return "{}:{}:{}:{}:{}".format(
         self.plays,
         self.op_plays,
         self.op_start_plays,
         actions_to_str(self.initial_actions),
         actions_to_str([v for k, v in sorted(self.table.items())])
     )
Beispiel #2
0
 def _write_interactions_to_file(self, results, writer):
     """Write the interactions to csv."""
     for index_pair, interactions in results.items():
         for interaction in interactions:
             row = list(index_pair)
             row.append(str(self.players[index_pair[0]]))
             row.append(str(self.players[index_pair[1]]))
             history1 = actions_to_str([i[0] for i in interaction])
             history2 = actions_to_str([i[1] for i in interaction])
             row.append(history1)
             row.append(history2)
             writer.writerow(row)
             self.num_interactions += 1
Beispiel #3
0
    def _write_interactions_to_file(self, results, writer):
        """Write the interactions to csv."""
        for index_pair, interactions in results.items():
            repetition = 0
            for interaction, results in interactions:

                if results is not None:
                    (
                        scores,
                        score_diffs,
                        turns,
                        score_per_turns,
                        score_diffs_per_turns,
                        initial_cooperation,
                        cooperations,
                        state_distribution,
                        state_to_action_distributions,
                        winner_index,
                    ) = results
                for index, player_index in enumerate(index_pair):
                    opponent_index = index_pair[index - 1]
                    row = [
                        self.num_interactions, player_index, opponent_index,
                        repetition,
                        str(self.players[player_index]),
                        str(self.players[opponent_index])
                    ]
                    history = actions_to_str([i[index] for i in interaction])
                    row.append(history)

                    if results is not None:
                        row.append(scores[index])
                        row.append(score_diffs[index])
                        row.append(turns)
                        row.append(score_per_turns[index])
                        row.append(score_diffs_per_turns[index])
                        row.append(int(winner_index is index))
                        row.append(initial_cooperation[index])
                        row.append(cooperations[index])

                        states = [(C, C), (C, D), (D, C), (D, D)]
                        if index == 1:
                            states = [s[::-1] for s in states]
                        for state in states:
                            row.append(state_distribution[state])
                        for state in states:
                            row.append(
                                state_to_action_distributions[index][(state,
                                                                      C)])
                            row.append(
                                state_to_action_distributions[index][(state,
                                                                      D)])

                        row.append(
                            int(cooperations[index] >= cooperations[index -
                                                                    1]))

                    writer.writerow(row)
                repetition += 1
                self.num_interactions += 1
Beispiel #4
0
 def find_state(self, opponent: Player) -> str:
     """
     Finds the my_state (the opponents last n moves +
     its previous proportion of playing C) as a hashable state
     """
     prob = "{:.1f}".format(opponent.cooperations)
     action_str = actions_to_str(opponent.history[-self.memory_length:])
     return action_str + prob
Beispiel #5
0
 def find_state(self, opponent: Player) -> str:
     """
     Finds the my_state (the opponents last n moves +
     its previous proportion of playing C) as a hashable state
     """
     prob = "{:.1f}".format(opponent.cooperations)
     action_str = actions_to_str(opponent.history[-self.memory_length :])
     return action_str + prob
Beispiel #6
0
    def _write_interactions_to_file(self, results, writer):
        """Write the interactions to csv."""
        for index_pair, interactions in results.items():
            repetition = 0
            for interaction, results in interactions:

                if results is not None:
                    (
                        scores,
                        score_diffs,
                        turns,
                        score_per_turns,
                        score_diffs_per_turns,
                        initial_cooperation,
                        cooperations,
                        state_distribution,
                        state_to_action_distributions,
                        winner_index,
                    ) = results
                for index, player_index in enumerate(index_pair):
                    opponent_index = index_pair[index - 1]
                    row = [
                        self.num_interactions,
                        player_index,
                        opponent_index,
                        repetition,
                    ]
                    row.append(str(self.players[player_index]))
                    row.append(str(self.players[opponent_index]))
                    history = actions_to_str([i[index] for i in interaction])
                    row.append(history)

                    if results is not None:
                        row.append(scores[index])
                        row.append(score_diffs[index])
                        row.append(turns)
                        row.append(score_per_turns[index])
                        row.append(score_diffs_per_turns[index])
                        row.append(int(winner_index is index))
                        row.append(initial_cooperation[index])
                        row.append(cooperations[index])

                        states = [(C, C), (C, D), (D, C), (D, D)]
                        if index == 1:
                            states = [s[::-1] for s in states]
                        for state in states:
                            row.append(state_distribution[state])
                        for state in states:
                            row.append(state_to_action_distributions[index][(state, C)])
                            row.append(state_to_action_distributions[index][(state, D)])

                        row.append(int(cooperations[index] >= cooperations[index - 1]))

                    writer.writerow(row)
                repetition += 1
                self.num_interactions += 1
Beispiel #7
0
 def strategy(opponent: Player) -> Action:
     # Cooperate on the first move
     if not opponent.history:
         return C
     # Defects if two consecutive D in the opponent's last three moves
     history_string = actions_to_str(opponent.history[-3:])
     if "DD" in history_string:
         return D
     # Otherwise cooperates
     return C
Beispiel #8
0
 def strategy(opponent: Player) -> Action:
     # Cooperate on the first move
     if not opponent.history:
         return C
     # Defects if two consecutive D in the opponent's last three moves
     history_string = actions_to_str(opponent.history[-3:])
     if "DD" in history_string:
         return D
     # Otherwise cooperates
     return C
Beispiel #9
0
 def mutate(self) -> EvolvablePlayer:
     """
     Basic mutation which may change any random actions in the sequence.
     """
     if random.random() <= self.mutation_probability:
         mutated_sequence = list(str_to_actions(self.cycle))
         for _ in range(self.mutation_potency):
             index_to_change = random.randint(0, len(mutated_sequence) - 1)
             mutated_sequence[index_to_change] = mutated_sequence[index_to_change].flip()
         cycle = actions_to_str(mutated_sequence)
     else:
         cycle = self.cycle
     cycle, _ = self._normalize_parameters(cycle)
     return self.create_new(cycle=cycle)
Beispiel #10
0
 def sorter(plays):
     return tuple(
         actions_to_str(getattr(plays, field) for field in sort_by))
Beispiel #11
0
 def test_actions_to_str_with_iterable(self):
     self.assertEqual(actions_to_str(iter([C, D, C])), "CDC")
     generator = (action for action in [C, D, C])
     self.assertEqual(actions_to_str(generator), "CDC")
Beispiel #12
0
 def test_actions_to_str(self):
     self.assertEqual(actions_to_str([]), "")
     self.assertEqual(actions_to_str([C]), "C")
     self.assertEqual(actions_to_str([C, D, C]), "CDC")
     self.assertEqual(actions_to_str((C, C, D)), "CCD")
Beispiel #13
0
 def sorter(plays):
     return tuple(actions_to_str(getattr(plays, field) for field in sort_by))
Beispiel #14
0
 def __str__(self):
     return actions_to_str(self._plays)
Beispiel #15
0
 def _generate_random_cycle(cls, cycle_length: int) -> str:
     """
     Generate a sequence of random moves
     """
     return actions_to_str(random.choice(actions) for _ in range(cycle_length))