How to use the psychopy.core.Clock function in psychopy

To help you get started, we’ve selected a few psychopy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github psychopy / psychopy / psychopy / demos / coder / experiment control / JND_staircase_exp.py View on Github external
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='simple JND Exp', fixed=['date'])
if dlg.OK:
    misc.toFile('lastParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

#make a text file to save data
fileName = expInfo['observer'] + dateStr
dataFile = open(fileName+'.txt', 'w')
dataFile.write('targetSide	oriIncrement	correct\n')

#create window and stimuli
globalClock = core.Clock()#to keep track of time
trialClock = core.Clock()#to keep track of time
win = visual.Window([800,600],allowGUI=False, monitor='testMonitor', units='deg')
foil = visual.PatchStim(win, sf=1, size=4, mask='gauss', ori=expInfo['refOrientation'])
target = visual.PatchStim(win, sf=1,  size=4, mask='gauss', ori=expInfo['refOrientation'])
fixation = visual.PatchStim(win, color='black', tex=None, mask='circle',size=0.2)
message1 = visual.TextStim(win, pos=[0,+3],text='Hit a key when ready.')
message2 = visual.TextStim(win, pos=[0,-3], text="Then press left or right to identify the %.1fdegree probe." %(expInfo['refOrientation']))

#create the staircase handler
staircase = data.StairHandler(startVal = 20.0,
                          stepType = 'lin', stepSizes=[8,4,4,2,2,1,1], #reduce step size every two reversals
                          minVal=0, maxVal=90,
                          nUp=1, nDown=3,  #will home in on the 80% threshold
                          nTrials=50)

#display instructions and wait
github psychopy / psychopy / psychopy / demos / coder / stimuli / counterphase.py View on Github external
from psychopy import core, visual, event
from numpy import sin, pi

# Create a window to draw in
win = visual.Window((600, 600), allowGUI=False, monitor='testMonitor', units='deg')

# Initialize some stimuli
grating1 = visual.GratingStim(
    win, tex="sin", mask="circle", texRes=128,
    color='white', size=5, sf=2, ori=45, depth=0.5, autoLog=False)
message = visual.TextStim(
    win, text='Any key to quit',
    pos=(-0.95, -0.95), units='norm',
    anchorVert='bottom', anchorHoriz='left')

trialClock = core.Clock()
t = 0
while not event.getKeys() and t < 20:  # quits after 20 secs
    t = trialClock.getTime()

    grating1.contrast = sin(t * pi * 2)
    grating1.draw()
    message.draw()

    win.flip()

win.close()
core.quit()
github psychopy / psychopy / psychopy / demos / coder / stimuli / textbox_editable.py View on Github external
#!/usr/bin/env python
# -*- coding: utf-8 -*-


from psychopy import visual, core, event, logging

logging.console.setLevel(logging.DEBUG)
c = core.Clock()

from psychopy.visual.textbox2 import TextBox2, allFonts

win = visual.Window([800, 800], monitor='testMonitor', backend='glfw')
logging.exp("{:.3f}: created window".format(c.getTime()))

text = u"<i>The quick</i> brown <b>fox</b> jumped"
loremIpsum = u"PsychoPy is an open-source Python application allowing you to run a supercali-fragilisticexpeilidocious wide range of neuroscience, psychology and psychophysics experiments. It’s a free, powerful alternative to Presentation™ or e-Prime™, written in Python (a free alternative to Matlab™ g)."

fontSize = 16
# preload some chars into a font to see how long it takes
nChars = 256
arial = allFonts.getFont("Arial", fontSize)
logging.exp("{:.3f}: created font".format(c.getTime()))
arial.preload(nChars)
logging.exp("{:.3f}: preloaded {} chars".format(c.getTime(), nChars))
github psychopy / psychopy / psychopy / demos / coder / stimuli / MovieStim.py View on Github external
To create a movie that will play on all systems I would recommend using the format:
    video: H.264 compressed,
    audio: Linear PCM
"""

from __future__ import division
from __future__ import print_function

from psychopy import visual, core, event

win = visual.Window((800, 600))
mov = visual.MovieStim3(win, 'jwpIntro.mov', size=(320, 240),
    flipVert=False, flipHoriz=False, loop=False)
print('orig movie size=%s' % mov.size)
print('duration=%.2fs' % mov.duration)
globalClock = core.Clock()

while mov.status != visual.FINISHED:
    mov.draw()
    win.flip()
    if event.getKeys():
        break

win.close()
core.quit()
github psychopy / psychopy / psychopy / demos / coder / timing / clocksAndTimers.py View on Github external
Demo for clocks and count-down timers
"""

from __future__ import division
from __future__ import print_function

from psychopy import core
core.wait(0.5)  # give the system time to settle

# create a clock
clock = core.Clock()
clock.reset()  # whenever you like

# to create a timer you can 'add' time to the zero point
# and wait to get back to zero
timer = core.Clock()
timer.add(3)

# there's also a countdown timer (just a flip of the clock)
countDown = core.CountdownTimer()
countDown.add(3)

another = core.Clock()

print("down       up          clock")
while countDown.getTime() > 0:
    msg = "%.4f   %.4f   %.4f"
    print(msg % (countDown.getTime(), timer.getTime(), clock.getTime()))
    core.wait(0.2)  # this combined + print will allow a gradual timing 'slip'

# use the timer, rather than wait(), to prevent the slip
print("\ndown          clock")
github adopy / adopy / examples / dd / dd_psychopy_ado.py View on Github external
def run_trial(design):
    """Run one trial for the delay discounting task using PsychoPy."""
    global window

    # Direction: -1 (L - LL / R - SS) or
    #            1  (L - SS / R - LL)
    direction = np.random.randint(0, 2) * 2 - 1  # Return -1 or 1
    is_ll_on_left = int(direction == -1)

    draw_option(design['t_ss'], design['r_ss'], -1 * direction)
    draw_option(design['t_ll'], design['r_ll'], 1 * direction)
    window.flip()

    timer = core.Clock()
    keys = event.waitKeys(keyList=KEYS_LEFT + KEYS_RIGHT)
    rt = timer.getTime()

    key_left = int(keys[0] in KEYS_LEFT)
    response = int((key_left and is_ll_on_left) or
                   (not key_left and not is_ll_on_left))  # LL option

    draw_option(design['t_ss'], design['r_ss'], -1 * direction, response == 0)
    draw_option(design['t_ll'], design['r_ll'], 1 * direction, response == 1)
    window.flip()
    core.wait(1)

    # Show an empty screen
    window.flip()
    core.wait(1)
github qbilius / psychopy_ext / scripts / exp.py View on Github external
def loop_trials(self, datafile='data.csv', noOutput=False):
        """
        Iterate over the sequence of events
        """
        if not noOutput:
            self.try_makedirs(os.path.dirname(datafile))
            dataFile = open(datafile, 'wb')
            dataCSV = csv.writer(dataFile, lineterminator = '\n') 
            header = self.extraInfo.keys() + self.trialList[0].keys()
            dataCSV.writerow(header)

        # set up clocks
        globClock = core.Clock()
        trialClock = core.Clock()
        eventClock = core.Clock()

        # go over the trial sequence
        for thisTrial in self:
            trialClock.reset()
            thisTrial['onset'] = globClock.getTime()

            # go over each event in a trial
            allKeys = []
            for j, thisEvent in enumerate(self.trial):
                eventClock.reset()
                eventKeys = thisEvent['defaultFun'](globClock, trialClock, eventClock,
                    thisTrial, thisEvent, j)
                if eventKeys is not None: allKeys += eventKeys
                # this is to get keys if we did not do that during trial
                allKeys += event.getKeys(
                    keyList = self.comp.validResponses.keys(),
github BciPy / BciPy / bcipy / tasks / rsvp / calibration.py View on Github external
def __init__(self, win, daq, parameters, file_save):
        super(RSVPCalibrationTask, self).__init__()

        self.window = win
        self.frame_rate = self.window.getActualFrameRate()
        self.parameters = parameters
        self.daq = daq
        self.static_clock = core.StaticPeriod(screenHz=self.frame_rate)
        self.experiment_clock = core.Clock()
        self.buffer_val = parameters['task_buffer_len']
        self.alp = alphabet(parameters)
        self.rsvp = init_calibration_display_task(
            self.parameters, self.window, self.daq,
            self.static_clock, self.experiment_clock)
        self.file_save = file_save
        trigger_save_location = f"{self.file_save}/{parameters['triggers_file_name']}"
        self.trigger_file = open(trigger_save_location, 'w')

        self.wait_screen_message = parameters['wait_screen_message']
        self.wait_screen_message_color = parameters[
            'wait_screen_message_color']

        self.num_sti = parameters['num_sti']
        self.len_sti = parameters['len_sti']
        self.timing = [parameters['time_target'],
github wehr-lab / autopilot / autopilot / stim / visual / visuals.py View on Github external
def __init__(self, debug=False):
        # psychopy Window
        self.win = None
        self.duration = None
        self.ppo = None # psychopy object
        #self.get_window()

        self.debug = debug

        self.clock = core.Clock()
        self.draw_time = 0

        self.thread_lock = threading.Lock()