<commit_before>#!/usr/bin/python

import os
import csv
import datetime as dt
from numpy import random
from pyoperant.tricks import base
from pyoperant import components, utils,reinf

class TwoAltChoiceExp(base.BaseExp):
    """docstring for Experiment"""
    def __init__(self, *args, **kwargs):
        super(TwoAltChoiceExp,  self).__init__(*args, **kwargs)

        # assign stim files full names
        for name, filename in self.parameters['stims'].items():
            filename_full = os.path.join(self.parameters['stim_path'], filename)
            self.parameters['stims'][name] = filename_full

        self.req_panel_attr += ['speaker',
                                'left',
                                'center',
                                'right',
                                'reward',
                                'punish',
                                ]

        # configure csv file for data
        self.fields_to_save = ['session',
                               'index',
                               'type_',
                               'stimulus',
                               'class_',
                               'response',
                               'correct',
                               'rt',
                               'reward',
                               'timeout',
                               'time',
                               ]

        self.trials = []
        self.session_id = 0

        self.data_csv = os.path.join(self.parameters['experiment_path'],
                                     self.parameters['subject']+'_trialdata_'+self.timestamp+'.csv')

        if 'reinforcement' in self.parameters.keys():
            reinforcement = self.parameters['reinforcement']
            if reinforcement['schedule'] == 'variable_ratio':
                self.reinf_sched = reinf.VariableRatioSchedule(ratio=reinforcement['ratio'])
            elif reinf['schedule'] == 'fixed_ratio':
                self.reinf_sched = reinf.FixedRatioSchedule(ratio=reinforcement['ratio'])
            else:
                self.reinf_sched = reinf.ContinuousReinforcement()

        else:
            self.reinf_sched = reinf.ContinuousReinforcement()

    def make_data_csv(self):
        with open(self.data_csv, 'wb') as data_fh:
            trialWriter = csv.writer(data_fh)
            trialWriter.writerow(self.fields_to_save)

    ## session flow
    def check_session_schedule(self):
        return self.check_light_schedule()

    def session_pre(self):
        self.log.info('starting session')
        self.trials = []
        self.session_id += 1

        self.class_assoc = {}
        for class_, class_params in self.parameters['classes'].items():
            try:
                self.class_assoc[class_] = getattr(self.panel,class_params['component'])
            except KeyError:
                pass

        return 'main'

    def session_main(self):
        self._run_trial()
        if self.check_session_schedule:
            return 'main'
        else:
            return 'post'
    def session_post(self):
        self.log.info('ending session')
        return None

    ## trial flow
    def new_trial(self):
        '''create a new trial and append it to the trial list'''
        do_correction = False
        if self.trials:
            last_trial = self.trials[-1]
            index = last_trial.index+1
            if self.parameters['correction_trials'] and last_trial.response and (last_trial.correct==False):
                do_correction = True
        else:
            last_trial = None
            index = 0

        if do_correction:
            trial = utils.Trial(type_='correction',
                                index=index,
                                class_=last_trial.class_)
            for ev in last_trial.events:
                if ev.label is 'wav':
                    trial.events.append(ev[:])
                    trial.stimulus_event = trial.events[-1]
                    trial.stimulus = trial.stimulus_event.name
                elif ev.label is 'motif':
                    trial.events.append(ev[:])
            self.log.debug("correction trial: class is %s" % trial.class_)
        else:
            trial = utils.Trial(index=index)
            trial.class_ = random.choice(self.class_assoc.keys())
            trial_stim, trial_motifs = self.get_stimuli(trial.class_)
            trial.events.append(trial_stim)
            trial.stimulus_event = trial.events[-1]
            trial.stimulus = trial.stimulus_event.name
            for mot in trial_motifs:
                trial.events.append(mot)

        self.trials.append(trial)
        self.this_trial = self.trials[-1]
        self.this_trial_index = self.trials.index(self.this_trial)
        self.log.debug("trial %i: %s, %s" % (self.this_trial.index,self.this_trial.type_,self.this_trial.class_))

        return True

    def get_stimuli(self,trial_class):
        # TODO: default stimulus selection
        pass

    def analyze_trial(self):
        # TODO: calculate reaction times
        pass

    def save_trial(self,trial):
        '''write trial results to CSV'''
<commit_msg>fixed something<commit_after>#!/usr/bin/python

import os
import csv
import copy
import datetime as dt
from numpy import random
from pyoperant.tricks import base
from pyoperant import components, utils,reinf

class TwoAltChoiceExp(base.BaseExp):
    """docstring for Experiment"""
    def __init__(self, *args, **kwargs):
        super(TwoAltChoiceExp,  self).__init__(*args, **kwargs)

        # assign stim files full names
        for name, filename in self.parameters['stims'].items():
            filename_full = os.path.join(self.parameters['stim_path'], filename)
            self.parameters['stims'][name] = filename_full

        self.req_panel_attr += ['speaker',
                                'left',
                                'center',
                                'right',
                                'reward',
                                'punish',
                                ]

        # configure csv file for data
        self.fields_to_save = ['session',
                               'index',
                               'type_',
                               'stimulus',
                               'class_',
                               'response',
                               'correct',
                               'rt',
                               'reward',
                               'punish',
                               'time',
                               ]

        self.trials = []
        self.session_id = 0

        self.data_csv = os.path.join(self.parameters['experiment_path'],
                                     self.parameters['subject']+'_trialdata_'+self.timestamp+'.csv')

        if 'reinforcement' in self.parameters.keys():
            reinforcement = self.parameters['reinforcement']
            if reinforcement['schedule'] == 'variable_ratio':
                self.reinf_sched = reinf.VariableRatioSchedule(ratio=reinforcement['ratio'])
            elif reinf['schedule'] == 'fixed_ratio':
                self.reinf_sched = reinf.FixedRatioSchedule(ratio=reinforcement['ratio'])
            else:
                self.reinf_sched = reinf.ContinuousReinforcement()

        else:
            self.reinf_sched = reinf.ContinuousReinforcement()

    def make_data_csv(self):
        with open(self.data_csv, 'wb') as data_fh:
            trialWriter = csv.writer(data_fh)
            trialWriter.writerow(self.fields_to_save)

    ## session flow
    def check_session_schedule(self):
        return self.check_light_schedule()

    def session_pre(self):
        self.log.info('starting session')
        self.trials = []
        self.session_id += 1

        self.class_assoc = {}
        for class_, class_params in self.parameters['classes'].items():
            try:
                self.class_assoc[class_] = getattr(self.panel,class_params['component'])
            except KeyError:
                pass

        return 'main'

    def session_main(self):
        self._run_trial()
        if self.check_session_schedule:
            return 'main'
        else:
            return 'post'
    def session_post(self):
        self.log.info('ending session')
        return None

    ## trial flow
    def new_trial(self):
        '''create a new trial and append it to the trial list'''
        do_correction = False
        if self.trials:
            last_trial = self.trials[-1]
            index = last_trial.index+1
            if self.parameters['correction_trials'] and last_trial.response and (last_trial.correct==False):
                do_correction = True
        else:
            last_trial = None
            index = 0

        if do_correction:
            trial = utils.Trial(type_='correction',
                                index=index,
                                class_=last_trial.class_)
            for ev in last_trial.events:
                if ev.label is 'wav':
                    trial.events.append(copy.copy(ev))
                    trial.stimulus_event = trial.events[-1]
                    trial.stimulus = trial.stimulus_event.name
                elif ev.label is 'motif':
                    trial.events.append(copy.copy(ev))
            self.log.debug("correction trial: class is %s" % trial.class_)
        else:
            trial = utils.Trial(index=index)
            trial.class_ = random.choice(self.class_assoc.keys())
            trial_stim, trial_motifs = self.get_stimuli(trial.class_)
            trial.events.append(trial_stim)
            trial.stimulus_event = trial.events[-1]
            trial.stimulus = trial.stimulus_event.name
            for mot in trial_motifs:
                trial.events.append(mot)

        trial.annotate(session=self.session_id)

        self.trials.append(trial)
        self.this_trial = self.trials[-1]
        self.this_trial_index = self.trials.index(self.this_trial)
        self.log.debug("trial %i: %s, %s" % (self.this_trial.index,self.this_trial.type_,self.this_trial.class_))

        return True

    def get_stimuli(self,trial_class):
        # TODO: default stimulus selection
        pass

    def analyze_trial(self):
        # TODO: calculate reaction times
        pass

    def save_trial(self,trial):
        '''write trial results to CSV'''

{'fraction_non_alphanumeric': 0.09907922501438711, 'fraction_numerical': 0.0015346249760214848, 'mean_word_length': 1.570759368836292, 'pattern_counts': {'":': 0, '<': 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': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4534748', 'n_tokens_mistral': 2903, 'n_tokens_neox': 2697, 'n_words': 546}