Sunday, December 18, 2011

PEBL Programming Tutorial V: Iteration

This is Part V of a series of tutorials on PEBL
First  |   Previous   | Next


The previous tutorials showed how to do some simple but important things required for an experiment, such as displaying a stimulus or collecting a response.  Another important part of almost every experiment is repetition.  For example, you may have multiple questions you ask, or multiple trials where you want to do similar or identical things.  The way this is done is through a mechanism called iteration, which allows you to repeat a piece of code multiple times.

We will use a list to do iteration.  This is really the simplest way to iterate, and representing stimuli or conditions in a list allows you to randomize and design experiments in fairly simple ways.  So, we must start with a list.

In PEBL, a list is an arbitrary sequence of values.  It is defined by the [ and ] brackets, with values separated by commas.  It is a lot like vectors or arrays you may have experience with, but there are subtle differences.  More on that later.

An example list in PEBL might look like this:

   example <- [1,2,2,1,1,2,2,1,1,2,2,1]



Now, we would like to iterate over the values of example, choosing them one at a time and doing something with each value.  To do this, we use loop().  Loop is used like this:

  loop(i, example)
   {
     Print(i)
   }


loop moves through all elements of example in order, and each time it does it binds the value to the first argument of the loop primitive (in this case, the variable i).

That's it for loop().  One way it is used is to specify a set of trial conditions or stimuli, then loop through a shuffled list of those stimuli.  On each  iteration, run a function you create called Trial, which takes the condition as an argument.  A full-fledged experiment could look like this:



define Start(p)
{
      stim <- Shuffle([1,1,1,1,1,2,2,2,2,2])
      gWin <- MakeWindow()
      inst <- EasyLabel("Press the number you see on the keyboard",gVideoWidth/2,40,gWin,30)

     loop(i,stim)
      {
         resp <-  Trial(i)
         Print(resp)
      }

}


define Trial(stimulus)
 {
     lab <- EasyLabel(stimulus+"",gVideoWidth/2,
                              gVideoHeight/2,gWin,28)
    Draw()
    time0 <- GetTime()
    resp <-  WaitForListKeyPress(["1","2"])
    time1 <- GetTime()
  
    ##Score whether we are correct
   if(stimulus+""==resp)
   {
      corr <- 1
    }else {
      corr <- 0
    }
   return [resp,corr,(time1-time0)]

2 comments:

Henry said...

This is not working for me, it is saying that there is an error near line 18, that "stim" is an undefined variable.

Shane Mueller said...

I've updated the example--it should work now.