예제 #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()
예제 #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()
예제 #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")
예제 #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")
예제 #5
0
파일: clock.py 프로젝트: jzeitoun/pacu-src
 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.')
예제 #6
0
    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)
예제 #7
0
    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)
예제 #8
0
                    fullscr=True,
                    screen=0,
                    allowGUI=False,
                    allowStencil=False,
                    monitor='testMonitor',
                    color='black',
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='norm')

session, phases = 30, 120
R1, R2, score, phase, zeros, ones = 0, 0, 0, 0, 0, 0
lpressed, rpressed = False, False
mouse = Mouse()
stimuli_timer = CountdownTimer(0)
phase_timer = CountdownTimer(0)
global_time = Clock()
p_list = [0.25, 0.75]

data = []  #array for data
data.append(['time', 'R1', 'R2', 'score', 'number', 'zeros', 'ones',
             'p'])  #column names in csv file

#displayed text
text = TextStim(win=win, pos=(0, 0), text=' ')

#defines click boxes
lbox = Rect(win=win,
            width=0.3,
            height=0.3,
예제 #9
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'])))
#system settings (session duration, interval length and size of COD)
session = 60  #minutes
phase_time = session / 6
COD = 5
schedule_list = ['ConcChFR20VI5/FR20FI5',
                 'ConcChFR20FI5/FR20VI5']  #where random schedule is located
interval = 5
ratio = 20
link_time = 100
initial = False

#initialization
#counts time from the start of reinforcement
global_time = Clock()
#timers for the schedule of reinforcement
interval_timer = CountdownTimer(0)
phase_timer = CountdownTimer(0)
link_timer = CountdownTimer(0)
#tracks responses
lpressed, rpressed, cpressed = False, False, False
mouse = Mouse()
R1, n1 = 0, 0  #tracks responses from left and prevents changeovers
R2, n2 = 0, 0  #tracks responses from right
R3 = 0  #tracks responses from center
#tracks consequences
Cs1, Cs2, Cs3, score = 0, 0, 0, 500
#tracks experiment
phase = 0  #how many different conditions introduced

data = []  #array for data
data.append([
  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)
예제 #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'])))
예제 #13
0
파일: trial.py 프로젝트: jzeitoun/pacu-src
 def start(self):
     self.getTime = CountdownTimer(self.duration).getTime
     return self
예제 #14
0
 def start(self):
     self.getTime = CountdownTimer(self.duration).getTime
     self.stimulus.window.flip()
     return self
예제 #15
0
                    useFBO=True,
                    units='norm')

#system settings (session duration, interval length and size of COD)
session = 60  #minutes
phase_time = session / 6
COD = 5
schedule_list = ['ConcVI15FI15',
                 'ConcFI15VI15']  #where random schedule is located
interval = 15

#initialization
#counts time from the start of reinforcement
global_time = Clock()
#timers for the schedule of reinforcement
T1, T2 = CountdownTimer(0), CountdownTimer(0)
phase_timer = CountdownTimer(0)
#tracks responses
lpressed, rpressed = False, False
mouse = Mouse()
R1, n1 = 0, 0  #tracks responses from left and prevents changeovers
R2, n2 = 0, 0  #tracks responses from right
#tracks consequences
Rf1, Rf2, score = 0, 0, 0
#tracks experiment
phase = 0  #how many different conditions introduced

data = []  #array for data
data.append(['time', 'R1', 'R2', 'Rf1', 'Rf2', 'phase',
             'schedule'])  #column names in csv file