Exemple #1
0
def feature_dimension_fit(matrix, k_range, fName = None):
        Var = []
        timer = Clock()
        for k in k_range:
                print "Reducing feature-rank to {}".format(k)
                timer.reset()
                Rn = TruncatedSVD(n_components = k, random_state = 42).fit(matrix)
                t = timer.getTime()
                Var.append([k,sum(Rn.explained_variance_ratio_)*100,t])
                print "processing time (s): {}".format(t)
        Var = np.array(Var)
        if fName != None:
                plt.plot(Var.T[0],Var.T[1])
                plt.ylabel("%variance")
                plt.xlabel("dimension in feature space")
                plt.savefig(fName)
                plt.show()
        return Var, Rn
Exemple #2
0
def testClock():
    try:
        c = Clock()

        t1=c.getTime()
        time.sleep(1.0)
        t2=c.getTime()

        startTime=c.getLastResetTime()

        assert t2>t1
        assert t2-t1 > 0.95
        assert t2-t1 < 1.05
        assert startTime > 0

        c.reset()
        t=c.getTime()
        assert t < 0.01

        c.reset(10)
        t=c.getTime()
        assert t > -10.0
        assert t < -9.9

        t1=c.getTime()
        c.add(50)
        t2=c.getTime()
        assert t2-t1 > -50.0
        assert t2-t1 < -49.9

        printf(">> Clock Test: PASSED")

    except Exception:
        printf(">> Clock Test: FAILED")
        printExceptionDetails()

    printf("-------------------------------------\n")
Exemple #3
0
def test_Clock():
    try:
        c = Clock()

        t1 = c.getTime()
        time.sleep(1.0)
        t2 = c.getTime()

        startTime = c.getLastResetTime()

        assert t2 > t1
        assert t2 - t1 > 0.95
        assert t2 - t1 < 1.05
        assert startTime > 0

        c.reset()
        t = c.getTime()
        assert t < 0.01

        c.reset(10)
        t = c.getTime()
        assert t > -10.0
        assert t < -9.9

        t1 = c.getTime()
        c.add(50)
        t2 = c.getTime()
        assert t2 - t1 > -50.0
        assert t2 - t1 < -49.9

        printf(">> Clock Test: PASSED")

    except Exception:
        printf(">> Clock Test: FAILED")
        printExceptionDetails()

    printf("-------------------------------------\n")
Exemple #4
0
class Session:
    """ Base Session class """
    def __init__(self, settings_file=None, eyetracker_on=False):
        """ Initializes base Session class.

        parameters
        ----------
        settings_file : str
            Path to settings file. If None, default_settings.yml is used
        eyetracker_on : bool
            Whether to enable eyetracker
        """
        self.settings_file = settings_file
        self.eyetracker_on=eyetracker_on
        self.clock = Clock()
        self.timer = Clock()
        self.start_exp = None
        self.current_trial = None
        self.log = []
        self.logfile = logging.LogFile(f='log.txt', filemode='w', level=logging.EXP)

        # Initialize
        self.settings = self._load_settings()
        self.monitor = self._create_monitor()
        self.win = self._create_window()
        self.mouse = Mouse(**self.settings['mouse'])
        self.default_fix = Circle(self.win, radius=0.3, fillColor='white', edges=1000)
        self.mri_simulator = self._setup_mri_simulator() if self.settings['mri']['simulate'] else None
        self.tracker = None

    def _load_settings(self):
        """ Loads settings and sets preferences. """
        if self.settings_file is None:
            self.settings_file = op.join(op.dirname(__file__), 'default_settings.yml')
            logging.warn(f"Using default logfile ({self.settings_file}")

        with open(self.settings_file, 'r') as f_in:
            settings = yaml.load(f_in)

        exp_prefs = settings['preferences']  # set preferences globally
        for preftype, these_settings in exp_prefs.items():
            for key, value in these_settings.items():
                pref_subclass = getattr(psychopy_prefs, preftype)
                pref_subclass[key] = value
                setattr(psychopy_prefs, preftype, pref_subclass)

        return settings

    def _create_monitor(self):
        monitor = Monitor(**self.settings['monitor'])
        monitor.save()  # needed for iohub eyetracker
        return monitor

    def _create_window(self):
        win = Window(monitor=self.monitor, **self.settings['window'])
        return win

    def _setup_mri_simulator(self):
        args = self.settings['mri'].copy()
        args.pop('simulate')
        return SyncGenerator(**args)

    def start_experiment(self):
        """ Logs the onset of the start of the experiment """
        self.start_exp = getTime()  # abs time
        self.clock.reset()  # resets global clock
        self.timer.reset()  # phase-timer

        if self.mri_simulator is not None:
            self.mri_simulator.start()

    def display_text(self, text, keys=['return'], **kwargs):
        stim = TextStim(self.win, text=text, **kwargs)
        stim.draw()
        self.win.flip()
        waitKeys(keyList=keys)

    def close(self):
        self.exp_stop = self.clock.getTime()
        print(f"Duration experiment: {self.exp_stop:.3f}\n")
        self.log = pd.concat(self.log)
        self.log['onset_abs'] = self.log['onset'] + self.start_exp
        print(self.log)

        if self.mri_simulator is not None:
            self.mri_simulator.stop()

        quit()

    def init_eyetracker(self):

        if not self.eyetracker_on:
            raise ValueError("Cannot initialize eyetracker if eyetracker_on=False!")

        EYETRACKER_NAME = 'eyetracker.hw.sr_research.eyelink.EyeTracker'
        # default_native_data_file_name: et_data
        self.iohub = launchHubServer(
            psychopy_monitor_name=self.monitor.name,
            datastore_name='test_et',
            **{EYETRACKER_NAME: {
                'enable_interface_without_connection': True
            }}
        )

        self.tracker = self.iohub.getDevice('eyetracker.hw.sr_research.eyelink.EyeTracker')

    def start_recording_eyetracker(self):
        self.tracker.setRecordingState(True)

    def stop_recording_eyetracker(self):
        self.tracker.setRecordingState(False)

    def calibrate_eyetracker(self):
        self.tracker.runSetupProcedure()

    def close_tracker(self):
        self.stop_recording_eyetracker()
        self.iohub.quit()
Exemple #5
0
#defines click boxes
lbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
            lineWidth=5,
            pos=(-0.3, -0.6))

rbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
            lineWidth=5,
            pos=(+0.3, -0.6))

while global_time.getTime() < session * 60:

    #checks of keyboard input
    resp_key = getKeys(['q', 'escape'])

    #proceeds to next phase if 'q' is pressed or timer expires
    if 'q' in resp_key or phase_timer.getTime() < 0:
        #picks new schedule randomly
        p = choice(p_list)
        #store data
        phase += 1
        #resets phase timer
        phase_timer = CountdownTimer((session / phases) * 60)

    #finishes script if 'escape' pressed
    if 'escape' in resp_key:
Exemple #6
0
class Controller:
    def __init__(self, pars, display, logger, joystick):
        self.pars = pars
        self.display = display
        self.trialnum = 0
        self.score = 0
        self.end_task = False
        self.mark_event = logger
        self.joystick = joystick

    def open_trial(self):
        self.trialnum += 1
        self.result = ''
        self.pts_this_trial = 0
        self.trial_over = False
        self.target_is_on = False
        self.input_received = False
        self.no_response = False
        self.response_timer = None
        self.rt = float('NaN')
        self.data = []

        numtargs = np.prod(self.pars['grid'])
        self.which_target = np.random.randint(0, numtargs)
        self.onset_interval = np.random.uniform(self.pars['min_onset'],
                                                self.pars['max_onset'])
        self.is_nogo = np.random.rand() < self.pars['frac_nogo']
        if self.is_nogo:
            self.trial_type = 'no'
        else:
            self.trial_type = 'go'

        self.onset_countdown = CountdownTimer(self.onset_interval)
        self.mark_event('trial_start', channel=1)

    def run_trial(self):
        self.open_trial()

        while not self.trial_over:
            self.wait_for_input()

            if self.input_received:
                self.handle_input()
                self.display_outcome()
            else:
                self.handle_no_input()

            self.refresh()

        self.close_trial()

        return self.data

    def wait_for_input(self):
        pressed = []
        while True:
            self.present_target()
            pressed = event.getKeys(keyList=['left', 'right', 'escape'])
            if 'escape' in pressed:
                self.end_task = True
                break
            elif pressed or True in self.joystick.getAllButtons():
                self.input_received = True
                self.mark_event('responded', channel=3)
                break
            elif self.target_is_on and (self.response_timer.getTime() >
                                        self.pars['max_rt']):
                self.no_response = True
                self.mark_event('no_response', channel=4)
                break

    def present_target(self):
        if not self.target_is_on and self.onset_countdown.getTime() < 0:
            # rotate target into view
            self.display.onset(self.which_target, self.trial_type)
            self.target_is_on = True
            self.response_timer = Clock()
            self.mark_event('target on', channel=2)

        self.display.draw()

    def handle_input(self):
        if self.target_is_on:
            self.result = 'hit'
            self.trial_over = True
            self.rt = self.response_timer.getTime()

            self.correct = not self.is_nogo
            if self.correct:
                self.pts_this_trial = self.calculate_points(self.pars, self.rt)
                self.outcome_sound = self.display.cashsnd
            else:
                self.pts_this_trial = -self.pars['pts_per_correct']
                self.outcome_sound = self.display.buzzsnd

            self.outcome_delay = self.pars['disp_resp']

        else:
            self.result = 'premature'
            self.pts_this_trial = -self.pars['pts_per_correct']
            self.outcome_sound = self.display.firesnd
            self.outcome_delay = 0.3

        # remember to reset input
        self.input_received = False

    def handle_no_input(self):
        self.result = 'no response'
        self.correct = self.is_nogo
        self.trial_over = True

    def display_outcome(self):
        # update text onscreen
        self.display.set_target_text(self.which_target,
                                     str(self.pts_this_trial))
        self.score += self.pts_this_trial
        self.display.set_score(self.score)

        # refresh screen
        self.outcome_sound.play()
        self.mark_event('outcome', channel=5)

        # during static period, code between start and complete will run
        iti = StaticPeriod()
        iti.start(self.outcome_delay)
        self.display.draw()
        iti.complete()

        # remove text overlay on target
        self.display.set_target_text(self.which_target, '')

    def refresh(self):
        if self.target_is_on:
            self.display.offset(self.which_target)
            self.display.draw()

    def close_trial(self):
        # print to screen
        self.mark_event('trial_over', channel=8)
        print 'Trial {0:d}: Type {1}  Result: {2}  RT: {3:0.3g}  Correct: {4:d}  Points: {5:d}'.format(
            self.trialnum, self.trial_type, self.result, self.rt, self.correct,
            self.pts_this_trial)

    def calculate_points(self, pars, rt):
        return int(
            np.floor(pars['pts_per_correct'] *
                     np.exp(-(rt - pars['pts_offset']) / pars['pts_decay'])))
Exemple #7
0
 def callback(self, clock: core.Clock, stimuli: str) -> None:
     if self.first_time:
         self.timing = [stimuli, clock.getTime()]
         self.first_time = False
            lineWidth=5,
            pos=(+0.5, -0.6))

cbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
            lineWidth=5,
            pos=(0.0, -0.6))

#controls over experiment flow
#'q' - proceed to next phase prematurely
#'escape' - close window (with data saving and record about stopping)

#chained concurrent fixed-variable schedule (sampling with replacement)
while global_time.getTime() < session * 60 or score > 0:

    #checks of keyboard input
    resp_key = getKeys(['q', 'escape'])

    #proceeds to next phase if 'q' is pressed or timer expires
    if 'q' in resp_key or phase_timer.getTime() < 0:
        #picks new schedule randomly
        schedule = choice(schedule_list)
        #store data
        phase += 1
        #resets system values
        n1 = 0
        n2 = 0
        #resets phase timer
        phase_timer = CountdownTimer(phase_time * 60)
Exemple #9
0
expintro = TextStim(win,
                    text="""Practice Block \n\nPress any key to continue""",
                    wrapWidth=20,
                    units='deg',
                    pos=[0, 3],
                    height=1,
                    color='White')
meg = TextStim(win,
               text="""Click the circle to start.""",
               wrapWidth=20,
               units='deg',
               pos=[0, 3],
               height=1,
               color='White')

expStartTime = clock.getTime()
for condition in range(0, 3):
    if a[condition] == 0:
        megchoice = baseline
        cond = 'NO AID'
        startPracticeTrials = 1
        endPracticeTrials = 21
        megprac = TextStim(
            win,
            text=
            """Practice Block. \n\nUse the left mouse button to attempt production or the right mouse button to refrain from production.""",
            wrapWidth=25,
            units='deg',
            pos=[0, 8],
            height=1,
            color='White')
Exemple #10
0
def run_lextale():
    global trial_num, stim_text, stim_type, stim_status, incorrect, response, rt_start
    print("len(blck_itms):", len(lextale_items))
    maus = Mouse()
    instruction_page.setText(lextale_instructions)
    instruction_page.draw()
    ok_button.draw()
    ok_text.draw()
    win.flip()
    while not maus.isPressedIn(ok_button, buttons=[0]):
        pass

    stopwatch = Clock()
    for trial_num in range(
            len(lextale_items)):  # go through all stimuli of current block
        print("------- Trial number:", trial_num)
        stim_current = lextale_items[trial_num]
        stim_type = stim_current["dummy"]
        stim_text = stim_current["word"]
        stim_status = stim_current["wstatus"]

        center_disp.setText(stim_text)
        draw_labels()
        center_disp.draw()
        win.callOnFlip(stopwatch.reset)
        clearEvents()
        win.flip()
        while True:
            if maus.isPressedIn(right_bg, buttons=[0]):
                rt_start = stopwatch.getTime()
                response = 'yes'
                right_bg.fillColor = "darkgreen"
                draw_labels()
                center_disp.draw()
                win.flip()
                while maus.isPressedIn(right_bg, buttons=[0]):
                    pass
                right_bg.fillColor = "green"
                if stim_status == 1:
                    incorrect = 0
                    if stim_type == 0:
                        lextale_data[
                            'corr_word'] = lextale_data['corr_word'] + 1
                else:
                    incorrect = 1
                break
            elif maus.isPressedIn(left_bg, buttons=[0]):
                rt_start = stopwatch.getTime()
                response = 'no'
                left_bg.fillColor = "darkred"
                draw_labels()
                center_disp.draw()
                win.flip()
                while maus.isPressedIn(left_bg, buttons=[0]):
                    pass
                left_bg.fillColor = "red"
                if stim_status == 0:
                    incorrect = 0
                    if stim_type == 0:
                        lextale_data[
                            'corr_nonword'] = lextale_data['corr_nonword'] + 1
                else:
                    incorrect = 1
                break
            elif len(getKeys(keyList=[escape_key], timeStamped=stopwatch)) > 0:
                end_on_esc(escape_key)
                draw_labels()
                center_disp.draw()
                win.flip()
        add_resp()  # store trial data
    curr_smil = row['smiley']

    # Create and draw text/img
    stim_txt = TextStim(win, curr_word, pos=(0, 0.3))
    stim_img = ImageStim(
        win,
        curr_smil + '.png',
    )
    stim_img.size *= 0.5  # make a bit smaller

    # Initially, onset is undefined
    cond_df.loc[idx, 'onset'] = -1

    trial_clock.reset()
    kb.clock.reset()
    while trial_clock.getTime() < 2:
        # Draw stuff

        if trial_clock.getTime() < 0.5:
            stim_txt.draw()
            stim_img.draw()
        else:
            fix_target.draw()

        win.flip()
        if cond_df.loc[idx, 'onset'] == -1:
            cond_df.loc[idx, 'onset'] = clock.getTime()

        # Get responses
        resp = kb.getKeys()
        if resp:
Exemple #12
0
class Controller:

    def __init__(self, pars, display, logger, joystick):
        self.pars = pars
        self.display = display
        self.trialnum = 0
        self.score = 0
        self.end_task = False
        self.mark_event = logger
        self.joystick = joystick

    def open_trial(self):
        self.trialnum += 1
        self.result = ''
        self.pts_this_trial = 0
        self.trial_over = False
        self.target_is_on = False
        self.input_received = False
        self.no_response = False
        self.response_timer = None
        self.rt = float('NaN')
        self.data = []

        numtargs = np.prod(self.pars['grid'])
        self.which_target = np.random.randint(0, numtargs)
        self.onset_interval = np.random.uniform(self.pars['min_onset'],
                                                self.pars['max_onset'])
        self.is_nogo = np.random.rand() < self.pars['frac_nogo']
        if self.is_nogo:
            self.trial_type = 'no'
        else:
            self.trial_type = 'go'

        self.onset_countdown = CountdownTimer(self.onset_interval)
        self.mark_event('trial_start', channel=1)

    def run_trial(self):
        self.open_trial()

        while not self.trial_over:
            self.wait_for_input()

            if self.input_received:
                self.handle_input()
                self.display_outcome()
            else:
                self.handle_no_input()

            self.refresh()

        self.close_trial()

        return self.data

    def wait_for_input(self):
        pressed = []
        while True:
            self.present_target()
            pressed = event.getKeys(keyList=['left', 'right', 'escape'])
            if 'escape' in pressed:
                self.end_task = True
                break
            elif pressed or (self.joystick and True in
                self.joystick.getAllButtons()):
                self.input_received = True
                self.mark_event('responded', channel=3)
                break
            elif self.target_is_on and (self.response_timer.getTime() > self.pars['max_rt']):
                self.no_response = True
                self.mark_event('no_response', channel=4)
                break

    def present_target(self):
        if not self.target_is_on and self.onset_countdown.getTime() < 0:
            # rotate target into view
            self.display.onset(self.which_target, self.trial_type)
            self.target_is_on = True
            self.response_timer = Clock()
            self.mark_event('target on', channel=2)

        self.display.draw()

    def handle_input(self):
        if self.target_is_on:
            self.result = 'hit'
            self.trial_over = True
            self.rt = self.response_timer.getTime()

            self.correct = not self.is_nogo
            if self.correct:
                self.pts_this_trial = self.calculate_points(self.pars,
                                                            self.rt)
                self.outcome_sound = self.display.cashsnd
            else:
                self.pts_this_trial = -self.pars['pts_per_correct']
                self.outcome_sound = self.display.buzzsnd

            self.outcome_delay = self.pars['disp_resp']

        else:
            self.result = 'premature'
            self.pts_this_trial = -self.pars['pts_per_correct']
            self.outcome_sound = self.display.firesnd
            self.outcome_delay = 0.3

        # remember to reset input
        self.input_received = False

    def handle_no_input(self):
        self.result = 'no response'
        self.correct = self.is_nogo
        self.trial_over = True

    def display_outcome(self):
        # update text onscreen
        self.display.set_target_text(self.which_target,
                                     str(self.pts_this_trial))
        self.score += self.pts_this_trial
        self.display.set_score(self.score)

        # refresh screen
        self.outcome_sound.play()
        self.mark_event('outcome', channel=5)

        # during static period, code between start and complete will run
        iti = StaticPeriod()
        iti.start(self.outcome_delay)
        self.display.draw()
        iti.complete()

        # remove text overlay on target
        self.display.set_target_text(self.which_target, '')

    def refresh(self):
        if self.target_is_on:
            self.display.offset(self.which_target)
            self.display.draw()

    def close_trial(self):
        # print to screen
        self.mark_event('trial_over', channel=8)
        print 'Trial {0:d}: Type {1}  Result: {2}  RT: {3:0.3g}  Correct: {4:d}  Points: {5:d}'.format(self.trialnum, self.trial_type, self.result, self.rt, self.correct, self.pts_this_trial)

    def calculate_points(self, pars, rt):
        return int(np.floor(pars['pts_per_correct'] * np.exp(
            -(rt - pars['pts_offset']) / pars['pts_decay'])))
Exemple #13
0
def mainLoop(blocks=1, trialNumber=216):

    #global blockCount
    blockCount = 0

    trialCount = 0
    timer = Clock()

    maskDelay = delayForMask

    #make finalItems which will be reused for every block
    generatedItems = finalItems(blocks)
    itemsForDisplay = generatedItems

    #main trial loop runns for n-blocks
    for block in range(blocks):

        #f' is the python3 equivalent of "something{}something.format()" function for python2
        betweenBlocksInfo = (
            f'Der {blockCount}. Block ist nun vorbei, wenn Sie möchten können Sie eine kurze Pause machen.\n\
        \n\
        Fortfahren mit "Leertaste".')

        if blockCount == blocks - 1 and blockCount > 0:
            TextStim(win, (
                f'Der {blockCount}. Block ist nun vorbei, wenn Sie möchten können Sie eine kurze Pause machen. Nun folgt der letzte Durchgang.\n\
            \n\
Fortfahren mit "Leertaste".'),
                     units='norm',
                     pos=(0.0, 0.0)).draw()
            win.flip()
            waitKeys(keyList=['space'])
        elif blockCount > 0:
            TextStim(win, betweenBlocksInfo, units='norm',
                     pos=(0.0, 0.0)).draw()
            win.flip()
            waitKeys(keyList=['space'])

        fixationCross.draw()
        win.flip()
        wait(0.6)
        win.flip()

        blockCount = block + 1

        #loop run for n-trials
        for trial in range(trialNumber):
            if itemsForDisplay[trial]['itemInfo'][
                    'side'] == -1 and itemsForDisplay[trial]['itemInfo'][
                        'first'] == 1:
                corr = -1
            elif itemsForDisplay[trial]['itemInfo'][
                    'side'] == 1 and itemsForDisplay[trial]['itemInfo'][
                        'first'] == 1:
                corr = 1
            elif itemsForDisplay[trial]['itemInfo'][
                    'side'] == -1 and itemsForDisplay[trial]['itemInfo'][
                        'first'] == 0:
                corr = 1
            elif itemsForDisplay[trial]['itemInfo'][
                    'side'] == 1 and itemsForDisplay[trial]['itemInfo'][
                        'first'] == 0:
                corr = -1

            timeDelayBetweenNames = itemsForDisplay[trial]['itemInfo']['delay']

            timer.reset()
            time1 = timer.getTime()
            intertDelay = 0

            trialCount += 1

            waitDuration = StaticPeriod(screenHz=60)
            d = interTrialDelay()
            print('interTrialDelay: ', d)
            t1 = clock.getTime()

            if timeDelayBetweenNames != 0.0:
                waitDuration.start(d)

                nameToDrawFirst = itemsForDisplay[trial]['firstName']
                nameToDrawSecond = itemsForDisplay[trial]['secondName']
                if expVersion == 1:
                    mask1 = itemsForDisplay[trial]['firstMask']
                    mask2 = itemsForDisplay[trial]['secondMask']
                    maskStimuli = [mask1, mask2]

                stimuli = [nameToDrawFirst, nameToDrawSecond]

                intertDelay += d

                print('delay should be: ', timeDelayBetweenNames)

                nameToDrawFirst.draw()

                waitDuration.complete()
                print('1. loop dur: ', clock.getTime() - t1)

                win.flip()
                t1 = clock.getTime()

                w1 = clock.getTime()
                waitDuration.start(timeDelayBetweenNames)
                for s in stimuli:
                    s.draw()
                waitDuration.complete()
                print('2. loop dur: ', clock.getTime() - w1)

                win.flip()
                realTimeDelay = clock.getTime() - t1
                print('effective time delay: ', realTimeDelay)

                if expVersion == 1:
                    waitDuration.start(maskDelay)
                    for m in maskStimuli:
                        m.draw()
                    waitDuration.complete()
                    win.flip()

            else:
                waitDuration.start(d)

                nameToDrawFirst = itemsForDisplay[trial]['firstName']
                nameToDrawSecond = itemsForDisplay[trial]['secondName']

                if expVersion == 1:
                    mask1 = itemsForDisplay[trial]['firstMask']
                    mask2 = itemsForDisplay[trial]['secondMask']
                    maskStimuli = [mask1, mask2]

                stimuli = [nameToDrawFirst, nameToDrawSecond]

                print('delay should be: ', timeDelayBetweenNames)

                for s in stimuli:
                    s.draw()
                waitDuration.complete()
                realTimeDelay = 0
                win.flip()

                print('effective time delay: ', realTimeDelay)

                if expVersion == 1:
                    waitDuration.start(maskDelay)
                    for m in maskStimuli:
                        m.draw()
                    waitDuration.complete()
                    win.flip()

            #start response record
            responseStart = clock.getTime()

            #wait a specific amount of time for the keypress
            pressedKey = waitKeys(
                keyList=['f', 'j', 'space',
                         quitkey])  #escape for quiting the experiment

            #below just for simulating persons
            #            pressedKey = random.choice(['f','j','space'])
            #            wait(0.2)

            #end response clock
            responseEnd = clock.getTime()

            #calculate response time
            RT = responseEnd - responseStart

            if pressedKey == None:
                pass
            elif quitkey in pressedKey:
                quit()
            print('response time: ', RT)

            correct = 0

            #if-else statements for 'possible' feedback and response recording
            if pressedKey == None:
                correct = 0
            elif itemsForDisplay[trial]['itemInfo']['delay'] == 0.0:
                correct = -2  #with 0 delay there cannot be a correct answer
            elif 'f' in pressedKey and corr == 1:
                print('incorrect')
                correct = 0
            elif 'j' in pressedKey and corr == -1:
                print('incorrect')
                correct = 0
            elif 'f' in pressedKey and corr == -1:
                print('correct')
                correct = 1
            elif 'j' in pressedKey and corr == 1:
                print('correct')
                correct = 1
            elif 'space' in pressedKey:
                correct = -1  # -1 then means didnt know

            win.flip()
            d = interTrialDelay()
            print('interTrialDelay: ', d)
            intertDelay += d
            wait(d)
            fixationCross.draw()
            win.flip()

            #aand again save the current trials while waiting the inter-trial duration instead of doing nothing
            d = interTrialDelay()
            print('interTrialDelay: ', d)
            t1 = clock.getTime()
            waitDuration.start(d)
            intertDelay += d
            interTrialDuration = intertDelay
            trialDuration = timer.getTime() - time1 + d

            #what is saved:
            #name class
            #if garbled or not
            #left name
            #right name
            #intended time delay
            #real time delay
            #which name was displayed first
            #response time
            #if the response was correct
            #person ID, first name, last name, country, adress

            if itemsForDisplay[trial]['itemInfo']['side'] == -1:
                leftName = itemsForDisplay[trial]['itemInfo']['unfamWord']
                rightName = itemsForDisplay[trial]['itemInfo']['famWord']
                leftNameType = 'unfamiliar'
                rightNameType = 'familiar'
            else:
                leftName = itemsForDisplay[trial]['itemInfo']['famWord']
                rightName = itemsForDisplay[trial]['itemInfo']['unfamWord']
                leftNameType = 'familiar'
                rightNameType = 'unfamiliar'

            if itemsForDisplay[trial]['itemInfo']['first'] == 1:
                firstNameType = 'unfamiliar'
            else:
                firstNameType = 'familiar'

            if os.path.isfile(f'exp_degrade_{person.id}_{startDate}.txt'):
                with open(f'exp_degrade_{person.id}_{startDate}.txt',
                          'a') as file:
                    file.write('\t'.join([itemsForDisplay[trial]['itemInfo']['class'],str(itemsForDisplay[trial]['itemInfo']['garbled']),leftName ,\
                    rightName , leftNameType, rightNameType, str(itemsForDisplay[trial]['itemInfo']['delay']) , str(realTimeDelay), \
                    nameToDrawFirst.text.replace('%',''), firstNameType , str(RT) , str(pressedKey) ,str(correct) , str(blockCount) , str(trialCount) , person.id ,\
                    str(trialDuration), str(interTrialDuration)])+ '\n')

            else:
                with open(f'exp_degrade_{person.id}_{startDate}.txt',
                          'w+') as file:
                    file.write(
                        'class\tgarbled\tleft Name\tright Name\tleftNameType\trightNameType\tintendedTimeDelay\trealTimeDelay\t\
nameShowedFirst\tfirstNameType\tresponseTime\tpressedKey\tcorrectAnswer\tblock\ttrial\tID\ttrialDuration\tinterTrialDuration'
                        + '\n')
                with open(f'exp_degrade_{person.id}_{startDate}.txt',
                          'a') as file:
                    file.write('\t'.join([itemsForDisplay[trial]['itemInfo']['class'],str(itemsForDisplay[trial]['itemInfo']['garbled']),leftName ,\
                    rightName , leftNameType, rightNameType, str(itemsForDisplay[trial]['itemInfo']['delay']) , str(realTimeDelay), \
                    nameToDrawFirst.text.replace('%',''), firstNameType , str(RT) , str(pressedKey) ,str(correct) , str(blockCount) , str(trialCount) , person.id ,\
                    str(trialDuration), str(interTrialDuration)])+ '\n')

            waitDuration.complete()
            print('3. loop dur: ', clock.getTime() - t1)

            win.flip()

            print('trialDuration: ', trialDuration)

    endTime = expTime.getTime() - startTime
    #write person demographics
    with open(f'exp_degrade_{person.id}_{startDate}.txt', 'a') as file:
        file.write(' '.join(['experiment Duration: ', str(endTime),' ID: ',person.id,' first name: ',person.first,\
    ' last name: ',person.last,' country: ',person.country,\
    ' adress: ',person.adress,' birhtday: ',person.adress,' animal: ',person.animal]))

    TextStim(win,
             AppEndText,
             font='Calibri',
             units='norm',
             pos=(0, 0),
             height=0.08,
             wrapWidth=0.9).draw()
    win.flip()
    waitKeys(keyList=['escape'])
Exemple #14
0
demographicsWindow.addField('adress of your childhood: ', 'Huberstria Street')
demographicsWindow.addField('birthday - (e.g.: JAN 15): ', 'JAN 15')
demographicsWindow.addField('favorite animal: ', 'OCTOPUS')
demographicsWindow.addField('age: ', 35)
#0 is degrade 1 is masked
demographicsWindow.addField('version', '0')

demographics = demographicsWindow.show()

if demographicsWindow.OK:
    personInfo = demographics
else:
    print('user cancel')

expTime = Clock()
startTime = expTime.getTime()
startDate = datetime.now().strftime("%Y%m%d%H%M")


class person:
    pass


person.id = demographics[0]
person.first = demographics[1].upper()
person.last = demographics[2].upper()
person.country = demographics[3].upper()
person.adress = demographics[4].upper()
person.birth = demographics[5].upper()
person.animal = demographics[6].upper()
person.age = demographics[7]
Exemple #15
0
            lineColor='red',
            lineWidth=5,
            pos=(-0.5, -0.6))
rbox = Rect(win=win,
            width=0.3,
            height=0.3,
            lineColor='red',
            lineWidth=5,
            pos=(+0.5, -0.6))

#controls over experiment flow
#'q' - proceed to next phase prematurely
#'escape' - close window (with data saving and record about stopping)

#concurrent fixed-variable schedule
while global_time.getTime() < session * 60:
    #draws click boxes
    lbox.draw()
    rbox.draw()

    #check of keyboard input
    resp_key = getKeys(['q', 'escape'])

    #proceed to next phase if 'q' is pressed or timer expires
    if 'q' in resp_key or phase_timer.getTime() < 0:
        #picks new schedule randomly
        schedule = choice(schedule_list)
        #store data
        phase += 1
        #reset system values
        T1 = CountdownTimer(0)