def _hwsetup(self):
     """Set up hardware like displays, sounds, etc"""
     # See documentation for visual.Window parameters
     self.win = visual.Window()
     # store frame rate of monitor if we can measure it successfully
     self.frameRate = self.win.getActualFrameRate()
     if self.frameRate is not None:
         self.frameDur = 1.0/round(self.frameRate)
     else:
         self.frameDur = 1.0/60.0  # couldn't get a reliable measure/guess
     # Set up the sound card
     sound.init(rate=48000, stereo=True, buffer=256)
     # Create some handy timers
     self.clock = core.Clock()  # to track the time since experiment started
     # Create a parallel port handler
     self.port = parallel.ParallelPort(address=0x0378)
Example #2
0
 def _hwsetup(self):
     """Set up hardware like displays, sounds, etc"""
     self.win = visual.Window(size=(1280, 1024),
                              fullscr=True,
                              allowGUI=False,
                              useFBO=True,
                              monitor='testMonitor',
                              units='norm')
     # store frame rate of monitor if we can measure it successfully
     self.frameRate = self.win.getActualFrameRate()
     # Create a parallel port handler
     self.port = parallel.ParallelPort(address=0x0378)
     self.clock = core.Clock()  # to track the time since experiment started
     if self.frameRate is not None:
         self.frameDur = 1.0 / round(self.frameRate)
     else:
         self.frameDur = 1.0 / 60.0  # couldn't get a reliable measure/guess
     # Set up the sound card
     sound.init(rate=48000, stereo=True, buffer=256)
Example #3
0
 def start(self):
     #print("initializing")
     self.pm2812 = gpib.find("pm2812")
     self.hp6633a = gpib.find("6633a")
     #select channel 1 and enable
     self.port = parallel.ParallelPort(address=0x0378)
     gpib.write(self.pm2812,"INST:NSEL 1")
     gpib.write(self.pm2812,"OUTP ON")
     gpib.write(self.pm2812,"VOLT 0")
     #select channel 2 and enable
     gpib.write(self.pm2812,"INST:NSEL 2")
     gpib.write(self.pm2812,"OUTP ON")
     gpib.write(self.pm2812,"VOLT 0")
     #select 6633a
     gpib.write(self.hp6633a,"CLR")
     gpib.write(self.hp6633a ,"VSET 0")
     gpib.write(self.hp6633a,"OUTP ON")
     self.enable = True
     self.syncDio()
def send_code(code):
    '''    This is a function for sending trigger to our parallel port
    :param code: code number
    :return: the code that recognizable for our digitimer and bio-pac
    
    in behavioural lab 2, pin 2 is digitimer, pin 3 is channel 28, pin 4 is channel 29.
    In behavioural lab 1, pin 2 is ....
    '''
    # set all the port to zero before the experiment start
    port = parallel.ParallelPort(0x0378)
    port.setData(0) # set all pins low
    if code == 1:         # marker the start and the end of block, both triggers are sent
        port.setPin(2, 0) # Send 0 to pin 2, i.e., no shcok
        port.setPin(3, 1) # Send 1 to pin 3 (channel 28), as marker
        port.setPin(4, 1) # Send 1 to pin 4 (channel 29), as marker
        core.wait(0.025)
        port.setPin(2, 0) # pin 2 back to 0
        port.setPin(3, 0) # pin 3 back to 0
        port.setPin(4, 0) # pin 4 back to 0
    elif code == 3:       # CS+
        port.setPin(2, 0) # Send 0 to pin 2, i.e., no shcok
        port.setPin(3, 1) # Send 1 to pin 3, as marker
        port.setPin(4, 0) # Send 0 to pin 4, as marker
        core.wait(0.025)
        port.setPin(2, 0) # pin 2 back to 0
        port.setPin(3, 0) # pin 3 back to 0
        port.setPin(4, 0) # pin 1 back to 0
    elif code == 2:       # CS+ with shocks
        port.setPin(2, 0) # Send 0 to pin 2, i.e., no shcok
        port.setPin(3, 1) # Send 1 to pin 3, as marker
        port.setPin(4, 0) # Send 0 to pin 4, as marker
        core.wait(0.025)
        port.setPin(2, 0) # pin 2 back to 0
        port.setPin(3, 0) # pin 3 back to 0
        port.setPin(4, 0) # pin 1 back to 0
    elif code == 4:       # CS-
        port.setPin(2, 0) # Send 1 to pin 2, i.e., no shcok
        port.setPin(3, 0) # Send 1 to pin 3, as marker
        port.setPin(4, 1) # Send 0 to pin 4, as marker
        core.wait(0.025)
        port.setPin(2, 0) # pin 2 back to 0
        port.setPin(3, 0) # pin 3 back to 0
        port.setPin(4, 0) # pin 4 back to 0
Example #5
0
    def __init__(self,
                 pp_address,
                 zeroTTL=True,
                 lookup_func=int,
                 verbose=True):
        """
        send codes to LPT 'pp_address'.
        optionally set the TTL to zero after
        b/c TTL is limited 0-255. use lookup_func to lookup codes for event
        NB. this introduces a .01 second lag
        TODO: use async?
        """
        from psychopy import parallel
        self.zeroTTL = zeroTTL
        self.pp_address = pp_address
        self.port = parallel.ParallelPort(address=pp_address)
        self.lookup_func = lookup_func
        self.verbose = verbose

        # need core.wait for zeroing
        if zeroTTL:
            from psychopy import core
Example #6
0
def play(order, interval, s0, s1):
    '''
    :param order: order with which the sounds are to be played
    :param interval: the interval between consecutive sounds
    :param s0: the array of the negative sound
    :param s1: the array of the positive sound
    :return:
    '''
    supported = True
    port = parallel.ParallelPort(address=0x0378)
    loop = asyncio.get_event_loop()
    for i in order:
        time.sleep(interval)
        if i:
            loop.run_until_complete(async_play_send(s0, 0, port))
        else:
            loop.run_until_complete(async_play_send(s1, 1, port))
        time.sleep(len(s0) / 44100)
    time.sleep(interval * 5)
    try:
        port.setData(0)
    except:
        pass
##### SETUP #####

#Experimenter input
dlg = gui.Dlg(title = 'Experiment Parameters')
dlg.addField('Subject ID:')
dlg.addField('Run', choices = ['1','2','3','4',])
dlg.addField('Scanner', choices = ['yes','no'])
dlg.addField('Stimulus Threshold (in Frames):')
dlg.addField('Go Side', choices = ['left','right'])
dlg.addField('Practice', choices = ['yes','no'])
dlg.addField('Language', choices = ['en', 'de'])

exp_input = dlg.show()

port = parallel.ParallelPort(0x1FF8)
### Parameters ###
language = exp_input[6]
###### EDIT PARAMETERS BELOW #######

stim_dur = {'strong':1,'weak':float(exp_input[3])}     # time in seconds that the subliminal stim appears on the screen [strong,weak,catch]
blank_dur = {'strong':2,'weak':2}        # time a blank screen between stim and mask is on screen [strong,weak,catch]
mask_dur = {'strong':12,'weak': 12 - float(exp_input[3]) + 1}     # time the mask appears on the screen [strong,weak,catch]
response_dur = 78              # time the response period stays on the screen
fixation_dur = 12			# fixation before stimulus_strength
blank_dur_pre = 3
pause_dur = 1200
#strength_prob = [.5,.5]   # probability of the trial being strong or weak
stim_size = .06             #size of the stimulus on screen
mask_size_ratio = 1.6         #how much proptionally bigger is mask
#stim_line_width =  200      # width of diamond frame lines
Example #8
0
#Creates window for the experiment
win = visual.Window(size=(1920, 1200),
                    fullscr=True,
                    screen=0,
                    allowGUI=False,
                    allowStencil=False,
                    monitor=u'testMonitor',
                    color=[0, 0, 0],
                    colorSpace=u'rgb',
                    blendMode=u'avg',
                    winType='pyglet')

expInfo[u'frameRate'] = win.getActualFrameRate()
#Input
port = parallel.ParallelPort(address=0x1120)  #For output
inp = parallel.ParallelPort(
    address=0x1121
)  #For input from handles, gulmarkerade = 63, svartmarkerade = 255

#Instructions
instruk = u"""Your task is to match the intensity a sound with the intensity of the vibrations. You are going to match 12 times in each part of the experiment.
You should adjust the intensity of the sound to a level that you perceive matches the intensity of the vibration. \n \ n
For example, if you perceive the sound intensity lower than the vibrations intensity adjust the sound by pressing on the right button (i.e., increase the volume of the sound) until you think that it matches the vibration.  \n
Hold the handles in your hands,\n
Press a button on either one of the handles to start the task."""

ainstruk = u'''Your task is to match the distractibility of the sound to that of the vibrations by adjusting the level of the sound until you feel that it is equally distracting as the vibration.  You are going to match 12 times in each part of the experiment (i.e., in each block).
For example, if you perceive the sound, at current volume, is less distracting than the vibration adjust the sound by pressing on the right button (i.e., increase the volume of the sound) until you think that it matches the vibrations distractibility.  \n
Hold the handles in your hands,\n
Press a button on either one of the handles to start the task.'''
class port:

    """
    Doesn't do anything, just makes it easy to test without parallel ports
    """

    @staticmethod
    def setData(a):
        a = 2

    @staticmethod
    def setPin(a, b):
        a = 2

port = parallel.ParallelPort(address=0x2cf8)  # TODO UNCOMMENT THIS IF YOU WANT PARALLEL PORTS TO WORK!!!!!

script_location = os.path.dirname(__file__)

# Data containers for each trial
dataCategories = ['id', 'trial_number', 'Rewarded', 'Response', 'A_reward', 'RT', 'Duration', 'Reward_prob', 'Confidence', 'Condition', 'Contingencies']
trial = dict(zip(dataCategories,['' for i in dataCategories]))

# Set monitor variables
myMon = monitors.Monitor('testMonitor')

# Intro dialogue
dialogue = gui.Dlg()
dialogue.addField('subjectID')
dialogue.show()
if dialogue.OK:
Example #10
0
                              flipHoriz=False,
                              flipVert=False,
                              texRes=128,
                              interpolate=True,
                              depth=-1.0)
for n in range(10):  #Cedrus connection doesn't always work first time!
    try:
        devices = pyxid.get_xid_devices()
        core.wait(0.1)
        buttonBox = devices[0]
        break  #once we found the device we can break the loop
    except:
        pass
buttonBox.status = NOT_STARTED
buttonBox.clock = core.Clock()
p_port = parallel.ParallelPort(address=u'0xE010')

# Initialize components for Routine "highlight"
highlightClock = core.Clock()
imageLeftHL = visual.ImageStim(win=win,
                               name='imageLeftHL',
                               image='sin',
                               mask=None,
                               ori=0,
                               pos=[-0.3, 0],
                               size=[0.3, 0.5],
                               color=[1, 1, 1],
                               colorSpace='rgb',
                               opacity=1,
                               flipHoriz=False,
                               flipVert=False,
reskeys_list = ['b','z']
pix_size = .001

practice_iti_dur = 2
practice_stim_dur = 1.5

#Design stuff
nr_blocks = 14
nr_trial_per_block = 6
duration_rest = 9

###### STOP EDITING BELOW THIS LINE #######

## ParallelPort

port = parallel.ParallelPort()


#Experimenter input
dlg = gui.Dlg(title = 'Experiment Parameters')
dlg.addField('Subject ID:')
dlg.addField('Session:')
dlg.addField('Scanner', choices = ['yes','no'])
dlg.addField('Practice', choices = ['yes','no'])
dlg.addField('Opacity:')
exp_input = dlg.show()

subid = exp_input[0]
session = exp_input[1]
if exp_input[2] == 'yes':
	scanner = True
Example #12
0
                    monitor='testMonitor',
                    color=[0, 0, 0],
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='height')
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
if expInfo['frameRate'] != None:
    frameDur = 1.0 / round(expInfo['frameRate'])
else:
    frameDur = 1.0 / 60.0  # could not measure, so guess

# Initialize components for Routine "trial"
trialClock = core.Clock()
p_port = parallel.ParallelPort(address=u'0x0378')

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer(
)  # to track time remaining of each (non-slip) routine

# ------Prepare to start Routine "trial"-------
t = 0
trialClock.reset()  # clock
frameN = -1
continueRoutine = True
routineTimer.add(1.000000)
# update component parameters for each repeat
# keep track of which components have finished
trialComponents = [p_port]
from psychopy import core
from psychopy import visual
from psychopy import monitors
from psychopy import gui
from psychopy import event
from psychopy import parallel

port = parallel.ParallelPort(address=0x0378)

monitors_ = {"office": [1920, 1080, 52.70, 29.64, 56]}


def trigger(send_bit):
    port.setData(send_bit)
    core.wait(0.004)
    port.setData(0)


which_monitor = "office"
mon = monitors.Monitor("default")
w_px, h_px, w_cm, h_cm, d_cm = monitors_[which_monitor]
mon.setWidth(w_cm)
mon.setDistance(d_cm)
mon.setSizePix((w_px, h_px))

win = visual.Window([w_px, h_px],
                    monitor=mon,
                    units="deg",
                    color="#000000",
                    fullscr=True,
                    allowGUI=False,
# Test parameters
ppt = False  # Using parallel port to send triggers
sst = True  # Using parallel port to send triggers
fullscreen = True
ntrials = 30
gap_dur = 1
grating_dur = 0.2

prefs.hardware['audioLib'] = [
    'pyo'
]  # use Pyo audiolib for good temporal resolution
from psychopy.sound import Sound  # This should be placed after changing the audio library

if ppt:
    p_port = parallel.ParallelPort(address=u'0x0378')  # this is for windows
if sst:
    p_port = serial.Serial('COM3', 115200, timeout=0)  # this is for windows
    p_port.write(b'00')
    core.wait(0.2)
    p_port.write(b'RR')
#p_port_2 = parallel.ParallelPort(address=u'0x0378')
#p_port = parallel.ParallelPort(address='/dev/parport0') # this is for linux

#create a window
win = visual.Window([800, 600],
                    monitor="testMonitor",
                    units="deg",
                    fullscr=fullscreen)

#create some stimuli
                             mask=None,
                             ori=0,
                             pos=[0, 0],
                             size=[200, 200],
                             color=[1, 1, 1],
                             colorSpace='rgb',
                             opacity=0,
                             flipHoriz=False,
                             flipVert=False,
                             texRes=128,
                             interpolate=True,
                             depth=-2.0)

if actually_send_triggers:
    from psychopy import parallel
    parallel_trigger = parallel.ParallelPort(address='0xd050')
    #    eeg_trigger = parallel.ParallelPort(address='0xcff8')
    parallel_trigger.setData(0)
#    eeg_trigger.setData(0)
prepare_time = core.StaticPeriod(win=win,
                                 screenHz=expInfo['frameRate'],
                                 name='prepare_time')
stop_signal = visual.Rect(win=win,
                          name='stop_signal',
                          width=[60, 60][0],
                          height=[60, 60][1],
                          ori=0,
                          pos=[0, 2],
                          lineWidth=1,
                          lineColor=[0, 0, 1],
                          lineColorSpace='rgb',
Example #16
0
def send_signal(data):
    port = parallel.ParallelPort(address=config.PARALLEL_PORT_ADDRESS)
    port.setData(data)
    time.sleep(1)
    port.setData(0)  #reset
Example #17
0
#        raise RuntimeError("Video File could not be found:"+vismaskpath)

#if not os.path.exists(pixpath):
#        raise RuntimeError("Video File could not be found:"+pixpath)

TRIALS_FILE = 'movie_block.csv'

#---------------------------------------
# Set up parallel port
#---------------------------------------

pparallel = None
try:
    from psychopy import parallel

    pparallel = parallel.ParallelPort(address=0x378)  #888
except ImportError:

    class DummyParallel:
        def setData(self, val):
            print("Port parallele: setData %s" % val)

    pparallel = DummyParallel()

trigger_stim = int("00000011", 2)
trigger_mask = int("00000101", 2)
trigger_space = int("00010100", 2)
trigger_fixation = int("10100000", 2)

#---------------------------------------
# Store info about the experiment session
Example #18
0
# Initialize components for Routine "Trial"
TrialClock = core.Clock()
FixationPoint = visual.TextStim(win=win,
                                ori=0,
                                name='FixationPoint',
                                text='+',
                                font='Arial',
                                pos=[0, 0],
                                height=0.1,
                                wrapWidth=None,
                                color=1.0,
                                colorSpace='rgb',
                                opacity=1,
                                depth=0.0)
p_port = parallel.ParallelPort(address=u'0xDFF8')
p_port_images = parallel.ParallelPort(address=u'0xDFF8')

# Initialize components for Routine "Break"
BreakClock = core.Clock()
Break = visual.TextStim(
    win=win,
    ori=0,
    name='Break',
    text=
    'That was the end of the block.\n\nIf you need to take a break please take one now.\n\nWhen you are ready to continue please press the spacebar.',
    font='Arial',
    pos=[0, 0],
    height=0.1,
    wrapWidth=1.5,
    color='white',
Example #19
0
from __future__ import absolute_import, division
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, clock, parallel
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
                                STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
                   sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding

sendTTL = False
parallelPortAddress = 49168

if sendTTL:
    port = parallel.ParallelPort(address = parallelPortAddress)
    port.setData(0) #make sure all pins are low

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding())
os.chdir(_thisDir)

# Store info about the experiment session
expName = u'test_experiment'  # from the Builder filename that created this script
expInfo = {u'session': u'001', u'participant': u''}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False:
    core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName
#===================================================
def clean_quit():
    #    os.system("sudo /home/knight_lab/Startup_Scripts/python_priority_rush_off.sh")     # If using core.rush in Linux
    rtbox.close()
    win.close()
    if paradigm_type == 'eeg':
        port.setData(255)  # stop EEG recording
    core.quit()


#============================================================
# INSTRUCTIONS
#============================================================
if paradigm_type == 'eeg':
    port = parallel.ParallelPort(address=53504)
    port.setData(254)  # start BioSemi recording
    core.wait(1)  # biosemi needs a pause to read the start trigger
    port.setData(0)  # sets all pins low

# ECoG Photodiode flicker sequence to signal start of data block
if paradigm_type == 'ecog':
    for flick in range(n_flicker):
        trigger_rect.draw()
        win.flip()
        core.wait(flicker_dur)
        win.flip()
        core.wait(flicker_dur)
        if flick % flicker_brk == flicker_brk - 1:
            core.wait(flicker_dur)
Example #21
0
     def __init__(self, 
                  messagedict,
                  clock, 
                  destip='127.0.0.1', 
                  destport=6500, 
                  LPTAddress=0x0378,
                  filename='log/triggerlog.log',
                  sendParallel=True, 
                  sendTcpIp=True, 
                  sendLogFile=True
                  ):
         '''
         we check parallel port, network port, and a file here (and we use the
         logger to do all of that log stuff)
         '''
         
         super(eventHandler, self).__init__()
         
         self.messagedict=messagedict
         self.clock=clock
         self.sendParallel=sendParallel
         self.sendTcpIp=sendTcpIp
         self.sendLogFile=sendLogFile
         self.destip=destip
         self.destport=destport
         
         
         # do we even have a parallel port?
         try:
             self._port=parallel.ParallelPort(LPTAddress)
             self._port.setData(0)  # this is the 'reset' to 0
             self._port_doreset=False  # once done we shouldn't do it..
             self._port_waitttime=0.005  # wait 5 msec after a trigger..
             
         except OSError:
             self._port=None
             self._port_doreset=False
             self._port_waitttime=None
             print('OS Does not seem to have a parallel port')
             # deactivate our parallel...
             self.sendParallel=False
             
         self._queue = multiprocessing.Queue()
         
         self._timequeue = multiprocessing.Queue()
         
         self._shutdown = multiprocessing.Event()
         
 
         
         # check whether there's another logfile - in log directory
         # make efl_triggers version of it, too.
         logdir=os.path.dirname(filename)
         logbasename, ext = os.path.splitext(os.path.basename(filename))
 
         
         # figure out if there's a log directory, if not --> make it:
         if not os.path.exists(logdir):
             os.makedirs(logdir)
         
         # figure out which files reside within this logfile directory:
         if len(os.listdir(logdir)) == 0:
             logcounter=0
         else:
             # figure out biggest number:
             matches=[match for match in [re.match(logbasename+'([0-9]*)'+ext,item) for item in os.listdir(logdir)]]
             newlist=[]
             for match in matches:
                 if match is not None:
                     newlist.append(match.group(1))
             logcounter = max([int(n) for n in newlist])
                     
                     
         
         # so make just another logfile on top of this one -- it'll be timestamped    
         logcounter += 1
         
         # this is the new logfile:
         newLogFile=os.path.join(logdir,logbasename+'%d'%logcounter + ext )
         
         
         # open up a log:
         self.expLogger = logging.LogFile(newLogFile, logging.EXP) # the correct loglevel should be EXP!
         
         
         
         # so that's the logfile -- open op the socet, too:
         self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 
         
         
         print(newLogFile)
Example #22
0
                        allowGUI=False,
                        color="black")

    ## stimulus
    # Setup each present stimulus before experiment began
    # Fixation cross is just the character "+".
    fix = visual.TextStim(win, "+")
    # Stimulus state
    stim_text = visual.TextStim(win,
                                height=config.MESSAGE_HEIGHT,
                                wrapWidth=config.MESSAGE_WIDTH)
    # Initate parallel port
    if eeg:
        ## May need to manually key in the address ##
        #pp = parallel.ParallelPort(address = 0x0378)
        pp = parallel.ParallelPort(address=0xEFB8)
        pp.setData(0)


###################
## (2).Functions ##
###################
def pp_reset(eeg):
    if eeg:
        pp.setData(0)


def keypress(config):
    """Keypress for the experiment
    Accepts only responds and quit keys set in the configuration file
    and if quit key is accepted, close out the window.
Example #23
0
home = os.path.expanduser('~')

#i/o
if 'factory' in SCRN:
    # data_dir = 'C://Users//dunsmoorlab//Desktop//Experiments//{:s}//{:s}'.format(PROJ_NAME,SUBJ)
    data_dir = os.path.join(home, 'Desktop', 'Experiments', PROJ_NAME, SUBJ)
else:
    data_dir = os.path.join(home, 'Db_lpl', 'STUDY', 'ExPress')

#read in the design file with everything on it
design = pd.read_csv('express_design.csv')

#initialize the parallel port if in the testing room
if BIO:
    port = parallel.ParallelPort(address=0xDFF8)
    port.setData(0)

#initialize some vairables
N_RUNS = 4  # number of runs
N_TRIALS = 60  # total per run
STIM_SECS = 6  # day1 encoding duration
ITI_SECS = 1
phase_names = ['mem1', 'mem2', 'mem3',
               'mem4']  # the names of each phase for memory_runs

# there are 4 groups of animals/tools/food that are always seen together,
# these lines randomize which group of images go to which phase
blocks = [1, 2, 3, 4]
np.random.shuffle(blocks)
Example #24
0
def pingTMS(ping_at):
    port.setData(1)  # send a one to the TMS machine to make it send a pulse
    print("\nping with {} milliseconds on the timer\n".format(
        round(ping_at * 1000, 6)))


def pingDummy(ping_at):
    print("ping {} seconds after the timer elapsed".format(round(ping_at, 6)))
    print("ping {} milliseconds after the timer elapsed".format(
        round(ping_at * 1000, 6)))
    print("")


# Initialise the parallel port if it exists, otherwise run the script with a dummy parallel port
if os.path.exists('/dev/parport0'):
    port = parallel.ParallelPort('/dev/parport0')
else:
    port = "dummy_port"
    print("\nWARNING: Proceeding with a dummy port\n")

videopath = r'./movies/jwpIntro.mov'
videopath = os.path.join(os.getcwd(), videopath)
if not os.path.exists(videopath):
    raise RuntimeError("Video File could not be found:" + videopath)

benq = monitors.Monitor(name="benq", width=53.5, distance=75.0)
benq.saveMon()
win = visual.Window(size=[1024, 768],
                    pos=[(1920 - 1024) / 2, (1080 - 768) / 2],
                    monitor=benq,
                    allowGUI=False)
Example #25
0
                                  colorSpace='rgb',
                                  opacity=1,
                                  depth=0.0)
textPreCue = visual.TextStim(win=win,
                             ori=0,
                             name='textPreCue',
                             text=u'+',
                             font=u'Arial',
                             pos=[0, 0],
                             height=0.1,
                             wrapWidth=None,
                             color=u'black',
                             colorSpace='rgb',
                             opacity=1,
                             depth=-1.0)
p_port = parallel.ParallelPort(address=u'0xD010')

# Initialize components for Routine "trial"
trialClock = core.Clock()
imageCard = visual.ImageStim(win=win,
                             name='imageCard',
                             image='sin',
                             mask=None,
                             ori=0,
                             pos=[0, 0],
                             size=[0.3, 0.5],
                             color=[1, 1, 1],
                             colorSpace='rgb',
                             opacity=1,
                             flipHoriz=False,
                             flipVert=False,
Example #26
0
    letterstimtex = []
    for (i, y) in enumerate(letterstimuli):
        letterstimtex.append(visual.TextStim(win, height=128, text=y, name=y))

    def send_dummy_trigger(trigger_value):
        core.wait(trigger_duration)

    def send_real_trigger(trigger_value):
        trigger_port.setData(trigger_value)
        core.wait(trigger_duration)
        trigger_port.setData(0)

    if debug_usedummytriggers:
        sendtrigger = send_dummy_trigger
    else:
        trigger_port = parallel.ParallelPort(address=trigger_port)
        trigger_port.setData(0)
        sendtrigger = send_real_trigger

    nevents = eventlist[-1][0]
    nsequences = eventlist[-1][1]
    sequencenumber = -1
    for eventnr in range(len(eventlist)):
        if eventlist[eventnr][1] > sequencenumber:
            writeout(eventlist)
            sequencenumber = eventlist[eventnr][1]
            condition = eventlist[eventnr][2]
            correct = 0

            if not debug_testsubject:
                try:
Example #27
0
##    screenRes = [1920, 1200]
#    if params['screenToShow']>0:
#        params['fullScreen'] = False
#else:
#    screenRes = [800,600]

screenRes = (1024,768)
print "screenRes = [%d,%d]"%screenRes


# ========================== #
# == SET UP PARALLEL PORT == #
# ========================== #

if params['sendPortEvents']:
    port = parallel.ParallelPort(address=params['portAddress'])
    port.setData(0) # initialize to all zeros
else:
    print "Parallel port not used."
    

# ========================== #
# ===== SET UP STIMULI ===== #
# ========================== #
#from psychopy import visual

# Initialize deadline for displaying next frame
tNextFlip = [0.0] # put in a list to make it mutable (weird quirk of python variables) 

#create clocks and window
globalClock = core.Clock()#to keep track of time
from psychopy import locale_setup, sound, gui, visual, core, data, event, logging, parallel

from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
                                STOPPED, FINISHED, PRESSED, RELEASED, FOREVER)
import numpy as np  # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
                   sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle
import os  # handy system and path functions
import sys  # to get file system encoding

# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(sys.getfilesystemencoding())
os.chdir(_thisDir)

p_port = parallel.ParallelPort(address='0xC010') #set up a class
p_port.setData(0) #clear out the pport

# define a function that sends triggers
def send_trigger(trg):
    """Send a trigger :D"""
    p_port.setData(0)
    core.wait(.0025)
    p_port.setData(trg)
    core.wait(0.005)
    p_port.setData(0)


# define a dictionary that contains the music genre-trigger mapping, also including sound off & pause triggers
trg_dict = {"alternative.wav": 1,
            "baroque.wav": 2,
wd = os.getcwd()
fname = os.path.expanduser(wd + "\\logfile\\"+ "morphFaces_ET_" + exp_info["university"] + "_S" + exp_info["Num Sujet"] + "_" + exp_info["session"] + ".csv")

i=1
while exists(fname) == True:
    print "Logfile name alredy exists"
    fname = os.path.expanduser(wd + "\\logfile\\"+ "morphFaces_ET_" + exp_info["university"] + "_S" + exp_info["Num Sujet"] + "_" + exp_info["session"] + str(i) + ".csv")
    i+=1
    
datafile = open(fname, "wb")
writer = csv.writer(datafile, delimiter =";")

# Parallel port initialization
parallelPortID = 0xD020
portP = parallel.ParallelPort(address = parallelPortID)
# Add experiment ID 3 times
portP.setData(0) # resets the port to 0
portP.setData(7); core.wait(0.1)
portP.setData(0); core.wait(0.1)
portP.setData(7); core.wait(0.1)
portP.setData(0); core.wait(0.1)
portP.setData(7); core.wait(0.1)
portP.setData(0);

# *********************
# ***LANGUAGE SETUP ***

# Load instruction image
img_instr = visual.ImageStim(win)
img_instr.setImage("instruen.png")
Example #30
0
yellow = [yellow_one, yellow_two, yellow_three]

# Both Handles
# Activate pin 2 + 4 (Speed 1)
both_one = int("00000101", 2)
# Activate pin 5 + 3 (Speed 2)
both_two = int("00001010", 2)
# Activate pin 2, 3, 4 & 5 (Speed 1+2)
both_three = int("00001111", 2)

both = [both_one, both_two, both_three]

# Vibrations

vibs = {'black': black, 'yellow': yellow, 'both': both}

port = pp.ParallelPort(adress=0x3FF8)

# In the loop we go from the 'black' to the 'yellow' and the both handles
for key in vibs:
    for speed in vibs[key]:

        # Activate and start vibration
        port.setData(speed)

        # Vibrate for 400ms.
        core.wait(.4)

        # Stop vibration
        port.setData(0)