Exemplo n.º 1
0
background.draw()
MTMinfo.draw()
win.flip()
event.waitKeys()
background.draw()
instructinfo.draw()
win.flip()
event.waitKeys()

# Prompt the user to input the mouse and the session that they wish to record.
background.draw()
win.flip()
slot = None
session = None
while slot is None or session is None:
    mouse = gui.Dlg(title="Information of the Subject Mouse")
    mouse.addText('Location Info')
    mouse.addField("Stack:", choices=["1", "2"])
    mouse.addField("Level:", choices=["a", "b", "c", "d"])
    mouse.addField("slot:", choices=["1", "2", "3", "4", "5", "6"])
    mouse.addText('Session Info')
    mouse.addField("Session:", choices=["Habituation", "Test"])
    mouse.show()
    if mouse.OK:  # or if ok_data is not None
        slot = "s" + mouse.data[0] + mouse.data[1] + mouse.data[2]
        session = mouse.data[3]

# Create the video stimuli based on the info
if df.loc[df.slot == slot, "group"][0][:3] == "CPP":
    left_video = slot + "-" + session + "-Plain.avi"
    right_video = slot + "-" + session + "-Circles.avi"
Exemplo n.º 2
0
### IMPORTANT:
### Under psychopy preferences/general
### (1) change the audio driver to "portaudio" (otherwise the program won't stop running when it's done)
### (2) change the audio library to "pygame" (otherwise the audio won't stop playing when the video stops)

# import psychopy modules
import psychopy
from psychopy import visual, core, event, sound, gui, data, logging
from psychopy.sound import Sound
import math
import numpy as np
import random
import pandas as pd

myDlg = gui.Dlg(title="AV Int")
myDlg.addField('ID Number:')
myDlg.addField('Order:')
myDlg.addField('Computer Type:', choices=["PC", "Mac"])
myDlg.addField('Experiment Type:', choices=["Full", "Clipped"])
myDlg.show()  #show dialog and wait for OK or Cancel
if gui.OK:  #then the user pressed OK
    info = myDlg.data
else:
    print 'user cancelled'

subject = info[0]
order = int(info[1])
computer = info[2]
exp_type = info[3]
Exemplo n.º 3
0
                print 'QUITTING!'
                return True  #say switched task->will start free mode, one more escape to quit


if __name__ == '__main__':
    #CD.start_camera()
    print os.getpid()
    StimToolLib.open_and_close_vmeter(
    )  #this hack seems to fix a problem with the vMeter not responding the first time it's used after logging in...

    modules = mod_mapping.keys()
    modules.append('SKIP')
    modules.append('SKIP TO')
    modules.sort()  #sorted alphabetically so tasks are easier to find

    myDlg = gui.Dlg(title="StimTool")
    myDlg.addField('Subject ID:',
                   StimToolLib.get_var_from_file('Default.params',
                                                 'last_subject'))  #subject ID
    myDlg.addField(
        'Administrator ID:',
        StimToolLib.get_var_from_file(
            'Default.params',
            'last_admin'))  #name of the person administering the session
    task_lists = [
        f for f in os.listdir('.') if f.endswith('.TL')
    ]  #get a list of all ".TL" files (tasklists), which have a list of all tasks to be run in a session
    task_lists.sort()
    task_lists.insert(0, 'free')
    myDlg.addField(
        'Experiment Order:', choices=task_lists
Exemplo n.º 4
0
#import packages
from psychopy import visual, event, core, gui
import pygame, time, sys, csv, math, random as r, matplotlib.pyplot as graph, numpy as np, os
from random import randint
from matplotlib.collections import LineCollection

import pygame, pygame.font, pygame.event, pygame.draw, string
from pygame.locals import *

Startup = gui.Dlg(title="EXPERIMENTER")
Startup.addField('Items:', 'default')
Startup.addField('Time:', 'default')
Startup.addField('RecogTime:', 'default')
Startup.addField('Version:', "2")
Startup.show()  # show dialog and wait for OK or Cancel
if Startup.OK:  # then the user pressed OK
    Starters = Startup.data
    input1, input2, input3, input4 = Starters
else:
    print('user cancelled')

Startup = gui.Dlg(title="Part 1")
Startup.addField('SONA ID:')
Startup.addField('Age:')
Startup.addField('Gender:', 'F')
Startup.show()  # show dialog and wait for OK or Cancel
if Startup.OK:  # then the user pressed OK
    Demographics = Startup.data
    subject, age, gender = Demographics
else:
    print('user cancelled')
Exemplo n.º 5
0
from psychopy import gui
import raw_plotter
import spectral_plotter
import multi_plotter

#class InputBox(object):

myDlg = gui.Dlg(title="OpenBCI Menu")
myDlg.addText('Subject info')
myDlg.addField('Participant')  #0
myDlg.addField('Session', 001)  #1
myDlg.addField('Port', '/dev/tty/ACM0')  #2
myDlg.addText('Visual Options')
myDlg.addField('Plots:',
               choices=["None", "Spectral_Plot", "FFT", "Spectogram"])  #3
myDlg.addText('Experiment Choices')
myDlg.addField('Experiments',
               choices=["None", "SSVEP", "ERP", "Motor_Imagery"])  #4
myDlg.show()  # show dialog and wait for OK or Cancel
if myDlg.OK:  # then the user pressed OK
    thisInfo = myDlg.data
    options = {
        'participant': thisInfo[0],
        'session': thisInfo[1],
        'port': thisInfo[2],
        'plot': thisInfo[3],
        'experiment': thisInfo[4]
    }
    fname = '%s_%s.csv' % (options['participant'], options['session'])
    port = options['port']
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from psychopy import  gui, visual, core, data, event, logging, parallel
from time import strftime
from random import choice
from numpy.random import choice as choice2
import numpy.random as rd
import numpy as np
import random
import pandas as pd

##### SETUP #####

#Experimenter input
dlg = gui.Dlg(title = 'Experiment Parameters')
dlg.addField('Subject ID:')
dlg.addField('Run:')
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'])
dlg.addField('Session:')

exp_input = dlg.show()

#port = parallel.ParallelPort(0x1FF8)
### Parameters ###

###### EDIT PARAMETERS BELOW #######
        refreshMsg1 += ' program assumes ' + str(refreshRate)
        refreshMsg2 = 'which is off by more than' + str(
            round(refreshRateTolerancePct, 0)) + '%!!'
    else:
        refreshMsg1 += ', which is close enough to desired val of ' + str(
            round(refreshRate, 1))
    myWinRes = myWin.size
    myWin.allowGUI = True
    print(myWinRes)
myWin.close()  # have to close window to show dialog box

defaultNoiseLevel = 0.0  # to use if no staircase, can be set by user
trialsPerCondition = 6  # default value
dlgLabelsOrdered = list()

myDlg = gui.Dlg(title="RSVP experiment", pos=(200, 400))
if not autopilot:
    myDlg.addField('Subject name (default="Adi"):',
                   'Adi',
                   tip='or subject code')
    dlgLabelsOrdered.append('subject')

myDlg.addField('\tPercent noise dots=',
               defaultNoiseLevel,
               tip=str(defaultNoiseLevel))
dlgLabelsOrdered.append('defaultNoiseLevel')
myDlg.addField('Trials per condition (default=' + str(trialsPerCondition) +
               '):',
               trialsPerCondition,
               tip=str(trialsPerCondition))
dlgLabelsOrdered.append('trialsPerCondition')
Exemplo n.º 8
0
def run_S1_prosody(sound_path,
                   data_path,
                   laptop=1,
                   pretest=0,
                   pretest_order=1):

    print "Running S1  prosody experiment"
    print ""
    if laptop:
        print "Running on a laptop:",

    # Debugging switch:
    waiting_time = 1
    #waiting_time = 0.01
    waiting_time_2 = 2

    # Create a window
    # Laptop screen
    # fullscreen mode: When fullscreen mode is chosen, psychopy will alert
    # if the monitor size is not given as the window pixel size (first argument).
    # The problem with the fullscreen mode is that it it hiding dialog boxes.
    # If we close the window and show the dialog box, there will be no background
    # drawn and the desktop of the computer will be shown. Since this is even worse
    # we will skip fullscreen.
    if laptop:
        win = visual.Window([1440, 900],
                            color=(1, 1, 1),
                            monitor="testMonitor",
                            units="pix")  #, fullscr = True)
    # Large screen:
    else:
        win = visual.Window([1800, 1000],
                            color=(1, 1, 1),
                            monitor="testMonitor",
                            units="pix")

    ####################################
    # Welcome and retrieve user info   #
    ####################################

    text_stim = visual.TextStim(win, height=50, wrapWidth=5000)
    text_stim.pos = (0, 0)
    text_stim.color = "black"
    text_stim.bold = True

    # Input user info:
    # The pos argument must be given
    # input_box = gui.Dlg(title="", labelButtonOK="OK", labelButtonCancel="Avbryt", pos=QPoint(800,500))
    input_box = gui.Dlg(title="",
                        labelButtonOK="OK",
                        labelButtonCancel="Avbryt",
                        pos=(800, 500))
    input_box.addField(u'Ange subject ID')
    input_data = input_box.show()

    if not input_box.OK:
        print "User name not entered, quitting test"
        return
    else:
        participant_ID = input_data[0].replace(" ", "_")
        print 'p ID'
        print type(participant_ID)
        print repr(participant_ID)
        print unicode(participant_ID).encode('utf8')

    ####################################
    # Instructions and test trial      #
    ####################################

    # Instructions
    text_stim_instr = visual.TextStim(win,
                                      height=25,
                                      wrapWidth=1000,
                                      font="Times")
    text_stim_instr.pos = (0, 0)
    text_stim_instr.color = "black"

    #    text_stim_instr.setText(u'Du kommer nu att få lyssna på tolv par av personer som pratar med varandra. Det kommer alltid vara en person som börjar prata (vi kallar hen talaren) och en person som svarar (vi kallar hen lyssnaren). \n \n Sättet som lyssnaren svarar på ger information om det är så att lyssnaren förstått vad talaren säger eller inte förstått och därför skulle behöva ett förtydligande. \n \n Alla svar som lyssnarna ger är sådana att de går att säga både på ett sådant sätt som antyder att lyssnaren förstått, och på ett sätt som visar att lyssnaren inte förstått.')
    #
    #    text_stim_instr.draw()
    #    win.flip()
    #    core.wait(waiting_time*25)
    #
    #
    #    text_stim_instr.setText(u'Hälften av försöken kommer att vara sådana att lyssnaren behöver ett förtydligande, och hälften sådana där lyssnaren inte behöver ett förtydligande. Ordningen är helt blandad. \n \n Din uppgift är att avgöra vilka lyssnare som behöver ett förtydligande. \n \n Tänk inte på längden på pausen innan svaret kommer, för den är bara ett resultat av hur inspelningen gick till.')
    #
    #    text_stim_instr.draw()
    #    win.flip()
    #    core.wait(waiting_time*15)
    #
    #    text_stim_instr.setText(u'Ett förtydligande kan behövas om lyssnaren inte riktigt förstår hur talaren menar. \n \n Om lyssnaren inte behöver ett förtydligande kan det betyda att lyssnaren väntar sig att talaren ska fortsätta prata som hen hade tänkt, utan att stanna upp och förtydliga. Det kan också betyda att samtalsämnet eller hela konversationen eller är färdigt. ')
    #
    #    text_stim_instr.draw()
    #    win.flip()
    #    core.wait(waiting_time*25)
    #
    #    text_stim_instr.setText(u'Försök att undvika att tänka eller analysera, utan använd istället gärna din magkänsla för att avgöra!')
    #
    #    text_stim_instr.draw()
    #    win.flip()
    #    core.wait(waiting_time*5)
    #
    text_stim_instr.setText(
        u'Här kommer ett exempel (som inte ingår i det riktiga testet)!')

    text_stim_instr.draw()
    win.flip()
    core.wait(waiting_time * 3)

    input_box = gui.Dlg(title="",
                        labelButtonOK=u"Fortsätt",
                        labelButtonCancel="Avbryt",
                        pos=(900, 800))

    user_input = -1
    input_box.show()
    if not input_box.OK:
        return

#================================

    S1_prosody_trial.S1_prosody_instruction_trial(win, sound_path)

    #================================

    win.flip()

    input_box = gui.Dlg(title="",
                        labelButtonOK="Starta testet",
                        labelButtonCancel="Avbryt",
                        pos=(900, 800))
    input_box.addText(
        u'Tryck "Starta testet" för att starta det riktiga testet')
    #input_box.addField('Soker talaren respons fran lyssnaren?', choices=["Ja", "Nej"])
    user_input = -1
    input_box.show()
    if not input_box.OK:
        return

    text_stim_instr.setText(u'Nu börjar det riktiga testet!')
    text_stim_instr.draw()

    win.flip()
    core.wait(waiting_time * 5)

    ##########################
    # Prepare the trials  #
    #########################

    n_trials = 12
    #n_trials = 2
    trials = range(0, n_trials)

    # Retrieve trial texts from python file
    texts = S1_prosody_trial_texts.texts

    # Randomize which trials will have test and which control.
    # 1 is test and 0 is control
    test_or_control = y = [1] * 6 + [0] * 6
    rand.shuffle(test_or_control)

    # If pretest, two different orders should be used.
    if pretest:
        test_or_control = [1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0]
        if pretest_order == 2:
            # Invert order:
            test_or_control = [(i - 1) * -1 for i in test_or_control]

    ###################################################
    # Prepare for storing test input from participant #
    ###################################################

    # Input_data_file:
    input_data_test_file_name = "S1_prosody_test_" + participant_ID + ".json"
    input_data_test_file = data_path + input_data_test_file_name
    input_data_pretest_ratings_file_name = "S1_prosody_pretest_ratings_" + participant_ID + ".json"
    input_data_pretest_ratings_file = data_path + input_data_pretest_ratings_file_name
    input_data_pretest_freetext_file_name = "S1_prosody_pretest_freetext_" + participant_ID + ".json"
    input_data_pretest_freetext_file = data_path + input_data_pretest_freetext_file_name

    # Formats:
    # user_input_test = [{'trial_type': 1, 'user_input': 0} ,{'trial_type': 0, 'user_input': 0}, ...]}
    # user_input_pretest_ratings =  [{'certainty': 5, 0, 'difficulty': 0}, {'certainty': 3, 'difficulty': 0}...
    # user_input_pretest_freetext = [u'Bla bla bla', u'Blo blo blo', ...]}

    #The index of the trials list is the trial index (trial number - 1)

    # Trial info and user input.
    user_input_test = n_trials * [-1]
    user_input_pretest_ratings = n_trials * [-1]
    user_input_pretest_freetext = n_trials * [-1]

    # Counter
    yes_input_ctr = 0

    #############################################################################################################

    #############################
    # Test loop over trials
    #############################

    for trial_ind in trials:

        trial_nr = trial_ind + 1

        print "trial nr ", trial_nr

        trial_type = test_or_control[trial_ind]

        trial_nr_text = u'Försök ' + str(trial_nr)
        text_stim.setText(trial_nr_text)
        text_stim.bold = True

        text_stim.draw()

        win.flip()
        core.wait(waiting_time * 2)

        # Trial text to show
        text = texts[trial_ind]

        #================================

        user_input_test[trial_ind] = S1_prosody_trial.S1_prosody_test_trial(
            win,
            text,
            sound_path,
            trial_type,
            trial_nr,
            yes_input_ctr,
            request_user_input=1)

        #================================

        # Keep track of nr of "yes" replies:
        if user_input_test[trial_ind]['user_input'] == 1:
            yes_input_ctr = yes_input_ctr + 1

        if pretest:

            # 2 questions with rating options
            questions = [
                u'Hur tydlig upplever du att talaren var med att hen ville ha förtydligande eller inte?',
                u'Hur säker var du på att du svarade rätt?',
            ]

            user_input_certainty = ""
            user_input_difficulty = ""

            scales = ['difficulty', 'certainty']

            for (i, scale) in zip([0, 1], scales):

                text_stim_q = visual.TextStim(win, height=35, wrapWidth=1000)
                text_stim_q.color = "black"
                text_stim_q.pos = (0, 0)
                text_stim_q.setText(questions[i])

                text_stim_p = visual.TextStim(win, height=25, wrapWidth=1000)
                text_stim_p.pos = (0, -100)
                text_stim_p.color = "black"
                text_stim_p.setText(
                    "Skriv in en siffra 1 - 5 och tryck sedan ENTER")
                if scale == 'certainty':
                    ratingScale = visual.RatingScale(
                        win,
                        low=1,
                        high=5,
                        scale=None,
                        labels=[u"1 = Inte alls säker", u"5 = Helt säker"])
                else:
                    ratingScale = visual.RatingScale(
                        win,
                        low=1,
                        high=5,
                        scale=None,
                        labels=[u"1 = Inte alls tydlig", u"5 = Mycket tydlig"])

                while ratingScale.noResponse:
                    text_stim_q.draw()
                    text_stim_p.draw()
                    ratingScale.draw()
                    win.flip()

                rating = ratingScale.getRating()
                if scale == 'certainty':
                    user_input_certainty = rating
                else:
                    user_input_difficulty = rating

                #decisionTime = ratingScale.getRT()
                #choiceHistory = ratingScale.getHistory()

            ######################
            # Save user input    #
            ######################

                user_input_pretest_ratings[trial_ind] = {
                    'user_input_certainty': user_input_certainty,
                    'user_input_difficulty': user_input_difficulty
                }

    #################################################################################################################################################

    ##############################
    # Write user input to file   #
    ##############################

    f = open(input_data_test_file, 'wb+')
    json.dump(user_input_test, f)
    f.close()

    f = open(input_data_pretest_ratings_file, 'wb+')
    json.dump(user_input_pretest_ratings, f)
    f.close()

    #########################################
    # Communicate that the test is over    #
    #########################################

    text = u"Nu är testet klart!"
    text_stim_instr.setText(text)

    # Draw the text
    text_stim_instr.draw()
    win.flip()
    # Hold the image
    core.wait(waiting_time_2 * 2)

    #################################################################################################################################################

    #If pretest: another loop with the trials followed by a questionnaire where they can write freely.

    if pretest:

        # Pretest instructions
        text = u"Nu kommer alla försöken igen och efter varje försök kommer du att få fylla i vad du tyckte om dem."
        text_stim_instr.setText(text)

        text_stim_instr.draw()
        win.flip()
        core.wait(waiting_time_2 * 2)

        input_box = gui.Dlg(title="",
                            labelButtonOK=u"Fortsätt",
                            labelButtonCancel="Avbryt",
                            pos=(900, 800))
        #input_box.addText(u'Tryck "Starta testet" för att starta det riktiga testet')
        #input_box.addField('Soker talaren respons fran lyssnaren?', choices=["Ja", "Nej"])
        user_input = -1
        input_box.show()
        if not input_box.OK:
            return

        #############################
        # Pretest loop over trials
        #############################

        for trial_ind in trials:

            trial_nr = trial_ind + 1

            trial_type = test_or_control[trial_ind]

            # Trial texts
            text = texts[trial_ind]

            #================================

            S1_prosody_trial.S1_prosody_test_trial(win,
                                                   text,
                                                   sound_path,
                                                   trial_type,
                                                   trial_nr,
                                                   -1,
                                                   request_user_input=0)

            #================================

            win.flip()

            #input_box = gui.Dlg(title="", pos = QPoint(800,500))
            input_box = gui.Dlg(title="", pos=(800, 500))
            input_box.addField(
                u'Hur gick dina tankar kring dessa bilder?  (byt "å","ä" och "ö" mot "a" och "o")'
            )
            user_input = input_box.show()

            if input_box.OK:
                user_input = user_input[0]
            else:
                user_input = ""

            ######################
            # Save user input    #
            ######################

            # Save user input
            user_input_pretest_freetext[trial_ind] = user_input

        ##############################
        # Write user input to file   #
        ##############################

        f = open(input_data_pretest_freetext_file, 'wb+')
        json.dump(user_input_pretest_freetext, f)
        f.close()

    #################################################################################################################################################

    text = u"Tack för att du deltog!"
    text_stim_instr.setText(text)

    text_stim_instr.draw()
    win.flip()
    # Hold the image
    core.wait(waiting_time_2)
    win.close()

    # Cleanup
    core.quit()
Exemplo n.º 9
0
#parameters
useFullScreen = True
useDualScreen = 1
DEBUG = False

frame_rate = 1
instruct_dur = 3
initial_fixation_dur = 4
#final_fixation_dur = 2
decision_dur = 2.5
outcome_dur = 1

responseKeys = ('2', '3', 'z')

#get subjID
subjDlg = gui.Dlg(title="Shared Reward Task")
subjDlg.addField('Enter Subject ID: ')
subjDlg.addField('Enter Friend Name: ')  #1
subjDlg.addField(
    'Enter Partner Name: ')  #NOTE: PARTNER IS THE CONFEDERATE/STRANGER #2
subjDlg.show()

if gui.OK:
    subj_id = subjDlg.data[0]
    friend_id = subjDlg.data[1]
    stranger_id = subjDlg.data[2]
    run = range(0, 1)

else:
    sys.exit()
Exemplo n.º 10
0
from psychopy import visual, event, core, gui
from math import sin, cos
import numpy, time, math, random, pygame, datetime, os, os.path, codecs, glob
from random import shuffle
import textwrap
pygame.init()

request = gui.Dlg()
request.addField("Probandennummer:")
request.addField("Alter:")
request.addField("Geschlecht:")
request.show()
subj_id = request.data[0]
age = request.data[1]
Geschlecht = request.data[2]


def TextDisplay(file, x_pos, y_pos, width, size, screen):
    """reads in a text file and displays it on the screen"""
    string = filter(
        None, [str.replace("\n", '') for str in open(file, 'r').readlines()])
    wrappedstring = []
    for str in string:
        new = textwrap.wrap(str, width)
        for st in new:
            wrappedstring.append(st)
        wrappedstring.append('')

    shift = 0
    for str in wrappedstring:
        font = pygame.font.Font(None, size)
Exemplo n.º 11
0
        os.path.join(os.path.dirname(__file__), '../..', "tfMRI_output"))

_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
expName = 'FaceMatching'

# Collect run mode and participant ID
expInfo = {}
#check if current subject files already exists (by checking files created today)
date_stamp = data.getDateStr(format="%Y_%b_%d")
existingCurrentBANDA = glob.glob('C:/Users/banda/Documents/tfMRI_output/**/*' +
                                 date_stamp + '*')
selectedRuns = []

if not existingCurrentBANDA:
    dlg1 = gui.Dlg(title="Participant ID")
    dlg1.addField('Participant')
    dlg1.addField('Mode', choices=["Scanner", "Practice"])
    #dlg1.addField('Group', choices=["HC", "MDD"])
    #dlg1.addField('Session', choices=["ABCD","IPAT2","CMRR"])
    dlg1.addField('Run(Default)', choices=["AB"])
    dlg1.addField('Custom Select Runs?', initial=False)
    dlg1.show()
    if dlg1.OK:  # then the user pressed OK
        # add the new entries to expInfo
        expInfo['participant'] = dlg1.data[0]
        expInfo['runMode'] = dlg1.data[1]
        #Custom Runs
        if dlg1.data[3]:
            dlg1Runs = gui.Dlg(title="Select Runs")
            dlg1Runs.addField('A', initial=False)
Exemplo n.º 12
0
    def __init__(self, **kwargs):
        self.DATA_DIR = kwargs.get('data_dir', 'digitspan_data')
        self.MONITOR = kwargs.get('monitor', 'testMonitor')
        self.MONITOR_RESOLUTION = kwargs.get('monitor_resolution', (1024, 768))
        self.SOUND_GENDER = kwargs.get('sound_gender', 'female')
        self.SOUND_PATH = kwargs.get('sound_path', os.path.join(os.path.dirname(os.path.realpath(__file__)), 'sounds'))
        self.SOUND_INIT_SAMPLES = kwargs.get('sound_init_samples', 48000)
        self.N_PRACTICE_TRIALS = kwargs.get('practice_trials', 2)
        self.LEN_PRACTICE_TRIAL = kwargs.get('practice_trial_len', 3)
        self.DIGIT_DISPLAY_TIME = kwargs.get('digit_display_time', 0.500)
        # renamed from "IN_BETWEEN_DIGITS_TIME"
        self.DIGIT_DISPLAY_GAP = kwargs.get('digit_display_gap', 0.300)
        self.NUM_TRIAL_BLOCKS = kwargs.get('trial_blocks', 1)
        self.INTER_TRIAL_DELAY = kwargs.get('inter_trial_delay', 0.500)
        self.sequence_range = {
            'forward': {
                'min': kwargs.get('forward_min', 3),
                'max': kwargs.get('forward_max', 15)
            },
            'reverse': {
                'min': kwargs.get('reverse_min', 2),
                'max': kwargs.get('reverse_max', 15)
            }
        }
        self.MAX_TRIALS_WRONG = kwargs.get('max_wrong_trials', 2)
        self.FULLSCREEN = kwargs.get('fullscreen', True)

        if not os.path.isdir(self.DATA_DIR):
            try:
                os.mkdir(self.DATA_DIR)
            except Exception as e:
                print e.getMessage()
                print "Error: cannot create data directory: " + self.DATA_DIR
                sys.exit(1)

        while True:
            # tuple of form: (subject_id, test_number)
            subject_info = self.get_subject_info(sys.argv[1:])
            self.log_file = os.path.join(
                self.DATA_DIR, '_'.join(subject_info) + '.csv')

            if os.path.isfile(self.log_file):
                rename_dialog = gui.Dlg(title='Error: Log File Exists')
                rename_dialog.addText("A log file with the subject ID " + subject_info[0] +
                                      " and test number " + subject_info[1] + " already exists. Overwrite?")
                rename_dialog.show()

                if rename_dialog.OK:
                    self.log_file = open(self.log_file, "w")
                    break
                else:
                    # not exactly necessary but w/e
                    continue
            else:
                self.log_file = open(self.log_file, "w")
                break

        # now log_file is a proper file
        self.data = []

        # this should load Pyo. However, it may require manually symlinking in
        # the newest liblo.
        sound.init(self.SOUND_INIT_SAMPLES, buffer=128)

        self.sound_correct = sound.Sound(value=440, secs=0.4)
        self.sound_incorrect = sound.Sound(value=330, secs=0.4)
        self.sound_files = [sound.Sound(value=os.path.join(self.SOUND_PATH, fn)) for fn in os.listdir(self.SOUND_PATH)
                            if fn.startswith(self.SOUND_GENDER) and fn.endswith('.wav')]

        # this is a bad way of doing this. Should load from a file.
        self.sequences = {
            'forward':  [(9, 7),
                         (6, 3),
                         (5, 8, 2),
                         (6, 9, 4),
                         (7, 2, 8, 6),
                         (6, 4, 3, 9),
                         (4, 2, 7, 3, 1),
                         (7, 5, 8, 3, 6),
                         (3, 9, 2, 4, 8, 7),
                         (6, 1, 9, 4, 7, 3),
                         (4, 1, 7, 9, 3, 8, 6),
                         (6, 9, 1, 7, 4, 2, 8),
                         (3, 8, 2, 9, 6, 1, 7, 4),
                         (5, 8, 1, 3, 2, 6, 4, 7),
                         (2, 7, 5, 8, 6, 3, 1, 9, 4),
                         (7, 1, 3, 9, 4, 2, 5, 6, 8)],
            'reverse':  [(3, 1),
                         (2, 4),
                         (4, 6),
                         (5, 7),
                         (6, 2, 9),
                         (4, 7, 5),
                         (8, 2, 7, 9),
                         (4, 9, 6, 8),
                         (6, 5, 8, 4, 3),
                         (1, 5, 4, 8, 6),
                         (5, 3, 7, 4, 1, 8),
                         (7, 2, 4, 8, 5, 6),
                         (8, 1, 4, 9, 3, 6, 2),
                         (4, 7, 3, 9, 6, 2, 8),
                         (9, 4, 3, 7, 6, 2, 1, 8),
                         (7, 2, 8, 1, 5, 6, 4, 3)]
        }

        # after this line executes, the window is showing.
        self.window = visual.Window(
            self.MONITOR_RESOLUTION, monitor=self.MONITOR, units='deg', fullscr=self.FULLSCREEN)
        self.mouse = event.Mouse(win=self.window)
# Set up GUI for inputing participant/run information (with defaults)
if len(sys.argv) > 1:
    DBIC_ID = sys.argv[1]
    accession = sys.argv[2]
    participant = sys.argv[3]
    run = sys.argv[4]
else:
    #DBIC_ID = "e.g., SID000001"
    #accession = "e.g., A000001"
    #participant = "e.g., 1"
    DBIC_ID = "SID000001"
    accession = "A000000"
    participant = "00"
    run = "00"

run_configuration = gui.Dlg(title='Run configuration')
run_configuration.addField("DBIC ID:", DBIC_ID)
run_configuration.addField("Scan accession number:", accession)
run_configuration.addField("Participant:", participant)
run_configuration.addField("Run number:", run)
run_configuration.show()

if run_configuration.OK:
    DBIC_ID = run_configuration.data[0]
    accession = run_configuration.data[1]
    participant = str(run_configuration.data[2])
    run = int(run_configuration.data[3])
elif not run_configuration.OK:
    core.quit()

# Start PsychoPy's clock (mostly for logging)
Exemplo n.º 14
0
## from psychopy.gui import qtgui as gui

# create a DlgFromDict
info = {'Observer':'jwp', 'gender':['male', 'female'],
    'GratingOri':45, 'ExpVersion': 1.1, 'Debug Mode': True}
infoDlg = gui.DlgFromDict(dictionary=info, title='TestExperiment',
    order=['ExpVersion', 'Observer'],
    tip={'Observer': 'trained visual observer, initials'},
    fixed=['ExpVersion'])  # this attribute can't be changed by the user
if infoDlg.OK:  # this will be True (user hit OK) or False (cancelled)
    print(info)
else:
    print('User Cancelled')

# This alternative uses a gui.Dlg and you manually extract the data.
# This approach gives more control, eg, text color.
dlg = gui.Dlg(title="My experiment", pos=(200, 400))
dlg.addText('Subject Info', color='Blue')
dlg.addField('Name:', tip='or subject code')
dlg.addField('Age:', 21)
dlg.addText('Experiment Info', color='Blue')
dlg.addField('', 45)

thisInfo = dlg.show()  # you have to call show() for a Dlg (automatic with a DlgFromDict)    
if dlg.OK:
    print(thisInfo)
else:
    print('User cancelled')

# The contents of this file are in the public domain.
Exemplo n.º 15
0
def L2_facial_exp_instruction_trial(window, image_path):

    waiting_time = 2

    text = u'- För jag vill ju se hur färgen såg ut när den målades.'

    text_stim_instr = visual.TextStim(window,
                                      text,
                                      height=25,
                                      wrapWidth=1000,
                                      font="Times")
    text_stim_instr.pos = (0, 0)
    text_stim_instr.color = "black"
    text_stim_instr.setText(
        u'Du kommer nu att få se en person som söker respons.')
    text_stim_instr.draw()
    window.flip()
    core.wait(waiting_time * 2)

    input_box = gui.Dlg(title="",
                        labelButtonOK=u"Fortsätt",
                        labelButtonCancel="Avbryt",
                        pos=(900, 800))
    user_input = -1
    input_box.show()
    if not input_box.OK:
        return

    ################################
    # Test trial
    ################################

    # Trial text
    text_stim = visual.TextStim(window, height=40, wrapWidth=1000)
    text_stim.setText(text)

    text_stim.pos = (50, -300)
    text_stim.color = "white"
    text_stim.bold = True

    # Define images to draw
    img_1_stim = visual.ImageStim(window)
    img_1_file_name = "L2_facial_exp_instruction.png"
    img_1_stim.setImage(image_path + img_1_file_name)
    img_1_stim.size = img_1_stim.size * 0.40

    # Draw the first image and the text
    img_1_stim.draw()
    text_stim.draw()
    window.flip()

    # Hold the image
    core.wait(waiting_time * 2)

    img_2_stim = visual.ImageStim(window)
    img_2_file_name = ""

    img_2_file_name = "L2_facial_exp_instruction_test.png"
    img_2_stim.setImage(image_path + img_2_file_name)
    img_2_stim.size = img_2_stim.size * 0.40

    # Draw the second image and the text again
    img_2_stim.draw()
    text_stim.draw()
    window.flip()

    core.wait(waiting_time * 1.5)

    # Input from user: response-seeking or not

    window.flip()

    #    input_box = gui.Dlg(title="MMU", labelButtonOK = "ja", labelButtonCancel = "nej", pos = QPoint(800,500))
    #    input_box.addText(u'Söker talaren respons från lyssnaren?')
    #    #input_box.addField('Soker talaren respons fran lyssnaren?', choices=["Ja", "Nej"])
    #    user_input = -1
    #    input_box.show()
    #    if input_box.OK:
    #        user_input = 1

    ################################

    text_stim_instr.setText(
        u'Såhär ser personen ut när den inte söker respons.')
    text_stim_instr.draw()
    window.flip()
    core.wait(waiting_time * 2)

    input_box = gui.Dlg(title="",
                        labelButtonOK=u"Fortsätt",
                        labelButtonCancel="Avbryt",
                        pos=(900, 800))
    input_box.show()
    if not input_box.OK:
        return

    ################################
    # Control trial
    ################################

    # Draw the first image and the text
    img_1_stim.draw()
    text_stim.draw()
    window.flip()

    # Hold the image
    core.wait(waiting_time * 2)

    img_3_stim = visual.ImageStim(window)
    img_3_file_name = "L2_facial_exp_instruction_control.png"
    img_3_stim.setImage(image_path + img_3_file_name)
    img_3_stim.size = img_3_stim.size * 0.40

    # Draw the second image and the text again
    img_3_stim.draw()
    text_stim.draw()
    window.flip()

    #TODO# Different waiting times for different trials
    core.wait(waiting_time * 1.5)
Exemplo n.º 16
0
    def __init__(self, fullscr=True, interactive=True, log=True):
        super(BenchmarkWizard, self).__init__()
        self.firstrun = False
        self.prefs = prefs
        self.appName = 'PsychoPy3'
        self.name = self.appName + _translate(' Benchmark Wizard')

        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(_translate('Benchmarking takes ~20-30 seconds to gather'))
        dlg.addText(_translate('configuration and performance data. Begin?'))
        dlg.addText('')
        if interactive:
            dlg.show()
            if not dlg.OK:
                return

        self._prepare()
        win = visual.Window(fullscr=fullscr,
                            allowGUI=False,
                            monitor='testMonitor',
                            autoLog=False)

        # do system info etc first to get fps, add to list later because
        # it's nicer for benchmark results to appears at top of the report:
        diagnostics = self.runDiagnostics(win, verbose=True)
        info = {}
        for k, v, m, w in diagnostics:
            # list of tuples --> dict, ignore msg m, warning w
            info[k] = v
        fps = 1000.0 / float(info['visual sync (refresh)'].split()[0])

        itemsList = [('Benchmark', '', '', False)]
        itemsList.append(('benchmark version', '0.1',
                          _translate('dots & configuration'), False))
        itemsList.append(('full-screen', str(fullscr),
                          _translate('visual window for drawing'), False))

        if int(info['no dropped frames'].split('/')[0]) != 0:  # eg, "0 / 180"
            start = 50  # if 100 dots had problems earlier, here start lower
        else:
            start = 200
        for shape in ('circle', 'square'):
            # order matters: circle crashes first
            dotsList = self.runLotsOfDots(win,
                                          fieldShape=shape,
                                          starting=start,
                                          baseline=fps)
            itemsList.extend(dotsList)
            # start square where circle breaks down
            start = int(dotsList[-1][1])
        itemsList.extend(diagnostics)
        win.close()

        itemsDict = {}
        for itm in itemsList:
            if 'proxy setting' in itm[0] or not itm[1]:
                continue
            itemsDict[itm[0]] = itm[1].replace('<strong>', '').replace(
                '</strong>', '').replace('&nbsp;', '').replace('&nbsp', '')

        # present dialog, upload only if opt-in:
        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(
            _translate('Benchmark complete! (See the Coder output window.)'))

        self.htmlReport(itemsList)
        self.reportPath = os.path.join(self.prefs.paths['userPrefsDir'],
                                       'benchmarkReport.html')
        self.save()
        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(
            _translate(
                'Click OK to view full configuration and benchmark data.'))
        dlg.addText(_translate('Click Cancel to stay in PsychoPy.'))
        dlg.addText('')
        if interactive:
            dlg.show()
            if dlg.OK:
                url = 'file://' + self.reportPath
                wx.LaunchDefaultBrowser(url)
Exemplo n.º 17
0
#parameters
useFullScreen = True
useDualScreen=1
DEBUG = False

frame_rate=1
initial_fixation_dur = 4
#final_fixation_dur = 2
decision_dur=4.5
#outcome_dur=0.25
fileSuffix = 'UG'

responseKeys=('8','2','z','num_8','num_2')

#get subjID
subjDlg=gui.Dlg(title="Bargaining Task")
subjDlg.addField('Enter Subject ID: ') #0
subjDlg.addField('Enter Gender (0 for male, 1 for female): ') #1
subjDlg.addField('Enter Ethnicity (0 for Caucasian, 1 for Other): ') #2
subjDlg.addField('Enter Age: ') #3
subjDlg.addField('Full Screen? (Enter lowercase: y or n):') #4
subjDlg.show()

if gui.OK:
    subj_id=subjDlg.data[0]
    subj_gen=subjDlg.data[1]
    subj_eth=subjDlg.data[2]
    subj_age=subjDlg.data[3]
else:
    sys.exit()
Exemplo n.º 18
0
import csv, math, sys
import pdb

from psychopy import visual, os, core, gui, event, logging, microphone, data, sound
from psychopy.hardware.emulator import launchScan

####### SET UP

full_screen = 'n'  #y/n
DEBUG = False
EMULATE = False
COUNT_DOWN_DURATION = 3
ONE_COUNT_DURATION = 1

# Prompt for subjID and Run
subjDlg = gui.Dlg(title="Video Task")
subjDlg.addField('Enter Participant ID:')
subjDlg.show()

if gui.OK:
    subj_id = subjDlg.data[0]
    if (not subj_id):
        print(
            "You need to enter a subject ID! Please consult the participant folder for the correct ID."
        )
        sys.exit()
else:
    sys.exit()

# Logs
expdir = os.getcwd()
Exemplo n.º 19
0
import numpy as np  # whole numpy lib is available, prepend 'np.'
from psychopy.constants import *  # things like STARTED, FINISHED
from numpy.random import random, randint, normal, shuffle
import pandas as pd
import random
from psychopy.iohub import launchHubServer

#number of trials per conditions
TRIALS = 30
practice_trials = 2
#at the very beginning to load the server
io = launchHubServer()
keyboard = io.devices.keyboard

# gui requesting participant info
participant_id = gui.Dlg(title="Imitation-Inhibition experiment")
participant_id.addText('Subject Info')
participant_id.addField('Participant:')

participant_id.show()

if participant_id.OK:
    Participant = participant_id.data[
        0]  #saves data from dialogue box into the variable 'ID'
else:
    core.quite()

#where we will save the data
columnss = [
    'Participant', 'Congruity', 'Reaction_time', 'Response', 'Correctness',
    'Order_number', 'Finger_Screen'
Exemplo n.º 20
0
positionDown = int(win.winfo_screenheight()/3 - windowHeight/2)
win.geometry("+{}+{}".format(positionRight, positionDown))
f.mainloop()

# output escape contrail
for i in np.arange(1, len(pts2)):
    if pts2[i - 1] is None or pts2[i] is None:
        continue
    thickness2 = int(np.sqrt( buffer_2 / float(i + 1)) * 5)
    cv2.line(img_output, pts2[i - 1], pts2[i], (255, 255, 255), thickness2)

# save data
now = datetime.now()
data_to_save = [ animalID, timepoint, treatment, trial[-1:], round(totaldis,1), round(max_v,1), abs(escape_angle), round(before_loom,1), round(after_loom,1), now.strftime("%y/%m/%d %H:%M") ]
cv2.imshow("contrail", img_output)
save_or_not = gui.Dlg()
save_or_not.addText('Save data?')
save_or_not.show()
if save_or_not.OK:
    cv2.imwrite('output_contrails/' + filenamefolder[-1] + '.jpg',img_output)
    if os.path.exists('data.csv') == False:
        with open ('data.csv', 'w', newline='') as datafileinit:
            datafileinitwriter = csv.writer(datafileinit)
            datafileinitwriter.writerow( [ 'Animal ID', 'Timepoint', 'Treatment', 'Trial #', 'Esc Dist', 'Esc Vel', 'Esc Ang', 'Before Dist', 'After Dist', 'Timestamp' ] )
    with open('data.csv', 'a', newline='') as datafile:
        datafilewriter = csv.writer(datafile)
        datafilewriter.writerow( data_to_save )
    if os.path.exists('output_speed/' + animalID + '_' + timepoint + '_' + treatment + '.csv') == False:
        with open ('output_speed/' + animalID + '_' + timepoint + '_' + treatment + '.csv', 'w', newline='') as datafileinit:
            datafileinitwriter = csv.writer(datafileinit)
            datafileinitwriter.writerow( [ 'Time'] )
Exemplo n.º 21
0
# Look in results folder to determine the appropriate subject number.
if not os.path.exists(os.getcwd() + '/swets_deep_results/'):
    os.makedirs(os.getcwd() + '/swets_deep_results/')
results_files = os.listdir(os.getcwd() + '/swets_deep_results/')
if len(results_files) != 0:
    subjects_run = [
        int(s.split('.')[0]) for s in results_files
        if s not in ['.DS_Store', 'Icon\r']
    ]
else:
    subjects_run = [0]
current_subject_number = max(subjects_run) + 1

# Show dialog and wait for OK or Cancel.
subject_info = gui.Dlg(title='Swets Replication: SPR Deep Condition')
subject_info.addField('Subject Number:', current_subject_number)
subject_info.addField('Age:', 21)
subject_info.addField('Gender:', 'M')
subject_info.show()

# The user pressed OK.
if gui.OK:
    current_subject_number = int(subject_info.data[0])
# The user pressed Cancel.
else:
    print('User cancelled')

#### Create output
data = open(os.getcwd() + "/swets_deep_results/" +
            str("%03d" % (current_subject_number, )) + ".txt",
Exemplo n.º 22
0
import pandas as pd
from task import sequence, training
from parameters import getParameters
from recording import Oximeter
from psychopy import visual, gui, monitors

path = os.getcwd()

# Wrapper function
##################

# Get parameters
parameters = getParameters()

# Create a GUI and store subject ID
g = gui.Dlg()
g.addField("Subject Number:")
g.addField("Subject ID:")
g.show()
nSub = g.data[0]
subID = g.data[1]

# Open window
mon = monitors.Monitor('testMonitor', width=60, distance=57)
win = visual.Window(size=(1920, 1080),
                    fullscr=True,
                    units='height',
                    monitor=mon)

# Create the recording instance
ser = serial.Serial('COM4',
Exemplo n.º 23
0
def importTrials(trialsFilename, colNames=None, separator=','):
    trialsFile = open(trialsFilename, 'rb')

    if colNames is None:
        # Assume the first row contains the column names
        colNames = trialsFile.next().rstrip().split(separator)
    trialsList = []
    for trialStr in trialsFile:
        trialList = trialStr.rstrip().split(separator)
        assert len(trialList) == len(colNames)
        trialDict = dict(zip(colNames, trialList))
        trialsList.append(trialDict)
    return trialsList


dlg = gui.Dlg();
dlg.addText("Enter the name: ");
dlg.addField("name");
dlg.show();

if dlg.OK:
    trialName = dlg.data[0] + '.csv'
    outName = dlg.data[0] + '_data.csv'
else:
    trialName = "trials.csv"
    outName = 'data.csv'


generateTrials(trialName)
trialList = importTrials(trialName)
Exemplo n.º 24
0
    def __init__(self, firstrun=False, interactive=True, log=True):
        """Check drivers, show GUIs, run diagnostics, show report."""
        self.firstrun = firstrun
        self.prefs = prefs
        self.appName = 'PsychoPy2'
        self.name = self.appName + _translate(' Configuration Wizard')
        self.reportPath = os.path.join(self.prefs.paths['userPrefsDir'],
                                       'firstrunReport.html')
        #self.iconfile = os.path.join(self.prefs.paths['resources'], 'psychopy.png')
        #dlg.SetIcon(wx.Icon(self.iconfile, wx.BITMAP_TYPE_PNG)) # no error but no effect

        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        if firstrun:
            dlg.addText(_translate("Welcome to PsychoPy2!"), color='blue')
            dlg.addText('')
            dlg.addText(
                _translate(
                    "It looks like you are running PsychoPy for the first time."
                ))
            dlg.addText(
                _translate(
                    "This wizard will help you get started quickly and smoothly."
                ))
        else:
            dlg.addText(_translate("Welcome to the configuration wizard."))

        # test for fatal configuration errors:
        fatalItemsList = []
        if not driversOkay():
            cardInfo = gl_info.get_renderer().replace('OpenGL Engine',
                                                      '').strip()
            dlg.addText('')
            dlg.addText(_translate(
                "The first configuration check is your video card's drivers. The current"
            ),
                        color='red')
            dlg.addText(_translate(
                "drivers cannot support PsychoPy, so you'll need to update the drivers."
            ),
                        color='red')
            msg = _translate(
                """<p>Critical issue:\n</p><p>Your video card (%(card)s) has drivers
                that cannot support the high-performance features that PsychoPy depends on.
                Fortunately, it's typically free and straightforward to get new drivers
                directly from the manufacturer.</p>
                <p><strong>To update the drivers:</strong>
                <li> You'll need administrator privileges.
                <li> On Windows, don't use the windows option to check for updates
                  - it can report that there are no updates available.
                <li> If your card is made by NVIDIA, go to
                  <a href="http://www.nvidia.com/Drivers">the NVIDIA website</a>
                  and use the 'auto detect' option. Try here for
                  <a href="http://support.amd.com/">ATI / Radeon drivers</a>. Or try
                  <a href="http://www.google.com/search?q=download+drivers+%(card2)s">
                  this google search</a> [google.com].
                <li> Download and install the driver.
                <li> Reboot the computer.
                <li> Restart PsychoPy.</p>
                <p>If you updated the drivers and still get this message, you'll
                  need a different video card to use PsychoPy. Click
                <a href="http://www.psychopy.org/installation.html#recommended-hardware">here
                for more information</a> [psychopy.org].</p>
            """) % {
                    'card': cardInfo,
                    'card2': cardInfo.replace(' ', '+')
                }
            fatalItemsList.append(msg)
        if not cardOkay():
            cardInfo = gl_info.get_renderer().replace('OpenGL Engine',
                                                      '').strip()
            msg = _translate("""<p>Critical issue:\n</p>""")
            msg += cardInfo
            fatalItemsList.append(msg)
            pass
        # other fatal conditions? append a 'Critical issue' msg to itemsList
        if not fatalItemsList:
            dlg.addText(
                _translate(
                    "We'll go through a series of configuration checks in about 10 seconds. "
                ))
            dlg.addText('')
            if firstrun:  # explain things more
                dlg.addText(
                    _translate(
                        'Note: The display will switch to full-screen mode and will '
                    ))
                dlg.addText(
                    _translate(
                        "then switch back. You don't need to do anything."))
            dlg.addText(
                _translate(
                    'Optional: For best results, please quit all email programs, web-browsers, '
                ))
            dlg.addText(
                _translate('Dropbox, backup or sync services, and others.'))
            dlg.addText('')
            dlg.addText(_translate('Click OK to start, or Cancel to skip.'))
            if not self.firstrun:
                dlg.addField(label=_translate('Full details'),
                             initial=self.prefs.app['debugMode'])
        else:
            dlg.addText('')
            dlg.addText(
                _translate(
                    'Click OK for more information, or Cancel to skip.'))

        # show the first dialog:
        dlg.addText('')
        if interactive:
            dlg.show()
        if fatalItemsList:
            self.htmlReport(fatal=fatalItemsList)
            self.save()
            # user ends up in browser:
            url = 'file://' + self.reportPath
            if interactive:
                wx.LaunchDefaultBrowser(url)
            return
        if interactive and not dlg.OK:
            return  # no configuration tests run

        # run the diagnostics:
        verbose = interactive and not self.firstrun and dlg.data[0]
        win = visual.Window(fullscr=interactive,
                            allowGUI=False,
                            monitor='testMonitor',
                            autoLog=log)
        itemsList = self.runDiagnostics(win, verbose)  # sets self.warnings
        win.close()
        self.htmlReport(itemsList)
        self.save()

        # display summary & options:
        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(_translate('Configuration testing complete!'))
        summary = self.summary(items=itemsList)
        numWarn = len(self.warnings)
        if numWarn == 0:
            msg = _translate('All values seem reasonable (no warnings).')
        elif numWarn == 1:
            msg = _translate(
                '1 suboptimal value was detected (%s)') % self.warnings[0]
        else:
            msg = _translate(
                '%(num)i suboptimal values were detected (%(warn)s, ...)') % {
                    'num': len(self.warnings),
                    'warn': self.warnings[0]
                }
        dlg.addText(msg)
        for item in summary:
            dlg.addText(item[0], item[1])  # (key, color)
        dlg.addText('')
        dlg.addText(
            _translate(
                'Click OK for full details (will open in a web-browser),'))
        dlg.addText(_translate('or Cancel to stay in PsychoPy.'))
        dlg.addText('')
        if interactive:
            dlg.show()
            if dlg.OK:
                url = 'file://' + self.reportPath
                wx.LaunchDefaultBrowser(url)
        return
Exemplo n.º 25
0
from psychopy import core, event, gui, visual
import random
import numpy as np
import sys
import os
from Variablen1 import Variables
from Matrix1 import RandomMatrix
#from state import State

### Sicherstellen, dass Pfad von selbem Verzeichnis wie dieses Skript startet
_thisDir = os.path.dirname(os.path.abspath(__file__)).decode(
    sys.getfilesystemencoding())
os.chdir(_thisDir)

### Eingabefenster für Daten der Vpn, automatisch beim Start geöffnet
eingabe = gui.Dlg(title="Signalentdeckung.py")

eingabe.addField("Versuchsperson:")
eingabe.addField("Durchgang:")
eingabe.addField("State:", choices=["Yes/No Task", "2IFC"])

eingabe.show()

# Abbruch falls Cancel gedrückt wurde
if eingabe.OK == False:
    core.quit()

nameVpn = eingabe.data[0]
durchgangVpn = eingabe.data[1]
state = eingabe.data[2]
Exemplo n.º 26
0
    def __init__(self, fullscr=True, interactive=True, log=True):
        self.firstrun = False
        self.prefs = prefs
        self.appName = 'PsychoPy2'
        self.name = self.appName + _translate(' Benchmark Wizard')

        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(_translate('Benchmarking takes ~20-30 seconds to gather'))
        dlg.addText(_translate('configuration and performance data. Begin?'))
        dlg.addText('')
        if interactive:
            dlg.show()
            if not dlg.OK:
                return

        self._prepare()
        win = visual.Window(fullscr=fullscr,
                            allowGUI=False,
                            monitor='testMonitor',
                            autoLog=False)

        # do system info etc first to get fps, add to list later because
        # it's nicer for benchmark results to appears at top of the report:
        diagnostics = self.runDiagnostics(win, verbose=True)
        info = {}
        for k, v, m, w in diagnostics:  # list of tuples --> dict, ignore msg m, warning w
            info[k] = v
        fps = 1000. / float(info['visual sync (refresh)'].split()[0])

        itemsList = [('Benchmark', '', '', False)]
        itemsList.append(('benchmark version', '0.1',
                          _translate('dots & configuration'), False))
        itemsList.append(('full-screen', str(fullscr),
                          _translate('visual window for drawing'), False))

        if int(info['no dropped frames'].split('/')[0]) != 0:  # eg, "0 / 180"
            start = 50  # if 100 dots had problems earlier, here start lower
        else:
            start = 200
        for shape in ['circle',
                      'square']:  # order matters: circle crashes first
            dotsList = self.runLotsOfDots(win,
                                          fieldShape=shape,
                                          starting=start,
                                          baseline=fps)
            itemsList.extend(dotsList)
            start = int(
                dotsList[-1][1])  # start square where circle breaks down
        itemsList.extend(diagnostics)
        win.close()

        itemsDict = {}
        for itm in itemsList:
            if 'proxy setting' in itm[0] or not itm[1]:
                continue
            itemsDict[itm[0]] = itm[1].replace('<strong>', '').replace(
                '</strong>', '').replace('&nbsp;', '').replace('&nbsp', '')
            #if log:
            #    print itm[0]+': ' + itemsDict[itm[0]]

        # present dialog, upload only if opt-in:
        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(
            _translate('Benchmark complete! (See the Coder output window.)'))

        # disable upload for now at least:
        '''
        dlg.addText(_translate('Are you willing to share your data at psychopy.org?'))
        dlg.addText(_translate('Only configuration and performance data are shared;'))
        dlg.addText(_translate('No personally identifying information is sent.'))
        dlg.addText(_translate('(Sharing requires an internet connection.)'))
        if interactive:
            dlg.show()
            if dlg.OK:
                status = self.uploadReport(itemsDict)
                dlg = gui.Dlg(title=self.name + ' result')
                dlg.addText('')
                if status and status.startswith('success good_upload'):
                    dlg.addText(_translate('Configuration data were successfully uploaded to'))
                    dlg.addText('http://upload.psychopy.org/benchmark/report.html')
                    dlg.addText(_translate('Thanks for participating!'))
                else:
                    if not eval(info['internet access']):
                        dlg.addText('Upload error: maybe no internet access?')
                    else:
                        dlg.addText('Upload error status: %s' % status[:20])
                dlg.show()
        '''

        self.htmlReport(itemsList)
        self.reportPath = os.path.join(self.prefs.paths['userPrefsDir'],
                                       'benchmarkReport.html')
        self.save()
        dlg = gui.Dlg(title=self.name)
        dlg.addText('')
        dlg.addText(
            _translate(
                'Click OK to view full configuration and benchmark data.'))
        dlg.addText(_translate('Click Cancel to stay in PsychoPy.'))
        dlg.addText('')
        if interactive:
            dlg.show()
            if dlg.OK:
                url = 'file://' + self.reportPath
                wx.LaunchDefaultBrowser(url)
Exemplo n.º 27
0
        myWinRes = myWin.size
        myWin.allowGUI = True
        myWin.close()  #have to close window to show dialog box
##
### END Setup of the screen parameters    ##############################################################################################
####################################
askUserAndConfirmExpParams = True

if autopilot:
    subject = 'autoTest'
###############################
### Ask user exp params    ##############################################################################################
## askUserAndConfirmExpParams
if askUserAndConfirmExpParams:
    dlgLabelsOrdered = list()  #new dialog box
    myDlg = gui.Dlg(title=expname, pos=(200, 400))
    if not autopilot:
        myDlg.addField('Subject code :', subject)
        dlgLabelsOrdered.append('subject')
    else:
        myDlg.addField('Subject code :', subject)
        dlgLabelsOrdered.append('subject')
        myDlg.addField('autoPilotTime:',
                       0,
                       tip='Auto response time relative to cue')
        myDlg.addField(
            'randomTime:',
            False,
            tip='Add (rounded) gaussian N(0,2) error to time offset?')
        myDlg.addField('autoPilotSpace:',
                       0,
Exemplo n.º 28
0
def L2_facial_exp_test_trial(window, text, image_path, trial_type, trial_nr,
                             n_yes_inputs, request_user_input):

    waiting_time = 2

    text_stim = visual.TextStim(window, height=50, wrapWidth=1200)
    text_stim.setText(text)

    text_stim.pos = (50, -300)
    if trial_nr == 6:
        text_stim.color = "grey"
    else:
        text_stim.color = "white"
    text_stim.bold = True

    # Define images to draw

    img_1_stim = visual.ImageStim(window)
    img_1_file_name = "L2_facial_exp_" + str(trial_nr) + ".png"
    img_1_stim.setImage(image_path + img_1_file_name)
    img_1_stim.size = img_1_stim.size * 0.40

    # Draw the first image and the text
    img_1_stim.draw()
    text_stim.draw()

    window.flip()

    core.wait(waiting_time * 2.5)

    img_2_stim = visual.ImageStim(window)
    img_2_file_name = ""

    if trial_type == 1:
        img_2_file_name = "L2_facial_exp_" + str(trial_nr) + "_test.png"
    else:
        img_2_file_name = "L2_facial_exp_" + str(trial_nr) + "_control.png"
    img_2_stim.setImage(image_path + img_2_file_name)
    img_2_stim.size = img_2_stim.size * 0.40

    # Draw the second image and the text again
    img_2_stim.draw()
    text_stim.draw()
    window.flip()

    core.wait(waiting_time * 1.5)

    if request_user_input:

        window.flip()
        # Input from user: response-seeking or not
        n_yes_inputs_left = 6 - n_yes_inputs
        n_trials_left = 12 - trial_nr

        text_stim_instr = visual.TextStim(window,
                                          text,
                                          height=25,
                                          wrapWidth=1000,
                                          font="Times")
        text_stim_instr.pos = (0, 0)
        text_stim_instr.color = "black"

        text_instr = u'Du har svarat "Ja" ' + str(
            n_yes_inputs) + u' gånger. Du kan svara "Ja" ' + str(
                n_yes_inputs_left) + u' gånger till. \n \n Du har ' + str(
                    n_trials_left) + u' försök kvar.'
        text_stim_instr.setText(text_instr)
        text_stim_instr.draw()
        window.flip()

        input_box = gui.Dlg(title="",
                            labelButtonOK="ja",
                            labelButtonCancel="nej",
                            pos=(900, 800))
        input_box.addText(u'Söker talaren respons från lyssnaren?')
        user_input = -1
        input_box.show()
        if input_box.OK:
            user_input = 1
        else:
            user_input = 0

        output = {'trial_type': trial_type, 'user_input': user_input}

        return output
Exemplo n.º 29
0
                output = row[1]
else:
    # CHANGED FOR THIS FILE!!
    #outerpath = '/Users/amennen/Dropbox/rtPennBehavData/facematching/'
    #output=os.path.abspath(os.path.join(outerpath,"tfMRI_output"))
    # changing back to just save data in this directory so the data will be stored on this computer only
    output = os.path.abspath(
        os.path.join(os.path.dirname(__file__), '../..', "tfMRI_output"))

_thisDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(_thisDir)
expName = 'Resting'

# Collect run mode and participant ID
expInfo = {}
dlg1 = gui.Dlg(title="Participant ID")
dlg1.addField('Participant')
dlg1.addField('Mode', choices=["Scanner", "Practice"])  # , "Debug"])
dlg1.addField('Group', choices=["HC", "MDD"])
dlg1.addField('Session', choices=["ABCD", "IPAT2", "CMRR"])
dlg1.addField('Run', choices=["AB"])  #,"Practice"])
dlg1.show()
if dlg1.OK:  # then the user pressed OK
    # add the new entries to expInfo
    expInfo['participant'] = dlg1.data[0]
    expInfo['runMode'] = dlg1.data[1]
    expInfo['group'] = dlg1.data[2]
    expInfo['session'] = dlg1.data[3]
    expInfo['run'] = dlg1.data[4]
    expInfo['CB'] = "1"  #dlg2.data[2]
    RunMode = expInfo['runMode']
Exemplo n.º 30
0
import numpy as np
import pandas as pd
import os, sys
from psychopy import visual, core, event, gui, logging, sound
import random
import matplotlib.pyplot as plt
import csv

#system setup
framerate = 100  #For debugging purposes only. Must be 100 for data collection

if framerate != 100:
    print("Warning: framerate not set to 100 Hz")

#get Subject ID
subgui = gui.Dlg()
subgui.addField("Subject ID:")
subgui.show()
subj = subgui.data[0]

#setup
win = visual.Window(fullscr=True,
                    allowGUI=False,
                    color="black",
                    screen=0,
                    units='height',
                    waitBlanking=True)
trialClock = core.Clock()
all_responses = []

num_blocks = 4