def annealingoptimize(domain,costf,T=10000.0,cool=0.95,step=1): # 从一个随机解开始 vec=[float(random.randint(domain [0],domain[1]))] while T>0.1: # 随机选择一个维度 i=random.randint(0,len(domain)-1) # 选择一个搜索方向 dir=random.randint(-step,step) # 在搜索方向上生成新解 vecb=vec[:] vecb +=dir elif vecb>domain[1]: vecb=domain[1] ea=costf(vec) eb=costf(vecb) #重新计算系统稳定性-概率p,退火算法核心 p=pow(math.e,(-eb-ea)/T) # 更优解将替换当前解,在系统早期,温度很高,系统很不稳定,非更优解也可能替换当前解,这样做的目的,是避免过快陷入局部最优解,更大范围搜索最优解。 if (eb<ea or random.random()<p): vec=vecb # 减低温度 T=T*cool
def mutation(self, gene): """突变""" index1 = random.randint(0, self.geneLenght - 1) index2 = random.randint(0, self.geneLenght - 1) gene[index1], gene[index2] = gene[index2], gene[index1] self.mutationCount += 1 return gene
def cross(self, parent1, parent2): """交叉""" index1 = random.randint(0, self.geneLenght - 1) index2 = random.randint(index1, self.geneLenght - 1) tempGene = parent2.gene[index1:index2] # 交叉的基因片段 newGene = [] p1len = 0 for g in parent1.gene: if p1len == index1: newGene.extend(tempGene) # 插入基因片段 p1len += 1 if g not in tempGene: newGene.append(g) p1len += 1 self.crossCount += 1 return newGene
def makerandom(numTrials): print 'Writing random trials' vector = [] count = 0 Respvec = [] other = [] while len(vector) < numTrials: x = random.randint(1, 4) while count < 1: vector.append(x) count = count + 1 # print count while x != vector[-1]: vector.append(x) count = count + 1 # print count for i in range(len(vector)): if vector[i] == 1: Respvec.append('X 0 0 0') elif vector[i] == 2: Respvec.append('0 X 0 0') elif vector[i] == 3: Respvec.append('0 0 X 0') else: Respvec.append('0 0 0 X') with open('TrialOrder.csv', 'wb') as csvfile: csvfile.truncate() spamwriter = csv.writer(csvfile, delimiter=',') spamwriter.writerow(['Stimulus', 'ResponseRq']) for i in range(len(vector)): spamwriter.writerow([Respvec[i], vector[i]])
def recover(self): #shuffle(self.infected_agents) perm = random.randint(0, len(self.isolated_agents) - 1) temp = self.isolated_agents[-1] self.isolated_agents[len(self.isolated_agents) - 1] = self.isolated_agents[perm] patient = self.isolated_agents.pop() patient.recover() self.append(patient)
def isolate(self): # shuffle(self.susceptible_agents) # shuffle list to random order perm = random.randint(0, len(self.infected_agents) - 1) temp = self.infected_agents[-1] self.infected_agents[len(self.infected_agents) - 1] = self.infected_agents[perm] patient = self.infected_agents.pop() patient.isolate() self.append(patient)
def infected(self): # shuffle(self.susceptible_agents) # shuffle list to random order perm = random.randint(0, len(self.exposed_agents) - 1) temp = self.exposed_agents[-1] self.exposed_agents[len(self.exposed_agents) - 1] = self.exposed_agents[perm] self.exposed_agents[perm] = temp patient = self.exposed_agents.pop() # remove patient from list patient.infect() self.append(patient) # handle appropriate list
def random_item(self): """sample an item uniformly or from the empirical distribution observed in the training data """ if self.sample_negative_items_empirically: # just pick something someone rated! u = self.uniform_user() i = random.choice(self.dataModel.getItemIDsFromUid(u)) else: i = random.randint(0, self.num_items - 1) return i
def random_item(self): """sample an item uniformly or from the empirical distribution observed in the training data """ if self.sample_negative_items_empirically: # just pick something someone rated! u = self.uniform_user() i = random.choice(self.dataModel.getItemIDsFromUid(u)) else: i = random.randint(0,self.num_items-1) return i
def generate_run_order(siteList, restList): conditions = [] siteList1 = siteList.copy() siteList2 = siteList.copy() restList1 = restList.copy() restList2 = restList.copy() random.shuffle(siteList1) random.shuffle(siteList2) while siteList1: for i in range(random.randint(1,3)): conditions.append(siteList1.pop()) if not siteList1: break if restList1: conditions.append(restList1.pop()) while siteList2: for i in range(random.randint(1,3)): conditions.append(siteList2.pop()) if not siteList2: break if restList2: conditions.append(restList2.pop()) return conditions
def bootstrap(default_cfg=None, print_cfg=True): """TODO: Docstring for bootstrap. Kwargs: use_argparser (TODO): TODO use_logger (TODO): TODO Returns: TODO """ config = bootstrap_args(default_cfg) if hasattr(config, 'DDP'): config.DDP.NUM_GPUS = torch.cuda.device_count() if config.DDP.MASTER_PORT == '-1': config.DDP.MASTER_PORT = str(random.randint(10000, 20000)) logger = setup_logger(config) if print_cfg: display_config(config) return config
from psychopy.constants import * # things like STARTED, FINISHED import numpy as np # whole numpy lib is available, prepend 'np.' from numpy import sin, cos, tan, log, log10, pi, average, sqrt, std, deg2rad, rad2deg, linspace, asarray from numpy.random import random, randint, normal, shuffle import os # handy system and path functions import random # Store info about the experiment session expName = u'sublim2' # from the Builder filename that created this script expInfo = {'participant': '', 'session': '001'} dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName random.seed() bilyvlevo = random.randint( 0, 1) #nahodne urcim, jestli bily ctverec bud pro sipku vlevo nebo vpravo expInfo['bilyvlevo'] = bilyvlevo # Setup filename for saving filename = 'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename) #save a log file for detail verbose info
if (size == 0): size = 1 numReversals = 0 totalReversals = 0 responses = 0 lastResponse = False stairCaseCompleted = False while not stairCaseCompleted: #CHOOSE RANDOM STIM LETTER, CALCULATE COORDINATES AND HEIGHT, GENERATE STIM letter = random.choice(letters) matching = random.randint(0, 1) if matching == 1: centerChar = letter else: centerChar = random.choice(letters) if centerChar == letter: match = True else: match = False heightCm, angleCm, xPos, yPos = displayVariables(angle, dir, size) displayText = genDisplay(letter, xPos, yPos, heightCm, 'white') if responses == 0:
trialList=[None], seed=None, name='trials') thisExp.addLoop(trials) # add the loop to the experiment thisTrial = trials.trialList[ 0] # so we can initialise stimuli with some values # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb) if thisTrial != None: for paramName in thisTrial: exec('{} = thisTrial[paramName]'.format(paramName)) for thisTrial in trials: #!#######################################################--RANDOM CHOOSING ONE OF THE POLYGON CHANGING SIZE FUNCTIONS FROM LIST--########################## last_index = len(functions_of_hex) - 1 function_of_hex = functions_of_hex[random.randint( 0, last_index)] #take function from list #!######################################################################################################################################################### currentLoop = trials # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb) if thisTrial != None: for paramName in thisTrial: exec('{} = thisTrial[paramName]'.format(paramName)) # ------Prepare to start Routine "Cross"------- routineTimer.add(2.000000) # update component parameters for each repeat # keep track of which components have finished CrossComponents = [cross] for thisComponent in CrossComponents: thisComponent.tStart = None
# keep track of which components have finished main_blankComponents = [main_blank_text] for thisComponent in main_blankComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # -------Start Routine "main_blank"------- while continueRoutine: # get current time t = main_blankClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame import random ITI = random.randint(800, 1500) ITI = ITI * 0.001 # *main_blank_text* updates if t >= 0.0 and main_blank_text.status == NOT_STARTED: # keep track of start time/frame for later main_blank_text.tStart = t main_blank_text.frameNStart = frameN # exact frame index main_blank_text.setAutoDraw(True) frameRemains = 0.0 + ITI - win.monitorFramePeriod * 0.75 # most of one frame period left if main_blank_text.status == STARTED and t >= frameRemains: main_blank_text.setAutoDraw(False) # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine
monitor='Lab', color=[0,0,0], colorSpace='rgb', blendMode='avg', useFBO=True, ) # store frame rate of monitor if we can measure it successfully expInfo['frameRate']=win.getActualFrameRate() if expInfo['frameRate']!=None: frameDur = 1.0/round(expInfo['frameRate']) else: frameDur = 1.0/60.0 # couldn't get a reliable measure so guess # Initialize components for Routine "trial" this component generates 30 trials, each # consisting of targets variables=[] # generate 30 random orientation gradients to be used as target orientations in the trials. random.seed(45) randomori=[random.randint(0,3)*90 for x in range (30)] # creates the list called variables, a list containing 30 trails each consisting of 300 randomly # places and oriented c's for a in range (30): random.seed(a) # generates random orientations for the stimuli. placeholder= [random.randint(0,3)*90 for x in range (600)] # Removes the orientations which equal the target for this trial, # since targets will be assigned their orientation separately orientationlist= [x for x in placeholder if x != randomori[a] ] # generaties random locations for stimuli. This needs to be higher # than the actual number of stimuli since many will be removed. Q = [random.randint(-60,60)/4 for x in range (1000)] R = [random.randint(-46,46)/4 for x in range (1000)] x=0 # this loop removes stimuli that are to close to each other.
logging.flush() song_index = 0 #Loop to run the trials for exp_runN in range(total_runs): #read the story file and prepare the letters to be displayed song_files = [f for f in os.listdir('songs')] filename = 'songs/' + song_files[song_index] logging.exp("Story file displayed: " + str(filename)) storyfile = codecs.open(filename, encoding='utf-8') real_artist = song_files[song_index].split('-')[0].replace('_', ' ') fake_artist = real_artist while fake_artist == real_artist: fake_artist = song_files[random.randint( 0, len(song_files) - 1)].split('-')[0].replace('_', ' ') artists = [real_artist, fake_artist] random.shuffle(artists) artist_choice_text = "%s oder %s" % tuple(artists) logging.exp("artist order: %s" % artists) song_index += 1 letters = storyfile.read() letters = ' '.join(letters.split()) + ' ' storyfile.close() letter_counter = -1 temporal_combi_list = combi.combination_for_run() #Trial_times=[int(random.uniform(5,9)) for i in xrange(len(temporal_combi_list))]
while output_stim.status != visual.FINISHED: output_stim.draw() noise.draw() win.flip() noise.updateNoise() ## Setup Section iteration_count = 0 target_met = False subject_video_answers = [[] for x in range(len(options))] ## Experiment Section while iteration_count < minimum_iterations: # Select a stimulus from the list of files correct_answer_index = random.randint(0, len(options)-1) correct_answer = options[correct_answer_index] test_file = correct_answer + ".mov" correct_answer = correct_answer[0].lower() # Play the video start_video(test_file, noise_level) # Get response prompt.draw() win.flip() # Read a character c = event.waitKeys() if c[0] == correct_answer: subject_video_answers[correct_answer_index].append(1)
def unknown_command(self): print self._unknown_cmd_messages[random.randint( 0, len(self._unknown_cmd_messages))]
def uniform_user(self): return random.randint(0, self.num_users - 1)
num_promptComponents = [text] for thisComponent in num_promptComponents: if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # -------Start Routine "num_prompt"------- while continueRoutine and routineTimer.getTime() > 0: # get current time t = num_promptClock.getTime() frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *text* updates if t >= 0.0 and text.status == NOT_STARTED: # keep track of start time/frame for later this_num = str(random.randint(0, 1000)) text.tStart = t text.frameNStart = frameN # exact frame index text.setAutoDraw(True) frameRemains = 1.0 - win.monitorFramePeriod * 0.75 # most of one frame period left if text.status == STARTED and t >= frameRemains: text.setAutoDraw(False) if text.status == STARTED: # only update if drawing text.setText((this_num), log=False) # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in num_promptComponents: if hasattr(thisComponent,
def expmatrix(trials): Cue = ([cueA] * int(round(trials * .25 * .5)) + [cueB] * int( round(trials * .5) ) # Sets the predictive switch cue for half of switch trials, the non-predictive cue for the other half of switch and half of repeat trials, + [cueC] * int(round(trials * .75 * .5)) ) # and the predictive repeat cue for the other half of repeat trials if trials == ptrials: continuity = (['repeat'] * int((trials / 2)) + [ 'switch' ] # This and the next two lines set the first half of practice trials as 'vowel/consonant' trials + ['repeat'] * int((trials / 2) - 1) ) # and the second half as 'upper/lowercase' trials currentTask = 1 elif trials == maintrials: continuity = ['switch'] * switchtrials + [ 'repeat' ] * repeattrials # Sets 25% (62/250) of trials as switch trials and 75% as repeat trials currentTask = random.choice( [1, 2] ) # Randomizes the task for the first trial in the main exp; starting point for the `continuity` list that determines the task for each trial toshuffle = list( zip(continuity, Cue) ) # This and next two lines shuffle the order of repeat/switch trials and their corresponding cues random.shuffle(toshuffle) continuity[:], Cue[:] = zip( *toshuffle ) # "zip" means we can randomize cues and switch/repeats in the same order so cues still appear with only certain trial types np.random.shuffle(lowvowelSet) # Randomize list order of lowercase vowels np.random.shuffle(capvowelSet) # uppercase vowels np.random.shuffle( lowconsonantSet) # lowercase consonants np.random.shuffle( capconsonantSet) # uppercase consonants np.random.shuffle(extra_appearances) # Sets an equal number of trials in both practice and main experimente that are uppercase vowel, uppercase consonant, lowercase vowel, and lowercase consonant trials if trials == ptrials: stimSet = (lowconsonantSet[:3] + capconsonantSet[:3] + lowvowelSet[:3] + capvowelSet[:3]) elif trials == maintrials: stimSet = (lowconsonantSet * 2 + capconsonantSet * 2 + lowvowelSet * 12 + capvowelSet * 12 + lowconsonantSet[0 + extra_appearances[0]:] + capconsonantSet[0 + extra_appearances[1]:] + lowvowelSet[2 + extra_appearances[2]:] + capvowelSet[2 + extra_appearances[3]:]) np.random.shuffle(stimSet) # Randomize trial order of letter types task = [] corrAns = [] taskColor = [] ITI = [] stim_delay = [] for tr in range(len(continuity)): # Determines which task to present depending on whether it's a switch or repeat trial, and appends this task to the experimental matrix if continuity[tr] == 'repeat': task.append(currentTask) else: task.append( 3 - currentTask ) # We use "3-" because 3-2 = 1 and 3-1=2, representing the two tasks' numbers currentTask = task[tr] if ( (currentTask == 1 and stimSet[tr] in (lowvowelSet + capvowelSet) ) # If it's a vowel/consonant trial and the stimulus is a vowel, or (currentTask == 2 and stimSet[tr].islower()) ): # or it's a upper/lowercase trial and the stimulus is lowercase, corrAns.append( SRmapping_full[0] ) # Set the correct response as "z" and append this response to the experimental matrix else: # otherwise set the correct response as the keypad number 3 button corrAns.append(SRmapping_full[1]) # append the task type and corresponding rectangle color to the experimental matrix if currentTask == 1: task[ tr] = 'vowel/consonant' # replaces the number representing task with the string corresponding to that number taskColor.append(taskColorRGB[0]) else: task[tr] = 'vowel/consonant' taskColor.append(taskColorRGB[1]) ITI.append( random.randint(ITI_min, ITI_max) ) # Append the randomized ITI (jittered between 2000-3000 ms) to the experimental matrix stim_delay.append( random.randint(stim_delay_min, stim_delay_max) ) # Append the randomized delay between mask and stimulus (jittered between 1500-2500 ms) to the experimental matrixx return [ stimSet, continuity, task, taskColor, corrAns, Cue, ITI, stim_delay ]
import numpy as np from operator import itemgetter # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(_thisDir) Post_Instr_1 = visual.TextStim(win=win, name='Post_Instr_1', color='black', text='Welcome to the post-test! You will answer a few questions about the experimental stimuli and do some judgement tasks. Press the spacebar to continue.') Post_Q1 = visual.TextStim(win=win, name='Post_Q1', color='black', text='Did you notice that the presentation frequency of the images varied? Press Y if you noticed and N if you did not.') Post_Q2 = visual.TextStim(win=win, name='Post_Q2', color='black', text='In this session, you will see some images from the main experiment that you just finished. If you know or can guess the presentation frequencies of these images, press the corresponding key (e.g., if you think it was presented very frequently, press 3; moderately frequently, press 2; not frequently press 1). If you do not know and cannot guess, then press enter. There is no time limit to respond if you are uncertain about your response. Press the spacebar to begin.') ###PostImage### os.chdir(_thisDir + '/Stimuli_faces1') Imagelist = list(os.listdir()) os.chdir(_thisDir) posttrials = 30 ITI_min = 800.0 ITI_max = 2000.0 postImage = postmatrix = [postImage, [random.randint(fix_duration_min, fix_duration_max) for i in range(posttrials)]]
def train_and_validate(train, validate): a, b = np.zeros((validate.shape[1] - 1, 1)), 0 accuracy_per_lambda = {} coefficient_per_lambda = {} coefficient_vector_per_lambda = {} for LAMBDA in LAMBDAS: accuracy = [] coefficient_vector = [] total_step_count = 1 final_a, final_b = 0, 0 for epoch in range(1, EPOCHS + 1): sample_train = train.sample( 50 if train.shape[0] > 50 else train.shape[0]) eta = 1 / (0.01 * epoch + 50) for step in range(1, STEPS + 1): if total_step_count % ACCURACY_STEPS == 0: accuracy.append(evaluate_accuracy(a, b, sample_train)) coefficient_vector.append(np.dot(a.T, a)[0][0]) total_step_count += 1 idx = np.random.randint(validate.shape[0], size=1) validationK = validate.iloc[idx] xk = validationK.iloc[:, 0:(validationK.shape[1] - 1)] yk = validationK.iloc[0][validationK.shape[1] - 1] if (yk * (np.dot(a.T, xk.T)[0][0] + b)) >= 1: a = np.subtract(a, eta * LAMBDA * a) b = b else: a = np.subtract(a, eta * np.subtract(LAMBDA * a, yk * xk.T)) b = b - (-1 * eta * yk) final_a = a final_b = b # accuracy_frame = pd.DataFrame(accuracy, list(range(1, len(accuracy) + 1))) accuracy_per_lambda[str(LAMBDA)] = accuracy coefficient_vector_per_lambda[str(LAMBDA)] = coefficient_vector coefficient_per_lambda[str(LAMBDA)] = [final_a, final_b] # plt.plot(list(range(1, len(accuracy) + 1)), accuracy_per_lambda, 'r--') plt.ioff() plt.subplot(2, 1, 1) for key in accuracy_per_lambda: plt.plot(list(range(1, len(accuracy_per_lambda[key]) + 1)), accuracy_per_lambda[key], label=str(key)) plt.xlabel('Steps') plt.ylabel('Accuracy') plt.legend() plt.subplot(2, 1, 2) for key in coefficient_vector_per_lambda: plt.plot(list(range(1, len(coefficient_vector_per_lambda[key]) + 1)), coefficient_vector_per_lambda[key], label=str(key)) plt.xlabel('Steps') plt.ylabel('Coefficient Vector') plt.legend() # plt.show() plt.savefig('accuracy and coefficient ' + str(random.randint(1, 100)) + '.png') for key in coefficient_per_lambda: print('LAMBDA = {} a = {} b = {}'.format( key, str(coefficient_per_lambda[key][0]), str(coefficient_per_lambda[key][1]))) return coefficient_per_lambda
import csv import matplotlib as mpl from mpl_toolkits.mplot3d import Axes3D import numpy as np import matplotlib.pyplot as plt from numpy.random import random import time import math as m import random import networkx as nx def calculate_distanceMatrix(G,randompoints): number_of_point = len(randompoints) #print number_of_point distance = np.zeros(shape=(number_of_point,number_of_point), dtype=int) for i in range(0,number_of_point): for j in range(0,number_of_point): d = nx.dijkstra_path_length(G, source = randompoints[i], target = randompoints[j]) distance[i,j] = d #print distance np.savetxt('distance_matrix.out', distance, delimiter=',') return distance def get_eta(eta_0,t,tmax): return eta_0*(1.0-float(t)/float(tmax)) def get_sigma(sigma_0,t,tmax): return sigma_0*np.exp(-float(t)/float(tmax)) pointsX = []
def uniform_user(self): return random.randint(0,self.num_users-1)
stim_image = stim_image_high +stim_image_medium + stim_image_low # frequency frequency = ['high']*80 + ['medium']*80 + ['low']*80 # corrAns for i in stim_image: if ('m' or 'M') in i: corrAns.append('w') else: corrAns.append('o') #ITI & duration for i in range(240): ITI.append(random.randint(ITI_min, ITI_max)/1000) duration = [duration]*240 expmatrix = [stim_image, frequency, corrAns, duration, ITI] ##----------------------------------------------------------------------------## ##-----------------------------START RUNNING----------------------------------## ##----------------------------------------------------------------------------## ##---------------------------START INSTRUCTIONS-------------------------------##
if thisTrial != None: for paramName in thisTrial.keys(): exec(paramName + '= thisTrial.' + paramName) #------Prepare to start Routine "select"------- t = 0 selectClock.reset() # clock frameN = -1 # update component parameters for each repeat import random from threading import Timer repsLeft = 0 repsRight = 0 preTargetDuration = random.uniform(0.5, 3) if random.randint(0, 1) == 0: repsLeft = 1 repsRight = 0 else: repsLeft = 0 repsRight = 1 #side = 'left' if repsLeft else 'right' #def send(): # sendEvent('attention', side) #Timer(2, send).start() # keep track of which components have finished selectComponents = [] for thisComponent in selectComponents:
def load_image_gt(dataset, config, image_id, augment=False, augmentation=None, use_mini_mask=False): """Load and return ground truth data for an image (image, mask, bounding boxes). augment: (deprecated. Use augmentation instead). If true, apply random image augmentation. Currently, only horizontal flipping is offered. augmentation: Optional. An imgaug (https://github.com/aleju/imgaug) augmentation. For example, passing imgaug.augmenters.Fliplr(0.5) flips images right/left 50% of the time. use_mini_mask: If False, returns full-size masks that are the same height and width as the original image. These can be big, for example 1024x1024x100 (for 100 instances). Mini masks are smaller, typically, 224x224 and are generated by extracting the bounding box of the object and resizing it to MINI_MASK_SHAPE. Returns: image: [height, width, 3] shape: the original shape of the image before resizing and cropping. class_ids: [instance_count] Integer class IDs bbox: [instance_count, (y1, x1, y2, x2)] mask: [height, width, instance_count]. The height and width are those of the image unless use_mini_mask is True, in which case they are defined in MINI_MASK_SHAPE. """ # Load image and mask image = dataset.load_image(image_id) mask, class_ids = dataset.load_mask(image_id) original_shape = image.shape image, window, scale, padding, crop = utils.resize_image( image, min_dim=config.IMAGE_MIN_DIM, min_scale=config.IMAGE_MIN_SCALE, max_dim=config.IMAGE_MAX_DIM, mode=config.IMAGE_RESIZE_MODE) mask = utils.resize_mask(mask, scale, padding, crop) # Random horizontal flips. # TODO: will be removed in a future update in favor of augmentation if augment: logging.warning("'augment' is deprecated. Use 'augmentation' instead.") if random.randint(0, 1): image = np.fliplr(image) mask = np.fliplr(mask) # Augmentation # This requires the imgaug lib (https://github.com/aleju/imgaug) if augmentation: import imgaug # Augmenters that are safe to apply to masks # Some, such as Affine, have settings that make them unsafe, so always # test your augmentation on masks MASK_AUGMENTERS = [ "Sequential", "SomeOf", "OneOf", "Sometimes", "Fliplr", "Flipud", "CropAndPad", "Affine", "PiecewiseAffine" ] def hook(images, augmenter, parents, default): """Determines which augmenters to apply to masks.""" return augmenter.__class__.__name__ in MASK_AUGMENTERS # Store shapes before augmentation to compare image_shape = image.shape mask_shape = mask.shape # Make augmenters deterministic to apply similarly to images and masks det = augmentation.to_deterministic() image = det.augment_image(image) # Change mask to np.uint8 because imgaug doesn't support np.bool mask = det.augment_image(mask.astype(np.uint8), hooks=imgaug.HooksImages(activator=hook)) # Verify that shapes didn't change assert image.shape == image_shape, "Augmentation shouldn't change image size" assert mask.shape == mask_shape, "Augmentation shouldn't change mask size" # Change mask back to bool mask = mask.astype(np.bool) # Note that some boxes might be all zeros if the corresponding mask got cropped out. # and here is to filter them out _idx = np.sum(mask, axis=(0, 1)) > 0 mask = mask[:, :, _idx] class_ids = class_ids[_idx] # Bounding boxes. Note that some boxes might be all zeros # if the corresponding mask got cropped out. # bbox: [num_instances, (y1, x1, y2, x2)] bbox = utils.extract_bboxes(mask) # Active classes # Different datasets have different classes, so track the # classes supported in the dataset of this image. active_class_ids = np.zeros([dataset.num_classes], dtype=np.int32) source_class_ids = dataset.source_class_ids[dataset.image_info[image_id] ["source"]] active_class_ids[source_class_ids] = 1 # Resize masks to smaller size to reduce memory usage if use_mini_mask: mask = utils.minimize_mask(bbox, mask, config.MINI_MASK_SHAPE) # Image meta data image_meta = mutil.compose_image_meta(image_id, original_shape, image.shape, window, scale, active_class_ids) return image, image_meta, class_ids, bbox, mask
# start calibration XL, XR, height, base_positionsl, base_positionsr, flickering_positions = calibration( XL, XR, height) framel.draw() framer.draw() bordersl.draw() bordersr.draw() waitScreen() # TRIAL PERIOD, NO DATA SAVED # for a in range(20): endTRIAL = False opas = 0 ran_time = random.randint(0, 4) #set random position for the flickering images flickinge = flickering_positions[a] #set sitmuli to the opposite side of the flickering if flickinge[0] > 0: flickingr = ((flickinge[0] - (106)), 0) test_image.pos = base_positionsl[count_l] count_l = count_l + 1 else: flickingr = ((flickinge[0] + 106), height) test_image.pos = base_positionsr[count_r] count_r = count_r + 1 stopwatch.reset() while not endTRIAL:
def ShapeBuilderFunction(**OptionalParameters): # ##################### MODULES TO IMPORT ######################################################################################################### ######################################################################################################### ######################################################################################################### # import math import numpy as np import random from psychopy import visual, info, core from sys import platform as _platform import numbers # jeopardy = sound.SoundPyo(volume = 1) # jeopardy.setSound('jeopardy.wav') # expInfo = info.RunTimeInfo(refreshTest = None) # versionNum = int(str(expInfo['psychopyVersion']).replace('.','')) # ##################### Functions ######################################################################################################### ######################################################################################################### ######################################################################################################### # def EucDist(Pos1,Pos2): return math.sqrt(abs(Pos1[0]-Pos2[0])**2 + abs(Pos1[1]-Pos2[1])**2) def shift(seq, n): n = n % len(seq) return seq[n:] + seq[:n] def DrawStimuliFlip(WhatToDisplay,Window): [curImage.draw() for curImage in WhatToDisplay] Window.flip() def AngleCalc(Rad,Xorigin,Yorigin,YCorrectionFactor,AngleNum,Start): X=Start - float(360)/AngleNum Degrees = [] for i in range(0,AngleNum): X = X + float(360)/AngleNum Degrees.append(X) Degrees=np.array(Degrees) Xcoordinates=Xorigin + np.cos(np.deg2rad(Degrees)) * Rad Ycoordinates=Yorigin + np.sin(np.deg2rad(Degrees)) * Rad * YCorrectionFactor return (zip(Xcoordinates,Ycoordinates)) #This is just used because I have had problems with the mouse #when switching between macs and windows. The main issue is that #event.Mouse() has issues if a window (e.g., event.Mouse(win =myWindow) is not supplied on windows machines #however, on macs specifying the window causes problems, but only on older versions #of psychopy...what a mess. On a mac, with new versions (>1.82..I think!), you need to specify the window. #Thus, this function gets what the version. def DetermineSystemType(psychopyVersion): if _platform == "linux" or _platform == "linux2": core.quit() elif _platform == "darwin": if versionNum <= 18201: compType = 'mac' else: compType = 'pc' elif _platform == "win32": compType = 'pc' else: compType = 'pc' return(compType) ################# Optional Paramaeter Stuff ######################################################################################################### ######################################################################################################### ######################################################################################################### #Do you want to write data to the file if 'writeData' in OptionalParameters: WriteData = OptionalParameters['writeData'] if WriteData not in [True,False]: print('Only True or False are possible parameters for writeData brahh!') elif 'writeData' not in OptionalParameters: WriteData = True if 'numPracTrials' in OptionalParameters: if isinstance(OptionalParameters['numPracTrials'],numbers.Number): if OptionalParameters['numPracTrials'] < 27 and OptionalParameters['numPracTrials'] > -1: numPracticeTrials = int(OptionalParameters['numPracTrials']) elif OptionalParameters['numPracTrials'] < 0 or OptionalParameters['numPracTrials'] > 26: print('Please enter a non-negative integer for the number of practice trials that is less than 26.') core.quit() else: print('Please enter a single number for "numPracTrials".') core.quit() elif 'numPracTrials' not in OptionalParameters: numPracticeTrials = 6 if 'win' in OptionalParameters: window = OptionalParameters['win'] elif 'win' not in OptionalParameters: window = visual.Window(fullscr=True,monitor='Default',units='norm',colorSpace='rgb') #Had to include this because I was having trouble #automatically detecting the version type on windows machines. if 'computerAndVersionType' in OptionalParameters: if OptionalParameters['computerAndVersionType'] == 'pc': myMouse = event.Mouse(win=window) elif OptionalParameters['computerAndVersionType'] == 'mac': myMouse = event.Mouse(win=window) elif OptionalParameters['computerAndVersionType'] == 'macOld': myMouse = event.Mouse() else: print('Not a valid option for "computerAndVersionType" -- "pc", "mac", or "macOld" d00d.') core.quit() elif 'computerAndVersionType' not in OptionalParameters: myMouse = event.Mouse(win=window) if 'physicalMonSize' in OptionalParameters: screenRez = win.size physicalMonSize = OptionalParameters['physicalMonSize'] yCorrFactor = float(physicalMonSize[0])/physicalMonSize[1] elif 'physicalMonSize' not in OptionalParameters: yCorrFactor = 1.6 background = visual.Rect(window, size=(window.size)*2, fillColor=(-1.0,-1.0,-1.0)) #Enter monitor size in cm. If left at [0,0] it is assumed that #1 pixel on the x axis is the same size as 1 pixel on the y axis monSize=[0,0] shapeLWidth=3 lineCol=[-1,-1,-1] trialNum = 0 curMemSize=2 startShapeDur=0.7 curScore = 0 curMemTrial = 0 timeBetweenShapes = 0.5 if numPracticeTrials == 0: numTimesThroughSB = 1 else: numTimesThroughSB = 2 timesThrough = 0 whenToChange = [3,6,9] difColors=[ [ 1, 1,-1], [-1,-1, 1], [ 1,-1,-1], [-1, 1,-1] ] # edges=[[-0.32,0.32],[0.32,0.32],[0.32,-0.32],[-0.32,-0.32]] edges=[[-0.25,0.25],[0.25,0.25],[0.25,-0.25],[-0.25,-0.25]] edges=[[curEdge[0],curEdge[1]*yCorrFactor] for curEdge in edges] Ydist=float(max(edges[0][0],edges[2][0]) - min(edges[0][0],edges[2][0]))/5*yCorrFactor Xdist=float(max(edges[1][0],edges[3][0]) - min(edges[1][0],edges[3][0]))/5 outerRect=visual.Rect(window,lineWidth=0,lineColor=(-0.6,-0.6,-0.6),fillColor=(0,0,0),width=abs(edges[0][0])*5,height=abs(edges[0][0])*4*yCorrFactor,pos=(0,0)) outerRectShapeColor = visual.Rect(window,lineWidth=0,fillColor=[-0.2,-0.2,-0.2],width=abs(edges[0][0])*5*1.01,height=abs(edges[0][0])*4*yCorrFactor*1.01,pos=outerRect.pos,opacity=0.4) defRectColor = outerRectShapeColor.fillColor triangleDistX=0.052 triangleDistY=triangleDistX * yCorrFactor realTriDistX = triangleDistX * 0.8 realTriDistY = triangleDistY * 1.45 triangleYAdj = 2.9 if yCorrFactor > 1.3: textSizeInc = 0.65 realTriDistX = triangleDistX * 0.8 realTriDistY = triangleDistY * 1.45 triangleYAdj = 2.9 else: textSizeInc = 0.45 realTriDistX = triangleDistX * 0.8 realTriDistY = triangleDistY * 1.65 triangleYAdj = 2.5 pushOut = 1.05 allPos = [] cenPos = [] for i in range(0,len(edges)): curPos=[] if i == 0 or i== 2: curEdgeDist = float(max(edges[i][0],edges[i+1][0]) - min(edges[i][0],edges[i+1][0]))/5 float(max(edges[i][0],edges[i+1][0]) - min(edges[i][0],edges[i+1][0]))/2 if i == 0: for j in range(1,5): curPos.append([edges[i][0] + curEdgeDist*j,edges[i][1]]) else: for j in range(1,5): curPos.append([edges[i][0] - curEdgeDist*j,edges[i][1]]) curPos=curPos[::-1] elif i == 1: curEdgeDist = float(max(edges[i][1],edges[i+1][1]) - min(edges[i][1],edges[i+1][1]))/5 for j in range(1,5): curPos.append([edges[i][0], edges[i][1] - curEdgeDist*j]) else: curEdgeDist = float(max(edges[3][1],edges[0][1]) - min(edges[3][1],edges[0][1]))/5 for j in range(1,5): curPos.append([edges[i][0], edges[i][1] + curEdgeDist*j]) curPos=curPos[::-1] allPos.append(curPos) for i in range(len(allPos)): for j in range(len(allPos[i])): for k in range(1): if i == 0 or i == 2: allPos[i][j][1] = float(allPos[i][j][1]) * pushOut else: allPos[i][j][0] = float(allPos[i][j][0]) * pushOut squareOutlinePos=[] allSquarePos=[] allXSqPos=[] allYSqPos=[] yTempStart = edges[0][0] for i in range(1,5): allXSqPos.append(edges[0][0]+Xdist*i) allYSqPos.append(-edges[0][1]+Ydist*i) for i in range(0,len(allYSqPos)): for j in range(0,len(allXSqPos)): allSquarePos.append([allXSqPos[j],allYSqPos[i]]) allSquareRect=[] for i in range(0,len(allSquarePos)): allSquareRect.append(visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0.4,0.4,0.4),width=Xdist,height=Ydist,pos=allSquarePos[i])) scoreRect=visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0.45,0.45,0.45),width=Xdist*2.5,height=Ydist*0.8,pos=(0,edges[0][1]*1.5)) scoreNum=visual.TextStim(window, text=curScore,color = (-1,0.2,0.2),pos=scoreRect.pos,height=Ydist*0.7) scoreLabel=visual.TextStim(window, text="Score",color = 'black',pos=(scoreRect.pos[0],scoreRect.pos[1]+Ydist*0.8),height=Ydist*0.5) scoreValueTexts=[visual.TextStim(window, text=0,color = (-1,-1,-1),pos=scoreRect.pos,height=Ydist*0.6) for i in range(0,4)] beginRect=visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0,0.3,0.8),width=Xdist*2,height=Ydist*0.8,pos=(0.2,edges[0][1]*-1.5)) beginText=visual.TextStim(window, text="Begin",color = (-1,-1,-1),pos=beginRect.pos,height=Ydist*0.5) practiceRect=visual.Rect(window,lineWidth=shapeLWidth*2,lineColor=lineCol,fillColor=(0,0.3,0.8),width=Xdist*2,height=Ydist*0.8,pos=(-beginRect.pos[0],edges[0][1]*-1.5)) practiceText=visual.TextStim(window, text="Practice",color = (-1,-1,-1),pos=practiceRect.pos,height=beginText.height) rectangles=[] testRect=[] unRect=[] for i in range(0,len(edges)): curPos=allPos[i][0] rectangles.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],width=triangleDistX*1.4,height=triangleDistY*1.4,pos=curPos)) testRect.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],width=triangleDistX*1.4,height=triangleDistY*1.4,pos=curPos)) unRect.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],width=triangleDistX*1.4,height=triangleDistY*1.4,pos=curPos)) circles=[] testCircles=[] unCircles=[] for i in range(0,len(edges)): curPos=allPos[i][1] curVertices = AngleCalc(float(triangleDistX)/2*1.5,0,0,yCorrFactor,90,-90) circles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) testCircles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) unCircles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) triangles=[] testTriangles=[] unTriangles=[] for i in range(0,len(edges)): curPos=allPos[i][2] triangles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i], \ vertices=((-realTriDistX,-float(realTriDistX)/2*triangleYAdj),(0,float(realTriDistY)/2),(realTriDistX,-float(realTriDistX)/2*triangleYAdj)), closeShape=True, pos=curPos)) testTriangles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i], \ vertices=((-realTriDistX,-float(realTriDistX)/2*triangleYAdj),(0,float(realTriDistY)/2),(realTriDistX,-float(realTriDistX)/2*triangleYAdj)), closeShape=True, pos=curPos)) unTriangles.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i], \ vertices=((-realTriDistX,-float(realTriDistX)/2*triangleYAdj),(0,float(realTriDistY)/2),(realTriDistX,-float(realTriDistX)/2*triangleYAdj)), closeShape=True, pos=curPos)) diamonds=[] testDiamonds=[] unDiamonds=[] diamondCorrX = 1.15 diamondCorrY = 1.6 for i in range(0,len(edges)): curPos=allPos[i][3] curVertices = [[0,float(triangleDistY)*diamondCorrY/2],[float(triangleDistX)*diamondCorrX/2,0],[0,-(float(triangleDistY)*diamondCorrY/2)],[-(float(triangleDistX)*diamondCorrX/2),0]] diamonds.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) testDiamonds.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) unDiamonds.append(visual.ShapeStim(window,lineWidth=shapeLWidth,lineColor=lineCol,fillColor=difColors[i],vertices=curVertices,pos=curPos)) instRect = visual.Rect(window,lineWidth=shapeLWidth,lineColor='black',fillColor=(0,0,0),width=Xdist*4,height=Ydist*4,pos=(0,0),opacity=0.9) borderingRects = [] borderingRects2 = [] for i in range(0,len(edges)): if i == 0 or i ==2: curPos=[edges[i][0]*pushOut,0] curXSize = Xdist curYSize = Ydist*4 else: curPos=[0,edges[i][1]*pushOut] curXSize = Xdist*4 curYSize = Ydist borderingRects.append(visual.Rect(window,lineWidth=0,lineColor='black',fillColor=(0,0,0),width=curXSize,height=curYSize,pos=curPos,opacity=0.6)) borderingRects2.append(visual.Rect(window,lineWidth=shapeLWidth,lineColor='black',fillColor=(0.4,0.4,0.4),width=curXSize,height=curYSize,pos=curPos)) allShapes=[] testShapes=[] unShapes=[] for i in range(0,4): allShapes.append(rectangles[i]) allShapes.append(circles[i]) allShapes.append(triangles[i]) allShapes.append(diamonds[i]) testShapes.append(testRect[i]) testShapes.append(testCircles[i]) testShapes.append(testTriangles[i]) testShapes.append(testDiamonds[i]) unShapes.append(unRect[i]) unShapes.append(unCircles[i]) unShapes.append(unTriangles[i]) unShapes.append(unDiamonds[i]) allPosFlat=np.array(allPos) allPosFlat=np.reshape(allPosFlat,(allPosFlat.shape[0]*allPosFlat.shape[1],allPosFlat.shape[2])) allPosFlat=allPosFlat.tolist() allStimNoPres = [] allStimNoPres.extend([outerRectShapeColor,outerRect,scoreRect,scoreLabel,scoreNum]) for i in range(len(allSquareRect)): allStimNoPres.append(allSquareRect[i]) [allStimNoPres.append(borderingRects2[i]) for i in range(len(borderingRects2))] for i in range(len(allShapes)): allStimNoPres.append(allShapes[i]) ####################### Outer loop starts here for outerLoop in range(numTimesThroughSB): curScore = 0 instructions='This task tests your ability to remember the ' +\ 'order and spatial position in which a series of colored geometric ' +\ 'shapes are presented. You will see between 2 and 4 shapes. Your job ' +\ 'is to remember the order, spatial position, color, and shape of each ' +\ 'item presented. After the final shape is presented, recreate the ' +\ 'sequence by clicking on the correct colored shape and dragging ' +\ 'it to the appropriate spatial position. The better you do the ' +\ 'more points you will earn. The number of points you earn will ' +\ 'increase the more you get correct without making a mistake. ' +\ 'Click begin to start.' instStim = visual.TextStim(window, text=instructions,color = (-1,-1,-1),pos=(0,0),height=triangleDistX*textSizeInc,wrapWidth = instRect.width * 0.93) outerRect.setOpacity(0.6) # compType = DetermineSystemType(versionNum) # if compType == 'pc': # myMouse = event.Mouse(win=window) # elif compType == 'mac': # myMouse = event.Mouse() background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] outerRect.draw() instRect.draw() instStim.draw() if timesThrough == 0: if numPracticeTrials > 0: practiceRect.draw() practiceText.draw() else: beginRect.draw() beginText.draw() else: beginRect.draw() beginText.draw() window.flip() somethingPressed = False while not somethingPressed: for key in event.getKeys(): if key in ['escape']: core.quit() if myMouse.isPressedIn(beginRect) and timesThrough == 0: numTimesThroughSB = 1 trialNums = [26,26] trialTypes = ["ExperimentalTrials","ExperimentalTrials"] somethingPressed = True elif myMouse.isPressedIn(practiceRect): numTimesThroughSB = 2 trialNums = [numPracticeTrials,26] trialTypes = ["Practice","ExperimentalTrials"] somethingPressed = True elif myMouse.isPressedIn(beginRect) and timesThrough == 1: somethingPressed = True trialTypes = ["Practice","ExperimentalTrials"] trialNum = 0 curMemSize=2 startShapeDur=0.7 curMemTrial = 0 timeBetweenShapes = 0.5 totalHighScore = 0 scoreNum.setText(curScore) timeBetweenShapes = 1.0 startShapeDur = 0.8 trialType = trialTypes[timesThrough] numTrials = trialNums[timesThrough] outerRect.setOpacity(1.0) shiftNums = [0,4,8,12] timeShifts = [0.25]*3 + [0.5] # jeopardy.play() for k in range(len(timeShifts)): for i in range(len(shiftNums)): colorsDummy = shift(allPosFlat,shiftNums[i]) [allShapes[j].setPos(colorsDummy[j]) for j in range(len(allShapes))] background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() countDown1 = core.CountdownTimer(timeShifts[k]) while countDown1.getTime() > 0: doNothing = 1 [allShapes[j].setPos(allPosFlat[j]) for j in range(len(allShapes))] background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() timesThrough += 1 #####################################Outer loop ends here for shapeBuilderInnerLoop in range(numTrials): myMouse.setVisible(False) ranNumStim=[i for i in xrange(0,len(testShapes))] random.shuffle(ranNumStim) ranNumPos=[i for i in xrange(0,len(allSquarePos))] random.shuffle(ranNumPos) allSameColor=np.array([[0,1,2,3],[4,5,6,7],[8,9,10,11],[12,13,14,15]]) allSameShape=np.transpose(allSameColor) allShapeTestPos=[i for i in range(len(allSquarePos))] allShapeTestRandom=[i for i in range(len(allSquarePos))] random.shuffle(allShapeTestRandom) normList = [i for i in range(len(allSameColor))] colorShuffle = [i for i in range(len(allSameColor))] shapeShuffle = [i for i in range(len(allSameColor))] random.shuffle(colorShuffle) random.shuffle(shapeShuffle) whatType = random.randint(0,2) correctShapesList=[] correctShapes=[] correctAtt=[] cTrialShapes=[] positions=[] AA=0 BB=0 oneStep = [9,10,11,18,19,20,21,22,23] allDiff = [3,4,5,12,13,14,24,25] if curMemSize == 4 and trialNum in [18,19,20]: changeIt = [0,2] random.shuffle(changeIt) changeIt = changeIt[0] else: changeIt = random.randint(0,curMemSize-2) allObjects = [] allPositions = [] for i in range(0,curMemSize): curColor = normList[colorShuffle[AA]] curShape = normList[shapeShuffle[BB]] if whatType == 0: if (trialNum in allDiff): AA += 1 BB += 1 elif (trialNum in oneStep) and (i==changeIt): AA += 1 BB += 1 else: AA += 0 BB += 1 else: if (trialNum in allDiff): AA += 1 BB += 1 elif (trialNum in oneStep) and (i==changeIt): AA += 1 BB += 1 else: AA += 1 BB += 0 curObject = allSameColor[curColor][curShape] allObjects.append(curObject) newShape=testShapes[curObject] newShape.setPos(allSquarePos[allShapeTestPos[allShapeTestRandom[i]]]) cTrialShapes.append(newShape) correctShapes.append([curObject,allShapeTestPos[allShapeTestRandom[i]]]) allPositions.append(allShapeTestRandom[i]) correctAtt.append([allSameColor[curColor].tolist(),allSameShape[curShape].tolist()]) core.wait(1.0) for i in xrange(0,len(cTrialShapes)): background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [borderingRects[j].draw() for j in range(len(borderingRects))] window.flip() core.wait(timeBetweenShapes) background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [borderingRects[j].draw() for j in range(len(borderingRects))] cTrialShapes[i].draw() window.flip() core.wait(startShapeDur) background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() grabbedShape = -1 # myMouse.setVisible(visible=True) selectedShapesNum = [] timer = [core.CountdownTimer(400.0) for i in range(curMemSize)] perfect = 0 limboShapes = [] limbShapesTime = [0,0,0,0] coloredRectsBin = [0,0,0,0] allScores=[] placedShapes=[] coloredRects=[] lightSquare = 0 #Mouse start myMouse.setVisible(True) while len(selectedShapesNum) < curMemSize: #continue until keypress if sum(limbShapesTime) > 0: outerRectShapeColor.fillColor = defRectColor for j in range(len(limboShapes)): if timer[j].getTime() <= 0: limbShapesTime[j] = 0 lightSquare = 0 background.draw() coloredRects=[] [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] window.flip() for key in event.getKeys(): if key in ['escape']: core.quit() for i in range(0,len(allShapes)): if myMouse.isPressedIn(allShapes[i]) == True: grabbedShape = i allShapes[i].setPos(myMouse.getPos()) mouse1, mouse2, mouse3 = myMouse.getPressed() clickedOn = True if grabbedShape <= 3 and grabbedShape > -1: curRectCol = 0 elif grabbedShape <= 7 and grabbedShape > 3: curRectCol = 1 elif grabbedShape <= 11 and grabbedShape > 7: curRectCol = 2 elif grabbedShape <= 15 and grabbedShape > 11: curRectCol = 3 outerRectShapeColor.fillColor = difColors[curRectCol] while (clickedOn): allShapes[grabbedShape].setPos(myMouse.getPos()) for j in range(len(allSquarePos)): if EucDist([allShapes[grabbedShape].pos[0],allShapes[grabbedShape].pos[1]],allSquarePos[allShapeTestPos[allShapeTestRandom[j]]]) <= 0.06: coloredRects = [] coloredRectsBin[len(selectedShapesNum)] = 1 lightSquare = 1 coloredRects.append(visual.Rect(window,lineWidth=shapeLWidth*3,lineColor=difColors[curRectCol],fillColor=(0.4,0.4,0.4),width=Xdist,height=Ydist,pos=allSquarePos[allShapeTestPos[allShapeTestRandom[j]]],opacity=0.5)) background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() mouse1, mouse2, mouse3 = myMouse.getPressed() if not mouse1: for j in xrange(0,len(allSquarePos)): if EucDist([allShapes[grabbedShape].pos[0],allShapes[grabbedShape].pos[1]],allSquarePos[allShapeTestPos[allShapeTestRandom[j]]]) <= 0.06: placedShapes.append(grabbedShape) squareSel = allShapeTestPos[allShapeTestRandom[j]] selectedShapesNum.append(squareSel) if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] unShapes[grabbedShape].setPos(allSquarePos[squareSel]) unShapes[grabbedShape].draw() ShapeSet = True curShapeVal = 0 if squareSel == correctShapes[len(selectedShapesNum)-1][1]: if grabbedShape == correctShapes[len(selectedShapesNum)-1][0]: if len(selectedShapesNum)-1 == 0 or perfect == 0: curShapeVal = 15 else: curShapeVal = int(scoreValueTexts[len(selectedShapesNum)-2].text) * 2 perfect = 1 elif grabbedShape in correctAtt[len(selectedShapesNum)-1][1]: curShapeVal = 10 perfect = 0 elif squareSel == correctShapes[len(selectedShapesNum)-1][1]: curShapeVal = 5 perfect = 0 else : curShapeVal = 0 perfect = 0 curScore += curShapeVal # scoreNum.setText(curScore) allScores.append(curShapeVal) [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] scoreValueTexts[len(selectedShapesNum)-1].setText(curShapeVal) scoreValueTexts[len(selectedShapesNum)-1].setPos(allSquarePos[squareSel]) timer[len(selectedShapesNum)-1] = core.CountdownTimer(1.5) unShapes[grabbedShape].setPos(allSquarePos[squareSel]) limboShapes.append(unShapes[grabbedShape]) limbShapesTime[len(selectedShapesNum)-1] = 1 clickedOn = False background.draw() [allStimNoPres[k].draw() for k in range(len(allStimNoPres))] if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] [limboShapes[k].draw() for k in range(len(limboShapes)) if limbShapesTime[k] == 1] [scoreValueTexts[k].draw() for k in range(len(limboShapes)) if limbShapesTime[k] == 1] [allShapes[k].draw() for k in range(len(allShapes))] clickedOn = False if sum(limbShapesTime) > 0: for j in range(len(limboShapes)): if timer[j].getTime() <= 0: limbShapesTime[j] = 0 background.draw() [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] if lightSquare == 1: [coloredRects[k].draw() for k in range(len(coloredRects))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() if clickedOn == False: outerRectShapeColor.fillColor = defRectColor lightSquare = 0 if sum(limbShapesTime) > 0: for j in range(len(limboShapes)): if timer[j].getTime() <= 0: limbShapesTime[j] = 0 lightSquare = 0 background.draw() coloredRects=[] [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [limboShapes[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [scoreValueTexts[j].draw() for j in range(len(limboShapes)) if limbShapesTime[j] == 1] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() else: background.draw() [allShapes[k].setPos(allPosFlat[k]) for k in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] [allShapes[k].draw() for k in range(len(allShapes))] window.flip() event.clearEvents()#get rid of other, unprocessed events countDown3 = core.CountdownTimer(0.5) while countDown3.getTime() > 0: doNothing = 1 if (curScore - int(scoreNum.text)) <= 0: scoreTime = 0.1 else: scoreTime = (0.75/(curScore - int(scoreNum.text)))*0.25 countDown1 = core.CountdownTimer(1.5) countDown2 = core.CountdownTimer(0) if curScore - int(scoreNum.text) < 45: curInc = 1 elif curScore - int(scoreNum.text) < 100: curInc = 5 else: curInc = 10 while countDown1.getTime() > 0: countDown2.add(scoreTime) if (curScore - int(scoreNum.text)) < 11: curInc = 1 if int(scoreNum.text) < curScore: scoreNum.setText(int(scoreNum.text) + curInc) else: scoreNum.setText(curScore) DrawStimuliFlip([background] + allShapes + allStimNoPres + allShapes,window) while countDown2.getTime() > 0: doNothing = 1 scoreNum.setText(curScore) background.draw() [allShapes[i].setPos(allPosFlat[i]) for i in range(len(allShapes))] [allStimNoPres[j].draw() for j in range(len(allStimNoPres))] window.flip() posHighSchores = [15,30,60,120] maxScoreTrial = sum(posHighSchores[0:curMemSize]) totalHighScore += maxScoreTrial if WriteData == True: thisExp.addData("Trial", trialNum) thisExp.addData("CurrentMemorySetSize", curMemSize) thisExp.addData("TimeBetweenShapes", timeBetweenShapes) thisExp.addData("ShapeDuration", startShapeDur) thisExp.addData("TrialType", trialType) thisExp.addData("CurrentScore", curScore) thisExp.addData("MaxScore_Trial", maxScoreTrial) thisExp.addData("MaxScore_Total", totalHighScore) for temp in range(len(selectedShapesNum)): thisExp.addData("Shape_" + str(temp+1) + "_DraggedTo", selectedShapesNum[temp]) thisExp.addData("Shape_" + str(temp+1) + "_Score", allScores[temp]) thisExp.addData("Shape_" + str(temp+1) + "_Placed", placedShapes[temp]) thisExp.addData("Shape_" + str(temp+1) + "_CorrectShape", allObjects[temp]) thisExp.addData("Shape_" + str(temp+1) + "_CorrectPosition", allPositions[temp]) for temp2 in range(len(correctAtt[temp])): thisExp.addData("Shape_" + str(temp+1) + "_CorrectColors", correctAtt[temp][0][temp2]) thisExp.addData("Shape_" + str(temp+1) + "_CorrectShapes", correctAtt[temp][1][temp2]) curMemTrial += 1 trialNum += 1 startShapeDur -= 0.1 timeBetweenShapes -= 0.4 whenToInc = [6,15] if curMemTrial in whenToChange: timeBetweenShapes = 1.0 startShapeDur = 0.8 if trialNum in whenToInc: curMemSize += 1 startShapeDur=1.0 curMemTrial = 0 ####Inner Loop end doneText = visual.TextStim(window, text="You are done with the experiment. \ Press the SPACEBAR to end the task.",color = (1,-1,-1),pos=(0,0),height=0.03,wrapWidth = instRect.width * 0.95) background.draw() scoreRect.draw() scoreNum.draw() scoreLabel.draw() doneText.draw() window.flip() event.waitKeys(keyList='space') if WriteData==True: thisExp.addData("FinalScore", curScore) return curScore
random.randint(ITI_min, ITI_max) ) # Append the randomized ITI (jittered between 2000-3000 ms) to the experimental matrix stim_delay.append( random.randint(stim_delay_min, stim_delay_max) ) # Append the randomized delay between mask and stimulus (jittered between 1500-2500 ms) to the experimental matrixx return [ stimSet, continuity, task, taskColor, corrAns, Cue, ITI, stim_delay ] postCues = np.repeat(cueSet, posttrials / len(cueSet)) # Repeat each of the three cues 10 times np.random.shuffle(postCues) # Shuffle the order of these 30 cues postmatrix = [ postCues, [random.randint(ITI_min, ITI_max) for i in range(posttrials)] ] # Creates an experimental matrix for the cue perception post-task (only relevant for exps 1 + 2); matrix includes only the 30 randomized cues and randomized ITI's ##----------------------------------------------------------------------------## ##----------------------------------------------------------------------------## ##--------------------------START RUNNING TRIALS------------------------------## ##----------------------------------------------------------------------------## ##----------------------------------------------------------------------------## ##----------------------------------------------------------------------------## ##---------------------------START INSTRUCTIONS-------------------------------## ##----------------------------------------------------------------------------## instr_list = [ Instr_1a, Instr_1b, Instr_1c, Instr_1c_2, Instr_1c_3, Instr_1d, Instr_1e, Instr_1f, Instr_1g, Instr_1h, Mapping, Instr_1i