Beispiel #1
0
"""This is a simple lexical decision experiment.

At each trial, an item is displayed and the participant must press the key 'f' if it is a word,
'j' if it is a non-word.
"""

import random
import pandas
from expyriment import design, control, stimuli

STIM_FILE = "stimuli.csv"  # a csv file with two columns: `item` (containing a word or a pseudoword) and `category` ('P' or 'W')
WORD_RESPONSE_KEY = 'f'
NONW_RESPONSE_KEY = 'j'
MAX_RESPONSE_DELAY = 2000

exp = design.Experiment(name="Lexical Decision", text_size=40)
control.initialize(exp)

# prepare the stimuli
materials = pandas.read_csv(STIM_FILE)
trials = [(row['category'], row['item'], stimuli.TextLine(row['item']))
          for _, row in materials.iterrows()]

random.shuffle(trials)

cue = stimuli.FixCross(size=(50, 50), line_width=4)
blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen(
    "Instructions",
    f"""When you'll see a stimulus, your task to decide, as quickly as possible, whether it is a word or not.
#DEFINING STIMULI
fixcross = stimuli.FixCross()
fixcross.preload()
response_key = [misc.constants.K_SPACE]
txt_input=io.TextInput("= ")
#design.experiment.register_wait_callback_function
#----------------------------------------------------------
#TEST 01 DESIGN
NUMBER = [1,2,3,4,5]#,6,7,8,9]
OPERATOR = ["+","x","-"]
#tr=[0,0,0,0,0,0,0,0,0]

for i in range(0,3)#["LEVEL 1"]:#,"LEVEL 2"]:
    print("---lap no. %d---"%i)#level)

    exp = design.Experiment("Arithmetic test")
    control.initialize(exp)
    control.start()

    b = design.Block()
    for i in range (0,10):  #FOR 10 TRIALS
        b.clear_trials()
        b = design.Block()
        print(i)
        tr=atl.arithmetictriall1(NUMBER,OPERATOR)
        print(tr)
        for trel in tr[0]:
            t=design.Trial()
            s = stimuli.TextLine(text=str(trel),text_size=100,text_colour=misc.constants.C_GREEN)
            t.add_stimulus(s)
            b.add_trial(t)
#! /usr/bin/env python
# Time-stamp: <2021-03-23 21:24:50 [email protected]>
"""A series of trials where a cross or a sound is presented and the participant must press a key as quickly as possible.
"""

import random
from expyriment import design, control, stimuli

NTRIALS = 20
ITI = 1000  # inter trial interval
MAX_RESPONSE_TIME = 2000
AUDIO_STIMULUS = 'click.wav'

exp = design.Experiment(name="AudioVisual Detection")
control.initialize(exp)

blankscreen = stimuli.BlankScreen()

visual_trial = design.Trial()
visual_trial.add_stimulus(stimuli.FixCross(size=(50, 50), line_width=4))

audio_trial = design.Trial()
audio_trial.add_stimulus(stimuli.Audio(AUDIO_STIMULUS))

visual_block = design.Block("visual")
for i in range(NTRIALS):
    visual_block.add_trial(visual_trial)
exp.add_block(visual_block)

audio_block = design.Block("audio")
for i in range(NTRIALS):
Beispiel #4
0
import os
from expyriment import design, control, stimuli, io, misc
import numpy as np

###### GET SUBJECT PARAMETERS ######
subjectNumber 	= int(raw_input("Please enter the subject number: "))
runNumber 	 	= int(raw_input("Please enter the run number: "))

###### EXPYRIMENT INITIALIZATION ######
exp = design.Experiment("FOSS Localizer")
exp.data.__init__("Run%02d" % runNumber, time_stamp=False)
control.initialize(exp)
fixCross = stimuli.FixCross()
theKeyboard = exp.keyboard
myKeyboard = io.Keyboard
exp.events.__init__("Run%02d" % runNumber, time_stamp=False)

###### CONTROL PANEL ######
# Define most experimental parameters here.

# Visual Angle
viewingDistance = 1020 #mm
monitorSize = 330 #mm
desiredVA = 6
currentImageSize = 700 #make this dynamic!
newImageSize = np.tan(np.radians(desiredVA/2)) * 2 * viewingDistance * (exp.screen.size[0]*2/monitorSize)
# IMPORTANT: multiply exp.screen.size[0] by 2 if running on a retina display.
scaleFactor = float(newImageSize/currentImageSize)

imagesPerBlock = 20
imagePresentationTime = 600 #ms
import expyriment
from expyriment import design, stimuli, control, io, misc
from expyriment.misc import constants
import pandas as pd
import os.path

### OPEN DATA FILE ###
Stim_Shape = pd.read_csv("Task_Stimuli_Shapes.csv")
Stim_Color = pd.read_csv("Task_Stimuli_Colors.csv")

### CREATE NEW DATA FILE FOR DEMOGRAPHIC INFORMATION IN DATA FOLDER ###
DEMO = 'Data/demographics.csv'

### EXPERIMENTAL DESIGN ####
exp = design.Experiment("Task")  #create and name new exp object
control.initialize(
    exp
)  #starts countdown, sets up experimental clock, creates the screen (exp.screen), creates and event file (exp.events) and presents the preparing expyriment screen_size
screen_size = exp.screen.surface.get_size()

### INSTRUCTIONS ###
General_Instructions = "This study has two parts. You will have to answer questions using the keyboard for both parts!"
Continue_Instructions = 'Press any key to continue...'
Demographic_Task_Instructions = "In PART 1, you will be asked to answer some general questions about yourself."
Image_Task_Instructions = "In PART 2, you will be asked to judge shapes and colors. Press any key to continue."
Instructions_Shape_Task = "You will be shown several shapes and you will be asked to evaluate each shape. Press any key to start."
Instructions_Color_Task = "You will be shown several colors and you will be asked to evaluate each color. Press any key to start."
Image_Task_Answer = "Please select between 1 and 5, with 1 = definitely yes, 2 = mostly yes, 3  = neither yes nor no,  4 = mostly no, 5 = definitely no."

Question_1 = "Press f if you are a female, m for male, o for other."
Question_2 = "How old are you?"
# Time-stamp: <2021-11-16 15:36:47 [email protected]>
""" This is a simple reaction-time experiment.

At each trial, a cross is presented at the center of the screen and
the participant must press a key as quickly as possible.
"""

import random
from expyriment import design, control, stimuli

N_TRIALS = 50
MIN_WAIT_TIME = 1000
MAX_WAIT_TIME = 2000
MAX_RESPONSE_DELAY = 2000

exp = design.Experiment(name="Visual Detection", text_size=40)
control.set_develop_mode(on=True)
control.initialize(exp)

target = stimuli.FixCross(size=(50, 50), line_width=4)
blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen(
    "Instructions",
    f"""From time to time, a cross will appear at the center of screen.

    Your task is to press a key as quickly as possible when you see it (We measure your reaction-time).

    There will be {N_TRIALS} trials in total.

    Press the space bar to start.""")
Beispiel #7
0
    instructions.present()
    exp.keyboard.wait(misc.constants.K_SPACE)

    for i in range(nb_block_r):
        block_name = "real" + str(i + 1)
        blocks(nb_el_block_r, nb_nogo_r, nb_probes_r, exp, block_name)
        instructions = stimuli.TextLine(
            text="Ready for the next trial? Press spacebar")
        instructions.present()
        exp.keyboard.wait(misc.constants.K_SPACE)

    control.end(goodbye_text="Thank you very much...", goodbye_delay=2000)


## initialize xp
exp = design.Experiment(name="SART")
control.set_develop_mode(
    on=False)  ## Set develop mode. Comment for real experiment
control.initialize(exp)
control.start()
exp.data_variable_names = ["digit", "btn", "rt", "error", "block_name"]

#creation probe files
data_probe_name = ['probe_data', str(exp.subject)]
data_file_name = ['probe_data', str(exp.subject), '.txt']
globals()[''.join(data_probe_name)] = open(''.join(data_file_name), "w")
globals()[''.join(data_probe_name)].write(
    'block_number, trial_number, relatedness\
, rt_rel, control, rt_con\n')
globals()[''.join(data_probe_name)].close
Beispiel #8
0
#!/usr/bin/env python
"""
Minimal skeleton for an expyriment script

See <https://docs.expyriment.org/Tutorial.html>

"""

from expyriment import design, control, stimuli

exp = design.Experiment(name="Experiment")
control.set_develop_mode(
    on=True)  ## Set develop mode. Comment out for actual experiment

control.initialize(exp)

### insert here some code to generate the stimuli

control.start()

### insert here some code to present the stimuli and record responses

control.end()
Beispiel #9
0
    control.defaults.window_mode = windowMode
    control.defaults.window_size = misc.get_monitor_resolution()
    windowSize = control.defaults.window_size
else:
    control.defaults.window_mode = windowMode
    control.defaults.window_size = windowSize

m = LdMatrix(matrixSize, windowSize)  # Create Matrix

arguments = str(''.join(sys.argv[1:])).split(
    ',')  # Get arguments - experiment name and subject

experimentName = arguments[0]
subjectName = arguments[1]

exp = design.Experiment(experimentName)  # Save experiment name
exp.add_experiment_info(['Subject: '])  # Save Subject Code
exp.add_experiment_info([subjectName])  # Save Subject Code

# Save time, Response, correctAnswer, RT
exp.add_data_variable_names(['Time', 'Matrix', 'CorrectAnswer', 'RT'])

exp.add_experiment_info(['Learning: '])  # Save Subject Code
learningMatrix = getPreviousMatrix(subjectName, 0, 'DayOne-Learning')
exp.add_experiment_info([learningMatrix])  # Add listPictures

interferenceMatrix = getPreviousMatrix(subjectName, 0, 'DayTwo-Interference')

exp.add_experiment_info(['RandomMatrix: '])  # Save Subject Code
randomMatrix = m.findMatrix(learningMatrix)
if np.any(randomMatrix == interferenceMatrix):
Beispiel #10
0
"""A series of trials where a Circle is presented and the participant must press a key as quickly as possible.
"""
import random
from expyriment import design, control, misc, stimuli

########## *******************  PART 1.Experiment settings ******************* ####################

NTRIALS = 5
ITI = 1000  # inter trial interval

exp = design.Experiment(name="Side Detection")
control.initialize(exp)

blankscreen = stimuli.BlankScreen()
instructions = stimuli.TextScreen(
    "Instructions",
    f"""From time to time, a Circle will appear at the center of screen.

    Your task is to press the space bar key as quickly as possible when you see it (We measure your reaction-time).

    There will be {3*NTRIALS} trials in total.

    Press the space bar to start.""")

###### 1.A --> Definition of the only two possible trials made up of two stimuli "Blue/Red"

#Stimulus red
visual_trial_red = design.Trial()
visual_trial_red.add_stimulus(stimuli.Circle(radius=100, colour=(255, 0, 0)))

#Stimulus blue
Beispiel #11
0
import numpy as np
from csv import reader

###### GET SUBJECT PARAMETERS ######
subjectNumber = int(raw_input("Please enter the subject number: "))
runNumber = int(raw_input("Please enter the run number: "))
threshold = int(raw_input("Threshold (1), No Thresh (2): "))
CBL = int(raw_input("Please enter the counterbalance number: "))

if threshold == 1:
    isThreshed = "Thresh"
else:
    isThreshed = "NoThresh"

###### EXPYRIMENT INITIALIZATION ######
exp = design.Experiment(name="Inversion",
                        filename_suffix="Run%02d" % runNumber)
control.initialize(exp)
fixCross = stimuli.FixCross()
theKeyboard = exp.keyboard
myKeyboard = io.Keyboard

###### CONTROL PANEL ######
# Define most experimental parameters here.

# Visual Angle
viewingDistance = 1020  #mm
monitorSize = 330  #mm
desiredVA = 6
currentImageSize = 700  #make this dynamic!
newImageSize = np.tan(np.radians(desiredVA / 2)) * 2 * viewingDistance * (
    exp.screen.size[0] * 2 / monitorSize)
from expyriment import design, control, stimuli, io, misc


# Create and initialize an Experiment
exp = design.Experiment("Simon Cat Task")
control.initialize(exp)

# Define and preload standard stimuli
fixcross = stimuli.FixCross()
fixcross.preload()

# Create IO
#response_device = io.EventButtonBox(io.SerialPort("/dev/ttyS1"))
response_device = exp.keyboard

# Create design
for task in ["left key for green", "left key for red"]:
    b = design.Block()
    b.set_factor("Response", task)
    for where in [["left", -300], ["right", 300]]:
        for what in [["red", misc.constants.C_RED],
                     ["green", misc.constants.C_GREEN]]:
            t = design.Trial()
            t.set_factor("Position", where[0])
            t.set_factor("Colour", what[0])
            s = stimuli.Rectangle([50, 50], position=[where[1], 0],
                                  colour=what[1])
            t.add_stimulus(s)
            b.add_trial(t, copies=20)
    b.shuffle_trials()
Beispiel #13
0
"""
PCBS Project - Acceptability judgment task in polish
Anna Szmarowska
"""

#Importation of packages
from expyriment import design, control, stimuli, io, misc
from pandas import read_csv
import os.path

#Creation and initialization
exp = design.Experiment(name="Acceptability judgment task")
control.initialize(exp)


#Creation of stimuli
def create_picture_stimuli(number, position):
    return stimuli.Picture(os.path.join("pictures",
                                        str(number) + ".png"), position)


img0 = create_picture_stimuli(0, (-250, -100))
img1 = create_picture_stimuli(1, (-175, -100))
img2 = create_picture_stimuli(2, (-100, -100))
img3 = create_picture_stimuli(3, (-25, -100))
img4 = create_picture_stimuli(4, (50, -100))
img5 = create_picture_stimuli(5, (125, -100))
img6 = create_picture_stimuli(6, (200, -100))
img7 = create_picture_stimuli(7, (275, -100))
data_stimuli = read_csv("sentences.csv")
Beispiel #14
0
from ld_matrix import LdMatrix
from config import *

control.defaults.window_mode = windowMode
control.defaults.window_size = windowSize


arguments = str(''.join(sys.argv[1:])).split(',')  # Get arguments - experiment name and subject

dataFile = arguments[0]

agg = misc.data_preprocessing.read_datafile(dataFile, only_header_and_variable_names=True)
header = agg[3].split('\n#e ')
previousMatrix = ast.literal_eval(header[-1].split('\n')[0].split('\n')[0])

exp = design.Experiment(dataFile)  # Save experiment name

m = LdMatrix(matrixSize, windowSize)  # Create Matrix

control.initialize(exp)
control.start(exp, auto_create_subject_id=True, skip_ready_screen=True)

m.associatePictures(previousMatrix)  # Associate Pictures to cards
bs = stimuli.BlankScreen(bgColor)  # Create blank screen
bs = m.plotDefault(bs,False)

''' Presentation all locations '''
presentationOrder = np.array(range(m.size[0]*m.size[1]))
removeCards.sort(reverse=True)
for nCard in removeCards:
    presentationOrder = np.delete(presentationOrder, nCard)
def startTrial(NUMBER,OPERATOR):

    w, h = 10, 3;
    Matrix = [[0 for x in range(w)] for y in range(h)]       # Define 2D array

    #fixcross.preload()
    exp = design.Experiment("MATH")
    control.initialize(exp)
    control.start()
    fixcross = stimuli.FixCross(size=(40,40),colour=misc.constants.C_WHITE,position=(0,200))
    txt_input=io.TextInput("= ")

    inputNAME=io.TextInput("ENTER NAME: ")
    VolunteerNAME = inputNAME.get() # First input by volunteer
    Matrix[2][1]=VolunteerNAME

    stimuli.TextScreen("MATH GAME -LEVEL 1",". . . RELAX . . .\n\n\n\n\n\n+\n\nlook at fixcross\n\n\nSTARTS IN 10 SECONDS",heading_size=40,text_size=20,heading_colour=misc.constants.C_WHITE,text_colour=misc.constants.C_WHITE).present()
    exp.clock.wait(10000) #stim -1                                               REMOVE # ON COMMISSION
    fixcross.preload()
    fixcross.present()
    exp.clock.wait(10000)                                                        # REMOVE # ON COMMISSION
    b = design.Block()

    for i in range (0,10):                                                       # cOMMISSION : 3->10 #FOR 10 TRIALS
        b.clear_trials()
        b = design.Block()
        print(i)
        tr=atl.arithmetictriall1(NUMBER,OPERATOR)
        print(tr)

        for trel in tr[0]:
            t=design.Trial()
            s = stimuli.TextLine(text=str(trel),text_size=200,text_colour=misc.constants.C_GREEN)
            t.add_stimulus(s)
            b.add_trial(t)
        #print(b.trials)
        exp.add_block(b)

        #START TEST: ONSCREEN
        #tx0=time.time()
        fixcross.present()
        exp.clock.wait(1000)
        #tx1=time.time()-tx0
        #print("ttt %d"%tx1)
        #xcount = 1                #debug fixcross timings (previously increasing time b=1)
        for b in exp.blocks:

            for t in b.trials:
                t.stimuli[0].present()
                exp.clock.wait(800) #>1000
            #xcount=0

        print(b)
        #exp.clock.reset_stopwatch()
        t0=time.time()
        answer = txt_input.get()
        responsetime=time.time()-t0     #response time

        try:
            answer=int(answer)
            if answer==tr[1]:
                print("Correct")
                Matrix[0][i]=5
                Matrix[1][i]=responsetime
            else:
                print("incorrect")
                Matrix[0][i]=-5
                Matrix[1][i]=responsetime
        except:
            print("incorrect")
            Matrix[0][i]=-5
            Matrix[1][i]=responsetime

    fixcross.present()
    exp.clock.wait(5000)
    control.end()
    #print(Matrix)
    return Matrix
from expyriment import control, design, misc, io, stimuli
from expyriment.design.extras import StimulationProtocol


# SETTINGS
REPETITIONS = 25  # times 4 is total
TR = 2.0
SCAN_TRIGGER = misc.constants.K_5
SCAN_TRIGGER_LTP_ADDRESS = None  # None = USB (keyboard emulation)
BB_SERIAL_PORT_ADDRESS = None  # None = USB (keyboard emulation)
RESPONSE_LEFT = 49
RESPONSE_RIGHT = 50


# DESIGN
exp = design.Experiment("Stroop Task (Colour)")
exp.add_data_variable_names(["TrialID, Condition, Text, Colour, Key, RT, Correct"])
control.initialize(exp)

out_protocol = StimulationProtocol("time")
out_protocol.add_condition("congruent")
out_protocol.add_condition("incongruent")
out_protocol.add_condition("error")

fixcross = stimuli.FixCross()
fixcross.preload()

main = design.Block()
for r in range(REPETITIONS):
    for name in ("RED",
                 "GREEN"):
Beispiel #17
0
# Prepare stimuli
phrases = prepare_phrases()
instruction = prepare_instruction()

# Set mode for convenient development
# control.set_develop_mode(True)

# Define variables
response_keys = [misc.constants.K_UP, misc.constants.K_DOWN
                 ]  # left and right arrow keys for responses
random_colour = [misc.constants.C_BLUE, misc.constants.C_GREEN
                 ]  # green or blue colour for last stimuli

# Create and initialize an Experiment
exp = design.Experiment("The Influence Of Emotions")
control.initialize(exp)

# Define and preload standard stimuli
fixcross = stimuli.FixCross()
fixcross.preload()

# Initialise block
block = design.Block(name="Block 1")

# Create design
for i in range(len(phrases)):

    # Initialise trail
    trial = design.Trial()
        update_stimulus(dot_list, arena)
        key, time = check_keyboard_response_and_time()
        exp.clock.wait(1)

    return (key, time)


def randomize_trials():
    np.random.shuffle(MOTION_COHERENCE)


def choose_random_direction():
    return (np.random.choice(['left', 'right'], 1)[0])


exp = design.Experiment(name="Random Dot Motion Task")
control.initialize(exp)

INSTRUCTIONS = stimuli.TextScreen(
    "Instructions",
    f"""You are going to see small white dots moving in a grey circle on the screen.

    Your task is to decide, as quickly as possible, if the dots are moving to the left or to the right.

    If you think that they are moving to the left, press the left arrow key. If you think that they are moving to  the right, press the right arrow key.

    There will be {N_TRIALS} trials in total.

    Press the space bar to start.""")

randomize_trials()
Beispiel #19
0
    c_tr = Circle(radius, color_tr, position = (right, top), anti_aliasing = 10)
    c_bl = Circle(radius, color_bl, position = (left, bottom), anti_aliasing = 10)
    c_br = Circle(radius, color_br, position = (right, bottom), anti_aliasing = 10)
    rect = Rectangle((width, height), square_color,  position = (0, 0), corner_anti_aliasing = True)

    c_tl.plot(surface)
    c_tr.plot(surface)
    c_bl.plot(surface)
    c_br.plot(surface)
    rect.plot(surface)

    return surface


if __name__ == '__main__':
    exp = design.Experiment(name="Kanisza square")
    control.set_develop_mode(on=True)  # Comment out for full screen experiment
    control.initialize(exp)
    control.start(skip_ready_screen=True)

    RADIUS = 50
    WIDTH, HEIGHT = 200, 200
    surface = Kanisza_square(WIDTH, HEIGHT, RADIUS, backgroung_color=GRAY, square_color=GRAY,
                             color_tl=BLACK, color_tr=BLACK, color_bl=BLACK,  color_br=BLACK)

    surface.present()
    exp.screen.save('kanisza-squares2.png')
    exp.keyboard.wait()

    control.end()