示例#1
0
def run():
    env = gym.make('CartPole-v0')
    env._max_episode_steps = None

    state_size = env.observation_space.shape[0]
    action_size = env.action_space.n
    agent = HRL(state_size, action_size)

    horizon = 20

    for e in range(agent.episodes):
        state = torch.tensor(env.reset(), dtype=torch.float)
        goal = torch.tensor([0.0, 0.0, 0.0, 0.0], dtype=torch.float)
        score = 0

        # Rollout
        for t in range(horizon):
            score += 1
            env.render()
            action = agent.act(state, goal,
                               torch.tensor([horizon - t], dtype=torch.float))
            next_state, _, done, _ = env.step(action)
            agent.remember(state, action, next_state, None, None, done)
            agent.augment_goals(state, action, next_state, done)
            state = next_state
            if done:
                print("episode: {}/{}, score: {}, e: {:.2}".format(
                    e, agent.episodes, score, agent.epsilon))
                break

        # Perform optimization
        for _ in range(agent.n):
            agent.replay()
示例#2
0
文件: verify.py 项目: TUBvision/hrl
def verify(args):

    args = prsr.parse_args(args)

    wdth = 1024
    hght = 768

    # Initializing HRL

    flnm = args.flnm
    flds = ['Intensity'] + [ 'Luminance' + str(i) for i in range(args.nsmps) ]

    graphics = 'datapixx'
    inputs = 'keyboard'
    photometer = args.photometer
    lut = args.lut

    bg = args.bg

    fs = True

    hrl = HRL(graphics=graphics,inputs=inputs,photometer=photometer
            ,wdth=wdth,hght=hght,bg=bg,rfl=flnm,rhds=flds,fs=fs,lut=lut,scrn=1)

    itss = np.linspace(args.mn,args.mx,args.stps)
    if args.rndm: shuffle(itss)
    if args.rvs: itss = itss[::-1]

    (pwdth,phght) = (wdth*args.sz,hght*args.sz)
    ppos = ((wdth - pwdth)/2,(hght - phght)/2)
    print pwdth
    print ppos
    print phght

    done = False

    for its in itss:

        hrl.results['Intensity'] = its

        ptch = hrl.graphics.newTexture(np.array([[its]]))
        ptch.draw(ppos,(pwdth,phght))
        hrl.graphics.flip()

        print 'Current Intensity:', its
        smps = []
        for i in range(args.nsmps):
            smps.append(hrl.photometer.readLuminance(5,args.slptm))

        for i in range(len(smps)):
            hrl.results['Luminance' + str(i)] = smps[i]

        hrl.writeResultLine()

        if hrl.inputs.checkEscape(): break

    # Experiment is over!
    hrl.close()
示例#3
0
文件: shiftsin.py 项目: TUBvision/hrl
def main():
    wdth = 1024
    hght = 768
    args = prsr.parse_args()

    # Initializations

    hrl = HRL(wdth,hght,0,dpx=True,ocal=True,fs=True)
    hrl = HRL(wdth,hght,0,coords=(0,1,0,1),flipcoords=False,dpx=True,ocal=True,fs=True)

    pwdth,phght = int(wdth*args.sz),int(hght*args.sz)
    ppos = ((wdth - pwdth)/2,(hght - phght)/2)

    wv1 = np.array([ [round((np.sin(x*np.pi*2) + 1)/2)] for x in
                       np.linspace(0,args.scyc,phght) ])

    wv2 = np.array([ [round((np.sin(x*np.pi*2 + np.pi) + 1)/2)] for x in
                       np.linspace(0,args.scyc,phght) ])

    ptch1 = hrl.newTexture(wv1)
    ptch2 = hrl.newTexture(wv2)

    slptm = int(1000.0 / args.tfrq)

    for i in range(args.ncyc):

        ptch1.draw(ppos,(pwdth,phght))
        hrl.flip()

        pg.time.wait(slptm)

        ptch2.draw(ppos,(pwdth,phght))
        hrl.flip()

        pg.time.wait(slptm)

        if hrl.checkEscape(): break

# Experiment is over!
    hrl.close()
示例#4
0
def main():

    hrl = HRL(graphics='datapixx',
              inputs='responsepixx',
              photometer=None,
              wdth=WIDTH,
              hght=HEIGHT,
              bg=0.27,
              scrn=1,
              lut='lut.csv',
              db=False,
              fs=True)

    # loop over design
    # ================
    for trl in np.arange(start_trl, end_trl):
        run_trial(hrl, trl, start_trl,
                  end_trl)  # function that executes the experiment

    hrl.close()
    print "Session complete"
    rfl.close()
示例#5
0
def main():
    wdth = 1024
    hght = 768
    flds = ['Intensity','Luminance']
    args = prsr.parse_args()
    flnm = 'results/' + args.flnm

    hrl = HRL(wdth,hght,0,coords=(0,1,0,1),flipcoords=False,dpx=True,ocal=True,rfl=flnm,rhds=flds,fs=True)
    # Initializations

    ptch = hrl.newTexture(np.array([[args.lm]]))
    pwdth,phght = wdth*args.sz,hght*args.sz
    ppos = ((wdth - pwdth)/2,(hght - phght)/2)

    if args.rnd: rnd = round
    else: rnd = lambda x: x

    nitss = int(args.tmprs/args.bfrq)
    itss = [ args.bamp * rnd((1 + np.sin(2*np.pi*x)) / 2) + ((1-args.bamp)/2)
            for x in np.linspace(0,1,nitss) ]
    tsts = [ n % (nitss / args.sfrq) == 0 for n in range(nitss) ]
    cycl = zip(itss,tsts)
    slptm = int(1000.0 / args.tmprs)

    def opticalRead(its):
        print 'Current Intensity:', its
        lm = hrl.readLuminance(1,0)
        hrl.rmtx['Intensity'] = its
        hrl.rmtx['Luminance'] = lm
        hrl.writeResultLine()

    for (its,tst) in cycl * args.ncyc:

        hrl.changeBackground(its)
        ptch.draw(ppos,(pwdth,phght))
        hrl.flip()

        pg.time.wait(slptm)

        if tst:
            prcs = Process(target=opticalRead,args=(its,))
            prcs.start()

        if hrl.checkEscape(): break

    # Experiment is over!
    hrl.close
示例#6
0
def main():
    # determine design and result file name
    try:
        (design_fn, result_fn, completed_trials, total_trials, check_fn) = prepare_files()
    except EndExperiment:
        return 0
    result_headers = ['Trial', 'adaptor_type', 'coaxial_lum', 'test_lum',
                      'match_lum', 'flank_lum', 'test_loc', 'grating_ori',
                      'response_time', 'match_initial', 'adaptor_shift']
    global hrl
    hrl = HRL(graphics='datapixx',
              inputs='responsepixx',
              photometer=None,
              wdth=1024,
              hght=768,
              bg=0.5,
              dfl=design_fn,
              rfl=result_fn,
              rhds=result_headers,
              scrn=1,
              lut='lut0to88.csv',
              db = False,
              fs=True)

    # monkey patch to use non-blocking readButton function
    # should be removed once hrl.inputs.readButton is fixed
    hrl.inputs.readButton = lambda to: waitButton(hrl.datapixx, to)

    # set the bar width of the grating. this value determines all positions
    global bar_width
    bar_width = 38
    y_border = 768 // 2 - int(6 * bar_width)
    x_border = (1024 - 6 * bar_width) // 2
    # the coordinates of the four possible test check positions
    # test coordinates are (y,x) position within the grating array
    global test_coords
    test_coords = ((bar_width * 3, bar_width * 2),
                   (bar_width * 3, bar_width * 3),
                   (bar_width * 4, bar_width * 2),
                   (bar_width * 4, bar_width * 3))
    # match coordinates are (x,y) screen positions
    global match_coords
    match_coords = ((x_border + bar_width * 2, 384 + int(bar_width * 2)),
                    (x_border + bar_width * 3, 384 + int(bar_width * 2)),
                    (x_border + bar_width * 2, 384 + int(bar_width * 1)),
                    (x_border + bar_width * 3, 384 + int(bar_width * 1)))
    global match_bg_loc
    match_bg_loc = (x_border, 384)
    global stim_loc
    stim_loc = (x_border, y_border)

    # prepare fixation mark textures
    global fix_inner
    fix_inner = hrl.graphics.newTexture(np.ones((1,1)) * .5, 'circle')
    global fix_outer
    fix_outer = hrl.graphics.newTexture(np.zeros((1,1)), 'circle')

    # prepare confirmation texture
    global confirmation
    confirmation = hrl.graphics.newTexture(draw_text('Weiter?', bg=.5))

    # show instruction screen
    if completed_trials == 0:
        for i in range(6):
            instructions = plt.imread('instructions%d.png' % (i + 1))[..., 0]
            instructions = hrl.graphics.newTexture(instructions)
            instructions.draw((0, 0))
            hrl.graphics.flip(clr=True)
            btn = None
            while btn != 'Space':
                btn, _ = hrl.inputs.readButton(to=3600)

        # show test trials
        test_dsgn = [{'adaptor_type': 'none',
                      'grating_ori': 'horizontal',
                      'grating_vals': '0.45,0.55',
                      'test_loc': '0',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'vertical',
                      'grating_ori': 'horizontal',
                      'grating_vals': '0.55,0.45',
                      'test_loc': '1',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'horizontal',
                      'grating_ori': 'horizontal',
                      'grating_vals': '0.45,0.55',
                      'test_loc': '2',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'vertical',
                      'grating_ori': 'vertical',
                      'grating_vals': '0.55,0.45',
                      'test_loc': '2',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'none',
                      'grating_ori': 'vertical',
                      'grating_vals': '0.45,0.45',
                      'test_loc': '1',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'vertical_shifted',
                      'grating_ori': 'vertical',
                      'grating_vals': '0.55,0.45',
                      'test_loc': '2',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'none',
                      'grating_ori': 'vertical',
                      'grating_vals': '0.55,0.55',
                      'test_loc': '1',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'horizontal_shifted',
                      'grating_ori': 'vertical',
                      'grating_vals': '0.45,0.55',
                      'test_loc': '1',
                      'test_lum': '0.5'},
                     {'adaptor_type': 'horizontal',
                      'grating_ori': 'vertical',
                      'grating_vals': '0.45,0.55',
                      'test_loc': '3',
                      'test_lum': '0.5'}]
        for dsgn in test_dsgn:
            run_trial(dsgn)

    # show experiment start confirmation
    hrl.graphics.flip(clr=True)
    lines = [u'Die Probedurchgänge sind fertig.',
        u'Wenn du bereit bist, drücke die mittlere Taste.',
        u' ',
        u'Wenn du noch Fragen hast, oder mehr Probedurchgänge',
        u'machen willst, wende dich an den Versuchsleiter.']
    for line_nr, line in enumerate(lines):
        textline = hrl.graphics.newTexture(draw_text(line, fontsize=36))
        textline.draw(((1024 - textline.wdth) / 2,
                       (768 / 2 - (3 - line_nr) * (textline.hght + 10))))
    hrl.graphics.flip(clr=True)
    btn = None
    while btn != 'Space':
        btn, _ = hrl.inputs.readButton(to=3600)

    ### Core Loop ###

    # hrl.designs is an iterator over all the lines in the specified design
    # matrix, which was loaded at the creation of the hrl object. Looping over
    # it in a for statement provides a nice way to run each line in a design
    # matrix. The fields of each design line (dsgn) are drawn from the design
    # matrix in the design file (design.csv).

    start_time = time.time()
    try:
        for trial, dsgn in enumerate(hrl.designs):

            # skip trials that we already had data for
            if trial < completed_trials:
                continue

            # check if we should take a break (every 15 minutes)
            if time.time() - start_time > (60 * 15):
                show_break(trial, total_trials)
                start_time = time.time()

            match_lum, t, bg_values = run_trial(dsgn)

            # convert adaptor type name to convention more useful for analysis
            adaptor_ori = dsgn['adaptor_type'].replace('_shifted', '')
            if adaptor_ori == 'none':
                adaptor_type = 'none'
            elif dsgn['grating_ori'] == adaptor_ori:
                adaptor_type = 'parallel'
            else:
                adaptor_type = 'orthogonal'
            # determine flank and coaxial luminance based on test patch position
            grating_vals = [float(v) for v in dsgn['grating_vals'].split(',')]
            loc = int(dsgn['test_loc'])
            go = dsgn['grating_ori']
            if (go == 'horizontal' and loc in [2, 3]) or \
               (go == 'vertical' and loc in [0, 2]):
                coaxial_lum, flank_lum = grating_vals
            else:
                flank_lum, coaxial_lum = grating_vals

            # Once a value has been chosen by the subject, we save all relevant
            # variables to the result file by loading it all into the hrl.results
            # dictionary, and then finally running hrl.writeResultLine().
            hrl.results['Trial'] = trial
            hrl.results['test_lum'] = dsgn['test_lum']
            hrl.results['adaptor_type'] = adaptor_type
            hrl.results['test_loc'] = dsgn['test_loc']
            hrl.results['grating_ori'] = dsgn['grating_ori']
            hrl.results['coaxial_lum'] = coaxial_lum
            hrl.results['flank_lum'] = flank_lum
            hrl.results['response_time'] = time.time() - t
            hrl.results['match_lum'] = float(match_lum)
            hrl.writeResultLine()

            # write match bg values to file
            with open(check_fn, 'a') as f:
                f.write('%s\n' %','.join('%0.4f' % x for x in bg_values))

            # We print the trial number simply to keep track during an experiment
            print hrl.results['Trial']

    # catch EndExperiment exception raised by pressing escp for clean exit
    except EndExperiment:
        print "Experiment aborted"
    # And the experiment is over!
    hrl.close()
    print "Session complete"
示例#7
0
    bfl = open('results/%s/mlds/%s_blocks_done.txt' %(vp_id, vp_id), 'a')
    if blocksdone == None:
        block_headers = ['number', 'block']
        bfl.write('\t'.join(block_headers)+'\n')
        bfl.flush()
        
    # Pass this to HRL if we want to use gamma correction.
    lut = 'lut.csv'   
    
    if inlab:
        ## create HRL object
        hrl = HRL(graphics='datapixx',
                  inputs='responsepixx',
                  photometer=None,
                  wdth=WIDTH,
                  hght=HEIGHT,
                  bg=0.27,
                  scrn=1,
                  lut=lut,
                  db = False,
                  fs=True)

    else: 
        hrl = HRL(graphics='gpu',
                  inputs='keyboard',
                  photometer=None,
                  wdth=WIDTH,
                  hght=HEIGHT,
                  bg=0.27,
                  scrn=1,
                  lut=lut,
                  db = True,
示例#8
0
def main(subject, target_type):
    ### Argument Parser ###

    ### HRL Parameters ###
    ttype = target_type

    # Here we define all the paremeters required to instantiate an HRL object.

    # Which devices we wish to use in this experiment. See the
    # pydoc documentation for a list of # options.
    graphics = "datapixx"  # 'datapixx' is another option
    inputs = "responsepixx"  # 'responsepixx' is another option
    scrn = 1
    photometer = None

    # Screen size
    wdth = 1024
    hght = 768

    # Whether or not to use fullscreen. You probably want to do this when
    # actually running experiments, but when just developing one, fullscreen
    # locks out access to the rest of the computer, so you'll probably want to
    # turn this off.
    fs = True

    # Pass this to HRL if we want to use gamma correction.
    lut = "../lut.csv"

    # Design and result matrix information. This allows us the to use the HRL
    # functionality for automatically reading a design matrix, and
    # automatically generating a result matrix. See 'pydoc hrl.hrl' for more
    # information about these.

    if target_type == 0.0:
        dfl = "../design/base/test_design_onDark.csv"
        rfl = "../results/base/test_results_onDark_" + subject + ".csv"
        rhds = ["Trial", "target", "LumT", "LumM_start", "LumM_end", "RT"]
        hrl = HRL(
            graphics=graphics,
            inputs=inputs,
            photometer=photometer,
            scrn=scrn,
            wdth=wdth,
            hght=hght,
            bg=0,
            dfl=dfl,
            rfl=rfl,
            rhds=rhds,
            fs=fs,
            lut=lut,
        )
        hrl.results["Trial"] = 0

    elif target_type == 1.0:
        dfl = "../design/base/test_design_onLight.csv"
        rfl = "../results/base/test_results_onLight_" + subject + ".csv"
        rhds = ["Trial", "target", "LumT", "LumM_start", "LumM_end", "RT"]
        hrl = HRL(
            graphics=graphics,
            inputs=inputs,
            photometer=photometer,
            scrn=scrn,
            wdth=wdth,
            hght=hght,
            bg=0,
            dfl=dfl,
            rfl=rfl,
            rhds=rhds,
            fs=fs,
            lut=lut,
        )
        hrl.results["Trial"] = float(len(pd.read_csv(dfl, sep=" ", index_col=0)))

    smlstp = 2 / 255.0
    bgstp = 10 / 255.0

    for dsgn in hrl.designs:
        # Here we save the values of the design line with appropriately cast
        # types and simple names.
        Lum_S = float(dsgn["Lum_S"])
        Lum_CD = float(dsgn["Lum_CD"])
        # ~ Lum_S = float(53)
        # ~ Lum_CD = float(68.4285714286)

        curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)

        # stimulus presentation
        frm1 = hrl.graphics.newTexture(curr_image)
        frm1.draw((0, 0), (wdth, hght))
        hrl.graphics.flip(clr=True)

        # And finally we preload some variables to prepare for our button
        # reading loop.

        # The button pressed
        btn = None
        # The time it took to decide on the mean luminance
        t = 0.0
        # Whether escape was pressed
        escp = False

        print hrl.results["Trial"], "   LumS = ", Lum_S, "    LumCD = ", Lum_CD
        ### Input Loop ####

        # Until the user finalizes their luminance choice for the central
        # circle, or pressed escape...
        while (btn != "Space") & (escp != True):

            # Read the next button press
            (btn, t1) = hrl.inputs.readButton()
            # Add the time it took to press to the decision time
            t += t1
            if ttype == 1:
                # Respond to the pressed button
                if btn == "Up":
                    Lum_CD += bgstp * 255
                    # Make sure the luminance doesn't fall out of the range [0,1]
                    if Lum_CD > 255:
                        Lum_CD = 255
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Right":
                    Lum_CD += smlstp * 255
                    if Lum_CD > 255:
                        Lum_CD = 255
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Down":
                    Lum_CD -= bgstp * 255
                    if Lum_CD < 0:
                        Lum_CD = 0
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Left":
                    Lum_CD -= smlstp * 255
                    if Lum_CD < 0:
                        Lum_CD = 0
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Escape":
                    escp = True
                    break

            if ttype == 0:
                # Respond to the pressed button
                if btn == "Up":
                    Lum_S += bgstp * 255
                    # Make sure the luminance doesn't fall out of the range [0,1]
                    if Lum_S > 255:
                        Lum_S = 255
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Right":
                    Lum_S += smlstp * 255
                    if Lum_S > 255:
                        Lum_S = 255
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Down":
                    Lum_S -= bgstp * 255
                    if Lum_S < 0:
                        Lum_S = 0
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Left":
                    Lum_S -= smlstp * 255
                    if Lum_S < 0:
                        Lum_S = 0
                    curr_image = drawImg("../renTemplate", 25, Lum_S, Lum_CD)
                    frm1 = hrl.graphics.newTexture(curr_image)
                    frm1.draw((0, 0), (wdth, hght))
                    hrl.graphics.flip(clr=True)
                elif btn == "Escape":
                    escp = True
                    break

                    # Once a value has been chosen by the subject, we save all the relevant
                    # variables to the result file by loading it all into the hrl.results
                    # dictionary, and then finally running hrl.writeResultLine().
                    # rhds = ['Trial', 'target', 'LumS', 'Lum_CD', 'LumCD_end', 'RT']

                    # We print the trial number simply to keep track during an experiment
        print hrl.results["Trial"], "    LumS= ", Lum_S, "   LumCD= ", Lum_CD

        if ttype == 0:
            hrl.results["Trial"] += 1
            hrl.results["target"] = ttype
            hrl.results["LumT"] = Lum_CD
            hrl.results["LumM_start"] = float(dsgn["Lum_S"])
            hrl.results["LumM_end"] = Lum_S
            hrl.results["RT"] = t
            hrl.writeResultLine()

        if ttype == 1:
            hrl.results["Trial"] += 1
            hrl.results["target"] = ttype
            hrl.results["LumT"] = Lum_S
            hrl.results["LumM_start"] = float(dsgn["Lum_CD"])
            hrl.results["LumM_end"] = Lum_CD
            hrl.results["RT"] = t
            hrl.writeResultLine()

            # If escape has been pressed we break out of the core loop
        if escp:
            print "Session cancelled"
            break

            # And the experiment is over!
    hrl.close()
    print "Session complete"
def main(sbj, blk):
	#~ observer_id  = raw_input ('Please write the subject\'s initials: ')
	#~ os.path.isfile(observer_id*)
	### HRL Parameters ###


	# Here we define all the paremeters required to instantiate an HRL object.

	# Which devices we wish to use in this experiment. See the
	# pydoc documentation for a list of # options.
	graphics='datapixx' # 'datapixx' is another option
	inputs='responsepixx' # 'responsepixx' is another option
	photometer=None
	scrn = 1

	# Screen size
	wdth = 1024
	hght = 768
	
	# Whether or not to use fullscreen. You probably want to do this when
	# actually running experiments, but when just developing one, fullscreen
	# locks out access to the rest of the computer, so you'll probably want to
	# turn this off.
	fs = True

	# Design and result matrix information. This allows us the to use the HRL
	# functionality for automatically reading a design matrix, and
	# automatically generating a result matrix. See 'pydoc hrl.hrl' for more
	# information about these.

	# Design and Result matrix files names
	#~ designFname = 
	#~ dfl = '../design/' + designFname + '.csv'
	#~ dfl = '../design/%s_design.csv' %(observer_id)
	#~ rfl = '../results/%s_results.csv' %(observer_id)
	
	if blk == 0:
		dfl = '../design/2afc_design_Dark_' + sbj + '.csv'
		rfl = '../results/2afc_results_Dark_' + sbj + '.csv'
	if blk == 1:
		dfl = '../design/2afc_design_Light_' + sbj + '.csv'
		rfl = '../results/2afc_results_Light_' + sbj + '.csv'
	
	# The names of the fields in the results matrix. In each loop of the
	# script, we write another line of values to results.csv under these
	# headings.
	rhds = ['Trial', 'LumTarget', 'LumMatch', 'LT-LM', 'LumComp', '%deviance', 'Choice', 'RT']

	# Pass this to HRL if we want to use gamma correction.
	lut = '../stimuli/lut.csv'

	# Create the hrl object with the above fields. All the default argument names are
	# given just for illustration.
	hrl = HRL(graphics=graphics,
			  inputs=inputs,
			  photometer=photometer,
			  wdth=wdth,
			  hght=hght,
			  bg=0,
			  dfl=dfl,
			  rfl=rfl,
			  rhds=rhds,
			  fs=fs,
			  scrn=scrn,
			  lut=lut )

	# hrl.results is a dictionary which is automatically created by hrl when
	# give a list of result fields. This can be used to easily write lines to
	# the result file, as will be seen later.
	hrl.results['Trial'] = 0
	
	btn = None
	t = 0
	escp = False
	
	#instruction screen 
	frmInst = hrl.graphics.newTexture(np.array([[1]]))
	frmInst.draw((0,0), (wdth,hght))
	hrl.graphics.flip(clr=True)
	while ((btn != 'Space') & (escp != True)):
		(btn,t1) = hrl.inputs.readButton()
		if btn == 'Escape':
			escp = True
			raise Exception('experiment terminated by the subject')
	
	### Experiment setup ###

	# texture creation in buffer : stimulus	   I DO NOT NEED A BUFFERED IMAGE TO DRAW ON
		
	### Core Loop ###

	# hrl.designs is an iterator over all the lines in the specified design
	# matrix, which was loaded at the creation of the hrl object. Looping over
	# it in a for statement provides a nice way to run each line in a design
	# matrix. The fields of each design line (dsgn) are drawn from the design
	# matrix in the design file (design.csv).
	for dsgn in hrl.designs:
		# Here we save the values of the design line with appropriately cast
		# types and simple names.
		LumS = float(dsgn['Lum_S'])
		LumCD = float(dsgn['Lum_CD'])
		LumCL = float(dsgn['Lum_CL'])

		if blk == 1:
			img_fname = '../stimuli/' + sbj +'/lS%d_CD%d_CL%d' %(int(LumS), int(LumCD), int(LumCL))
		if blk == 0:
			img_fname = '../stimuli/' +sbj + '/dS%d_CD%d_CDD%d' %(int(LumS), int(LumCD), int(LumCL))
		#~ curr_image = image_to_array(img_fname)
		curr_image2 = image_to_array(img_fname)
		curr_image  = normalize_image2(curr_image2, 0, 1)
		
		# prestimulus fixation 
		frmFix = hrl.graphics.newTexture(np.array([[float(120.0/255.0)]]))
		frmFix.draw((0,0), (wdth,hght))
		hrl.graphics.flip(clr=False)
		time.sleep(0.5)
		
		# And finally we preload some variables to prepare for our button
		# reading loop.
		
		# stimulus presentation
		#~ frm1 = hrl.graphics.newTexture(curr_image)
		frm1 = hrl.graphics.newTexture(curr_image)
		frm1.draw((0,0),(wdth,hght)) 
		hrl.graphics.flip(clr=True)
		time.sleep(0.25)
		#~ time.sleep(1.0)
		
		# response fixation
		frmFix.draw((0,0), (wdth,hght))
		if hrl.results['Trial'] > 99:
			nte2 = hrl.results['Trial'] / 100
			nte1 = hrl.results['Trial'] / 10 - nte2*10
			nte0 = hrl.results['Trial'] %10
			fileN = 'testingImg_%d' %(nte1)
			fileN2 = 'testingImg_%d' %(nte0)
			fileN3 = 'testingImg_%d' %(nte2)
			nT = normalize_image2(image_to_array(fileN),0,1)
			nT2 = normalize_image2(image_to_array(fileN2),0,1)
			nT3 = normalize_image2(image_to_array(fileN3),0,1)
			hrl.graphics.newTexture(nT).draw((25,0), (20,28))
			hrl.graphics.newTexture(nT2).draw((50,0), (20,28)) 
			hrl.graphics.newTexture(nT3).draw((5,0), (20,28)) 
			hrl.graphics.flip(clr=True) 
			
		elif hrl.results['Trial'] > 9:
			nte1 = hrl.results['Trial'] / 10
			nte0 = hrl.results['Trial'] %10
			fileN = 'testingImg_%d' %(nte1)
			filen2 = 'testingImg_%d' %(nte0)
			nT = normalize_image2(image_to_array(fileN),0,1)
			nT2 = normalize_image2(image_to_array(filen2),0,1)
			hrl.graphics.newTexture(nT).draw((5,0), (20,28))
			hrl.graphics.newTexture(nT2).draw((25,0), (20,28)) 
			hrl.graphics.flip(clr=True) 
			
		else:
			fileN = 'testingImg_%d' %(hrl.results['Trial'])
			nT = normalize_image2(image_to_array(fileN), 0, 1)
			hrl.graphics.newTexture(nT).draw((5,0), (20,28)) 
			hrl.graphics.flip(clr=True)
			
		### Input Loop ####
		
		# Until the user finalizes their luminance choice for the central
		# circle, or pressed escape...
		
		# The button pressed
		btn = None
		# The time it took to decide on which pair is more different
		t = 0
		# Whether escape was pressed
		escp = False
		
		while ((btn != 'Space') & (escp != True)):

			# Read the next button press
			(btn,t1) = hrl.inputs.readButton()
			# Add the time it took to press to the decision time
			t += t1
			# Respond to the pressed button
			if blk == 0:
				if btn == 'Left': # if CDD-CD-S, then Left = CDD-CD looks more similar
								  # if CD-S-CL , then Left = CD- S  looks more similar 
					hrl.results['Trial'] += 1
					hrl.results['LumTarget'] = LumS
					hrl.results['LumMatch'] = LumCD
					hrl.results['LT-LM'] = LumS-LumCD
					hrl.results['LumComp'] = LumCL
					hrl.results['%deviance'] = np.round(((LumCL-LumCD)/LumCD)*100, 0)
					hrl.results['Choice'] = 0
					hrl.results['RT'] = t
					hrl.writeResultLine()
					break
				elif btn == 'Right': # if CDD-CD-S, then Right = CD-S looks more similar
									 # if CD-S-CL , then Right = S- CL  looks more similar 
					hrl.results['Trial'] += 1
					hrl.results['LumTarget'] = LumS
					hrl.results['LumMatch'] = LumCD
					hrl.results['LT-LM'] = LumS-LumCD
					hrl.results['LumComp'] = LumCL
					hrl.results['Choice'] = 1
					hrl.results['%deviance'] = np.round(((LumCL-LumCD)/LumCD)*100, 0)
					hrl.results['RT'] = t
					hrl.writeResultLine()
					break
				elif btn == 'Escape':
					escp = True
					break
			if blk == 1:
				if btn == 'Down': # if CDD-CD-S, then Left = CDD-CD looks more similar
								  # if CD-S-CL , then Left = CD- S  looks more similar 
					hrl.results['Trial'] += 1
					hrl.results['LumTarget'] = LumS
					hrl.results['LumMatch'] = LumCD
					hrl.results['LT-LM'] = LumS-LumCD
					hrl.results['LumComp'] = LumCL
					hrl.results['%deviance'] = np.round(((LumCL-LumCD)/LumCD)*100, 0)
					hrl.results['Choice'] = 0
					hrl.results['RT'] = t
					hrl.writeResultLine()
					break
				elif btn == 'Up': # if CDD-CD-S, then Right = CD-S looks more similar
									 # if CD-S-CL , then Right = S- CL  looks more similar 
					hrl.results['Trial'] += 1
					hrl.results['LumTarget'] = LumS
					hrl.results['LumMatch'] = LumCD
					hrl.results['LT-LM'] = LumS-LumCD
					hrl.results['LumComp'] = LumCL
					hrl.results['Choice'] = 1
					hrl.results['%deviance'] = np.round(((LumCL-LumCD)/LumCD)*100, 0)
					hrl.results['RT'] = t
					hrl.writeResultLine()
					break
				elif btn == 'Escape':
					escp = True
					break
		# We print the trial number simply to keep track during an experiment
		print hrl.results['Trial']
		
		# If escape has been pressed we break out of the core loop
		if escp:
			print "Session cancelled"
			break
				
	# And the experiment is over!
	hrl.close()
	print "session complete"
def main():

    debug = 0
    #print debug
    if debug:

        ### HRL Parameters for DESKTOP ###
        graphics = 'gpu'
        inputs = 'keyboard'

        # Screen GPU
        wdth = 800
        hght = 600
        fs = False  # fullscreen mode off
        scrn = 0  # screen number

    else:

        ### HRL Parameters for DATAPIXX ###
        graphics = 'datapixx'
        inputs = 'responsepixx'  # or 'responsepixx'

        wdth = 1024
        hght = 768
        #wdth = 1600
        #hght = 1200
        #wdth = 2048
        #hght = 1536
        fs = True  # fullscreen mode
        scrn = 1  # screen number

    #############################################
    hrl = HRL(graphics=graphics,
              inputs=inputs,
              lut=lut,
              photometer=None,
              wdth=wdth,
              hght=hght,
              bg=background,
              fs=fs,
              scrn=scrn)

    whlf = wdth / 2.0
    hhlf = hght / 2.0
    weht = wdth / 8.0
    heht = hght / 8.0

    # texture creation in buffer, input is numpy array [0-1]
    white = hrl.graphics.newTexture(np.array([[1]]))
    black = hrl.graphics.newTexture(np.array([[0]]))

    s = 150
    white.draw((whlf - s, hhlf - s), (s, s))
    black.draw((whlf, hhlf - s), (s, s))
    white.draw((whlf, hhlf), (s, s))
    black.draw((whlf - s, hhlf), (s, s))

    hrl.graphics.flip(clr=False)

    #######################################
    while True:
        #hrl.graphics.flip(clr=True)   # clr= True to clear buffer

        (btn, t1) = hrl.inputs.readButton()
        #print btn

        if btn == 'Space':
            break

    # closing window
    hrl.close()
def main():
    # determine design and result file name
    try:
        (design_fn, result_fn, completed_trials, total_trials,
         check_fn) = prepare_files()
    except EndExperiment:
        return 0
    result_headers = [
        'Trial', 'adaptor_type', 'coaxial_lum', 'test_lum', 'match_lum',
        'flank_lum', 'test_loc', 'grating_ori', 'response_time',
        'match_initial', 'adaptor_shift'
    ]
    global hrl
    hrl = HRL(graphics='datapixx',
              inputs='responsepixx',
              photometer=None,
              wdth=1024,
              hght=768,
              bg=0.5,
              dfl=design_fn,
              rfl=result_fn,
              rhds=result_headers,
              scrn=1,
              lut='lut0to88.csv',
              db=False,
              fs=True)

    # monkey patch to use non-blocking readButton function
    # should be removed once hrl.inputs.readButton is fixed
    hrl.inputs.readButton = lambda to: waitButton(hrl.datapixx, to)

    # set the bar width of the grating. this value determines all positions
    global bar_width
    bar_width = 38
    y_border = 768 // 2 - int(6 * bar_width)
    x_border = (1024 - 6 * bar_width) // 2
    # the coordinates of the four possible test check positions
    # test coordinates are (y,x) position within the grating array
    global test_coords
    test_coords = ((bar_width * 3, bar_width * 2), (bar_width * 3,
                                                    bar_width * 3),
                   (bar_width * 4, bar_width * 2), (bar_width * 4,
                                                    bar_width * 3))
    # match coordinates are (x,y) screen positions
    global match_coords
    match_coords = ((x_border + bar_width * 2, 384 + int(bar_width * 2)),
                    (x_border + bar_width * 3, 384 + int(bar_width * 2)),
                    (x_border + bar_width * 2, 384 + int(bar_width * 1)),
                    (x_border + bar_width * 3, 384 + int(bar_width * 1)))
    global match_bg_loc
    match_bg_loc = (x_border, 384)
    global stim_loc
    stim_loc = (x_border, y_border)

    # prepare fixation mark textures
    global fix_inner
    fix_inner = hrl.graphics.newTexture(np.ones((1, 1)) * .5, 'circle')
    global fix_outer
    fix_outer = hrl.graphics.newTexture(np.zeros((1, 1)), 'circle')

    # prepare confirmation texture
    global confirmation
    confirmation = hrl.graphics.newTexture(draw_text('Weiter?', bg=.5))

    # show instruction screen
    if completed_trials == 0:
        for i in range(6):
            instructions = plt.imread('instructions%d.png' % (i + 1))[..., 0]
            instructions = hrl.graphics.newTexture(instructions)
            instructions.draw((0, 0))
            hrl.graphics.flip(clr=True)
            btn = None
            while btn != 'Space':
                btn, _ = hrl.inputs.readButton(to=3600)

        # show test trials
        test_dsgn = [{
            'adaptor_type': 'none',
            'grating_ori': 'horizontal',
            'grating_vals': '0.45,0.55',
            'test_loc': '0',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'vertical',
            'grating_ori': 'horizontal',
            'grating_vals': '0.55,0.45',
            'test_loc': '1',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'horizontal',
            'grating_ori': 'horizontal',
            'grating_vals': '0.45,0.55',
            'test_loc': '2',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'vertical',
            'grating_ori': 'vertical',
            'grating_vals': '0.55,0.45',
            'test_loc': '2',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'none',
            'grating_ori': 'vertical',
            'grating_vals': '0.45,0.45',
            'test_loc': '1',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'vertical_shifted',
            'grating_ori': 'vertical',
            'grating_vals': '0.55,0.45',
            'test_loc': '2',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'none',
            'grating_ori': 'vertical',
            'grating_vals': '0.55,0.55',
            'test_loc': '1',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'horizontal_shifted',
            'grating_ori': 'vertical',
            'grating_vals': '0.45,0.55',
            'test_loc': '1',
            'test_lum': '0.5'
        }, {
            'adaptor_type': 'horizontal',
            'grating_ori': 'vertical',
            'grating_vals': '0.45,0.55',
            'test_loc': '3',
            'test_lum': '0.5'
        }]
        for dsgn in test_dsgn:
            run_trial(dsgn)

    # show experiment start confirmation
    hrl.graphics.flip(clr=True)
    lines = [
        u'Die Probedurchgänge sind fertig.',
        u'Wenn du bereit bist, drücke die mittlere Taste.', u' ',
        u'Wenn du noch Fragen hast, oder mehr Probedurchgänge',
        u'machen willst, wende dich an den Versuchsleiter.'
    ]
    for line_nr, line in enumerate(lines):
        textline = hrl.graphics.newTexture(draw_text(line, fontsize=36))
        textline.draw(((1024 - textline.wdth) / 2,
                       (768 / 2 - (3 - line_nr) * (textline.hght + 10))))
    hrl.graphics.flip(clr=True)
    btn = None
    while btn != 'Space':
        btn, _ = hrl.inputs.readButton(to=3600)

    ### Core Loop ###

    # hrl.designs is an iterator over all the lines in the specified design
    # matrix, which was loaded at the creation of the hrl object. Looping over
    # it in a for statement provides a nice way to run each line in a design
    # matrix. The fields of each design line (dsgn) are drawn from the design
    # matrix in the design file (design.csv).

    start_time = time.time()
    try:
        for trial, dsgn in enumerate(hrl.designs):

            # skip trials that we already had data for
            if trial < completed_trials:
                continue

            # check if we should take a break (every 15 minutes)
            if time.time() - start_time > (60 * 15):
                show_break(trial, total_trials)
                start_time = time.time()

            match_lum, t, bg_values = run_trial(dsgn)

            # convert adaptor type name to convention more useful for analysis
            adaptor_ori = dsgn['adaptor_type'].replace('_shifted', '')
            if adaptor_ori == 'none':
                adaptor_type = 'none'
            elif dsgn['grating_ori'] == adaptor_ori:
                adaptor_type = 'parallel'
            else:
                adaptor_type = 'orthogonal'
            # determine flank and coaxial luminance based on test patch position
            grating_vals = [float(v) for v in dsgn['grating_vals'].split(',')]
            loc = int(dsgn['test_loc'])
            go = dsgn['grating_ori']
            if (go == 'horizontal' and loc in [2, 3]) or \
               (go == 'vertical' and loc in [0, 2]):
                coaxial_lum, flank_lum = grating_vals
            else:
                flank_lum, coaxial_lum = grating_vals

            # Once a value has been chosen by the subject, we save all relevant
            # variables to the result file by loading it all into the hrl.results
            # dictionary, and then finally running hrl.writeResultLine().
            hrl.results['Trial'] = trial
            hrl.results['test_lum'] = dsgn['test_lum']
            hrl.results['adaptor_type'] = adaptor_type
            hrl.results['test_loc'] = dsgn['test_loc']
            hrl.results['grating_ori'] = dsgn['grating_ori']
            hrl.results['coaxial_lum'] = coaxial_lum
            hrl.results['flank_lum'] = flank_lum
            hrl.results['response_time'] = time.time() - t
            hrl.results['match_lum'] = float(match_lum)
            hrl.writeResultLine()

            # write match bg values to file
            with open(check_fn, 'a') as f:
                f.write('%s\n' % ','.join('%0.4f' % x for x in bg_values))

            # We print the trial number simply to keep track during an experiment
            print hrl.results['Trial']

    # catch EndExperiment exception raised by pressing escp for clean exit
    except EndExperiment:
        print "Experiment aborted"
    # And the experiment is over!
    hrl.close()
    print "Session complete"
示例#12
0
def main():

    ### HRL Parameters ###

    # Here we define all the paremeters required to instantiate an HRL object.

    # Which devices we wish to use in this experiment. See the
    # pydoc documentation for a list of # options.
    graphics = "gpu"  # 'datapixx' is another option
    inputs = "keyboard"  # 'responsepixx' is another option
    photometer = None

    # Screen size
    wdth = 1024
    hght = 768

    # Whether or not to use fullscreen. You probably want to do this when
    # actually running experiments, but when just developing one, fullscreen
    # locks out access to the rest of the computer, so you'll probably want to
    # turn this off.
    fs = True

    # Design and result matrix information. This allows us the to use the HRL
    # functionality for automatically reading a design matrix, and
    # automatically generating a result matrix. See 'pydoc hrl.hrl' for more
    # information about these.

    # Design and Result matrix files names
    dfl = "design.csv"
    rfl = "results.csv"

    # The names of the fields in the results matrix. In each loop of the
    # script, we write another line of values to results.csv under these
    # headings.
    rhds = [
        "SelectedMunsell",
        "LeftMunsell",
        "RightMunsell",
        "Trial",
        "TrialTime",
        "FramePresent",
        "LeftLuminance",
        "RightLuminance",
        "InitialLuminance",
        "InitialMunsell",
        "SelectedLuminance",
    ]

    # Pass this to HRL if we want to use gamma correction.
    lut = "lut.csv"

    # Create the hrl object with the above fields. All the default argument names are
    # given just for illustration.
    hrl = HRL(
        graphics=graphics,
        inputs=inputs,
        photometer=photometer,
        wdth=wdth,
        hght=hght,
        bg=0,
        dfl=dfl,
        rfl=rfl,
        rhds=rhds,
        fs=fs,
    )

    # hrl.results is a dictionary which is automatically created by hrl when
    # give a list of result fields. This can be used to easily write lines to
    # the result file, as will be seen later.
    hrl.results["Trial"] = 0

    ### Experiment setup ###

    # We are arranging circles and shapes around the screen, so it's helpful to
    # section the screen into eights and halves.
    whlf = wdth / 2.0
    hhlf = hght / 2.0
    weht = wdth / 8.0
    heht = hght / 8.0

    # These are the big and small step sizes for luminance changes
    smlstp = 0.005
    bgstp = 0.05

    # Here we load the square frame which contains the circles into the back
    # buffer. This is simply a white square covered by a slightly smaller black
    # square. The textures loaded are simply 1x1 pixel values, but then we use
    # the draw function to stretch them to the appropriate size. Since we never
    # draw these objects again, we don't bother saving the texture objects
    # returned by newTexture, but rather simply draw them right away and then
    # throw them away.
    frm1 = hrl.graphics.newTexture(np.array([[1]]))
    frm2 = hrl.graphics.newTexture(np.array([[0]]))

    frm1.draw((1.9 * weht, 1.9 * heht), (0.525 * wdth, 0.525 * hght))
    frm2.draw((2 * weht, 2 * heht), (0.5 * wdth, 0.5 * hght))

    hrl.graphics.flip(clr=False)

    frm1.draw((1.9 * weht, 1.9 * heht), (0.525 * wdth, 0.525 * hght))
    frm2.draw((2 * weht, 2 * heht), (0.5 * wdth, 0.5 * hght))

    ### Core Loop ###

    # hrl.designs is an iterator over all the lines in the specified design
    # matrix, which was loaded at the creation of the hrl object. Looping over
    # it in a for statement provides a nice way to run each line in a design
    # matrix. The fields of each design line (dsgn) are drawn from the design
    # matrix in the design file (design.csv).
    for dsgn in hrl.designs:

        # Here we save the values of the design line with appropriately cast
        # types and simple names.
        lmns = float(dsgn["LeftMunsell"])
        rmns = float(dsgn["RightMunsell"])
        rds = float(dsgn["Radius"])
        frm = bool(dsgn["FramePresent"])

        # And we randomly initialize the luminance of the central circle.
        cmns = uniform(0.0, 1.0)

        # Here we create our circle textures. Again, they are simply 1x1 pixel
        # textures, but since they are uniform in colour, it serves simply to
        # stretch them to our desired dimensions.
        llm = munsell2luminance(np.array([[lmns]]))
        rlm = munsell2luminance(np.array([[rmns]]))
        clm = munsell2luminance(np.array([[cmns]]))

        # Here we draw the circles to the back buffer
        lcrc = hrl.graphics.newTexture(llm, "circle")
        rcrc = hrl.graphics.newTexture(clm, "circle")

        lcrc.draw((whlf - weht, hhlf), (2 * rds, 2 * rds))
        rcrc.draw((whlf + weht, hhlf), (2 * rds, 2 * rds))
        hrl.graphics.flip(clr=False)

        lcrc.draw((whlf - weht, hhlf), (2 * rds, 2 * rds))
        rcrc.draw((whlf + weht, hhlf), (2 * rds, 2 * rds))
        hrl.graphics.newTexture(rlm, "circle").draw((whlf, hhlf), (2 * rds, 2 * rds))

        # Finally we load our frame and our circles to the screen. We don't
        # clear the back buffer because we don't want to redraw the frame, and
        # we'll simply draw new circles ontop of old ones.
        hrl.graphics.flip(clr=False)

        # And finally we preload some variables to prepare for our button
        # reading loop.

        # The button pressed
        btn = None
        # The time it took to decide on the mean luminance
        t = 0.0
        # Whether escape was pressed
        escp = False

        ### Input Loop ####

        # Until the user finalizes their luminance choice for the central
        # circle, or pressed escape...
        while (btn != "Space") & (escp != True):

            # Read the next button press
            (btn, t1) = hrl.inputs.readButton()
            # Add the time it took to press to the decision time
            t += t1

            # Respond to the pressed button
            if btn == "Up":
                cmns += bgstp
            elif btn == "Right":
                cmns += smlstp
            elif btn == "Down":
                cmns -= bgstp
            elif btn == "Left":
                cmns -= smlstp
            elif btn == "Escape":
                escp = True
                break

            # Make sure the luminance doesn't fall out of the range [0,1]
            if cmns > 1:
                cmns = 1
            if cmns < 0:
                cmns = 0

            # And update the display with the new value
            clm = munsell2luminance(np.array([[cmns]]))
            hrl.graphics.newTexture(clm, "circle").draw((whlf, hhlf), (2 * rds, 2 * rds))
            hrl.graphics.flip(clr=False)

        # Once a value has been chosen by the subject, we save all the relevant
        # variables to the result file by loading it all into the hrl.results
        # dictionary, and then finally running hrl.writeResultLine().
        hrl.results["Trial"] += 1
        hrl.results["FramePresent"] = frm
        hrl.results["LeftLuminance"] = llm[0, 0]
        hrl.results["LeftMunsell"] = lmns
        hrl.results["RightLuminance"] = rlm[0, 0]
        hrl.results["RightMunsell"] = rmns
        hrl.results["InitialLuminance"] = clm[0, 0]
        hrl.results["InitialMunsell"] = cmns
        hrl.results["TrialTime"] = t
        hrl.results["SelectedLuminance"] = clm[0, 0]
        hrl.results["SelectedMunsell"] = cmns
        hrl.writeResultLine()

        # We print the trial number simply to keep track during an experiment
        print hrl.results["Trial"]

        # If escape has been pressed we break out of the core loop
        if escp:
            print "Session cancelled"
            break

    # And the experiment is over!
    hrl.close()
    print "Session complete"
def main(files):

    debug = 0
    #print debug
    if debug:

        ### HRL Parameters for DESKTOP ###
        graphics = 'gpu'
        inputs = 'keyboard'

        # Screen GPU
        wdth = 800
        hght = 600
        fs = False  # fullscreen mode off
        scrn = 0  # screen number

    else:

        ### HRL Parameters for DATAPIXX ###
        graphics = 'datapixx'
        inputs = 'responsepixx'  # or 'responsepixx'

        wdth = 1024
        hght = 768
        fs = True  # fullscreen mode
        scrn = 1  # screen number

    #############################################
    hrl = HRL(graphics=graphics,
              inputs=inputs,
              lut=lut,
              photometer=None,
              wdth=wdth,
              hght=hght,
              bg=background,
              fs=fs,
              scrn=scrn)

    whlf = wdth / 2.0
    hhlf = hght / 2.0
    #qh = hght/4.0
    #qw = wdth/4.0
    #ws = wdth/6.0

    # reading PNGs and converting to grayscale
    textures = []
    for fname in files:

        print "loading... %s " % fname
        ## the image is loaded using PIL module and converted to a
        ## numpy array ranging from 0 to 1.
        image = Image.open(fname).convert("L")
        im = np.asarray(image) / 255.

        # texture creation in buffer, input is numpy array [0-1]
        tex = hrl.graphics.newTexture(im)
        textures.append(tex)

    # generating text for filenames to be displayed
    texts = []
    for fname in files:
        im = draw_text(fname, bg=0.27, text_color=0, fontsize=20)
        tex = hrl.graphics.newTexture(im)
        texts.append(tex)

    #######
    i = 0
    #######################################
    while True:
        tex = textures[i]
        tex.draw((whlf - tex.wdth / 2, hhlf - tex.hght / 2))

        tex = texts[i]
        tex.draw((100, 100))

        hrl.graphics.flip(clr=True)  # clr= True to clear buffer
        print "currently showing: %s" % files[i]

        (btn, t1) = hrl.inputs.readButton()
        #print btn

        if btn == 'Space':
            break
        elif btn == 'Right':
            i += 1
        elif btn == 'Left':
            i -= 1

        if i < 0:
            i = len(textures) - 1
        if i == len(textures):
            i = 0

    # closing window
    hrl.close()
示例#14
0
def main():

    # Parse args
    args = prsr.parse_args()

    # HRL parameters
    wdth = 1024
    hght = 768

    # Section the screen - used by Core Loop
    wqtr = wdth/4.0
    
    # IO Stuff
    dpxBool = False
    dfl = 'design.csv'
    rfl = 'results/' + args.sbj + '.csv'
    flds = ['TrialTime','SelectedLuminance']
    btns = ['Yellow','Red','Blue','Green','White']

    # Central Coordinates (the origin of the graphics buffers is at the centre of the
    # screen. Change this if you don't want a central coordinate system. If you delete
    # this part the default will be a matrix style coordinate system.
    coords = (-0.5,0.5,-0.5,0.5)
    flipcoords = False

    # Pass this to HRL if we want to use gamma correction.
    lut = 'LUT.txt'
    # If fs is true, we must provide a way to exit with e.g. checkEscape().
    fs = False

    # Step sizes for luminance changes
    smlstp = 0.01
    bgstp = 0.1

    # HRL Init
    hrl = HRL(wdth,hght,dpx=dpxBool,dfl=dfl,rfl=rfl,rhds=flds
              ,btns=btns,fs=fs,coords=coords,flipcoords=flipcoords)

    # Core Loop
    for dsgn in hrl.dmtx:

        # Load Trial
        mnl = float(dsgn['MinLuminance'])
        mxl = float(dsgn['MaxLuminance'])
        rds = float(dsgn['Radius'])

        # Create Patches
        mnptch = hrl.newTexture(np.array([[mnl]]),'circle')
        mxptch = hrl.newTexture(np.array([[mxl]]),'circle')
        cntrllm = uniform(0.0,1.0)
        cntrlptch = hrl.newTexture(np.array([[cntrllm]]),'circle')

        # Draw Patches
        mnptch.draw((-wqtr,0),(2*rds,2*rds))
        mxptch.draw((wqtr,0),(2*rds,2*rds))
        cntrlptch.draw((0,0),(2*rds,2*rds))
        # Draw but don't clear the back buffer
        hrl.flip(clr=False)

        # Prepare Core Loop logic
        btn = None
        t = 0.0
        escp = False

        # Adjust central patch
        while ((btn != 'White') & (escp != True)):
            
            (btn,t1) = hrl.readButton()
            t += t1

            if btn == 'Yellow':
                cntrllm += smlstp
            elif btn == 'Red':
                cntrllm += bgstp
            elif btn == 'Blue':
                cntrllm -= smlstp
            elif btn == 'Green':
                cntrllm -= bgstp

            # Bound Checking
            if cntrllm > 1: cntrllm = 1
            if cntrllm < 0: cntrllm = 0

            # Update display
            cntrlptch = hrl.newTexture(np.array([[cntrllm]]),'circle')
            cntrlptch.draw((0,0),(2*rds,2*rds))
            hrl.flip(clr=False)

            if hrl.checkEscape(): escp = True

        # Save results of trial
        hrl.rmtx['TrialTime'] = t
        hrl.rmtx['SelectedLuminance'] = cntrllm
        hrl.writeResultLine()
        
        # Check if escape has been pressed
        if escp: break

    # Experiment is over!
    hrl.close()