<commit_before>import csv
from functools import partial
from itertools import repeat
from multiprocessing import Pool
from operator import itemgetter
import os
from random import randrange
from statistics import mean, pstdev

import axelrod as axl


## Output Evolutionary Algorithm results

class Outputer(object):
    def __init__(self, filename, mode='w'):
        self.output = open(filename, mode)
        self.writer = csv.writer(self.output)

    def write(self, row):
        self.writer.writerow(row)
        self.output.flush()
        os.fsync(self.output.fileno())


## Objective functions for optimization

def prepare_objective(name="score", turns=200, noise=0., repetitions=None,
                      nmoran=None):
    name = name.lower()
    if name not in ["score", "score_diff", "moran"]:
        raise ValueError("Score must be one of score, score_diff, or moran")
    if name == "moran":
        if repetitions is None:
            repetitions = 1000
        if nmoran is None:
            nmoran = 4
        objective = partial(objective_moran_win, turns=turns, noise=noise,
                            repetitions=repetitions, N=nmoran)
    elif name == "score":
        if repetitions is None:
            repetitions = 20
        objective = partial(objective_score, turns=turns, noise=noise,
                            repetitions=repetitions)
    elif name == "score_diff":
        if repetitions is None:
            repetitions = 20
        objective = partial(objective_score_diff, turns=turns, noise=noise,
                            repetitions=repetitions)
    return objective


def objective_score(me, other, turns, noise, repetitions):
    """Objective function to maximize total score over matches."""
    match = axl.Match((me, other), turns=turns, noise=noise)
    if not match._stochastic:
        repetitions = 1
    scores_for_this_opponent = []

    for _ in range(repetitions):
        match.play()
        scores_for_this_opponent.append(match.final_score_per_turn()[0])
    return scores_for_this_opponent


def objective_score_diff(me, other, turns, noise, repetitions):
    """Objective function to maximize total score difference over matches."""
    match = axl.Match((me, other), turns=turns, noise=noise)
    if not match._stochastic:
        repetitions = 1
    scores_for_this_opponent = []

    for _ in range(repetitions):
        match.play()
        final_scores = match.final_score_per_turn()
        score_diff = final_scores[0] - final_scores[1]
        scores_for_this_opponent.append(score_diff)
    return scores_for_this_opponent


def objective_moran_win(me, other, turns, noise, repetitions, N=5):
    """Objective function to maximize Moran fixations over N=4 matches"""
    assert(noise == 0)
    population = []
    for _ in range(N):
        population.append(me.clone())
        population.append(other.clone())
    mp = axl.MoranProcess(population, turns=turns, noise=noise)

    scores_for_this_opponent = []

    for _ in range(repetitions):
        mp.play()
        if mp.winning_strategy_name == str(me):
            scores_for_this_opponent.append(1)
        else:
            scores_for_this_opponent.append(0)
    return scores_for_this_opponent

# Evolutionary Algorithm
<commit_msg>Remove noise == 0 assertion<commit_after>import csv
from functools import partial
from itertools import repeat
from multiprocessing import Pool
from operator import itemgetter
import os
from random import randrange
from statistics import mean, pstdev

import axelrod as axl


## Output Evolutionary Algorithm results

class Outputer(object):
    def __init__(self, filename, mode='w'):
        self.output = open(filename, mode)
        self.writer = csv.writer(self.output)

    def write(self, row):
        self.writer.writerow(row)
        self.output.flush()
        os.fsync(self.output.fileno())


## Objective functions for optimization

def prepare_objective(name="score", turns=200, noise=0., repetitions=None,
                      nmoran=None):
    name = name.lower()
    if name not in ["score", "score_diff", "moran"]:
        raise ValueError("Score must be one of score, score_diff, or moran")
    if name == "moran":
        if repetitions is None:
            repetitions = 1000
        if nmoran is None:
            nmoran = 4
        objective = partial(objective_moran_win, turns=turns, noise=noise,
                            repetitions=repetitions, N=nmoran)
    elif name == "score":
        if repetitions is None:
            repetitions = 20
        objective = partial(objective_score, turns=turns, noise=noise,
                            repetitions=repetitions)
    elif name == "score_diff":
        if repetitions is None:
            repetitions = 20
        objective = partial(objective_score_diff, turns=turns, noise=noise,
                            repetitions=repetitions)
    return objective


def objective_score(me, other, turns, noise, repetitions):
    """Objective function to maximize total score over matches."""
    match = axl.Match((me, other), turns=turns, noise=noise)
    if not match._stochastic:
        repetitions = 1
    scores_for_this_opponent = []

    for _ in range(repetitions):
        match.play()
        scores_for_this_opponent.append(match.final_score_per_turn()[0])
    return scores_for_this_opponent


def objective_score_diff(me, other, turns, noise, repetitions):
    """Objective function to maximize total score difference over matches."""
    match = axl.Match((me, other), turns=turns, noise=noise)
    if not match._stochastic:
        repetitions = 1
    scores_for_this_opponent = []

    for _ in range(repetitions):
        match.play()
        final_scores = match.final_score_per_turn()
        score_diff = final_scores[0] - final_scores[1]
        scores_for_this_opponent.append(score_diff)
    return scores_for_this_opponent


def objective_moran_win(me, other, turns, noise, repetitions, N=5):
    """Objective function to maximize Moran fixations over N=4 matches"""
    population = []
    for _ in range(N):
        population.append(me.clone())
        population.append(other.clone())
    mp = axl.MoranProcess(population, turns=turns, noise=noise)

    scores_for_this_opponent = []

    for _ in range(repetitions):
        mp.play()
        if mp.winning_strategy_name == str(me):
            scores_for_this_opponent.append(1)
        else:
            scores_for_this_opponent.append(0)
    return scores_for_this_opponent

# Evolutionary Algorithm

{'fraction_non_alphanumeric': 0.09195402298850575, 'fraction_numerical': 0.007049808429118774, 'mean_word_length': 2.90311004784689, 'pattern_counts': {'":': 6, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2796752', 'n_tokens_mistral': 1975, 'n_tokens_neox': 1886, 'n_words': 495}