Esempio n. 1
0
def testStaticPeriod():
    static = StaticPeriod()
    static.start(0.1)
    wait(0.05)
    assert static.complete() == 1
    static.start(0.1)
    wait(0.11)
    assert static.complete() == 0

    win = Window(autoLog=False)
    static = StaticPeriod(screenHz=60, win=win)
    static.start(.002)
    assert win.recordFrameIntervals == False
    static.complete()
    assert static._winWasRecordingIntervals == win.recordFrameIntervals
    win.close()

    # Test if screenHz parameter is respected, i.e., if after completion of the
    # StaticPeriod, 1/screenHz seconds are still remaining, so the period will
    # complete after the next flip.
    refresh_rate = 100.0
    period_duration = 0.1
    timer = CountdownTimer()
    win = Window(autoLog=False)

    static = StaticPeriod(screenHz=refresh_rate, win=win)
    static.start(period_duration)
    timer.reset(period_duration)
    static.complete()

    assert np.allclose(timer.getTime(), 1.0 / refresh_rate, atol=0.001)
    win.close()
Esempio n. 2
0
def testStaticPeriod():
    static = StaticPeriod()
    static.start(0.1)
    wait(0.05)
    assert static.complete()==1
    static.start(0.1)
    wait(0.11)
    assert static.complete()==0

    win = Window(autoLog=False)
    static = StaticPeriod(screenHz=60, win=win)
    static.start(.002)
    assert win.recordFrameIntervals == False
    static.complete()
    assert static._winWasRecordingIntervals == win.recordFrameIntervals
    win.close()

    # Test if screenHz parameter is respected, i.e., if after completion of the
    # StaticPeriod, 1/screenHz seconds are still remaining, so the period will
    # complete after the next flip.
    refresh_rate = 100.0
    period_duration = 0.1
    timer = CountdownTimer()
    win = Window(autoLog=False)

    static = StaticPeriod(screenHz=refresh_rate, win=win)
    static.start(period_duration)
    timer.reset(period_duration )
    static.complete()

    assert np.allclose(timer.getTime(),
                       1.0/refresh_rate,
                       atol=0.001)
    win.close()
Esempio n. 3
0
def testCountdownTimer():
    try:
        cdt = CountdownTimer(5.0)

        assert cdt.getTime() <= 5.0
        assert cdt.getTime() >= 4.75

        time.sleep(cdt.getTime())

        assert np.fabs(cdt.getTime()) < 0.1

        printf(">> CountdownTimer Test: PASSED")

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

    printf("-------------------------------------\n")
Esempio n. 4
0
def test_CountdownTimer():
    try:
        cdt = CountdownTimer(5.0)

        assert cdt.getTime() <= 5.0
        assert cdt.getTime() >= 4.75

        time.sleep(cdt.getTime())

        assert np.fabs(cdt.getTime()) < 0.1

        printf(">> CountdownTimer Test: PASSED")

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

    printf("-------------------------------------\n")
Esempio n. 5
0
 def synchronize(self, stimulus):
     logging.msg('Await a signal from Labjack in {} sec...'.format(
         self.component.timeout))
     logging.flush()
     for i in range(self.component.timeout, 0, -1):
         timer = CountdownTimer(1)
         msg = 'Await a signal from LabJack in {} sec...'.format(i)
         stimulus.flip_text(msg)
         while timer.getTime() > 0:
             if event.getKeys('escape'):
                 raise UserAbortException()
             if self.u3.get_counter():
                 logging.msg('counter increased')
                 logging.flush()
                 # self.instance.reset_timer()
                 return
     else:  # timeout...
         raise TimeoutException('Could not catch any signal from LabJack.')
Esempio n. 6
0
            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:
        break

    if stimuli_timer.getTime() < 0:
        number = binomial(1, p)
        if number == 0:
            zeros += 1
Esempio n. 7
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'])))
            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)
        link_timer = CountdownTimer(link_time)

    #finishes script if 'escape' pressed
    if 'escape' in resp_key:
        break
  def run(self):
    mainTimer = getTime
    self.__appInterface.displayInstructions()

    totalTestTimer = CountdownTimer(TOTAL_TEST_DURATION)
    inbetweenSessionCountdown = CountdownTimer(TEST_BLOCK_DURATION)
    
    while totalTestTimer.getTime() > 0:
      presentedItems = filter(lambda x: len(x.presentations) > 0, self.__stimuli)
      
      stimulus = None
      minActivationStimulus = None
      if len(presentedItems) > 0:
        # Select item from presented items with activation <= ACTIVATION_THRESHOLD_RETEST
        predictionTime = mainTimer() + ACTIVATION_PREDICTION_TIME_OFFSET
        minActivation, minActivationStimulus = min([(calculateActivation(s, predictionTime), s) for s in presentedItems], key=lambda x: x[0])
        if minActivation <= ACTIVATION_THRESHOLD_RETEST:
          stimulus = minActivationStimulus
      if not stimulus:
        # None under that threshold? Add a new item if possible
        if len(presentedItems) < len(self.__stimuli):
          stimulus = self.__stimuli[len(presentedItems)]
      if not stimulus:
        stimulus = minActivationStimulus
      if not stimulus:
        raise ValueError("Could not select any stimulus for presentation")

      #print "Presented items:\n  ", "\n  ".join([str((calculateActivation(s, predictionTime), s.name, s.alpha, map(str, s.presentations))) for s in presentedItems])

      newPresentation = WordItemPresentation()
      presentationStartTime = mainTimer()
      newPresentation.decay = calculateNewDecay(stimulus, presentationStartTime)

      if len(stimulus.presentations) == 0:
        # First presentation of stimulus
        self.__appInterface.learn(stimulus.image, stimulus.name, stimulus.translation)
      else:
        # Second presentations of stimulus
        response = self.__appInterface.test(stimulus.name)
        
        if response.lower() == stimulus.translation.lower():
          self.currentScore += CORRECT_ANSWER_SCORE
          self.__appInterface.updateHighscore(self.currentScore)
          self.__appInterface.displayCorrect(response, stimulus.translation)
          repeat = False
        else:
          stimulus.alpha += ALPHA_ERROR_ADJUSTMENT_SUMMAND
          newPresentation.decay = calculateNewDecay(stimulus, presentationStartTime)
          
          mixedUpWord = self.findMixedUpWord(response)
          if mixedUpWord:
            self.__appInterface.mixedup(stimulus.name, stimulus.translation, mixedUpWord.name, mixedUpWord.translation)
          else:
            self.__appInterface.displayWrong(response, stimulus.translation, stimulus.image)

      newPresentation.time = presentationStartTime
      stimulus.presentations.append(newPresentation)
      
      if inbetweenSessionCountdown.getTime() <= 0:
        imageWordPairs = {}
        imageSequence = []
        for stimulus in self.__stimuli:
          if stimulus.presentations:
            translationData = (stimulus.name, stimulus.translation)
            if stimulus.image in imageWordPairs:
              imageWordPairs[stimulus.image].append(translationData)
            else:
              imageWordPairs[stimulus.image] = [translationData]
              imageSequence.append(stimulus.image)
        
        self.__appInterface.startInbetweenSession([(image, imageWordPairs[image]) for image in imageSequence])
        inbetweenSessionCountdown = CountdownTimer(TEST_BLOCK_DURATION)
Esempio n. 10
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'])))
Esempio n. 11
0
#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)
        T2 = CountdownTimer(0)
        n1 = 0
        n2 = 0
        #reset phase timer
        phase_timer = CountdownTimer(phase_time * 60)

    #process left schedule
    if mouse.isPressedIn(lbox, buttons=[0]):
        lpressed = True