%load script_0.py #============================================== # Settings that we might want to tweak later on #============================================== # directory to save data in data # directory where images can be found image # image names without the suffixes 1,2,3,4,5,6 # suffix for the first image a.jpg # suffix for the second image b.jpg # screen size in pixels 1200x800 # image freezing time in seconds 30 # image changing time in seconds 0.5 # number of bubbles overlayed on the image 40 #========================================== # Store info about the experiment session #========================================== # Get subject name, gender, age, handedness through a dialog box # If 'Cancel' is pressed, quit # Get date and time # Store this information as general session info # Create a unique filename for the experiment data #======================== # Prepare condition lists #======================== # Check if all images exist # Randomize the image order # Create the orientations list: half upright, half inverted # Randomize the orientation order #=============================== # Creation of window and stimuli #=============================== # Open a window # Define trial start text # Define the bitmap stimuli (contents can still change) # Define a bubble (position and size can still change) #========================== # Define the trial sequence #========================== # Define a list of trials with their properties: # - Which image (without the suffix) # - Which orientation #===================== # Start the experiment #===================== # Run through the trials. On each trial: # - Display trial start text # - Wait for a spacebar press to start the trial, or escape to quit # - Set the images, set the orientation # - Switch the image every 0.5s, and: # - Draw bubbles of increasing radius at random positions # - Listen for a spacebar or escape press # - Stop trial if spacebar or escape has been pressed, or if 30s have passed # - Analyze the keypress # - Escape press = quit the experiment # - Spacebar press = correct change detection; register response time # - No press = failed change detection; maximal response time # - Advance to the next trial #====================== # End of the experiment #====================== # Save all data to a file # Quit the experiment # Assign values to the three variable types # Here, we simply assign a literal my_int = 5 print my_int print type(my_int) my_float = 5.0 print my_float print type(my_float) my_boolean = False print my_boolean print type(my_boolean) first_number = 5 second_number = 5.0 ## Now we assign an expression to a variable ## Since an expression evaluates to a value, this is equivalent # Simple expression summed_numbers = first_number + second_number print summed_numbers, type(summed_numbers) # Re-assign a variable using an expression involving its own value first_number = first_number * 3 print first_number # A more complex expression result = ((first_number-3)*second_number)/1.3 print result a = 1 b = 2 if True: print a if False: print b a = 1 my_boolean = True if my_boolean: print a a = 1 # This expression evaluates to a boolean my_boolean = a > 0 print my_boolean # We can assign to a variable and use that if my_boolean: print a # Or we could use the full expression directly if a > 0: print a a = 1 b = 2 c = 3 if a > 0: print a elif b == 2: # Execute if b equals 2 # ...but ONLY if the first condition was False # Note the difference with the assignment symbol = print b elif c <= 3: # Execute if c is smaller than or equal to 3 # ...but ONLY if the first two conditions were False print c else: # Execute in any case # But ONLY if all others were False print 4 if b >= 0: # Execute if b is greater than or equal to 0 # A new if-statement, evaluated independent of previous conditions print b # This statement is not indented # ...and will therefore always execute print 5 a = 1 b = 2 c = 3 # We can logically combine booleans to create another boolean # using 'and', 'or' and 'not' my_boolean = a > 0 and b == 2 print my_boolean # Instead of assigning to a variable, again we can use # the full expression in the conditional statement if a > 0 and b == 2: print a, b elif b == 3 or c <= 3: print b, c elif not a < 0 and c == 3: print a, c # Instead of this: a = 1 print a a = a + 1 print a a = a + 1 print a a = a + 1 print a a = a + 1 print a # (copy-paste as many times as you need...) # We can write much shorter and far more flexibly: a = 1 maximum_number = 5 while a <= maximum_number: print a a = a + 1 a = 1 maximum_number = 5 while True: print a a = a + 1 if a > maximum_number: break # A string represents an ordered series of characters my_string = "a line of text" my_string = 'a line of text' print my_string print type(my_string) print len(my_string) # A tuple is an ordered series of values # ... but these values may consist of different data types my_tuple = (1, 2.0, False) print my_tuple print type(my_tuple) print len(my_tuple) # A list is similar (see below for the difference) # Note that tuples and lists may even have complex data types as elements my_list = [True, "a string!", (1,'tuple','in', 1, 'list')] print my_list print type(my_list) print len(my_list) # A dictionary connects values to one another # It is unordered; the order of elements does not matter # Again, all variable types may be used my_dictionary = {1:[1,1,1], 3:'three', False:2.0} print my_dictionary my_dictionary = {False:2.0, 1:[1,1,1], 3:'three'} print my_dictionary print type(my_dictionary) print len(my_dictionary) a = "kumbaya, milord" print a # Fetch and print the first element of a string print a[0] # Fetch the first until, but not including, the fifth element # This is called 'slicing' print a[0:4] # -1 is the index of the last element # -2 of the second-to-last, etc print a[-2] print a[-5:-1] print a[-5:] # Reverse the order or change step size # Syntax: [start:end:step] print a[-1:-10:-1] print a[0::3] # The same applies to the other ordered data types b = [1, 2.0, True] print b # In lists, you can change existing elements # Change the second element in a list b[1] = 'foo' print b # Print the elements in reverse print b[::-1] # '+' performs concatenation on strings, tuples and lists # Since we do not re-assign the result to a variable however # ...nothing changes in the original ordered series a = "kumbaya, milord" print a print a + '!!!' print a # Similarly, '*' performs replication of the entire string print a * 2 # Same goes for a tuple (or a list) b = (1, 2.0, True) print b + (5,) print b * 2 print b # By re-assigning, we do change the tuple b = b + (5,) print b # Retrieve the value corresponding to 1 in the dictionary # Note that this retrieval is one-way only # ...therefore the first values (the 'keys') need to be unique d = {1:'one', 2:'two', 3:'three'} print d[1] # Add a value to the dictionary d[4] = 'four' print d # String a = 'example' result = 'i' in a print result # Tuple b = (1,2,3) print 0 in b # List c = [1,2,3] print 5 in c # In case of a dictionary, this pertains only to the keys d = {1:'one', 2:'two', 3:'three'} print 2 in d print 'two' in d a = [] # We could do: if len(a) == 0: print 'This variable is empty!' else: print 'There is something in here!' # But this is shorter: if not a: print 'This variable is empty!' else: print 'There is something in here!' # Without the for-syntax, we could do it like this a = 'hi!' n = 0 while n < len(a): print a[n] n = n + 1 # With the for-syntax, this becomes much more intuitive a = 'hi!' for letter in a: print letter number_of_paws = -1 if number_of_paws < 0: raise Exception('Your dog cannot have a negative number of paws!') print 'My dog has', number_of_paws, 'paw(s).' aseries = (0,2,3) a_series[0] = 1 my_string = 'Hi!' my_list = [] # We try to turn a string into a list # of individual characters n = 0 while True: my_list + [my_string[n]] n = n + 1 if n > len(my_string): break print my_list %load script_1.py #============================================== # Settings that we might want to tweak later on #============================================== datapath = 'data' # directory to save data in impath = 'images' # directory where images can be found imlist = ['1','2','3','4','5','6'] # image names without the suffixes asfx = 'a.jpg' # suffix for the first image bsfx = 'b.jpg' # suffix for the second image scrsize = (1200,800) # screen size in pixels timelimit = 30 # image freezing time in seconds changetime = .5 # image changing time in seconds n_bubbles = 40 # number of bubbles overlayed on the image #======================================== # Store info about the experiment session #======================================== exp_name = 'Change Detection' exp_info = {} # Get subject name, gender, age, handedness through a dialog box # If 'Cancel' is pressed, quit # Get date and time # Store this information as general session info # Create a unique filename for the experiment data data_fname = exp_info['participant'] + '_' + exp_info['date'] #======================== # Prepare condition lists #======================== # Check if all images exist # Randomize the image order # Create the orientations list: half upright, half inverted orilist = [0,1]*(len(imlist)/2) # Randomize the orientation order #=============================== # Creation of window and stimuli #=============================== # Open a window # Define trial start text text = "Press spacebar to start the trial" # Define the bitmap stimuli (contents can still change) # Define a bubble (position and size can still change) #========================== # Define the trial sequence #========================== # Define a list of trials with their properties: # - Which image (without the suffix) # - Which orientation #===================== # Start the experiment #===================== for trial in trials: # Display trial start text # Wait for a spacebar press to start the trial, or escape to quit # Set the image filename, set the orientation # Start the trial # Stop trial if spacebar or escape has been pressed, or if 30s have passed while not response and time < timelimit: # Switch the image # Draw bubbles of increasing radius at random positions # For the duration of 'changetime', # Listen for a spacebar or escape press while time < changetime: if response: break # Analyze the keypress if response: if escape_pressed: # Escape press = quit the experiment break elif spacebar_pressed: # Spacebar press = correct change detection; register response time else: # No press = failed change detection; maximal response time # Advance to the next trial #====================== # End of the experiment #====================== # Save all data to a file # Quit the experiment def print_something(): print "preparing to print" print "the function is printing" print "done printing" print_something() print_something() # Function definition def print_and_sum(a, b): print 'The first number is', a print 'The second number is', b return a + b # Assign function output to a variable c = print_and_sum(3,5) print 'Their sum is', c # Print function output directly print print_and_sum(10,20) def my_len(inp): x = 0 for el in inp: x = x + 1 return x a = [1, True, 'T'] print len(a) print my_len(a) def times_two(x): print x*2 def times_three(x): print x*3 import multiplications a = 5 multiplications.times_two(a) multiplications.times_three(a) import multiplications as mt mt.times_two(5) from multiplications import times_two times_two(5) a = [1,2,3] print a def append_element(old_list, new_element): return old_list + [new_element] a = append_element(a,4) print a # Do the same thing # ...using the append member function of the list object a = [1,2,3] a.append(4) print a # reverse() reverses the list a.reverse() print a # remove() removes its first encounter of the specified element a.remove(2) print a # sort() sorts the list from low to high a.sort() print a # pop() returns AND removes the last element print a.pop() print a print a print a.reverse() print a a = 'kumbaya, milord' # Split at spaces, and return a list of strings print a.split(' ') # To print the second word in a sentence, you could then do print a.split(' ')[1] # Check whether a string starts or ends with certain characters # Returns a boolean print a.startswith('kumba') print a.endswith('ard') # Remove the first/last part of a string # ...note that the original string is not changed # A new, different string is returned instead print a.lstrip('kumba') print a.rstrip('ord') print a # Replace part of a string # Again, a new string is returned print a.replace('lord', 'lard') # Here we assign the result to the original string variable # To the same effect as an in-place function a = a.replace('u','x') print a im_order = [5, 6, 3, 2, 1, 4] ori_order = [0, 1, 1, 0, 1, 0] trials_n = [1, 2, 3, 4, 5, 6] data_acc = [] data_rt = [] for trn in trials_n: current_image = im_order[trn-1] current_orientation = ori_order[trn-1] # Present the correct stimuli # ...then gather the responses as acc and rt # e.g., acc = 1 rt = 0.32 data_acc.append(acc) data_rt.append(rt) print data_acc print data_rt # Find some function that turns all these lists into a text file # Preferably easily loadable by your statistics program # import the TrialHandler from psychopy.data import TrialHandler # Define conditions values as a list of dicts stim_order = [{'im':5,'ori':0}, {'im':6,'ori':1}, {'im':3,'ori':1}, {'im':2,'ori':0}, {'im':1,'ori':1}, {'im':4,'ori':0}] # Construct the TrialHandler object # nReps = number of repeats # method = randomization method (here: no randomization) trials = TrialHandler(stim_order, nReps=1, method='sequential') # Loop over the trials for trial in trials: print trial['im'], trial['ori'] # Present the correct stimuli # ...then gather the responses as acc and rt # e.g., acc = 1 rt = 0.32 trials.addData('acc',acc) trials.addData('rt',rt) # And save everything to a file trials.saveAsWideText('test.csv', delim=',') %load script_2.py #=============== # Import modules #=============== from psychopy import data #============================================== # Settings that we might want to tweak later on #============================================== datapath = 'data' # directory to save data in impath = 'images' # directory where images can be found imlist = ['1','2','3','4','5','6'] # image names without the suffixes asfx = 'a.jpg' # suffix for the first image bsfx = 'b.jpg' # suffix for the second image scrsize = (1200,800) # screen size in pixels timelimit = 30 # image freezing time in seconds changetime = .5 # image changing time in seconds n_bubbles = 40 # number of bubbles overlayed on the image #======================================== # Store info about the experiment session #======================================== exp_name = 'Change Detection' exp_info = {} # Get subject name, gender, age, handedness through a dialog box # If 'Cancel' is pressed, quit # Get date and time # Store this information as general session info # Create a unique filename for the experiment data data_fname = exp_info['participant'] + '_' + exp_info['date'] #======================== # Prepare condition lists #======================== # Check if all images exist # Randomize the image order # Create the orientations list: half upright, half inverted orilist = [0,1]*(len(imlist)/2) # Randomize the orientation order #=============================== # Creation of window and stimuli #=============================== # Open a window # Define trial start text text = "Press spacebar to start the trial" # Define the bitmap stimuli (contents can still change) # Define a bubble (position and size can still change) #========================== # Define the trial sequence #========================== # Define a list of trials with their properties: # - Which image (without the suffix) # - Which orientation # We need a list of dictionaries, e.g. {im:'6',ori:1} # Leave blank, we will soon learn how to fill this with imlist and orilist stim_order = [{},{},{},{},{},{}] trials = data.TrialHandler(stim_order, nReps=1, extraInfo=exp_info, method='sequential', originPath=datapath) #===================== # Start the experiment #===================== for trial in trials: # Display trial start text # Wait for a spacebar press to start the trial, or escape to quit # Set the images, set the orientation trial['im'] trial['ori'] # Start the trial # Stop trial if spacebar or escape has been pressed, or if 30s have passed while not response and time < timelimit: # Switch the image # Draw bubbles of increasing radius at random positions # For the duration of 'changetime', # Listen for a spacebar or escape press while time < changetime: if response: break # Analyze the keypress if response: if escape_pressed: # Escape press = quit the experiment break elif spacebar_pressed: # Spacebar press = correct change detection; register response time acc = 1 rt = else: # No press = failed change detection; maximal response time acc = 0 rt = timelimit # Add the current trial's data to the TrialHandler trials.addData('rt', rt) trials.addData('acc', acc) # Advance to the next trial #====================== # End of the experiment #====================== # Save all data to a file trials.saveAsWideText(data_fname + '.csv', delim=',') # Quit the experiment # zip() takes two ordered series of equal length # ...and creates a list of tuple pairs from their elements print zip('haha', 'hihi') print zip([1,2,4],[4,5,6]) # range() creates a sequence of integers # ...by default, starting from 0 and not including the specified integer print range(10) # The (included) starting value can however be specified print range(1,10) # As can the step size print range(1,10,2) import os my_file = 'multiplications' my_ext = '.py' # Get the current working directory # Returns a string my_dir = os.getcwd() print my_dir # Check whether a directory exists # Returns a boolean print os.path.isdir(my_dir) # Creates a directory if not os.path.isdir('temp'): os.makedirs('temp') # Joins together different parts of a file path # Returns a string my_full_path = os.path.join(my_dir, my_file+my_ext) print my_full_path # Check whether a file exists # Returns a boolean print os.path.exists(my_full_path) import numpy.random as rnd a = [1, 2, 3, 4, 5] print a # Shuffle the order of a rnd.shuffle(a) print a # Generate 5 random floats between 0 and 1 b = rnd.random(5) print b # Generate 5 integers up to but not including 10 # Also notice how we specify the 'size' argument here # It is an OPTIONAL argument; specified by name rather than order c = rnd.randint(10, size=5) print c %load script_3.py #=============== # Import modules #=============== import os # for file/folder operations import numpy.random as rnd # for random number generators from psychopy import visual, event, core, gui, data #============================================== # Settings that we might want to tweak later on #============================================== datapath = 'data' # directory to save data in impath = 'images' # directory where images can be found imlist = ['1','2','3','4','5','6'] # image names without the suffixes asfx = 'a.jpg' # suffix for the first image bsfx = 'b.jpg' # suffix for the second image scrsize = (1200,800) # screen size in pixels timelimit = 30 # image freezing time in seconds changetime = .5 # image changing time in seconds n_bubbles = 40 # number of bubbles overlayed on the image #======================================== # Store info about the experiment session #======================================== exp_name = 'Change Detection' exp_info = {} # Get subject name, gender, age, handedness through a dialog box # If 'Cancel' is pressed, quit # Get date and time # Store this information as general session info # Create a unique filename for the experiment data if not os.path.isdir(datapath): os.makedirs(datapath) data_fname = exp_info['participant'] + '_' + exp_info['date'] data_fname = os.path.join(datapath, data_fname) #========================= # Prepare conditions lists #========================= # Check if all images exist for im in imlist: if (not os.path.exists(os.path.join(impath, im+asfx)) or not os.path.exists(os.path.join(impath, im+bsfx))): raise Exception('Image files not found in image folder: ' + str(im)) # Randomize the image order rnd.shuffle(imlist) # Create the orientations list: half upright, half inverted orilist = [0,1]*(len(imlist)/2) # Randomize the orientation order rnd.shuffle(orilist) #=============================== # Creation of window and stimuli #=============================== # Open a window # Define trial start text text = "Press spacebar to start the trial" # Define the bitmap stimuli (contents can still change) # Define a bubble (position and size can still change) #========================== # Define the trial sequence #========================== # Define a list of trials with their properties: # - Which image (without the suffix) # - Which orientation stim_order = [] for im, ori in zip(imlist, orilist): stim_order.append({'im': im, 'ori': ori}) trials = data.TrialHandler(stim_order, nReps=1, extraInfo=exp_info, method='sequential', originPath=datapath) #===================== # Start the experiment #===================== for trial in trials: # Display trial start text # Wait for a spacebar press to start the trial, or escape to quit # Set the images, set the orientation im_fname = os.path.join(impath, trial['im']) trial['ori'] # Empty the keypresses list keys = [] # Start the trial # Stop trial if spacebar or escape has been pressed, or if 30s have passed while not response and time < timelimit: # Switch the image # Draw bubbles of increasing radius at random positions for radius in range(n_bubbles): radius/2. pos = ((rnd.random()-.5) * scrsize[0], (rnd.random()-.5) * scrsize[1] ) # For the duration of 'changetime', # Listen for a spacebar or escape press while time < changetime: if response: break # Analyze the keypress if response: if escape_pressed: # Escape press = quit the experiment break elif spacebar_pressed: # Spacebar press = correct change detection; register response time acc = 1 rt else: # No press = failed change detection; maximal response time acc = 0 rt = timelimit # Add the current trial's data to the TrialHandler trials.addData('rt', rt) trials.addData('acc', acc) # Advance to the next trial #====================== # End of the experiment #====================== # Save all data to a file trials.saveAsWideText(data_fname + '.csv', delim=',') # Quit the experiment