Search code examples
matlabpsychtoolbox

Explaning a line in code from PsychToolBox tutorial


I am learning PsychToolBox and referring to this tutorial. http://peterscarfe.com/movingdotgriddemo.html

There is this line :

vbl  = Screen('Flip', window, vbl + (waitframes - 0.5) * ifi); 

which I cannot figure out. Can someone please explain it to me? Especially the vbl + (waitframes - 0.5) * ifi) part. Thanks!


Solution

  • Everything Alex said is correct; I'm just adding an explanation for the -0.5 (I don't have enough reputation to comment on his answer)

    To recap: On each loop / frame, you flip the screen buffers and get the time of the flip in the vbl variable. In the next loop, you time the next flip according to the last one, i.e. vbl + [some number of seconds]. Thus your line of code is both using the previous value of vbl in the function call, and setting it to a new value which the function returns. vbl is updated on a rolling basis. vbl is the 'vertical blanking' time, a pretty accurate estimate of when your monitor actually refreshed*, so aligning frames to this is a good idea.

    The question is how far ahead from the last vbl to do the next flip. As Alex said, ifi is the time between refreshes, or 1/[your monitor refresh rate in Hz]. Lets ignore waitframes for now and assume you want to flip on every monitor refresh, i.e. waitframes = 1.

    Then your line of code simplifies to

    vbl  = Screen('Flip', window, vbl + ifi/2);
    

    so we are asking to flip half an ifi before the next refresh. Why not just ask to flip on the next refresh, i.e. vbl + ifi? Because that sum is a floating-point calculation and may contain small rounding errors. Screen('Flip') can only swap the screen buffers on the next monitor refresh, so what happens if the error in that sum slightly overshoots? Then you've just asked for a flip time slightly beyond the monitor refresh you actually wanted, and PTB has to wait almost an entire ifi to actually flip**.

    So we ask for a flip time some amount (less than ifi) before the desired monitor refresh - ifi/2 is reasonable. We're really saying "do the next flip ASAP after vbl+ifi/2", knowing both that Screen('Flip') can't actually do it prior to the refresh, and safe in the knowledge that we have ifi/2 leeway to absorb minor inaccuracies in the timing calculation.

    The arithmetic of waitframes is left as an exercise for the reader.

    *assuming PTB is set up correctly to play nice with your hardware - pay attention to those warning messages!

    **Even worse, this might not show up in PTB's errors e.g. the dropped frame count, because PTB has achieved what you asked it: flipped the buffers on the next monitor refresh from your specified time. In that case the only way you'd know your experiment was lagging and presenting mis-timed stimuli would be if you happened to spot it during runtime!